示例#1
0
文件: AI.cpp 项目: Py0s/gomoku_ninuki
int AI::calcMinMax(Map& map, int depth, Referee::E_STATE ret, Stone::E_COLOR color, int alpha, int beta) {

    if (depth == 0 || Referee::gameHasEnded(ret))
        return eval(map, ret, color);

    // int y_first = 0;
    // int x_first = 0;

    // On récupère l'évaluation du premier coup possible
    // int current = getEvalForFirstMovePossible(map, depth, color, alpha, beta, y_first, x_first);
    // if (current >= alpha)
    //     alpha = current;

    // if (current < beta)
    // {
        TILE_IT_T it = _openTiles.begin();
        // On parcours les autres cases du Goban
        while (it != _openTiles.end()) {
            checkTime();
            int y = it->first;//le temps de faire marcher les iterateurs
            int x = it->second;

            // Copy de la map et des nombres de pierres capturées
            Map map_tmp = map;
            // On crée la pierre et on joue le coup
            char fake = 0;
            Referee::E_STATE ret = _referee.check(Stone(y, x, color), map_tmp, fake);
            // Si le coup est valide on évalue (Pas de double trois)
            if (ret != Referee::INVALID)
            {
                // int score = 1;
                int score = -calcMinMax(map_tmp, depth-1, ret, Referee::OP_COLOR[color], -(alpha+1), -alpha);
                if (score > alpha && score < beta)
                    score = -calcMinMax(map_tmp, depth-1, ret, Referee::OP_COLOR[color], -beta, -alpha);
                // if (score >= current)
                // {
                    // current = score;
                    if (score >= alpha)
                    {
                        alpha = score;
                        if (/*alpha*/score >= beta)
                            return score;
                            // return current;
                    }
                // }
            }
            ++it;
        }
    // }
    return alpha;
    // return /*alpha*/current;
}
示例#2
0
int IAclass::calcCoup(std::map<poseCase, typeCase>& mapLevel, int prof)
{
    int alpha = -10001;
    int beta = 10001;
    int tmpMax = 0;
    poseCase poseMax(-1, -1);
    poseCase poseActu(-1, -1);
    for(int i = 0; i < 7; ++i)
    {
        poseActu = coupPossible(mapLevel, i);
        if(poseActu == poseCase(-1, -1))
        {
            continue;
        }

        mapLevel[poseActu] = color;
        lastPose = poseActu;
        tmpMax = calcMinMax(mapLevel, prof - 1, false, alpha, beta);
        if(tmpMax > alpha)
        {
            alpha = tmpMax;
            poseMax = poseActu;
        }

        mapLevel[poseActu] = VIDE;
    }

    return poseMax.first;
}
示例#3
0
void Gl1_PotentialParticle::go( const shared_ptr<Shape>& cm, const shared_ptr<State>& state ,bool wire2, const GLViewInfo&) {

	PotentialParticle* pp = static_cast<PotentialParticle*>(cm.get());
	int shapeId = pp->id;

	if(store == false) {
		if(SF.size()>0) {
			SF.clear();
			initialized = false;
		}
	}


	if(initialized == false ) {
		FOREACH(const shared_ptr<Body>& b, *scene->bodies) {
			if (!b) continue;
			PotentialParticle* cmbody = dynamic_cast<PotentialParticle*>(b->shape.get());
			if (!cmbody) continue;
			calcMinMax(*cmbody);
			mc.init(sizeX,sizeY,sizeZ,min,max);
			mc.resizeScalarField(scalarField,sizeX,sizeY,sizeZ);
			SF.push_back(scalarF());
			generateScalarField(*cmbody);
			mc.computeTriangulation(scalarField,0.0);
			SF[b->id].triangles = mc.getTriangles();
			SF[b->id].normals = mc.getNormals();
			SF[b->id].nbTriangles = mc.getNbTriangles();
			for(unsigned int i=0; i<scalarField.size(); i++) {
				for(unsigned int j=0; j<scalarField[i].size(); j++) scalarField[i][j].clear();
				scalarField[i].clear();
			}
			scalarField.clear();
		}
		initialized = true;
	}
示例#4
0
文件: AI.cpp 项目: Py0s/gomoku_ninuki
int AI::getEvalForFirstMovePossible(Map& map, int depth, Stone::E_COLOR color, int alpha, int beta,
                                    int &y, int &x) {

    // On parcours le Goban a la recherche du premier coup possible
    for (; y < Map::_MAPSIZE_Y; ++y)
    {
        for (; x < Map::_MAPSIZE_X; ++x)
        {
            checkTime();

            if (map[y][x].isEmpty())
            {
                // Copy de la map et des nombres de pierres capturées
                Map map_tmp = map;

                // On crée la pierre et on joue le coup
                char fake = 0;
                Referee::E_STATE ret = _referee.check(Stone(y, x, color), map_tmp, fake);

                // Si le coup est valide on évalue (Pas de double trois)
                if (ret != Referee::INVALID)
                    return -calcMinMax(map_tmp, depth-1, ret, Referee::OP_COLOR[color], -beta, -alpha);
            }
        }
    }
    return 0;
}
示例#5
0
void VertexBox::setData(float *i_pData, int i_numElementsPerVertex,
		int i_numVertices, int i_numPrimitives, bool *i_pCoverage)
{
	int i;

	if (m_numVertices > 0) {
		delete[] m_pData;
		delete[] m_pDataMap;
		delete[] m_nMinData;
		delete[] m_nMaxData;
		delete[] m_nAbsMinData;
		delete[] m_nAbsMaxData;
		m_pData = NULL;
		m_pDataMap = NULL;
	}
	if (i_numVertices > 0 && i_pData) {
		m_pData = new float[i_numVertices * i_numElementsPerVertex];
		m_pDataMap = new bool[i_numVertices];
		memcpy(m_pData, i_pData,
				i_numVertices * i_numElementsPerVertex * sizeof(float));
		m_numElementsPerVertex = i_numElementsPerVertex;
		m_numVertices = i_numVertices;
		m_numPrimitives = i_numPrimitives;
		/* Initially use all given data */
		if (i_pCoverage) {
			memcpy(m_pDataMap, i_pCoverage, m_numVertices * sizeof(bool));
		} else {
			for (i = 0; i < m_numVertices; i++) {
				m_pDataMap[i] = true;
			}
		}
		m_pCoverage = i_pCoverage;

		m_nMinData = new float[m_numElementsPerVertex];
		m_nMaxData = new float[m_numElementsPerVertex];
		m_nAbsMinData = new float[m_numElementsPerVertex];
		m_nAbsMaxData = new float[m_numElementsPerVertex];
		calcMinMax();
	} else {
		m_pData = NULL;
		m_pDataMap = NULL;
		m_pCoverage = NULL;
		m_numElementsPerVertex = 0;
		m_numVertices = 0;
		m_numPrimitives = 0;
		m_nMinData = NULL;
		m_nMaxData = NULL;
		m_nAbsMinData = NULL;
		m_nAbsMaxData = NULL;
	}

	dbgPrint(DBGLVL_INFO,
			"VertexBox::setData: numPrimitives=%i numVertices=%i numElementsPerVertex=%i\n", m_numPrimitives, m_numVertices, m_numElementsPerVertex);

	emit dataChanged();
}
示例#6
0
/*!
SLCamera::updateAABBRec builds and returns the axis-aligned bounding box.
*/
SLAABBox& SLCamera::updateAABBRec()
{
    // calculate min & max in object space
    SLVec3f minOS, maxOS;
    calcMinMax(minOS, maxOS);

    // apply world matrix
    _aabb.fromOStoWS(minOS, maxOS, _wm);
    return _aabb;
}
示例#7
0
bool Comb::calc(Point startPoint, Point endPoint, std::vector<std::vector<Point>>& combPaths)
{
    if (shorterThen(endPoint - startPoint, MM2INT(1.5)))
    {
//         DEBUG_PRINTLN("too short dist!");
        return true;
    }
    
    bool addEndpoint = false;
    //Check if we are inside the comb boundaries
    if (!boundary.inside(startPoint))
    {
        if (!moveInside(&startPoint))    //If we fail to move the point inside the comb boundary we need to retract.
        {   
//             std::cerr << " fail to move the start point inside the comb boundary we need to retract."<< std::endl;
            return false;
        }
        combPaths.emplace_back();
        combPaths.back().push_back(startPoint);
    }
    if (!boundary.inside(endPoint))
    {
        if (!moveInside(&endPoint))    //If we fail to move the point inside the comb boundary we need to retract.
        {
//             std::cerr << " fail to move the end point inside the comb boundary we need to retract."<< std::endl;
            return false;
        }
        addEndpoint = true;
    }
    
    
    //Check if we are crossing any boundaries, and pre-calculate some values.
    if (!lineSegmentCollidesWithBoundary(startPoint, endPoint))
    {
        //We're not crossing any boundaries. So skip the comb generation.
        if (!addEndpoint && combPaths.size() == 0) //Only skip if we didn't move the start and end point.
            return true;
    }
    
//     std::cerr << "calcuklating comb path!" << std::endl;
    
    //Calculate the minimum and maximum positions where we cross the comb boundary
    calcMinMax();
    
    std::vector<std::vector<Point>> basicCombPaths;
    getBasicCombingPaths(endPoint, basicCombPaths);
    
    bool succeeded = optimizePaths(startPoint, basicCombPaths, combPaths);
    if (addEndpoint)
        combPaths.back().push_back(endPoint);
    
//     std::cerr << "succeeded = " << succeeded << std::endl;
    return succeeded;
}
示例#8
0
/*!
SLCamera::buildAABB builds and returns the axis-aligned bounding box.
*/
SLAABBox& SLCamera::buildAABB()
{
   // calculate min & max in object space
   SLVec3f minOS, maxOS;
   calcMinMax(minOS, maxOS);

   // enlarge aabb for avoiding rounding errors
   //minOS -= 0.01f;
   //maxOS += 0.01f;

   // apply world matrix
   _aabb.fromOStoWS(minOS, maxOS, _wm);
   return _aabb;
}
示例#9
0
文件: AI.cpp 项目: Py0s/gomoku_ninuki
Stone AI::calc(int depth) {
    int score;
    int max_y=-1,max_x=-1;
    //int max = -AI_INFINITY;
    int alpha = -AI_INFINITY;
    int beta = AI_INFINITY;

    //On parcourt les cases du Goban
    TILE_IT_T it = _openTiles.begin();
    while (it != _openTiles.end()) {
        checkTime();
        int y = it->first;//le temps de faire marcher les iterateurs
        int x = it->second;

        Map map_tmp = _map;// Copy de la map et des nombres de pierres capturées

        char fake = 0;// On crée la pierre et on joue le coup
        Referee::E_STATE ret = _referee.check(Stone(y,x, _color), map_tmp, fake);

        // _closeTiles.push_back(*it);
        // it = _openTiles.erase(it);
        // Si le coup est valide on évalue (Pas de double trois)
        if (ret != Referee::INVALID)
        {
            //score = calcMin(map_tmp, depth - 1, ret, alpha, beta);
            
            score = -calcMinMax(map_tmp, depth - 1, ret, Referee::OP_COLOR[_color], -beta, -alpha);
            // Si ce score est plus grand
            //if (score > max)/*Moins optimise mais aleatoire: if (score > max || (score == max && rand()%2))*/
            if (score > alpha)
            {
                std::cout << "depth:"<<depth<<"[" << alpha << "("<<max_y<<";"<<max_x<<")->" << score << "("<<y<<";"<<x<< ")]" << std::endl;
                //On le choisit
                //max = score;
                alpha = score;
                // On sauvegarde les coordonnées du coup optimum
                max_y = y;
                max_x = x;
            }
        }
        // On annule le coup (Ici rien pour l'instant car copie de la Map et des éléments)
        // TILE_VALUE_T tmp_tile = _closeTiles.back();
        // _closeTiles.pop_back();
        // it = _openTiles.insert(it, tmp_tile);
        ++it;
    }
    // On retourne la pierre optimale
    return Stone(max_y, max_x, _color);
}
示例#10
0
int IAclass::calcMinMax(std::map<poseCase, typeCase>& mapLevel, int prof, bool isMax, int alpha, int beta)
{
    int tmpNb = 0;
    poseCase poseActu(-1, -1);

    if(checkEndGame(mapLevel) == true || prof <= 0)
    {
        return evalue(mapLevel);
    }

    for(int i = 0; i < 7; ++i)
    {
        poseActu = coupPossible(mapLevel, i);
        if(poseActu == poseCase(-1, -1))
        {
            continue;
        }

        mapLevel[poseActu] = isMax ? color : enemiColor;
        lastPose = poseActu;
        tmpNb = calcMinMax(mapLevel, prof - 1, !isMax, alpha, beta);
        mapLevel[poseActu] = VIDE;
        if(isMax)
        {
            if(tmpNb > alpha)
            {
                alpha = tmpNb;
            }
            if(alpha >= beta)
            {
                return alpha;
            }
        }
        else if(!isMax)
        {
            if(tmpNb < beta)
            {
                beta = tmpNb;
            }
            if(beta <= alpha)
            {
                return beta;
            }
        }
    }

    return (isMax ? alpha : beta);
}
示例#11
0
void Gl1_PotentialBlock::go( const shared_ptr<Shape>& cm, const shared_ptr<State>& state ,bool wire2, const GLViewInfo&){


	PotentialBlock* pp = static_cast<PotentialBlock*>(cm.get());	
		int shapeId = pp->id;

	if(store == false) {
		if(SF.size()>0) {
			SF.clear();
			initialized = false;
		}
	}


	if(initialized == false ) {
		FOREACH(const shared_ptr<Body>& b, *scene->bodies) {
			if (!b) continue;
			PotentialBlock* cmbody = dynamic_cast<PotentialBlock*>(b->shape.get());
			if (!cmbody) continue;

				Eigen::Matrix3d rotation = b->state->ori.toRotationMatrix(); //*pb->oriAabb.conjugate(); 
				int count = 0;
				for (int i=0; i<3; i++){
					for (int j=0; j<3; j++){
						//function->rotationMatrix[count] = directionCos(j,i);
						rotationMatrix(i,j) = rotation(i,j);	//input is actually direction cosine?				
						count++;
					}
				}

			calcMinMax(*cmbody);
			mc.init(sizeX,sizeY,sizeZ,min,max);
			mc.resizeScalarField(scalarField,sizeX,sizeY,sizeZ);
			SF.push_back(scalarF());
			generateScalarField(*cmbody);
			mc.computeTriangulation(scalarField,0.0);
			SF[cmbody->id].triangles = mc.getTriangles();
			SF[cmbody->id].normals = mc.getNormals();
			SF[cmbody->id].nbTriangles = mc.getNbTriangles();
			for(unsigned int i=0; i<scalarField.size(); i++) {
				for(unsigned int j=0; j<scalarField[i].size(); j++) scalarField[i][j].clear();
				scalarField[i].clear();
			}
			scalarField.clear();
		}
		initialized = true;
	}
示例#12
0
/*! 
SLMesh::buildAABB builds and returns the axis-aligned bounding box.
*/
SLAABBox& SLMesh::buildAABB()
{     
   // calculate min & max in object space
   SLVec3f minOS, maxOS;
   calcMinMax(minOS, maxOS);
   
   // enlarge aabb for avoiding rounding errors 
   minOS -= 0.01f;
   maxOS += 0.01f;
   
   // apply world matrix
   _aabb.fromOStoWS(minOS, maxOS, _wm);
   
   // build accelerations structure
   if (_accelStruct && numF > 5) 
      _accelStruct->build(minOS, maxOS);
      
   return _aabb;
}
示例#13
0
void ObjModel::normalize() {
	
	// get old minimums and maximums
	calcMinMax();

	// get old midpoint
	double midx = (maxX - minX) / 2.0 + minX;
	double midy = (maxY - minY) / 2.0 + minY;
	double midz = (maxZ - minZ) / 2.0 + minZ;
	this->center = Vector3(midx, midy, midz);

	


	double scaleFactor = 1.0 / max(maxX - minX, max(maxY - minY, maxZ - minZ));

	minX = minY = minZ = 1024;
	maxX = maxY = maxZ = -1024;
	this->radius = 0.0;
	for (vector<Vector3>::iterator it = vertices.begin(); it != vertices.end(); ++it) {
		// scale
		it->set((it->getX() - midx)*scaleFactor, (it->getY() - midy)*scaleFactor, (it->getZ() - midz)*scaleFactor);
		// calc radius
		double d = sqrt(it->getX()*it->getX() + it->getY()*it->getY() + it->getZ()*it->getZ());
		if (d > this->radius) {
			this->radius = d;
		}

		// calc new minimums and maximums
		// X
		if (it->getX() < minX) minX = it->getX();
		if (it->getX() > maxX) maxX = it->getX();

		// Y
		if (it->getY() < minY) minY = it->getY();
		if (it->getY() > maxY) maxY = it->getY();

		// Z
		if (it->getZ() < minZ) minZ = it->getZ();
		if (it->getZ() > maxZ) maxZ = it->getZ();
	}
}
示例#14
0
bool Comb::calc(Point startPoint, Point endPoint, std::vector<Point>& combPoints)
{
    if (shorterThen(endPoint - startPoint, MM2INT(1.5)))
        return true;
    
    bool addEndpoint = false;
    //Check if we are inside the comb boundaries
    if (!boundary.inside(startPoint))
    {
        if (!moveInside(&startPoint))    //If we fail to move the point inside the comb boundary we need to retract.
            return false;
        combPoints.push_back(startPoint);
    }
    if (!boundary.inside(endPoint))
    {
        if (!moveInside(&endPoint))    //If we fail to move the point inside the comb boundary we need to retract.
            return false;
        addEndpoint = true;
    }
    
    //Check if we are crossing any boundaries, and pre-calculate some values.
    if (!lineSegmentCollidesWithBoundary(startPoint, endPoint))
    {
        //We're not crossing any boundaries. So skip the comb generation.
        if (!addEndpoint && combPoints.size() == 0) //Only skip if we didn't move the start and end point.
            return true;
    }
    
    //Calculate the minimum and maximum positions where we cross the comb boundary
    calcMinMax();
    
    std::vector<Point> pointList;
    getBasicCombingPath(endPoint, pointList);
    
    bool succeeded = optimizePath(startPoint, pointList, combPoints);
    if (addEndpoint)
        combPoints.push_back(endPoint);
    return succeeded;
}
示例#15
0
void VertexBox::addVertexBox(VertexBox *f)
{
	int i, j;
	float *pDstData, *pSrcData;
	bool *pDstDataMap, *pSrcDataMap;

	if (m_numVertices != f->getNumVertices()
			|| m_numPrimitives != f->getNumPrimitives()
			|| m_numElementsPerVertex != f->getNumElementsPerVertex()) {
		return;
	}

	pDstData = m_pData;
	pDstDataMap = m_pDataMap;

	pSrcData = f->getDataPointer();
	pSrcDataMap = f->getDataMapPointer();

	for (i = 0; i < m_numVertices; i++) {
		for (j = 0; j < m_numElementsPerVertex; j++) {
			if (*pSrcDataMap) {
				*pDstDataMap = true;
				*pDstData = *pSrcData;
				pDstData++;
				pSrcData++;
			} else {
				pDstData++;
				pSrcData++;
			}
		}
		pDstDataMap++;
		pSrcDataMap++;
	}
	calcMinMax();

	emit dataChanged();
}
示例#16
0
bool Comb::calc(Point startPoint, Point endPoint, vector<Point>& combPoints)
{
    if (shorterThen(endPoint - startPoint, MM2INT(1.5)))
        return true;
    
    bool addEndpoint = false;
    //Check if we are inside the comb boundaries
    if (!checkInside(startPoint))
    {
        if (!moveInside(&startPoint))    //If we fail to move the point inside the comb boundary we need to retract.
            return false;
        combPoints.push_back(startPoint);
    }
    if (!checkInside(endPoint))
    {
        if (!moveInside(&endPoint))    //If we fail to move the point inside the comb boundary we need to retract.
            return false;
        addEndpoint = true;
    }
    
    //Check if we are crossing any bounderies, and pre-calculate some values.
    if (!preTest(startPoint, endPoint))
    {
        //We're not crossing any boundaries. So skip the comb generation.
        if (!addEndpoint && combPoints.size() == 0) //Only skip if we didn't move the start and end point.
            return true;
    }
    
    //Calculate the minimum and maximum positions where we cross the comb boundary
    calcMinMax();
    
    int64_t x = sp.X;
    vector<Point> pointList;
    //Now walk trough the crossings, for every boundary we cross, find the initial cross point and the exit point. Then add all the points in between
    // to the pointList and continue with the next boundary we will cross, until there are no more boundaries to cross.
    // This gives a path from the start to finish curved around the holes that it encounters.
    while(true)
    {
        unsigned int n = getPolygonAbove(x);
        if (n == UINT_MAX) break;
        
        pointList.push_back(matrix.unapply(Point(minX[n] - MM2INT(0.2), sp.Y)));
        if ( (minIdx[n] - maxIdx[n] + boundery[n].size()) % boundery[n].size() > (maxIdx[n] - minIdx[n] + boundery[n].size()) % boundery[n].size())
        {
            for(unsigned int i=minIdx[n]; i != maxIdx[n]; i = (i < boundery[n].size() - 1) ? (i + 1) : (0))
            {
                pointList.push_back(getBounderyPointWithOffset(n, i));
            }
        }else{
            minIdx[n]--;
            if (minIdx[n] == UINT_MAX) minIdx[n] = boundery[n].size() - 1;
            maxIdx[n]--;
            if (maxIdx[n] == UINT_MAX) maxIdx[n] = boundery[n].size() - 1;
            for(unsigned int i=minIdx[n]; i != maxIdx[n]; i = (i > 0) ? (i - 1) : (boundery[n].size() - 1))
            {
                pointList.push_back(getBounderyPointWithOffset(n, i));
            }
        }
        pointList.push_back(matrix.unapply(Point(maxX[n] + MM2INT(0.2), sp.Y)));
        
        x = maxX[n];
    }
    pointList.push_back(endPoint);
    
    //Optimize the pointList, skip each point we could already reach by not crossing a boundary. This smooths out the path and makes it skip any unneeded corners.
    Point p0 = startPoint;
    for(unsigned int n=1; n<pointList.size(); n++)
    {
        if (collisionTest(p0, pointList[n]))
        {
            if (collisionTest(p0, pointList[n-1]))
                return false;
            p0 = pointList[n-1];
            combPoints.push_back(p0);
        }
    }
    if (addEndpoint)
        combPoints.push_back(endPoint);
    return true;
}
示例#17
0
文件: main.cpp 项目: ptitSeb/f1spirit
int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    LPSTR lpCmdLine, int nCmdShow)
{
#else
int main(int argc, char** argv) {
#endif

	SDL_Surface *screen_sfc;
	F1SpiritApp *game;
	KEYBOARDSTATE *k;

	int time, act_time;
	SDL_Event event;
	bool quit = false;
	bool need_to_redraw = true;

#ifdef F1SPIRIT_DEBUG_MESSAGES

	output_debug_message("Application started\n");
#endif
#ifdef HAVE_GLES
	fullscreen = true;
#endif
	screen_sfc = initialization((fullscreen ? SDL_FULLSCREEN : 0));

	if (screen_sfc == 0)
		return 0;

	k = new KEYBOARDSTATE();

	game = new F1SpiritApp();

	#if 0//ndef HAVE_GLES
	// why recreating the context ???
	if (fullscreen) {
	#ifdef HAVE_GLES
		EGL_Close();
		screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, (fullscreen ? SDL_FULLSCREEN : 0));
		EGL_Open((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y);
	#else
		screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0));
	#endif
		SDL_WM_SetCaption(application_name, 0);
		SDL_ShowCursor(SDL_DISABLE);
		reload_textures++;

	#ifndef HAVE_GLES
		SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	#endif
	} 
	#endif

	time = init_time = SDL_GetTicks();
	
	IMG_Init(IMG_INIT_JPG|IMG_INIT_PNG);

	while (!quit) {
		while ( SDL_PollEvent( &event ) ) {
			switch ( event.type ) {
					/* Keyboard event */

				case SDL_KEYDOWN:
#ifdef __APPLE__

					if (event.key.keysym.sym == SDLK_q) {
						SDLMod modifiers;
						modifiers = SDL_GetModState();

						if ((modifiers &KMOD_META) != 0) {
							quit = true;
						}
					}

#else
					if (event.key.keysym.sym == SDLK_F12) {
						quit = true;
					} 

#endif
					if (event.key.keysym.sym == SDLK_F10) {
						game->save_configuration("f1spirit.cfg");
						game->load_configuration("f1spirit.cfg");
					} 

#ifdef _WIN32
					if (event.key.keysym.sym == SDLK_F4) {
						SDLMod modifiers;

						modifiers = SDL_GetModState();

						if ((modifiers&KMOD_ALT) != 0)
							quit = true;
					} 

#endif
#ifdef __APPLE__
					if (event.key.keysym.sym == SDLK_f) {
						SDLMod modifiers;

						modifiers = SDL_GetModState();

						if ((modifiers&KMOD_META) != 0) {
							/* Toggle FULLSCREEN mode: */
							if (fullscreen)
								fullscreen = false;
							else
								fullscreen = true;

							screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0));

							calcMinMax((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y);

							SDL_WM_SetCaption(application_name, 0);

							SDL_ShowCursor(SDL_DISABLE);

							reload_textures++;

							SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);

							SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);

							SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);

							SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
						}
					}

#else
					if (event.key.keysym.sym == SDLK_RETURN) {
						SDLMod modifiers;

						modifiers = SDL_GetModState();

						if ((modifiers&KMOD_ALT) != 0) {
							/* Toggle FULLSCREEN mode: */
							if (fullscreen)
								fullscreen = false;
							else
								fullscreen = true;
							#ifndef HAVE_GLES

							#ifdef HAVE_GLES
							EGL_Close();
							screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0));
							EGL_Open((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y);
							#else
							screen_sfc = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, COLOUR_DEPTH, SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0));
							#endif

							calcMinMax((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y);
							
							SDL_WM_SetCaption(application_name, 0);

							SDL_ShowCursor(SDL_DISABLE);

							reload_textures++;

							#ifndef HAVE_GLES
							SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
							SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
							SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
							SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
							SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
							SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
							#endif
							#endif
						}
					}

#endif

					if (event.key.keysym.sym == SDLK_f) {
						SDLMod modifiers;

						modifiers = SDL_GetModState();

						if ((modifiers&KMOD_ALT) != 0) {
							/* toggle FPS mode: */
							if (show_fps)
								show_fps = false;
							else
								show_fps = true;
						} 
					} 

					/* Keyboard event */
					SDL_keysym *ks;

					ks = new SDL_keysym();

					*ks = event.key.keysym;

					k->keyevents.Add(ks);

					break;

					/* SDL_QUIT event (window close) */

				case SDL_QUIT:
					quit = true;

					break;
			} 
		} 

		act_time = SDL_GetTicks();

		if (act_time - time >= REDRAWING_PERIOD) 
		{
			int max_frame_step = 10;
			/*
			   frames_per_sec_tmp+=1;
			   if ((act_time-init_time)>=1000) {
			    frames_per_sec=frames_per_sec_tmp;
			    frames_per_sec_tmp=0;
			    init_time=act_time;
			   } // if
			*/
			// On PANDORA, let's target 25 fps...
			int min_frame=1;
			#ifdef PANDORA
			min_frame=2;
			#endif

			do {
				time += REDRAWING_PERIOD;

				if ((act_time - time) > 10*REDRAWING_PERIOD)
					time = act_time;

				/* cycle */
				k->cycle();

				if (!game->cycle(k))
					quit = true;

				need_to_redraw = true;

				k->keyevents.Delete();

				act_time = SDL_GetTicks();

				max_frame_step--;
				min_frame--;
			} while (((act_time - time >= REDRAWING_PERIOD) && (max_frame_step > 0)) || (min_frame > 0));

		} 

		/* Redraw */
		if (need_to_redraw) {
			game->draw();
			need_to_redraw = false;
			frames_per_sec_tmp += 1;
		} 

		if ((act_time - init_time) >= 1000) {
			frames_per_sec = frames_per_sec_tmp;
			frames_per_sec_tmp = 0;
			init_time = act_time;
		} 

		#ifndef PANDORA
		SDL_Delay(1);
		#endif

	} 


	delete k;

	k = 0;

	delete game;

	game = 0;

	Stop_playback();

	finalization();

#ifdef F1SPIRIT_DEBUG_MESSAGES

	output_debug_message("Application finished\n");

	close_debug_messages();

#endif

	return 0;
} /* main */
示例#18
0
文件: main.cpp 项目: ptitSeb/f1spirit
SDL_Surface *initialization(int flags)
{
	const SDL_VideoInfo* info = 0;
	int bpp = 0;
	SDL_Surface *screen;

	rg = new TRanrotBGenerator(0);

#ifdef F1SPIRIT_DEBUG_MESSAGES

	output_debug_message("Initializing SDL\n");
#endif

	if (SDL_Init(SDL_INIT_VIDEO | (sound ? SDL_INIT_AUDIO : 0) | SDL_INIT_JOYSTICK | SDL_INIT_EVENTTHREAD) < 0) {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("Video initialization failed: %s\n", SDL_GetError());
#endif

		return 0;
	} 

#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("SDL initialized\n");

#endif

	info = SDL_GetVideoInfo();

	if (!info) {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("Video query failed: %s\n", SDL_GetError());
#endif

		return 0;
	} 

	if (fullscreen) {
		bpp = COLOUR_DEPTH;
	} else {
		bpp = info->vfmt->BitsPerPixel;
	}

	desktopW = info->current_w;
	desktopH = info->current_h;
#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("Setting OpenGL attributes\n");

#endif
#ifndef HAVE_GLES
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
#endif
#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("OpenGL attributes set\n");

#endif

#ifdef F1SPIRIT_DEBUG_MESSAGES

	output_debug_message("Initializing video mode\n");

#endif
#ifdef HAVE_GLES
	fullscreen = true;
	flags = SDL_FULLSCREEN;
#else
	flags = SDL_OPENGL | flags;
#endif
	screen = SDL_SetVideoMode((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y, bpp, flags);

	if (screen == 0) {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("Video mode set failed: %s\n", SDL_GetError());
#endif

		return 0;
	} 
#ifdef HAVE_GLES
	EGL_Open((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y);
#endif

#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("Video mode initialized\n");

#endif

	calcMinMax((fullscreen)?desktopW:SCREEN_X, (fullscreen)?desktopH:SCREEN_Y);

	SDL_WM_SetCaption(application_name, 0);

	SDL_WM_SetIcon(SDL_LoadBMP("graphics/f1sicon.bmp"), NULL);

	SDL_ShowCursor(SDL_DISABLE);

	if (sound) {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("Initializing Audio\n");
#endif

		N_SFX_CHANNELS = Sound_initialization(N_SFX_CHANNELS, 0);

#ifdef F1SPIRIT_DEBUG_MESSAGES

		output_debug_message("Audio initialized\n");
#endif

	} 

	// Network:
#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("Initializing SDL_net...\n");

#endif

	if (SDLNet_Init() == -1) {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("Error initializing SDL_net: %s.\n", SDLNet_GetError());
#endif

		network = false;
	} else {
#ifdef F1SPIRIT_DEBUG_MESSAGES
		output_debug_message("SDL_net initialized.\n");
#endif

		network = true;
	} 

	SDL_EnableUNICODE(1);

	glGetIntegerv(GL_STENCIL_BITS, &g_stencil_bits);

#ifdef F1SPIRIT_DEBUG_MESSAGES
	output_debug_message("OpenGL stencil buffer bits: %i\n", g_stencil_bits);

#endif


	return screen;
} /* initialization */
void CTimelineControl::paintControl( uiGraphics *pG )
{
	if ( m_needSortValue == true )
	{
		sortValue(m_value);	
		calcMinMax(m_value);
		m_needSortValue = false;
	}

	int nWidth = getClientWidth();
	int nHeight = getClientHeight();
	
	uiBrush bgGrey( uiColor(0x9f9f9f) );
	uiBrush bgGreyDark( uiColor(0x666666) );

	uiFont tahoma(14, L"tahoma");
	tahoma.setFontNormal();

	uiGraphics *graphics = pG->createBackBuffer( nWidth, nHeight );
	
	// fill background
	graphics->drawFillRectangle(0,0, nWidth, nHeight, &bgGrey);	
		
	if ( m_timeLength > 0.0f )
	{
		// draw header & left
		graphics->drawFillRectangle(0,0, OFFSET_X, nHeight, &bgGreyDark);
		graphics->drawFillRectangle(0,0, nWidth, OFFSET_Y, &bgGreyDark);

		float midValue = (m_maxValue + m_minValue)*0.5f;	
		
		uiPen pen(1, PS_SOLID, uiColor(0x888888));
		uiPen penX(2, PS_SOLID, uiColor(0x0000ff));
		uiPen penY(2, PS_SOLID, uiColor(0x00ff00));
		uiPen penZ(2, PS_SOLID, uiColor(0xff0000));

		graphics->selectObject(&pen);

		// draw center line
		graphics->drawLine(0, getY(midValue), nWidth, getY(midValue));
		
		// draw limit line
		graphics->drawLine(0, getY(m_minValue), nWidth, getY(m_minValue));
		graphics->drawLine(0, getY(m_maxValue), nWidth, getY(m_maxValue));
		
		graphics->selectObject( &tahoma );
		graphics->setTextBkTransparent(true);
		
		wchar_t text[512];
		graphics->setTextColor( uiColor(0xffffff) );

		swprintf(text,512,L"%.2f", m_minValue);
		graphics->drawText( 5, getY(m_minValue), text );

		swprintf(text,512,L"%.2f", m_maxValue);
		graphics->drawText( 5, getY(m_maxValue), text );

		swprintf(text,512,L"%.2f", midValue);
		graphics->drawText( 5, getY(midValue), text );
		
		// set clipping
		graphics->setClip(OFFSET_X, 0, nWidth - OFFSET_X, nHeight);

		int len = (int)m_value.size();
		for ( int i = 1; i < len; i++ )
		{
			int x0 = getX( m_value[i-1].time );
			int x1 = getX( m_value[i].time );
									
			int y0 = getY( m_value[i-1].x );
			int y1 = getY( m_value[i].x );

			// draw col
			graphics->selectObject(&pen);
			graphics->drawLine(x1,0, x1,nHeight);
			
			swprintf(text,512,L"%.2f", m_value[i].time);
			if ( i == m_selectTimeID )
				graphics->setTextColor( uiColor(0x0000ff) );
			else
				graphics->setTextColor( uiColor(0xffffff) );

			graphics->drawText( x1, 0, text );

			// draw line x
			graphics->selectObject(&penX);
			graphics->drawLine(x0, y0, x1, y1);
			
			// draw line y
			y0 = getY( m_value[i-1].y );
			y1 = getY( m_value[i].y );
			graphics->selectObject(&penY);
			graphics->drawLine(x0, y0, x1, y1);

			// draw line z
			y0 = getY( m_value[i-1].z );
			y1 = getY( m_value[i].z );
			graphics->selectObject(&penZ);
			graphics->drawLine(x0, y0, x1, y1);
		}
		
		for ( int i = 0; i < len; i++ )
		{
			int r = 4;
			int x1 = getX( m_value[i].time );									
			int y1 = getY( m_value[i].x );					

			// draw rectX
			graphics->selectObject(&penX);			
			graphics->drawRectangle( x1-r,y1-r,x1+r,y1+r );
			
			// draw rectY
			y1 = getY( m_value[i].y );
			graphics->selectObject(&penY);
			graphics->drawRectangle( x1-r,y1-r,x1+r,y1+r );

			// draw rectZ
			y1 = getY( m_value[i].z );
			graphics->selectObject(&penZ);
			graphics->drawRectangle( x1-r,y1-r,x1+r,y1+r );
		}

		graphics->selectObject(&penX);
	
		// paint current time
		uiPen penTime(1, PS_SOLID, uiColor(0x00FFFF));

		if ( m_selectTimeID == -1 )
		{
			int xTime = getX( m_currentTime );
			graphics->selectObject(&penTime);
			graphics->drawLine( xTime, 0, xTime, nHeight );
		}
		else
		{
			int xTime = getX( m_value[m_selectTimeID].time );
			graphics->selectObject(&penTime);
			graphics->drawLine( xTime, 0, xTime, nHeight );
		}

	}	

	pG->swapBuffer(0,0,nWidth, nHeight, graphics, 0,0,nWidth,nHeight, SRCCOPY);
	graphics->releaseGraphics();	
}