Ejemplo n.º 1
1
CPlaylistItem& CPlaylist::GetNextWrap(POSITION& pos)
{
    if (AfxGetAppSettings().bShufflePlaylistItems && GetCount() > 2) {
        pos = Shuffle();
    } else {
        GetNext(pos);
        if (!pos) {
            pos = GetHeadPosition();
        }
    }

    return GetAt(pos);
}
Ejemplo n.º 2
0
CPlaylistItem& CPlaylist::GetNextWrap(POSITION& pos)
{
	if(PlayerPreference::GetInstance()->GetIntVar(INTVAR_SHUFFLEPLAYLISTITEMS) && GetCount() > 2)
	{
		pos = Shuffle();
	}
	else
	{
		GetNext(pos);
		if(!pos) pos = GetHeadPosition();
	}

	return(GetAt(pos));
}
Ejemplo n.º 3
0
void BESCipher::Init()
{
    for (int i = 0; i < 256; i++)
    {
        Cipher[i] = (byte) i;
    }

    Shuffle(10);

    for (int i = 0; i < 256; i++)
    {
        std::cout << to_string(Cipher[i]) << endl;
    }
}
Ejemplo n.º 4
0
void BenchMaps() {
    const ui32 seed = 19650218UL; // TODO: take from command line
    TMersenne<ui32> rng(seed);
    TVector<ui32> keys;
    for (size_t i = 0; i < ElementsCount; ++i) {
        keys.push_back(rng.GenRand() % MaxElementValue);
    }

    TVector<ui32> shuffledKeys(keys);
    Shuffle(shuffledKeys.begin(), shuffledKeys.begin(), rng);

    size_t yhashMapFound, denseHashMapFound, stdHashMapFound, googleDenseHashMapFound;

    {
        THashMap<ui32, ui32> yhashMap;
        BenchAddingToHashMap(yhashMap, keys, "adding to THashMap");
        yhashMapFound = BenchGettingFromHashMap(yhashMap, shuffledKeys, "getting from THashMap");
        BenchSerialization(yhashMap, "THashMap");
    }
    Cout << "---------------" << Endl;
    {
        TDenseHashAdapter<ui32, ui32> denseHash((ui32)-1);
        BenchAddingToHashMap(denseHash, keys, "adding to dense hash");
        denseHashMapFound = BenchGettingFromHashMap(denseHash, shuffledKeys, "getting from dense hash");
        BenchSerialization(denseHash, "dense hash");
    }
    Cout << "---------------" << Endl;
    {
        TStdHash<ui32, ui32> stdHash;
        BenchAddingToHashMap(stdHash, keys, "adding to std hash");
        stdHashMapFound = BenchGettingFromHashMap(stdHash, shuffledKeys, "getting from std hash");
        BenchSerialization(stdHash, "std hash");
    }
    Cout << "---------------" << Endl;
    {
        TGoogleDenseHash<ui32, ui32> googleDenseHash;
        BenchAddingToHashMap(googleDenseHash, keys, "adding to google dense hash");
        googleDenseHashMapFound = BenchGettingFromHashMap(googleDenseHash, shuffledKeys, "getting from google dense hash");
        BenchSerialization(googleDenseHash, "google dense hash");
    }
    Cout << "---------------" << Endl;

    Cout << "found in THashMap: " << yhashMapFound << "\n";
    Cout << "found in dense hash: " << denseHashMapFound << "\n";
    Cout << "found in std hash: " << stdHashMapFound << "\n";
    Cout << "found in google dense hash: " << googleDenseHashMapFound << "\n";

    Cout << "\n";
}
Ejemplo n.º 5
0
void TfrmObjAllocMain::Stress(void)
{
	clock_t start, end;

	int size = sizeof(TStudent);
	int MaxPages = StrToInt(edtMaxPages->Text);
	int ObjectsPerPage = StrToInt(edtObjectsPerPage->Text);
	int padbytes = StrToInt(edtPaddingSize->Text);
	int Align = StrToInt(edtAlignment->Text);
	int headers = StrToInt(edtHeaderSize->Text);
	int total = MaxPages * ObjectsPerPage;
	void **ptrs = new void *[total];

	OAConfig config(radUseCPPHeapMgr->Checked,
									ObjectsPerPage,
									MaxPages,
									chkDebugState->Checked,
									padbytes,
									headers,
									Align
								 );
	ObjectAllocator *oa = new ObjectAllocator(size, config);

	start = clock();
	for (int i = 0; i < total; i++)
	{
		void *p = oa->Allocate();
		ptrs[i] = p;
		Application->ProcessMessages();
	}

	if (FIsProcessing)
	{
		Shuffle(ptrs, total);
		for (int i = 0; i < total; i++)
		{
			oa->Free(ptrs[i]);
			Application->ProcessMessages();
			if (!FIsProcessing)
				break;
		}
	}

	delete oa;
	end = clock();
	lblElapsedTime->Caption = Format("%4.3f secs", ARRAYOFCONST(( ((double)end - start) / 1000)) );
	delete [] ptrs;
}
Ejemplo n.º 6
0
    /*
      The construtor creates 13 cards for each of the 4 suits
      and thens huffles them.
    */
    Deck()
    {
      int i, j, index;
      for(i=0; i < 4; i++)
      {
        for(j=1; j <= 13; j++)
        {
          index = (i*13) + j - 1;
          this->deck[index].value = j;
          this->deck[index].suit = i;
        }
      }

      Shuffle();
      this->used_index = 0;
    }
Ejemplo n.º 7
0
void Net::Train(const mxArray *mx_data, const mxArray *mx_labels) {  

  //mexPrintMsg("Start training...");  
  ReadData(mx_data);
  ReadLabels(mx_labels);
  InitNorm();
  
  size_t train_num = data_.size1();
  size_t numbatches = DIVUP(train_num, params_.batchsize_);
  trainerrors_.resize(params_.epochs_, 2);
  trainerrors_.assign(0);
  for (size_t epoch = 0; epoch < params_.epochs_; ++epoch) {    
    if (params_.shuffle_) {
      Shuffle(data_, labels_);      
    }
    StartTimer();    
    size_t offset = 0;
    Mat data_batch, labels_batch, pred_batch;      
    for (size_t batch = 0; batch < numbatches; ++batch) {
      size_t batchsize = MIN(train_num - offset, params_.batchsize_);      
      UpdateWeights(epoch, false);
      data_batch.resize(batchsize, data_.size2());
      labels_batch.resize(batchsize, labels_.size2());      
      SubSet(data_, data_batch, offset, true);      
      SubSet(labels_, labels_batch, offset, true);
      ftype error1;      
      InitActiv(data_batch);
      Forward(pred_batch, 1);            
      InitDeriv(labels_batch, error1);
      trainerrors_(epoch, 0) += error1;
      Backward();
      UpdateWeights(epoch, true); 
      offset += batchsize;
      if (params_.verbose_ == 2) {
        mexPrintInt("Epoch", (int) epoch + 1);
        mexPrintInt("Batch", (int) batch + 1);
      }
    } // batch  
    MeasureTime("totaltime");
    if (params_.verbose_ == 1) {
      mexPrintInt("Epoch", (int) epoch + 1);
    }        
  } // epoch  
  trainerrors_ /= (ftype) numbatches;
  //mexPrintMsg("Training finished");
}
Ejemplo n.º 8
0
void ShuffleRound::HandleData(QDataStream &stream, const Id &id)
{
    qDebug() << _group.GetIndex(_local_id) << _local_id.ToString() <<
             ": received initial data from " << _group.GetIndex(id) << id.ToString();

    if(_state != KeySharing && _state != DataSubmission &&
            _state != WaitingForShuffle)
    {
        qWarning() << "Received a data message while in state " <<
                   StateToString(_state) << " from " << id.ToString();
        return;
    }

    int idx = _group.GetIndex(_local_id);
    if(idx != 0) {
        qWarning() << "Received a data message while not the first node " <<
                   " in the group.  Actual position: " << idx;
        return;
    }

    QByteArray data;
    stream >> data;

    idx = _group.GetIndex(id);

    if(data.isEmpty()) {
        qWarning() << _group.GetIndex(_local_id) << _local_id.ToString() <<
                   ": received null data from " << idx << id.ToString();
        return;
    }

    if(!_shuffle_data[idx].isEmpty()) {
        if(_shuffle_data[idx] != data) {
            qWarning() << "Received a second data message from " << id.ToString();
        } else {
            qWarning() << "Received a duplicate data message from " << id.ToString();
        }
        return;
    }

    _shuffle_data[idx] = data;

    if(++_data_received == _group.GetSize()) {
        Shuffle();
    }
}
Ejemplo n.º 9
0
void FreeCell::newDeal(difficulty_type h)
{
    for (int n = 0; n < 8; n++)
        tableau[n] = new TableauPile(10 + (n) * (CARD_WIDTH + CARD_SPACING + 10), 10 + CARD_HEIGHT + 15, 0, 18, parent);
    tableau[0]->AddDropRules(3,
                             new ProhibitDropSameColor,
                             new DropOneDown,
                             new DropFreeCellLimit);
    tableau[0]->AddDragRules(3,
                             new DragStackDecreasing,
                             new DragFreeCellLimit,
                             new DragAlternatingColors);
    for (int n = 0; n < 4; n++)
        freecell[n] = new FreeCellPile(10 + (n) * (CARD_WIDTH + CARD_SPACING), 10, 0, 0, parent);
    freecell[0]->AddDropRules(2,
                              new DropEmptyStack,
                              new DropSingle);
    freecell[0]->AddDragRules(0);
    for (int n = 0; n < 4; n++)
        foundation[n] = new FoundationPile(79 + (n+4) * (CARD_WIDTH + CARD_SPACING), 10, 0, 0, parent);
    foundation[0]->AddDropRules(4,
                                new AceOnEmpty,
                                new AllowDropSameSuit,
                                new DropOneUp,
                                new DropSingle);
    foundation[0]->AddDragRules(1,
                                new ProhibitDrag);

    Card* Deck[52];
    for (int v = 0; v < 52; v++)
        Deck[v] = new Card(v, parent);
    Shuffle(Deck, 52);
    int n = 0;
    while (n < 52)
    {
        int column = 0;
        while (column < 8 && n < 52)
        {
            Deck[n]->Faceup(true);
            tableau[column]->acceptCard(Deck[n++], true, false, false);
            column++;
        }
    }

}
Ejemplo n.º 10
0
void main (void)
{

	worldADT world;
	int i;
	double time=InitialTimeInterval;
	int numcreature;
	speciesADT *speciesP;
	creatureADT *creatureP; 


	while(TRUE)
	{
		Randomize();
		InitGraphics();
		InitWorldMap(NColumns,NRows);
		i=0;
		numcreature=0;
	
		world=NewWorld(NColumns,NRows);
		PrintInstructions1();

		speciesP=SetSpecies(&numcreature);
		speciesP=Shuffle(speciesP,numcreature);
	
		creatureP=GetBlock( numcreature * sizeof (creatureADT) );
		PlacingCreatures(world,creatureP,speciesP,numcreature);
		
		PrintInstructions2();

		while ( !MouseButtonIsDown() || WantToContinue(creatureP,numcreature,&time) )
		{
			TakeOneTurn(creatureP[i]);
			i=(i+1)%numcreature;
			Pause(time);
		}
				
		FreeWorld(world);
		FreeBlock(creatureP);

		if (!WantToPlayAgain())  {break;}

	}
}
Ejemplo n.º 11
0
/* Deal out the next card of the shoe */
const Card Croupier::Deal()
{
	Card TempStore;

	NextCard++;
	/* When the cut card is reached, reshuffle the shoe */
	string CompareString = Shoe[NextCard].GetName();
	if (CompareString.compare("Cut") == 0)
	{	
		cout << "Cut card reached. Reshuffling cards...." << endl << endl;
		/* Move the cut card to the end of the pack so that it isn't shuffled */
		TempStore = Shoe[ShoeSize];
		Shoe[ShoeSize] = Shoe[NextCard];
		Shoe[NextCard] = TempStore;
		Shuffle();
		NextCard = 0;
	}
	return Shoe[NextCard];
}
Ejemplo n.º 12
0
Archivo: tile.cpp Proyecto: kyak/Tile
void Tile::Shuffle()
{
    Reset();
    for (int i = 1; i < 16; i++) {
        //get random number 1..15
        int id = randInt(1,15);
        //swap it
        QPushButton *button_1 = idtoButton(i);
        QPushButton *button_2 = idtoButton(id);
        QString str = button_1->text();
        button_1->setText(button_2->text());
        button_2->setText(str);
    }
    if (!isSolvable()) {
        Shuffle();
    } else {
        isRunning = 1;
    }
}
Ejemplo n.º 13
0
void ShuffleRound::HandleShuffle(QDataStream &stream, const Id &id)
{
    qDebug() << _group.GetIndex(_local_id) << _local_id.ToString() <<
             ": received shuffle data from " << _group.GetIndex(id) << id.ToString();

    if(_state != WaitingForShuffle) {
        qWarning() << "Received a shuffle message while in state " <<
                   StateToString(_state) << " from " << id.ToString();
        return;
    }

    if(_group.Previous(_local_id) != id) {
        qWarning() << "Received shuffle out of order from " << id.ToString();
        return;
    }

    stream >> _shuffle_data;

    Shuffle();
}
Ejemplo n.º 14
0
int ShuffleCommand :: Execute( ALib::CommandLine & cmd ) {

    ProcessFlags( cmd );
    mRows.clear();
    IOManager io( cmd );
    CSVRow row;

    if ( mFields.size() == 0 ) {
        while( io.ReadCSV( row ) ) {
            mRows.push_back( row );
        }
        Shuffle( io );
    }
    else {
        while( io.ReadCSV( row ) ) {
            ShuffleFields( row );
            io.WriteRow( row );
        }
    }
    return 0;
}
Ejemplo n.º 15
0
void OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
	switch( id )
	{
	case ID_GAME_NEW: 
		if ( g_bRunning == TRUE )
		{
			UINT ret = MessageBox(hwnd, "현재 게임을 포기 하시겠습니까 ?", "확인", MB_YESNO);
			if (ret != IDYES ) return;
		} 
		Shuffle( hwnd );
		g_bRunning = TRUE;
			return;


	case ID_GAME_HINT: return;

	case ID_GAME_EXIT:
		SendMessage( hwnd, WM_CLOSE, 0,0);
		return;
	}
}
Ejemplo n.º 16
0
// Sets up the array of cards to be a unique deck
void Deck::Initialize()
{
	/* TODO Lab3:
			Implement this method.
	
			Set the values in the m_cards array to be the appropriate values for your game.

			For Go Fish: 13 cards of each of the 4 suits
	*/
	
	int index = 0;
	for (size_t i = 3; i <= 6; i++)
	{
		for (size_t j = 2; j <= 14; j++)
		{
			m_cards[index].SetSuit(i);
			m_cards[index].SetFace(j);
			index++;
		}
	}
	Shuffle();
}
Ejemplo n.º 17
0
void test4_16()
{
  std::cout << "==================== test4_16 ====================\n";
  const unsigned asize = 1;

  Digipen::Utils::srand(2, 1);
  BList<int, asize> bl;
  std::cout << "nodesize is " << bl.nodesize() << std::endl;
  unsigned low = 10;
  unsigned high = 99;
  unsigned range = high - low;
  unsigned size = 16;
  int *ia = new int[range];
  for (unsigned i = low; i < high; i++)
    ia[i - low] = i + 1;

  Shuffle(ia, range);
  for (unsigned i = 0; i < size; i++) 
  {
    bl.insert(ia[i]);
    //DumpList(bl, true);
    //DumpList(bl);
    //std::cout << "==========================\n";
  }
  DumpList(bl, false);

  for (unsigned i = 0; i < size; i++) 
  {
    std::cout << bl[i] << " ";
  }
  std::cout << std::endl << std::endl;

  DumpList(bl, false);
  DumpList(bl, true);
  DumpStats(bl);
  std::cout << std::endl;
  delete [] ia;
}
Ejemplo n.º 18
0
//a simple constructor that takes a x and y size of a board and creates a 1d array,
//later on the 1d array is accessed using indexes calculated as if it were a 2d array.
//A winning arrangement is also calculated.
Board::Board(int X, int Y)
{

    sizeX = X;
    sizeY = Y;
    maxVal = (sizeX * sizeY);

    board = new int[maxVal];
    winningArrangement = new int[maxVal];

    //initialise the board
    InitBoard();
    emptyVal = maxVal - 1;
    Cursor.x = 0;
    Cursor.y = 0;

    //shuffle the board
    Shuffle();

    //create the empty square!
    InitEmptySquare();

}
Ejemplo n.º 19
0
// MaxMinDistSampler Method Definitions
void MaxMinDistSampler::StartPixel(const Point2i &p) {
    Float invSPP = (Float)1 / samplesPerPixel;
    for (int i = 0; i < samplesPerPixel; ++i)
        samples2D[0][i] = Point2f(i * invSPP, SampleGeneratorMatrix(CPixel, i));
    Shuffle(&samples2D[0][0], samplesPerPixel, 1, rng);
    // Generate remaining samples for _MaxMinDistSampler_
    for (size_t i = 0; i < samples1D.size(); ++i)
        VanDerCorput(1, samplesPerPixel, &samples1D[i][0], rng);

    for (size_t i = 1; i < samples2D.size(); ++i)
        Sobol2D(1, samplesPerPixel, &samples2D[i][0], rng);

    for (size_t i = 0; i < samples1DArraySizes.size(); ++i) {
        int count = samples1DArraySizes[i];
        VanDerCorput(count, samplesPerPixel, &sampleArray1D[i][0], rng);
    }

    for (size_t i = 0; i < samples2DArraySizes.size(); ++i) {
        int count = samples2DArraySizes[i];
        Sobol2D(count, samplesPerPixel, &sampleArray2D[i][0], rng);
    }
    PixelSampler::StartPixel(p);
}
Ejemplo n.º 20
0
void test6_512()
{
  std::cout << "==================== test5_512 ====================\n";
  const unsigned asize = 512;

  BList<int, asize> bl;
  std::cout << "nodesize is " << bl.nodesize() << std::endl;
  unsigned low = 1000;
  unsigned high = 9999;
  unsigned range = high - low;
  unsigned size = 8000;
  int *ia = new int[range];
  for (unsigned i = low; i < high; i++)
    ia[i - low] = i + 1;

  Shuffle(ia, range);

  for (unsigned i = 0; i < size; i++)
    bl.insert(ia[i]);

  //DumpList(bl, true);
  //DumpList(bl, false);
  for (unsigned i = 0; i < size; i++)
  {
    int index = bl.find(ia[i]);
    if (index == -1)
      std::cout << "Item: " << ia[i] << " not found. Something's wrong.\n";
    else
      if (!(i % 400))
        std::cout << "Found " << ia[i] << " at index " << index << std::endl;
  }
  std::cout << std::endl;
  DumpStats(bl);
  std::cout << std::endl;

  delete [] ia;
}
Ejemplo n.º 21
0
Archivo: tile.cpp Proyecto: kyak/Tile
void Tile::swapButtons(QPushButton *button, QPushButton *button_neighbour) {
    button->hide();
    button_neighbour->setText(button->text());
    button->setText("16");
    button_neighbour->show();
    button_neighbour->setFocus();
    if (isRunning) {
        Moves++;
        updateMoves();
    }
    if (isRunning && isSolved()) {
        isRunning = 0;
        switch (QMessageBox::information(this,
                                 "Solved!",
                                 "Hooray, you solved it!\nShuffle again?",
                                 "&Yes","&No"))
        {
        case 0:
            Shuffle();
        default:
            break;
        }
    }
}
Ejemplo n.º 22
0
static void
NewGame (void)
{
    int	color, shape, i;

    DIAG (("NewGame\n"));
    game.seed = TimGetTicks ();
    RandomBoard (game.board);
    DamageBoard ();
    i = 0;
    for (color = RED; color <= BLUE; color = COLOR_NEXT(color))
        for (shape = TARGET_TRIANGLE;
                shape <= TARGET_CIRCLE;
                shape = TARGET_NEXT(shape))
        {
            game.targets[i++] = shape|color;
        }
    game.targets[i++] = TARGET_WHIRL|COLOR_ANY;
    DIAG (("Generated %d targets\n", i));
    Shuffle (game.targets, i);
    game.ntarget = 0;
    DIAG (("NextTarget\n"));
    NextTarget ();
}
Ejemplo n.º 23
0
NzWorley2D::NzWorley2D(unsigned int seed) : NzWorley2D()
{
    SetSeed(seed);
    Shuffle();
}
Ejemplo n.º 24
0
	Worley::Worley(unsigned int seed) :
	Worley()
	{
		SetSeed(seed);
		Shuffle();
	}
Ejemplo n.º 25
0
void MySort::QuickSort(int* a,int length)
{
	Shuffle(a,length);
	sortquick(a,0,length-1);
}
Ejemplo n.º 26
0
Simplex::Simplex(unsigned int seed) : Simplex()
{
    SetSeed(seed);
    Shuffle();
}
Ejemplo n.º 27
0
int main () {
int c;

	srand (0);
	InitDeck (&Deck);
	Shuffle (&Deck);		/* Shuffle Deck. */

#if 1
	printf ("STRAIGHT_FLUSH_SCORE\t%08x\n",STRAIGHT_FLUSH_SCORE);
	printf ("FOUR_KIND_SCORE\t\t%08x\n",FOUR_KIND_SCORE);
	printf ("FULL_HOUSE_SCORE\t%08x\n",FULL_HOUSE_SCORE);
	printf ("FLUSH_SCORE\t\t%08x\n",FLUSH_SCORE);
	printf ("STRAIGHT_SCORE\t\t%08x\n",STRAIGHT_SCORE);
	printf ("THREE_KIND_SCORE\t%08x\n",THREE_KIND_SCORE);
	printf ("TWO_PAIR_SCORE\t\t%08x\n",TWO_PAIR_SCORE);
	printf ("TWO_KIND_SCORE\t\t%08x\n",TWO_KIND_SCORE);

	printf ("\n");

	for (c=0; c < 8; c++) {
		Deal (&Hand, &Deck, 5);
		DisplayHand5 (&Hand);
		Deal (&Deck, &Hand, 5);
		Shuffle (&Deck);
	}

	for (c=0; c < 8; c++) {
		Deal (&Hand, &Deck, 7);
		DisplayHand7 (&Hand);
		Deal (&Deck, &Hand, 7);
		Shuffle (&Deck);
	}

	printf("\nRigged hands\n\n");

	Hand.len = 5;
	Hand.entry[0] = 12;
	Hand.entry[1] = 12+13;
	Hand.entry[2] = 12+26;
	Hand.entry[3] = 12+39;
	Hand.entry[4] = 11;
	DisplayHand5 (&Hand);

	Hand.entry[0] = 12;
	Hand.entry[1] = 12+13;
	Hand.entry[2] = 12+26;
	Hand.entry[3] = 11+39;
	Hand.entry[4] = 11;
	DisplayHand5 (&Hand);

	Hand.entry[0] = 12;
	Hand.entry[1] =  0+13;
	Hand.entry[2] =  1+26;
	Hand.entry[3] =  2+39;
	Hand.entry[4] =  3;
	DisplayHand5 (&Hand);

	printf ("\n");
#endif

#ifndef DETERMINISTIC
	srand ((unsigned int) time ((void *) 0));
#endif
	Shuffle (&Deck);		/* Shuffle Deck. */
	Hand.len = 0;

	c = 0;

	printf ("7 Card Draw test\n\n");

	for (;;) {
		Deal (&Hand, &Deck, 7);
		if (SevenCardDrawScore (&Hand.entry[0]) != SevenCardDrawScoreSlow (&Hand.entry[0])) break;
		Deal (&Deck, &Hand, 7);	/* Add hand back into Deck. */
		Shuffle (&Deck);		/* Reshuffle Deck.          */
		c++;
		if ((c & 0xFFFFF) == 0) {
#ifndef DETERMINISTIC
			srand ((unsigned int) time ((void *) 0));
#endif
			printf ("%d \t(no errors)\n", c);
		}
	}

	/* There must be an error ! */

	DisplayHand7 (&Hand);
	return 0;
}
Ejemplo n.º 28
0
void MLTTask::Run() {
    PBRT_MLT_STARTED_MLT_TASK(this);
    // Declare basic _MLTTask_ variables and prepare for sampling
    PBRT_MLT_STARTED_TASK_INIT();
    uint32_t nPixels = (x1-x0) * (y1-y0);
    uint32_t nPixelSamples = renderer->nPixelSamples;
    uint32_t largeStepRate = nPixelSamples / renderer->largeStepsPerPixel;
    Assert(largeStepRate > 1);
    uint64_t nTaskSamples = uint64_t(nPixels) * uint64_t(largeStepRate);
    uint32_t consecutiveRejects = 0;
    uint32_t progressCounter = progressUpdateFrequency;

    // Declare variables for storing and computing MLT samples
    MemoryArena arena;
    RNG rng(taskNum);
    vector<PathVertex> cameraPath(renderer->maxDepth, PathVertex());
    vector<PathVertex> lightPath(renderer->maxDepth, PathVertex());
    vector<MLTSample> samples(2, MLTSample(renderer->maxDepth));
    Spectrum L[2];
    float I[2];
    uint32_t current = 0, proposed = 1;

    // Compute _L[current]_ for initial sample
    samples[current] = initialSample;
    L[current] = renderer->PathL(initialSample, scene, arena, camera,
                     lightDistribution, &cameraPath[0], &lightPath[0], rng);
    I[current] = ::I(L[current]);
    arena.FreeAll();

    // Compute randomly permuted table of pixel indices for large steps
    uint32_t pixelNumOffset = 0;
    vector<int> largeStepPixelNum;
    largeStepPixelNum.reserve(nPixels);
    for (uint32_t i = 0; i < nPixels; ++i) largeStepPixelNum.push_back(i);
    Shuffle(&largeStepPixelNum[0], nPixels, 1, rng);
    PBRT_MLT_FINISHED_TASK_INIT();
    for (uint64_t s = 0; s < nTaskSamples; ++s) {
        // Compute proposed mutation to current sample
        PBRT_MLT_STARTED_MUTATION();
        samples[proposed] = samples[current];
        bool largeStep = ((s % largeStepRate) == 0);
        if (largeStep) {
            int x = x0 + largeStepPixelNum[pixelNumOffset] % (x1 - x0);
            int y = y0 + largeStepPixelNum[pixelNumOffset] / (x1 - x0);
            LargeStep(rng, &samples[proposed], renderer->maxDepth,
                      x + dx, y + dy, t0, t1, renderer->bidirectional);
            ++pixelNumOffset;
        }
        else
            SmallStep(rng, &samples[proposed], renderer->maxDepth,
                      x0, x1, y0, y1, t0, t1, renderer->bidirectional);
        PBRT_MLT_FINISHED_MUTATION();

        // Compute contribution of proposed sample
        L[proposed] = renderer->PathL(samples[proposed], scene, arena, camera,
                         lightDistribution, &cameraPath[0], &lightPath[0], rng);
        I[proposed] = ::I(L[proposed]);
        arena.FreeAll();

        // Compute acceptance probability for proposed sample
        float a = min(1.f, I[proposed] / I[current]);

        // Splat current and proposed samples to _Film_
        PBRT_MLT_STARTED_SAMPLE_SPLAT();
        if (I[current] > 0.f) {
            if (!isinf(1.f / I[current])) {
            Spectrum contrib =  (b / nPixelSamples) * L[current] / I[current];
            camera->film->Splat(samples[current].cameraSample,
                                (1.f - a) * contrib);
        }
        }
        if (I[proposed] > 0.f) {
            if (!isinf(1.f / I[proposed])) {
            Spectrum contrib =  (b / nPixelSamples) * L[proposed] / I[proposed];
            camera->film->Splat(samples[proposed].cameraSample,
                                a * contrib);
        }
        }
        PBRT_MLT_FINISHED_SAMPLE_SPLAT();

        // Randomly accept proposed path mutation (or not)
        if (consecutiveRejects >= renderer->maxConsecutiveRejects ||
            rng.RandomFloat() < a) {
            PBRT_MLT_ACCEPTED_MUTATION(a, &samples[current], &samples[proposed]);
            current ^= 1;
            proposed ^= 1;
            consecutiveRejects = 0;
        }
        else
        {
            PBRT_MLT_REJECTED_MUTATION(a, &samples[current], &samples[proposed]);
            ++consecutiveRejects;
        }
        if (--progressCounter == 0) {
            progress.Update();
            progressCounter = progressUpdateFrequency;
        }
    }
    Assert(pixelNumOffset == nPixels);
    // Update display for recently computed Metropolis samples
    PBRT_MLT_STARTED_DISPLAY_UPDATE();
    int ntf = AtomicAdd(&renderer->nTasksFinished, 1);
    int64_t totalSamples = int64_t(nPixels) * int64_t(nPixelSamples);
    float splatScale = float(double(totalSamples) / double(ntf * nTaskSamples));
    camera->film->UpdateDisplay(x0, y0, x1, y1, splatScale);
    if ((taskNum % 8) == 0) {
        MutexLock lock(*filmMutex);
        camera->film->WriteImage(splatScale);
    }
    PBRT_MLT_FINISHED_DISPLAY_UPDATE();
    PBRT_MLT_FINISHED_MLT_TASK(this);
}
Ejemplo n.º 29
0
void GROUPAI::GroupAI()
{
	if(m_members.empty() || m_pMaster == NULL)return;

	int memberStates[] = {0, 0, 0};
	m_state = GROUP_STATE_IDLE;

	std::vector<MAPOBJECT*>::iterator i;
	for(i = m_members.begin();i != m_members.end();)
	{
		if((*i) == NULL || (*i)->m_dead)
		{
			//Remove dead Group m_members
			RemoveMember(*i);
		}
		else 
		{
			(*i)->m_pGroup = this;

			//determine group m_state
			if(!(*i)->m_isBuilding)
			{
				UNIT *unit = (UNIT*)(*i);
				
				if(unit->m_state == STATE_ATTACK)
					memberStates[GROUP_STATE_BATTLE]++;
				else if(unit->m_moving)
					memberStates[GROUP_STATE_MOVING]++;
				else memberStates[GROUP_STATE_IDLE]++;
			}
			i++;
		}
	}

	//Set group state
	if(memberStates[GROUP_STATE_BATTLE] >= m_members.size() * 0.2f)
		m_state = GROUP_STATE_BATTLE;
	else if(memberStates[GROUP_STATE_MOVING] >= m_members.size() * 0.4f)
		m_state = GROUP_STATE_MOVING;
	else m_state = GROUP_STATE_IDLE;

	//Group state machine
	switch(m_state)
	{
		case GROUP_STATE_IDLE:
		{			
			if(m_task == TASK_SCOUT)
			{
				AREA *area = m_pMaster->m_pStrategyMap->GetScoutArea(GetCenter());
				if(area != NULL)Goto(area->m_mapArea);
			}
			else if(m_task == TASK_ATTACK_LOCATION)
			{
				AREA *area = m_pMaster->m_pStrategyMap->GetAttackArea(GetCenter());
				if(area != NULL)Goto(area->m_mapArea);				
			}
			else if(m_task == TASK_NONE || m_task == TASK_DEFEND_LOCATION)
			{
				Shuffle();
			}

			break;
		}
		case GROUP_STATE_MOVING:
		{
			Attack(m_visibleEnemies);

			break;
		}
		case GROUP_STATE_BATTLE:
		{
			Attack(m_visibleEnemies);

			if(m_task == TASK_DEFEND_LOCATION)
				RetreatTo(m_mapArea);

			break;
		}
	}

	//Report enemies to Master AI
	m_pMaster->EnemiesSpotted(m_visibleEnemies);
	m_visibleEnemies.clear();
}
Ejemplo n.º 30
0
Archivo: puzzle.c Proyecto: paa/vlc
/**
 * Filter a picture
 */
static picture_t *Filter( filter_t *p_filter, picture_t *p_pic )
{
    filter_sys_t *p_sys = p_filter->p_sys;

    picture_t *p_outpic = filter_NewPicture( p_filter );
    if( !p_outpic )
    {
        picture_Release( p_pic );
        return NULL;
    }

    /* */
    vlc_mutex_lock( &p_sys->lock );
    if( p_sys->b_change )
    {
        p_sys->i_rows      = p_sys->change.i_rows;
        p_sys->i_cols      = p_sys->change.i_cols;
        p_sys->b_blackslot = p_sys->change.b_blackslot;
        p_sys->b_change = false;

        Shuffle( p_sys );
    }
    vlc_mutex_unlock( &p_sys->lock );

    /* */
    const int i_rows = p_sys->i_rows;
    const int i_cols = p_sys->i_cols;

    /* Draw each piece of the puzzle at the right place */
    for( int i_plane = 0; i_plane < p_outpic->i_planes; i_plane++ )
    {
        const plane_t *p_in = &p_pic->p[i_plane];
        plane_t *p_out = &p_outpic->p[i_plane];

        for( int i = 0; i < i_cols * i_rows; i++ )
        {
            int i_piece_height = p_out->i_visible_lines / i_rows;
            int i_piece_width  = p_out->i_visible_pitch / i_cols;

            int i_col = (i % i_cols) * i_piece_width;
            int i_row = (i / i_cols) * i_piece_height;
            int i_last_row = i_row + i_piece_height;

            int i_ocol = (p_sys->pi_order[i] % i_cols) * i_piece_width;
            int i_orow = (p_sys->pi_order[i] / i_cols) * i_piece_height;

            if( p_sys->b_blackslot && !p_sys->b_finished && i == p_sys->i_selected )
            {
                uint8_t color = ( i_plane == Y_PLANE ? 0x0 : 0x80 );
                for( int r = i_row; r < i_last_row; r++ )
                {
                    memset( p_out->p_pixels + r * p_out->i_pitch + i_col,
                            color, i_piece_width );
                }
            }
            else
            {
                for( int r = i_row, or = i_orow; r < i_last_row; r++, or++ )
                {
                    memcpy( p_out->p_pixels + r * p_out->i_pitch + i_col,
                            p_in->p_pixels + or * p_in->i_pitch  + i_ocol,
                            i_piece_width );
                }
            }

            /* Draw the borders of the selected slot */
            if( i_plane == 0 && !p_sys->b_blackslot && p_sys->i_selected == i )
            {
                memset( p_out->p_pixels + i_row * p_out->i_pitch + i_col,
                        0xff, i_piece_width );
                for( int r = i_row; r < i_last_row; r++ )
                {
                    p_out->p_pixels[r * p_out->i_pitch + i_col + 0             + 0 ] = 0xff;
                    p_out->p_pixels[r * p_out->i_pitch + i_col + i_piece_width - 1 ] = 0xff;
                }
                memset( p_out->p_pixels + (i_last_row - 1) * p_out->i_pitch + i_col,
                        0xff, i_piece_width );
            }
        }
    }

    /* Draw the 'Shuffle' button if the puzzle is finished */
    if( p_sys->b_finished )
    {
        plane_t *p_out = &p_outpic->p[Y_PLANE];
        for( int i = 0; i < SHUFFLE_HEIGHT; i++ )
        {
            for( int j = 0; j < SHUFFLE_WIDTH; j++ )
            {
                if( shuffle_button[i][j] == '.' )
                   p_out->p_pixels[ i * p_out->i_pitch + j ] = 0xff;
            }
        }
    }

    return CopyInfoAndRelease( p_outpic, p_pic );
}