Пример #1
0
void DFS::Solve(GraphNode *startNode, int maxIterations)
{
	StartTimer();
	stack<GraphNode*> nodesStack;

	GraphNode *node = new GraphNode(startNode);
	elements.push_back(node);
	nodesStack.push(node);
	node->visited = true;
	int iterations = 0;
	while (!node->IsSolution())
	{
		node->visited = true;
		node->FindNeighbours(elements);
		node->PushNeighbours(nodesStack);
		node = nodesStack.top();
		while ((node = nodesStack.top())->visited)
		{
			nodesStack.pop();
		}
		iterations++;
		if (iterations > maxIterations)
		{
			ShowResult(false, iterations);
			StopTimer();
			return;
		}
	}
	StopTimer();
	ShowResult(true, iterations, node);
}
Пример #2
0
/*
정인호. 11/14
현재 Base의 상황을 체크하여 게임 종료 여부를 체크.
불타입으로 변경, 스테이지 관련 부분 구현 후 내용추가할 필요가 있어보임
*/
bool CPlayScene::CheckGameOver()
{
	if (m_pPlayer->GetPlayerStatus() == PLAYER_ON_PLAYING ) {
		if(m_pMapCreator->GetPoliceBase()->GetHP() <= 0) {
			m_pPlayer->SetPlayerStatus(PLAYER_WIN);
			if (m_pPlayer->GetClearedStage() == m_pPlayer->GetPlayingStage() )
			{
				m_pPlayer->IncreaseClearedStage();
			}
			m_pPlayer->ReadyToSave();
			SaveGame();
			ShowResult(L"WIN");			
			printf_s("WIN!\n");
		} else if(m_pMapCreator->GetZombieBase()->GetHP() <= 0) {
			m_pPlayer->SetPlayerStatus(PLAYER_LOSE);
			m_pPlayer->ReadyToSave();
			SaveGame();
			ShowResult(L"LOSE");
			printf_s("LOSE!\n");
		} else {
			return false;	
		}
	} 
	else  // when the game is over
	{
		if( NNInputSystem::GetInstance()->GetKeyState(VK_LBUTTON) && m_pResultOKButton->CheckButtonArea() ) 
		{
			NNSceneDirector::GetInstance()->ChangeScene(CStageSelectScene::Create());
			m_pInstance = nullptr;		
		}
	}
	
	return true;
}
Пример #3
0
// 人 vs 人
void
GameManVsMan(void)
{
     BOARD board;
     uint64_t pos, valid;

     Init(&board);
     DispBoard(&board);

     // 石を置く
     while(board.teban != GAME_OVER){
	  // 合法手を得る
	  valid = GenValidMove(&board);
	  // 手を受け取る
	  pos = GetPos();
	  if (pos == INPUT_ERROR){
	       printf("エラーです。\n");
	       continue;
	  }
	  else if((pos & valid) == 0){
	       printf("非合法手です。\n");
	       continue;
	  }
	  Put(&board, pos);
	  DispBoard(&board);

	  CheckFinishPass(&board);
     }

     ShowResult(&board);

     return;
}
void COpenCVInterfaceDlg::OnContrastExponential()
{
	/*
	Creez un ob de tip ParametersDlg. Cat timp parametrii "m" si "E" nu sunt ambii numere,
	ii las utilizatorului oportunitatea de a introduce noi date.
	*/

	CParametersDlg parameters;
	while(parameters.areNumbers == false && parameters.windowWasClosed == false)
		parameters.DoModal();

	//	Intr-un final, datele introduse sunt bune. Fac conversia la double.
	if(parameters.areNumbers == true)
	{
		double m = 0, pE = 0;
		m = atof(parameters.m1);
		pE = atof(parameters.E1);


		// Modificarea imaginii

		prelImage=InitImage(mainImage.rows,mainImage.cols);
		for(int i=0;i<mainImage.rows;i++)
			for(int j=0;j<mainImage.cols;j++)
			{
				double c = pow(m,pE) / ( 255 * (pow(255,pE) + pow(m,pE)) );
				prelImage.at<uchar>(i,j)=255 * ( pow(mainImage.at<uchar>(i,j),pE) / ( pow(mainImage.at<uchar>(i,j),pE) + pow(m,pE) ) + c*mainImage.at<uchar>(i,j) );
			}
			ShowResult(prelImage);
	}
}
void COpenCVInterfaceDlg::OnLuminosityInverselogaritmicoperator()
{
	if(mainImage.cols)
	{
		prelImage=Tools::inverseLogaritm(mainImage);
		ShowResult(prelImage);
	}
	else
		MessageBox("No image loaded");
}
void COpenCVInterfaceDlg::OnSobelSobelpi4()
{
	if(mainImage.cols)
	{
		prelImage=Filters::sobelDirectional(mainImage);
		ShowResult(prelImage);
	}
	else
		MessageBox("No image loaded");

}
void COpenCVInterfaceDlg::OnContrastLogaritmicoperator()
{
	double *LookUp ;
	LookUp = CreateLookUpForContrast();
	prelImage=InitImage(mainImage.rows,mainImage.cols);
	for(int i=0;i<mainImage.rows;i++)
		for(int j=0;j<mainImage.cols;j++)
		{
			prelImage.at<uchar>(i,j)=LookUp[mainImage.at<uchar>(i,j)];
		}
		ShowResult(prelImage);
		delete LookUp;
}
void COpenCVInterfaceDlg::OnMorphologyConvexhull()
{
	if(mainImage.cols)
	{
		ConvexHull c;
		Mat rez=mainImage.clone();
		mainImage=Filters::gaussianFilter(mainImage,1);
		Scalar meanVal,stdval;

		meanStdDev(mainImage,meanVal,stdval);
		Canny(mainImage,mainImage,meanVal.val[0]*1/3.,meanVal.val[0]);
		//imshow("contours",mainImage);

		vector<std::vector<cv::Point>> contours;
		findContours(mainImage,contours,CV_RETR_LIST,CV_CHAIN_APPROX_NONE,Point(2,2));

		vector<Point> Points;
		//Points.resize(contours.size()*contours[0].size());
		for(int i=0;i<contours.size();i++)
		{
			for(int j=0;j<contours[i].size();j++)
			{
				Points.push_back(contours[i][j]);
			}
		}

		//for(int i=2;i<mainImage.rows-2;i++)
		//{
		//	for(int j=2;j<mainImage.cols-2;j++)
		//	{
		//		if(mainImage.at<uchar>(i,j)==255)
		//			Points.push_back(Point(i,j));
		//	}
		//}	

		std::vector<Point> chull;
		c.graham(Points, chull);

		for(int i=0;i<chull.size()-1;i++)
		{
			line(rez,chull[i],chull[i+1],Scalar(255,255,255),2);
		}

		line(rez,chull[chull.size()-1],chull[0],Scalar(255,255,255),2);
		prelImage=rez.clone();
		ShowResult(prelImage);
	}
	else
		MessageBox("No image loaded");
}
void COpenCVInterfaceDlg::OnFiltersMedianfilter()
{
	int n=mainImage.rows,m=mainImage.cols;
	prelImage=InitImage(n,m);
	int k;
	FiltruMedianCristi obj;
	if(obj.DoModal())
	{
		k = obj.getVal();
		prelImage = CalculeazaFiltruMedian(k);
		ShowResult(prelImage);
	}

}
Пример #10
0
void CMobilePhone::RunL(void)
{
  TBuf16<128> string;
  if(iStatus==KErrNone)
  {
    string.Append(_L("Success."));
  }
  else
  {
    string.Append(_L("Error ("));
    string.AppendNum(iStatus.Int());
    string.Append(_L(")."));
  }
  ShowResult(string);
}
void COpenCVInterfaceDlg::OnToolsInvert()
{
	if(mainImage.cols)
	{
		prelImage=InitImage(mainImage.rows,mainImage.cols);
		for(int i=0;i<mainImage.rows;i++)
			for(int j=0;j<mainImage.cols;j++)
			{
				prelImage.at<uchar>(i,j)=255-mainImage.at<uchar>(i,j);
			}

			ShowResult(prelImage);
	}
	else
		MessageBox("No image loaded");
}
void COpenCVInterfaceDlg::OnLuminosityGammacorrection()
{
	if(mainImage.cols)
	{
		GammaValue dlg;
		INT_PTR nRet=dlg.DoModal();
		if(nRet==IDOK)
		{
			double g=dlg.getGamma();
			prelImage=Tools::gammaCorrection(mainImage,g);
			ShowResult(prelImage);
		}
	}
	else
		MessageBox("No image loaded");
}
void COpenCVInterfaceDlg::OnToolsBinarization()
{
	if(mainImage.cols)
	{
		Bin1Val dlg;
		INT_PTR nRet=dlg.DoModal();
		if(nRet==IDOK)
		{
			int T=dlg.getT();
			prelImage=Tools::binarization(mainImage,T);
			ShowResult(prelImage);
		}
	}
	else
		MessageBox("No image loaded");
}
void COpenCVInterfaceDlg::OnFiltersGaussianfilter()
{
	if(mainImage.cols)
	{
		Sigma dlg;
		INT_PTR nRet=dlg.DoModal();
		if(nRet==IDOK)
		{
			double s;
			s=dlg.getSigma();
			prelImage=Filters::gaussianFilter(mainImage,s);
			ShowResult(prelImage);
		}
	}
	else
		MessageBox("No image loaded");
}
void COpenCVInterfaceDlg::OnLuminosityDecreaseluminosity()
{
	if(mainImage.cols)
	{
		LumVal dlg;
		INT_PTR nRet=dlg.DoModal();
		if(nRet==IDOK)
		{

			int b=dlg.getB();
			prelImage=Tools::decreaseLuminosity(mainImage,b);
			ShowResult(prelImage);
		}
	}
	else
		MessageBox("No image loaded");
}
void COpenCVInterfaceDlg::OnFiltersMedianFilterAnca()
{
	/*
	Creez un ob de tip MaskDlg. Cat timp parametrul introdus nu e numar,
	il las pe utilizator sa introduca dimensiunea mastii din nou.
	*/

	CMaskDlg mask;
	while(mask.DimensionIsValid() == false && mask.windowWasClosed == false)
		mask.DoModal();

	//	Intr-un final, datele introduse sunt bune. Fac conversia la double.
	if(mask.DimensionIsValid() == true)
	{
		int n = 0;
		n = atoi(mask.n1);

		// Modificarea imaginii

		clock_t start, stop;
		start = clock(); 
		prelImage = InitImage(mainImage.rows,mainImage.cols);
		for(int i=n/2; i<mainImage.rows-n/2; i++)
			for(int j=n/2; j<mainImage.cols-n/2; j++)
			{
				double *v = new double[n*n];
				int ind = -1;
				for(int k1=0; k1<n; k1++)
				{
					for(int k2=0; k2<n; k2++)
						v[++ind] = mainImage.at<uchar>(i-n/2+k1, j-n/2+k2);
				}

				int k = (n*n)/2;
				prelImage.at<uchar>(i, j) = Statistica(v, k, 0, n*n-1);
			}
			stop = clock();
			double rez = double(stop - start);
			CString rezS;
			rezS.Format("time = %lf", rez);
			MessageBox(rezS + " seconds");

			ShowResult(prelImage);
	}
}
Пример #17
0
// \brief adjust the ray brightness
static
void onTrackbar3(int pos)
{
    float color[3];
    color[0] = color[1] = color[2] = 255.0f * (float)pos / 100.0f;

    switch (g_effectId)
    {
        case EFFECT01:
            g_pEffect01->SetOuterColor(color);
            g_pEffect01->Draw();
            break;
        case EFFECT02:
            g_pEffect02->SetColor(color);
            g_pEffect02->Draw();
            break;
        case EFFECT03:
            g_pEffect03->SetColor(color);
            g_pEffect03->Draw();
            break;
        case EFFECT05:
            g_pEffect05->SetColor(color);
            g_pEffect05->Draw();
            break;
        case EFFECT09:
            g_pEffect09->SetColor(color);
            g_pEffect09->Draw();
            break;
        case EFFECT10:
            g_pEffect10->SetColor(color);
            g_pEffect10->Draw();
            break;
        case EFFECT15:
            g_pEffect15->SetColor(color);
            g_pEffect15->Draw();
            break;
        case EFFECT19:
            g_pEffect19->SetColor(color);
            g_pEffect19->Draw();
            break;
    }
    ShowResult();
}
Пример #18
0
static
void onTrackbar1(int pos)
{
    switch (g_effectId)
    {
        case EFFECT01:
            g_pEffect01->SetRingSoftness(g_rayNumber);
            //g_pEffect01->SetRampGamma(g_rayNumber);
            g_pEffect01->Draw();
            break;
        case EFFECT02:
            g_pEffect02->SetNumber(g_rayNumber);
            g_pEffect02->Draw();
            break;
        case EFFECT03:
            //g_pEffect03->SetCount(g_rayNumber);
            g_pEffect03->SetThickness(g_rayNumber);
            g_pEffect03->Draw();
            break;
        case EFFECT05:
            g_pEffect05->SetCount(g_rayNumber);
            g_pEffect05->Draw();
            break;
        case EFFECT09:
            g_pEffect09->SetThickness(g_rayNumber);
            g_pEffect09->Draw();
            break;
        case EFFECT10:
            g_pEffect10->SetNumber(g_rayNumber);
            g_pEffect10->Draw();
            break;
        case EFFECT15:
            g_pEffect15->SetCount(g_rayNumber);
            g_pEffect15->Draw();
            break;
        case EFFECT19:
            g_pEffect19->SetCount(g_rayNumber);
            g_pEffect19->Draw();
            break;
    }

    ShowResult();
}
Пример #19
0
// \brief adjust the ray length.
static
void onTrackbar2(int pos)
{
    switch (g_effectId)
    {
        case EFFECT01:
            g_pEffect01->SetRingTaper(g_rayLength);
            //g_pEffect01->SetRampScale(g_rayLength);
            g_pEffect01->Draw();
            break;
        case EFFECT02:
            g_pEffect02->SetScale(g_rayLength);
            g_pEffect02->Draw();
            break;
        case EFFECT03:
            g_pEffect03->SetScale(g_rayLength);
            g_pEffect03->Draw();
            break;
        case EFFECT05:
            g_pEffect05->SetSpread(g_rayLength);
            g_pEffect05->Draw();
            break;
        case EFFECT09:
            g_pEffect09->SetLength(g_rayLength);
            g_pEffect09->Draw();
            break;
        case EFFECT10:
            g_pEffect10->SetScale(g_rayLength);
            g_pEffect10->Draw();
        case EFFECT15: 
            g_pEffect15->SetScale(g_rayLength);
            g_pEffect15->Draw();
            break;
        case EFFECT19: 
            g_pEffect19->SetScale(g_rayLength);
            g_pEffect19->Draw();
            break;
    }
    ShowResult();
}
Пример #20
0
// \brief adjust the ray angle
static
void onTrackbar4(int pos)
{
    float rayAngle = M_PI * (float)g_rayAngle / 180.0f;

    switch (g_effectId)
    {
        case EFFECT02:
            g_pEffect02->SetAngle(rayAngle);
            g_pEffect02->Draw();
            break;
        case EFFECT03:
            g_pEffect03->SetAngle(rayAngle);
            g_pEffect03->Draw();
            break;
        case EFFECT05:
            g_pEffect05->SetAngle(rayAngle);
            g_pEffect05->Draw();
            break;
        case EFFECT09:
            g_pEffect09->SetAngle(rayAngle);
            g_pEffect09->Draw();
            break;
        case EFFECT10:
            g_pEffect10->SetAngle(rayAngle);
            g_pEffect10->Draw();
            break;
        case EFFECT15:
            g_pEffect15->SetAngle(rayAngle);
            g_pEffect15->Draw();
            break;
        case EFFECT19:
            g_pEffect19->SetRandSeed(g_rayAngle);
            g_pEffect19->Draw();
        default:
            break;
    }

    ShowResult();
}
Пример #21
0
// 人 vs AI
void
GameManVsCom(void)
{
  BOARD board;
  uint64_t pos, valid;

  Init(&board);
  DispBoard(&board);
  while(board.teban != GAME_OVER){
    valid = GenValidMove(&board);

    if(board.teban == SENTE){     // 先手(人) の処理
      while(1){
        pos = GetPos();
        if(pos == INPUT_ERROR){
          printf("エラーです。\n");
          continue;
        }
        else if((pos & valid) == 0){
          printf("非合法手です。\n");
          continue;
        }
        break;
      }
    }
    else if(board.teban == GOTE){ // 後手 (AI) の処理
      // コンピュータ側の処理をここにかく
      pos = Think(&board, valid);
    }

    Put(&board, pos);
    DispBoard(&board);
    CheckFinishPass(&board);
  }

  ShowResult(&board);
  return;
}
Пример #22
0
void TitleMenu() {
  int program_quit = 0;
  char ch = '\0';
  while(!program_quit) {
    clear();
    attron(A_BOLD);
    attron(COLOR_PAIR(3));
    mvprintw(5, 25, "A S C I I     P A C K - M A N ");
    mvprintw(15, 25, "[P] PLAY GAME");
    mvprintw(16, 25, "[H] HELP");
    mvprintw(17, 25, "[Q] QUIT");
    mvprintw(13, 25, "Choose an option :");
    attroff(COLOR_PAIR(3));
    attroff(A_BOLD);

    ch = getch();
    switch(ch) {
      case 'p':
      case 'P':
        PrepareGame();
        PlayGame();
        ShowResult();
        break;
      case 'h':
      case 'H':
        ShowHelp();
        break;
      case 'q':
      case 'Q':
        program_quit = 1;
        break;
      default:
        break;
    }
  }
}
Пример #23
0
void Execute()
{	
	int i;
	int j;
	int k;
	Table tableinfor;
	Index indexinfor;
	string tempKeyValue;
	int tempPrimaryPosition=-1;
	int rowCount=0;
	Data data;
	switch(parsetree.m_operation)
	{
	case CRETAB:
		parsetree.getTableInfo.attriNum=parsetree.getTableInfo.attributes.size();
		catalog.createTable(parsetree.getTableInfo);
		record.createTable(parsetree.getTableInfo);
		cout<<"Table "<<parsetree.getTableInfo.name<<" is created successfully"<<endl;
		break;
	case TABLEEXISTED:
		cout<<"CREATE ERROR: Table existed"<<endl;
		break;
	case DRPTAB:
		record.dropTable(parsetree.getTableInfo);
		for(int i = 0; i < parsetree.getTableInfo.attriNum; i++){//���������е�index��ɾ��
			indexinfor = catalog.getIndexInformation(parsetree.getTableInfo.name, i);
			if(indexinfor.index_name != "")
				indexm.dropIndex(indexinfor);
		}
		catalog.dropTable(parsetree.getTableInfo);
		cout<<"Table "<<parsetree.getTableInfo.name<<" is dropped successfully"<<endl;
		break;
	case INSERT:
		tableinfor = parsetree.getTableInfo;
		if(parsetree.PrimaryKeyPosition==-1&&parsetree.UniquePostion==-1){
			record.insertValue(tableinfor, parsetree.row);
			catalog.update(tableinfor);
			cout<<"Insert successfully"<<endl;
			break;
		}
		if(parsetree.PrimaryKeyPosition!=-1)
		{
			data=record.select(tableinfor, parsetree.condition);
			if(data.rows.size()>0){
				cout<<"INSERT ERROR: Primary key redundancy"<<endl;
				break;
			}
		}
		if(parsetree.UniquePostion!=-1){
			
			data=record.select(tableinfor, parsetree.UniqueCondition);
			if(data.rows.size()>0){
				cout<<"INSERT ERROR: Unique value redundancy"<<endl;
				break;
			}
		}
		record.insertValue(tableinfor,parsetree.row);
		catalog.update(tableinfor);
		cout<<"Insert successfully"<<endl;
		break;
	case INSERTERR:
		cout << "Syntax ERROR: Incorrect usage of \"insert\"." << endl;
		break;
	case SELECT_NOWHERE_CAULSE:
		tableinfor = parsetree.getTableInfo;
		data=record.select(tableinfor);
		if(data.rows.size()!=0)
			ShowResult( data, tableinfor, parsetree.column);
		else{
			cout << "No data is found." << endl;
		}
		break;
	case SELECT_WHERE_CAULSE:
		tableinfor=parsetree.getTableInfo;
		if(parsetree.condition.size()==1){
			for(int i=0;i<parsetree.getTableInfo.attributes.size();i++){
		/*�޸�*/if((parsetree.getTableInfo.attributes[i].isPrimeryKey==true||parsetree.getTableInfo.attributes[i].isUnique==true)&&parsetree.m_colname==parsetree.getTableInfo.attributes[i].name){
					tempPrimaryPosition=i;
					indexinfor=catalog.getIndexInformation(tableinfor.name,i);
					break;
				}
			}
			if(tempPrimaryPosition==parsetree.condition[0].columnNum&&parsetree.condition[0].op==Eq&&indexinfor.table_name!=""){
				
				tempKeyValue=parsetree.condition[0].value;
				data= indexm.selectEqual(tableinfor,indexinfor,tempKeyValue);
			}
			else{

				data=record.select(tableinfor,parsetree.condition);
			}
		}
		else{
			data=record.select(tableinfor,parsetree.condition);
		}
		if(data.rows.size()!=0)
			ShowResult( data, tableinfor, parsetree.column);
		else{
			cout << "No data is found." << endl;
		}
		break;
	case DELETE:
		rowCount = record.deleteValue(parsetree.getTableInfo,parsetree.condition);
		cout<< rowCount <<"  tuples are deleted."<<endl;
		break;
	case CREIND:
		indexinfor = parsetree.getIndexInfo;
		tableinfor = parsetree.getTableInfo;
		if(!tableinfor.attributes[indexinfor.column].isPrimeryKey && !tableinfor.attributes[indexinfor.column].isUnique){//����primary key�������Խ�index
			cout << "Column " << tableinfor.attributes[indexinfor.column].name <<"  is not unique."<< endl;
			break;
		}
		catalog.createIndex(indexinfor);
		indexm.createIndex(tableinfor, indexinfor);
		catalog.update(indexinfor);
		cout<<"Index "<< indexinfor.index_name << "is created successfully."<<endl;
		break;
	case INDEXERROR:
		cout<<"ERROR: Index existed."<<endl;
		break;
	case DRPIND:
		indexinfor = catalog.getIndexInformation(parsetree.m_indname);
		if(indexinfor.index_name == ""){
			cout << "ERROR: Index" << parsetree.m_indname << "does not exist!" << endl;
		}
		indexm.dropIndex(indexinfor);
		catalog.dropIndex(parsetree.m_indname);
		cout<<"The index is dropped successfully"<<endl;
		break;
	case CREINDERR:
		cout << "Syntax ERROR: Incorrect usage of \"create index\" query." << endl;
		break;
	case QUIT:
		cout << "Bye Bye~" << endl;
		system("pause");
		exit(0);
		break;
	case EMPTY:
		cout << "Query Empty." << endl;
		break;
	case UNKNOW:
		cout << "Syntax ERROR: Please check your query." << endl;
		break;
	case SELERR:
		cout << "Syntax ERROR: Incorrect usage of \"select\" query." << endl;
		break;
	case CRETABERR:
		cout << "Syntax ERROR: Incorrect usage of \"create table\" query." << endl;
		break;
	case DELETEERR:
		cout << "Syntax ERROR: Incorrect usage of \"delete from\" query." << endl;
		break;
	case DRPTABERR:
		cout << "Syntax ERROR: Incorrect usage of \"drop table\" query." << endl;
		break;
	case DRPINDERR:
		cout << "Syntax ERROR: Incorrect usage of \"drop index\" query." << endl;
		break;
	case VOIDPRI:
		cout << "ERROR: Invalid primary key." << endl;
		break;
	case VOIDUNI:
		cout << "ERROR: Invalid unique key." << endl;
		break;
	case CHARBOUD:
		cout << "ERROR: Too long query. Only 1~255 charactors is allowed." << endl;
		break;
	case NOPRIKEY:
		cout << "ERROR: Please define a primary key." << endl;
		break;
	case TABLEERROR:
		cout << "ERROR: Table is not existed."<<endl;
		break;
	case INDEXEROR:
		cout << "ERROR: Index is not existed."<<endl;
		break;
	case COLUMNERROR:
		cout << "ERROR: Column is not existed"<<endl;
		break;
	case INSERTNUMBERERROR:
		cout << "ERROR: The amount of the columns is not matched."<<endl;
		break;
	}
	
}
Пример #24
0
static
void onTrackbar0(int pos)
{
    ShowResult();
}
Пример #25
0
/*****************************************************************************
UINT __stdcall ThreadProc_Calc(VOID * pParam)
	pParam	: (IN/OUT) THREAD_PARAMS_CALC struct pointer special for this thread

Return Value:
	returns 0

Notes:
- requests jobs from the queue and calculates hashes until the queue is empty
- spawns up to three additional threads, one for each hash value
- performs asynchronous I/O with two buffers -> one buffer is filled while the hash-threads
  work on the other buffer
- if an error occured, GetLastError() is saved in the current pFileinfo->dwError
- what has be calculated is determined by bDoCalculate[HASH_TYPE_CRC32]/bDoCalculate[HASH_TYPE_MD5]/bDoCalculate[HASH_TYPE_ED2K] of the
  current job
*****************************************************************************/
UINT __stdcall ThreadProc_Calc(VOID * pParam)
{
	THREAD_PARAMS_CALC * CONST pthread_params_calc = (THREAD_PARAMS_CALC *)pParam;
	CONST HWND * CONST arrHwnd = pthread_params_calc->arrHwnd;
	SHOWRESULT_PARAMS * CONST pshowresult_params = pthread_params_calc->pshowresult_params;

	BOOL bDoCalculate[NUM_HASH_TYPES];

	QWORD qwStart, qwStop, wqFreq;
	HANDLE hFile;
	BYTE *readBuffer = (BYTE *)malloc(MAX_BUFFER_SIZE_CALC);
	BYTE *calcBuffer = (BYTE *)malloc(MAX_BUFFER_SIZE_CALC);
	BYTE *tempBuffer;
	DWORD readWords[2];
	DWORD *dwBytesReadRb = &readWords[0];
	DWORD *dwBytesReadCb = &readWords[1];
	DWORD *dwBytesReadTb;
	BOOL bSuccess;
	BOOL bFileDone;
	BOOL bAsync;

    HANDLE hEvtThreadGo[NUM_HASH_TYPES];
    HANDLE hEvtThreadReady[NUM_HASH_TYPES];

	HANDLE hEvtReadDone;
	OVERLAPPED olp;
	ZeroMemory(&olp,sizeof(olp));

    HANDLE hThread[NUM_HASH_TYPES];
	
	HANDLE hEvtReadyHandles[NUM_HASH_TYPES];
	DWORD cEvtReadyHandles;

    THREAD_PARAMS_HASHCALC calcParams[NUM_HASH_TYPES];

	lFILEINFO *fileList;
	list<FILEINFO*> finalList;

	if(readBuffer == NULL || calcBuffer == NULL) {
		ShowErrorMsg(arrHwnd[ID_MAIN_WND],GetLastError());
		ExitProcess(1);
	}
	

	// set some UI stuff:
	// - disable action buttons while in thread
	EnableWindowsForThread(arrHwnd, FALSE);

	ShowResult(arrHwnd, NULL, pshowresult_params);
	
	while((fileList = SyncQueue.popQueue()) != NULL) {

        cEvtReadyHandles = 0;

        for(int i=0;i<NUM_HASH_TYPES;i++) {
		    bDoCalculate[i]	= !fileList->bCalculated[i] && fileList->bDoCalculate[i];

            if(bDoCalculate[i]) {
			    fileList->bCalculated[i] = TRUE;
			    hEvtThreadGo[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
			    hEvtThreadReady[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
			    if(hEvtThreadGo[i] == NULL || hEvtThreadReady[i] == NULL) {
				    ShowErrorMsg(arrHwnd[ID_MAIN_WND],GetLastError());
				    ExitProcess(1);
			    }
			    hEvtReadyHandles[cEvtReadyHandles] = hEvtThreadReady[i];
			    cEvtReadyHandles++;
			    calcParams[i].bFileDone = &bFileDone;
			    calcParams[i].hHandleGo = hEvtThreadGo[i];
			    calcParams[i].hHandleReady = hEvtThreadReady[i];
			    calcParams[i].buffer = &calcBuffer;
			    calcParams[i].dwBytesRead = &dwBytesReadCb;
		    }
        }

		hEvtReadDone = CreateEvent(NULL,FALSE,FALSE,NULL);
		if(hEvtReadDone == NULL) {
			ShowErrorMsg(arrHwnd[ID_MAIN_WND],GetLastError());
			ExitProcess(1);
		}

		QueryPerformanceFrequency((LARGE_INTEGER*)&wqFreq);

		if(g_program_options.bEnableQueue && g_pstatus.bHaveComCtrlv6) {
			if(fileList->iGroupId==0)
				InsertGroupIntoListView(arrHwnd[ID_LISTVIEW],fileList);
			else
				RemoveGroupItems(arrHwnd[ID_LISTVIEW],fileList->iGroupId);
		}

		for(list<FILEINFO>::iterator it=fileList->fInfos.begin();it!=fileList->fInfos.end();it++)
		{
			pthread_params_calc->pFileinfo_cur = &(*it);
			pthread_params_calc->qwBytesReadCurFile = 0;
			
			FILEINFO& curFileInfo = (*it);

			if ( (curFileInfo.dwError == NO_ERROR) && cEvtReadyHandles > 0)
			{

                DisplayStatusOverview(arrHwnd[ID_EDIT_STATUS]);

				QueryPerformanceCounter((LARGE_INTEGER*) &qwStart);
				hFile = CreateFile(curFileInfo.szFilename,
						GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED | FILE_FLAG_SEQUENTIAL_SCAN , 0);
				if(hFile == INVALID_HANDLE_VALUE){
					curFileInfo.dwError = GetLastError();
                } else {

				    bFileDone = FALSE;

                    for(int i=0;i<NUM_HASH_TYPES;i++) {
                        if(bDoCalculate[i]) {
                            ResetEvent(hEvtThreadGo[i]);
                            ResetEvent(hEvtThreadReady[i]);
                            calcParams[i].result = &curFileInfo.hashInfo[i].r;
					        hThread[i] = CreateThread(NULL,0,hash_function[i],&calcParams[i],0,NULL);
					        if(hThread[i] == NULL) {
						        ShowErrorMsg(arrHwnd[ID_MAIN_WND],GetLastError());
						        ExitProcess(1);
					        }
                        }
				    }

				    ZeroMemory(&olp,sizeof(olp));
				    olp.hEvent = hEvtReadDone;
				    olp.Offset = 0;
				    olp.OffsetHigh = 0;
				    bSuccess = ReadFile(hFile, readBuffer, MAX_BUFFER_SIZE_CALC, dwBytesReadRb, &olp);
				    if(!bSuccess && (GetLastError()==ERROR_IO_PENDING))
					    bAsync = TRUE;
				    else
					    bAsync = FALSE;

				    do {
					    if(bAsync)
						    bSuccess = GetOverlappedResult(hFile,&olp,dwBytesReadRb,TRUE);
					    if(!bSuccess && (GetLastError() != ERROR_HANDLE_EOF)) {
						    curFileInfo.dwError = GetLastError();
						    bFileDone = TRUE;
					    }
					    pthread_params_calc->qwBytesReadCurFile  += *dwBytesReadRb; //for progress bar
					    pthread_params_calc->qwBytesReadAllFiles += *dwBytesReadRb;

					    olp.Offset = pthread_params_calc->qwBytesReadCurFile & 0xffffffff;
					    olp.OffsetHigh = (pthread_params_calc->qwBytesReadCurFile >> 32) & 0xffffffff;
    					
					    WaitForMultipleObjects(cEvtReadyHandles,hEvtReadyHandles,TRUE,INFINITE);
					    SWAPBUFFERS();
					    bSuccess = ReadFile(hFile, readBuffer, MAX_BUFFER_SIZE_CALC, dwBytesReadRb, &olp);
					    if(!bSuccess && (GetLastError()==ERROR_IO_PENDING))
						    bAsync = TRUE;
					    else
						    bAsync = FALSE;

					    if(*dwBytesReadCb<MAX_BUFFER_SIZE_CALC || pthread_params_calc->signalExit)
						    bFileDone=TRUE;

                        for(int i=0;i<NUM_HASH_TYPES;i++) {
                            if(bDoCalculate[i])
						        SetEvent(hEvtThreadGo[i]);
                        }

				    } while(!bFileDone);

				    WaitForMultipleObjects(cEvtReadyHandles,hEvtReadyHandles,TRUE,INFINITE);

				    if(hFile != NULL)
					    CloseHandle(hFile);

                    for(int i=0;i<NUM_HASH_TYPES;i++) {
                        if(bDoCalculate[i])
					        CloseHandle(hThread[i]);
                    }

				    if(pthread_params_calc->signalExit)
					    break;

				    QueryPerformanceCounter((LARGE_INTEGER*) &qwStop);
				    curFileInfo.fSeconds = (float)((qwStop - qwStart) / (float)wqFreq);
                }
			}

            curFileInfo.status = InfoToIntValue(&curFileInfo);
			SetFileInfoStrings(&curFileInfo,fileList);

            if(!g_pstatus.bHideVerified || curFileInfo.status != STATUS_OK) {
			    InsertItemIntoList(arrHwnd[ID_LISTVIEW], &curFileInfo,fileList);
            }

            SyncQueue.getDoneList();
            SyncQueue.adjustErrorCounters(&curFileInfo,1);
            SyncQueue.releaseDoneList();

			ShowResult(arrHwnd, &curFileInfo, pshowresult_params);
		}

        for(int i=0;i<NUM_HASH_TYPES;i++) {
            if(bDoCalculate[i]) {
		        CloseHandle(hEvtThreadGo[i]);
			    CloseHandle(hEvtThreadReady[i]);
            }
        }

		if(pthread_params_calc->signalExit)
			break;

		if(fileList->uiCmdOpts!=CMD_NORMAL) {
			for(list<FILEINFO>::iterator it=fileList->fInfos.begin();it!=fileList->fInfos.end();it++) {
				finalList.push_back(&(*it));
			}
			finalList.sort(ListPointerCompFunction);
			switch(fileList->uiCmdOpts) {
				case CMD_SFV:
				case CMD_MD5:
				case CMD_SHA1:
                case CMD_SHA256:
                case CMD_SHA512:
					CreateChecksumFiles(arrHwnd,fileList->uiCmdOpts,&finalList);
					break;
				case CMD_NAME:
                    ActionHashIntoFilename(arrHwnd, TRUE, &finalList, HASH_TYPE_CRC32);
					break;
				case CMD_NTFS:
					ActionCrcIntoStream(arrHwnd,TRUE,&finalList);
					break;
				default:
					break;
			}
			finalList.clear();
		}

		SyncQueue.addToList(fileList);

	}
Пример #26
0
Файл: Tab.c Проект: tinnfu/ftp
int Tab(Node *resultHead, const char *info,\
	    const char *path, int ti,\
			   char *cmd)
{
    int mode		 = 0;
    int i		 = 0;
    int len		 = 0;
    int times		 = 2;
    int flag 		 = -1;
    int pos		 = -1;
    char tmp[BUFFSIZE]	 = {0};
    struct stat buf	 = {0};
    char child[BUFFSIZE] = {0};
    const char *s	 = NULL;

    assert(NULL != resultHead);
    assert(NULL != path);

    strcpy(tmp, path);

    if('\0' == *tmp)
    {
	strcpy(tmp, ".");
    }

    //The path is exist or not exist?
    while((times--)\
	&& (-1 == (flag = lstat(tmp, &buf))))
    {
	if(ENOENT != errno)
	{
	    return -1;
	}

	if(times > 0)
	{
	    s = GetTail(tmp, '/');

	    //If string tmp is not equal to it's
	    //tail string s(is a part of string tmp
	    //which contain the last '/' int tmp),
	    //delete the tail(string s) of string
	    //tmp (maybe the new string tmp[the old
	    //string tmp delete tail s] is exist).
	    //But if string tmp is equal to string s
	    //means the string tmp(as same as string
	    // path) doesn't contain a '/'(break).
	    if(strcmp(tmp, s))
	    {
	        tmp[strlen(tmp) - strlen(s)] = '\0';
	    }
	    else
	    {
		break;
	    }
	}
    }

    //Get string child from the tail of
    //string path.
    strcpy(child, GetTail(path, '/'));

    //If 'times = 1', means the path isn't
    //contain '/' or the path is exist.
    /////And in this section string path is
    //equal to string tmp.
    //Else if 'times = -1', means the string
    //tmp is a part of string path. Maybe tmp
    //is exist or not exist.
    if(1 == times)
    {
	//If 'flag = -1', maybe the path is
	//a part of file name in current
	//directory.
	//Else if 'flag = 0', means the path
	//is exist.
	if(-1 == flag)
	{
	    strcpy(tmp, ".");
	}
	else
	{
	    if(! S_ISDIR(buf.st_mode))
	    {
		write(STDOUT_FILENO, " ", 1);
	    	strcat(cmd, " ");
	    }
	    else
	    {
		if( ('\0' != path[0])
		  && ('/'  != path[strlen(path) - 1])
		  && (('.' != path[strlen(path) - 1])
		  || ('.') == path[strlen(path) - 2]))
		{
		    write(STDOUT_FILENO, "/", 1);
		    strcat(cmd, "/");
		}
	    }

	    s = GetTail(tmp, '/');

	    if( strcmp(path, ".")
	      && ( ('.' != path[strlen(path) - 1])
		    || ('.') == path[strlen(path) - 2]))
	    {
	        //Because path is exist so click button
	        //'Tab' means to get other file name of
	        //the specified directory(name of 'path'
	        //is also included in this directory).
	        strcpy(child, "\0");
	    }

	    //If path is not a directory.
	    //If string path isn't equal to string
	    //s(is tail of string path), means the
	    //s(file) is exist in 'path-s'.
	    //Else string path is a file exist in
	    //current directory.
	    if(! S_ISDIR(buf.st_mode))
	    {
	        if(0 != strcmp(tmp, s))
	        {
		    tmp[strlen(path) - strlen(s)] = '\0';
	        }
	        else
	        {
		    strcpy(tmp, ".");
	        }
	    }
	}
    }
    else
    {
	//If 'flag = -1', the path and tmp
	//is not exist.
	//Else the tmp(delete the tail of path)
	//is exist.
	if(-1 == flag)
	{
	    return -1;
	}
    }

    if( -1 == (flag = FindFileName(resultHead,
			    tmp, child)) )
    {
	return -1;
    }

    if((len = GetLen(resultHead)) > 0)
    {
        if(len > 1)
        {
	    if(ti > 0)
	    {
	        if(-1 ==  ShowResult(resultHead, NULL,\
					1, cmd))
	        {
		    return -1;
	        }

		write(STDOUT_FILENO, info, strlen(info));

		write(STDOUT_FILENO, cmd, strlen(cmd));
	    }
        }
        else
        {
	    strcpy(tmp, GetVal(resultHead, 1));

	    flag = ( flag ? 0 :
		   ('/' != tmp[strlen(tmp) - 1]) );

	    if( -1 ==  ShowResult(resultHead, child,
				    flag, cmd) )
	    {
	        return -1;
	    }
        }
    }

    return 0;
}
Пример #27
0
int main(int argc, char* argv[])
{
    // Load the input image and texture.
    g_pImage = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3);

    // FIXME: Change the rand seed here.
    srand(10001);

    // Create the glare effect object.
    float color[] = {255, 255, 255};
    float color1[] = {255, 0, 0};

    g_pEffect01 = new effect01_glowball::Effect(
            640, 
            480,
            20,
            30,
            20,
            g_rayLength,
            g_rayNumber,          
            color,
            color1);
    if (!g_pEffect01->Init())
    {
        fprintf(stderr, "Err: effect01 init failed.\n");
        return -1;
    }
    //g_pEffect01->SetPosition(100, 100);
    g_pEffect01->Draw();


    g_pEffect02 = new effect02_spikeball::Effect(
            640, 
            480,
            g_rayLength,           
            g_rayNumber,
            color,
            M_PI * (float)g_rayAngle / 180.0f);
    if (!g_pEffect02->Init())
    {
        fprintf(stderr, "Err: effect02 init failed.\n");
        return -1;
    }
    g_pEffect02->Draw();
    
    g_pEffect03 = new effect03_starfilter::Effect(
            640, 
            480,
            g_rayNumber,           
            g_rayLength,
            color,
            M_PI * (float)g_rayAngle / 180.0f,
            5,
            10);
    if (!g_pEffect03->Init())
    {
        fprintf(stderr, "Err: effect03 init failed.\n");
        return -1;
    }
    g_pEffect03->Draw();
    
    g_pEffect05 = new effect05_circlespread::Effect(
            640, 
            480,
            50,
            g_rayNumber,           
            5,
            50,
            101,
            102,
            M_PI * (float)g_rayAngle / 180.0f,
            color);
    if (!g_pEffect05->Init())
    {
        fprintf(stderr, "Err: effect05 init failed.\n");
        return -1;
    }
    g_pEffect05->Draw();
    
    g_pEffect09 = new effect09_stripe::Effect(
            640, 
            480,
            g_rayLength,           
            g_rayNumber,
            color1,
            true,
            color,
            M_PI * (float)g_rayAngle / 180.0f);
    if (!g_pEffect09->Init())
    {
        fprintf(stderr, "Err: effect09 init failed.\n");
        return -1;
    }
    g_pEffect09->Draw();

    g_pEffect10 = new effect10_randomfan::Effect(
            640, 
            480,
            g_rayNumber,           
            g_rayLength,
            color,
            M_PI * (float)g_rayAngle / 180.0f);
    if (!g_pEffect10->Init())
    {
        fprintf(stderr, "Err: effect10 init failed.\n");
        return -1;
    }
    g_pEffect10->Draw();
    
    g_pEffect15 = new effect15_singlepoly::Effect(
            640, 
            480,
            g_rayLength,
            g_rayNumber,
            0,
            color,
            M_PI * (float)g_rayAngle / 180.0f);
    if (!g_pEffect15->Init())
    {
        fprintf(stderr, "Err: effect15 init failed.\n");
        return -1;
    }
    g_pEffect15->Draw();
    
    g_pEffect19 = new effect19_sparkle::Effect(
            640, 
            480,
            g_rayNumber,
            g_rayLength,
            color,
            g_rayAngle);
    if (!g_pEffect19->Init())
    {
        fprintf(stderr, "Err: effect19 init failed.\n");
        return -1;
    }
    g_pEffect19->Draw();
    
   
    // Create window.
    cvNamedWindow("Lens Flare", 1);
    
    cvCreateTrackbar("Effect",     "Lens Flare", &g_effectId,     20,  onTrackbar0);
    cvCreateTrackbar("Count",      "Lens Flare", &g_rayNumber,    100, onTrackbar1);
    cvCreateTrackbar("Scale",      "Lens Flare", &g_rayLength,    100, onTrackbar2);
    cvCreateTrackbar("Brightness", "Lens Flare", &g_rayThickness, 100, onTrackbar3);
    cvCreateTrackbar("Angle",      "Lens Flare", &g_rayAngle,     180,  onTrackbar4);

    ShowResult();
    
    // Enter the main loop.
    while(1){
        int key = cvWaitKey(10);

        // Exit.
        if (key == 27)
        {
            break;
        }

        switch (key)
        {
            case 'd':
                {
                    static int fileId = 1;
                    char filename[1024];
                    sprintf(filename, "dumpsrc_%04d.bmp", fileId);
                    cvSaveImage(filename, g_pImage);
                }
                break;
        }
    }
    
    cvDestroyWindow("Lens Flare");

    // The end of the main loop.
    cvReleaseImage(&g_pImage);

    delete g_pEffect01;
    delete g_pEffect02;
    delete g_pEffect03;
    delete g_pEffect09;
    delete g_pEffect10;
    delete g_pEffect15;

    return 0;
}