Esempio n. 1
0
  Object* Proc::call(STATE, CallFrame* call_frame, Arguments& args) {
    bool lambda_style = RTEST(lambda_);
    int flags = 0;

    // Check the arity in lambda mode
    if(lambda_style) {
      flags = CallFrame::cIsLambda;
      int total = block_->code()->total_args()->to_native();
      int required = block_->code()->required_args()->to_native();

      bool arity_ok = false;
      if(Fixnum* fix = try_as<Fixnum>(block_->code()->splat())) {
        switch(fix->to_native()) {
        case -2:
          arity_ok = true;
          break;
        case -4:
          // splat = -4 means { |(a, b)| }
          if(args.total() == 1) {
            Array* ary = 0;
            Object* obj = args.get_argument(0);

            if(!(ary = try_as<Array>(obj))) {
              if(RTEST(obj->respond_to(state, state->symbol("to_ary"), Qfalse))) {
                obj = obj->send(state, call_frame, state->symbol("to_ary"));
                if(!(ary = try_as<Array>(obj))) {
                  Exception::type_error(state, "to_ary must return an Array", call_frame);
                  return 0;
                }
              }
            }

            if(ary) args.use_argument(ary);
          }
          // fall through for arity check
        case -3:
          // splat = -3 is used to distinguish { |a, | } from { |a| }
          if(args.total() == (size_t)required) arity_ok = true;
          break;
        default:
          if(args.total() >= (size_t)required) {
            arity_ok = true;
          }
        }

      /* For blocks taking one argument { |a|  }, in 1.8, there is a warning
       * issued but no exception raised when less than or more than one
       * argument is passed. If more than one is passed, 'a' receives an Array
       * of all the arguments.
       */
      } else if(required == 1 && LANGUAGE_18_ENABLED(state)) {
        arity_ok = true;
      } else {
        arity_ok = args.total() <= (size_t)total &&
                   args.total() >= (size_t)required;
      }

      if(!arity_ok) {
        Exception* exc =
          Exception::make_argument_error(state, required, args.total(),
              state->symbol("__block__"));
        exc->locations(state, Location::from_call_stack(state, call_frame));
        state->thread_state()->raise_exception(exc);
        return NULL;
      }
    }

    Object* ret;
    if(bound_method_->nil_p()) {
      ret = block_->call(state, call_frame, args, flags);
    } else if(NativeMethod* nm = try_as<NativeMethod>(bound_method_)) {
      ret = nm->execute(state, call_frame, nm, G(object), args);
    } else {
      Dispatch dis(state->symbol("__yield__"));
      ret = dis.send(state, call_frame, args);
    }

    return ret;
  }
Esempio n. 2
0
int Trajectory(double* X1, double* X2, double* Phi1, double* Phi2, double* K, int numProcs, int myID)
{
    double* Eta = new double[TOT];
    double* P = new double[TOT];
    double* F = new double[TOT];
    double* temK = new double[TOT];
    double* temBuf = new double[TOT];
    double t = sqrt(0.5);
    int flag;
    MPI_Generate(Eta, t, numProcs, myID);
    M(Eta, Phi1, K, numProcs, myID);
    MPI_Generate(Eta, t, numProcs, myID);
    M(Eta, Phi2, K, numProcs, myID);
    MPI_Setzero(X1, numProcs, myID);
    MPI_Setzero(X2, numProcs, myID);
    MPI_Generate(P, 1.0, numProcs, myID);
    MPI_Assign(K, temK, numProcs, myID);
    double hamStart = Hamiltonian(X1, X2, Phi1, Phi2, P, K, numProcs, myID);
    flag = FermionForce(X1, X2, Phi1, Phi2, F, K, numProcs, myID);
    if(!flag)
    {
        MPI_Assign(temK, K, numProcs, myID);
        return 0;
    }
    MPI_Multiply(F, 0.5*dt, temBuf, numProcs, myID);
    MPI_Add(P, temBuf, P, numProcs, myID);
    for(int i = 0; i<(N_md-1); i++)
    {
        MPI_Multiply(P, dt, temBuf, numProcs, myID);
        MPI_Add(K, temBuf, K, numProcs, myID);
        flag = FermionForce(X1, X2, Phi1, Phi2, F, K, numProcs, myID);
        if(!flag)
        {
            MPI_Assign(temK, K, numProcs, myID);
            return 0;
        }
        MPI_Multiply(F, dt, temBuf, numProcs, myID);
        MPI_Add(P, temBuf, P, numProcs, myID);
    }
    MPI_Multiply(P, dt, temBuf, numProcs, myID);
    MPI_Add(K, temBuf, K, numProcs, myID);
    flag = FermionForce(X1, X2, Phi1, Phi2, F, K, numProcs, myID);
    if(!flag)
    {
        MPI_Assign(temK, K, numProcs, myID);
        return 0;
    }
    MPI_Multiply(F, 0.5*dt, temBuf, numProcs, myID);
    MPI_Add(P, temBuf, P, numProcs, myID);
    double hamEnd = Hamiltonian(X1, X2, Phi1, Phi2, P, K, numProcs, myID);
    double r = 0.0;
    if(myID == ROOT)
    {
        random_device rd;
        mt19937 generator(rd());
        uniform_real_distribution<double> dis(0.0, 1.0);
        r = dis(generator);
    }
    MPI_Bcast(&r, 1, MPI_DOUBLE, ROOT, MPI_COMM_WORLD);
    double s = exp(hamStart-hamEnd);
    if(myID == ROOT)
    {
        ofstream file_log("evolution.log", ios_base::app);
        file_log<<"Hamiltoian: "<<hamStart<<" "<<hamEnd<<" "<<r<<" "<<s<<endl;
        file_log.close();
    }
    delete [] Eta;
    delete [] P;
    delete [] F;
    delete [] temK;
    delete [] temBuf;
    if(r<s)
    {
        return 1;
    }
    else
    {
        MPI_Assign(temK, K, numProcs, myID);
        return 0;
    }
}
Esempio n. 3
0
node_bfs* bfs(nodetype *vertex,int p){
int search,count1=0,l=1,a[100],t=1,count=0,i;
nodetype *s;
node_bfs *head,*m,*tmp,*y;
node *k;
head=NULL;
printf("The starting vertex\n");
scanf("%d",&search);
a[0]=search;
for(i=0;i<p;i++){
s=vertex;
while(search!=s->edge){
s=s->next;
}
//printf("%d\n",s->edge);
if(head==NULL){
head=getnode_bfs(head);
head->level=0;
head->gave_level=-1;
head->edge_value=s->edge;
m=head;
y=head;
}
//printf("%d\n",s->edge);
k=s->adj_edge;
//printf("%d\n",k->value);
while(k!=NULL){
//printf("%d\n",k->value);
while(y!=NULL){
//printf("%d ",y->edge_value);
if(k->value==y->edge_value){
count1++;
}
//printf("%d ",count1);
y=y->front;
}
y=head;
//printf("%d\n",count1);
if(count1==0){
tmp=getnode_bfs(tmp);
tmp->gave_level=s->edge;
a[l++]=k->value;
//printf("%d ",a[l-1]);
while(s->edge!=y->edge_value){
//printf("%d",y->edge_value);
y=y->front;
}
//printf("\n");
tmp->edge_value=k->value;
tmp->level=y->level+1;
m->front=tmp;
m=m->front;
}
y=head;
k=k->next_adj_edge;
//count++;
}
//printf("\n");
search=a[t++];
count1=0;
//dis(head);
//printf("%d\n",search);
}
dis(head);
}
Esempio n. 4
0
	int math::random_range(int min, int max)
	{ 
		std::uniform_int_distribution<> dis(min, max);
		return dis(gen);
	}
Esempio n. 5
0
APPROXMVBB_EXPORT void samplePointsGrid(Matrix3Dyn & newPoints,
                      const MatrixBase<Derived> & points,
                      const unsigned int nPoints,
                      OOBB & oobb) {


    if(nPoints >= points.cols() || nPoints < 2) {
        ApproxMVBB_ERRORMSG("Wrong arguements!")
    }

    newPoints.resize(3,nPoints);

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<unsigned int> dis(0, points.cols()-1);

    //total points = bottomPoints=gridSize^2  + topPoints=gridSize^2
    unsigned int gridSize = std::max( static_cast<unsigned int>( std::sqrt( static_cast<double>(nPoints) / 2.0 )) , 1U );

    // Set z-Axis to longest dimension
    //std::cout << oobb.m_minPoint.transpose() << std::endl;
    oobb.setZAxisLongest();

    unsigned int halfSampleSize = gridSize*gridSize;
    std::vector< std::pair<unsigned int , PREC > > topPoints(halfSampleSize,    std::pair<unsigned int,PREC>{} );    // grid of indices of the top points (indexed from 1 )
    std::vector< std::pair<unsigned int , PREC > > bottomPoints(halfSampleSize, std::pair<unsigned int,PREC>{} ); // grid of indices of the bottom points (indexed from 1 )

    using LongInt = long long int;
    MyMatrix<LongInt>::Array2 idx; // Normalized P
    //std::cout << oobb.extent() << std::endl;
    //std::cout << oobb.m_minPoint.transpose() << std::endl;
    Array2 dxdyInv =  Array2(gridSize,gridSize) / oobb.extent().head<2>(); // in K Frame;
    Vector3 K_p;

    Matrix33 A_KI(oobb.m_q_KI.matrix().transpose());

    // Register points in grid
    auto size = points.cols();
    for(unsigned int i=0; i<size; ++i) {

        K_p = A_KI * points.col(i);
        // get x index in grid
        idx = (  (K_p - oobb.m_minPoint).head<2>().array() * dxdyInv ).template cast<LongInt>();
        // map to grid
        idx(0) = std::max(   std::min( LongInt(gridSize-1), idx(0)),  0LL   );
        idx(1) = std::max(   std::min( LongInt(gridSize-1), idx(1)),  0LL   );
        //std::cout << idx.transpose() << std::endl;
        unsigned int pos = idx(0) + idx(1)*gridSize;

        // Register points in grid
        // if z axis of p is > topPoints[pos]  -> set new top point at pos
        // if z axis of p is < bottom[pos]     -> set new bottom point at pos

        if( topPoints[pos].first == 0) {
            topPoints[pos].first  = bottomPoints[pos].first  = i+1;
            topPoints[pos].second = bottomPoints[pos].second = K_p(2);
        } else {
            if( topPoints[pos].second < K_p(2) ) {
                topPoints[pos].first = i+1;
                topPoints[pos].second = K_p(2);
            }
            if( bottomPoints[pos].second > K_p(2) ) {
                bottomPoints[pos].first = i+1;
                bottomPoints[pos].second = K_p(2);
            }
        }
    }

    // Copy top and bottom points
    unsigned int k=0;

    // k does not overflow -> 2* halfSampleSize = 2*gridSize*gridSize <= nPoints;
    for(unsigned int i=0; i<halfSampleSize; ++i) {
        if( topPoints[i].first != 0 ) {
            // comment in if you want the points top points of the grid
//            Array3 a(i % gridSize,i/gridSize,oobb.m_maxPoint(2)-oobb.m_minPoint(2));
//            a.head<2>()*=dxdyInv.inverse();
            newPoints.col(k++) =  points.col(topPoints[i].first-1);  //  A_KI.transpose()*(oobb.m_minPoint + a.matrix()).eval() ;
            if(topPoints[i].first != bottomPoints[i].first) {
                // comment in if you want the bottom points of the grid
//                Array3 a(i % gridSize,i/gridSize,0);
//                a.head<2>()*=dxdyInv.inverse();
                newPoints.col(k++) = points.col(bottomPoints[i].first-1); //  A_KI.transpose()*(oobb.m_minPoint + a.matrix()).eval() ;
            }
        }
    }
    // Add random points!
    while( k < nPoints) {
        newPoints.col(k++) = points.col( dis(gen) ); //= Vector3(0,0,0);//
    }
}
Esempio n. 6
0
inline bool contain(const circle &a, const circle &b) {
	return a.radius > dis(a.center, b.center) + b.radius - EPS;
}
Esempio n. 7
0
bool cmp(const point &a,const point &b)
{
    if(fabs(det(p[0],a,b))<eps)
        return dis(p[0],a)<dis(p[0],b);
    return det(p[0],a,b)>0;
}
Esempio n. 8
0
void generator(double a, double b, double& num){
	std::random_device rd;
	std::mt19937 gen(rd());
	std::uniform_real_distribution<> dis(a, b);
	num = dis(gen);
}
Esempio n. 9
0
int main(int argc, char** argv) {
	CommandServer cs(1);
	cs.init();

	CommonNet dis(1);
	dis.init_server(100);

	PROCESS_INFORMATION pi = {0};
	STARTUPINFO si = {0};
	si.cb = sizeof(si);

	HANDLE hnd = GetCurrentProcess();

	printf("Listening\nhandle %d\n", hnd);

	LPSECURITY_ATTRIBUTES lp_attributes;
	LPSECURITY_ATTRIBUTES lpThreadAttributes;
	STARTUPINFO startupInfo = {sizeof(startupInfo)};
	memset(&startupInfo,0,sizeof(STARTUPINFO));
	startupInfo.cb = sizeof(STARTUPINFO);
	startupInfo.dwFlags=0;
	startupInfo.wShowWindow = SW_HIDE;

	PROCESS_INFORMATION processInformation;
	char cmdLine[100];
	string AppName;
	int recv_len = 0;
	char RecvB[100];

	if(argc == 2 || argc == 3) {
		//启动游戏进程
		DWORD id = GetCurrentProcessId();

		int dump_mesh = 0;
		if(argc == 3) dump_mesh = 1;

		sprintf(cmdLine,"%s %d %d %d %d",argv[1], dump_mesh, -1,-1, id);
		printf("cmd line is %s\n", cmdLine);

		bool ret = DetourCreateProcessWithDll(NULL,cmdLine, NULL, NULL, TRUE, CREATE_DEFAULT_ERROR_MODE,
			NULL, NULL, &si, &pi, "game_server.dll", NULL);

		if(!ret) {
			char err_str[200];
			sprintf(err_str, "Game Start %s Failed", AppName.c_str());
			MessageBox(NULL, err_str, "Error", MB_OK);
		}

		return 0;
	}

	while(true) {
		cs.accept_client();
		printf("client has come with connect socket:%d\n", cs.get_connect_socket());

		dis.AcceptClient(1);
		printf("input client connect to socket:%d\n", dis.get_connect_socket());
		
		cs.recv_raw_buffer(AppName, recv_len);
		if(recv_len <= 0) {
			printf("recv error\n");
			break;
		}
		printf("Appname: %s\n", AppName.c_str());


		//启动游戏进程
		DWORD id = GetCurrentProcessId();
		sprintf(cmdLine,"%s %d %d %d %d",AppName.c_str(), 0, cs.get_connect_socket(), dis.get_connect_socket(), id);
		printf("cmd line is %s\n", cmdLine);
		bool ret = DetourCreateProcessWithDll(NULL,cmdLine, NULL, NULL, TRUE, CREATE_DEFAULT_ERROR_MODE,
			NULL, NULL, &si, &pi, "game_server.dll", NULL);

		if(!ret) {
			char err_str[200];
			sprintf(err_str, "Game Start %s Failed", AppName.c_str());
			MessageBox(NULL, err_str, "Error", MB_OK);
		}
	}

	return 0;
}
Esempio n. 10
0
std::pair<float,float> evaluate_fib(
        const image::geometry<3>& dim,
        const std::vector<std::vector<float> >& fib_fa,
        const std::vector<std::vector<float> >& fib_dir)
{
    unsigned char num_fib = fib_fa.size();
    char dx[13] = {1,0,0,1,1,0, 1, 1, 0, 1,-1, 1, 1};
    char dy[13] = {0,1,0,1,0,1,-1, 0, 1, 1, 1,-1, 1};
    char dz[13] = {0,0,1,0,1,1, 0,-1,-1, 1, 1, 1,-1};
    std::vector<image::vector<3> > dis(13);
    for(unsigned int i = 0;i < 13;++i)
    {
        dis[i] = image::vector<3>(dx[i],dy[i],dz[i]);
        dis[i].normalize();
    }
    float otsu = *std::max_element(fib_fa[0].begin(),fib_fa[0].end())*0.1;
    std::vector<std::vector<unsigned char> > connected(fib_fa.size());
    for(unsigned int index = 0;index < connected.size();++index)
        connected[index].resize(dim.size());
    float connection_count = 0;
    for(image::pixel_index<3> index(dim);index < dim.size();++index)
    {
        if(fib_fa[0][index.index()] <= otsu)
            continue;
        unsigned int index3 = index.index()+index.index()+index.index();
        for(unsigned char fib1 = 0;fib1 < num_fib;++fib1)
        {
            if(fib_fa[fib1][index.index()] <= otsu)
                break;
            for(unsigned int j = 0;j < 2;++j)
            for(unsigned int i = 0;i < 13;++i)
            {
                image::vector<3,int> pos;
                pos = j ? image::vector<3,int>(index[0] + dx[i],index[1] + dy[i],index[2] + dz[i])
                          :image::vector<3,int>(index[0] - dx[i],index[1] - dy[i],index[2] - dz[i]);
                if(!dim.is_valid(pos))
                    continue;
                image::pixel_index<3> other_index(pos[0],pos[1],pos[2],dim);
                unsigned int other_index3 = other_index.index()+other_index.index()+other_index.index();
                if(std::abs(image::vector<3>(&fib_dir[fib1][index3])*dis[i]) <= 0.8665)
                    continue;
                for(unsigned char fib2 = 0;fib2 < num_fib;++fib2)
                    if(fib_fa[fib2][other_index.index()] > otsu &&
                            std::abs(image::vector<3>(&fib_dir[fib2][other_index3])*dis[i]) > 0.8665)
                    {
                        connected[fib1][index.index()] = 1;
                        connected[fib2][other_index.index()] = 1;
                        connection_count += fib_fa[fib2][other_index.index()];
                    }
            }
        }
    }
    float no_connection_count = 0;
    for(image::pixel_index<3> index(dim);index < dim.size();++index)
    {
        for(unsigned int i = 0;i < num_fib;++i)
            if(fib_fa[i][index.index()] > otsu && !connected[i][index.index()])
            {
                no_connection_count += fib_fa[i][index.index()];
            }

    }

    return std::make_pair(connection_count,no_connection_count);
}
int main(int argc, char* argv[]) {
    std::chrono::time_point<std::chrono::system_clock> start, end;
    start = std::chrono::system_clock::now();
    std::time_t start_time = std::chrono::system_clock::to_time_t(start);
    std::cout << "Started computation at " << std::ctime(&start_time) << std::endl;


    uint8_t board_size = 0;
    unsigned int training_set = 0;
    unsigned int start_cycle = 0;
    unsigned int end_cycle = 0;
    bool uniform = 0;
    bool scaled = 0;
    // Validate command line parameters
    if (argc == 1) {
        // No parameters, use the Macros
        board_size = BOARD_SIZE;
        training_set = TRAINING_SET;
        start_cycle = STARTCYCLE;
        end_cycle = ENDCYCLE;
        uniform = UNIFORM;
        scaled = SCALED;
    } else if (argc == 7) {
        // TODO(wdfraser): Add some better error checking
        board_size = uint8_t(atoi(argv[1]));
        training_set = atoi(argv[2]);
        start_cycle = atoi(argv[3]);
        end_cycle = atoi(argv[4]);
        uniform = atoi(argv[5]) != 0;
        scaled = atoi(argv[6]) != 0;
    } else {
        throw TrainingArgumentError();
    }

    for (unsigned int n = start_cycle; n <= end_cycle; n++) {
        std::vector<GoGameNN> training_networks(NETWORKCOUNT, GoGameNN(board_size, uniform));
        std::vector<int> training_scores(NETWORKCOUNT);

        // Scaling networks used for seeding networks if scaled = true
        std::vector<GoGameNN> scaling_networks;
        // Set Random generator for use when selecting networks for reseeding
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> dis(0, NETWORKKEEP - 1);

        unsigned int export_count = 0;

        std::string output_directory =
                "size" + std::to_string(board_size) + "set" + std::to_string(training_set) + "/";

        std::ifstream best_networks_in(output_directory + "lastbestnetworks.txt");
        std::ifstream import_networks(output_directory + "import_networks.txt");

        if (scaled) {
            // If scaled network, confirm import_networks is open
            if (!import_networks.is_open()) {
                throw TrainingImportError();
            } else {
                scaling_networks.assign(NETWORKKEEP, GoGameNN(board_size - SEGMENT_DIVISION, uniform));
                // If it is, import example_networks;
                for (unsigned int i = 0; i < NETWORKKEEP; i++) {
                    scaling_networks[i].import_weights_stream(import_networks);
                }
            }
        }

        std::cout << "Generation with " << NETWORKCOUNT << " Neural Networks.\n"
        << "Total Games: " << NETWORKCOUNT * NETWORKCOUNT << std::endl;

        if (best_networks_in.is_open()) {
            std::cout << "Starting generation " << n << ". Last best network file succesfully opened. \n";

            // Read kept networks from file
            for (unsigned int i = 0; i < NETWORKKEEP; i++) {
                training_networks[i].import_weights_stream(best_networks_in);
            }
            for (unsigned int i = 0; i < NETWORKKEEP; i++) {
                training_networks[i + NETWORKKEEP] = training_networks[i];
                training_networks[i + NETWORKKEEP].mutate(MUTATER);
            }
            for (unsigned int i = 0; i < NETWORKKEEP; i++) {
                if (scaled) {
                    // If scaled network, seed network subsections from a random imported network
                    training_networks[i + (NETWORKKEEP * 2)].scale_network(scaling_networks[dis(gen)]);
                } else {
                    training_networks[i + (NETWORKKEEP * 2)].initialize_random();
                }
            }
        } else if (n == 1) {
            std::cout << "Starting first generation. Last best network file failed to open."
            << " Initializing random weights. \n";
            for (GoGameNN &element : training_networks) {
                if (scaled) {
                    // If scaled network, seed network subsections from a random imported network
                    element.scale_network(scaling_networks[dis(gen)]);
                } else {
                    element.initialize_random();
                }
            }
        } else {
            std::cout << "Starting generation " << n << ". Last best network file failed to open. Ending training. \n";
            break;
        }

        training_scores = score_networks(training_networks, board_size);

        for (unsigned int i = 0; i < training_scores.size(); i++) {
            std::cout << "Neural Network: " << i << ". Score: " << training_scores[i] << ".\n";
        }

        std::ofstream output_file(output_directory + "generation" + std::to_string(n) + ".txt");
        std::ofstream best_networks_file(output_directory + "lastbestnetworks.txt",
                                         std::ofstream::out | std::ofstream::trunc);

        if (output_file.is_open()) {
            for (unsigned int i = 0; i < training_scores.size(); i++) {
                output_file << "Neural Network: " << i << ". Score: " << training_scores[i] << ".\n";
            }
            output_file << std::endl;
            for (unsigned int i = 0; i < training_scores.size(); i++) {
                output_file << "Neural Network: " << i << ".\n";
                training_networks[i].export_weights_stream(output_file);
                output_file << std::endl;
            }
            output_file.close();
        } else {
            std::cout << "Error opening output file. \n";
            break;
        }

        if (best_networks_file.is_open()) {
            // Check down to lowest possible score, -NETWORKCOUNT*2
            for (int i = NETWORKCOUNT - 1; i > -NETWORKCOUNT * 2; i--) {
                if (export_count >= NETWORKKEEP) {
                    break;
                }
                for (unsigned int j = 0; j < NETWORKCOUNT; j++) {
                    if (export_count >= NETWORKKEEP) {
                        break;
                    }
                    if (training_scores[j] == i) {
                        training_networks[j].export_weights_stream(best_networks_file);
                        export_count += 1;
                    }
                }
            }
            best_networks_file.close();
        } else {
            std::cout << "Error opening best networks file. \n";
            break;
        }
    }
    end = std::chrono::system_clock::now();
    std::chrono::duration<double> elapsed_seconds = end - start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout << "Finished computation at " << std::ctime(&end_time) << "elapsed time: " <<
            elapsed_seconds.count() << "s" << std::endl;
}
Esempio n. 12
0
File: SIL.c Progetto: ndg2012/jp
int main(void)
{
    rect a, b;
    int da = 0;
    int db = 0;

    scanf("%d %d %d %d", &a.ld.x, &a.ld.y, &a.pg.x, &a.pg.y);
    scanf("%d %d %d %d", &b.ld.x, &b.ld.y, &b.pg.x, &b.pg.y);


    if (dis(a, b) == 1)
	printf("%d\n", area(a) + area(b));
    else {
	if (in(a, b) == 1)
	    printf("%d\n", area(a) > area(b) ? area(a) : area(b));
	else {
	    if (a.pg.x <= b.pg.x && a.pg.y <= b.pg.y) {
		if (a.ld.x <= b.ld.x && b.pg.x >= a.pg.x
		    && a.pg.y == b.pg.y) {
		    da = a.pg.x - b.ld.x;
		    db = a.pg.y - a.ld.y;
		    printf("%d\n", area(a) + area(b) - da * db);
		} else {
		    da = a.pg.x - b.ld.x;
		    db = a.pg.y - b.ld.y;
		    printf("%d\n", area(a) + area(b) - da * db);
		}
	    } else if (a.ld.y == b.ld.y) {
		if (b.pg.x <= a.pg.x && b.pg.y <= a.pg.y) {
		    da = b.pg.x - a.ld.x;
		    db = b.pg.y - b.ld.y;
		    printf("%d\n", area(a) + area(b) - da * db);
		} else {
		    da = a.pg.x - a.ld.x;
		    db = b.pg.y - b.ld.y;
		    printf("%d\n", area(a) + area(b) - da * db);
		}
	    } else if (a.pg.y == b.pg.y) {
		da = b.pg.x - a.ld.x;
		db = a.pg.y - a.ld.y;
		printf("%d\n", area(a) + area(b) - da * db);
	    } else if (a.ld.x == b.ld.x) {
		if (b.pg.x <= a.pg.x && b.pg.y <= a.pg.y) {
		    da = b.pg.x - b.ld.x;
		    db = b.pg.y - a.ld.y;
		    printf("%d\n", area(a) + area(b) - da * db);
		}
		else if(b.pg.x <= a.pg.x && b.pg.y >= a.pg.y){
		  da = b.pg.x - b.ld.x;
		  db = a.pg.y - a.ld.y;
	          printf("%d\n", area(a) + area(b) - da * db);
		} else {
		    da = a.pg.x - a.ld.x;
		    db = b.pg.y - b.ld.y;
		    printf("%d\n", area(a) + area(b) - da * db);
		}
	    } else if (a.pg.x >= b.pg.x && a.pg.y <= b.pg.y
		       && b.ld.y >= a.ld.y) {
		if (a.ld.x <= b.ld.x && b.pg.x <= a.pg.x) {
		    da = b.pg.x - b.ld.x;
		    db = a.pg.y - b.ld.y;
		    printf("%d\n", area(a) + area(b) - da * db);
		} else {
		    da = b.pg.x - a.ld.x;
		    db = a.pg.y - b.ld.y;
		    printf("%d\n", area(a) + area(b) - da * db);
		}
	    } else if (a.ld.x <= b.ld.x && a.pg.x <= b.pg.x) {
		if (a.ld.y <= b.ld.y && b.pg.y <= a.pg.y) {
		    da = a.pg.x - b.ld.x;
		    db = b.pg.y - b.ld.y;
		    printf("%d\n", area(a) + area(b) - da * db);
		} else if (a.ld.y >= b.ld.y && a.pg.y >= b.pg.y) {
		    da = a.pg.x - b.ld.x;
		    db = b.pg.y - a.ld.y;
		    printf("%d\n", area(a) + area(b) - da * db);
		} else
		    fprintf(stderr, "Error2. Nieznany przypadek.\n");
	    } else if (b.ld.x <= a.ld.x && b.pg.x <= a.pg.x) {
		da = b.pg.x - a.ld.x;
		db = b.pg.y - a.ld.y;
		printf("%d\n", area(a) + area(b) - da * db);
	    } else if (a.ld.x <= b.ld.x && b.pg.x <= a.pg.x) {
		da = b.pg.x - b.ld.x;
		db = b.pg.y - a.ld.y;
		printf("%d\n", area(a) + area(b) - da * db);
	    } else
		fprintf(stderr, "Error. Nieznany przypadek.\n");
	}
    }

    return 0;
}
Esempio n. 13
0
std::string MusicDay::choose_one_string(std::vector<std::string> choices) {
    std::uniform_int_distribution<> dis(0, choices.size() - 1);
    int choice_index = dis(rand_generator);
    std::string choice = choices[choice_index];
    return choice;
}
Esempio n. 14
0
std::string MusicDay::choose_one_string(const std::string choices[], int array_size) {
    std::uniform_int_distribution<> dis(0, array_size - 1);
    int choice_index = dis(rand_generator);
    std::string choice = choices[choice_index];
    return choice;
}
Esempio n. 15
0
TEST(Solution, CouplingFem2)
{
    // problem definition
    const size_t div = 20;
    const double poro = 1.0;
    const double mol_diff = 1e-6;
    const double darcy_vel = 1e-5;

    try {
        //space
        MeshLib::IMesh *msh = MeshGenerator::generateStructuredRegularQuadMesh(2.0, div, .0, .0, .0);
        GeoLib::Rectangle* _rec = new GeoLib::Rectangle(Point(0.0, 0.0, 0.0),  Point(2.0, 2.0, 0.0));
        //time
        //TimeStepFunctionConstant tim(.0, 1e+3, 1e+3);
        TimeStepFunctionConstant tim(.0, 1e+4, 1e+3);
        //material
        Geo::PorousMedia pm;
        pm.hydraulic_conductivity = new NumLib::TXFunctionConstant(1.e-11);
        pm.porosity = new NumLib::TXFunctionConstant(poro);
        Geo::Compound tracer;
        tracer.molecular_diffusion = new NumLib::TXFunctionConstant(mol_diff);
        //problems
        DiscreteSystem dis(msh);
        FemLib::LagrangeFeObjectContainer feObjects(msh);
        Geo::GWFemProblem* pGW = defineGWProblem(dis, *_rec, pm, &feObjects);
        Geo::MassFemProblem* pMass = defineMassTransportProblem(dis, *_rec, pm, tracer, &feObjects);
        pGW->setTimeSteppingFunction(tim);
        pMass->setTimeSteppingFunction(tim);
        //options
        BaseLib::Options optionsGW;
        BaseLib::Options* op_lis = optionsGW.addSubGroup("LinearSolver");
        op_lis->addOption("solver_type", "CG");
        op_lis->addOption("precon_type", "NONE");
        op_lis->addOptionAsNum("error_tolerance", 1e-10);
        op_lis->addOptionAsNum("max_iteration_step", 1000);
        BaseLib::Options* op_nl = optionsGW.addSubGroup("Nonlinear");
        op_nl->addOption("solver_type", "Picard");
        op_nl->addOptionAsNum("error_tolerance", 1e-6);
        op_nl->addOptionAsNum("max_iteration_step", 500);
        BaseLib::Options optionsMT;
        op_lis = optionsMT.addSubGroup("LinearSolver");
        op_lis->addOption("solver_type", "BICG");
        op_lis->addOption("precon_type", "NONE");
        op_lis->addOptionAsNum("error_tolerance", 1e-10);
        op_lis->addOptionAsNum("max_iteration_step", 1000);
        BaseLib::Options* op_nl2 = optionsMT.addSubGroup("Nonlinear");
        op_nl2->addOption("solver_type", "Picard");
        op_nl2->addOptionAsNum("error_tolerance", 1e-6);
        op_nl2->addOptionAsNum("max_iteration_step", 500);
        // unknowns
        MyFunctionHead f_head;
        f_head.define(&dis, pGW, optionsGW);
        f_head.setOutputParameterName(0, "h");
        MyFunctionVelocity f_vel;
        f_vel.define(dis, pm);
        f_vel.setInputParameterName(0, "h");
        f_vel.setOutputParameterName(0, "v");
        MyFunctionConcentration f_c;
        f_c.define(&dis, pMass, optionsMT);
        f_c.setInputParameterName(0, "v");
        f_c.setOutputParameterName(0, "c");


        SerialStaggeredMethod method(1e-5, 100);
        AsyncPartitionedSystem apart1;
        apart1.setAlgorithm(method);
        apart1.resizeOutputParameter(3);
        apart1.setOutputParameterName(0, "h");
        apart1.setOutputParameterName(1, "v");
        apart1.setOutputParameterName(2, "c");
        apart1.addProblem(f_head);
        apart1.addProblem(f_vel);
        apart1.addProblem(f_c);
        apart1.connectParameters();

        TimeSteppingController timestepping;
        timestepping.setTransientSystem(apart1);

        //const double epsilon = 1.e-3;
        timestepping.setBeginning(.0);
        timestepping.solve(tim.getEnd());

        const MyNodalFunctionScalar* r_f_head = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("h"));
        //const MyIntegrationPointFunctionVector* r_f_v = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("v"));
        const MyNodalFunctionScalar* r_f_c = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("c"));
        const IDiscreteVector<double>* vec_h = r_f_head->getDiscreteData();
        //const FEMIntegrationPointFunctionVector2d::DiscreteVectorType* vec_v = r_f_v->getNodalValues();
        const IDiscreteVector<double>* vec_c = r_f_c->getDiscreteData();

        //r_f_head->printout();
        //r_f_v->printout();
//#undef OUTPUT_C
#define OUTPUT_C
        std::vector<double> expectedHead(msh->getNumberOfNodes());
        const double p_left = 2.e+6;
        const double p_right = .0;
        const double x_len = 2.0;
#ifdef OUTPUT_C
        std::cout << std::endl << "expected p=";
#endif
        for (size_t i=0; i<expectedHead.size(); i++) {
            double x = msh->getNodeCoordinatesRef(i)->getData()[0];
            expectedHead[i] = (p_right-p_left) / x_len * x + p_left;
#ifdef OUTPUT_C
            std::cout << expectedHead[i] << " ";
#endif
        }
//        getGWExpectedHead(expectedHead);
        ASSERT_DOUBLE_ARRAY_EQ(&expectedHead[0], &(*vec_h)[0], expectedHead.size(), 1e-5);


        std::vector<double> expectedC(msh->getNumberOfNodes());

#ifdef OUTPUT_C
        std::cout << std::endl << "simulated C:"<< std::endl;
        r_f_c->printout();
        std::cout << "expected C=";
#endif
        for (size_t i=0; i<msh->getNumberOfNodes(); i++) {
            double x = msh->getNodeCoordinatesRef(i)->getData()[0];
            expectedC[i] = analyticalOgataBank(x, tim.getEnd(), darcy_vel/poro, mol_diff);
#ifdef OUTPUT_C
            std::cout << expectedC[i] << " ";
#endif
        }
#ifdef OUTPUT_C
        std::cout << std::endl;
#endif
        ASSERT_DOUBLE_ARRAY_EQ(&expectedC[0], &(*vec_c)[0], expectedC.size(), 5e-2);


    } catch (const char* e) {
        std::cout << "***Exception caught! " << e << std::endl;
    }

}
Esempio n. 16
0
int Randomizer::Random(int a, int b) {
        std::random_device rd_;
        std::mt19937 gen_(rd_());
	std::uniform_int_distribution<> dis(a, b);
	return dis(gen_);
}
Esempio n. 17
0
TEST(Solution, LinearElastic2D)
{
    try {
        MeshLib::IMesh *msh = MeshGenerator::generateStructuredRegularQuadMesh(2.0, 2, .0, .0, .0);
        GeoLib::Rectangle* _rec = new GeoLib::Rectangle(Point(0.0, 0.0, 0.0),  Point(2.0, 2.0, 0.0));
        Geo::PorousMedia pm;
        pm.hydraulic_conductivity = new NumLib::TXFunctionConstant(1.e-11);
        pm.porosity = new NumLib::TXFunctionConstant(0.2);
        Geo::Solid solid;
        solid.density = 3e+3;
        solid.poisson_ratio = 0.2;
        solid.Youngs_modulus = 10e+9;
        pm.solidphase = &solid;
        DiscreteSystem dis(msh);
        FemLib::LagrangeFeObjectContainer feObjects(msh);
        Geo::FemLinearElasticProblem* pDe = defineLinearElasticProblem(dis, *_rec, pm, &feObjects);
        TimeStepFunctionConstant tim(.0, 10.0, 10.0);
        pDe->setTimeSteppingFunction(tim);
        // options
        BaseLib::Options options;
        BaseLib::Options* op_lis = options.addSubGroup("LinearSolver");
        op_lis->addOption("solver_type", "CG");
        op_lis->addOption("precon_type", "NONE");
        op_lis->addOptionAsNum("error_tolerance", 1e-10);
        op_lis->addOptionAsNum("max_iteration_step", 500);
        BaseLib::Options* op_nl = options.addSubGroup("Nonlinear");
        op_nl->addOption("solver_type", "Linear");
        op_nl->addOptionAsNum("error_tolerance", 1e-6);
        op_nl->addOptionAsNum("max_iteration_step", 500);

        MyFunctionDisplacement f_u;
        f_u.define(&dis, pDe, &pm, options);
        f_u.setOutputParameterName(0, "u_x");
        f_u.setOutputParameterName(1, "u_y");
        f_u.setOutputParameterName(2, "Strain");
        f_u.setOutputParameterName(3, "Stress");
//        MyFunctionStressStrain f_sigma;
//        f_sigma.setOutputParameterName(0, "strain_xx");

        SerialStaggeredMethod method(1e-5, 100);
        AsyncPartitionedSystem apart1;
        apart1.setAlgorithm(method);
        apart1.resizeOutputParameter(4);
        apart1.setOutputParameterName(0, "u_x");
        apart1.setOutputParameterName(1, "u_y");
        apart1.setOutputParameterName(2, "Strain");
        apart1.setOutputParameterName(3, "Stress");
        apart1.addProblem(f_u);
        apart1.connectParameters();

        TimeSteppingController timestepping;
        timestepping.setTransientSystem(apart1);

        //const double epsilon = 1.e-3;
        timestepping.setBeginning(.0);
        timestepping.solve(tim.getEnd());

//        const MyNodalFunctionScalar* r_f_ux = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("u_x"));
//        const MyNodalFunctionScalar* r_f_uy = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("u_y"));
        const MyIntegrationPointFunctionVector* r_f_strain = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("Strain"));
        const MyIntegrationPointFunctionVector* r_f_stress = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("Stress"));
//        const IDiscreteVector<double>* vec_r_f_ux = r_f_ux->getDiscreteData();
//        const IDiscreteVector<double>* vec_r_f_uy = r_f_uy->getDiscreteData();
        const MyIntegrationPointFunctionVector::MyDiscreteVector* vec_strain = r_f_strain->getDiscreteData();
        const MyIntegrationPointFunctionVector::MyDiscreteVector* vec_stress = r_f_stress->getDiscreteData();

//        r_f_ux->printout();
//        r_f_uy->printout();
//        r_f_strain->printout();
//        r_f_stress->printout();

        const MathLib::LocalVector &strain1 = (*vec_strain)[0][0];
        const MathLib::LocalVector &stress1 = (*vec_stress)[0][0];
        double E = solid.Youngs_modulus;
        double nu = solid.poisson_ratio;
        double sx = .0; //E/((1.+nu)*(1-2*nu))*((1-nu)*ex+nu*ey);
        double sy = -1e+6; //E/((1.-nu)*(1-2*nu))*(nu*ex+(1-nu)*ey);
        double sxy = .0; //0.5*E/(1.+nu)*exy;
        double ex = (1+nu)/E*((1-nu)*sx-nu*sy);
        double ey = (1+nu)/E*((1-nu)*sy-nu*sx);
        double exy = 2*(1+nu)/E*sxy;
        double sz = nu*E/((1.+nu)*(1-2*nu))*(ex+ey);
        double epsilon = 1e-6;
        ASSERT_NEAR(ex, strain1(0), epsilon);
        ASSERT_NEAR(ey, strain1(1), epsilon);
        ASSERT_NEAR(.0, strain1(2), epsilon);
        ASSERT_NEAR(exy, strain1(3), epsilon);
        epsilon = 1;
        ASSERT_NEAR(sx, stress1(0), epsilon);
        ASSERT_NEAR(sy, stress1(1), epsilon);
        ASSERT_NEAR(sz, stress1(2), epsilon);
        ASSERT_NEAR(sxy, stress1(3), epsilon);

    } catch (const char* e) {
        std::cout << "***Exception caught! " << e << std::endl;
    }

}
Esempio n. 18
0
    int HGRAD_TET_COMP12_FEM_Test01(const bool verbose) {
      
      Teuchos::RCP<std::ostream> outStream;
      Teuchos::oblackholestream bhs; // outputs nothing
      
      if (verbose)
        outStream = Teuchos::rcp(&std::cout, false);
      else
        outStream = Teuchos::rcp(&bhs,       false);

      Teuchos::oblackholestream oldFormatState;
      oldFormatState.copyfmt(std::cout);

      typedef typename
        Kokkos::Impl::is_space<DeviceSpaceType>::host_mirror_space::execution_space HostSpaceType ;

      *outStream << "DeviceSpace::  "; DeviceSpaceType::print_configuration(*outStream, false);
      *outStream << "HostSpace::    ";   HostSpaceType::print_configuration(*outStream, false);

      *outStream                                                        
        << "===============================================================================\n"
        << "|                                                                             |\n"
        << "|             Unit Test (Basis_HGRAD_TET_COMP12_FEM)                          |\n"
        << "|                                                                             |\n"
        << "|     1) Evaluation of Basis Function Values                                  |\n"
        << "|                                                                             |\n"
        << "|  Questions? Contact  Pavel Bochev  ([email protected]),                    |\n"
        << "|                      Denis Ridzal  ([email protected]),                    |\n"
        << "|                      Kara Peterson ([email protected]),                    |\n"
        << "|                      Jake Ostien   ([email protected]),                    |\n"
        << "|                      Kyungjoo Kim  ([email protected]).                     |\n"
        << "|                                                                             |\n"
        << "|  Intrepid's website: http://trilinos.sandia.gov/packages/intrepid           |\n"
        << "|  Trilinos website:   http://trilinos.sandia.gov                             |\n"
        << "|                                                                             |\n"
        << "===============================================================================\n";

      typedef Kokkos::DynRankView<ValueType,DeviceSpaceType> DynRankView;
      typedef Kokkos::DynRankView<ValueType,HostSpaceType>   DynRankViewHost;
#define ConstructWithLabel(obj, ...) obj(#obj, __VA_ARGS__)

      const ValueType tol = tolerence();
      int errorFlag = 0;

      // for virtual function, value and point types are declared in the class
      typedef ValueType outputValueType;
      typedef ValueType pointValueType;
      Basis_HGRAD_TET_COMP12_FEM<DeviceSpaceType,outputValueType,pointValueType> tetBasis;

      *outStream
        << "\n"
        << "===============================================================================\n"
        << "| TEST 1: correctness of basis function values                                |\n"
        << "===============================================================================\n";
      
      // output precision
      outStream -> precision(20);
      
      // VALUE: Each row gives the 10 correct basis set values at an evaluation point
      const ValueType nodalBasisValues[] = {
        // first 4 vertices
        1.0, 0.0, 0.0, 0.0,  0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
        0.0, 1.0, 0.0, 0.0,  0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
        0.0, 0.0, 1.0, 0.0,  0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
        0.0, 0.0, 0.0, 1.0,  0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
        // second 6 vertices
        0.0, 0.0, 0.0, 0.0,  1.0, 0.0, 0.0, 0.0, 0.0, 0.0,
        0.0, 0.0, 0.0, 0.0,  0.0, 1.0, 0.0, 0.0, 0.0, 0.0,
        0.0, 0.0, 0.0, 0.0,  0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
        0.0, 0.0, 0.0, 0.0,  0.0, 0.0, 0.0, 1.0, 0.0, 0.0,
        0.0, 0.0, 0.0, 0.0,  0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
        0.0, 0.0, 0.0, 0.0,  0.0, 0.0, 0.0, 0.0, 0.0, 1.0
      };

      const ValueType pointBasisValues[] = {
        // pt 0 {0.25, 0.25, 0.25}
        0.0, 0.0, 0.0, 0.0,  1./6., 1./6., 1./6., 1./6., 1./6., 1./6.,
        // pt 1 {0.5, 1/6, 1/6}
        0.0, 0.0, 0.0, 0.0,  1./3., 1./3., 0.0, 0.0, 1./3., 0.0,
        // pt 2 {1/6, 0.5, 0.1/6}
        0.0, 0.0, 0.0, 0.0,  0.0, 1./3., 1./3., 0.0, 0.0, 1./3.,
        // pt 3 {1/6, 1/6, 0.5}
        0.0, 0.0, 0.0, 0.0,  0.0, 0.0, 0.0, 1./3., 1./3., 1./3.,
        // pt 4 {1/6, 1/6, 1/6}
        0.0, 0.0, 0.0, 0.0,  1./3., 0.0, 1./3., 1./3., 0.0, 0.0,
        // pt 5
        0.170820393249936908922752100619382870632, 0.0, 0.0, 0.0, 0.276393202250021030359082633126872376456, 0.0, 0.276393202250021030359082633126872376456, 0.276393202250021030359082633126872376456, 0.0, 0.0,
        // pt 6
        0.0, 0.170820393249936908922752100619382870632, 0.0, 0.0, 0.276393202250021030359082633126872376456, 0.276393202250021030359082633126872376456, 0.0, 0.0, 0.276393202250021030359082633126872376456, 0.0,
        // pt 7
        0.0, 0.0, 0.170820393249936908922752100619382870632, 0.0, 0.0, 0.276393202250021030359082633126872376456, 0.276393202250021030359082633126872376456, 0.0, 0.0, 0.276393202250021030359082633126872376456,
        // pt 8
        0.0, 0.0, 0.0, 0.170820393249936908922752100619382870632, 0.0, 0.0, 0.0, 0.276393202250021030359082633126872376456, 0.276393202250021030359082633126872376456, 0.276393202250021030359082633126872376456,
      };

      // GRAD and D1: each row gives the 3x10 correct values of the gradients of the 10 basis functions
      const ValueType pointBasisGrads[] = {
        // point 0
        -1./4.,   -1./4.,   -1./4.,
        1./4.,      0.0,      0.0, 
        0.0,    1./4.,      0.0,   
        0.0,      0.0,    1./4.,
        0.0,   -3./4.,   -3./4.,
        3./4.,    3./4.,      0.0,
        -3./4.,      0.0,   -3./4.,
        -3./4.,   -3./4.,      0.0,
        3./4.,      0.0,    3./4.,
        0.0,    3./4.,    3./4.,

        // point 1
        -1./24.,  -1./24.,  -1./24.,
        7./8.,      0.0,      0.0,
        0.0,   1./24.,      0.0,
        0.0,      0.0,   1./24.,
        -35./36., -19./12., -19./12.,
        11./18.,  19./12.,      0.0,
        -17./36.,      0.0,   -1./3.,
        -17./36.,   -1./3.,      0.0,
        11./18.,      0.0,  19./12.,
        -5./36.,    1./3.,    1./3.,

        // point 2
        -1./24.,  -1./24.,  -1./24.,
        1./24.,      0.0,      0.0,
        0.0,    7./8.,      0.0,
        0.0,      0.0,   1./24.,
        0.0, -17./36.,   -1./3.,
        19./12.,  11./18.,      0.0,
        -19./12., -35./36., -19./12.,
        -1./3., -17./36.,      0.0,
        1./3.,  -5./36.,    1./3.,
        0.0,  11./18.,  19./12.,

        // point 3
        -1./24.,  -1./24.,  -1./24.,
        1./24.,      0.0,      0.0,
        0.0,   1./24.,      0.0,
        0.0,      0.0,    7./8.,
        0.0,   -1./3., -17./36.,
        1./3.,    1./3.,  -5./36.,
        -1./3.,      0.0, -17./36.,
        -19./12., -19./12., -35./36.,
        19./12.,      0.0,  11./18.,
        0.0,  19./12.,  11./18.,

        // point 4
        -7./8.,   -7./8.,   -7./8.,
        1./24.,      0.0,      0.0,
        0.0,   1./24.,      0.0,
        0.0,      0.0,   1./24.,
        35./36., -11./18., -11./18.,
        17./36.,  17./36.,   5./36.,
        -11./18.,  35./36., -11./18.,
        -11./18., -11./18.,  35./36.,
        17./36.,   5./36.,  17./36.,
        5./36.,  17./36.,  17./36.,

        // point 5
        -1.088525491562421136153440125774228588290, -1.088525491562421136153440125774228588290, -1.088525491562421136153440125774228588290,
        -0.029508497187473712051146708591409529430, 0.0, 0.0,
        0.0, -0.029508497187473712051146708591409529430, 0.0,
        0.0, 0.0, -0.029508497187473712051146708591409529430,
        1.30437298687487732290535130675991113734, -0.563661001875017525299235527605726980380, -0.563661001875017525299235527605726980380,
        0.377322003750035050598471055211453960760, 0.377322003750035050598471055211453960760, 0.186338998124982474700764472394273019620,
        -0.563661001875017525299235527605726980380, 1.30437298687487732290535130675991113734, -0.563661001875017525299235527605726980380,
        -0.563661001875017525299235527605726980380, -0.563661001875017525299235527605726980380, 1.30437298687487732290535130675991113734,
        0.377322003750035050598471055211453960760, 0.186338998124982474700764472394273019620, 0.377322003750035050598471055211453960760,
        0.186338998124982474700764472394273019620, 0.377322003750035050598471055211453960760, 0.377322003750035050598471055211453960760,

        // point 6
        0.029508497187473712051146708591409529430, 0.029508497187473712051146708591409529430, 0.029508497187473712051146708591409529430,
        1.088525491562421136153440125774228588290, 0.0, 0.0,
        0.0, -0.029508497187473712051146708591409529430, 0.0,
        0.0, 0.0, -0.029508497187473712051146708591409529430,
        -1.30437298687487732290535130675991113734, -1.868033988749894848204586834365638117720, -1.868033988749894848204586834365638117720,
        0.563661001875017525299235527605726980380, 1.868033988749894848204586834365638117720, 0.0,
        -0.377322003750035050598471055211453960760, 0.0, -0.190983005625052575897706582817180941140,
        -0.377322003750035050598471055211453960760, -0.190983005625052575897706582817180941140, 0.0,
        0.563661001875017525299235527605726980380, 0.0, 1.868033988749894848204586834365638117720,
        -0.186338998124982474700764472394273019620, 0.190983005625052575897706582817180941140, 0.19098300562505257589770658281718094114,

        // point 7
        0.029508497187473712051146708591409529430, 0.029508497187473712051146708591409529430, 0.029508497187473712051146708591409529430,
        -0.029508497187473712051146708591409529430, 0.0, 0.0,          
        0.0, 1.088525491562421136153440125774228588290, 0.0,           
        0.0, 0.0, -0.029508497187473712051146708591409529430,          
        0.0, -0.377322003750035050598471055211453960760, -0.190983005625052575897706582817180941140,
        1.868033988749894848204586834365638117720, 0.563661001875017525299235527605726980380, 0.0,
        -1.868033988749894848204586834365638117720, -1.30437298687487732290535130675991113734, -1.868033988749894848204586834365638117720,
        -0.190983005625052575897706582817180941140, -0.377322003750035050598471055211453960760, 0.0,
        0.190983005625052575897706582817180941140, -0.186338998124982474700764472394273019620, 0.190983005625052575897706582817180941140,
        0.0, 0.563661001875017525299235527605726980380, 1.868033988749894848204586834365638117720,

        // point 8
        0.029508497187473712051146708591409529430, 0.029508497187473712051146708591409529430, 0.029508497187473712051146708591409529430,
        -0.029508497187473712051146708591409529430, 0.0, 0.0,
        0.0, -0.029508497187473712051146708591409529430, 0.0,
        0.0, 0.0, 1.088525491562421136153440125774228588290,
        0.0, -0.190983005625052575897706582817180941140, -0.377322003750035050598471055211453960760,
        0.190983005625052575897706582817180941140, 0.190983005625052575897706582817180941140, -0.186338998124982474700764472394273019620,
        -0.190983005625052575897706582817180941140, 0.0, -0.377322003750035050598471055211453960760,
        -1.868033988749894848204586834365638117720, -1.868033988749894848204586834365638117720, -1.30437298687487732290535130675991113734,
        1.868033988749894848204586834365638117720, 0.0, 0.563661001875017525299235527605726980380,
        0.0, 1.868033988749894848204586834365638117720, 0.563661001875017525299235527605726980380,
      };
      
      try{
        DynRankViewHost ConstructWithLabel(tetNodesHost, 10, 3);
        
        tetNodesHost(0,0) = 0.0;  tetNodesHost(0,1) = 0.0;  tetNodesHost(0,2) = 0.0;
        tetNodesHost(1,0) = 1.0;  tetNodesHost(1,1) = 0.0;  tetNodesHost(1,2) = 0.0;
        tetNodesHost(2,0) = 0.0;  tetNodesHost(2,1) = 1.0;  tetNodesHost(2,2) = 0.0;
        tetNodesHost(3,0) = 0.0;  tetNodesHost(3,1) = 0.0;  tetNodesHost(3,2) = 1.0;
        tetNodesHost(4,0) = 0.5;  tetNodesHost(4,1) = 0.0;  tetNodesHost(4,2) = 0.0;
        tetNodesHost(5,0) = 0.5;  tetNodesHost(5,1) = 0.5;  tetNodesHost(5,2) = 0.0;
        tetNodesHost(6,0) = 0.0;  tetNodesHost(6,1) = 0.5;  tetNodesHost(6,2) = 0.0;
        tetNodesHost(7,0) = 0.0;  tetNodesHost(7,1) = 0.0;  tetNodesHost(7,2) = 0.5;
        tetNodesHost(8,0) = 0.5;  tetNodesHost(8,1) = 0.0;  tetNodesHost(8,2) = 0.5;
        tetNodesHost(9,0) = 0.0;  tetNodesHost(9,1) = 0.5;  tetNodesHost(9,2) = 0.5;
        
        auto tetNodes = Kokkos::create_mirror_view(typename DeviceSpaceType::memory_space(), tetNodesHost);
        Kokkos::deep_copy(tetNodes, tetNodesHost);

        DynRankViewHost ConstructWithLabel(tetPointsHost, 9, 3);
        
        // from the 5 point integration
        tetPointsHost(0,0) = 0.25;     tetPointsHost(0,1) = 0.25;     tetPointsHost(0,2) = 0.25;
        tetPointsHost(1,0) = 0.5;      tetPointsHost(1,1) = (1./6.);  tetPointsHost(1,2) = (1./6.);
        tetPointsHost(2,0) = (1./6.);  tetPointsHost(2,1) = 0.5;      tetPointsHost(2,2) = (1./6.);
        tetPointsHost(3,0) = (1./6.);  tetPointsHost(3,1) = (1./6.);  tetPointsHost(3,2) = 0.5;
        tetPointsHost(4,0) = (1./6.);  tetPointsHost(4,1) = (1./6.);  tetPointsHost(4,2) = (1./6.);
        
        // from the 4 point integration
        tetPointsHost(5,0) = 0.1381966011250105151795413165634361882280;
        tetPointsHost(5,1) = 0.1381966011250105151795413165634361882280;
        tetPointsHost(5,2) = 0.1381966011250105151795413165634361882280;
        
        tetPointsHost(6,0) = 0.5854101966249684544613760503096914353161;
        tetPointsHost(6,1) = 0.1381966011250105151795413165634361882280;
        tetPointsHost(6,2) = 0.1381966011250105151795413165634361882280;
        
        tetPointsHost(7,0) = 0.1381966011250105151795413165634361882280;
        tetPointsHost(7,1) = 0.5854101966249684544613760503096914353161;
        tetPointsHost(7,2) = 0.1381966011250105151795413165634361882280;
        
        tetPointsHost(8,0) = 0.1381966011250105151795413165634361882280;
        tetPointsHost(8,1) = 0.1381966011250105151795413165634361882280;
        tetPointsHost(8,2) = 0.5854101966249684544613760503096914353161;

        auto tetPoints = Kokkos::create_mirror_view(typename DeviceSpaceType::memory_space(), tetPointsHost);
        Kokkos::deep_copy(tetPoints, tetPointsHost);

        // Dimensions for the output arrays:
        const auto numFields = tetBasis.getCardinality();
        const auto numNodes  = tetNodes.dimension(0);
        const auto spaceDim  = tetBasis.getBaseCellTopology().getDimension();
    
        // Check VALUE of basis functions at nodes: resize vals to rank-2 container:\n";
        {
          *outStream << " check VALUE of basis functions at nodes\n";
          DynRankView vals = DynRankView("vals", numFields, numNodes);
          tetBasis.getValues(vals, tetNodes, OPERATOR_VALUE);
          auto vals_host = Kokkos::create_mirror_view(typename HostSpaceType::memory_space(), vals);
          Kokkos::deep_copy(vals_host, vals);

          for (auto i=0;i<numFields;++i) {
            for (auto j=0;j<numNodes;++j) {
              const auto l =  i + j * numFields;
              if (std::abs(vals_host(i,j) - nodalBasisValues[l]) > tol) {
                errorFlag++;
                *outStream << std::setw(70) << "^^^^----FAILURE!" << "\n";

                // Output the multi-index of the value where the error is:
                *outStream << " At multi-index { ";
                *outStream << i << " ";*outStream << j << " ";
                *outStream << "}  computed value: " << vals_host(i,j)
                           << " but reference value: " << nodalBasisValues[l] << "\n";
              }
            }
          }
        }

        const auto numPoints = tetPoints.dimension(0);

        // Check VALUE of basis functions at points: resize vals to rank-2 container:\n";
        {
          *outStream << " check VALUE of basis functions at points\n";
          DynRankView vals = DynRankView("vals", numFields, numPoints);
          tetBasis.getValues(vals, tetPoints, OPERATOR_VALUE);
          auto vals_host = Kokkos::create_mirror_view(typename HostSpaceType::memory_space(), vals);
          Kokkos::deep_copy(vals_host, vals);

          for (auto i=0;i<numFields;++i) {
            for (auto j=0;j<numPoints;++j) {
              const auto l =  i + j * numFields;
              if (std::abs(vals_host(i,j) - pointBasisValues[l]) > tol) {
                errorFlag++;
                *outStream << std::setw(70) << "^^^^----FAILURE!" << "\n";

                // Output the multi-index of the value where the error is:
                *outStream << " At multi-index { ";
                *outStream << i << " ";*outStream << j << " ";
                *outStream << "}  computed value: " << vals_host(i,j)
                           << " but reference value: " << pointBasisValues[l] << "\n";
              }
            }
          }
        }
        
        // Check VALUE of basis functions at random points: resize vals to rank-2 container:\n";
        {
          *outStream << " check VALUE of basis functions at random points\n";
          const auto numRandomPoints = 16384;

          DynRankViewHost tetRandomPointsHost = DynRankViewHost("tetRandomPointsHost", numRandomPoints, 3);
          {
            ordinal_type point = 0;

            std::random_device rd;
            std::mt19937 gen(rd());
            std::uniform_real_distribution<> dis(0, 1);
            while (point < numRandomPoints) {
              const ValueType r = dis(gen), s = dis(gen), t = dis(gen);
              if (r + s + t > 1.0) {
                // do nothing
              } else {
                tetRandomPointsHost(point, 0) = r;
                tetRandomPointsHost(point, 1) = s;
                tetRandomPointsHost(point, 2) = t;
                ++point;
              }
            }
          }
          
          auto tetRandomPoints = Kokkos::create_mirror_view(typename DeviceSpaceType::memory_space(), tetRandomPointsHost);
          Kokkos::deep_copy(tetRandomPoints, tetRandomPointsHost);

          DynRankView vals = DynRankView("vals", numFields, numRandomPoints);
        
          tetBasis.getValues(vals, tetRandomPoints, OPERATOR_VALUE);
          auto vals_host = Kokkos::create_mirror_view(typename HostSpaceType::memory_space(), vals);
          Kokkos::deep_copy(vals_host, vals);
        
          for (auto j=0;j<numRandomPoints;++j) {
            ValueType sum = 0.0;
            for (auto i=0;i<numFields;++i) 
              sum += vals_host(i,j);

            if (std::abs(sum - 1.0) > tol) {
              errorFlag++;
              *outStream << std::setw(70) << "^^^^----FAILURE!" << "\n";
              
              // Just indicate something bad happened
              *outStream << " Composite tet basis functions";
              *outStream << " are not summing to 1.0\n";
              *outStream << " sum : " << sum << "\n";
            }
          }
        }
        
    
        // Check GRAD of basis functions at points: resize vals to rank-3 container:\n";
        {
          DynRankView vals = DynRankView("vals", numFields, numPoints, spaceDim);
          tetBasis.getValues(vals, tetPoints, OPERATOR_GRAD);
          auto vals_host = Kokkos::create_mirror_view(typename HostSpaceType::memory_space(), vals);
          Kokkos::deep_copy(vals_host, vals);
          for (auto i=0;i<numFields;++i) {
            for (auto j=0;j<numPoints;++j) {
              for (auto k=0;k<spaceDim;++k) {
                const auto l = k + i * spaceDim + j * spaceDim * numFields;
                if (std::abs(vals_host(i,j,k) - pointBasisGrads[l]) > tol) {
                  errorFlag++;
                  *outStream << std::setw(70) << "^^^^----FAILURE!" << "\n";
                  
                  // Output the multi-index of the value where the error is:
                  *outStream << " At multi-index { ";
                  *outStream << i << " ";*outStream << j << " ";*outStream << k << " ";
                  *outStream << "}  computed grad component: " << vals_host(i,j,k)
                             << " but reference grad component: " << pointBasisGrads[l] << "\n";
                }
              }
            }
          }
        }
      } catch (std::logic_error err) {
        *outStream << err.what() << "\n\n";
        errorFlag = -1000;
      }

      if (errorFlag != 0)
        std::cout << "End Result: TEST FAILED\n";
      else
        std::cout << "End Result: TEST PASSED\n";

      // reset format state of std::cout
      std::cout.copyfmt(oldFormatState);
      return errorFlag;
    }
Esempio n. 19
0
void Ennemi::initCaracteristics()
{

    se::Config* conf = se::Config::getInstance();

    int vitesseMin, vitesseMax = 1;

    if(conf->get(MIN_SPEED,vitesseMin)&&conf->get(MAX_SPEED,vitesseMax))
    {
        std::uniform_int_distribution<> dis(vitesseMin,vitesseMax);

        speed.x = static_cast<float>(dis(gen));
        speed.y = static_cast<float>(dis(gen));
    }
    else
    {
        speed.x = static_cast<float>(dis(gen));
        speed.y = static_cast<float>(dis(gen));
    }

    nspeed = se::Utils::norm(speed);

    sf::RenderWindow& window = se::GraphicEngine::getInstance()->getRenderWindow();

    std::uniform_int_distribution<> disMod(0,3);
    std::uniform_int_distribution<> varMod(0,100);

    float startX = 0;
    float startY = 0;
    int varPart = varMod(gen);

    switch(disMod(gen))
    {
    case 0 :
        startX = varPart;
        startY = -varPart;
        break;
    case 1 :
        startX = window.getSize().x + varPart;
        startY = varPart;
        break;
    case 2 :
        startX = window.getSize().x + varPart;
        startY = window.getSize().y + varPart;
        break;
    case 3 :
        startX = -varPart;
        startY = window.getSize().y +varPart;
        break;
    default :
        ;
        break;
    }

    myEntity->setPosition(startX,startY);

    myEntity->setOrigin(SIZE,SIZE);

    myShadow->setOrigin(SIZE,SIZE);


}
Esempio n. 20
0
int main()
{
    int n, i, j, ans, sum, k = 0;
    double r1, r2, r3, r4, r;
    double x1, y1, x2, y2, x, y;
    while (scanf("%d", &n), n)
    {
        scanf("%lf%lf%lf%lf%lf", &x1, &y1, &x2, &y2, &r);
        r = 1.0 * r / PI;
        for (i = 0; i < n; i++)
        {
            scanf("%lf%lf", &x, &y);
            d1[i] = dis(x, y, x1, y1);
            d2[i] = dis(x, y, x2, y2);
        }
        for (i = 0, ans = n; i < n; i++)
        {
            r1 = d1[i];
            if (r1 <= r)//涓句涓瑰朵腑涓涓濉璺绂r1,╀纾娉㈣绂讳负r2
            {
                r2 = r - r1;
                for (j = 0, sum = 0; j < n; j++)
                {
                    if (d1[j] <= r1)
                    {
                        sum++;
                    }
                    else if (d2[j] <= r2)
                    {
                        sum++;
                    }
                }
                if (ans > n - sum)
                {
                    ans = n - sum;
                }
            }
            r2 = d2[i];
            if (r2 <= r)
            {
                r1 = r - r2;
                for (j = 0, sum = 0; j < n; j++)
                {
                    if (d1[j] <= r1)
                    {
                        sum++;
                    }
                    else if (d2[j] <= r2)
                    {
                        sum++;
                    }
                }
                if (ans > n - sum)
                {
                    ans = n - sum;
                }
            }
        }
        k++;
        printf("%d. %d\n", k, ans);
    }
    return 0;
}
Esempio n. 21
0
 Iter random_element(Iter start, Iter end, RandomGenerator& g) {
     std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
     std::advance(start, dis(g));
     return start;
 }
Esempio n. 22
0
	unsigned int random() {
		return dis(gen) + INT_MAX;
	}
Esempio n. 23
0
	float math::random_range(float min, float max)
	{
		std::uniform_real_distribution<float> dis(min, max);
		return dis(gen);
	}
Esempio n. 24
0
int randomInt(int min, int max) {
    thread_local std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(min, max);
    return dis(gen);
}
Esempio n. 25
0
	double Random::generate(int n){
		std::random_device rd;
		std::mt19937 gen(rd());
		std::uniform_real_distribution<> dis(minRange, maxRange);
		return dis(gen);
	}
Esempio n. 26
0
TEST(Solution, CouplingFem2D)
{
    try {
        MeshLib::IMesh *msh = MeshGenerator::generateStructuredRegularQuadMesh(2.0, 2, .0, .0, .0);
        GeoLib::Rectangle* _rec = new GeoLib::Rectangle(Point(0.0, 0.0, 0.0),  Point(2.0, 2.0, 0.0));
        Geo::PorousMedia pm;
        pm.hydraulic_conductivity = new NumLib::TXFunctionConstant(1.e-11);
        pm.porosity = new NumLib::TXFunctionConstant(0.2);
        DiscreteSystem dis(msh);
        FemLib::LagrangeFeObjectContainer feObjects(msh);
        Geo::GWFemProblem* pGW = defineGWProblem(dis, *_rec, pm, &feObjects);
        TimeStepFunctionConstant tim(.0, 100.0, 10.0);
        pGW->setTimeSteppingFunction(tim);
        // options
        BaseLib::Options options;
        BaseLib::Options* op_lis = options.addSubGroup("LinearSolver");
        op_lis->addOption("solver_type", "CG");
        op_lis->addOption("precon_type", "NONE");
        op_lis->addOptionAsNum("error_tolerance", 1e-10);
        op_lis->addOptionAsNum("max_iteration_step", 500);
        BaseLib::Options* op_nl = options.addSubGroup("Nonlinear");
        op_nl->addOption("solver_type", "Picard");
        op_nl->addOptionAsNum("error_tolerance", 1e-6);
        op_nl->addOptionAsNum("max_iteration_step", 500);

        MyFunctionHead f_head;
        f_head.define(&dis, pGW, options);
        f_head.setOutputParameterName(0, "h");
        MyFunctionVelocity f_vel;
        f_vel.define(dis, pm);
        f_vel.setInputParameterName(0, "h");
        f_vel.setOutputParameterName(0, "v");

        SerialStaggeredMethod method(1e-5, 100);
        AsyncPartitionedSystem apart1;
        apart1.setAlgorithm(method);
        apart1.resizeOutputParameter(2);
        apart1.setOutputParameterName(0, "h");
        apart1.setOutputParameterName(1, "v");
        apart1.addProblem(f_head);
        apart1.addProblem(f_vel);
        apart1.connectParameters();

        TimeSteppingController timestepping;
        timestepping.setTransientSystem(apart1);

        //const double epsilon = 1.e-3;
        timestepping.setBeginning(.0);
        timestepping.solve(tim.getEnd());

        const MyNodalFunctionScalar* r_f_head = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("h"));
        const MyIntegrationPointFunctionVector* r_f_v = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("v"));
        const IDiscreteVector<double>* vec_h = r_f_head->getDiscreteData();
        //const FEMIntegrationPointFunctionVector2d::DiscreteVectorType* vec_v = r_f_v->getNodalValues();

        r_f_head->printout();
        r_f_v->printout();

        std::vector<double> expected;
        getGWExpectedHead(expected);

        ASSERT_DOUBLE_ARRAY_EQ(&expected[0], &(*vec_h)[0], vec_h->size());

    } catch (const char* e) {
        std::cout << "***Exception caught! " << e << std::endl;
    }

}
Esempio n. 27
0
void World::update() {
  uint32_t updateTime = SDL_GetTicks();
  float dtime = (updateTime-lastUpdateTime)/1000.f;

  // If F5 released, reload the scene
  if (wasF5Down and not Input::isKeyDown(SDL_SCANCODE_F5)) {
    if (Input::isKeyDown(SDL_SCANCODE_LSHIFT) || Input::isKeyDown(SDL_SCANCODE_RSHIFT)) {
      // Enable reload-on-change (inotify on Linux)
    }

    loadScene(currentScenePath);
  }
  wasF5Down = Input::isKeyDown(SDL_SCANCODE_F5);
  // If Tab released, toggle editor
  if (wasTabDown and not Input::isKeyDown(SDL_SCANCODE_TAB)) {
    isEditorShown = !isEditorShown;
  }
  wasTabDown = Input::isKeyDown(SDL_SCANCODE_F5);

  Entity &player = scene->player;
  Health &plrHealth = player.getComponent<Health>();
  Transform &plrTform = player.getComponent<Transform>();
  PlayerMotion &plrMotion = player.getComponent<PlayerMotion>();

  // Check if player is still alive
  if (not plrHealth.isAlive()) {
    plrTform.position = scene->start.getComponent<Transform>().position;
    plrHealth.revive();
    hidePortals();
  }

  // Calculate the view and new velocity of the player
  // FIXME: don't do this here, let a manager handle
  plrMotion.mouseLook();
  plrMotion.move(dtime);

  // Figure out the provisional new player position
  Vector3f pos = plrTform.position + plrMotion.velocity;

  //Y collision
  BoxCollider bboxY(Vector3f(plrTform.position.x, pos.y, plrTform.position.z), plrTform.scale);
  
  if (collidesWithWalls(bboxY)) {
    bool portaling = false;
    portaling = WorldHelper::isPlayerPortalingY(bboxY, &player, scene);

    if (not portaling and not plrMotion.noclip) {
      if (plrMotion.velocity.y < 0) {
        if(plrMotion.velocity.y < -HURT_VELOCITY) {
          std::uniform_int_distribution<> dis(0, PLAYER_FALL_SOUND.size()-1);
          player.getComponent<SoundSource>().playSound(
            Environment::getDataDir() + PLAYER_FALL_SOUND[dis(generator)]);
        }
        plrMotion.grounded = true;
      }
      plrMotion.velocity.y = 0;
    }
  } else {
    plrMotion.grounded = false;
  }

  //X collision
  BoxCollider bboxX(Vector3f(pos.x, plrTform.position.y, plrTform.position.z), plrTform.scale);
  if (collidesWithWalls(bboxX)) {
    bool portaling = false;
    portaling = WorldHelper::isPlayerPortalingX(bboxX, &player, scene);
    if (not portaling and not plrMotion.noclip) {
      plrMotion.velocity.x = 0;
    }
  }

  //Z collision
  BoxCollider bboxZ(Vector3f(plrTform.position.x, plrTform.position.y, pos.z), plrTform.scale);
  if (collidesWithWalls(bboxZ)) {
    bool portaling = false;
    portaling = WorldHelper::isPlayerPortalingZ(bboxZ, &player, scene);
    if (not portaling and not plrMotion.noclip) {
      plrMotion.velocity.z = 0;
    }
  }

  for (Entity &e : scene->entities) {
    // Trigger
    if (e.hasComponent<Trigger>()) {
      const Trigger &trigger = e.getComponent<Trigger>();
      const Transform &trTform = e.getComponent<Transform>();
      BoxCollider playerCollider(plrTform.position, plrTform.scale);
      BoxCollider triggerCollider(trTform.position, trTform.scale);

      if (playerCollider.collidesWith(triggerCollider)) {
        if (trigger.type == "radiation") {
          player.getComponent<Health>().harm(.1f);
        } else if (trigger.type == "death") {
          player.getComponent<Health>().kill();
          printf("Death touched\n");
        } else if (trigger.type == "win") {
          if(currentLevel + 1 < mapList.size()) {
            currentLevel++;
          }
          loadScene(mapList[currentLevel]);
          printf("Win touched\n");
        } else if (trigger.type == "map") {
          printf("Map Trigger touched\n");
          throw __FILE__ ": Map trigger type de-implemented, please reimplement";
          //loadScene(trigger.reference);
        } else if (trigger.type == "button") {
          printf("Button touched\n");
        } else {
          printf("Some trigger touched: %s\n", trigger.type.c_str());
        }
      }
    }
  }

  pos = plrTform.position + plrMotion.velocity;

  // Check if the player is moving through a portal
  BoxCollider playerCollider(pos, plrTform.scale);
  for (EntityPair &p : scene->portalPairs) {
    Portal &portal1 = p.first->getComponent<Portal>(),
            &portal2 = p.second->getComponent<Portal>();
    Transform &p1Tform = p.first->getComponent<Transform>(),
              &p2Tform = p.second->getComponent<Transform>();
    if (portal1.open and portal2.open) {
      if (portal1.throughPortal(playerCollider)) {
        plrTform.position = p2Tform.position;
        float rotation = p2Tform.rotation.y - p1Tform.rotation.y + rad(180);
        plrTform.rotation.y += rotation;
        // Transform the velocity of the player
        float velocity = plrMotion.velocity.length();
        plrMotion.velocity = portal2.getDirection() * velocity;
      }
      if (portal2.throughPortal(playerCollider)) {
        plrTform.position = p1Tform.position;
        float rotation = p1Tform.rotation.y - p2Tform.rotation.y + rad(180);
        plrTform.rotation.y += rotation;
        // Transform the velocity of the player
        float velocity = plrMotion.velocity.length();
        plrMotion.velocity = portal1.getDirection() * velocity;
      }
    }
  }

  //Add velocity to the player position
  plrTform.position += plrMotion.velocity;

  //Parent camera to player
  scene->camera.setPerspective();
  int vpWidth, vpHeight;
  renderer->getViewport()->getSize(&vpWidth, &vpHeight);
  scene->camera.setAspect((float)vpWidth / vpHeight);
  scene->camera.setPosition(plrTform.position + Vector3f(0, plrTform.scale.y/2, 0));
  scene->camera.setRotation(plrTform.rotation);

  //Check if the end of the level has been reached
  float distToEnd = (scene->end.getComponent<Transform>().position - plrTform.position).length();
  if (distToEnd < 1) {
    if(currentLevel + 1 < mapList.size()) {
      currentLevel++;
    }
    loadScene(mapList[currentLevel]);
  }

  lastUpdateTime = updateTime;
}
Esempio n. 28
0
TEST(Solution, line)
{
    try {
        const double len = 2.0;
        const size_t div = 2;
        const double h = len / div;
        const double p_out = .0;
        const double q_in = 1e-5;
        const double k = 1e-11;
        const double poro = 0.2;
        MeshLib::IMesh *msh = MeshGenerator::generateLineMesh(len, div, .0, .0, .0);
        GeoLib::Line* line = new GeoLib::Line(Point(0.0, 0.0, 0.0),  Point(len, 0.0, 0.0));
        Geo::PorousMedia pm;
        pm.hydraulic_conductivity = new NumLib::TXFunctionConstant(k);
        pm.porosity = new NumLib::TXFunctionConstant(poro);
        DiscreteSystem dis(msh);
        FemLib::LagrangeFeObjectContainer feObjects(msh);
        Geo::GWFemProblem* pGW = defineGWProblem1D(dis, *line, pm, &feObjects, p_out, q_in);
        TimeStepFunctionConstant tim(.0, 10.0, 10.0);
        pGW->setTimeSteppingFunction(tim);
        // options
        BaseLib::Options options;
        BaseLib::Options* op_lis = options.addSubGroup("LinearSolver");
        op_lis->addOption("solver_type", "CG");
        op_lis->addOption("precon_type", "NONE");
        op_lis->addOptionAsNum("error_tolerance", 1e-10);
        op_lis->addOptionAsNum("max_iteration_step", 500);

        MyFunctionHead f_head;
        f_head.define(&dis, pGW, options);
        f_head.setOutputParameterName(0, "h");
        MyFunctionVelocity f_vel;
        f_vel.define(dis, pm);
        f_vel.setInputParameterName(0, "h");
        f_vel.setOutputParameterName(0, "v");

        SerialStaggeredMethod method(1e-5, 100);
        AsyncPartitionedSystem apart1;
        apart1.setAlgorithm(method);
        apart1.resizeOutputParameter(2);
        apart1.setOutputParameterName(0, "h");
        apart1.setOutputParameterName(1, "v");
        apart1.addProblem(f_head);
        apart1.addProblem(f_vel);
        apart1.connectParameters();

        TimeSteppingController timestepping;
        timestepping.setTransientSystem(apart1);

        //const double epsilon = 1.e-3;
        timestepping.setBeginning(.0);
        timestepping.solve(tim.getEnd());

        const MyNodalFunctionScalar* r_f_head = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("h"));
        const MyIntegrationPointFunctionVector* r_f_v = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("v"));
        const IDiscreteVector<double>* vec_h = r_f_head->getDiscreteData();
        //const FEMIntegrationPointFunctionVector2d::DiscreteVectorType* vec_v = r_f_v->getNodalValues();

        r_f_head->printout();
        r_f_v->printout();

        std::vector<double> expected;
        expected.resize(div+1);
        //const double p_left = 2.e+6;
        const double p_left = p_out + q_in * len / k;
        const double p_right = p_out;
        const double x_len = len;
        for (size_t i=0; i<expected.size(); i++) {
            double x = i*h;
            expected[i] = (p_right-p_left) / x_len * x + p_left;
        }

        ASSERT_DOUBLE_ARRAY_EQ(&expected[0], &(*vec_h)[0], vec_h->size());

    } catch (const char* e) {
        std::cout << "***Exception caught! " << e << std::endl;
    }

}
Esempio n. 29
0
	void
	super_overhang_world_generator::decorate (world& wr, chunk *out, int cx, int cz)
	{
		std::minstd_rand rnd (this->gen_seed + cx * 1917 + cz * 3947);
		std::uniform_int_distribution<> dis (0, 512);
		std::uniform_int_distribution<> grass_dis (0, 20);
		std::uniform_int_distribution<> tree_dis (0, 256);
		std::uniform_int_distribution<> waterfall_dis (0, 1000);
		
		int id, xx, zz;
		for (int x = 0; x < 16; ++x)
			for (int z = 0; z < 16; ++z)
				{
					out->set_biome (x, z, BI_EXTREME_HILLS);
					
					int depth = 0;
					int y = 150;
					for (; y > 30; --y)
						{
							id = out->get_id (x, y, z);
							if (id == BT_STONE)
								{
									if (depth == 0)
										{
											if (y == 50)
												out->set_id (x, y, z, BT_SAND);
											else
												out->set_id (x, y, z, BT_GRASS);
											if (y > 50)
												{
													if (y >= 64 && tree_dis (rnd) > 253)
														this->gen_trees.generate (wr, (cx << 4) | x, y + 1, (cz << 4) | z);
													else if (tree_dis (rnd) > 240)
														out->set_id (x, y + 1, z, BT_DANDELION);
													else if (grass_dis (rnd) < 8)
														out->set_block (x, y + 1, z, BT_TALL_GRASS, 1);
												}
										}
									else if (depth < 5)
										{
											out->set_id (x, y, z, BT_DIRT);
										}
									
									++ depth;
								}
							else
								{
									if (depth > 5 && out->get_id (x, y + 1, z) == BT_STONE)
										{
											if (dis (rnd) == 0)
												out->set_id (x, y + 1, z, BT_GLOWSTONE_BLOCK);
											else
												{
													// try for a waterfall
													bool waterfall = false;
													int h = 0;
													for (int yy = y - 1; yy >= 0; --yy)
														{
															int id = out->get_id (x, yy, z);
															if (id != BT_AIR)
																{
																	if (id == BT_WATER)
																		{
																			waterfall = true;
																			h = y - yy;
																		}
																	break;
																}
														}
										
													if (waterfall && h > 10 && waterfall_dis (rnd) < 3)
														{
															// spawn waterfall
															for (int i = -2; i < h; ++i)
																out->set_block (x, y - i, z, BT_WATER, 8);
														}
												}
										}
									
									depth = 0;
								}
						}
				}
	}
Esempio n. 30
0
int main(int argc, char *argv[]) {


    for(int i = 1; i < argc; ++i) {
        const char *const arg = argv[i];
        if(strcmp(arg, "--first-is-letter") == 0) {
            first_is_letter = true;
        } else if(strcmp(arg, "--mixed-case") == 0) {
            use_mixed_case = true;
        } else if(strcmp(arg, "--include-digits") == 0) {
            use_numbers = true;
        } else if(strcmp(arg, "--help") == 0) {
            usage(argv[0]);
        } else if(strcmp(arg, "--count") == 0) {
            if(i == (argc - 1)) {
                usage(argv[0]);
            }
            count = atoi(argv[++i]);
            assert(count > 0);
        } else if(strcmp(arg, "--length") == 0) {
            if(i == (argc - 1)) {
                usage(argv[0]);
            }
            length = atoi(argv[++i]);
            assert(length > 0);

        } else if(strcmp(arg, "--max-punctuation") == 0) {
            if(i == (argc - 1)) {
                usage(argv[0]);
            }
            max_punctuation = atoi(argv[++i]);
        } else {
            usage(argv[0]);
        }

    }

    const char alphabet_l[]  = "abcdefghijklmnopqrstuvwxyz";
    const char alphabet_h[]  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const char digits[]      = "0123456789";
    //const char punctuation[] = "!@#$%^&*()_-=+{[}]:;\"'<,>.?/`~|\\";
    const char punctuation[] = "%&_?#=-";


    // similar
    // i, l, o, 1, 0, I

    std::string set;
    set.append(punctuation);
    set.append(alphabet_l);

    if(use_mixed_case) {
        set.append(alphabet_h);
    }

    if(use_numbers) {
        set.append(digits);
    }

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, set.size() - 1);

    for(int n = 0; n < count; ++n) {
        int punctuation_count = 0;
        for(int i = 0; i < length; ++i) {
            char ch;
            do {
                do {
                    const int x = dis(gen);
                    ch = set[x];
                } while(i == 0 && first_is_letter && !isalpha(ch));

            } while(!isalnum(ch) && punctuation_count >= max_punctuation);

            if(!isalnum(ch)) {
                ++punctuation_count;
            }

            std::cout << ch;
        }

        std::cout << std::endl;
    }
}