Ejemplo n.º 1
0
 inline Launch(const double theta, const double phi, const double speed) : 
     theta(theta), phi(mod(phi,2*M_PI)), speed(speed) { }
Ejemplo n.º 2
0
/*
*     **********
*
*     subroutine lmdif
*
*     the purpose of lmdif is to minimize the sum of the squares of
*     m nonlinear functions in n variables by a modification of
*     the levenberg-marquardt algorithm. the user must provide a
*     subroutine which calculates the functions. the jacobian is
*     then calculated by a forward-difference approximation.
*
*     the subroutine statement is
*
*   subroutine lmdif(fcn,m,n,x,fvec,ftol,xtol,gtol,maxfev,epsfcn,
*            diag,mode,factor,nprint,info,nfev,fjac,
*            ldfjac,ipvt,qtf,wa1,wa2,wa3,wa4)
*
*     where
*
*   fcn is the name of the user-supplied subroutine which
*     calculates the functions. fcn must be declared
*     in an external statement in the user calling
*     program, and should be written as follows.
*
*     subroutine fcn(m,n,x,fvec,iflag)
*     integer m,n,iflag
*     double precision x(n),fvec(m)
*     ----------
*     calculate the functions at x and
*     return this vector in fvec.
*     ----------
*     return
*     end
*
*     the value of iflag should not be changed by fcn unless
*     the user wants to terminate execution of lmdif.
*     in this case set iflag to a negative integer.
*
*   m is a positive integer input variable set to the number
*     of functions.
*
*   n is a positive integer input variable set to the number
*     of variables. n must not exceed m.
*
*   x is an array of length n. on input x must contain
*     an initial estimate of the solution vector. on output x
*     contains the final estimate of the solution vector.
*
*   fvec is an output array of length m which contains
*     the functions evaluated at the output x.
*
*   ftol is a nonnegative input variable. termination
*     occurs when both the actual and predicted relative
*     reductions in the sum of squares are at most ftol.
*     therefore, ftol measures the relative error desired
*     in the sum of squares.
*
*   xtol is a nonnegative input variable. termination
*     occurs when the relative error between two consecutive
*     iterates is at most xtol. therefore, xtol measures the
*     relative error desired in the approximate solution.
*
*   gtol is a nonnegative input variable. termination
*     occurs when the cosine of the angle between fvec and
*     any column of the jacobian is at most gtol in absolute
*     value. therefore, gtol measures the orthogonality
*     desired between the function vector and the columns
*     of the jacobian.
*
*   maxfev is a positive integer input variable. termination
*     occurs when the number of calls to fcn is at least
*     maxfev by the end of an iteration.
*
*   epsfcn is an input variable used in determining a suitable
*     step length for the forward-difference approximation. this
*     approximation assumes that the relative errors in the
*     functions are of the order of epsfcn. if epsfcn is less
*     than the machine precision, it is assumed that the relative
*     errors in the functions are of the order of the machine
*     precision.
*
*   diag is an array of length n. if mode = 1 (see
*     below), diag is internally set. if mode = 2, diag
*     must contain positive entries that serve as
*     multiplicative scale factors for the variables.
*
*   mode is an integer input variable. if mode = 1, the
*     variables will be scaled internally. if mode = 2,
*     the scaling is specified by the input diag. other
*     values of mode are equivalent to mode = 1.
*
*   factor is a positive input variable used in determining the
*     initial step bound. this bound is set to the product of
*     factor and the euclidean norm of diag*x if nonzero, or else
*     to factor itself. in most cases factor should lie in the
*     interval (.1,100.). 100. is a generally recommended value.
*
*   nprint is an integer input variable that enables controlled
*     printing of iterates if it is positive. in this case,
*     fcn is called with iflag = 0 at the beginning of the first
*     iteration and every nprint iterations thereafter and
*     immediately prior to return, with x and fvec available
*     for printing. if nprint is not positive, no special calls
*     of fcn with iflag = 0 are made.
*
*   info is an integer output variable. if the user has
*     terminated execution, info is set to the (negative)
*     value of iflag. see description of fcn. otherwise,
*     info is set as follows.
*
*     info = 0  improper input parameters.
*
*     info = 1  both actual and predicted relative reductions
*           in the sum of squares are at most ftol.
*
*     info = 2  relative error between two consecutive iterates
*           is at most xtol.
*
*     info = 3  conditions for info = 1 and info = 2 both hold.
*
*     info = 4  the cosine of the angle between fvec and any
*           column of the jacobian is at most gtol in
*           absolute value.
*
*     info = 5  number of calls to fcn has reached or
*           exceeded maxfev.
*
*     info = 6  ftol is too small. no further reduction in
*           the sum of squares is possible.
*
*     info = 7  xtol is too small. no further improvement in
*           the approximate solution x is possible.
*
*     info = 8  gtol is too small. fvec is orthogonal to the
*           columns of the jacobian to machine precision.
*
*   nfev is an integer output variable set to the number of
*     calls to fcn.
*
*   fjac is an output m by n array. the upper n by n submatrix
*     of fjac contains an upper triangular matrix r with
*     diagonal elements of nonincreasing magnitude such that
*
*        t     t       t
*       p *(jac *jac)*p = r *r,
*
*     where p is a permutation matrix and jac is the final
*     calculated jacobian. column j of p is column ipvt(j)
*     (see below) of the identity matrix. the lower trapezoidal
*     part of fjac contains information generated during
*     the computation of r.
*
*   ldfjac is a positive integer input variable not less than m
*     which specifies the leading dimension of the array fjac.
*
*   ipvt is an integer output array of length n. ipvt
*     defines a permutation matrix p such that jac*p = q*r,
*     where jac is the final calculated jacobian, q is
*     orthogonal (not stored), and r is upper triangular
*     with diagonal elements of nonincreasing magnitude.
*     column j of p is column ipvt(j) of the identity matrix.
*
*   qtf is an output array of length n which contains
*     the first n elements of the vector (q transpose)*fvec.
*
*   wa1, wa2, and wa3 are work arrays of length n.
*
*   wa4 is a work array of length m.
*
*     subprograms called
*
*   user-supplied ...... fcn
*
*   minpack-supplied ... dpmpar,enorm,fdjac2,lmpar,qrfac
*
*   fortran-supplied ... dabs,dmax1,dmin1,dsqrt,mod
*
*     argonne national laboratory. minpack project. march 1980.
*     burton s. garbow, kenneth e. hillstrom, jorge j. more
*
*     **********
*/
void lmdif_C(
  void (*fcn)(int, int, double[], double[], int *, void *),
  int    m,
  int    n,
  double x[],
  double fvec[],
  double ftol,
  double xtol,
  double gtol,
  int    maxfev,
  double epsfcn,
  double diag[],
  int    mode,
  double factor,
  int    nprint,
  int   *info,
  int   *nfev,
  double fjac[],
  int    ldfjac,
  int    ipvt[],
  double qtf[],
  double wa1[],
  double wa2[],
  double wa3[],
  double wa4[],
  void *data)
{
   int i;
   int iflag;
   int ij;
   int jj;
   int iter;
   int j;
   int l;
   double actred;
   double delta;
   double dirder;
   double fnorm;
   double fnorm1;
   double gnorm;
   double par;
   double pnorm;
   double prered;
   double ratio;
   double sum;
   double temp;
   double temp1;
   double temp2;
   double temp3;
   double xnorm;
   static double one = 1.0;
   static double p1 = 0.1;
   static double p5 = 0.5;
   static double p25 = 0.25;
   static double p75 = 0.75;
   static double p0001 = 1.0e-4;
   static double zero = 0.0;
   //static double p05 = 0.05;
   
   *info = 0;
   iflag = 0;
   *nfev = 0;
   
   /*
    *     check the input parameters for errors.
    */
   if ((n <= 0) || (m < n) || (ldfjac < m) || (ftol < zero)
      || (xtol < zero) || (gtol < zero) || (maxfev <= 0)
      || (factor <= zero))
      goto L300;
   
   if (mode == 2)
   {
      /* scaling by diag[] */
      for (j=0; j<n; j++)
      {
         if (diag[j] <= 0.0)
            goto L300;
      }   
   }
   
#ifdef BUG
   printf( "lmdif\n" );
#endif
   
   /* evaluate the function at the starting point
    * and calculate its norm.
    */
   iflag = 1;
   fcn(m,n,x,fvec,&iflag, data);
   *nfev = 1;
   if (iflag < 0)
      goto L300;
   
   fnorm = enorm(m,fvec);
   /* initialize levenberg-marquardt parameter and iteration counter. */
   par = zero;
   iter = 1;

   /* beginning of the outer loop. */
L30:
   
   /* calculate the jacobian matrix. */
   iflag = 2;
   fdjac2(fcn, m,n,x,fvec,fjac,ldfjac,&iflag,epsfcn,wa4, data);
   // commented out DKB   
   //    *nfev += n;
   if (iflag < 0)
      goto L300;

   /* if requested, call fcn to enable printing of iterates. */
   if (nprint > 0)
   {
      iflag = 0;
      if (mod(iter-1,nprint) == 0)
      {
         fcn(m,n,x,fvec,&iflag, data);
         if (iflag < 0)
            goto L300;        
     //    printf( "fnorm %.15e\n", enorm(m,fvec));
      }
   }
   /* compute the qr factorization of the jacobian. */
   qrfac(m,n,fjac,ldfjac,1,ipvt,n,wa1,wa2,wa3);
//   for (j = 0; j < n; j++)
//   {
//      printf("wa1[%d] = %e\n", j, wa1[j]);
//      printf("wa2[%d] = %e\n", j, wa2[j]);
//      printf("wa3[%d] = %e\n", j, wa3[j]);
//   }
   /* on the first iteration and if mode is 1, scale according
    * to the norms of the columns of the initial jacobian.
    */
   if (iter == 1)
   {
 //     printf("iter = 1, mode = %d\n", mode);
      if (mode != 2)
      {
         for (j=0; j<n; j++)
         {
            diag[j] = wa2[j];
            if (wa2[j] == zero)
               diag[j] = one;
         }
      }
      
      /* on the first iteration, calculate the norm of the scaled x
       * and initialize the step bound delta.
       */
      for (j=0; j<n; j++)
         wa3[j] = diag[j] * x[j];
      
      xnorm = enorm(n,wa3);
      delta = factor*xnorm;
     // printf("iter1: xnorm = %e, delta = %e\n", xnorm, delta);
      //dkb
      if (fabs(delta) <= 1e-4)
//      if (delta == zero)
         delta = factor;
   }
   
   /* form (q transpose)*fvec and store the first n components in qtf. */
   for (i=0; i<m; i++)
      wa4[i] = fvec[i];
   
   jj = 0;
   for (j=0; j<n; j++)
   {
      temp3 = fjac[jj];
      if (temp3 != zero)
      {
         sum = zero;
         ij = jj;
         for (i=j; i<m; i++)
         {
            sum += fjac[ij] * wa4[i];
            ij += 1;    /* fjac[i+m*j] */
         }
         temp = -sum / temp3;
         ij = jj;
         for (i=j; i<m; i++)
         {
            wa4[i] += fjac[ij] * temp;
            ij += 1;    /* fjac[i+m*j] */
         }
      }
      fjac[jj] = wa1[j];
      jj += m+1;  /* fjac[j+m*j] */
      qtf[j] = wa4[j];
   }
   
   /* compute the norm of the scaled gradient. */
   gnorm = zero;
   if (fnorm != zero)
   {
      jj = 0;
      for (j=0; j<n; j++)
      {
         l = ipvt[j];
         if (wa2[l] != zero)
         {
            sum = zero;
            ij = jj;
            for (i=0; i<=j; i++)
            {
               sum += fjac[ij]*(qtf[i]/fnorm);
               ij += 1; /* fjac[i+m*j] */
            }
            gnorm = dmax1(gnorm,fabs(sum/wa2[l]));
         }
         jj += m;
      }
   }
   
   /* test for convergence of the gradient norm. */
   if (gnorm <= gtol)
      *info = 4;
   if (*info != 0)
      goto L300;
   
//for (j = 0; j < n; j++)
//   printf("diag[%d] = %e, wa2[%d] = %e\n", j, diag[j], j, wa2[j]);
   /* rescale if necessary. */
   if (mode != 2)
   {
      for (j=0; j<n; j++)
         diag[j] = dmax1(diag[j],wa2[j]);
   }
   
   /* beginning of the inner loop. */
L200:
   
   /* determine the levenberg-marquardt parameter. */
   lmpar(n,fjac,ldfjac,ipvt,diag,qtf,delta,&par,wa1,wa2,wa3,wa4);
   /* store the direction p and x + p. calculate the norm of p. */
   for (j=0; j<n; j++)
   {
      wa1[j] = -wa1[j];
      wa2[j] = x[j] + wa1[j];
      wa3[j] = diag[j]*wa1[j];
      //printf("wa2[%d] = %e + %e = %e\n", j, x[j], wa1[j], wa2[j]);
   }
   pnorm = enorm(n,wa3);
   /* on the first iteration, adjust the initial step bound. */
   if (iter == 1)
      delta = dmin1(delta,pnorm);
      
   /* evaluate the function at x + p and calculate its norm. */
   iflag = 1;
   //printf("evaluate at:\n");
   //for (j=0; j<n; j++)
   //   printf("wa2[%d] = %e\n", j, wa2[j]);
   fcn(m,n,wa2,wa4,&iflag, data);
   *nfev += 1;
   if (iflag < 0)
      goto L300;
   
   fnorm1 = enorm(m,wa4);
   
#ifdef BUG 
   printf( "pnorm %.10e  fnorm1 %.10e\n", pnorm, fnorm1 );
#endif
   
   /* compute the scaled actual reduction. */
   actred = -one;
   if ((p1*fnorm1) < fnorm)
   {
      temp = fnorm1/fnorm;
      actred = one - temp * temp;
   }
   /* compute the scaled predicted reduction and
    * the scaled directional derivative.
    */
   jj = 0;
   for (j=0; j<n; j++)
   {
      wa3[j] = zero;
      l = ipvt[j];
      temp = wa1[l];
      ij = jj;
      for (i=0; i<=j; i++)
      {
         wa3[i] += fjac[ij]*temp;
         ij += 1; /* fjac[i+m*j] */
      }
      jj += m;
   }
   temp1 = enorm(n,wa3)/fnorm;
   temp2 = (sqrt(par)*pnorm)/fnorm;
   prered = temp1*temp1 + (temp2*temp2)/p5;
   dirder = -(temp1*temp1 + temp2*temp2);
   /* compute the ratio of the actual to the predicted reduction. */
   ratio = zero;
   if (prered != zero)
      ratio = actred/prered;
   /* update the step bound. */
   if (ratio <= p25)
   {
      if (actred >= zero)
         temp = p5;
      else
         temp = p5*dirder/(dirder + p5*actred);
      if (((p1*fnorm1) >= fnorm) || (temp < p1))
         temp = p1;
      
      delta = temp*dmin1(delta,pnorm/p1);
      par = par/temp;
   }
   else
   {
      if ((par == zero) || (ratio >= p75))
      {
         delta = pnorm/p5;
         par = p5*par;
      }
   }
   /* test for successful iteration. */
   if (ratio >= p0001)
   {
      /* successful iteration. update x, fvec, and their norms. */
      for (j=0; j<n; j++)
      {
         x[j] = wa2[j];
         wa2[j] = diag[j]*x[j];
      }
      for (i=0; i<m; i++)
         fvec[i] = wa4[i];
      
      xnorm = enorm(n,wa2);
      fnorm = fnorm1;
      iter += 1;
   }
   /* tests for convergence. */
   if ((fabs(actred) <= ftol) && (prered <= ftol) && (p5*ratio <= one))
   {
      *info = 1;
   }
   
   if (delta <= xtol*xnorm)
      *info = 2;
   
   if ((fabs(actred) <= ftol) && (prered <= ftol)
      && (p5*ratio <= one) && (*info == 2))
   {
      *info = 3;
   }
   
   if (*info != 0)
      goto L300;
   
   /* tests for termination and stringent tolerances. */
   if (*nfev >= maxfev)
      *info = 5;
   
   if ((fabs(actred) <= MACHEP) && (prered <= MACHEP) && (p5*ratio <= one))
   {
      *info = 6;
   }
   
   if (delta <= MACHEP*xnorm)
      *info = 7;
   
   if (gnorm <= MACHEP)
      *info = 8;
   
   if (*info != 0)
      goto L300;
   
   /* end of the inner loop. repeat if iteration unsuccessful. */
   if (ratio < p0001)
      goto L200;
   
   /*  end of the outer loop. */
   goto L30;
   
L300:

   /* termination, either normal or user imposed. */
   if (iflag < 0)
      *info = iflag;
   
   iflag = 0;
   if (nprint > 0)
      fcn(m,n,x,fvec,&iflag, data);
}
Ejemplo n.º 3
0
static void nextFighter(void)
{
	page = mod(page + 1, maxPages);
	
	setNumDestroyed();
}
Ejemplo n.º 4
0
int _tmain(int argc, _TCHAR* argv[])
{
  int  First_Pass = TRUE;
  int  lastSize   = ARRAY_SIZE;
  int  recCnt     = 0;
  int  rejCnt     = 0;
  int  cycle      = 1;
  
  headOneType  H1;
  headTwoType  H2;
  recOneType   R1;
  recTwoType   R2;
  
  char    lineBuffer[82];
  long double  D1, D2, D3, DblDenum, T_last,  T_now,  val[ARRAY_SIZE];
  FILE   *inFile1, *inFile2,  *outFile;
  int     count, i,  j,  k, KS,  M,  
          group, maxLine, NC,    recNum, recSize, status;

    /*------------------------------------------------------------------------*/
    /* Open data files; quit if unable to open any of them.                   */
    /*------------------------------------------------------------------------*/

    if ( argc == 4 ) 
       { 
         inFile1 = fopen(argv[1],"r"); 
         inFile2 = fopen(argv[2],"r"); 
         outFile = fopen(argv[3],"wb");
       }
    else 
       { 
         printf("\n Improper number of command line arguments.\n\n");
         printf("\n usage:");
         printf("\n convert.exe <header.file> <ascii epemeris.file> <binary output> ");
         exit(1);
       }

    if ( (inFile1==NULL) | (inFile2==NULL) | (outFile==NULL) ) 
       { 
         if (inFile1==NULL) printf("\n Unable to open header file.\n\n");
         if (inFile2==NULL) printf("\n Unable to open ascii ephemeris file.\n\n");
         if (outFile==NULL) printf("\n Unable to open binary output ephemeris file.\n\n");
         exit(1);
       }

    /*------------------------------------------------------------------------*/
    /* Initialize constant name & value arrays.                               */
    /*------------------------------------------------------------------------*/

    for ( i=0 ; i<400 ; i++ ) 
        {
          for (j=0 ; j<6 ; j++ ) R1.constName[i][j] = ' ';
          R2.constValue[i] = 0.0;
        }

    /*------------------------------------------------------------------------*/
    /* Read first line from header file (into dummy variables).               */
    /*------------------------------------------------------------------------*/
  
    status = Read_File_Line(inFile1,FALSE,lineBuffer);
    sscanf(lineBuffer,"KSIZE= %d NCOEFF= %d",&KS,&NC);

    /*------------------------------------------------------------------------*/
    /* Read data from Group 1010                                              */
    /*------------------------------------------------------------------------*/
    
    group = Read_Group_Header(inFile1);

    if ( group == 1 ) 
       {
         for ( i=0 ; i<3 ; i++ ) 
             { 
               status = Read_File_Line(inFile1,FALSE,lineBuffer);
               for (j=0 ; j<81 ; j++) R1.label[i][j] = lineBuffer[j];
             }
       }
    else 
       {
         Warning(7);
         exit(1);
       }

    /*............................Convert <cr> to end of string marker ('\0') */

    for (i=0 ; i<3 ; i++)
        for (j=0 ; j<81 ; j++)
            if ( R1.label[i][j] == '\r') 
                R1.label[i][j] = '\0';

    /*------------------------------------------------------------------------*/
    /* Read data from Group 1030                                              */
    /*------------------------------------------------------------------------*/
    
    group = Read_Group_Header(inFile1);
    
    if ( group == 2 ) 
       {
         status = Read_File_Line(inFile1,FALSE,lineBuffer);
         sscanf(lineBuffer," %10Le",&R1.timeData[0]);
         sscanf(lineBuffer+14," %10Le",&R1.timeData[1]);
         sscanf(lineBuffer+27," %10Le",&R1.timeData[2]);
       }
    else 
       {
         Warning(8);
         exit(1);
       }

    /*------------------------------------------------------------------------*/
    /* Read data from Group 1040                                              */
    /*------------------------------------------------------------------------*/
    
    group = Read_Group_Header(inFile1);
    
    if ( group == 3 ) 
       {
         status = Read_File_Line(inFile1,FALSE,lineBuffer);
         sscanf(lineBuffer," %d",&M);
         count = 0;
         while ( count < M ) 
               {
                 status = Read_File_Line(inFile1,FALSE,lineBuffer);

                 for ( i=0 ; i<10 ; i++ )
                     {
                       sscanf(lineBuffer+(i*8),"  %6c",&R1.constName[count]);
                       if (++count == M) break;
                     }
               }
       }
    else 
       {
         Warning(9);
         exit(1);
       }

    /*------------------------------------------------------------------------*/
    /* Read data from Group 1041                                              */
    /*------------------------------------------------------------------------*/
    
    group = Read_Group_Header(inFile1);

    if ( group == 4 ) 
       {
         status = Read_File_Line(inFile1,FALSE,lineBuffer);
         sscanf(lineBuffer," %d",&NC);                /* NC now means "Number */
         if ( M == NC )                               /* of Constants"; it is */
            {                                         /* no longer a "dummy". */
              count = 0;
              while ( count < NC ) 
                    {
                      status = Read_File_Line(inFile1,TRUE,lineBuffer);
                      sscanf(lineBuffer," %Le %Le %Le",&D1,&D2,&D3);
                      R2.constValue[count] = D1;
                      if (++count == NC) break;
                      R2.constValue[count] = D2;
                      if (++count == NC) break;
                      R2.constValue[count] = D3;
                      if (++count == NC) break;
                    }
            }
         else 
            {
              Warning(10);
              exit(1);
            }
       }
    else 
       {
         Warning(11);
         exit(1);
       }

    /*------------------------------------------------------------------------*/
    /* Read data from Group 1050                                              */
    /*------------------------------------------------------------------------*/

    group = Read_Group_Header(inFile1); 

    if ( group == 5 ) 
       {
         for ( i=0 ; i<3 ; i++ ) 
             {
               status = Read_File_Line(inFile1,FALSE,lineBuffer); 
               for ( j=0 ; j<13 ; j++ ) 
                   {
                     if (j<12)
                        sscanf(lineBuffer+(j*6),"%3ld",&R1.coeffPtr[j][i]);
                     else
                        sscanf(lineBuffer+(j*6),"%3ld",&R1.libratPtr[i]);
                   }
             }
       }
    else 
       {
         Warning(12);
         exit(1);
       }

    /*------------------------------------------------------------------------*/
    /* The binary header record contains some constants whose values are      */
    /* assigned in the (ASCII) header file. These values are extracted and    */
    /* assigned to local variables here:                                      */
    /*------------------------------------------------------------------------*/

    R1.numConst = (long int) NC;
    R1.AU       = Find_Value("AU    ",R1.constName,R2.constValue);
    R1.EMRAT    = Find_Value("EMRAT ",R1.constName,R2.constValue);
    DblDenum    = Find_Value("DENUM ",R1.constName,R2.constValue);
    R1.DENUM    = (long int) DblDenum;
    H1.data     = R1;
    H2.data     = R2;

    /*------------------------------------------------------------------------*/
    /* Write binary header records.                                           */
    /*------------------------------------------------------------------------*/

    fwrite(&H1,sizeof(H1),1,outFile);
    fwrite(&H2,sizeof(H2),1,outFile);

    /*------------------------------------------------------------------------*/
    /* Main Loop: Read ASCII data and write binary data.                      */
    /*------------------------------------------------------------------------*/

    while (!feof(inFile2))
          {
          /*.........................................Increment record counter */
          
          recCnt  = recCnt + 1;

          /*..........................Read first line of current ASCII record */

          status = Read_File_Line(inFile2,FALSE,lineBuffer);
          
          if (status == EOF)                          /* Nominal program exit */
             break;
          else
             sscanf(lineBuffer," %d %d ",&recNum,&recSize);
         
          /*................................Check for record size consistancy */
         
          if ( recSize != lastSize ) 
             {
               Warning(13);
               exit(1);
             }
          lastSize = recSize;
         
          /*................Compute the number of lines with coefficient data */
         
          if (mod(recSize,3)==0) maxLine = recSize/3;
          else                   maxLine = recSize/3 + 1;
         
          /*..................................Read coefficients into an array */

          for ( i=0 ; i<maxLine ; i++ )  
              {
                status = Read_File_Line(inFile2,TRUE,lineBuffer);

                if ( status == EOF )
                   {
                     Warning(22);
                     break;
                   }

                sscanf(lineBuffer,"%Le",&val[3*i]); 
                if (3*i+1 >= recSize) break; 
                sscanf(lineBuffer+26,"%Le",&val[3*i+1]); 
                if (3*i+2 >= recSize) break;
                sscanf(lineBuffer+52,"%Le",&val[3*i+2]);
              }

          /*........................................Read start time of record */

          T_now = val[0];

          /*........................Write the coefficients to the binary file */
         
          if ( First_Pass )               /* Will force write of first record */
             {
               T_last     = val[0];
               First_Pass = FALSE;
             }

          if ( T_now == T_last )      /* Write only if no gap between records */
             {
               cycle  = cycle + 1;
	       
               if ( cycle == 26 )            /* Let the user know all is well */
                  {
                    printf("\n   Writing record: %d",recCnt);
                    cycle = 1;
                  }

               for ( i=0 ; i<recSize ; i++ )      /* Write binary data record */
                   {
                     fwrite(&val[i],sizeof(long double),1,outFile);
                   }

               T_last = val[1];                   /* Save stop time of record */
              
             }
          else
             {
               if (rejCnt == 0) printf("\n");
               rejCnt = rejCnt + 1;
               printf("   Record %d rejected:",recCnt);
               printf("  T_last = % 4d , ",T_last);
               printf("T_now = % 4d\n",val[0]);
               if (rejCnt > 10) return 1;              /* Major problem, quit */
             }
         
          } /*.................................................End: Main Loop */

    /*------------------------------------------------------------------------*/
    /*  Close files, print summary, and quit.                                 */
    /*------------------------------------------------------------------------*/
   
    fclose(inFile1);
    fclose(inFile2);
    fclose(outFile);
    
    printf("\n\n   Data Conversion Completed. \n");
    printf("\n      Records Converted: % 3d",recCnt);
    printf("\n       Records Rejected: % 2d\n\n",rejCnt);
   
    return 0;
   
} /**======================================================== End: convert.c **/
Ejemplo n.º 5
0
static void
xscan(Memimage *dst, Seg **seg, Seg *segtab, int nseg, int wind, Memimage *src, Point sp, int detail, int fixshift, int clipped, int op)
{
	int32_t y, maxy, x, x2, xerr, xden, onehalf;
	Seg **ep, **next, **p, **q, *s;
	int32_t n, i, iy, cnt, ix, ix2, minx, maxx;
	Point pt;
	void	(*fill)(Memimage*, int, int, int, Memimage*, Point, int);

	fill = fillline;
/*
 * This can only work on 8-bit destinations, since fillcolor is
 * just using memset on sp.x.
 *
 * I'd rather not even enable it then, since then if the general
 * code is too slow, someone will come up with a better improvement
 * than this sleazy hack.	-rsc
 *
	if(clipped && (src->flags&Frepl) && src->depth==8 && Dx(src->r)==1 && Dy(src->r)==1) {
		fill = fillcolor;
		sp.x = membyteval(src);
	}
 *
 */
	USED(clipped);


	for(i=0, s=segtab, p=seg; i<nseg; i++, s++) {
		*p = s;
		if(s->p0.y == s->p1.y)
			continue;
		if(s->p0.y > s->p1.y) {
			pt = s->p0;
			s->p0 = s->p1;
			s->p1 = pt;
			s->d = -s->d;
		}
		s->num = s->p1.x - s->p0.x;
		s->den = s->p1.y - s->p0.y;
		s->dz = sdiv(s->num, s->den) << fixshift;
		s->dzrem = mod(s->num, s->den) << fixshift;
		s->dz += sdiv(s->dzrem, s->den);
		s->dzrem = mod(s->dzrem, s->den);
		p++;
	}
	n = p-seg;
	if(n == 0)
		return;
	*p = 0;
	qsort(seg, p-seg , sizeof(Seg*), ycompare);

	onehalf = 0;
	if(fixshift)
		onehalf = 1 << (fixshift-1);

	minx = dst->clipr.min.x;
	maxx = dst->clipr.max.x;

	y = seg[0]->p0.y;
	if(y < (dst->clipr.min.y << fixshift))
		y = dst->clipr.min.y << fixshift;
	iy = (y + onehalf) >> fixshift;
	y = (iy << fixshift) + onehalf;
	maxy = dst->clipr.max.y << fixshift;

	ep = next = seg;

	while(y<maxy) {
		for(q = p = seg; p < ep; p++) {
			s = *p;
			if(s->p1.y < y)
				continue;
			s->z += s->dz;
			s->zerr += s->dzrem;
			if(s->zerr >= s->den) {
				s->z++;
				s->zerr -= s->den;
				if(s->zerr < 0 || s->zerr >= s->den)
					print("bad ratzerr1: %ld den %ld dzrem %ld\n", s->zerr, s->den, s->dzrem);
			}
			*q++ = s;
		}

		for(p = next; *p; p++) {
			s = *p;
			if(s->p0.y >= y)
				break;
			if(s->p1.y < y)
				continue;
			s->z = s->p0.x;
			s->z += smuldivmod(y - s->p0.y, s->num, s->den, &s->zerr);
			if(s->zerr < 0 || s->zerr >= s->den)
				print("bad ratzerr2: %ld den %ld ratdzrem %ld\n", s->zerr, s->den, s->dzrem);
			*q++ = s;
		}
		ep = q;
		next = p;

		if(ep == seg) {
			if(*next == 0)
				break;
			iy = (next[0]->p0.y + onehalf) >> fixshift;
			y = (iy << fixshift) + onehalf;
			continue;
		}

		zsort(seg, ep);

		for(p = seg; p < ep; p++) {
			cnt = 0;
			x = p[0]->z;
			xerr = p[0]->zerr;
			xden = p[0]->den;
			ix = (x + onehalf) >> fixshift;
			if(ix >= maxx)
				break;
			if(ix < minx)
				ix = minx;
			cnt += p[0]->d;
			p++;
			for(;;) {
				if(p == ep) {
					print("xscan: fill to infinity");
					return;
				}
				cnt += p[0]->d;
				if((cnt&wind) == 0)
					break;
				p++;
			}
			x2 = p[0]->z;
			ix2 = (x2 + onehalf) >> fixshift;
			if(ix2 <= minx)
				continue;
			if(ix2 > maxx)
				ix2 = maxx;
			if(ix == ix2 && detail) {
				if(xerr*p[0]->den + p[0]->zerr*xden > p[0]->den*xden)
					x++;
				ix = (x + x2) >> (fixshift+1);
				ix2 = ix+1;
			}
			(*fill)(dst, ix, ix2, iy, src, sp, op);
		}
		y += (1<<fixshift);
		iy++;
	}
}
Ejemplo n.º 6
0
Archivo: trace.cpp Proyecto: Tjuly/ME
/* returns 0 on success, 1 on error with errno set */
static int calc_lon(privpath_t *pp) {
  point_t *pt = pp->pt;
  int n = pp->len;
  int i, j, k, k1;
  int ct[4], dir;
  point_t constraint[2];
  point_t cur;
  point_t off;
  int *pivk = NULL;  /* pivk[n] */
  int *nc = NULL;    /* nc[n]: next corner */
  point_t dk;  /* direction of k-k1 */
  int a, b, c, d;

  SAFE_MALLOC(pivk, n, int);
  SAFE_MALLOC(nc, n, int);

  /* initialize the nc data structure. Point from each point to the
     furthest future point to which it is connected by a vertical or
     horizontal segment. We take advantage of the fact that there is
     always a direction change at 0 (due to the path decomposition
     algorithm). But even if this were not so, there is no harm, as
     in practice, correctness does not depend on the word "furthest"
     above.  */
  k = 0;
  for (i=n-1; i>=0; i--) {
    if (pt[i].x != pt[k].x && pt[i].y != pt[k].y) {
      k = i+1;  /* necessarily i<n-1 in this case */
    }
    nc[i] = k;
  }

  SAFE_MALLOC(pp->lon, n, int);

  /* determine pivot points: for each i, let pivk[i] be the furthest k
     such that all j with i<j<k lie on a line connecting i,k. */

  for (i=n-1; i>=0; i--) {
    ct[0] = ct[1] = ct[2] = ct[3] = 0;

    /* keep track of "directions" that have occurred */
    dir = (3+3*(pt[mod(i+1,n)].x-pt[i].x)+(pt[mod(i+1,n)].y-pt[i].y))/2;
    ct[dir]++;

    constraint[0].x = 0;
    constraint[0].y = 0;
    constraint[1].x = 0;
    constraint[1].y = 0;

    /* find the next k such that no straight line from i to k */
    k = nc[i];
    k1 = i;
    while (1) {

      dir = (3+3*sign(pt[k].x-pt[k1].x)+sign(pt[k].y-pt[k1].y))/2;
      ct[dir]++;

      /* if all four "directions" have occurred, cut this path */
      if (ct[0] && ct[1] && ct[2] && ct[3]) {
    pivk[i] = k1;
    goto foundk;
      }

      cur.x = pt[k].x - pt[i].x;
      cur.y = pt[k].y - pt[i].y;

      /* see if current constraint is violated */
      if (xprod(constraint[0], cur) < 0 || xprod(constraint[1], cur) > 0) {
    goto constraint_viol;
      }

      /* else, update constraint */
      if (abs(cur.x) <= 1 && abs(cur.y) <= 1) {
    /* no constraint */
      } else {
    off.x = cur.x + ((cur.y>=0 && (cur.y>0 || cur.x<0)) ? 1 : -1);
    off.y = cur.y + ((cur.x<=0 && (cur.x<0 || cur.y<0)) ? 1 : -1);
    if (xprod(constraint[0], off) >= 0) {
      constraint[0] = off;
    }
    off.x = cur.x + ((cur.y<=0 && (cur.y<0 || cur.x<0)) ? 1 : -1);
    off.y = cur.y + ((cur.x>=0 && (cur.x>0 || cur.y<0)) ? 1 : -1);
    if (xprod(constraint[1], off) <= 0) {
      constraint[1] = off;
    }
      }
      k1 = k;
      k = nc[k1];
      if (!cyclic(k,i,k1)) {
    break;
      }
    }
  constraint_viol:
    /* k1 was the last "corner" satisfying the current constraint, and
       k is the first one violating it. We now need to find the last
       point along k1..k which satisfied the constraint. */
    dk.x = sign(pt[k].x-pt[k1].x);
    dk.y = sign(pt[k].y-pt[k1].y);
    cur.x = pt[k1].x - pt[i].x;
    cur.y = pt[k1].y - pt[i].y;
    /* find largest integer j such that xprod(constraint[0], cur+j*dk)
       >= 0 and xprod(constraint[1], cur+j*dk) <= 0. Use bilinearity
       of xprod. */
    a = xprod(constraint[0], cur);
    b = xprod(constraint[0], dk);
    c = xprod(constraint[1], cur);
    d = xprod(constraint[1], dk);
    /* find largest integer j such that a+j*b>=0 and c+j*d<=0. This
       can be solved with integer arithmetic. */
    j = INFTY;
    if (b<0) {
      j = floordiv(a,-b);
    }
    if (d>0) {
      j = min(j, floordiv(-c,d));
    }
    pivk[i] = mod(k1+j,n);
  foundk:
    ;
  } /* for i */

  /* clean up: for each i, let lon[i] be the largest k such that for
     all i' with i<=i'<k, i'<k<=pivk[i']. */

  j=pivk[n-1];
  pp->lon[n-1]=j;
  for (i=n-2; i>=0; i--) {
    if (cyclic(i+1,pivk[i],j)) {
      j=pivk[i];
    }
    pp->lon[i]=j;
  }

  for (i=n-1; cyclic(mod(i+1,n),j,pp->lon[i]); i--) {
    pp->lon[i] = j;
  }

  free(pivk);
  free(nc);
  return 0;

 malloc_error:
  free(pivk);
  free(nc);
  return 1;
}
Ejemplo n.º 7
0
Archivo: trace.cpp Proyecto: Tjuly/ME
static int adjust_vertices(privpath_t *pp) {
  int m = pp->m;
  int *po = pp->po;
  int n = pp->len;
  point_t *pt = pp->pt;
  int x0 = pp->x0;
  int y0 = pp->y0;

  dpoint_t *ctr = NULL;      /* ctr[m] */
  dpoint_t *dir = NULL;      /* dir[m] */
  quadform_t *q = NULL;      /* q[m] */
  double v[3];
  double d;
  int i, j, k, l;
  dpoint_t s;
  int r;

  SAFE_MALLOC(ctr, m, dpoint_t);
  SAFE_MALLOC(dir, m, dpoint_t);
  SAFE_MALLOC(q, m, quadform_t);

  r = privcurve_init(&pp->curve, m);
  if (r) {
    goto malloc_error;
  }

  /* calculate "optimal" point-slope representation for each line
     segment */
  for (i=0; i<m; i++) {
    j = po[mod(i+1,m)];
    j = mod(j-po[i],n)+po[i];
    pointslope(pp, po[i], j, &ctr[i], &dir[i]);
  }

  /* represent each line segment as a singular quadratic form; the
     distance of a point (x,y) from the line segment will be
     (x,y,1)Q(x,y,1)^t, where Q=q[i]. */
  for (i=0; i<m; i++) {
    d = sq(dir[i].x) + sq(dir[i].y);
    if (d == 0.0) {
      for (j=0; j<3; j++) {
    for (k=0; k<3; k++) {
      q[i][j][k] = 0;
    }
      }
    } else {
      v[0] = dir[i].y;
      v[1] = -dir[i].x;
      v[2] = - v[1] * ctr[i].y - v[0] * ctr[i].x;
      for (l=0; l<3; l++) {
    for (k=0; k<3; k++) {
      q[i][l][k] = v[l] * v[k] / d;
    }
      }
    }
  }

  /* now calculate the "intersections" of consecutive segments.
     Instead of using the actual intersection, we find the point
     within a given unit square which minimizes the square distance to
     the two lines. */
  for (i=0; i<m; i++) {
    quadform_t Q;
    dpoint_t w;
    double dx, dy;
    double det;
    double min, cand; /* minimum and candidate for minimum of quad. form */
    double xmin, ymin;	/* coordinates of minimum */
    int z;

    /* let s be the vertex, in coordinates relative to x0/y0 */
    s.x = pt[po[i]].x-x0;
    s.y = pt[po[i]].y-y0;

    /* intersect segments i-1 and i */

    j = mod(i-1,m);

    /* add quadratic forms */
    for (l=0; l<3; l++) {
      for (k=0; k<3; k++) {
    Q[l][k] = q[j][l][k] + q[i][l][k];
      }
    }

    while(1) {
      /* minimize the quadratic form Q on the unit square */
      /* find intersection */

#ifdef HAVE_GCC_LOOP_BUG
      /* work around gcc bug #12243 */
      free(NULL);
#endif

      det = Q[0][0]*Q[1][1] - Q[0][1]*Q[1][0];
      if (det != 0.0) {
    w.x = (-Q[0][2]*Q[1][1] + Q[1][2]*Q[0][1]) / det;
    w.y = ( Q[0][2]*Q[1][0] - Q[1][2]*Q[0][0]) / det;
    break;
      }

      /* matrix is singular - lines are parallel. Add another,
     orthogonal axis, through the center of the unit square */
      if (Q[0][0]>Q[1][1]) {
    v[0] = -Q[0][1];
    v[1] = Q[0][0];
      } else if (Q[1][1]) {
    v[0] = -Q[1][1];
    v[1] = Q[1][0];
      } else {
    v[0] = 1;
    v[1] = 0;
      }
      d = sq(v[0]) + sq(v[1]);
      v[2] = - v[1] * s.y - v[0] * s.x;
      for (l=0; l<3; l++) {
    for (k=0; k<3; k++) {
      Q[l][k] += v[l] * v[k] / d;
    }
      }
    }
    dx = fabs(w.x-s.x);
    dy = fabs(w.y-s.y);
    if (dx <= .5 && dy <= .5) {
      pp->curve.vertex[i].x = w.x+x0;
      pp->curve.vertex[i].y = w.y+y0;
      continue;
    }

    /* the minimum was not in the unit square; now minimize quadratic
       on boundary of square */
    min = quadform(Q, s);
    xmin = s.x;
    ymin = s.y;

    if (Q[0][0] == 0.0) {
      goto fixx;
    }
    for (z=0; z<2; z++) {   /* value of the y-coordinate */
      w.y = s.y-0.5+z;
      w.x = - (Q[0][1] * w.y + Q[0][2]) / Q[0][0];
      dx = fabs(w.x-s.x);
      cand = quadform(Q, w);
      if (dx <= .5 && cand < min) {
    min = cand;
    xmin = w.x;
    ymin = w.y;
      }
    }
  fixx:
    if (Q[1][1] == 0.0) {
      goto corners;
    }
    for (z=0; z<2; z++) {   /* value of the x-coordinate */
      w.x = s.x-0.5+z;
      w.y = - (Q[1][0] * w.x + Q[1][2]) / Q[1][1];
      dy = fabs(w.y-s.y);
      cand = quadform(Q, w);
      if (dy <= .5 && cand < min) {
    min = cand;
    xmin = w.x;
    ymin = w.y;
      }
    }
  corners:
    /* check four corners */
    for (l=0; l<2; l++) {
      for (k=0; k<2; k++) {
    w.x = s.x-0.5+l;
    w.y = s.y-0.5+k;
    cand = quadform(Q, w);
    if (cand < min) {
      min = cand;
      xmin = w.x;
      ymin = w.y;
    }
      }
    }

    pp->curve.vertex[i].x = xmin + x0;
    pp->curve.vertex[i].y = ymin + y0;
    continue;
  }

  free(ctr);
  free(dir);
  free(q);
  return 0;

 malloc_error:
  free(ctr);
  free(dir);
  free(q);
  return 1;
}
Ejemplo n.º 8
0
float smoothPulseTrain(float e0,float e1,float e2,float e3,float period,float x) 
{
	return (smoothPulse(e0, e1, e2, e3, mod(x, period)));
}
Ejemplo n.º 9
0
void tipc_bclink_recv_pkt(struct sk_buff *buf)
{
#if (TIPC_BCAST_LOSS_RATE)
	static int rx_count = 0;
#endif
	struct tipc_msg *msg = buf_msg(buf);
	struct node* node = tipc_node_find(msg_prevnode(msg));
	u32 next_in;
	u32 seqno;
	struct sk_buff *deferred;

	msg_dbg(msg, "<BC<<<");

	if (unlikely(!node || !tipc_node_is_up(node) || !node->bclink.supported || 
		     (msg_mc_netid(msg) != tipc_net_id))) {
		buf_discard(buf);
		return;
	}

	if (unlikely(msg_user(msg) == BCAST_PROTOCOL)) {
		msg_dbg(msg, "<BCNACK<<<");
		if (msg_destnode(msg) == tipc_own_addr) {
			tipc_node_lock(node);
			tipc_bclink_acknowledge(node, msg_bcast_ack(msg));
			tipc_node_unlock(node);
			spin_lock_bh(&bc_lock);
			bcl->stats.recv_nacks++;
			bcl->owner->next = node;   /* remember requestor */
			bclink_retransmit_pkt(msg_bcgap_after(msg),
					      msg_bcgap_to(msg));
			bcl->owner->next = NULL;
			spin_unlock_bh(&bc_lock);              
		} else {
			tipc_bclink_peek_nack(msg_destnode(msg),
					      msg_bcast_tag(msg),
					      msg_bcgap_after(msg),
					      msg_bcgap_to(msg));
		}
		buf_discard(buf);
		return;
	}

#if (TIPC_BCAST_LOSS_RATE)
	if (++rx_count == TIPC_BCAST_LOSS_RATE) {
		rx_count = 0;
		buf_discard(buf);
		return;
	}
#endif

	tipc_node_lock(node);
receive:
	deferred = node->bclink.deferred_head;
	next_in = mod(node->bclink.last_in + 1);
	seqno = msg_seqno(msg);

	if (likely(seqno == next_in)) {
		bcl->stats.recv_info++;
		node->bclink.last_in++;
		bclink_set_gap(node);
		if (unlikely(bclink_ack_allowed(seqno))) {
			bclink_send_ack(node);
			bcl->stats.sent_acks++;
		}
		if (likely(msg_isdata(msg))) {
			tipc_node_unlock(node);
			tipc_port_recv_mcast(buf, NULL);
		} else if (msg_user(msg) == MSG_BUNDLER) {
			bcl->stats.recv_bundles++;
			bcl->stats.recv_bundled += msg_msgcnt(msg);
			tipc_node_unlock(node);
			tipc_link_recv_bundle(buf);
		} else if (msg_user(msg) == MSG_FRAGMENTER) {
			bcl->stats.recv_fragments++;
			if (tipc_link_recv_fragment(&node->bclink.defragm,
						    &buf, &msg))
				bcl->stats.recv_fragmented++;
			tipc_node_unlock(node);
			tipc_net_route_msg(buf);
		} else {
			tipc_node_unlock(node);
			tipc_net_route_msg(buf);
		}
		if (deferred && (buf_seqno(deferred) == mod(next_in + 1))) {
			tipc_node_lock(node);
			buf = deferred;
			msg = buf_msg(buf);
			node->bclink.deferred_head = deferred->next;
			goto receive;
		}
		return;
	} else if (less(next_in, seqno)) {
		u32 gap_after = node->bclink.gap_after;
		u32 gap_to = node->bclink.gap_to;

		if (tipc_link_defer_pkt(&node->bclink.deferred_head,
					&node->bclink.deferred_tail,
					buf)) {
			node->bclink.nack_sync++;
			bcl->stats.deferred_recv++;
			if (seqno == mod(gap_after + 1))
				node->bclink.gap_after = seqno;
			else if (less(gap_after, seqno) && less(seqno, gap_to))
				node->bclink.gap_to = seqno;
		}
		if (bclink_ack_allowed(node->bclink.nack_sync)) {
			if (gap_to != gap_after)
				bclink_send_nack(node);
			bclink_set_gap(node);
		}
	} else {
		bcl->stats.duplicates++;
		buf_discard(buf);
	}
	tipc_node_unlock(node);
}
Ejemplo n.º 10
0
double normalizeLonRad(double lon) {
	return( mod( (lon + M_PI), M_2PI) - M_PI);
}
Ejemplo n.º 11
0
//実行
int CSystem::Run()
{
	switch(state) {
	case SYSTEM_NORMAL://通常
		count++;
		if( GetInputPause() && (g_pBoss==NULL||g_pBoss->pTalk==NULL) ) {
			sndPause.Play(0);
			state = SYSTEM_PAUSE;
			g_pGame->Stop();
		}
		if( fullpower_count > 0 )
			fullpower_count--;
		if( spellbonus_count > 0 )
			spellbonus_count--;
		//リプレイ動作
		SunReplay.Run();
		break;
	case SYSTEM_PAUSE://ポーズ中
		{
			int old = pause_select;
			int maxpause = ( g_pTitle->title_select == 3 ) ? 2 : 3;
			pause_select += GetInputUD();
			pause_select = mod(pause_select,maxpause);
			if( pause_select != old )
				g_pTitle->sndSelect.Play(0);
			if(GetInputDecide()) {
				g_pTitle->sndDecide.Play(0);
				switch(pause_select) {
				case 0://ゲームを再開する
					ResumeGame();
					break;
				case 1://タイトルに戻る
					ReturnTitle();
					return 0;
				case 2://はじめからやり直す
					Restart();
					break;
				}
			}
		}
		if( GetInputPause() ) {
			ResumeGame();
		}
		break;
	case SYSTEM_GAMEOVER://ゲームオーバー
		{
			int old = gameover_select;
			gameover_select += GetInputUD();
			gameover_select = mod(gameover_select,2);
			if( gameover_select != old )
				g_pTitle->sndSelect.Play(0);
			if(GetInputDecide()) {
				g_pTitle->sndDecide.Play(0);
				switch(gameover_select) {
				case 0://コインいっこいれる
					life = 2;
					bomb = 3;
					continue_dirty = 1;
					continue_rest--;
					score = 0;
					graze = 0;
					//ゲーム再開
					this->ResumeGame();
					//弾をすべてアイテムに
					TamaToItem();
					//エフェクト
					g_lEffect2.Add( new CEffectDamage( g_pPlayer->GetX(),g_pPlayer->GetY() ));
					//位置初期化
					g_pPlayer->ResetPosition();
					break;
				case 1://人生をあきらめる
					if( g_pGame->mode == 0 || g_pGame->mode == 2 ) {
						g_pSystem->SaveReplay();
					}
					else {
						g_pTitle->Resume();
						return 0;
					}
					break;
				}
			}
		}
		break;
	case SYSTEM_REPLAY://リプレイ保存
		if( continue_dirty == 0 ) {
			int old = replay_select;
			replay_select += GetInputUD();
			replay_select = mod(replay_select,2);
			if( replay_select != old )
				g_pTitle->sndSelect.Play(0);
			if(GetInputDecide()) {
				g_pTitle->sndDecide.Play(0);
				switch(replay_select) {
				case 0://もちろん!
					SunReplay.Save();
					break;
				case 1://抹消
					break;
				}
				SunReplay.Exit();
				ReturnTitle();
				return 0;
			}
		}
		else if(GetInputDecide()) {
			g_pTitle->sndDecide.Play(0);
			SunReplay.Exit();
			ReturnTitle();
		}
		break;
	case SYSTEM_RESULT://ステージリザルト
		count++;
		switch( result_mode ) {
		case 0:
			result_count ++;
			//リプレイ動作
			SunReplay.Run();
			if( result_count == RESULT_COUNT ) {
				result_count = 0;
				result_mode ++;
				g_pGame->Stop();
			}
			break;
		case 1:
			result_count ++;
			if( GetInputDecide() || (g_pGame->mode == 3 && result_count > 180)) {
				result_count = 0;
				result_mode ++;
				g_pTitle->sndDecide.Play(0);

				g_lShot.DeleteAll();
				g_lLaser.DeleteAll();
				g_lTama.DeleteAll();
				g_lItem.DeleteAll();
				g_lEnemy.DeleteAll();
				g_lEffect.DeleteAll();
				g_lEffect2.DeleteAll();
				g_lEffect3.DeleteAll();
				SAFE_DELETE( g_pStage );
				g_pPlayer->ResetState();
				g_pGame->stop = 0;
				AddScore( (1+life*4+bomb)*g_pGame->stage*(1+GetDifficult())*10000 );
				if( (g_pGame->mode == 0 || (g_pGame->mode == 3&&SunReplay.m_header.mode==0)) && g_pGame->stage <= STAGE_NUM ) {
					g_pGame->CreateStage();
				}
				else if( g_pGame->mode == 2 || (g_pGame->mode==0&&g_pGame->stage > STAGE_NUM) ) {
					SaveReplay();
				}
				else{
					g_pTitle->Resume();
					return 0;
				}
			}
			break;
		case 2:
			result_count ++;
			//リプレイ動作
			SunReplay.Run();
			if( result_count == RESULT_COUNT ) {
				result_count = 0;
				result_mode = 0;
				state = SYSTEM_NORMAL;
				g_pGame->Resume();
			}
			break;
		}
		break;
	case SYSTEM_RESUME: //ゲームに復帰中
		resume_count--;
		if( resume_count == 0 ) {
			g_pGame->Resume();
		}
		break;
	}
	return 1;
}
Ejemplo n.º 12
0
double normalizeLonDeg(double lon) {
	return( mod( (lon + 180), 360 ) - 180 );
}
Ejemplo n.º 13
0
/**
 * tipc_bclink_recv_pkt - receive a broadcast packet, and deliver upwards
 *
 * tipc_net_lock is read_locked, no other locks set
 */
void tipc_bclink_recv_pkt(struct sk_buff *buf)
{
	struct tipc_msg *msg = buf_msg(buf);
	struct tipc_node *node;
	u32 next_in;
	u32 seqno;
	int deferred;

	/* Screen out unwanted broadcast messages */

	if (msg_mc_netid(msg) != tipc_net_id)
		goto exit;

	node = tipc_node_find(msg_prevnode(msg));
	if (unlikely(!node))
		goto exit;

	tipc_node_lock(node);
	if (unlikely(!node->bclink.recv_permitted))
		goto unlock;

	/* Handle broadcast protocol message */

	if (unlikely(msg_user(msg) == BCAST_PROTOCOL)) {
		if (msg_type(msg) != STATE_MSG)
			goto unlock;
		if (msg_destnode(msg) == tipc_own_addr) {
			tipc_bclink_acknowledge(node, msg_bcast_ack(msg));
			tipc_node_unlock(node);
			spin_lock_bh(&bc_lock);
			bcl->stats.recv_nacks++;
			bclink->retransmit_to = node;
			bclink_retransmit_pkt(msg_bcgap_after(msg),
					      msg_bcgap_to(msg));
			spin_unlock_bh(&bc_lock);
		} else {
			tipc_node_unlock(node);
			bclink_peek_nack(msg);
		}
		goto exit;
	}

	/* Handle in-sequence broadcast message */

	seqno = msg_seqno(msg);
	next_in = mod(node->bclink.last_in + 1);

	if (likely(seqno == next_in)) {
receive:
		/* Deliver message to destination */

		if (likely(msg_isdata(msg))) {
			spin_lock_bh(&bc_lock);
			bclink_accept_pkt(node, seqno);
			spin_unlock_bh(&bc_lock);
			tipc_node_unlock(node);
			if (likely(msg_mcast(msg)))
				tipc_port_recv_mcast(buf, NULL);
			else
				kfree_skb(buf);
		} else if (msg_user(msg) == MSG_BUNDLER) {
			spin_lock_bh(&bc_lock);
			bclink_accept_pkt(node, seqno);
			bcl->stats.recv_bundles++;
			bcl->stats.recv_bundled += msg_msgcnt(msg);
			spin_unlock_bh(&bc_lock);
			tipc_node_unlock(node);
			tipc_link_recv_bundle(buf);
		} else if (msg_user(msg) == MSG_FRAGMENTER) {
			int ret;
			ret = tipc_link_recv_fragment(&node->bclink.reasm_head,
						      &node->bclink.reasm_tail,
						      &buf);
			if (ret == LINK_REASM_ERROR)
				goto unlock;
			spin_lock_bh(&bc_lock);
			bclink_accept_pkt(node, seqno);
			bcl->stats.recv_fragments++;
			if (ret == LINK_REASM_COMPLETE) {
				bcl->stats.recv_fragmented++;
				/* Point msg to inner header */
				msg = buf_msg(buf);
				spin_unlock_bh(&bc_lock);
				goto receive;
			}
			spin_unlock_bh(&bc_lock);
			tipc_node_unlock(node);
		} else if (msg_user(msg) == NAME_DISTRIBUTOR) {
			spin_lock_bh(&bc_lock);
			bclink_accept_pkt(node, seqno);
			spin_unlock_bh(&bc_lock);
			tipc_node_unlock(node);
			tipc_named_recv(buf);
		} else {
			spin_lock_bh(&bc_lock);
			bclink_accept_pkt(node, seqno);
			spin_unlock_bh(&bc_lock);
			tipc_node_unlock(node);
			kfree_skb(buf);
		}
		buf = NULL;

		/* Determine new synchronization state */

		tipc_node_lock(node);
		if (unlikely(!tipc_node_is_up(node)))
			goto unlock;

		if (node->bclink.last_in == node->bclink.last_sent)
			goto unlock;

		if (!node->bclink.deferred_head) {
			node->bclink.oos_state = 1;
			goto unlock;
		}

		msg = buf_msg(node->bclink.deferred_head);
		seqno = msg_seqno(msg);
		next_in = mod(next_in + 1);
		if (seqno != next_in)
			goto unlock;

		/* Take in-sequence message from deferred queue & deliver it */

		buf = node->bclink.deferred_head;
		node->bclink.deferred_head = buf->next;
		buf->next = NULL;
		node->bclink.deferred_size--;
		goto receive;
	}

	/* Handle out-of-sequence broadcast message */

	if (less(next_in, seqno)) {
		deferred = tipc_link_defer_pkt(&node->bclink.deferred_head,
					       &node->bclink.deferred_tail,
					       buf);
		node->bclink.deferred_size += deferred;
		bclink_update_last_sent(node, seqno);
		buf = NULL;
	} else
		deferred = 0;

	spin_lock_bh(&bc_lock);

	if (deferred)
		bcl->stats.deferred_recv++;
	else
		bcl->stats.duplicates++;

	spin_unlock_bh(&bc_lock);

unlock:
	tipc_node_unlock(node);
exit:
	kfree_skb(buf);
}
Ejemplo n.º 14
0
void force(FILE       *fp,     int        step,
	   t_forcerec *fr,      t_inputrec *ir,
	   t_idef     *idef,    t_nsborder *nsb,
	   t_commrec  *cr,      t_commrec *mcr,
	   t_nrnb     *nrnb,
	   t_groups   *grps,    t_mdatoms  *md,
	   int        ngener,   t_grpopts  *opts,
	   rvec       x[],      rvec       f[],
	   real       epot[],   t_fcdata   *fcd,
	   bool       bVerbose, matrix     box,
	   real       lambda,   t_graph    *graph,
	   t_block    *excl,    bool       bNBFonly,
	   matrix lr_vir,       rvec       mu_tot,
	   real       qsum,     bool       bGatherOnly)
{
  int     i,nit;
  bool    bDoEpot;
  rvec    box_size;
  real    Vlr,Vcorr=0;
  
  /* Reset box */
  for(i=0; (i<DIM); i++)
    box_size[i]=box[i][i];
    
  bDoEpot=((fr->nmol > 0) && (fr->nstcalc > 0) && (mod(step,fr->nstcalc)==0));
  /* Reset epot... */
  if (bDoEpot) 
    for(i=0; (i<fr->nmol); i++)
      fr->mol_epot[i]=0.0;
  debug_gmx();
  
  /* Call the short range functions all in one go. */
  do_fnbf(fp,cr,fr,x,f,md,
	  fr->bBHAM ? grps->estat.ee[egBHAM] : grps->estat.ee[egLJ],
	  grps->estat.ee[egCOUL],box_size,nrnb,
	  lambda,&epot[F_DVDL],FALSE,-1);
  debug_gmx();

  if (debug) 
    pr_rvecs(debug,0,"fshift after SR",fr->fshift,SHIFTS);
  
  /* Shift the coordinates. Must be done before bonded forces and PPPM, 
   * but is also necessary for SHAKE and update, therefore it can NOT 
   * go when no bonded forces have to be evaluated.
   */
  if (debug && 0)
    p_graph(debug,"DeBUGGGG",graph);
  
  /* Check whether we need to do bondeds */
  if (!bNBFonly) {
    shift_self(graph,box,x);
    if (debug && 0) {
      fprintf(debug,"BBBBBBBBBBBBBBBB\n");
      fprintf(debug,"%5d\n",graph->nnodes);
      for(i=graph->start; (i<=graph->end); i++)
	fprintf(debug,"%5d%5s%5s%5d%8.3f%8.3f%8.3f\n",
		i,"A","B",i,x[i][XX],x[i][YY],x[i][ZZ]);
      fprintf(debug,"%10.5f%10.5f%10.5f\n",
	      box[XX][XX],box[YY][YY],box[ZZ][ZZ]);
    }
    if (TRICLINIC(box))
	inc_nrnb(nrnb,eNR_SHIFTX,2*graph->nnodes);
    else
	inc_nrnb(nrnb,eNR_SHIFTX,graph->nnodes);
    debug_gmx();
  }
  
  if (EEL_LR(fr->eeltype)) {
    switch (fr->eeltype) {
    case eelPPPM:
      Vlr = do_pppm(fp,FALSE,x,fr->f_pme,md->chargeT,
		    box_size,fr->phi,cr,nsb,nrnb);
      break;
    case eelPOISSON:
      Vlr = do_poisson(fp,FALSE,ir,md->nr,x,fr->f_pme,md->chargeT,
		       box_size,fr->phi,cr,nrnb,&nit,TRUE);
      break;
    case eelPME:
      Vlr = do_pme(fp,FALSE,ir,x,fr->f_pme,md->chargeT,
		   box,cr,nsb,nrnb,lr_vir,fr->ewaldcoeff,bGatherOnly);
      break;
    case eelEWALD:
      Vlr = do_ewald(fp,FALSE,ir,x,fr->f_pme,md->chargeT,
		     box_size,cr,nsb,lr_vir,fr->ewaldcoeff);
      break;
    default:
      Vlr = 0;
      fatal_error(0,"No such electrostatics method implemented %s",
		  eel_names[fr->eeltype]);
    }
    if(fr->bEwald)
      Vcorr =
	ewald_LRcorrection(fp,nsb,cr,fr,md->chargeT,excl,x,box,mu_tot,qsum,
			   ir->ewald_geometry,ir->epsilon_surface,lr_vir);
    else
      Vcorr = shift_LRcorrection(fp,nsb,cr,fr,md->chargeT,excl,x,TRUE,box,lr_vir);
    epot[F_LR] = Vlr + Vcorr;
    if (debug)
      fprintf(debug,"Vlr = %g, Vcorr = %g, Vlr_corr = %g\n",
	      Vlr,Vcorr,epot[F_LR]);
    if (debug) {
      pr_rvecs(debug,0,"lr_vir after corr",lr_vir,DIM);
      pr_rvecs(debug,0,"fshift after LR Corrections",fr->fshift,SHIFTS);
    }
  }
  debug_gmx();
  
  if (debug)    
    print_nrnb(debug,nrnb); 
  debug_gmx();
  
  if (!bNBFonly) {
    calc_bonds(fp,cr,mcr,
	       idef,x,f,fr,graph,epot,nrnb,box,lambda,md,
	       opts->ngener,grps->estat.ee[egLJ14],grps->estat.ee[egCOUL14],
	       fcd,step,fr->bSepDVDL && do_per_step(step,ir->nstlog));    
    debug_gmx();
  }
  if (debug) 
    pr_rvecs(debug,0,"fshift after bondeds",fr->fshift,SHIFTS);
  
  for(i=0; (i<F_EPOT); i++)
    if (i != F_DISRES)
      epot[F_EPOT]+=epot[i];
}
Ejemplo n.º 15
0
        void registerExtensions (Extensions& extensions)
        {
            static const char *attributes[numberOfAttributes] =
            {
                "strength", "intelligence", "willpower", "agility", "speed", "endurance",
                "personality", "luck"
            };

            static const char *dynamics[numberOfDynamics] =
            {
                "health", "magicka", "fatigue"
            };

            static const char *skills[numberOfSkills] =
            {
                "block", "armorer", "mediumarmor", "heavyarmor", "bluntweapon",
                "longblade", "axe", "spear", "athletics", "enchant", "destruction",
                "alteration", "illusion", "conjuration", "mysticism",
                "restoration", "alchemy", "unarmored", "security", "sneak",
                "acrobatics", "lightarmor", "shortblade", "marksman",
                "mercantile", "speechcraft", "handtohand"
            };

            static const char *magicEffects[numberOfMagicEffects] =
            {
                "resistmagicka", "resistfire", "resistfrost", "resistshock",
                "resistdisease", "resistblight", "resistcorprus", "resistpoison",
                "resistparalysis", "resistnormalweapons", "waterbreathing", "chameleon",
                "waterwalking", "swimspeed", "superjump", "flying",
                "armorbonus", "castpenalty", "silence", "blindness",
                "paralysis", "invisible", "attackbonus", "defendbonus"
            };

            std::string get ("get");
            std::string set ("set");
            std::string mod ("mod");
            std::string modCurrent ("modcurrent");
            std::string getRatio ("getratio");

            for (int i=0; i<numberOfAttributes; ++i)
            {
                extensions.registerFunction (get + attributes[i], 'l', "",
                    opcodeGetAttribute+i, opcodeGetAttributeExplicit+i);

                extensions.registerInstruction (set + attributes[i], "l",
                    opcodeSetAttribute+i, opcodeSetAttributeExplicit+i);

                extensions.registerInstruction (mod + attributes[i], "l",
                    opcodeModAttribute+i, opcodeModAttributeExplicit+i);
            }

            for (int i=0; i<numberOfDynamics; ++i)
            {
                extensions.registerFunction (get + dynamics[i], 'f', "",
                    opcodeGetDynamic+i, opcodeGetDynamicExplicit+i);

                extensions.registerInstruction (set + dynamics[i], "f",
                    opcodeSetDynamic+i, opcodeSetDynamicExplicit+i);

                extensions.registerInstruction (mod + dynamics[i], "f",
                    opcodeModDynamic+i, opcodeModDynamicExplicit+i);

                extensions.registerInstruction (modCurrent + dynamics[i], "f",
                    opcodeModCurrentDynamic+i, opcodeModCurrentDynamicExplicit+i);

                extensions.registerFunction (get + dynamics[i] + getRatio, 'f', "",
                    opcodeGetDynamicGetRatio+i, opcodeGetDynamicGetRatioExplicit+i);
            }

            for (int i=0; i<numberOfSkills; ++i)
            {
                extensions.registerFunction (get + skills[i], 'l', "",
                    opcodeGetSkill+i, opcodeGetSkillExplicit+i);

                extensions.registerInstruction (set + skills[i], "l",
                    opcodeSetSkill+i, opcodeSetSkillExplicit+i);

                extensions.registerInstruction (mod + skills[i], "l",
                    opcodeModSkill+i, opcodeModSkillExplicit+i);
            }

            for (int i=0; i<numberOfMagicEffects; ++i)
            {
                extensions.registerFunction (get + magicEffects[i], 'l', "",
                    opcodeGetMagicEffect+i, opcodeGetMagicEffectExplicit+i);

                extensions.registerInstruction (set + magicEffects[i], "l",
                    opcodeSetMagicEffect+i, opcodeSetMagicEffectExplicit+i);

                extensions.registerInstruction(mod + magicEffects[i], "l",
                    opcodeModMagicEffect+i, opcodeModMagicEffectExplicit+i);
            }

            extensions.registerFunction ("getpccrimelevel", 'f', "", opcodeGetPCCrimeLevel);
            extensions.registerInstruction ("setpccrimelevel", "f", opcodeSetPCCrimeLevel);
            extensions.registerInstruction ("modpccrimelevel", "f", opcodeModPCCrimeLevel);

            extensions.registerInstruction ("addspell", "cz", opcodeAddSpell, opcodeAddSpellExplicit);
            extensions.registerInstruction ("removespell", "c", opcodeRemoveSpell,
                opcodeRemoveSpellExplicit);
            extensions.registerInstruction ("removespelleffects", "c", opcodeRemoveSpellEffects,
                opcodeRemoveSpellEffectsExplicit);
            extensions.registerInstruction ("removeeffects", "l", opcodeRemoveEffects,
                opcodeRemoveEffectsExplicit);
            extensions.registerInstruction ("resurrect", "", opcodeResurrect,
                opcodeResurrectExplicit);
            extensions.registerFunction ("getspell", 'l', "c", opcodeGetSpell, opcodeGetSpellExplicit);

            extensions.registerInstruction("pcraiserank","/S",opcodePCRaiseRank, opcodePCRaiseRankExplicit);
            extensions.registerInstruction("pclowerrank","/S",opcodePCLowerRank, opcodePCLowerRankExplicit);
            extensions.registerInstruction("pcjoinfaction","/S",opcodePCJoinFaction, opcodePCJoinFactionExplicit);
            extensions.registerInstruction ("moddisposition","l",opcodeModDisposition,
                opcodeModDispositionExplicit);
            extensions.registerInstruction ("setdisposition","l",opcodeSetDisposition,
                opcodeSetDispositionExplicit);
            extensions.registerFunction ("getdisposition",'l', "",opcodeGetDisposition,
                opcodeGetDispositionExplicit);
            extensions.registerFunction("getpcrank",'l',"/S",opcodeGetPCRank,opcodeGetPCRankExplicit);

            extensions.registerInstruction("setlevel", "l", opcodeSetLevel, opcodeSetLevelExplicit);
            extensions.registerFunction("getlevel", 'l', "", opcodeGetLevel, opcodeGetLevelExplicit);

            extensions.registerFunction("getstat", 'l', "c", opcodeGetStat, opcodeGetStatExplicit);

            extensions.registerFunction ("getdeadcount", 'l', "c", opcodeGetDeadCount);

            extensions.registerFunction ("getpcfacrep", 'l', "/c", opcodeGetPCFacRep, opcodeGetPCFacRepExplicit);
            extensions.registerInstruction ("setpcfacrep", "l/c", opcodeSetPCFacRep, opcodeSetPCFacRepExplicit);
            extensions.registerInstruction ("modpcfacrep", "l/c", opcodeModPCFacRep, opcodeModPCFacRepExplicit);

            extensions.registerFunction ("getcommondisease", 'l', "", opcodeGetCommonDisease,
                opcodeGetCommonDiseaseExplicit);
            extensions.registerFunction ("getblightdisease", 'l', "", opcodeGetBlightDisease,
                opcodeGetBlightDiseaseExplicit);

            extensions.registerFunction ("getrace", 'l', "c", opcodeGetRace,
                opcodeGetRaceExplicit);
            extensions.registerFunction ("getwerewolfkills", 'l', "", opcodeGetWerewolfKills);
            extensions.registerFunction ("pcexpelled", 'l', "/S", opcodePcExpelled, opcodePcExpelledExplicit);
            extensions.registerInstruction ("pcexpell", "/S", opcodePcExpell, opcodePcExpellExplicit);
            extensions.registerInstruction ("pcclearexpelled", "/S", opcodePcClearExpelled, opcodePcClearExpelledExplicit);
            extensions.registerInstruction ("raiserank", "", opcodeRaiseRank, opcodeRaiseRankExplicit);
            extensions.registerInstruction ("lowerrank", "", opcodeLowerRank, opcodeLowerRankExplicit);

            extensions.registerFunction ("ondeath", 'l', "", opcodeOnDeath, opcodeOnDeathExplicit);
            extensions.registerFunction ("onmurder", 'l', "", opcodeOnMurder, opcodeOnMurderExplicit);
            extensions.registerFunction ("onknockout", 'l', "", opcodeOnKnockout, opcodeOnKnockoutExplicit);

            extensions.registerFunction ("iswerewolf", 'l', "", opcodeIsWerewolf, opcodeIsWerewolfExplicit);

            extensions.registerInstruction("becomewerewolf", "", opcodeBecomeWerewolf, opcodeBecomeWerewolfExplicit);
            extensions.registerInstruction("undowerewolf", "", opcodeUndoWerewolf, opcodeUndoWerewolfExplicit);
            extensions.registerInstruction("setwerewolfacrobatics", "", opcodeSetWerewolfAcrobatics, opcodeSetWerewolfAcrobaticsExplicit);
        }
/*! \brief Test vectors send for complex structures
 *
 * \tparam T primitives
 *
 * \param n size
 *
 */
template<typename T> void test_send_recv_primitives(size_t n, Vcluster & vcl)
{
	openfpm::vector<T> v_send = allocate_openfpm_primitive<T>(n,vcl.getProcessUnitID());

	{
	//! [Sending and receiving primitives]

	// Send to 8 processors
	for (size_t i = 0 ; i < 8 ; i++)
		vcl.send( mod(vcl.getProcessUnitID() + i * P_STRIDE, vcl.getProcessingUnits()) ,i,v_send);

	openfpm::vector<openfpm::vector<T> > pt_buf;
	pt_buf.resize(8);

	// Recv from 8 processors
	for (size_t i = 0 ; i < 8 ; i++)
	{
		pt_buf.get(i).resize(n);
		vcl.recv( mod( (vcl.getProcessUnitID() - i * P_STRIDE), vcl.getProcessingUnits()) ,i,pt_buf.get(i));
	}

	vcl.execute();

	//! [Sending and receiving primitives]

	// Check the received buffers (careful at negative modulo)
	for (size_t i = 0 ; i < 8 ; i++)
	{
		for (size_t j = 0 ; j < n ; j++)
		{
			T pt = pt_buf.get(i).get(j);

			T p_recv = mod( (vcl.getProcessUnitID() - i * P_STRIDE), vcl.getProcessingUnits());

			BOOST_REQUIRE_EQUAL(pt,p_recv);
		}
	}

	}

	{
	//! [Send and receive plain buffer data]

	// Send to 8 processors
	for (size_t i = 0 ; i < 8 ; i++)
		vcl.send( mod(vcl.getProcessUnitID() + i * P_STRIDE, vcl.getProcessingUnits()) ,i,v_send.getPointer(),v_send.size()*sizeof(T));

	openfpm::vector<openfpm::vector<T> > pt_buf;
	pt_buf.resize(8);

	// Recv from 8 processors
	for (size_t i = 0 ; i < 8 ; i++)
	{
		pt_buf.get(i).resize(n);
		vcl.recv( mod( (vcl.getProcessUnitID() - i * P_STRIDE), vcl.getProcessingUnits()) ,i,pt_buf.get(i).getPointer(),pt_buf.get(i).size()*sizeof(T));
	}

	vcl.execute();

	//! [Send and receive plain buffer data]

	// Check the received buffers (careful at negative modulo)
	for (size_t i = 0 ; i < 8 ; i++)
	{
		for (size_t j = 0 ; j < n ; j++)
		{
			T pt = pt_buf.get(i).get(j);

			T p_recv = mod( (vcl.getProcessUnitID() - i * P_STRIDE), vcl.getProcessingUnits());

			BOOST_REQUIRE_EQUAL(pt,p_recv);
		}
	}

	}
}
Ejemplo n.º 17
0
Archivo: trace.cpp Proyecto: Tjuly/ME
/* optimize the path p, replacing sequences of Bezier segments by a
   single segment when possible. Return 0 on success, 1 with errno set
   on failure. */
static int opticurve(privpath_t *pp, double opttolerance) {
  int m = pp->curve.n;
  int *pt = NULL;     /* pt[m+1] */
  double *pen = NULL; /* pen[m+1] */
  int *len = NULL;    /* len[m+1] */
  opti_t *opt = NULL; /* opt[m+1] */
  int om;
  int i,j,r;
  opti_t o;
  dpoint_t p0;
  int i1;
  double area;
  double alpha;
  double *s = NULL;
  double *t = NULL;

  int *convc = NULL; /* conv[m]: pre-computed convexities */
  double *areac = NULL; /* cumarea[m+1]: cache for fast area computation */

  SAFE_MALLOC(pt, m+1, int);
  SAFE_MALLOC(pen, m+1, double);
  SAFE_MALLOC(len, m+1, int);
  SAFE_MALLOC(opt, m+1, opti_t);
  SAFE_MALLOC(convc, m, int);
  SAFE_MALLOC(areac, m+1, double);

  /* pre-calculate convexity: +1 = right turn, -1 = left turn, 0 = corner */
  for (i=0; i<m; i++) {
    if (pp->curve.tag[i] == POTRACE_CURVETO) {
      convc[i] = sign(dpara(pp->curve.vertex[mod(i-1,m)], pp->curve.vertex[i], pp->curve.vertex[mod(i+1,m)]));
    } else {
      convc[i] = 0;
    }
  }

  /* pre-calculate areas */
  area = 0.0;
  areac[0] = 0.0;
  p0 = pp->curve.vertex[0];
  for (i=0; i<m; i++) {
    i1 = mod(i+1, m);
    if (pp->curve.tag[i1] == POTRACE_CURVETO) {
      alpha = pp->curve.alpha[i1];
      area += 0.3*alpha*(4-alpha)*dpara(pp->curve.c[i][2], pp->curve.vertex[i1], pp->curve.c[i1][2])/2;
      area += dpara(p0, pp->curve.c[i][2], pp->curve.c[i1][2])/2;
    }
    areac[i+1] = area;
  }

  pt[0] = -1;
  pen[0] = 0;
  len[0] = 0;

  /* Fixme: we always start from a fixed point -- should find the best
     curve cyclically */

  for (j=1; j<=m; j++) {
    /* calculate best path from 0 to j */
    pt[j] = j-1;
    pen[j] = pen[j-1];
    len[j] = len[j-1]+1;

    for (i=j-2; i>=0; i--) {
      r = opti_penalty(pp, i, mod(j,m), &o, opttolerance, convc, areac);
      if (r) {
    break;
      }
      if (len[j] > len[i]+1 || (len[j] == len[i]+1 && pen[j] > pen[i] + o.pen)) {
    pt[j] = i;
    pen[j] = pen[i] + o.pen;
    len[j] = len[i] + 1;
    opt[j] = o;
      }
    }
  }
  om = len[m];
  r = privcurve_init(&pp->ocurve, om);
  if (r) {
    goto malloc_error;
  }
  SAFE_MALLOC(s, om, double);
  SAFE_MALLOC(t, om, double);

  j = m;
  for (i=om-1; i>=0; i--) {
    if (pt[j]==j-1) {
      pp->ocurve.tag[i]     = pp->curve.tag[mod(j,m)];
      pp->ocurve.c[i][0]    = pp->curve.c[mod(j,m)][0];
      pp->ocurve.c[i][1]    = pp->curve.c[mod(j,m)][1];
      pp->ocurve.c[i][2]    = pp->curve.c[mod(j,m)][2];
      pp->ocurve.vertex[i]  = pp->curve.vertex[mod(j,m)];
      pp->ocurve.alpha[i]   = pp->curve.alpha[mod(j,m)];
      pp->ocurve.alpha0[i]  = pp->curve.alpha0[mod(j,m)];
      pp->ocurve.beta[i]    = pp->curve.beta[mod(j,m)];
      s[i] = t[i] = 1.0;
    } else {
      pp->ocurve.tag[i] = POTRACE_CURVETO;
      pp->ocurve.c[i][0] = opt[j].c[0];
      pp->ocurve.c[i][1] = opt[j].c[1];
      pp->ocurve.c[i][2] = pp->curve.c[mod(j,m)][2];
      pp->ocurve.vertex[i] = interval(opt[j].s, pp->curve.c[mod(j,m)][2], pp->curve.vertex[mod(j,m)]);
      pp->ocurve.alpha[i] = opt[j].alpha;
      pp->ocurve.alpha0[i] = opt[j].alpha;
      s[i] = opt[j].s;
      t[i] = opt[j].t;
    }
    j = pt[j];
  }

  /* calculate beta parameters */
  for (i=0; i<om; i++) {
    i1 = mod(i+1,om);
    pp->ocurve.beta[i] = s[i] / (s[i] + t[i1]);
  }
  pp->ocurve.alphacurve = 1;

  free(pt);
  free(pen);
  free(len);
  free(opt);
  free(s);
  free(t);
  free(convc);
  free(areac);
  return 0;

 malloc_error:
  free(pt);
  free(pen);
  free(len);
  free(opt);
  free(s);
  free(t);
  free(convc);
  free(areac);
  return 1;
}
Ejemplo n.º 18
0
    Status UpdateDriver::parse(const BSONObj& updateExpr, const bool multi) {
        clear();

        // Check if the update expression is a full object replacement.
        if (*updateExpr.firstElementFieldName() != '$') {
            if (multi) {
                return Status(ErrorCodes::FailedToParse,
                              "multi update only works with $ operators");
            }

            // Modifiers expect BSONElements as input. But the input to object replace is, by
            // definition, an object. We wrap the 'updateExpr' as the mod is expecting. Note
            // that the wrapper is temporary so the object replace mod should make a copy of
            // the object.
            auto_ptr<ModifierObjectReplace> mod(new ModifierObjectReplace);
            BSONObj wrapper = BSON( "dummy" << updateExpr );
            Status status = mod->init(wrapper.firstElement(), _modOptions);
            if (!status.isOK()) {
                return status;
            }

            _mods.push_back(mod.release());

            // Register the fact that this driver will only do full object replacements.
            _replacementMode = true;

            return Status::OK();
        }

        // The update expression is made of mod operators, that is
        // { <$mod>: {...}, <$mod>: {...}, ...  }
        BSONObjIterator outerIter(updateExpr);
        while (outerIter.more()) {
            BSONElement outerModElem = outerIter.next();

            // Check whether this is a valid mod type.
            modifiertable::ModifierType modType = modifiertable::getType(outerModElem.fieldName());
            if (modType == modifiertable::MOD_UNKNOWN) {
                return Status(ErrorCodes::FailedToParse,
                              str::stream() << "Unknown modifier: " << outerModElem.fieldName());
            }

            // Check whether there is indeed a list of mods under this modifier.
            if (outerModElem.type() != Object) {
                return Status(ErrorCodes::FailedToParse,
                              str::stream() << "Modifiers operate on fields but we found a "
                                            << typeName(outerModElem.type())
                                            << " instead. For example: {$mod: {<field>: ...}}"
                                            << " not {" << outerModElem.toString() << "}");
            }

            // Check whether there are indeed mods under this modifier.
            if (outerModElem.embeddedObject().isEmpty()) {
                return Status(ErrorCodes::FailedToParse,
                              str::stream() << "'" << outerModElem.fieldName()
                                            << "' is empty. You must specify a field like so: "
                                                    "{$mod: {<field>: ...}}");
            }

            BSONObjIterator innerIter(outerModElem.embeddedObject());
            while (innerIter.more()) {
                BSONElement innerModElem = innerIter.next();

                Status status = addAndParse(modType, innerModElem);
                if (!status.isOK()) {
                    return status;
                }
            }
        }

        // Register the fact that there will be only $mod's in this driver -- no object
        // replacement.
        _replacementMode = false;

        return Status::OK();
    }
Ejemplo n.º 19
0
Archivo: trace.cpp Proyecto: Tjuly/ME
/* find the optimal polygon. Fill in the m and po components. Return 1
   on failure with errno set, else 0. Non-cyclic version: assumes i=0
   is in the polygon. Fixme: implement cyclic version. */
static int bestpolygon(privpath_t *pp)
{
  int i, j, m, k;
  int n = pp->len;
  double *pen = NULL; /* pen[n+1]: penalty vector */
  int *prev = NULL;   /* prev[n+1]: best path pointer vector */
  int *clip0 = NULL;  /* clip0[n]: longest segment pointer, non-cyclic */
  int *clip1 = NULL;  /* clip1[n+1]: backwards segment pointer, non-cyclic */
  int *seg0 = NULL;    /* seg0[m+1]: forward segment bounds, m<=n */
  int *seg1 = NULL;   /* seg1[m+1]: backward segment bounds, m<=n */
  double thispen;
  double best;
  int c;

  SAFE_MALLOC(pen, n+1, double);
  SAFE_MALLOC(prev, n+1, int);
  SAFE_MALLOC(clip0, n, int);
  SAFE_MALLOC(clip1, n+1, int);
  SAFE_MALLOC(seg0, n+1, int);
  SAFE_MALLOC(seg1, n+1, int);

  /* calculate clipped paths */
  for (i=0; i<n; i++) {
    c = mod(pp->lon[mod(i-1,n)]-1,n);
    if (c == i) {
      c = mod(i+1,n);
    }
    if (c < i) {
      clip0[i] = n;
    } else {
      clip0[i] = c;
    }
  }

  /* calculate backwards path clipping, non-cyclic. j <= clip0[i] iff
     clip1[j] <= i, for i,j=0..n. */
  j = 1;
  for (i=0; i<n; i++) {
    while (j <= clip0[i]) {
      clip1[j] = i;
      j++;
    }
  }

  /* calculate seg0[j] = longest path from 0 with j segments */
  i = 0;
  for (j=0; i<n; j++) {
    seg0[j] = i;
    i = clip0[i];
  }
  seg0[j] = n;
  m = j;

  /* calculate seg1[j] = longest path to n with m-j segments */
  i = n;
  for (j=m; j>0; j--) {
    seg1[j] = i;
    i = clip1[i];
  }
  seg1[0] = 0;

  /* now find the shortest path with m segments, based on penalty3 */
  /* note: the outer 2 loops jointly have at most n iterations, thus
     the worst-case behavior here is quadratic. In practice, it is
     close to linear since the inner loop tends to be short. */
  pen[0]=0;
  for (j=1; j<=m; j++) {
    for (i=seg1[j]; i<=seg0[j]; i++) {
      best = -1;
      for (k=seg0[j-1]; k>=clip1[i]; k--) {
    thispen = penalty3(pp, k, i) + pen[k];
    if (best < 0 || thispen < best) {
      prev[i] = k;
      best = thispen;
    }
      }
      pen[i] = best;
    }
  }

  pp->m = m;
  SAFE_MALLOC(pp->po, m, int);

  /* read off shortest path */
  for (i=n, j=m-1; i>0; j--) {
    i = prev[i];
    pp->po[j] = i;
  }

  free(pen);
  free(prev);
  free(clip0);
  free(clip1);
  free(seg0);
  free(seg1);
  return 0;

 malloc_error:
  free(pen);
  free(prev);
  free(clip0);
  free(clip1);
  free(seg0);
  free(seg1);
  return 1;
}
Ejemplo n.º 20
0
void PV2D::nor() {
	scale(1.0/mod());
}
Ejemplo n.º 21
0
Archivo: trace.cpp Proyecto: Tjuly/ME
/* calculate best fit from i+.5 to j+.5.  Assume i<j (cyclically).
   Return 0 and set badness and parameters (alpha, beta), if
   possible. Return 1 if impossible. */
static int opti_penalty(privpath_t *pp, int i, int j, opti_t *res, double opttolerance, int *convc, double *areac) {
  int m = pp->curve.n;
  int k, k1, k2, conv, i1;
  double area, alpha, d, d1, d2;
  dpoint_t p0, p1, p2, p3, pt;
  double A, R, A1, A2, A3, A4;
  double s, t;

  /* check convexity, corner-freeness, and maximum bend < 179 degrees */

  if (i==j) {  /* sanity - a full loop can never be an opticurve */
    return 1;
  }

  k = i;
  i1 = mod(i+1, m);
  k1 = mod(k+1, m);
  conv = convc[k1];
  if (conv == 0) {
    return 1;
  }
  d = ddist(pp->curve.vertex[i], pp->curve.vertex[i1]);
  for (k=k1; k!=j; k=k1) {
    k1 = mod(k+1, m);
    k2 = mod(k+2, m);
    if (convc[k1] != conv) {
      return 1;
    }
    if (sign(cprod(pp->curve.vertex[i], pp->curve.vertex[i1], pp->curve.vertex[k1], pp->curve.vertex[k2])) != conv) {
      return 1;
    }
    if (iprod1(pp->curve.vertex[i], pp->curve.vertex[i1], pp->curve.vertex[k1], pp->curve.vertex[k2]) < d * ddist(pp->curve.vertex[k1], pp->curve.vertex[k2]) * COS179) {
      return 1;
    }
  }

  /* the curve we're working in: */
  p0 = pp->curve.c[mod(i,m)][2];
  p1 = pp->curve.vertex[mod(i+1,m)];
  p2 = pp->curve.vertex[mod(j,m)];
  p3 = pp->curve.c[mod(j,m)][2];

  /* determine its area */
  area = areac[j] - areac[i];
  area -= dpara(pp->curve.vertex[0], pp->curve.c[i][2], pp->curve.c[j][2])/2;
  if (i>=j) {
    area += areac[m];
  }

  /* find intersection o of p0p1 and p2p3. Let t,s such that o =
     interval(t,p0,p1) = interval(s,p3,p2). Let A be the area of the
     triangle (p0,o,p3). */

  A1 = dpara(p0, p1, p2);
  A2 = dpara(p0, p1, p3);
  A3 = dpara(p0, p2, p3);
  /* A4 = dpara(p1, p2, p3); */
  A4 = A1+A3-A2;

  if (A2 == A1) {  /* this should never happen */
    return 1;
  }

  t = A3/(A3-A4);
  s = A2/(A2-A1);
  A = A2 * t / 2.0;

  if (A == 0.0) {  /* this should never happen */
    return 1;
  }

  R = area / A;	 /* relative area */
  alpha = 2 - sqrt(4 - R / 0.3);  /* overall alpha for p0-o-p3 curve */

  res->c[0] = interval(t * alpha, p0, p1);
  res->c[1] = interval(s * alpha, p3, p2);
  res->alpha = alpha;
  res->t = t;
  res->s = s;

  p1 = res->c[0];
  p2 = res->c[1];  /* the proposed curve is now (p0,p1,p2,p3) */

  res->pen = 0;

  /* calculate penalty */
  /* check tangency with edges */
  for (k=mod(i+1,m); k!=j; k=k1) {
    k1 = mod(k+1,m);
    t = tangent(p0, p1, p2, p3, pp->curve.vertex[k], pp->curve.vertex[k1]);
    if (t<-.5) {
      return 1;
    }
    pt = bezier(t, p0, p1, p2, p3);
    d = ddist(pp->curve.vertex[k], pp->curve.vertex[k1]);
    if (d == 0.0) {  /* this should never happen */
      return 1;
    }
    d1 = dpara(pp->curve.vertex[k], pp->curve.vertex[k1], pt) / d;
    if (fabs(d1) > opttolerance) {
      return 1;
    }
    if (iprod(pp->curve.vertex[k], pp->curve.vertex[k1], pt) < 0 || iprod(pp->curve.vertex[k1], pp->curve.vertex[k], pt) < 0) {
      return 1;
    }
    res->pen += sq(d1);
  }

  /* check corners */
  for (k=i; k!=j; k=k1) {
    k1 = mod(k+1,m);
    t = tangent(p0, p1, p2, p3, pp->curve.c[k][2], pp->curve.c[k1][2]);
    if (t<-.5) {
      return 1;
    }
    pt = bezier(t, p0, p1, p2, p3);
    d = ddist(pp->curve.c[k][2], pp->curve.c[k1][2]);
    if (d == 0.0) {  /* this should never happen */
      return 1;
    }
    d1 = dpara(pp->curve.c[k][2], pp->curve.c[k1][2], pt) / d;
    d2 = dpara(pp->curve.c[k][2], pp->curve.c[k1][2], pp->curve.vertex[k1]) / d;
    d2 *= 0.75 * pp->curve.alpha[k1];
    if (d2 < 0) {
      d1 = -d1;
      d2 = -d2;
    }
    if (d1 < d2 - opttolerance) {
      return 1;
    }
    if (d1 < d2) {
      res->pen += sq(d1 - d2);
    }
  }

  return 0;
}
Ejemplo n.º 22
0
/*sectorlength tells how big this file must be in sectors*/
void writefile(char* name, char* buffer, int sectorlength)
{
	char dirsector[512];
	char mapsector[512];
	int i,j,k,index,sec,cyl,head;

	/*file sizes are limited to 25 sectors*/
	if (sectorlength>25)
		return;

	/*get directory and map*/
	readsector(dirsector,3,0,0);
	readsector(mapsector,2,0,0);

	/*find first available entry*/
	for (i=0; i<512; i=i+0x20)
	{
		if (dirsector[i]==0x00)
			break;
	}
	/*is directory full?*/
	if (i==512)
		return;

	/*copy name to directory, filling remainder with spaces*/
	for (j=0; j<6; j++)
		dirsector[i+j]=0x20;
	for (j=0; j<6; j++)
	{
		if (name[j]==0x00)
			break;
		dirsector[i+j]=name[j];
	}

	i=i+6;
	index=0;

	/*write the file*/
	for (j=0; j<sectorlength; j++)
	{
		/*find free sectors for file*/
		for (k=0; k<256; k++)
		{
			if (mapsector[k]==0)
				break;
		}
		if (k==256)
			break;
		/*set the map entry for the sector to "full"*/
		mapsector[k]=0x46;
		/*add that sector number to the file's dir entry*/
		dirsector[i]=(char)k;
		i++;
		
		/*compute CHS*/
		sec=mod(k,0x12)+1;
		head=mod(div(k,0x12),2);
		cyl=div(k,0x24);
		/*write a sector's worth to the disk*/
		writesector(buffer+index,sec,head,cyl);

		index=index+512;
		
	}
	/*set the next sector in the dir entry to 0.*/
	dirsector[i]=0;
	/*write back the map and directory*/
	writesector(mapsector,2,0,0);
	writesector(dirsector,3,0,0);
}
Ejemplo n.º 23
0
int main(int argc, char *argv[]) {
  llvm::cl::SetVersionPrinter(PrintVersion);
  llvm::cl::ParseCommandLineOptions(argc, argv, "CFG to LLVM");

  auto context = llvm::make_unique<llvm::LLVMContext>();

  if (OS.empty()) {
    if (ListSupported || ListUnsupported) {
      OS = "linux"; // just need something
    }
    else {
      std::cerr << "-os must be specified" << std::endl;
      return EXIT_FAILURE;
    }
  }

  if (!(ListSupported || ListUnsupported || ListCFGFunctions) && EntryPoints.empty()) {
    std::cerr
        << "-entrypoint must be specified" << std::endl;
        return EXIT_FAILURE;
  }

  if (!InitArch(context.get(), OS, Arch)) {
    std::cerr
        << "Cannot initialize for arch " << Arch
        << " and OS " << OS << std::endl;
    return EXIT_FAILURE;
  }

  auto M = CreateModule(context.get());
  if (!M) {
    return EXIT_FAILURE;
  }

  auto triple = M->getTargetTriple();

  if (ListSupported || ListUnsupported) {
    ListArchSupportedInstructions(triple, llvm::outs(), ListSupported, ListUnsupported);
    return EXIT_SUCCESS;
  }

  if (InputFilename.empty()) {
    std::cerr
        << "Must specify an input file." << std::endl;
    return EXIT_FAILURE;
  }

  //reproduce NativeModule from CFG input argument
  try {
    std::unique_ptr<NativeModule> mod(ReadProtoBuf(InputFilename));
    if (!mod) {
      std::cerr << "Unable to read module from CFG" << std::endl;
      return EXIT_FAILURE;
    }

    if (ListCFGFunctions) {
      PrintCFGFunctionList(mod.get(), Arch);
      return EXIT_SUCCESS;
    }

    //make sure the entry point list is correct before we start lifting the code
    const std::vector<NativeEntrySymbol> &module_entry_points = mod->getEntryPoints();

    for (const auto &entry_point : EntryPoints) {
      auto it = std::find_if(
        module_entry_points.begin(),
        module_entry_points.end(),

        [&entry_point](const NativeEntrySymbol &symbol) -> bool {
          return (symbol.getName() == entry_point);
        }
      );

      if (it == module_entry_points.end()) {
          std::cerr << "The following entry point could not be found: \"" << entry_point << "\". Aborting..." << std::endl;
          return EXIT_FAILURE;
      }
    }

    //now, convert it to an LLVM module
    ArchInitAttachDetach(M);

    if (!LiftCodeIntoModule(mod.get(), M)) {
      std::cerr << "Failure to convert to LLVM module!" << std::endl;
      return EXIT_FAILURE;
    }

    std::set<VA> entry_point_pcs;
    for (const auto &entry_point_name : EntryPoints) {
      auto entry_pc = FindSymbolInModule(mod.get(), entry_point_name);
      assert(entry_pc != static_cast<VA>( -1));

      std::cerr << "Adding entry point: " << entry_point_name << std::endl
                << entry_point_name << " is implemented by sub_" << std::hex
                << entry_pc << std::endl;

      if ( !ArchAddEntryPointDriver(M, entry_point_name, entry_pc)) {
        return EXIT_FAILURE;
      }

      entry_point_pcs.insert(entry_pc);
    }

    RenameLiftedFunctions(mod.get(), M, entry_point_pcs);

    // will abort if verification fails
    if (llvm::verifyModule( *M, &llvm::errs())) {
      std::cerr << "Could not verify module!" << std::endl;
      return EXIT_FAILURE;
    }

    std::error_code ec;
    llvm::tool_output_file Out(OutputFilename.c_str(), ec,
                               llvm::sys::fs::F_None);
    llvm::WriteBitcodeToFile(M, Out.os());
    Out.keep();

  } catch (std::exception &e) {
    std::cerr << "error: " << std::endl << e.what() << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
Ejemplo n.º 24
0
Archivo: main.cpp Proyecto: 2asoft/0ad
// moved into a helper function to ensure args is destroyed before
// exit(), which may result in a memory leak.
static void RunGameOrAtlas(int argc, const char* argv[])
{
	CmdLineArgs args(argc, argv);

	g_args = args;

	if (args.Has("version") || args.Has("-version"))
	{
		debug_printf("Pyrogenesis %s\n", engine_version);
		return;
	}

	const bool isVisualReplay = args.Has("replay-visual");
	const bool isNonVisualReplay = args.Has("replay");

	const CStr replayFile =
		isVisualReplay ? args.Get("replay-visual") :
		isNonVisualReplay ? args.Get("replay") : "";

	if (isVisualReplay || isNonVisualReplay)
	{
		if (!FileExists(OsPath(replayFile)))
		{
			debug_printf("ERROR: The requested replay file '%s' does not exist!\n", replayFile.c_str());
			return;
		}
		if (DirectoryExists(OsPath(replayFile)))
		{
			debug_printf("ERROR: The requested replay file '%s' is a directory!\n", replayFile.c_str());
			return;
		}
	}

	// We need to initialize SpiderMonkey and libxml2 in the main thread before
	// any thread uses them. So initialize them here before we might run Atlas.
	ScriptEngine scriptEngine;
	CXeromyces::Startup();

	if (ATLAS_RunIfOnCmdLine(args, false))
	{
		CXeromyces::Terminate();
		return;
	}

	if (isNonVisualReplay)
	{
		if (!args.Has("mod"))
		{
			LOGERROR("At least one mod should be specified! Did you mean to add the argument '-mod=public'?");
			CXeromyces::Terminate();
			return;
		}

		Paths paths(args);
		g_VFS = CreateVfs(20 * MiB);
		g_VFS->Mount(L"cache/", paths.Cache(), VFS_MOUNT_ARCHIVABLE);
		MountMods(paths, GetMods(args, INIT_MODS));

		{
			CReplayPlayer replay;
			replay.Load(replayFile);
			replay.Replay(
				args.Has("serializationtest"),
				args.Has("rejointest") ? args.Get("rejointest").ToInt() : -1,
				args.Has("ooslog"));
		}

		g_VFS.reset();

		CXeromyces::Terminate();
		return;
	}

	// run in archive-building mode if requested
	if (args.Has("archivebuild"))
	{
		Paths paths(args);

		OsPath mod(args.Get("archivebuild"));
		OsPath zip;
		if (args.Has("archivebuild-output"))
			zip = args.Get("archivebuild-output");
		else
			zip = mod.Filename().ChangeExtension(L".zip");

		CArchiveBuilder builder(mod, paths.Cache());

		// Add mods provided on the command line
		// NOTE: We do not handle mods in the user mod path here
		std::vector<CStr> mods = args.GetMultiple("mod");
		for (size_t i = 0; i < mods.size(); ++i)
			builder.AddBaseMod(paths.RData()/"mods"/mods[i]);

		builder.Build(zip, args.Has("archivebuild-compress"));

		CXeromyces::Terminate();
		return;
	}

	const double res = timer_Resolution();
	g_frequencyFilter = CreateFrequencyFilter(res, 30.0);

	// run the game
	int flags = INIT_MODS;
	do
	{
		restart = false;
		quit = false;
		if (!Init(args, flags))
		{
			flags &= ~INIT_MODS;
			Shutdown(SHUTDOWN_FROM_CONFIG);
			continue;
		}
		InitGraphics(args, 0);
		MainControllerInit();
		while (!quit)
			Frame();
		Shutdown(0);
		MainControllerShutdown();
		flags &= ~INIT_MODS;
	} while (restart);

	if (restart_in_atlas)
		ATLAS_RunIfOnCmdLine(args, true);

	CXeromyces::Terminate();
}
Ejemplo n.º 25
0
static void
yscan(Memimage *dst, Seg **seg, Seg *segtab, int nseg, int wind, Memimage *src, Point sp, int fixshift, int op)
{
	int32_t x, maxx, y, y2, yerr, yden, onehalf;
	Seg **ep, **next, **p, **q, *s;
	int n, i, ix, cnt, iy, iy2, miny, maxy;
	Point pt;

	for(i=0, s=segtab, p=seg; i<nseg; i++, s++) {
		*p = s;
		if(s->p0.x == s->p1.x)
			continue;
		if(s->p0.x > s->p1.x) {
			pt = s->p0;
			s->p0 = s->p1;
			s->p1 = pt;
			s->d = -s->d;
		}
		s->num = s->p1.y - s->p0.y;
		s->den = s->p1.x - s->p0.x;
		s->dz = sdiv(s->num, s->den) << fixshift;
		s->dzrem = mod(s->num, s->den) << fixshift;
		s->dz += sdiv(s->dzrem, s->den);
		s->dzrem = mod(s->dzrem, s->den);
		p++;
	}
	n = p-seg;
	if(n == 0)
		return;
	*p = 0;
	qsort(seg, n , sizeof(Seg*), xcompare);

	onehalf = 0;
	if(fixshift)
		onehalf = 1 << (fixshift-1);

	miny = dst->clipr.min.y;
	maxy = dst->clipr.max.y;

	x = seg[0]->p0.x;
	if(x < (dst->clipr.min.x << fixshift))
		x = dst->clipr.min.x << fixshift;
	ix = (x + onehalf) >> fixshift;
	x = (ix << fixshift) + onehalf;
	maxx = dst->clipr.max.x << fixshift;

	ep = next = seg;

	while(x<maxx) {
		for(q = p = seg; p < ep; p++) {
			s = *p;
			if(s->p1.x < x)
				continue;
			s->z += s->dz;
			s->zerr += s->dzrem;
			if(s->zerr >= s->den) {
				s->z++;
				s->zerr -= s->den;
				if(s->zerr < 0 || s->zerr >= s->den)
					print("bad ratzerr1: %ld den %ld ratdzrem %ld\n", s->zerr, s->den, s->dzrem);
			}
			*q++ = s;
		}

		for(p = next; *p; p++) {
			s = *p;
			if(s->p0.x >= x)
				break;
			if(s->p1.x < x)
				continue;
			s->z = s->p0.y;
			s->z += smuldivmod(x - s->p0.x, s->num, s->den, &s->zerr);
			if(s->zerr < 0 || s->zerr >= s->den)
				print("bad ratzerr2: %ld den %ld ratdzrem %ld\n", s->zerr, s->den, s->dzrem);
			*q++ = s;
		}
		ep = q;
		next = p;

		if(ep == seg) {
			if(*next == 0)
				break;
			ix = (next[0]->p0.x + onehalf) >> fixshift;
			x = (ix << fixshift) + onehalf;
			continue;
		}

		zsort(seg, ep);

		for(p = seg; p < ep; p++) {
			cnt = 0;
			y = p[0]->z;
			yerr = p[0]->zerr;
			yden = p[0]->den;
			iy = (y + onehalf) >> fixshift;
			if(iy >= maxy)
				break;
			if(iy < miny)
				iy = miny;
			cnt += p[0]->d;
			p++;
			for(;;) {
				if(p == ep) {
					print("yscan: fill to infinity");
					return;
				}
				cnt += p[0]->d;
				if((cnt&wind) == 0)
					break;
				p++;
			}
			y2 = p[0]->z;
			iy2 = (y2 + onehalf) >> fixshift;
			if(iy2 <= miny)
				continue;
			if(iy2 > maxy)
				iy2 = maxy;
			if(iy == iy2) {
				if(yerr*p[0]->den + p[0]->zerr*yden > p[0]->den*yden)
					y++;
				iy = (y + y2) >> (fixshift+1);
				fillpoint(dst, ix, iy, src, sp, op);
			}
		}
		x += (1<<fixshift);
		ix++;
	}
}
Ejemplo n.º 26
0
int main(){
	int a,b;
	while(scanf("%d%d",&a,&b)!=EOF)
		printf("%d\n",mod(a,b));
	return 0;
}
Ejemplo n.º 27
0
static void prevFighter(void)
{
	page = mod(page - 1, maxPages);
	
	setNumDestroyed();
}
Ejemplo n.º 28
0
void LoadProbes(bool isRerun) {
    #define mod(a,b) a = fmod(fmod(a,b)+b,b)
    mod(gPosition.x,GLH_SIZEX);
    mod(gPosition.y,GLH_SIZEY);
    mod(gPosition.z,GLH_SIZEZ);
    
    if (!gGodMode) {
        gh.MapOffset = gPosition;
    }
    
    Vec3f gv; //Goal direction.
    Vec3f d = {0, 0, 0};

    if (!isRerun) {
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::T)) {
            //reset full map.
            gh.TMap->DefaultIt();
            gh.TMap->RecalculateAccelerationStructure(0, 0, 0, GLH_SIZEX, GLH_SIZEY, GLH_SIZEZ);
            gh.TMap->m_bReloadFullTexture = true;

        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) d.x -= 1.;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) d.x += 1.;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) d.y += 1.;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) d.y -= 1.;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::RBracket)) d.z += 1.;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::LBracket)) d.z -= 1.;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && gTimeSinceOnGround < 0.1) gh.v.z = 10; // && gh.gTimeSinceOnGround < 0.1
        gTimeSinceOnGround += worldDeltaTime;

        /*
                float ny = dx * sin( -Yaw/180.*3.14159 ) + dy * cos( -Yaw/180.*3.14159 );
                float nx = dx * cos( -Yaw/180.*3.14159 ) - dy * sin( -Yaw/180.*3.14159 );
                Roll = Roll * .95; //auto-righting.
         */
    }

    Vec3f ForwardVec = LookQuaternion * Vec3f{0, 0, -1};
    ForwardVec.z = -ForwardVec.z; //??? WHY? WHY WHY??? Is LookQuaternion busted???
    Vec3f MoveVec = LookQuaternion * Vec3f{d.x, 0, d.y};
    float nx = MoveVec.x;
    float ny = MoveVec.y;

    //	printf( "%f %f %f\n", fwdx, fwdy, fwdz );

    if (gGodMode) {
        gh.v = {nx * 4.f, ny * 4.f, d.z * 4.f};
        gh.MapOffset += gh.v*worldDeltaTime;
    } else {
        if (!isRerun) {
            float xymag = sqrt(nx * nx + ny * ny);
            if (xymag > .001) {
                nx /= xymag;
                ny /= xymag;
            }

            gh.v.x = nx * 4.;
            gh.v.y = ny * 4.;
            gh.v.z -= worldDeltaTime * 16.; //gravity
            gh.v.z *= .995; //terminal velocity
        }
    }


    if (!isRerun) {
        if(worldDeltaTime != 0) gv = gh.v*worldDeltaTime;
        else gv = {1e-10,1e-10,1e-10}; //TODO fix crash when gv == 0,0,0
    } else {
        printf("GVRerun\n");
    }
    //Spew out a boatload of rays, trying to intersect things.

    int i, j;
    const int stacks = 6;
    for (i = 0; i < stacks * 2; i++) {
        //Stack goes: 1 2 3 4 5 4 3 2 1, i goes 012345678
        int stack = i;
        if (i >= stacks) stack = stacks * 2 - stack - 1;

        //Stack is the number of radial rays.
        float sigma = (i / ((float) stacks * 2 - 1)* 3.14159);
        d.z = cos(sigma);
        float mz = sin(sigma);
        stack++;
        for (j = 0; j < stack; j++) {
            float theta = (j / (float) stack) * 3.14159 * 2.0;
            d.x = mz * cos(theta);
            d.y = mz * sin(theta);
            CollisionProbe * p;
            probes.push_back(p = gh.AddProbe());
            p->Position = gh.MapOffset;
            p->Direction = RGBAf(d + gv, 10000);
        }
    }


    {
        gpTest = gh.AddProbe();
        gpTest->Position = gh.MapOffset;
        gpTest->Direction = RGBAf(gv, gv.len());

        gpTestVelocity = gh.AddProbe();
        gpTestVelocity->Position = gh.MapOffset;
        gpTestVelocity->Direction = RGBAf(gv, gv.len());
        gpTestVelocity->AuxRotation = gh.v;

    }


    gpForward = gh.AddProbe();
    gpForward->Position = gh.MapOffset;
    gpForward->Direction = RGBAf(ForwardVec, 10000);


    //	Yaw
    //	Pitch
    //	Roll
    //???


    Vec3f FrontRot = LookQuaternion * Vec3f{1, 0, 0};
    Vec3f UpRot = LookQuaternion * Vec3f{0, 1, 0};

    //	FrontRot[1] *= -1;
    //	FrontRot[0] *= -1;
    //	FrontRot[2] *= -1;
    //	UpRot[2] *= -1;

    gpRotFwd = gh.AddProbe();
    gpRotFwd->Position = gh.MapOffset;
    gpRotFwd->Direction = RGBAf(gv, gv.len());
    gpRotFwd->AuxRotation = FrontRot;

    gpRotUp = gh.AddProbe();
    gpRotUp->Position = gh.MapOffset;
    gpRotUp->Direction = RGBAf(gv, gv.len());
    gpRotUp->AuxRotation = UpRot;


}
void SharedTangibleObjectTemplate::parseVariableData(const String& varName, LuaObject* data) {
	lua_State* state = data->getLuaState();
	TemplateManager* templateManager = TemplateManager::instance();

	if (varName == "certificationsRequired") {
		LuaObject certifications(state);
		certificationsRequired.removeAll();
		for (int i = 1; i <= certifications.getTableSize(); ++i) {
			certificationsRequired.add(certifications.getStringAt(i));
		}

		certifications.pop();
	} else if (varName == "structureFootprintFileName") {
		structureFootprint = templateManager->loadStructureFootprint(Lua::getStringParameter(state));
	} else if (varName == "targetable") {
		targetable = Lua::getByteParameter(state);
	} else if (varName == "playerUseMask") {
		playerUseMask = Lua::getShortParameter(state);
	} else if (varName == "useCount") {
		useCount = Lua::getIntParameter(state);
	} else if (varName == "factoryCrateSize") {
		factoryCrateSize = Lua::getIntParameter(state);
	} else if (varName == "maxCondition") {
		maxCondition = Lua::getIntParameter(state);
	} else if (varName == "level") {
		level = Lua::getIntParameter(state);
	} else if (varName == "optionsBitmask") {
		optionsBitmask = Lua::getIntParameter(state);
	} else if (varName == "pvpStatusBitmask") {
		pvpStatusBitmask = Lua::getIntParameter(state);
	} else if (varName == "sliceable") {
		sliceable = Lua::getIntParameter(state);
	} else if (varName == "faction") {
		String factionString = Lua::getStringParameter(state);
		faction = factionString.toLowerCase().hashCode();
	} else if (varName == "playerRaces") {
		LuaObject races(state);

		// Inherited lists need to be tossed if a new list is about to be created
		if (playerRaces->size() != 0) {
			playerRaces->removeAll();
		}

		for (int i = 1; i <= races.getTableSize(); ++i) {
			String race = races.getStringAt(i);

			if (!playerRaces->contains(race.hashCode())) {
				playerRaces->add(race.hashCode());
			}


		}

		races.pop();
	} else if (varName == "skillMods") {
		skillMods.removeAll();

		LuaObject smods(state);
		for (int i = 1; i <= smods.getTableSize(); ++i) {
			lua_rawgeti(state, -1, i);
			LuaObject mod(state);

			String modName = mod.getStringAt(1);
			int modValue = mod.getIntAt(2);

			skillMods.put(modName, modValue);

			mod.pop();
		}
		smods.pop();
	} else if (varName == "numberExperimentalProperties") {
		LuaObject numberExperimentalPropertiesList(state);
		numberExperimentalProperties->removeAll();
		for (int i = 1; i <= numberExperimentalPropertiesList.getTableSize(); ++i) {
			numberExperimentalProperties->add(numberExperimentalPropertiesList.getIntAt(i));
		}

		numberExperimentalPropertiesList.pop();
	} else if (varName == "experimentalProperties") {
		LuaObject experimentalPropertiesList(state);
		experimentalProperties->removeAll();
		for (int i = 1; i <= experimentalPropertiesList.getTableSize(); ++i) {
			experimentalProperties->add(experimentalPropertiesList.getStringAt(i));
		}

		experimentalPropertiesList.pop();
	} else if (varName == "experimentalWeights") {
		LuaObject experimentalWeightsList(state);
		experimentalWeights->removeAll();
		for (int i = 1; i <= experimentalWeightsList.getTableSize(); ++i) {
			experimentalWeights->add(experimentalWeightsList.getIntAt(i));
		}

		experimentalWeightsList.pop();
	} else if (varName == "experimentalGroupTitles") {
		LuaObject experimentalGroupTitlesList(state);
		experimentalGroupTitles->removeAll();
		for (int i = 1; i <= experimentalGroupTitlesList.getTableSize(); ++i) {
			experimentalGroupTitles->add(experimentalGroupTitlesList.getStringAt(i));
		}

		experimentalGroupTitlesList.pop();
	} else if (varName == "experimentalSubGroupTitles") {
		LuaObject experimentalSubGroupTitlesList(state);
		experimentalSubGroupTitles->removeAll();
		for (int i = 1; i <= experimentalSubGroupTitlesList.getTableSize(); ++i) {
			experimentalSubGroupTitles->add(experimentalSubGroupTitlesList.getStringAt(i));
		}

		experimentalSubGroupTitlesList.pop();
	} else if (varName == "experimentalMin") {
		LuaObject experimentalMinList(state);
		experimentalMin->removeAll();
		for (int i = 1; i <= experimentalMinList.getTableSize(); ++i) {
			experimentalMin->add(experimentalMinList.getFloatAt(i));
		}

		experimentalMinList.pop();
	} else if (varName == "experimentalMax") {
		LuaObject experimentalMaxList(state);
		experimentalMax->removeAll();
		for (int i = 1; i <= experimentalMaxList.getTableSize(); ++i) {
			experimentalMax->add(experimentalMaxList.getFloatAt(i));
		}

		experimentalMaxList.pop();
	} else if (varName == "experimentalPrecision") {
		LuaObject experimentalPrecisionList(state);
		experimentalPrecision->removeAll();
		for (int i = 1; i <= experimentalPrecisionList.getTableSize(); ++i) {
			experimentalPrecision->add(experimentalPrecisionList.getIntAt(i));
		}
		experimentalPrecisionList.pop();
	} else if (varName == "experimentalCombineType") {
		LuaObject experimentalCombineList(state);
		experimentalCombineType->removeAll();
		for (int i = 1; i <= experimentalCombineList.getTableSize(); ++i) {
			experimentalCombineType->add(experimentalCombineList.getIntAt(i));
		}
		experimentalCombineList.pop();
	} else {
		data->pop();
	}

}
Ejemplo n.º 30
0
Float* Float::mod(STATE, Integer* other) {
    return mod(state, Float::coerce(state, other));
}