Esempio n. 1
0
void GameGraphics::updateWaterGraphics(Time elapsedTime)
{
	WaterPoint* fromState = waterSourceSelector ? waterPoints1 : waterPoints2;
	WaterPoint* toState = waterSourceSelector ? waterPoints2 : waterPoints1;
	waterSourceSelector = !waterSourceSelector;

	if (randomDisturbanceClock.getElapsedTime().asSeconds() > 0.05)
	{
		currentRandomWaterDisturbancePoint = Vector2i(rand() % RIPPLEMAP_WIDTH, rand() % RIPPLEMAP_HEIGHT);
		randomDisturbanceClock.restart();
	}

	Vector2i raft1InRippleMap = (Vector2i)Vector2f(game->raft1.getPosition().x*RIPPLEMAP_WIDTH / game->map.getSize().x, game->raft1.getPosition().y*RIPPLEMAP_HEIGHT / game->map.getSize().y);
	Vector2i raft2InRippleMap = (Vector2i)Vector2f(game->raft2.getPosition().x*RIPPLEMAP_WIDTH / game->map.getSize().x, game->raft2.getPosition().y*RIPPLEMAP_HEIGHT / game->map.getSize().y);

	for (int y = 0; y < RIPPLEMAP_HEIGHT; y++)
	{
		for (int x = 0; x < RIPPLEMAP_WIDTH; x++)
		{
			int mapX = x*game->map.getSize().x / RIPPLEMAP_WIDTH; 
			int mapY = y*game->map.getSize().y / RIPPLEMAP_HEIGHT;
			int index = y*RIPPLEMAP_WIDTH + x;

			if (raft1InRippleMap == Vector2i(x, y) || raft2InRippleMap == Vector2i(x, y))
			{
				toState[index].height = -0.3f;
				toState[index].velocity = 0.0;
			}
			else if (game->map.getTile(mapX, mapY)->type == TileType::Land)
			{
				toState[index].height = toState[index].velocity = 0;
			}
			else if(Vector2i(x,y)==currentRandomWaterDisturbancePoint)
			{
				toState[index].height = 0.4f;
				toState[index].velocity = 0.0f;
			}
			else
			{
				float sum = 0;
				int neighbourCount = 0;
				for (int deltaY = -1; deltaY <= 1; deltaY++)
				{
					for (int deltaX = -1; deltaX <= 1; deltaX++)
					{
						int neighbourX = x + deltaX;
						int neighbourY = y + deltaY;
						int neighbour_mapPointX = neighbourX*game->map.getSize().x / RIPPLEMAP_WIDTH;
						int neighbour_mapPointY = neighbourY*game->map.getSize().y / RIPPLEMAP_HEIGHT;
						if (neighbourX < 0 || neighbourX >= RIPPLEMAP_WIDTH || neighbourY < 0 || neighbourY >= RIPPLEMAP_HEIGHT || (neighbourX == x && neighbourY == y)) continue;
						sum += fromState[neighbourY * RIPPLEMAP_WIDTH + neighbourX].height;
						neighbourCount++;
					}
				}

				float average = sum / (float)neighbourCount;
				float force = -450.0f*(fromState[index].height - average) - 0.13f*fromState[index].velocity;

				toState[index].velocity = fromState[index].velocity + force*elapsedTime.asSeconds();
				toState[index].height = fromState[index].height + toState[index].velocity*elapsedTime.asSeconds();
				/*if (toState[index].height > 1) toState[index].height = 1;
				if (toState[index].height<-1) toState[index].height = -1;*/
			}

			int max = 160;
			int val = (int)(max / 2 + toState[index].height*max / 2);
			if (val > max) val = max;
			if (val < 0) val = 0;
			waterImage.setPixel(x, y, Color((max - val) / 2, max - val, 255 - 150 * val / max, 255));
		}
	}
	waterTexture.loadFromImage(waterImage);
	waterSprite.setTexture(waterTexture);
}
void
nest::poisson_generator_ps::event_hook( DSSpikeEvent& e )
{
  // get port number
  const port prt = e.get_port();

  // we handle only one port here, get reference to vector elem
  assert( 0 <= prt && static_cast< size_t >( prt ) < B_.next_spike_.size() );

  // obtain rng
  librandom::RngPtr rng = net_->get_rng( get_thread() );

  // introduce nextspk as a shorthand
  Buffers_::SpikeTime& nextspk = B_.next_spike_[ prt ];

  if ( nextspk.first.is_neg_inf() )
  {
    // need to initialize relative to t_min_active_
    // first spike is drawn from backward recurrence time to initialize the process in equilibrium.
    // In the case of the Poisson process with dead time, this has two domains:
    // one with uniform probability (t<dead_time) and one
    // with exponential probability (t>=dead_time).
    // First we draw a uniform number to choose the case according to the associated probability
    // mass.
    // If dead_time==0 we do not want to draw addtional random numbers (keeps old functionality).

    double spike_offset = 0;

    if ( P_.dead_time_ > 0 and rng->drand() < P_.dead_time_ * P_.rate_ / 1000.0 )
    {
      // uniform case: spike occurs with uniform probability in [0, dead_time].
      spike_offset = rng->drand() * P_.dead_time_;
    }
    else
    {
      // exponential case: spike occurs with exponential probability in [dead_time, infinity]
      spike_offset = V_.inv_rate_ms_ * V_.exp_dev_( rng ) + P_.dead_time_;
    }

    // spike_offset is now time from t_min_active_ til first spike.
    // Split into stamp+offset, then add t_min_active.
    nextspk.first = Time::ms_stamp( spike_offset );
    nextspk.second = nextspk.first.get_ms() - spike_offset;
    nextspk.first += V_.t_min_active_;
  }

  // as long as there are spikes in active period, emit and redraw
  while ( nextspk.first <= V_.t_max_active_ )
  {
    // std::cerr << nextspk.first << '\t' << nextspk.second << '\n';
    e.set_stamp( nextspk.first );
    e.set_offset( nextspk.second );
    e.get_receiver().handle( e );

    // Draw time of next spike
    // Time of spike relative to current nextspk.first stamp
    const double new_offset =
      -nextspk.second + V_.inv_rate_ms_ * V_.exp_dev_( rng ) + P_.dead_time_;

    if ( new_offset < 0 )           // still in same stamp
      nextspk.second = -new_offset; // stamps always 0 < stamp <= h
    else
    {
      // split into stamp and offset, then add to old stamp
      const Time delta_stamp = Time::ms_stamp( new_offset );
      nextspk.first += delta_stamp;
      nextspk.second = delta_stamp.get_ms() - new_offset;
    }
  }
  // std::cerr << "********************************\n";
}
void
MinstrelWifiManager::UpdateStats (MinstrelWifiRemoteStation *station)
{
  if (Simulator::Now () <  station->m_nextStatsUpdate)
    {
      return;
    }

  if (!station->m_initialized)
    {
      return;
    }
  NS_LOG_DEBUG ("Updating stats=" << this);

  station->m_nextStatsUpdate = Simulator::Now () + m_updateStats;

  Time txTime;
  uint32_t tempProb;

  for (uint32_t i = 0; i < m_nsupported; i++)
    {

      /// calculate the perfect tx time for this rate
      txTime = m_minstrelTable[i].perfectTxTime;

      /// just for initialization
      if (txTime.GetMicroSeconds () == 0)
        {
          txTime = Seconds (1);
        }

      NS_LOG_DEBUG ("m_txrate=" << station->m_txrate <<
                    "\t attempt=" << m_minstrelTable[i].numRateAttempt <<
                    "\t success=" << m_minstrelTable[i].numRateSuccess);

      /// if we've attempted something
      if (m_minstrelTable[i].numRateAttempt)
        {
          /**
           * calculate the probability of success
           * assume probability scales from 0 to 18000
           */
          tempProb = (m_minstrelTable[i].numRateSuccess * 18000) / m_minstrelTable[i].numRateAttempt;

          /// bookeeping
          m_minstrelTable[i].successHist += m_minstrelTable[i].numRateSuccess;
          m_minstrelTable[i].attemptHist += m_minstrelTable[i].numRateAttempt;
          m_minstrelTable[i].prob = tempProb;

          /// ewma probability (cast for gcc 3.4 compatibility)
          tempProb = static_cast<uint32_t> (((tempProb * (100 - m_ewmaLevel)) + (m_minstrelTable[i].ewmaProb * m_ewmaLevel) ) / 100);

          m_minstrelTable[i].ewmaProb = tempProb;

          /// calculating throughput
          m_minstrelTable[i].throughput = tempProb * (1000000 / txTime.GetMicroSeconds ());

        }

      /// bookeeping
      m_minstrelTable[i].prevNumRateAttempt = m_minstrelTable[i].numRateAttempt;
      m_minstrelTable[i].prevNumRateSuccess = m_minstrelTable[i].numRateSuccess;
      m_minstrelTable[i].numRateSuccess = 0;
      m_minstrelTable[i].numRateAttempt = 0;

      /// Sample less often below 10% and  above 95% of success
      if ((m_minstrelTable[i].ewmaProb > 17100) || (m_minstrelTable[i].ewmaProb < 1800))
        {
          /**
           * retry count denotes the number of retries permitted for each rate
           * # retry_count/2
           */
          m_minstrelTable[i].adjustedRetryCount = m_minstrelTable[i].retryCount >> 1;
          if (m_minstrelTable[i].adjustedRetryCount > 2)
            {
              m_minstrelTable[i].adjustedRetryCount = 2;
            }
        }
      else
        {
Esempio n. 4
0
void Sound::setPlayingOffset(Time timeOffset)
{
    alCheck(alSourcef(m_source, AL_SEC_OFFSET, timeOffset.asSeconds()));
}
Esempio n. 5
0
int
main(int argc, char* argv[]){
try{

  if (argc==1) usage();
  Options O = parse_options(&argc, &argv, options, 3);
  if (O.exists("help")) { usage(); return 1;}


  if (argc<2) {usage();  return 1;}
  const char * ifile = argv[0];
  const char * ofile = argv[1];

  // create map
  vmap::world W=vmap::read(ifile);
  if (W.size()==0) throw Err() << "Error: empty map\n";

  // set geometry if no --wgs_geom, --wgs_brd, --geom,
  //  --nom, --google option exists
  if (O.exists("nobrd")) W.brd.clear();
  if (!O.exists("geom") && !O.exists("wgs_geom") &&
      !O.exists("nom") && !O.exists("google") &&
      !O.exists("wgs_brd")){

    if (W.brd.size()>2) O.put("wgs_brd", W.brd);
    else O.put("wgs_geom", W.range());
  }

  if (!O.exists("rscale")) O.put("rscale", W.rscale);

  g_map ref = mk_ref(O);
  ref.comm=W.name;

  // process other options

  double dpi=O.get<double>("dpi", 300);

  // set margins
  int tm=0, bm=0, lm=0, rm=0;
  if (O.get<int>("draw_name", 0) ||
      O.get<int>("draw_date", 0) ||
      (O.get<string>("draw_text") != "")) {
    tm=dpi/3;
    bm=lm=rm=dpi/6;
  }
  int grid_labels = O.get<int>("grid_labels", 0);
  if (grid_labels){
    bm+=dpi/6;
    tm+=dpi/6;
    rm+=dpi/6;
    lm+=dpi/6;
  }

 // modify vmap
  vmap::join_labels(W);
  vmap::move_pics(W);


  // calculate picture range, create Image
  dRect rng = ref.border.range();
  rng.x = rng.y = 0;
  rng.w+=lm+rm; if (rng.w<0) rng.w=0;
  rng.h+=tm+bm; if (rng.h<0) rng.h=0;
  ref+=dPoint(lm,tm);
  cerr
     << "  scale  = 1:" << int(W.rscale) << "\n"
     << "  dpi    = " << dpi << "\n"
     << "  image = " << int(rng.w) << "x" << int(rng.h)<< "\n";
  iImage img(rng.w, rng.h);

  convs::map2wgs cnv(ref);
  if (W.size() == 0) cerr << "warning: no objects\n";

  GObjVMAP R(&W, O);

  R.set_ref(ref);
  R.draw(img, dPoint(0,0));

  CairoWrapper cr(img);
  if (O.get<int>("draw_name", 0))
    cr->render_text(W.name.c_str(), dPoint(dpi/5,dpi/15), 0, 0, 18, 14, dpi, 0, 2);
  if (O.get<int>("draw_date", 0)){
    Time t; t.set_current();
    cr->render_text(t.date_str().c_str(), dPoint(dpi/30,dpi), -M_PI/2, 0, 18, 10, dpi, 2, 2);
  }
  if (O.get<string>("draw_text") != ""){
    cr->render_text(O.get<string>("draw_text").c_str(), dPoint(dpi/5,rng.h-dpi/30), 0, 0, 18, 10, dpi, 0, 0);
  }

  //*******************************
  image_r::save(img, ofile);

  string map = O.get<string>("map");
  if (map!=""){
    g_map M = ref;
    M.file = ofile;
    if (W.brd.size()>2) M.border=cnv.line_bck(W.brd);
    M.border.push_back(*M.border.begin());
    M.border=generalize(M.border,1,-1); // 1pt accuracy
    M.border.resize(M.border.size()-1);
    try {oe::write_map_file(map.c_str(), M);}
    catch (Err e) {cerr << e.get_error() << endl;}
  }


  //*******************************
}
catch (Err e) {
  cerr << e.get_error() << endl;
  return 1;
}
return 0;
}
// Construct from components
dsmcGeneralBoundary::dsmcGeneralBoundary
(
    Time& t,
    const polyMesh& mesh,
    dsmcCloud& cloud,
    const dictionary& dict
)
:
    mesh_(refCast<const fvMesh>(mesh)),
    cloud_(cloud),
    boundaryDict_(dict.subDict("generalBoundaryProperties")),
//     timeDict_(boundaryDict_.subDict("timeProperties")),
//     time_(t, timeDict_),
    patchName_(boundaryDict_.lookup("patchName")),
    patchId_(0),
    faces_(),
    nFaces_(0),
    patchSurfaceArea_(0.0),
    cells_(),
    density_(0.0),
    velocity_(vector::zero),
    temperature_(0.0),
    densities_(),
    velocities_(),
    temperatures_(),
    writeInTimeDir_(true),
    writeInCase_(true)
{
    //- confirm that the patch exists on the mesh

    patchId_ = mesh_.boundaryMesh().findPatchID(patchName_);

    if(patchId_ == -1)
    {
        FatalErrorIn("atomisticPatchBoundary::atomisticPatchBoundary()")
            << "Cannot find patch: " << patchName_ << nl << "in: "
            << t.system()/"boundariesDict"
            << exit(FatalError);
    }

    const polyPatch& patch = mesh.boundaryMesh()[patchId_];

//     Pout << "patch name: " << patchName_ << ", patch size: " << patch.size() << endl;

    //- initialise data members
    faces_.setSize(patch.size());
    cells_.setSize(patch.size());

    //- loop through all faces and set the boundary cells
    //- no conflict with parallelisation because the faces are unique

    for(label i = 0; i < patch.size(); i++)
    {
        label globalFaceI = patch.start() + i;

        faces_[i] = globalFaceI;
        cells_[i] = patch.faceCells()[i];
        nFaces_++;
        patchSurfaceArea_ += mag(mesh_.faceAreas()[globalFaceI]);
    }

    if(Pstream::parRun())
    {
        reduce(patchSurfaceArea_, sumOp<scalar>());
    }
}
Esempio n. 7
0
SparseMatrix3D *Application::transform(int xID,int yID)
{
  bool useDelta=false;//true;
  cout<<"transforming "<<taxonName[xID]<<":"<<taxonName[yID]<<endl;
  Time timer;
  timer.startCounting();
  PhylogenyNode *x=nodes[xID], *y=nodes[yID];
  if(x->getNodeType()!=LEAF_NODE || y->getNodeType()!=LEAF_NODE) return NULL;
  int Lx=lengths[xID], Ly=lengths[yID];
  Array3D<float> M(Lx+1,Ly+1,3);
  M.setAllTo(LOG_0);

  // Match states:
  for(int i=1 ; i<=Lx ; ++i) {
    Array1D< Vector<float> > sums(Ly+1);
    for(int zID=0 ; zID<numLeaves ; ++zID) {
      PhylogenyNode *z=nodes[zID];
      int Lz=lengths[zID];
      float delta=useDelta ? 
	tree->getSpannedDistance(x->getID(),y->getID(),z->getID()) : 0;
      SparseMatrix3D &Mxz=*matrices[xID][zID], &Mzy=*matrices[zID][yID];
      EntryList &row=Mxz(i,PHMM_MATCH);
      EntryList::iterator cur=row.begin(), end=row.end();
      for(; cur!=end ; ++cur) {
	Entry &e1=*cur;
	int k=e1.y;
	float v1=e1.value;
	EntryList &col=Mzy(k,PHMM_MATCH);
	EntryList::iterator cur=col.begin(), end=col.end();
	for(; cur!=end ; ++cur) {
	  Entry &e2=*cur;
	  int j=e2.y;
	  float v2=e2.value;
	  float product=v1+v2-delta;
	  sums[j].push_back(product);
	}
      }
    }
    for(int j=0 ; j<=Ly ; ++j)
      M[i][j][PHMM_MATCH]=sumLogProbs(sums[j])-numLeaves;
  }
  //cout<<M<<endl;

  // Insertion states:
  for(int i=0 ; i<=Lx ; ++i) {
    Array1D< Vector<float> > sums(Ly+1);
    for(int zID=0 ; zID<numLeaves ; ++zID) {
      PhylogenyNode *z=nodes[zID];
      int Lz=lengths[zID];
      float delta=useDelta ? 
	tree->getSpannedDistance(x->getID(),y->getID(),z->getID()) : 0;
      SparseMatrix3D &Mxz=*matrices[xID][zID], &Mzy=*matrices[zID][yID];
      EntryList &row=Mxz(i,PHMM_INSERT);
      EntryList::iterator cur=row.begin(), end=row.end();
      for(; cur!=end ; ++cur) {
	Entry &e1=*cur;
	int k=e1.y;
	float v1=e1.value;
	EntryList &col=Mzy(k,PHMM_MATCH);
	EntryList::iterator cur=col.begin(), end=col.end();
	for(; cur!=end ; ++cur) {
	  Entry &e2=*cur;
	  int j=e2.y;
	  float v2=e2.value;
	  float product=v1+v2-delta;
	  sums[j].push_back(product);
	}
      }
    }
    for(int j=0 ; j<=Ly ; ++j) 
      M[i][j][PHMM_INSERT]=sumLogProbs(sums[j])-numLeaves;
  }

  // Deletion states:
  for(int i=0 ; i<=Lx ; ++i) {
    Array1D< Vector<float> > sums(Ly+1);
    for(int zID=0 ; zID<numLeaves ; ++zID) {
      PhylogenyNode *z=nodes[zID];
      int Lz=lengths[zID];
      float delta=useDelta ? 
	tree->getSpannedDistance(x->getID(),y->getID(),z->getID()) : 0;
      SparseMatrix3D &Mxz=*matrices[xID][zID], &Mzy=*matrices[zID][yID];
      EntryList &row=Mxz(i,PHMM_MATCH);
      EntryList::iterator cur=row.begin(), end=row.end();
      for(; cur!=end ; ++cur) {
	Entry &e1=*cur;
	int k=e1.y;
	float v1=e1.value;
	EntryList &col=Mzy(k,PHMM_DELETE);
	EntryList::iterator cur=col.begin(), end=col.end();
	for(; cur!=end ; ++cur) {
	  Entry &e2=*cur;
	  int j=e2.y;
	  float v2=e2.value;
	  float product=v1+v2-delta;
	  sums[j].push_back(product);
	}
      }
    }
    for(int j=0 ; j<=Ly ; ++j) 
      M[i][j][PHMM_DELETE]=sumLogProbs(sums[j])-numLeaves;
  }
  //cout<<M<<endl;
  timer.stopCounting();
  cout<<timer.elapsedTime()<<endl;
  if(useDelta) {
    SparseMatrix3D *newM=new SparseMatrix3D(M,0.0);
    normalize(*newM);
    SparseMatrix3D *newerM=new SparseMatrix3D(*newM,threshold);
    delete newM;
    return newerM;
  }	
  SparseMatrix3D *newM=new SparseMatrix3D(M,threshold);

  {//###
    normalize(*newM);
    SparseMatrix3D *newerM=new SparseMatrix3D(*newM,threshold);
    delete newM;
    return newerM;
  }//###

  return newM;
}
Esempio n. 8
0
 friend bool operator==(const Time& lhs, const Time& rhs) { return lhs.value() == rhs.value(); }
Esempio n. 9
0
 friend bool operator<(const Time& lhs, const Time& rhs) { return lhs.value() < rhs.value(); }
Esempio n. 10
0
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	HDC hdc,hdcMem;
	PAINTSTRUCT ps;

	TCHAR buf[128];

	//窗口的宽、高
	static int cxClient,cyClient;
	//显示器的宽和高
	static int screenX,screenY;
	//实例代号
	static HINSTANCE hInstance;

	//位图的相关句柄
	static HBITMAP hOldmap,hBitmap1,hcloudBit,hcloudMakBit,hgameoverBit,hgameoverMask;

	//位图的高和宽
	static int cx,cy,cx1,cy1,cx2,cy2;

	BITMAP  bitmap;

	int temp,temp1;
	
	static boolean isPuase=false;

	//两个变量来处理数字的变化

	static int first=6,second=0;

	static int count=60;

	static boolean isStart=false,isEnd=false;


	//画笔
	static HPEN  myPen;

	//纪录跳的次数(最多可以连续3次)
	static int jump_times=0;

	switch (message)
	{
	//按键处理
	case WM_KEYDOWN:
		
		if (isStart)
		{
			hdc=GetDC(hwnd);
			switch(wParam)
			{

			case VK_SPACE:

				if (!isPuase)
				{
					GameManagement::pauseMyGame(hwnd);
					isPuase=true;
				}else{
					myCurrentTime--;
					GameManagement::startMyTimer(hwnd);
					
					isPuase=false;
				}

				break;

			case VK_LEFT:

				marry.move(0);
				marry.isMoved=true;

				break;
			case VK_RIGHT:

				marry.move(2);
				marry.isMoved=true;


				break;
			}
			ReleaseDC(hwnd,hdc);
		}
		
		return 0;


	case WM_KEYUP:
		if (isStart)
		{
			switch(wParam)
			{
			case VK_LEFT:
			case 0x61:
			case 0x41:
				//marry.isMoved=false;
				marry.SetSpeed(0);
				break;
			/*case 0x77:
			case 0x57:
				marry.isJumped=false;
				break;*/
			case VK_RIGHT:
			case 0x64:
			case 0x44:
				//marry.isMoved=false;
				marry.SetSpeed(0);
				break;
			case 0x77:
			case 0x57:
				break;
			}
		}

		return 0;
	
	case WM_CHAR:
		if (isStart)
		{
			hdc=GetDC(hwnd);
			switch(wParam)
			{
			//a、A为向左
			case 0x61:
			case 0x41:
				
				marry.move(0);
				marry.isMoved=true;

				break;
			//w、W向上
			/*case 0x77:
			case 0x57:*/
			case 0x5A:
			case 0x7A:
				{
					//TCHAR buf1[50];
					
					//mciSendString(TEXT("stop guanghao"),buf,lstrlen(buf),NULL);
					PlayMySound::playJump(buf);
					
					hdc=GetDC(hwnd);
					
					marry.move(1);
					marry.isJumped=true;
					ReleaseDC(hwnd,hdc);
					
				}
				break;

			//d、D向右
			case 0x64:
			case 0x44:
				marry.move(2);
				marry.isMoved=true;
				break;
			}
			ReleaseDC(hwnd,hdc);
		}
		
		return 0;

	case WM_TIMER:
		switch(wParam)
		{
		//检测跳跃
		case ID_Timer7:
			hdc=GetDC(hwnd);
			if (marry.GetAllowedStatus())
			{
				if (marry.isJumped)
				{
					marry.Jump(hdc,hBitmap1);
				}else if (marry.isMoved)
				{
					if (marry.GetSpeed()!=0)
					{
						marry.testMove(hdc,hBitmap1);
					}

				}
			}
			ReleaseDC(hwnd,hdc);
			break;
		//让时钟动起来
		case ID_Timer2:
			if (myCurrentTime>0)
			{
				hdc=GetDC(hwnd);
				myCurrentTime--;
				myTime.Draw(myCurrentTime,hdc);
				ReleaseDC(hwnd,hdc);
			}
			else
			{
				//PlaySound(TEXT("./sound/gameover.wav"),NULL,SND_FILENAME|SND_ASYNC|SND_LOOP);
				mciSendString(TEXT("close adu"),buf,lstrlen(buf),NULL);
				PlayMySound::playGameover(buf);
				mRecord.SetMaxRecord(myCurrentRcd);
				isStart=false;
				isEnd=true;
				GameManagement::stopMyGame(hwnd);
				//KillTimer(hwnd,ID_Timer7);
				//KillTimer(hwnd,ID_Timer8);
				myCurrentTime=0;
				InvalidateRect(hwnd,NULL,FALSE);

			}
			break;

		//金币下落
		case ID_Timer3:

			hdc=GetDC(hwnd);
	
			for (i=0;i<8;i++)
			{
				for (k=0;k<3;k++)
				{
					
					temp1=dollar[i][k].IsTouched(marry.x,marry.y,marry.cx);
					if (dollar[i][k].y+dollar[i][k].speed<=430&&temp1==0)
					{
						if (dollar[i][k].isAlived())
						{
							dollar[i][k].Change(hdc,hBitmap1);
							if (dollar[i][k].y>=270)
							{
								temp=(k+1)%3;
								dollar[i][temp].setAlive(true);
								//deadNumbers[i]--;
							}
							
						}
					    //这里还有待改善,当三个都被我吃掉后,状态都为false
						//则不会重新唤醒一个新的金币,后续中需要更正这个bug
						//初步想法:用一个变量来存储死的数目,当达到3的时候,会唤醒第一个
						
					}else
					{
						if (temp1!=0)
						{
							if (temp1==5)
							{

								PlayMySound::playJiashi(buf);

								KillTimer(hwnd,ID_Timer2);
								SetTimer(hwnd,ID_Timer6,7000,NULL);
							}else if (temp1==1||temp1==-10)
							{
								if (temp1==1)
								{

									PlayMySound::playJinBi(buf);
								}else if (temp1==-10)
								{

									PlayMySound::playZhaDan(buf);
								}
								myCurrentRcd+=temp1;
								if (myCurrentRcd<=0)
								{
									myCurrentRcd=0;
								}
								mRecord.Change(hdc,myCurrentRcd,hBitmap1);
							}else if (temp1==3)
							{
								//jasu=true;
								//设置不可以移动,出现眩晕症状
								marry.setIsAllowed(false);
								marry.Cachu(hdc,hBitmap1);
                                marry.x=marry.x;
								marry.y=470;
								PlayMySound::playXuanyun(buf);
								marry.Draw(hdc);
								SetTimer(hwnd,ID_Timer9,3000,NULL);
							}

						}
						
						dollar[i][k].Cachu(hdc,hBitmap1);
						dollar[i][k].setAlive(false);
						
						dollar[i][k].Set(150+i*75,100+30*((i/2)%2),1,0);
					    //dollar[i][k].SetJiasu(jasu);
						dollar[i][k].SetType(0);
						
					}
					
				}
			}
			
			ReleaseDC(hwnd,hdc);

			break;

		//产生炸弹
		case ID_Timer4:
			srand((int)time(0));

			temp=rand()%160;
			temp=temp/20;

			for (k=0;k<3;k++)
			{
				if (!dollar[temp][k].isAlived())
				{
					dollar[temp][k].SetType(1);

					break;
				}
			}

			temp1=rand()%80;
			temp1=temp1/10;
			if (temp1!=temp)
			{
				for (k=0;k<3;k++)
				{
					if (!dollar[temp1][k].isAlived())
					{
						dollar[temp1][k].SetType(1);

						break;
					}
				}
			}
			
			break;

		//产生加时时钟
		case ID_Timer5:
			srand((int)time(0));
			temp=rand()%160;
			temp=temp/20;

			for (k=0;k<3;k++)
			{
				if (!dollar[temp][k].isAlived())
				{
					dollar[temp][k].SetType(2);
					break;
				}
			}

			
			
			break;


		//时间暂停
		case ID_Timer6:
			SetTimer(hwnd,ID_Timer2,1000,NULL);
			KillTimer(hwnd,ID_Timer6);
			break;

		//产生加速
		case ID_Timer8:
			
			srand((int)time(0));
			temp=rand()%160;
			temp=temp/20;

			for (k=0;k<3;k++)
			{
				if (!dollar[temp][k].isAlived())
				{
					dollar[temp][k].SetType(3);
					break;
				}
			}

			break;
		//恢复原来的速度
		case ID_Timer9:

			KillTimer(hwnd,NULL);
			//jasu=false;

			marry.setIsAllowed(true);

			//变为原来的速度
			break;
		}

		return 0;

	case WM_COMMAND:
		switch(LOWORD(wParam))
		{
		//最高纪录:
		case ID_40010:
			hDlgMaxRecord=CreateDialog(hInstance,MAKEINTRESOURCE(IDD_DIALOG4),hwnd,MaxRecordProc);
			ShowWindow(hDlgMaxRecord,SW_SHOW);
			//hDlgMaxRecord=CreateDialog(hInstance,TEXT("最高纪录"),hwnd,MaxRecordProc);

			break;

		//开始游戏
		case ID_40001:
		case ID_MENUITEM40001:

			if (!isStart)
			{
				hdc=GetDC(hwnd);
				
				myCurrentRcd=0;
				myCurrentTime=60;
				InvalidateRect(hwnd,NULL,FALSE);
				mciSendString(TEXT("close gameover"),buf,lstrlen(buf),NULL);
				//mciSendString(TEXT("close adu"),buf,lstrlen(buf),NULL);
				PlayMySound::playBkg(buf);
				GameManagement::startMyGame(hwnd,hdc,dollar);
				
				marry.setIsAllowed(true);
				
				ReleaseDC(hwnd,hdc);
				isStart=true;
				isEnd=false;
			}else
			{
				//给出一个温馨的提示,程序正在运行
				DialogBox(hInstance,MAKEINTRESOURCE(IDD_DIALOG3),hwnd,AboutProc);
			}

			break;

		//暂停游戏
		case ID_40002:
		case ID_MENUITEM40002:
			if (isStart)
			{
				GameManagement::pauseMyGame(hwnd);
				isPuase=true;
				
			}
			break;

		//重新开始
		case ID_40003:
		case ID_MENUITEM40003:
			
			mciSendString(TEXT("close gameover"),buf,lstrlen(buf),NULL);
			PlayMySound::playBkg(buf);

			GameManagement::stopMyGame(hwnd);
			myCurrentRcd=0;
			myCurrentTime=60;
			InvalidateRect(hwnd,NULL,FALSE);

			hdc=GetDC(hwnd);
			GameManagement::startMyGame(hwnd,hdc,dollar);

			marry.setIsAllowed(true);
			ReleaseDC(hwnd,hdc);

			isStart=true;
			isEnd=false;
			break;

		//退出游戏
		case ID_40004:
		case ID_MENUITEM40004:

			//exit(0);
			SendMessage(hwnd,WM_CLOSE,0,0);
			break;

		//保存游戏进度
		case ID_40005:
		case ID_MENUITEM40005:

			break;

		//恢复游戏进度
		case ID_40006:
		case ID_MENUITEM40006:

			break;

		//游戏简介
		case ID_40007:
		case ID_MENUITEM40007:

			DialogBox(hInstance,MAKEINTRESOURCE(IDD_DIALOG2),hwnd,AboutProc);

			break;
		case ID_40008:
		//关于
		case ID_MENUITEM40008:
			
			DialogBox(hInstance,MAKEINTRESOURCE(IDD_DIALOG1),hwnd,AboutProc);

			break;
		}

		return 0;
	
	case WM_CREATE:
		{
			hdc=GetDC(hwnd);

			hInstance=((LPCREATESTRUCT)lParam)->hInstance;


			//PlayMySound::playBkg(buf);

			
			//背景
			hBitmap1=LoadBitmap(hInstance,TEXT("Background"));
			GetObject(hBitmap1,sizeof(BITMAP),&bitmap);
			cx=bitmap.bmWidth;
			cy=bitmap.bmHeight;


			hgameoverBit=LoadBitmap(hInstance,TEXT("gameover"));
			hgameoverMask=LoadBitmap(hInstance,TEXT("gameovermask"));

			//加载云图
			hcloudBit=LoadBitmap(hInstance,TEXT("clouds"));
			GetObject(hcloudBit,sizeof(BITMAP),&bitmap);
			cx2=bitmap.bmWidth;
			cy2=bitmap.bmHeight;

			hcloudMakBit=LoadBitmap(hInstance,TEXT("clouds_mask"));

			

			//加载金币
			for (i=0;i<8;i++)
			{
				for (k=0;k<3;k++)
				{
					dollar[i][k].loadMyBitmap(hInstance);
				}
			}


			//加载小人
			marry.loadMyBitmap(hInstance);

			//加载纪录
			mRecord.loadMybitmap(hInstance);

			//加载时间
			myCurrentTime=60;
			myTime.loadMyBitmap(hInstance);
			myTime.setHbitmap1(hBitmap1);


			ReleaseDC(hwnd,hdc);
		}
		
		return 0 ;

	case WM_SIZE:
		screenX=GetSystemMetrics(SM_CXSCREEN);
		screenY=GetSystemMetrics(SM_CYSCREEN);

		cxClient=905;
		cyClient=650;

		//将窗口放在显示器的正中央
		MoveWindow(hwnd,(screenX-cxClient)/2,(screenY-cyClient-40)/2,cxClient,cyClient,TRUE);

		return 0 ;

	case WM_PAINT:
		hdc = BeginPaint (hwnd, &ps) ;

		

		hdcMem=CreateCompatibleDC(hdc);
		//加载到内存设备描述表
		hOldmap=(HBITMAP)SelectObject(hdcMem,hBitmap1);

		//背景
		BitBlt(hdc,0,0,cxClient,cyClient,hdcMem,0,0,SRCCOPY);


		if (isEnd)
		{
			SelectObject(hdcMem,hgameoverMask);
			BitBlt(hdc,245,245,410,110,hdcMem,0,0,SRCPAINT);


			SelectObject(hdcMem,hgameoverBit);

			BitBlt(hdc,245,245,410,110,hdcMem,0,0,SRCAND);


			/*BitBlt(hdc,287,170,325,260,hdcMem,0,0,SRCCOPY);*/
			/*TransparentBlt(hdc,245,245,410,110,hdcMem,0,0,410,110,RGB(255,255,255));*/
		}
		

		//画云图
		for (i=0;i<4;i++)
		{
			int addx=150;
			int addy=30;
			if (i==0||i==2)
			{
				SelectObject(hdcMem,hcloudMakBit);
				BitBlt(hdc,100+addx*i,0,cx2,cy2,hdcMem,0,0,SRCPAINT);

				SelectObject(hdcMem,hcloudBit);
				BitBlt(hdc,100+addx*i,0,cx2,cy2,hdcMem,0,0,SRCAND);
			}else
			{
				SelectObject(hdcMem,hcloudMakBit);
				BitBlt(hdc,100+addx*i,addy,cx2,cy2,hdcMem,0,0,SRCPAINT);

				SelectObject(hdcMem,hcloudBit);
				BitBlt(hdc,100+addx*i,addy,cx2,cy2,hdcMem,0,0,SRCAND);

			}
			
		}


		marry.Draw(hdc);

		myTime.Draw(myCurrentTime,hdc);


		//mRecord.Draw(hdc,hBitmap1);
		mRecord.Change(hdc,myCurrentRcd,hBitmap1);

		
		//恢复
		SelectObject(hdcMem,hOldmap);

		DeleteObject(hdcMem);
		
		EndPaint (hwnd, &ps) ;
		return 0 ;

	case WM_DESTROY:

		//释放资源
		DeleteObject(hBitmap1);

		PostQuitMessage (0) ;
		return 0 ;
	}
	return DefWindowProc (hwnd, message, wParam, lParam) ;
}
void Airplane::Handle(ProcessEventArg arg) {    
    Time t = timer.GetElapsedTimeAndReset();
    float dt = t.AsInt()/1000.0;

    Matrix<3,3,float> rotM = box->GetRotationMatrix();

    box->AddForce(rotM *  Vector<3,float>(0,0,1*dt*trottle));

    for (vector<Point*>::iterator itr = points.begin();
         itr != points.end();
         itr++) {
        Point* p = *itr;
        Vector<3,float> speedVec = box->GetSpeed();

        float speed = speedVec.GetLength();
        Vector<3,float> dragVec;


        if (speed > 0.1) 
            dragVec = -speedVec/speed;


        Vector<3,float> normal = Vector<3,float>(0,1,0);
        Vector<3,float> liftVector = (dragVec % normal) % dragVec;

        if (liftVector.IsZero())
            return;

        float liftLen = liftVector.GetLength();
        liftVector.Normalize();

        float dotP = dragVec * normal;
        dotP = fmin(fmax(dotP, -1),1);

        float attackAngel = asin(dotP);
        float rho = 1.2f;    
        float area = 5*5;
        float force = 0.5f * rho * speed * speed * area;
    
        Vector<3,float> forceVec = 
            (liftVector * LiftCoefficient(attackAngel,0) +
             dragVec * DragCoefficient(attackAngel,0)) * force;

        //logger.info << forceVec << logger.end;


        box->AddForce(rotM * forceVec, p->forceIdx );

    }
    


    //box->AddForce(Vector<3,float>(0,lift,0));


    return;

    // Matrix<3,3,float> rotM = box->GetRotationMatrix();

    // //logger.info << speed << logger.end;
    // //speed = rotM*speed;

    // Quaternion<float> q = Quaternion<float>(rotM);

    // Vector<3,float> angles = q.GetEulerAngles();

    // float pitch = -angles[0];

    // //logger.info << "pitch " << pitch << logger.end;

    // float cl = 1;
    
    // float lift = speedVec[2]*cl;

    

    //logger.info << "cl " << cl << logger.end;
    //logger.info << "lift " << lift << logger.end;

    
    // Vector<3,float> old_pos;
    // Quaternion<float> old_rot;    
    // node->GetAccumulatedTransformations(&old_pos, &old_rot);
    
    // node->Move(0,0,0.01*dt*trottle);
            
    // // calc lift
    
    // Vector<3,float> angles = old_rot.GetEulerAngles();
    
    // float pitch = -angles[0];
    
    // float cl = pitch*0.08+0.5;
    // float lift = speed.GetLengthSquared()*cl*.5*2000.0;
    
    // node->Move(0,(lift-9.82)*dt,0);
    // //logger.info << lift << logger.end;
    
    // logger.info << "speed: " << speed.GetLengthSquared()  <<
    // " cl: " << cl << 
    // " pitch: " << pitch << 
    // " lift: " << lift << logger.end;
    
    // // stuff
    
    // Vector<3,float> pos;
    // Quaternion<float> rot;    
    // node->GetAccumulatedTransformations(&pos, &rot);
    
    // // fix down.
    // if (pos[1] < 0) {
    //     node->SetPosition(Vector<3,float>(pos[0],0.0,pos[2]));
    //     node->GetAccumulatedTransformations(&pos, &rot);
    // }
    
    // Vector<3,float> dx = pos-old_pos;
    
    // logger.info << "pos: " << pos << " old_pos: " << old_pos << logger.end;
    
    // speed = dx/dt;
}
Esempio n. 12
0
Time Time::Local()
{
    Time ret;
    ret.local_time();
    return ret;
}
Esempio n. 13
0
void Foam::calcTypes::randomise::calc
(
    const argList& args,
    const Time& runTime,
    const fvMesh& mesh
)
{
    const scalar pertMag = args.argRead<scalar>(2);
    const word fieldName = args[3];

    Random rand(1234567);

    IOobject fieldHeader
    (
        fieldName,
        runTime.timeName(),
        mesh,
        IOobject::MUST_READ
    );

    // Check field exists
    if (fieldHeader.headerOk())
    {
        bool processed = false;

        writeRandomField<vector>
        (
            fieldHeader,
            pertMag,
            rand,
            mesh,
            processed
        );
        writeRandomField<sphericalTensor>
        (
            fieldHeader,
            pertMag,
            rand,
            mesh,
            processed
        );
        writeRandomField<symmTensor>
        (
            fieldHeader,
            pertMag,
            rand,
            mesh,
            processed
        );
        writeRandomField<tensor>
        (
            fieldHeader,
            pertMag,
            rand,
            mesh,
            processed
        );

        if (!processed)
        {
            FatalError
                << "Unable to process " << fieldName << nl
                << "No call to randomise for fields of type "
                << fieldHeader.headerClassName() << nl << nl
                << exit(FatalError);
        }
    }
    else
    {
        Info<< "    No " << fieldName << endl;
    }
}
void
aeif_cond_alpha_multisynapse::update( Time const& origin, const long_t from, const long_t to )
{
  assert( to >= 0 && ( delay ) from < Scheduler::get_min_delay() );
  assert( from < to );
  assert( State_::V_M == 0 );

  for ( long_t lag = from; lag < to; ++lag ) // proceed by stepsize B_.step_
  {
    double t = 0.0; // internal time of the integration period

    if ( S_.r_ > 0 ) // decrease remaining refractory steps if non-zero
      --S_.r_;

    // numerical integration with adaptive step size control:
    // ------------------------------------------------------
    // The numerical integration of the model equations is performed by
    // a Dormand-Prince method (5th order Runge-Kutta method with
    // adaptive stepsize control) as desribed in William H. Press et
    // al., “Adaptive Stepsize Control for Runge-Kutta”, Chapter 17.2
    // in Numerical Recipes (3rd edition, 2007), 910-914.  The solver
    // itself performs only a single NUMERICAL integration step,
    // starting from t and of size B_.IntegrationStep_ (bounded by
    // step); the while-loop ensures integration over the whole
    // SIMULATION step (0, step] of size B_.step_ if more than one
    // integration step is needed due to a small integration stepsize;
    // note that (t+IntegrationStep > step) leads to integration over
    // (t, step] and afterwards setting t to step, but it does not
    // enforce setting IntegrationStep to step-t; this is of advantage
    // for a consistent and efficient integration across subsequent
    // simulation intervals.

    double_t& h = B_.IntegrationStep_; // numerical integration step
    double_t& tend = B_.step_;         // end of simulation step

    const double_t& MAXERR = P_.MAXERR; // maximum error
    const double_t& HMIN = P_.HMIN;     // minimal integration step

    double_t err;
    double_t t_return = 0.0;

    while ( t < B_.step_ ) // while not yet reached end of simulation step
    {
      bool done = false;

      do
      {

        if ( tend - t < h ) // stop integration at end of simulation step
          h = tend - t;

        t_return = t + h; // update t

        // k1 = f(told, y)
        aeif_cond_alpha_multisynapse_dynamics( S_.y_, S_.k1 );

        // k2 = f(told + h/5, y + h*k1 / 5)
        for ( size_t i = 0; i < S_.y_.size(); ++i )
          S_.yin[ i ] = S_.y_[ i ] + h * S_.k1[ i ] / 5.0;
        aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k2 );

        // k3 = f(told + 3/10*h, y + 3/40*h*k1 + 9/40*h*k2)
        for ( size_t i = 0; i < S_.y_.size(); ++i )
          S_.yin[ i ] = S_.y_[ i ] + h * ( 3.0 / 40.0 * S_.k1[ i ] + 9.0 / 40.0 * S_.k2[ i ] );
        aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k3 );

        // k4
        for ( size_t i = 0; i < S_.y_.size(); ++i )
          S_.yin[ i ] = S_.y_[ i ]
            + h * ( 44.0 / 45.0 * S_.k1[ i ] - 56.0 / 15.0 * S_.k2[ i ] + 32.0 / 9.0 * S_.k3[ i ] );
        aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k4 );

        // k5
        for ( size_t i = 0; i < S_.y_.size(); ++i )
          S_.yin[ i ] = S_.y_[ i ]
            + h * ( 19372.0 / 6561.0 * S_.k1[ i ] - 25360.0 / 2187.0 * S_.k2[ i ]
                    + 64448.0 / 6561.0 * S_.k3[ i ]
                    - 212.0 / 729.0 * S_.k4[ i ] );
        aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k5 );

        // k6
        for ( size_t i = 0; i < S_.y_.size(); ++i )
          S_.yin[ i ] = S_.y_[ i ]
            + h * ( 9017.0 / 3168.0 * S_.k1[ i ] - 355.0 / 33.0 * S_.k2[ i ]
                    + 46732.0 / 5247.0 * S_.k3[ i ]
                    + 49.0 / 176.0 * S_.k4[ i ]
                    - 5103.0 / 18656.0 * S_.k5[ i ] );
        aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k6 );

        // 5th order
        for ( size_t i = 0; i < S_.y_.size(); ++i )
          S_.ynew[ i ] = S_.y_[ i ]
            + h * ( 35.0 / 384.0 * S_.k1[ i ] + 500.0 / 1113.0 * S_.k3[ i ]
                    + 125.0 / 192.0 * S_.k4[ i ]
                    - 2187.0 / 6784.0 * S_.k5[ i ]
                    + 11.0 / 84.0 * S_.k6[ i ] );
        aeif_cond_alpha_multisynapse_dynamics( S_.yin, S_.k7 );

        // 4th order
        for ( size_t i = 0; i < S_.y_.size(); ++i )
        {
          S_.yref[ i ] = S_.y_[ i ]
            + h * ( 5179.0 / 57600.0 * S_.k1[ i ] + 7571.0 / 16695.0 * S_.k3[ i ]
                    + 393.0 / 640.0 * S_.k4[ i ]
                    - 92097.0 / 339200.0 * S_.k5[ i ]
                    + 187.0 / 2100.0 * S_.k6[ i ]
                    + 1.0 / 40.0 * S_.k7[ i ] );
        }

        err = std::fabs( S_.ynew[ 0 ] - S_.yref[ 0 ] ) / MAXERR + 1.0e-200; // error estimate,
        // based on different orders for stepsize prediction. Small value added to prevent err==0

        // The following flag 'done' is needed to ensure that we accept the result
        // for h<=HMIN, irrespective of the error. (See below)

        done = ( h <= HMIN ); // Always exit loop if h was <=HMIN already

        // prediction of next integration stepsize. This step may result in a stepsize below HMIN.
        // If this happens, we must
        //   1. set the stepsize to HMIN
        //   2. compute the result and accept it irrespective of the error, because we cannot
        //      decrease the stepsize any further.
        //  the 'done' flag, computed above ensure that the loop is terminated after the
        //  result was computed.

        h *= 0.98 * std::pow( 1.0 / err, 1.0 / 5.0 );
        h = std::max( h, HMIN );

      } while ( ( err > 1.0 ) and ( not done ) ); // reject step if err > 1

      for ( size_t i = 0; i < S_.y_.size(); ++i )
        S_.y_[ i ] = S_.ynew[ i ]; // pass updated values

      t = t_return;

      // check for unreasonable values; we allow V_M to explode
      if ( S_.y_[ State_::V_M ] < -1e3 || S_.y_[ State_::W ] < -1e6 || S_.y_[ State_::W ] > 1e6 )
        throw NumericalInstability( get_name() );

      // spikes are handled inside the while-loop
      // due to spike-driven adaptation
      if ( S_.r_ > 0 )                               // if neuron is still in refractory period
        S_.y_[ State_::V_M ] = P_.V_reset_;          // clamp it to V_reset
      else if ( S_.y_[ State_::V_M ] >= P_.V_peak_ ) // V_m >= V_peak: spike
      {
        S_.y_[ State_::V_M ] = P_.V_reset_;
        S_.y_[ State_::W ] += P_.b;   // spike-driven adaptation
        S_.r_ = V_.RefractoryCounts_; // initialize refractory steps with refractory period

        set_spiketime( Time::step( origin.get_steps() + lag + 1 ) );
        SpikeEvent se;
        network()->send( *this, se, lag );
      }
    } // while

    for ( size_t i = 0; i < P_.num_of_receptors_; ++i )
    {
      S_.y_[ State_::DG_EXC + ( State_::NUMBER_OF_STATES_ELEMENTS_PER_RECEPTOR * i ) ] +=
        B_.spike_exc_[ i ].get_value( lag ) * V_.g0_ex_[ i ]; // add incoming spikes
      S_.y_[ State_::DG_INH + ( State_::NUMBER_OF_STATES_ELEMENTS_PER_RECEPTOR * i ) ] +=
        B_.spike_inh_[ i ].get_value( lag ) * V_.g0_in_[ i ];
    }
    // set new input current
    B_.I_stim_ = B_.currents_.get_value( lag );

    // log state data
    B_.logger_.record_data( origin.get_steps() + lag );

  } // for-loop
}
uint64 DamageOverTimeList::activateDots(CreatureObject* victim) {
	uint64 states = 0;
	uint64 statesBefore = 0;

	Locker guardLocker(&guard);

	for (int i = size() - 1; i >= 0 ; --i) {
		Vector<DamageOverTime>* vector = &elementAt(i).getValue();

		for (int j = vector->size() - 1; j >= 0 ; --j) {
			DamageOverTime* dot = &vector->elementAt(j);
			statesBefore |= dot->getType();

			if (dot->nextTickPast()) {
				//guard.unlock();

				try {
					dot->applyDot(victim);
				} catch (...) {
					//guard.wlock();

					throw;
				}

				//guard.wlock();
			}

			Time nTime = dot->getNextTick();

			if (nextTick.isPast() || (!dot->isPast() && (nTime.compareTo(nextTick) > 0)))
				nextTick = nTime;

			if (!dot->isPast()) {
				states |= dot->getType();
			} else {
				if (vector->size() == 1) {
					vector->remove(j);
					remove(i);
				} else {
					vector->remove(j);
				}
			}
		}
	}

	int statesRemoved = states ^ statesBefore;

	if( statesRemoved & CreatureState::BLEEDING )
		victim->clearState(CreatureState::BLEEDING);

	if( statesRemoved & CreatureState::POISONED )
		victim->clearState(CreatureState::POISONED);

	if( statesRemoved & CreatureState::DISEASED )
		victim->clearState(CreatureState::DISEASED);

	if( statesRemoved & CreatureState::ONFIRE )
		victim->clearState(CreatureState::ONFIRE);


	if (nextTick.isPast()) {
		dot = false;
		removeAll();

		states = 0;
	}

	return states;
}
void VehicleControlDeviceImplementation::generateObject(CreatureObject* player) {
	if (player->isDead() || player->isIncapacitated())
		return;

	if (!isASubChildOf(player))
		return;

	if (player->getParent() != NULL || player->isInCombat()) {
		player->sendSystemMessage("@pet/pet_menu:cant_call_vehicle"); // You can only unpack vehicles while Outside and not in Combat.
		return;
	}

	ManagedReference<TangibleObject*> controlledObject = this->controlledObject.get();

	if (controlledObject == NULL)
		return;

	if (controlledObject->isInQuadTree())
		return;

	ManagedReference<TradeSession*> tradeContainer = player->getActiveSession(SessionFacadeType::TRADE).castTo<TradeSession*>();

	if (tradeContainer != NULL) {
		server->getZoneServer()->getPlayerManager()->handleAbortTradeMessage(player);
	}

	if(player->getPendingTask("call_mount") != NULL) {
		StringIdChatParameter waitTime("pet/pet_menu", "call_delay_finish_vehicle");
		Time nextExecution;
		Core::getTaskManager()->getNextExecutionTime(player->getPendingTask("call_mount"), nextExecution);
		int timeLeft = (nextExecution.getMiliTime() / 1000) - System::getTime();
		waitTime.setDI(timeLeft);

		player->sendSystemMessage(waitTime);
		return;
	}

	ManagedReference<SceneObject*> datapad = player->getSlottedObject("datapad");

	if (datapad == NULL)
		return;

	int currentlySpawned = 0;

	for (int i = 0; i < datapad->getContainerObjectsSize(); ++i) {
		ManagedReference<SceneObject*> object = datapad->getContainerObject(i);

		if (object->isVehicleControlDevice()) {
			VehicleControlDevice* device = cast<VehicleControlDevice*>( object.get());

			ManagedReference<SceneObject*> vehicle = device->getControlledObject();

			if (vehicle != NULL && vehicle->isInQuadTree()) {
				if (++currentlySpawned > 2)
					player->sendSystemMessage("@pet/pet_menu:has_max_vehicle");

				return;
			}
		}
	}

	if(player->getCurrentCamp() == NULL && player->getCityRegion() == NULL) {

		Reference<CallMountTask*> callMount = new CallMountTask(_this.getReferenceUnsafeStaticCast(), player, "call_mount");

		StringIdChatParameter message("pet/pet_menu", "call_vehicle_delay");
		message.setDI(15);
		player->sendSystemMessage(message);

		player->addPendingTask("call_mount", callMount, 15 * 1000);

		if (vehicleControlObserver == NULL) {
			vehicleControlObserver = new VehicleControlObserver(_this.getReferenceUnsafeStaticCast());
			vehicleControlObserver->deploy();
		}

		player->registerObserver(ObserverEventType::STARTCOMBAT, vehicleControlObserver);

	} else {

		Locker clocker(controlledObject, player);
		spawnObject(player);
	}

}
// Read mesh if available. Otherwise create empty mesh with same non-proc
// patches as proc0 mesh. Requires all processors to have all patches
// (and in same order).
autoPtr<fvMesh> createMesh
(
    const Time& runTime,
    const word& regionName,
    const fileName& instDir,
    const bool haveMesh
)
{
    Pout<< "Create mesh for time = "
        << runTime.timeName() << nl << endl;

    IOobject io
    (
        regionName,
        instDir,
        runTime,
        IOobject::MUST_READ
    );

    if (!haveMesh)
    {
        // Create dummy mesh. Only used on procs that don't have mesh.
        fvMesh dummyMesh
        (
            io,
            xferCopy(pointField()),
            xferCopy(faceList()),
            xferCopy(labelList()),
            xferCopy(labelList()),
            false
        );
        Pout<< "Writing dummy mesh to " << dummyMesh.polyMesh::objectPath()
            << endl;
        dummyMesh.write();
    }

    Pout<< "Reading mesh from " << io.objectPath() << endl;
    autoPtr<fvMesh> meshPtr(new fvMesh(io));
    fvMesh& mesh = meshPtr();


    // Determine patches.
    if (Pstream::master())
    {
        // Send patches
        for
        (
            int slave=Pstream::firstSlave();
            slave<=Pstream::lastSlave();
            slave++
        )
        {
            OPstream toSlave(Pstream::blocking, slave);
            toSlave << mesh.boundaryMesh();
        }
    }
    else
    {
        // Receive patches
        IPstream fromMaster(Pstream::blocking, Pstream::masterNo());
        PtrList<entry> patchEntries(fromMaster);

        if (haveMesh)
        {
            // Check master names against mine

            const polyBoundaryMesh& patches = mesh.boundaryMesh();

            forAll(patchEntries, patchI)
            {
                const entry& e = patchEntries[patchI];
                const word type(e.dict().lookup("type"));
                const word& name = e.keyword();

                if (type == processorPolyPatch::typeName)
                {
                    break;
                }

                if (patchI >= patches.size())
                {
                    FatalErrorIn
                    (
                        "createMesh(const Time&, const fileName&, const bool)"
                    )   << "Non-processor patches not synchronised."
                        << endl
                        << "Processor " << Pstream::myProcNo()
                        << " has only " << patches.size()
                        << " patches, master has "
                        << patchI
                        << exit(FatalError);
                }

                if
                (
                    type != patches[patchI].type()
                 || name != patches[patchI].name()
                )
                {
                    FatalErrorIn
                    (
                        "createMesh(const Time&, const fileName&, const bool)"
                    )   << "Non-processor patches not synchronised."
                        << endl
                        << "Master patch " << patchI
                        << " name:" << type
                        << " type:" << type << endl
                        << "Processor " << Pstream::myProcNo()
                        << " patch " << patchI
                        << " has name:" << patches[patchI].name()
                        << " type:" << patches[patchI].type()
                        << exit(FatalError);
                }
            }
        }
        else
        {
            // Add patch
            List<polyPatch*> patches(patchEntries.size());
            label nPatches = 0;

            forAll(patchEntries, patchI)
            {
                const entry& e = patchEntries[patchI];
                const word type(e.dict().lookup("type"));
                const word& name = e.keyword();

                if (type == processorPolyPatch::typeName)
                {
                    break;
                }

                Pout<< "Adding patch:" << nPatches
                    << " name:" << name
                    << " type:" << type << endl;

                dictionary patchDict(e.dict());
                patchDict.remove("nFaces");
                patchDict.add("nFaces", 0);
                patchDict.remove("startFace");
                patchDict.add("startFace", 0);

                patches[patchI] = polyPatch::New
                (
                    name,
                    patchDict,
                    nPatches++,
                    mesh.boundaryMesh()
                ).ptr();
            }
            patches.setSize(nPatches);
            mesh.addFvPatches(patches, false);  // no parallel comms

            //// Write empty mesh now we have correct patches
            //meshPtr().write();
        }
    }
Esempio n. 18
0
void
nest::aeif_cond_exp::update( const Time& origin,
  const long from,
  const long to )
{
  assert(
    to >= 0 && ( delay ) from < kernel().connection_manager.get_min_delay() );
  assert( from < to );
  assert( State_::V_M == 0 );

  for ( long lag = from; lag < to; ++lag )
  {
    double t = 0.0;

    if ( S_.r_ > 0 )
      --S_.r_;

    // numerical integration with adaptive step size control:
    // ------------------------------------------------------
    // gsl_odeiv_evolve_apply performs only a single numerical
    // integration step, starting from t and bounded by step;
    // the while-loop ensures integration over the whole simulation
    // step (0, step] if more than one integration step is needed due
    // to a small integration step size;
    // note that (t+IntegrationStep > step) leads to integration over
    // (t, step] and afterwards setting t to step, but it does not
    // enforce setting IntegrationStep to step-t
    while ( t < B_.step_ )
    {
      const int status = gsl_odeiv_evolve_apply( B_.e_,
        B_.c_,
        B_.s_,
        &V_.sys_,             // system of ODE
        &t,                   // from t
        B_.step_,             // to t <= step
        &B_.IntegrationStep_, // integration step size
        S_.y_ );              // neuronal state

      if ( status != GSL_SUCCESS )
        throw GSLSolverFailure( get_name(), status );

      // check for unreasonable values; we allow V_M to explode
      if ( S_.y_[ State_::V_M ] < -1e3 || S_.y_[ State_::W ] < -1e6
        || S_.y_[ State_::W ] > 1e6 )
        throw NumericalInstability( get_name() );

      // spikes are handled inside the while-loop
      // due to spike-driven adaptation
      if ( S_.r_ > 0 )
        S_.y_[ State_::V_M ] = P_.V_reset_;
      else if ( S_.y_[ State_::V_M ] >= V_.V_peak )
      {
        S_.y_[ State_::V_M ] = P_.V_reset_;
        S_.y_[ State_::W ] += P_.b; // spike-driven adaptation
        S_.r_ = V_.refractory_counts_;

        set_spiketime( Time::step( origin.get_steps() + lag + 1 ) );
        SpikeEvent se;
        kernel().event_delivery_manager.send( *this, se, lag );
      }
    }
    S_.y_[ State_::G_EXC ] += B_.spike_exc_.get_value( lag );
    S_.y_[ State_::G_INH ] += B_.spike_inh_.get_value( lag );

    // set new input current
    B_.I_stim_ = B_.currents_.get_value( lag );

    // log state data
    B_.logger_.record_data( origin.get_steps() + lag );
  }
}
Esempio n. 19
0
void StaticPolicy::update () throw () {
  try{

  // aktive Spieler erfassen
  unsigned int num_robots = REMBB.robot_state.size();
  unsigned int num_active_players=0;
  vector<bool> is_active_player (num_robots);
  for (unsigned int i=0; i<num_robots; i++) {
//    cerr << "i: " << i << " Robot" << REMBB.robot_state[i].id << ": " << REMBB.robot_state[i].playerrole << "/" 
//    << REMBB.robot_state[i].desired_playerrole << " active: " << (REMBB.robot_state[i].in_game && !REMBB.robot_state[i].comm_interrupted) << endl;
    if (REMBB.robot_state[i].playertype==playertype && REMBB.robot_state[i].in_game && !REMBB.robot_state[i].comm_interrupted) {
      if (REMBB.robot_state[i].playerrole != REMBB.robot_state[i].desired_playerrole) {
        cerr << "StaticPolicy: Ein anderer Wechsel ist noch nicht ganz abgeschlossen. Mache nix." << endl;
        return;
      }
      num_active_players++;
      is_active_player[i]=true;
    } else {
      is_active_player[i]=false;
    }
  }    
  if (num_active_players>max_num_players)
    num_active_players=max_num_players;

  
  // Soll-Rollenverteilung erfassen
  vector<string> target_roles (num_active_players);
  for (unsigned int i=0; i<num_active_players; i++)
    target_roles[i] = roles(num_active_players-1, i);

  
  // aus der target_roles alle Rollen loeschen, die durch neu aktivierte Spieler belegt sind
  Time now;
  for (unsigned int i=0; i<num_robots; i++)
    if (is_active_player[i] && now.diff_msec(robot_activation_time[i])<1000) {
      vector<string>::iterator it = find (target_roles.begin(), target_roles.end(), REMBB.robot_state[i].playerrole);
      if (it!=target_roles.end()) {
//        cerr << "F: " << REMBB.robot_state[i].id << "<->" << *it << "   ";
        target_roles.erase (it); 
      }
      is_active_player[i]=false;
      num_active_players--;
    }

  
  // aus der target_roles Liste alle Rollen loeschen, die von aktiven Playern belegt sind
  for (unsigned int i=0; i<num_robots; i++)
    if (is_active_player[i]) {
      vector<string>::iterator it = find (target_roles.begin(), target_roles.end(), REMBB.robot_state[i].playerrole);
      if (it!=target_roles.end()) {
//                cerr << "G: " << REMBB.robot_state[i].id << "<->" << *it << "   ";
	target_roles.erase (it);
	is_active_player[i]=false;
	num_active_players--;
      }
    }

  // Wenn Rollen uebriggeblieben sind, diese vergeben
  if (target_roles.size()>0 && num_active_players>0) {
    // Roboter nach ihren Positionen von hinten nach vorne ordnen
    unsigned int in=0;
    vector<pair<unsigned int,double> > indeces (num_active_players);
    for (unsigned int i=0; i<num_robots; i++) {
      if (is_active_player[i]) {
        cerr << "Index: " << i << endl;
	indeces[in].first=i;
	indeces[in].second=REMBB.robot_state[i].own_half*REMBB.robot_state[i].robot_pos.pos.y;
	in++;
      }
    }
    for (unsigned int i=0; i<indeces.size(); i++) // Blasen-Sortierung
      for (unsigned int j=1; j<indeces.size(); j++)
	if (indeces[j].second<indeces[j-1].second) {
	  unsigned int swi=indeces[j].first;
	  double swy=indeces[j].second;
	  indeces[j].first=indeces[j-1].first;
	  indeces[j].second=indeces[j-1].second;
	  indeces[j-1].first=swi;
	  indeces[j-1].second=swy;
	}
    
    for (unsigned int i=0; i<indeces.size() && num_active_players>0; i++) {
      REMBB.robot_state[indeces[i].first].desired_playerrole  = target_roles[0];
//      cerr << "O: "<<  REMBB.robot_state[indeces[i].first].id << "<->" << REMBB.robot_state[indeces[i].first].playerrole << "   ";
      cerr << "Automatische Rollenzuweisung: " << REMBB.robot_state[indeces[i].first].name << " bekommt Rolle " << target_roles[0] <<'\n';
      target_roles.erase (target_roles.begin());
      is_active_player[indeces[i].first]=false;
      num_active_players--;	
    }
  }
  else if ((REMBB.team_state.refstate == preOwnKickOff ||
            REMBB.team_state.refstate == preOwnGoalKick ||
            REMBB.team_state.refstate == preOwnCornerKick ||
            REMBB.team_state.refstate == preOwnThrowIn ||
            REMBB.team_state.refstate == preOwnFreeKick ||
            REMBB.team_state.refstate == preOwnPenalty && num_active_players == 0) && // alle spieler haben eine rolle, alle rollen belegt
            target_roles.size() == 0) { // Der folgende Code ist neu und bisher noch wenig getestet (April 08)
    map<int, string> alloc;
    map<int, int> idToIndex;
    for (unsigned int i=0; i<num_robots; i++) {
      if (REMBB.robot_state[i].playertype==playertype && REMBB.robot_state[i].in_game && !REMBB.robot_state[i].comm_interrupted) {
        if (REMBB.robot_state[i].playerrole != REMBB.robot_state[i].desired_playerrole) {
          cerr << "Wechsel auf bevorzugte Position: Bereits ein anderer Wechsel aktiv. Mache nix." << endl;
          return;
        }
        alloc[REMBB.robot_state[i].id] = REMBB.robot_state[i].playerrole;
        idToIndex[REMBB.robot_state[i].id] = i;
      }
    }
    if (alloc.size() > 1) {  // nur, wenn auch ein spieler da ist
      int violations, changes;
      map<int, string> targetAlloc = RoleAllocationSolver::solve(prefs, alloc, &violations, &changes);
      if (changes > 0) {
        cerr << "Wechsel auf bevorzugte Position wird durchgefuehrt. Violations:  " << violations << " Changes: " << changes << endl;
        cerr << "Aenderungen: ";
        for (map<int, string>::iterator i = targetAlloc.begin(); i != targetAlloc.end(); i++) {
          // DEBUG Check: if (idToIndex[i->first] < 0 || idToIndex[i->first] > num_robots) { cerr << "MIST" << endl; }
          cerr << REMBB.robot_state[idToIndex[i->first]].playerrole << "->" << i->second << " ";
          REMBB.robot_state[idToIndex[i->first]].desired_playerrole = i->second;
        }
        cerr << endl;
      }
    }
  }
  }catch(exception& e) {
    JERROR (e.what());
  }
}
Esempio n. 20
0
int main()
{
  // print my name and this assignment's title 
  cout << "LAB 1b: More Class Programming And Testing\n"; 
  cout << "Programmer: Jacky Chow\n"; 
  cout << "Editor(s) used: Notepad++\n"; 
  cout << "Compiler(s) used: Visual C++\n"; 
  cout << "File: " << __FILE__ << endl; 
  cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl << endl;

  Time time;
  cout << "Hours is being set to 1 hour.\n";
  time.setHours(1);
  cout << "Minutes is being set to 40 minutes.\n";
  time.setMinutes(40);
  cout << "Seconds is being set to 30 seconds.\n\n";
  time.setSeconds(30);

  cout << "Time in hours is " << time.timeInHours() << " hours\n";
  assert(1.67499 < time.timeInHours() && time.timeInHours() < 1.67501);
  cout << "Time in minutes is " << time.timeInMinutes() << " minutes\n";
  assert(100.499 < time.timeInMinutes() && time.timeInMinutes() < 100.501);
  cout << "Time in seconds is " << time.timeInSeconds() << " seconds\n";
  assert(6030 == time.timeInSeconds());

  // object copy testing
  {
    const Time copy = time; // a read-only copy
    cout << "\nTime in hours in copy1 is " << copy.timeInHours() << " hours\n";
    assert(1.67499 < copy.timeInHours() && copy.timeInHours() < 1.67501);
    cout << "Time in minutes in copy1 is " << copy.timeInMinutes() << " minutes\n";
    assert(100.499 < copy.timeInMinutes() && copy.timeInMinutes() < 100.501);
    cout << "Time in seconds in copy1 is " << copy.timeInSeconds() << " seconds\n";
    assert(6030 == copy.timeInSeconds());
  }

  // object assignment testing
  {
    Time copy; 
    copy = time;
    cout << "\nTime in hours in copy2 is " << copy.timeInHours() << " hours\n";
    assert(1.67499 < copy.timeInHours() && copy.timeInHours() < 1.67501);
    cout << "Time in minutes in copy2 is " << copy.timeInMinutes() << " minutes\n";
    assert(100.499 < copy.timeInMinutes() && copy.timeInMinutes() < 100.501);
    cout << "Time in seconds in copy2 is " << copy.timeInSeconds() << " seconds\n";
    assert(6030 == copy.timeInSeconds());
  }
  
  cout << "\nHours is being set to 2 hours.\n";
  time.setHours(2);
  cout << "Minutes is being set to 10 minutes.\n";
  time.setMinutes(10);
  cout << "Seconds is being set to 15 seconds.\n\n";
  time.setSeconds(15);

  cout << "\nNew time in hours is " << time.timeInHours() << " hours\n";
  assert(2.170832 < time.timeInHours() && time.timeInHours() < 2.17834);
  cout << "New time in minutes is " << time.timeInMinutes() << " minutes\n";
  assert(130.2499 < time.timeInMinutes() && time.timeInMinutes() < 130.2501);
  cout << "New time in seconds is " << time.timeInSeconds() << " seconds\n";
  assert(7815 == time.timeInSeconds());
}
Esempio n. 21
0
void
nest::pp_pop_psc_delta::update( Time const& origin, const long_t from, const long_t to )
{
  assert( to >= 0 && ( delay ) from < kernel().connection_builder_manager.get_min_delay() );
  assert( from < to );

  for ( long_t lag = from; lag < to; ++lag )
  {


    S_.h_ = S_.h_ * V_.P33_ + V_.P30_ * ( S_.y0_ + P_.I_e_ ) + B_.spikes_.get_value( lag );


    // get_thetas_ages
    std::vector< double_t > tmp_vector;
    double_t integral = 0;
    tmp_vector.clear();


    for ( uint_t i = 0; i < V_.eta_kernel_.size(); i++ )
    {
      tmp_vector.push_back( V_.eta_kernel_[ i ]
        * S_.n_spikes_past_[ ( S_.p_n_spikes_past_ + i ) % S_.n_spikes_past_.size() ] * V_.h_
        * 0.001 );
      integral += tmp_vector[ i ];
    }

    S_.thetas_ages_.clear();
    S_.thetas_ages_.push_back( integral );

    for ( uint_t i = 1; i < V_.eta_kernel_.size(); i++ )
      S_.thetas_ages_.push_back( S_.thetas_ages_[ i - 1 ] - tmp_vector[ i - 1 ] );

    for ( uint_t i = 0; i < V_.eta_kernel_.size(); i++ )
      S_.thetas_ages_[ i ] += V_.theta_kernel_[ i ];

    S_.thetas_ages_.push_back( 0 );

    // get_escape_rate
    for ( uint_t i = 0; i < S_.rhos_ages_.size(); i++ )
      S_.rhos_ages_[ i ] = P_.rho_0_ * std::exp( ( S_.h_ + S_.thetas_ages_[ i ] ) / P_.delta_u_ );


    double p_argument;

    // generate_spikes
    for ( uint_t i = 0; i < S_.age_occupations_.size(); i++ )
    {

      if ( S_.age_occupations_[ ( S_.p_age_occupations_ + i ) % S_.age_occupations_.size() ] > 0 )
      {

        p_argument = -numerics::expm1( -S_.rhos_ages_[ i ] * V_.h_
                       * 0.001 ); // V_.h_ is in ms, S_.rhos_ages_ is in Hz

        if ( p_argument > V_.min_double_ )
        {
          V_.binom_dev_.set_p_n( p_argument,
            S_.age_occupations_[ ( S_.p_age_occupations_ + i ) % S_.age_occupations_.size() ] );
          S_.n_spikes_ages_[ i ] = V_.binom_dev_.ldev( V_.rng_ );
        }
        else
        {
          S_.n_spikes_ages_[ i ] = 0;
        }
      }
      else
        S_.n_spikes_ages_[ i ] = 0;
    }


    S_.p_n_spikes_past_ = ( S_.p_n_spikes_past_ - 1 + S_.n_spikes_past_.size() )
      % S_.n_spikes_past_.size(); // shift to the right

    int_t temp_sum = 0;
    for ( uint_t i = 0; i < S_.n_spikes_ages_.size(); i++ ) // cumulative sum
      temp_sum += S_.n_spikes_ages_[ i ];

    S_.n_spikes_past_[ S_.p_n_spikes_past_ ] = temp_sum;


    // update_age_occupations
    for ( uint_t i = 0; i < S_.age_occupations_.size(); i++ )
      S_.age_occupations_[ ( S_.p_age_occupations_ + i ) % S_.age_occupations_.size() ] -=
        S_.n_spikes_ages_[ i ];

    int_t last_element_value =
      S_.age_occupations_[ ( S_.p_age_occupations_ - 1 + S_.age_occupations_.size() )
        % S_.age_occupations_.size() ]; // save the last element

    S_.p_age_occupations_ = ( S_.p_age_occupations_ - 1 + S_.age_occupations_.size() )
      % S_.age_occupations_.size(); // shift to the right
    S_.age_occupations_[ ( S_.p_age_occupations_ - 1 + S_.age_occupations_.size() )
      % S_.age_occupations_.size() ] += last_element_value;
    S_.age_occupations_[ S_.p_age_occupations_ ] = S_.n_spikes_past_[ S_.p_n_spikes_past_ ];

    // Set new input current
    S_.y0_ = B_.currents_.get_value( lag );

    // Voltage logging
    B_.logger_.record_data( origin.get_steps() + lag );


    // test if S_.n_spikes_past_[S_.p_n_spikes_past_]!=0, generate spike and send this number as the
    // parameter

    if ( S_.n_spikes_past_[ S_.p_n_spikes_past_ ] > 0 ) // Is there any spike?
    {
      SpikeEvent se;
      se.set_multiplicity( S_.n_spikes_past_[ S_.p_n_spikes_past_ ] );
      kernel().event_delivery_manager.send( *this, se, lag );
    }
  }
}
Foam::cellShapeControlMesh::cellShapeControlMesh(const Time& runTime)
:
    DistributedDelaunayMesh<CellSizeDelaunay>
    (
        runTime,
        meshSubDir
    ),
    runTime_(runTime),
    defaultCellSize_(0.0)
{
    if (this->vertexCount())
    {
        fvMesh mesh
        (
            IOobject
            (
                meshSubDir,
                runTime.timeName(),
                runTime,
                IOobject::READ_IF_PRESENT,
                IOobject::NO_WRITE
            )
        );

        if (mesh.nPoints() == this->vertexCount())
        {
            pointScalarField sizes
            (
                IOobject
                (
                    "sizes",
                    runTime.timeName(),
                    meshSubDir,
                    runTime,
                    IOobject::READ_IF_PRESENT,
                    IOobject::NO_WRITE
                ),
                pointMesh::New(mesh)
            );

            triadIOField alignments
            (
                IOobject
                (
                    "alignments",
                    mesh.time().timeName(),
                    meshSubDir,
                    mesh.time(),
                    IOobject::READ_IF_PRESENT,
                    IOobject::AUTO_WRITE
                )
            );

            if
            (
                sizes.size() == this->vertexCount()
             && alignments.size() == this->vertexCount()
            )
            {
                for
                (
                    Finite_vertices_iterator vit = finite_vertices_begin();
                    vit != finite_vertices_end();
                    ++vit
                )
                {
                    vit->targetCellSize() = sizes[vit->index()];
                    vit->alignment() = alignments[vit->index()];
                }
            }
            else
            {
                FatalErrorIn
                (
                    "Foam::cellShapeControlMesh::cellShapeControlMesh"
                    "(const Time&)"
                )   << "Cell size point field is not the same size as the "
                    << "mesh."
                    << abort(FatalError);
            }
        }
    }
}
Esempio n. 23
0
void nest::iaf_cond_exp_sfa_rr::update(Time const & origin, const long_t from, const long_t to)
{
   
  assert(to >= 0 && (delay) from < Scheduler::get_min_delay());
  assert(from < to);

  for ( long_t lag = from ; lag < to ; ++lag )
  {
    
    double t = 0.0;
   
    // numerical integration with adaptive step size control:
    // ------------------------------------------------------
    // gsl_odeiv_evolve_apply performs only a single numerical
    // integration step, starting from t and bounded by step;
    // the while-loop ensures integration over the whole simulation
    // step (0, step] if more than one integration step is needed due
    // to a small integration step size;
    // note that (t+IntegrationStep > step) leads to integration over
    // (t, step] and afterwards setting t to step, but it does not
    // enforce setting IntegrationStep to step-t; this is of advantage
    // for a consistent and efficient integration across subsequent
    // simulation intervals
    while ( t < B_.step_ )
    {
      const int status = gsl_odeiv_evolve_apply(B_.e_, B_.c_, B_.s_, 
			   &B_.sys_,             // system of ODE
			   &t,                   // from t
			    B_.step_,            // to t <= step
			   &B_.IntegrationStep_, // integration step size
			    S_.y_); 	         // neuronal state

      if ( status != GSL_SUCCESS )
        throw GSLSolverFailure(get_name(), status);
    }

    S_.y_[State_::G_EXC] += B_.spike_exc_.get_value(lag);
    S_.y_[State_::G_INH] += B_.spike_inh_.get_value(lag);

    // absolute refractory period
    if ( S_.r_)
    {// neuron is absolute refractory
	    --S_.r_; 
	    S_.y_[State_::V_M] = P_.V_reset_; 
    }
    else
      // neuron is not absolute refractory
      if ( S_.y_[State_::V_M] >= P_.V_th_ )
	    {
	      S_.r_              = V_.RefractoryCounts_;
	      S_.y_[State_::V_M] = P_.V_reset_;

	      set_spiketime(Time::step(origin.get_steps()+lag+1));

	      S_.y_[State_::G_SFA] += P_.q_sfa;
	      S_.y_[State_::G_RR ] += P_.q_rr;
	  
	      SpikeEvent se;
	      network()->send(*this, se, lag);
	    }
    
    // set new input current
    B_.I_stim_ = B_.currents_.get_value(lag);

    // log state data
    B_.logger_.record_data(origin.get_steps() + lag);

  }
}
Esempio n. 24
0
/** Copy Konstruktor kelas DateTime*/
DateTime::DateTime(const DateTime& D) {
    Date tDate = D.getDate();
    Time tTime = D.getTime();
    date.setDate(tDate.getDay(), tDate.getMonth(), tDate.getYear());
    time.setTime(tTime.getHour(), tTime.getMinute(), tTime.getSecond());
}
Esempio n. 25
0
main(int argc, char **argv){

  if (argc!=3){
    std::cerr << "usage: " << argv[0] << " <style> <in.fig>\n";
    exit(0);
  }

  string conf_file = argv[1];
  string infile    = argv[2];

  zn::zn_conv zconverter(conf_file);

  fig_world W;
  if (!read(infile.c_str(), W)){
    cerr << "Bad fig file " << infile << "\n"; exit(0);
  }

  omap_t objects;

  // insert objects into multimap<type,object>
  for (fig_world::iterator i=W.begin(); i!=W.end(); i++){

    if ((i->type == 4) && (i->comment.size()>0) && (i->comment[0] == "CURRENT DATE")){
      Time t; t.set_current();
      i->text = t.date_str();
    }

    if (i->type == 6){ // shift comments into compounds
      fig::fig_world::iterator j = i; j++;
      if (j!=W.end()){
        if (j->comment.size()< i->comment.size()) j->comment.resize(i->comment.size());
        for (int n=0; n<i->comment.size(); n++) j->comment[n] = i->comment[n];
      }
      continue;
    }

    if (i->type == -6) continue;

    if ((i->comment.size()>0) && (i->comment[0] == "[skip]")) continue;
    if ((i->comment.size()>1) && (i->comment[1] == "[skip]")) continue;

    if ((i->depth <50) || (i->depth>=200)) continue;
    if (i->size() == 0) continue;

    int type = zconverter.get_type(*i);

    objects.insert(op_t(type,i));
  }

  for (map<int,zn::zn>::const_iterator i=zconverter.znaki.begin();
                                   i!=zconverter.znaki.end(); i++){
    if (!objects.count(i->first)) objects.insert(op_t(i->first, W.end()));
  }

  dRect drng(0,0,0,0);
  bool first=true;
  for (fig_world::iterator i=W.begin(); i!=W.end(); i++){
    if ((i->depth <50) || (i->depth>=200)) continue;
    if (first){
      first=false;
      drng=i->range();
    }
    else {
      drng = rect_bounding_box(drng, dRect(i->range()));
    }
  }

  dPoint r_tlc = dPoint(drng.TLC()) * fig2ps;
  dPoint r_brc = dPoint(drng.BRC()) * fig2ps;
  r_tlc.x=floor(r_tlc.x);
  r_tlc.y=floor(r_tlc.y);
  r_brc.x=ceil(r_brc.x);
  r_brc.y=ceil(r_brc.y);
  iRect rng(r_tlc, r_brc);

#define GS_SETBBOX    0
#define GS_MOVETO     1
#define GS_RMOVETO    2
#define GS_LINETO     3
#define GS_RLINETO    4
#define GS_CURVETO    5
#define GS_RCURVETO   6
#define GS_ARC        7
#define GS_ARCN       8
#define GS_ARCT       9
#define GS_CLOSEPATH 10
#define GS_UCACHE    11

  // print EPS header

  cout
    << "%!PS-Adobe-2.0 EPSF-2.0\n"
    << "%%Title: " << infile << "\n"
    << "%%Creator: mapsoft fig2ps\n"
    << "%%BoundingBox: 0 0 " << rng.w << " " << rng.h << "\n"
    << "%Magnification: 1.0000\n"
    << "%%EndComments\n";


  // print definitions of postscript upaths for all types
  for (omap_t::const_iterator t=objects.begin();
                  t!=objects.end(); t=objects.upper_bound(t->first)){
    // for each key in multimap

    char type='p';
    if (t->first & zn::line_mask) type='l';
    if (t->first & zn::area_mask) type='a';

//    if (type=='p') continue; // skip points

    vector<int> crd, cmd;
    cmd.push_back(GS_UCACHE);
    crd.push_back(0);
    crd.push_back(0);
    crd.push_back(rng.w);
    crd.push_back(rng.h);
    cmd.push_back(GS_SETBBOX);
    for (omap_t::const_iterator i=objects.lower_bound(t->first);
                               i!=objects.upper_bound(t->first); i++){
      if ((i->second==W.end()) || (i->second->size() < 1)) continue;
      cmd.push_back(GS_MOVETO);
      int s=i->second->size()-1;
      while ( s > 255-32){
        cmd.push_back(255);
        cmd.push_back(GS_LINETO);
        s-=255-32;
      }
      cmd.push_back(s+32);
      cmd.push_back(GS_LINETO);
      for (fig_object::const_iterator j=i->second->begin();
                                      j!=i->second->end(); j++){
        crd.push_back(j->x*fig2ps - rng.x);
        crd.push_back(rng.y + rng.h - 1 - j->y*fig2ps);
      }
      if (type=='a') cmd.push_back(GS_CLOSEPATH); // close areas
    }

    switch (type){
      case 'l': cout << "/POLYLINE"; break;
      case 'a': cout << "/POLYGON"; break;
      case 'p': cout << "/POI"; break;
    }
    cout << "_0x" << hex << (t->first & 0xFFFFF)
         << " {\n<9520" << setw(4) << setfill('0') << crd.size();
    int c=9; // column in file
    for (vector<int>::const_iterator i=crd.begin(); i!=crd.end(); i++){
      if (c>70){
        cout << "\n";
        c=0;
      }
      else {
        cout << " ";
        c++;
      }
      cout << setw(4) << setfill('0') << *i;
      c+=4;
    }
    cout << ">\n<";
    c=1;
    for (vector<int>::const_iterator i=cmd.begin(); i!=cmd.end(); i++){
      if (c>70){
        cout << "\n";
        c=0;
      }
      cout << setw(2) << setfill('0') << *i;
      c+=2;
    }
    cout << dec << ">\n} cvlit def\n\n";
  }

  cout << dec << "(./common.ps) run\n\n";

}
Esempio n. 26
0
void
iaf_psc_delta_canon::update( Time const& origin,
  const long from,
  const long to )
{
  assert( to >= 0 );
  assert( static_cast< delay >( from )
    < kernel().connection_manager.get_min_delay() );
  assert( from < to );

  // at start of slice, tell input queue to prepare for delivery
  if ( from == 0 )
  {
    B_.events_.prepare_delivery();
  }

  /*
    The psc_delta neuron can fire only
    1. precisely upon spike arrival
    2. in between spike arrivals when threshold is reached due
       to the DC current.
    3. if the membrane potential is superthreshold at the BEGINNING
       of a slice due to initialization.
    In case 1, the spike time is known immediately.
    In case 2, the spike time can be found by solving the membrane
    equation.
    In case 3, the spike time is defined to be at from+epsilon.
    Thus, we can take arbitrary time steps within (from, to].
    Since slice_ring_buffer's delivery mechanism is built on time slices,
    we still need to step through the individual time steps to check
    for events.
    In typical network simulations and for typical step sizes, the probability
    of steps without input spikes is small. So the outer loop is over steps.
   */

  // check for super-threshold at beginning
  if ( S_.U_ >= P_.U_th_ )
  {
    emit_instant_spike_( origin,
      from,
      V_.h_ms_ * ( 1 - std::numeric_limits< double >::epsilon() ) );
  }

  for ( long lag = from; lag < to; ++lag )
  {
    // time at start of update step
    const long T = origin.get_steps() + lag;

    // Time within step is measured by offsets, which are h at the beginning
    // and 0 at the end of the step.
    double t = V_.h_ms_;

    // place pseudo-event in queue to mark end of refractory period
    if ( S_.is_refractory_
      && ( T + 1 - S_.last_spike_step_ == V_.refractory_steps_ ) )
    {
      B_.events_.add_refractory( T, S_.last_spike_offset_ );
    }

    // get first event
    double ev_offset;
    double ev_weight;
    bool end_of_refract;

    if ( not B_.events_.get_next_spike(
           T, true, ev_offset, ev_weight, end_of_refract ) )
    { // No incoming spikes, handle with fixed propagator matrix.
      // Handling this case separately improves performance significantly
      // if there are many steps without input spikes.

      // update membrane potential
      if ( not S_.is_refractory_ )
      {
        /* The following way of updating U_ is numerically more precise
           than the more natural approach

              U_ = exp_t_ * U_ + I_contrib_;

           particularly when U_ * exp_t_ is close to -I_contrib_.
        */


        // contribution of the stepwise constant current
        const double I_ext = -V_.expm1_t_ * V_.R_ * ( S_.I_ + P_.I_e_ );
        S_.U_ = I_ext + V_.expm1_t_ * S_.U_ + S_.U_;

        S_.U_ =
          S_.U_ < P_.U_min_ ? P_.U_min_ : S_.U_; // lower bound on potential
        if ( S_.U_ >= P_.U_th_ )
        {
          emit_spike_( origin, lag, 0 ); // offset is zero at end of step
        }

        // We exploit here that the refractory period must be at least
        // one time step long. So even if the spike had happened at the
        // very beginning of the step, the neuron would remain refractory
        // for the rest of the step. We can thus ignore the time reset
        // issued by emit_spike_().
      }
      // nothing to do if neuron is refractory
    }
    else
    {
      // We only get here if there is at least one event,
      // which has been read above.  We can therefore use
      // a do-while loop.

      do
      {

        if ( S_.is_refractory_ )
        {
          // move time to time of event
          t = ev_offset;

          // normal spikes need to be accumulated
          if ( not end_of_refract )
          {
            if ( S_.with_refr_input_ )
            {
              V_.refr_spikes_buffer_ += ev_weight
                * std::exp( -( ( S_.last_spike_step_ - T - 1 ) * V_.h_ms_
                              - ( S_.last_spike_offset_ - ev_offset )
                              + P_.t_ref_ ) / P_.tau_m_ );
            }
          }
          else
          {
            // return from refractoriness---apply buffered spikes
            S_.is_refractory_ = false;

            if ( S_.with_refr_input_ )
            {
              S_.U_ += V_.refr_spikes_buffer_;
              V_.refr_spikes_buffer_ = 0.0;
            }

            // check if buffered spikes cause new spike
            if ( S_.U_ >= P_.U_th_ )
            {
              emit_instant_spike_( origin, lag, t );
            }
          }

          // nothing more to do in this loop iteration
          continue;
        }

        // we get here only if the neuron is not refractory
        // update neuron to time of event
        // time is measured backward: inverse order in difference
        propagate_( t - ev_offset );
        t = ev_offset;

        // Check whether we have passed the threshold. If yes, emit a
        // spike at the precise location of the crossing.
        // Time within the step need not be reset to the precise time
        // of the spike, since the neuron will be refractory for the
        // remainder of the step.
        // The event cannot be a return-from-refractoriness event,
        // since that violates the assumption that the neuron was not
        // refractory. We can thus ignore the event, since the neuron
        // is refractory after the spike and ignores all input.
        if ( S_.U_ >= P_.U_th_ )
        {
          emit_spike_( origin, lag, t );
          continue;
        }

        // neuron is not refractory: add input spike, check for output
        // spike
        S_.U_ += ev_weight;
        if ( S_.U_ >= P_.U_th_ )
        {
          emit_instant_spike_( origin, lag, t );
        }

      } while ( B_.events_.get_next_spike(
        T, true, ev_offset, ev_weight, end_of_refract ) );

      // no events remaining, plain update step across remainder
      // of interval
      if ( not S_.is_refractory_ && t > 0 ) // not at end of step, do remainder
      {
        propagate_( t );
        if ( S_.U_ >= P_.U_th_ )
        {
          emit_spike_( origin, lag, 0 );
        }
      }

    } // else

    // voltage logging
    B_.logger_.record_data( origin.get_steps() + lag );

    S_.I_ = B_.currents_.get_value( lag );
  }
}
// Same check as snapMesh
void checkSnapMesh
(
    const Time& runTime,
    const polyMesh& mesh,
    labelHashSet& wrongFaces
)
{
    IOdictionary snapDict
    (
        IOobject
        (
            "snapMeshDict",
            runTime.system(),
            mesh,
            IOobject::MUST_READ,
            IOobject::NO_WRITE
        )
    );

    // Max nonorthogonality allowed
    scalar maxNonOrtho(readScalar(snapDict.lookup("maxNonOrtho")));
    primitiveMesh::nonOrthThreshold_ = maxNonOrtho;

    // Max concaveness allowed.
    scalar maxConcave(readScalar(snapDict.lookup("maxConcave")));
    primitiveMesh::faceAngleThreshold_ = maxConcave;

    // Min volume allowed (factor of minimum cellVolume)
    scalar relMinVol(readScalar(snapDict.lookup("minVol")));
    const scalar minCellVol = min(mesh.cellVolumes());
    const scalar minPyrVol = relMinVol*minCellVol;

    // Min area
    scalar minArea(readScalar(snapDict.lookup("minArea")));

    if (maxNonOrtho < 180.0 - SMALL)
    {
        Pout<< "Checking non orthogonality" << endl;

        label nOldSize = wrongFaces.size();
        mesh.checkFaceOrthogonality(false, &wrongFaces);

        Pout<< "Detected " << wrongFaces.size() - nOldSize
            << " faces with non-orthogonality > " << maxNonOrtho << " degrees"
            << endl;
    }

    if (minPyrVol > -GREAT)
    {
        Pout<< "Checking face pyramids" << endl;

        label nOldSize = wrongFaces.size();
        mesh.checkFacePyramids(false, minPyrVol, &wrongFaces);
        Pout<< "Detected additional " << wrongFaces.size() - nOldSize
            << " faces with illegal face pyramids" << endl;
    }

    if (maxConcave < 180.0 - SMALL)
    {
        Pout<< "Checking face angles" << endl;

        label nOldSize = wrongFaces.size();
        mesh.checkFaceAngles(false, &wrongFaces);

        Pout<< "Detected additional " << wrongFaces.size() - nOldSize
            << " faces with concavity > " << maxConcave << " degrees"
            << endl;
    }

    if (minArea > -SMALL)
    {
        Pout<< "Checking face areas" << endl;

        label nOldSize = wrongFaces.size();

        const scalarField magFaceAreas = mag(mesh.faceAreas());

        forAll(magFaceAreas, faceI)
        {
            if (magFaceAreas[faceI] < minArea)
            {
                wrongFaces.insert(faceI);
            }
        }

        Pout<< "Detected additional " << wrongFaces.size() - nOldSize
            << " faces with area < " << minArea << " m^2" << endl;
    }
uint32 DamageOverTimeList::addDot(CreatureObject* victim,
								  CreatureObject* attacker,
								  uint64 objectID,
								  uint32 duration,
								  uint64 dotType,
								  uint8 pool,
								  uint32 strength,
								  float potency,
								  uint32 defense,
								  int secondaryStrength) {
	Locker locker(&guard);

	if (strength == 0 || duration == 0)
		return 0;

	// determine chance to hit, if no hit, just return 0. potency of less than 0 can't be resisted
	if (potency > 0 && System::random(100) >= MAX(5.f, MIN(potency * (80.f / (100.f + defense)), 95.f)))
		return 0;

	if (pool == CreatureAttribute::UNKNOWN) {
		pool = getRandomPool(dotType);
	}

	int oldStrength = getStrength(pool, dotType);

	int durationMod = 0;

	switch (dotType) {
	case CreatureState::POISONED:
		durationMod = victim->getSkillMod("dissipation_poison");
		break;
	case CreatureState::DISEASED:
		durationMod = victim->getSkillMod("dissipation_disease");
		break;
	case CreatureState::ONFIRE:
		durationMod = victim->getSkillMod("dissipation_fire");
		break;
	case CreatureState::BLEEDING:
		durationMod = victim->getSkillMod("dissipation_bleeding");
		break;
	default:
		break;
	}

	if (durationMod > 0) {
		if (durationMod > 90) durationMod = 90;
		duration = MAX(1, (int)(duration * (1.f - (durationMod / 100.f))));
	}

	//only 1 disease per bar allowed
	if(dotType == CreatureState::DISEASED) {
		objectID = Long::hashCode(CreatureState::DISEASED);
	} else if (dotType == CommandEffect::FORCECHOKE) {
		objectID = 0;
	}

	DamageOverTime newDot(attacker, dotType, pool, strength, duration, secondaryStrength);
	int dotPower = newDot.initDot(victim, attacker);

	uint64 key = generateKey(dotType, pool, objectID);

	if (contains(key)) {
		Vector<DamageOverTime>* vector = &get(key);
		Vector<DamageOverTime> newVec;

		// This seems to only ever put one value in the DOT vector. This needs to remain a vector to
		// maintain the integrity of the db.
		for (int i = 0; i < vector->size(); ++i) {
			DamageOverTime dot = vector->get(i);

			// Curing the dot can cause the dot to expire but not get
			// removed from the list, so if the dot is expired make sure
			// to not reset it
			if (dot.isPast()) {
				newVec.add(newDot);
			} else if (newDot.getStrength() >= dot.getStrength()) {
				// but we only want to reuse the tick if the old dot has not
				// expired yet but is being replaced due to strength
				newDot.setNextTick(dot.getNextTick());
				newVec.add(newDot);
			} else // the new dot has less strength and the old dot hasn't expired
				newVec.add(dot);

			drop(key);
			put(key, newVec);
		}
	} else {
		Vector<DamageOverTime> newVector;
		newVector.add(newDot);
		put(key, newVector);
	}

	Time nTime = newDot.getNextTick();

	if (isEmpty() || nextTick.isPast() || nTime.compareTo(nextTick) > 0)
		nextTick = nTime;

	if(oldStrength == 0)
		sendStartMessage(victim, dotType);
	else
		sendIncreaseMessage(victim, dotType);

	dot = true;

	locker.release();

	if (dotType != CommandEffect::FORCECHOKE)
		victim->setState(dotType);

	return dotPower;
}
Esempio n. 29
0
//Main Game loop. 
void Game::Loop() {
    sf::Clock clock;

    shared_ptr<Player> player_entity(new Player(0,0,"data/player.json"));
    shared_ptr<EntityList> entity_list(new EntityList());
    entity_list->push(player_entity);
    camera_->set_player(player_entity);

    Event event;
    Time previous = clock.getElapsedTime();
    Time lag = sf::milliseconds(0);
    while (window_->is_open()) {
        Time current = clock.getElapsedTime(); 
        Time elapsed = current - previous; //Get the time elapsed since last loop
        previous = current; 
        lag += elapsed; //Increase lag by elapsed time since last loop
        //Poll for an event.
        input_->clear();
        while (window_->poll_event(event)) {
            if (event.type == Event::Closed) {
                window_->close();
                break;
            } else if(event.type == Event::KeyPressed) {
                input_->key_down_event(event.key.code);
            } else if(event.type == Event::KeyReleased) {
                input_->key_up_event(event.key.code);
            }
        }

        //Control player input
        if(input_->is_key_held(sf::Keyboard::Left) &&
           input_->is_key_held(sf::Keyboard::Right)) {
            player_entity->stop_move();
        } else if(input_->is_key_held(sf::Keyboard::Left)) {
            player_entity->start_move_left();
        } else if(input_->is_key_held(sf::Keyboard::Right)) {
            player_entity->start_move_right();
        } else {
            player_entity->stop_move();
        }

        //Control player jump
        if(input_->was_key_pressed(sf::Keyboard::Up)) {
            player_entity->start_jump();
        } else if(input_->was_key_released(sf::Keyboard::Up)) {
            player_entity->stop_jump();
        }

        //Update the game until caught up
        while(lag >= MS_PER_UPDATE) {
            //Update every entity
            entity_list->update_all(lag.asMilliseconds());
            camera_->check_player();
            //Remove lag equal to one frame of time
            lag -= MS_PER_UPDATE;
        }
        //Render the current frame
        graphics_->clear();
        map_->draw(graphics_);
        entity_list->draw(graphics_);
        graphics_->display();
    }
}
Esempio n. 30
0
// Hack to do zones which have Lists in them. See above.
bool writeZones(const word& name, const fileName& meshDir, Time& runTime)
{
    IOobject io
    (
        name,
        runTime.timeName(),
        meshDir,
        runTime,
        IOobject::MUST_READ,
        IOobject::NO_WRITE,
        false
    );

    bool writeOk = false;

    if (io.headerOk())
    {
        Info<< "        Reading " << io.headerClassName()
            << " : " << name << endl;

        // Switch off type checking (for reading e.g. faceZones as
        // generic list of dictionaries).
        const word oldTypeName = IOPtrList<entry>::typeName;
        const_cast<word&>(IOPtrList<entry>::typeName) = word::null;

        IOPtrList<entry> meshObject(io);

        forAll(meshObject, i)
        {
            if (meshObject[i].isDict())
            {
                dictionary& d = meshObject[i].dict();

                if (d.found("faceLabels"))
                {
                    d.set("faceLabels", labelList(d.lookup("faceLabels")));
                }

                if (d.found("flipMap"))
                {
                    d.set("flipMap", boolList(d.lookup("flipMap")));
                }

                if (d.found("cellLabels"))
                {
                    d.set("cellLabels", labelList(d.lookup("cellLabels")));
                }

                if (d.found("pointLabels"))
                {
                    d.set("pointLabels", labelList(d.lookup("pointLabels")));
                }
            }
        }

        const_cast<word&>(IOPtrList<entry>::typeName) = oldTypeName;
        // Fake type back to what was in field
        const_cast<word&>(meshObject.type()) = io.headerClassName();

        Info<< "        Writing " << name << endl;

        // Force writing as ascii
        writeOk = meshObject.regIOobject::writeObject
        (
            IOstream::ASCII,
            IOstream::currentVersion,
            runTime.writeCompression()
        );
    }