Пример #1
0
static HRESULT CreateMap(const UStringVector &names,
    const UString &id,
    CFileMapping &fileMapping, NSynchronization::CManualResetEvent &event,
    UString &params)
{
  UInt32 extraSize = 2;
  UInt32 dataSize = 0;
  for (int i = 0; i < names.Size(); i++)
    dataSize += (names[i].Length() + 1) * sizeof(wchar_t);
  UInt32 totalSize = extraSize + dataSize;
  
  UString mappingName;
  
  CRandom random;
  random.Init(GetTickCount());
  for (;;)
  {
    int number = random.Generate();
    wchar_t temp[32];
    ConvertUInt64ToString(UInt32(number), temp);
    mappingName = id;
    mappingName += L"Mapping";
    mappingName += temp;
    if (!fileMapping.Create(INVALID_HANDLE_VALUE, NULL,
        PAGE_READWRITE, totalSize, GetSystemString(mappingName)))
      return E_FAIL;
    if (::GetLastError() != ERROR_ALREADY_EXISTS)
      break;
    fileMapping.Close();
  }
  
  UString eventName;
  RINOK(CreateTempEvent(id + L"MappingEndEvent", event, eventName));

  params += mappingName;
  params += L":";
  wchar_t string[10];
  ConvertUInt64ToString(totalSize, string);
  params += string;
  
  params += L":";
  params += eventName;

  LPVOID data = fileMapping.MapViewOfFile(FILE_MAP_WRITE, 0, totalSize);
  if (data == NULL)
    return E_FAIL;
  {
    wchar_t *curData = (wchar_t *)data;
    *curData = 0;
    curData++;
    for (int i = 0; i < names.Size(); i++)
    {
      const UString &s = names[i];
      memcpy(curData, (const wchar_t *)s, s.Length() * sizeof(wchar_t));
      curData += s.Length();
      *curData++ = L'\0';
    }
  }
  return S_OK;
}
Пример #2
0
void CHealGuyObject::SetState(HealType state){

  m_eState=state; //change state

  switch(m_eState){ //change behavior settings

   
    case herCRUISINGS3_STATE:
      m_nAiDelayTime=400+g_cRandom.number(0,200);
      m_nHeightDelayTime=3000+g_cRandom.number(0,5000);
      break;

    case herAVOIDINGS3_STATE:
      m_nAiDelayTime=250+g_cRandom.number(0,250); 
      m_fXspeed=-3;
      break;
	case herCHASINGS3_STATE:
      //m_nAiDelayTime=400+g_cRandom.number(0,200);
      //m_nHeightDelayTime=300+g_cRandom.number(0,50);
	  break;
	case herWAITS3_STATE:
	  m_nAiDelayTime=250+g_cRandom.number(0,250); 
	  break;

    default: break;
  }
}
Пример #3
0
void CHealGuyObject::AvoidingAi(){ //avoiding plane
		if(xdistance > cool.x)
	{
		m_fXspeed = (float)-g_cRandom.number(7,10); 
	
	}
	if(xdistance < cool.x)
	{
		m_fXspeed = (float)-g_cRandom.number(-7,-10);

	}
	if(ydistance > cool.y)
	{
		m_fYspeed = (float)-g_cRandom.number(-7,-10); 
		
	}
	if(ydistance < cool.y)
	{
		m_fYspeed = (float)-g_cRandom.number(7,10);
	
	}
	
	if(ydistance == cool.y && xdistance == cool.x)
		SetState(herCRUISINGS3_STATE);

 
}
Пример #4
0
//----------------------------------------------------------------------------
IDestination * CBuildingTest::getRandomDestination()
{
	CBuildingManager * bm = CBuildingManager::getInstance();
	nlassert( bm );

	IDestination * dest = NULL;
	do
	{
		sint32 randomNumber = RandomGenerator.rand( (uint16)bm->_Triggers.size()-1 );
		CHashMap<sint,CBuildingManager::CTrigger>::iterator itTrigger = bm->_Triggers.begin();
		for (sint32 i = 0; i < randomNumber; i++)
		{
			++itTrigger;
			if (itTrigger == bm->_Triggers.end())
				itTrigger = bm->_Triggers.begin();
		}

		const sint triggerId = (*itTrigger).first;
		CBuildingManager::CTrigger & trigger = (*itTrigger).second;
		if (trigger.Destinations.empty())
		{
			nlwarning("*** BuildingUnitTest *** trigger %u has no destination.", triggerId);
			continue;
		}

		randomNumber = RandomGenerator.rand( (uint16)trigger.Destinations.size()-1 );
		dest = trigger.Destinations[randomNumber];
	} while ( !dest );

	return dest;
}
Пример #5
0
void CHealGuyObject::CruisingAi(){ //just cruising along
int x=0;

if(g_cTimer.elapsed(m_nHeightTime, m_nHeightDelayTime))
	{
	int rand = g_cRandom.number(1,3000);
	m_nHeightDelayTime=100+g_cRandom.number(0,1000);
	
		if(rand%2 == 1)
	{
		m_fXspeed = 5;
		
	}
	else 
	{
		m_fXspeed = -5;
		
	}
	
	
if(m_fDistance < CLOSE_DISTANCE){
		//g_pSoundManager->play(DEADCROW14_SOUND);
		SetState(herCHASINGS3_STATE);}
	}


	
}
Пример #6
0
void CRoundManObject::ChasingAi()
{
	
	if(g_cTimer.elapsed(m_nHeightTime, m_nHeightDelayTime))
	{
		m_nHeightDelayTime=100+g_cRandom.number(0,50);
	

	if(m_fHorizontalDistance > 0)
	{
		m_fXspeed = (float)-g_cRandom.number(7,10); 
	
	}
	 if(m_fHorizontalDistance < 0)
	{
		m_fXspeed = (float)-g_cRandom.number(-7,-10);

	}
	if(m_fVerticalDistance > 0)
	{
		m_fYspeed = (float)-g_cRandom.number(-7,-10); 
		
	}
	if(m_fVerticalDistance < 0)
	{
		m_fYspeed = (float)-g_cRandom.number(7,10);
	
	}
	if(CLOSE_DISTANCE > m_fDistance)
		SetState(CRUISINGS5_STATE);
}
}
Пример #7
0
void Tree::draw(){


			
			glPushMatrix();
		  //trunk
 			glNewList(++list_number,GL_COMPILE);

      glTranslatef(center_point.x,center_point.y,center_point.z);
      trunk->set();
			 glutSolidCube(0.5);

    	glEndList();
			glPopMatrix();

			list_index = list_number;

      //cone
			glPushMatrix();
      glNewList(++list_number,GL_COMPILE);
      leaves->set();
			glTranslatef(center_point.x,center_point.y+0.05,center_point.z);
      glRotatef(-90.0, 1.0, 0.0, 0.0);
      glutSolidCone(rando.number(5,15)/10.0, rando.number(10,30)/10.0, 50, 50);
 			glEndList();
      glPopMatrix();

}
Пример #8
0
void CRoundManObject::SetState(States5Type state){

  m_eState=state; //change state

  switch(m_eState){ //change behavior settings

    case CRUISINGS5_STATE:
      m_nAiDelayTime=400+g_cRandom.number(0,200);
      m_nHeightDelayTime=3000+g_cRandom.number(0,5000);
      break;

    case AVOIDINGS5_STATE:
      m_nAiDelayTime=250+g_cRandom.number(0,250); 
      m_fXspeed=-3;
      break;
	case CHASINGS5_STATE:
      //m_nAiDelayTime=400+g_cRandom.number(0,200);
      m_nHeightDelayTime=300+g_cRandom.number(0,50);
	  break;
	case WAITS5_STATE:
	  m_nAiDelayTime=250+g_cRandom.number(0,250); 
	  break;

    default: break;
  }
}
Пример #9
0
void Target::ai(){

if(!timer.elapsed(last_time,delay_time)) return;
	
		if(center_point.x < -15.0)
			velocity.x = rando.number(0,50)/1000.0;
		else if(center_point.x > 15.0)
			velocity.x = rando.number(-50,0)/1000.0;
		else
			velocity.x = rando.number(-50,50)/1000.0;

		if(center_point.y < 0.0)
			velocity.y = rando.number(0,50)/1000.0;
		else if(center_point.y > 3.0)
			velocity.y = rando.number(-50,0)/1000.0;
		else
			velocity.y = rando.number(-50,50)/1000.0;

		if(center_point.z < -20.0)
			velocity.z = rando.number(0,50)/1000.0;
		else if(center_point.z > 5.0)
			velocity.z = rando.number(-50,0)/1000.0;
		else
			velocity.z = rando.number(-50,50)/1000.0;
	
	
	
	delay_time = 1500 + rando.number(0,2500);
	
	last_time = timer.time();


}
Пример #10
0
NCBITEST_INIT_TREE()
{
    if ( s_Random.GetSeed() == 0 ) {
        s_Random.Randomize();
        LOG_POST("Random seed: "<<s_Random.GetSeed());
    }
}
Пример #11
0
bool CThreadPoolTester::TestApp_Init(void)
{
    s_Pool = new CThreadPool(kQueueSize, kMaxThreads);

    s_RNG.SetSeed(CProcess::GetCurrentPid());

    if (s_NumThreads > kQueueSize) {
        s_NumThreads = kQueueSize;
    }

    int total_cnt = kTasksPerThread * s_NumThreads;
    s_Actions.resize(total_cnt + 1);
    s_ActionTasks.resize(total_cnt + 1);
    s_CancelTypes.resize(total_cnt + 1);
    s_WaitPeriods.resize(total_cnt + 1);
    s_PostTimes.resize(total_cnt + 1);
    s_Tasks.resize(total_cnt + 1);

    int req_num = 0;
    for (int i = 1; i <= total_cnt; ++i) {
        int rnd = s_RNG.GetRand(1, 1000);
        if (req_num <= 10 || rnd > 100) {
            s_Actions[i] = eAddTask;
            s_ActionTasks[i] = req_num;
            s_WaitPeriods[req_num] = s_RNG.GetRand(50, 100);
            rnd = s_RNG.GetRand(0, 100);
            s_CancelTypes[req_num] = (rnd <= 1? eSimpleWait: eCheckCancel);
            ++req_num;
        }
        else if (rnd <= 1) {
            s_Actions[i] = eFlushWaiting;
        }
        else if (rnd <= 2) {
            s_Actions[i] = eFlushNoWait;
        }
        else if (rnd <= 4) {
            s_Actions[i] = eAddExclusiveTask;
            s_ActionTasks[i] = req_num;
            ++req_num;
        }
        else if (rnd <= 6) {
            s_Actions[i] = eCancelAll;
        }
        else /* if (rnd <= 100) */ {
            s_Actions[i] = eCancelTask;
            s_ActionTasks[i] = req_num - 8;
        }
        s_PostTimes[i] = 100 * (i / 20) + s_RNG.GetRand(50, 100);
    }

    MSG_POST("Starting test for CThreadPool");

    s_Timer.Start();

    return true;
}
static string s_GenInput(int input_length)
{
    string input;
    input.reserve(input_length);
    s_Random.SetSeed(CRandom::TValue(time(0)));
    for (int n = 0; n < input_length; ++n) {
        input.append(1, s_Random.GetRand(0, 255));
    }
    return input;
}
Пример #13
0
DWORD WINAPI RandomSessionThreadEntry(void* pv)
{
	CoInitializeEx(NULL, COINIT_MULTITHREADED);
	CRandom::RandomSessionData* pS = (CRandom::RandomSessionData*)pv;
	CRandom* p = pS->pRandom;
	while (WaitForSingleObject(pS->m_hEvent, 0) != WAIT_OBJECT_0)
		p->Fire(pS->m_nID);
	
	CoUninitialize();
	return 0;
}
Пример #14
0
void Game::resetGame()
{ 
  objects->clear();
  objects->spawnTerrain(terrain);
  objects->spawnWater(water);
  
  // Create plane  
  unsigned int planeID = objects->spawnPlane(Vector3
    (0.0f,terrain->getHeight(0.0f,0.0f) + 10.0f,0.0f));
  m_tetherCamera->setTargetObject(planeID);

  // Load silos
  objects->spawnSilo(LocationOnterrain(-30.0f, 10.0f, 100.0f));
  objects->spawnSilo(LocationOnterrain(-10.0f, 10.0f, 100.0f));
  objects->spawnSilo(LocationOnterrain(10.0f, 10.0f, 100.0f));
  objects->spawnSilo(LocationOnterrain(30.0f, 10.0f, 100.0f));

  // Load windmill
  unsigned int windmillID = objects->spawnWindmill(LocationOnterrain(60.0f, 0.0f, 100.0f));
  
  // Load crows
  static const int numCrows = 20;
  for(int i = 0; i < numCrows; ++i)
  {
    // Distibute evenly over a hollow cylinder around the windmill
    
    GameObject *windmill = objects->getObjectPointer(windmillID);
    const Vector3 &windmillPos = windmill->getPosition();
    Vector3 boxSize = windmill->getBoundingBox().size();
    float minDist = sqrt(boxSize.x * boxSize.x + boxSize.z - boxSize.z); // At least the windmill's maximum diameter away from the windmill
    float maxDist = 175.0f; // Maximum distance; season to taste
    float radius = Random.getFloat(minDist, maxDist);
    float angle = Random.getFloat(0,k2Pi);
    float height = windmillPos.y + boxSize.y * Random.getFloat(1.5, 2.0f) + 10.0f; // Randomize crow height to somewhat above the windmill
    Vector3 crowPos(cos(angle) * radius + windmillPos.x, height, sin(angle) * radius + windmillPos.z);
    float crowSpeed = Random.getFloat(0.8f,2.5f);
    // One speedy crow, one slow crow
    if(i == numCrows - 2)
      crowSpeed = 6.0f;
    else if(i == numCrows - 1)
      crowSpeed = 0.5;
    
    //crowSpeed = 0.0;
    objects->spawnCrow(crowPos, windmillPos, crowSpeed, Random.getBool());
  }

  // Set the tether camera
  m_tetherCamera->minDist = 10.0f;
  m_tetherCamera->maxDist = 20.0f;
  m_tetherCamera->fov;
  m_tetherCamera->reset();
  m_tetherCamera->process(0.0f);
  m_currentCam = m_tetherCamera;   // select tether camera as the current camera
}
Пример #15
0
/// This slightly offsets the U V coordinates randomly.  This helps solve the
/// repeating look on the textures.
void Terrain::setTextureDistortion()
{
  for (int i = 0 ; i < m_nVPS ; ++i)   
	  for (int j = 0 ; j < m_nVPS ; ++j) 
    {
		  m_vertices[i*m_nVPS+j].u = ((float)i + Random.getFloat(-0.20f,0.20f))
        *m_textureScale;
		  m_vertices[i*m_nVPS+j].v = ((float)j + Random.getFloat(-0.20f,0.20f))
        *m_textureScale;
    }
    m_TextureDistorted = true;
}
int YubiKeyUtil::generateRandom(unsigned char *result, size_t resultLen) {
    size_t bufSize = resultLen;

    unsigned char buf[bufSize];
    memset(&buf, 0, sizeof(buf));

    size_t bufLen = 0;

#ifdef Q_WS_WIN
    CRandom random;
    random.getRand(buf, bufSize);

    bufLen = sizeof(buf);
#else
    const char *random_places[] = {
        "/dev/srandom",
        "/dev/urandom",
        "/dev/random",
        0
    };

    const char **random_place;

    for (random_place = random_places; *random_place; random_place++) {
        FILE *random_file = fopen(*random_place, "r");
        if (random_file) {
            size_t read_bytes = 0;

            while (read_bytes < bufSize) {
                size_t n = fread(&buf[read_bytes],
                                 1, bufSize - read_bytes,
                                 random_file);
                read_bytes += n;
            }

            fclose(random_file);

            bufLen = sizeof(buf);

            break; /* from for loop */
        }
    }
#endif

    if(bufLen > 0) {
        memcpy(result, buf, bufLen);
        return 1;
    }

    return 0;
}
Пример #17
0
//----------------------------------------------------------------------------
// Generate Array
//----------------------------------------------------------------------------
void CRandomArray::GenerateArray(unsigned int nElems)
{
    m_iNumElems = nElems;
    
    CRandom v;
    SYSTEMTIME ahora;
    GetLocalTime(&ahora);
    v.init((unsigned int)ahora.wMilliseconds);
    
    for(unsigned int i = 0 ; i < m_iNumElems ; i++)
    {
      m_vRandomArray.push_back(v.getRandFloat(0.0f,1.0f));
    }
}
static void s_SeedTokens(int num_aff_tokens)
{
    s_NumTokens = num_aff_tokens;
    s_Tokens = new char* [s_NumTokens];
    for (int n = 0; n < s_NumTokens; ++n) {
        int len = s_Random.GetRand(s_AvgTokenLength - s_DTokenLength,
                                   s_AvgTokenLength + s_DTokenLength);
        s_Tokens[n] = new char[len+1];
        for (int k = 0; k < len; ++k) {
            s_Tokens[n][k] =
                s_TokenLetters[s_Random.GetRand(0, sizeof(s_TokenLetters) - 1)];
        }
        s_Tokens[n][len] = 0;
    }
}
Пример #19
0
//---------------------------------------------------------------------------
//	@function:
//		CBitVectorTest::EresUnittest_Random
//
//	@doc:
//		Test with random bit vectors to avoid patterns
//
//---------------------------------------------------------------------------
GPOS_RESULT
CBitVectorTest::EresUnittest_Random()
{
	// create memory pool
	CAutoMemoryPool amp;
	IMemoryPool *pmp = amp.Pmp();

	// set up control vector
	ULONG cTotal = 10000;
	CHAR *rg = GPOS_NEW_ARRAY(pmp, CHAR, cTotal);
	
	CRandom rand;
	
	clib::PvMemSet(rg, 0 , cTotal);

	// set random chars in the control vector
	for (ULONG i = 0; i < cTotal * 0.2; i++)
	{
		ULONG index = rand.ULNext() % (cTotal - 1);
		GPOS_ASSERT(index < cTotal);
		rg[index] = 1;
	}

	ULONG cElements = 0;
	CBitVector bv(pmp, cTotal);
	for (ULONG i = 0; i < cTotal; i++)
	{
		if (1 == rg[i])
		{
			bv.FExchangeSet(i);
			cElements++;
		}
	}

	GPOS_ASSERT(cElements == bv.CElements());

	ULONG ulCursor = 0;
	while(bv.FNextBit(ulCursor + 1, ulCursor))
	{
		GPOS_ASSERT(1 == rg[ulCursor]);
		cElements--;
	}

	GPOS_ASSERT(0 == cElements);
	GPOS_DELETE_ARRAY(rg);

	return GPOS_OK;
}
Пример #20
0
void CLevelGraph::draw_restrictions	()
{
	CSpaceRestrictionManager::SPACE_RESTRICTIONS::const_iterator	I = Level().space_restriction_manager().restrictions().begin();
	CSpaceRestrictionManager::SPACE_RESTRICTIONS::const_iterator	E = Level().space_restriction_manager().restrictions().end();

	CRandom R;

	for ( ; I != E; ++I) {
		if (!(*I).second->m_ref_count)
			continue;
		if (!(*I).second->initialized()) continue;

		u8 b = u8(R.randI(255));
		u8 g = u8(R.randI(255));
		u8 r = u8(R.randI(255));

		xr_vector<u32>::const_iterator	i = (*I).second->border().begin();
		xr_vector<u32>::const_iterator	e = (*I).second->border().end();
		for ( ; i != e; ++i) {
			Fvector temp = ai().level_graph().vertex_position(*i);
			temp.y += .1f;
			Level().debug_renderer().draw_aabb(temp,.05f,.05f,.05f,D3DCOLOR_XRGB(r,g,b));
		}

#ifdef USE_FREE_IN_RESTRICTIONS
		CSpaceRestriction::FREE_IN_RESTRICTIONS::const_iterator II = (*I).second->m_free_in_restrictions.begin();
		CSpaceRestriction::FREE_IN_RESTRICTIONS::const_iterator EE = (*I).second->m_free_in_restrictions.end();
		for ( ; II != EE; ++II) {
			xr_vector<u32>::const_iterator	i = (*II).m_restriction->border().begin();
			xr_vector<u32>::const_iterator	e = (*II).m_restriction->border().end();
			for ( ; i != e; ++i) {
				Fvector temp = ai().level_graph().vertex_position(*i);
				temp.y += .1f;
				Level().debug_renderer().draw_aabb(temp,.05f,.05f,.05f,D3DCOLOR_XRGB(255,0,0));
			}
			{
				xr_vector<u32>::const_iterator	i = (*II).m_restriction->border().begin();
				xr_vector<u32>::const_iterator	e = (*II).m_restriction->border().end();
				for ( ; i != e; ++i) {
					Fvector temp = ai().level_graph().vertex_position(*i);
					temp.y += .1f;
					Level().debug_renderer().draw_aabb(temp,.05f,.05f,.05f,D3DCOLOR_XRGB(0,255,0));
				}
			}
		}
#endif
	}
}
Пример #21
0
//-----------------------------------------------
bool CTimedAction::testCancelOnHit( sint32 attackSkillValue, CEntityBase * attacker, CEntityBase * defender)
{
	// get defender defense skill
	sint32 defenderValue;
	if ( defender->getId().getType() == RYZOMID::player )
	{
		CCharacter *pC = dynamic_cast<CCharacter*> (defender);
		if (!pC)
		{
			nlwarning("Entity %s type is player but dynamic_cast in CCharacter * returns NULL ?!", defender->getId().toString().c_str());
			return false;
		}
		defenderValue = pC->getSkillValue(pC->getBestSkill());
	}
	else
	{
		const CStaticCreatures * form = defender->getForm();
		if ( !form )
		{
			nlwarning( "<MAGIC>invalid creature form %s in entity %s", defender->getType().toString().c_str(), defender->getId().toString().c_str() );
			return false;
		}	
		defenderValue = form->getAttackLevel();
	}
	
	//test if the spell is broken
	const uint8 chances = CStaticSuccessTable::getSuccessChance( SUCCESS_TABLE_TYPE::BreakCastResist, defenderValue - attackSkillValue);
	const uint8 roll = (uint8) RandomGenerator.rand(99);
	
	if ( roll >= chances )
		return true;
	else
		return false;
}
 void GenerateName(UString &s, const char *prefix)
 {
   s.AddAscii(prefix);
   char temp[16];
   ConvertUInt32ToString((UInt32)(unsigned)_random.Generate(), temp);
   s.AddAscii(temp);
 }
Пример #23
0
void CHomingObject::HomingAi()
{	if(g_cTimer.elapsed(m_nHeightTime, m_nHeightDelayTime))
	{
		m_nHeightDelayTime=100+g_cRandom.number(0,2000);
	

	if(m_fHorizontalDistance > 0)
	{
		m_fXspeed = -15; 
	
	}
	 if(m_fHorizontalDistance < 0)
	{
		m_fXspeed = 15;

	}
	if(m_fVerticalDistance > 0)
	{
		m_fYspeed = 15; 
		
	}
	if(m_fVerticalDistance < 0)
	{
		m_fYspeed = -15;
	
	}
	

}}
Пример #24
0
int main(int argc, char **argv)
{
  // Generates a vector of pairs, with a size given by the first argument. Each element is added to a priority queue.
  if (argc != 2)
    {
      cout << "Usage: " << argv[0] << " <number of pairs to generate>" << endl;
      return - 1;
    }

  int count = atoi(argv[1]);
  cout << "Creating priority queue of size " << count << endl;
  std::vector<C_FLOAT64> invec;
  CIndexedPriorityQueue pq;
  CRandom *rand = new CRandom(1);
  C_FLOAT64 rndval;
  cout << "Input vector:\n";

  for (int i = 0; i < count; i++)
    {
      rndval = rand->getUniformRandom();
      invec.push_back(rndval);
      cout << "element " << i << ":" << rndval << endl;
      pq.pushPair(i, invec[i]);
    }

  cout << "Building heap\n";
  pq.buildHeap();
  cout << "Done building heap\n";
  // Display the priority queue
  cout << "\nPriority Queue:\n";

  for (int i = 0; i < count; i++)
    {
      cout << "Queue: ";

      for (int j = 0; j < count; j++) cout << " " << j << "-" << pq[j];

      cout << endl;
      cout << "Position: " << i;
      cout << " Index = " << pq.topIndex();
      cout << " Key = " << pq.topKey() << endl;
      pq.updateNode(pq.topIndex(), 10000000);
    }

  return 0;
}
Пример #25
0
u8 EDetailManager::GetRandomObject(u32 color_index)
{
	ColorIndexPairIt CI=m_ColorIndices.find(color_index);
	R_ASSERT(CI!=m_ColorIndices.end());
	int k = DetailRandom.randI(0,CI->second.size());
    DetailIt it = std::find(objects.begin(),objects.end(),CI->second[k]);
    VERIFY(it!=objects.end());
	return u8(it-objects.begin());
}
Пример #26
0
static HRESULT CreateTempEvent(const wchar_t *name,
    NSynchronization::CManualResetEvent &event, UString &eventName)
{
  CRandom random;
  random.Init(GetTickCount());
  for (;;)
  {
    int number = random.Generate();
    wchar_t temp[32];
    ConvertUInt64ToString((UInt32)number, temp);
    eventName = name;
    eventName += temp;
    RINOK(event.CreateWithName(false, GetSystemString(eventName)));
    if (::GetLastError() != ERROR_ALREADY_EXISTS)
      return S_OK;
    event.Close();
  }
}
Пример #27
0
void CRoundManObject::CruisingAi(){ //just cruising along
	
if(g_cTimer.elapsed(m_nHeightTime, m_nHeightDelayTime))
	{
	int rand = g_cRandom.number(1,1000);
	m_nHeightDelayTime=100+g_cRandom.number(0,500);
	
	if(rand % 3 == 0)
	{
		rand = g_cRandom.number(1,1000);
		if(rand%2 == 0)
		{
		m_fXspeed = 0;
		m_fXspeed = 8;
		}
		else
		{
		m_fYspeed = 0;
		m_fYspeed = 8;
		}
	}
	else if(rand%3 == 1)
	{
		rand = g_cRandom.number(1,1000);
		if(rand%2 == 0)
		{
		m_fXspeed = 0;
		m_fXspeed = -8;
		}
		else
		{
		m_fYspeed = 0;
		m_fYspeed = -8;
		}
	}
	else
	{
		m_fXspeed = m_fYspeed = 0;
	}
	if(CLOSE_DISTANCE > m_fDistance)
	SetState(CHASINGS5_STATE);
	}

}
Пример #28
0
//load model, trail texture and brake texture
void CAsteroid::load(TAsteroidType type)
{

   static CRandom prng(37473);

   // Select model
   const char* strRoidFile = NULL;
   float fRandom(prng.randDouble());

   switch (type) {
   case ROID_GOLD:
      strRoidFile = fRandom > 0.5 ? roidfiles[1] : roidfiles[2];
      break;
   case ROID_ICE:
      strRoidFile = roidfiles[3];
      break;
   case ROID_RED:      
      if (fRandom < 0.333)
         strRoidFile = roidfiles[4];
      if (fRandom < 0.667)
         strRoidFile = roidfiles[5];
      else
         strRoidFile = roidfiles[6];
      break;
	case ROID_COPPER:
		strRoidFile = roidfiles[7];
		break;
   case ROID_COMMON:
   default:
      strRoidFile = roidfiles[0];
      break;
   }

   // Load model
   NSDIO::CLoad3DS oLoad3ds;
   if (oLoad3ds.import3DS(&(m_oModel), strRoidFile)) {
      m_oModel.init();
   }  

   // Set position
   CVector3 pos((prng.randDouble()-0.5) * 5000,(prng.randDouble()-0.5) * 5000,(prng.randDouble()-0.5) * 5000);
   m_ppMasses[0]->m_vecPos = pos;   

}
Пример #29
0
//---------------------------------------------------------------------------
//	@function:
//		CXMLSerializerTest::EresUnittest_Base64
//
//	@doc:
//		Testing base64 encoding and decoding
//
//---------------------------------------------------------------------------
GPOS_RESULT
CXMLSerializerTest::EresUnittest_Base64()
{
	CAutoMemoryPool amp;
	IMemoryPool *pmp = amp.Pmp();

	const ULONG ulraSize=5;
	ULONG rgulRandArr[ulraSize];
	
	CRandom cr;
	for (ULONG i=0;i<ulraSize;i++)
	{
		rgulRandArr[i] = cr.ULNext();
	}
	
	CWStringDynamic *pstr = CDXLUtils::PstrFromByteArray(pmp, (BYTE *) rgulRandArr, sizeof(rgulRandArr));

	ULONG len;
	
	ULONG *pulRandArrCopy = (ULONG *) CDXLUtils::PByteArrayFromStr(pmp, pstr, &len);
	
	GPOS_ASSERT(len == sizeof(rgulRandArr));

	for (ULONG i=0;i<ulraSize;i++)
	{
		if (rgulRandArr[i] != pulRandArrCopy[i])
		{
			return GPOS_FAILED;
		}
	}

	GPOS_DELETE(pstr);
	GPOS_DELETE_ARRAY(pulRandArrCopy);

	INT i = 1000;
	pstr = CDXLUtils::PstrFromByteArray(pmp, (BYTE *) &i, sizeof(i));
	
	gpos::oswcout << "Base64 encoding of " << i << " is " << pstr->Wsz() << std::endl;
	
	GPOS_DELETE(pstr);
	
	return GPOS_OK;
}
Пример #30
0
BOOL ComposeFrame(){ //compose a frame of animation
  //draw background


  static int next_powerup = Timer.time()+Random.number(3000,12000);
  static int frame = 1;
  RECT rect; //drawing rectangle
  rect.left=0; rect.right=g_nScreenWidth; 
  rect.top=0; rect.bottom=g_nScreenHeight; 
  lpSecondary->Blt(&rect,lpBackground,&rect,DDBLT_WAIT,NULL);
  //move objects


  Viewpoint.draw_background(lpBackground,lpSecondary,8);
  
  int collision = theObjects.collisiondetection();
  
  
  theObjects.animate(lpSecondary);	//animate the current frame
  theObjects.refresh(collision);	//refresh the objects

  


if(Timer.time()>=next_powerup){
	theObjects.powerup();
    next_powerup += Random.number(10000,30000);	//next power up in 10 - 30 sec
	
}

  //frame rate
  framecount++; //count frame
  if(Timer.elapsed(framerate_timer,500)){

   theObjects.set_current(STARFIRE_INDEX);
	  theObjects.changedirection(0,0);
    last_framecount=framecount; framecount=0;
  }
 
  return PageFlip(); //flip video memory surfaces
 // return TRUE;
} //ComposeFrame