void ComponentSteering::move(Vector2d steering)
{
	//steering.truncate(max_force);
	//steering /= mass;
	parent->velocity += steering * 0.1;
	//parent->velocity.truncate(maxSpeed);
	//Debug Lines
	gameManager->getGraphicsEngine()->drawDebugLine(parent->position.asVector3d(),(parent->position + parent->velocity*20).asVector3d(),2);
	gameManager->getGraphicsEngine()->drawDebugLine(Vector2d(100,100).asVector3d(),Vector2d(-100,100).asVector3d(),2);
	gameManager->getGraphicsEngine()->drawDebugLine(Vector2d(-100,100).asVector3d(),Vector2d(-100,-100).asVector3d(),2);
	gameManager->getGraphicsEngine()->drawDebugLine(Vector2d(-100,-100).asVector3d(),Vector2d(100,-100).asVector3d(),2);
	gameManager->getGraphicsEngine()->drawDebugLine(Vector2d(100,-100).asVector3d(),Vector2d(100,100).asVector3d(),2);
	//gameManager->getGraphicsEngine()->drawDebugLine(parent->position.asVector3d(),(parent->position + steering*150).asVector3d(),3);
	
	//Modificaciones en la nave
	parent->rotation = parent->velocity.getAngle(); 
	parent->position += parent->velocity * speed;
	//parent->velocity.normalize();
}
Example #2
0
void Map::CalcBetaSkeletonWithMoon(float gamma, const float STEP_X, const float STEP_Y, const float WIDTH, const float HEIGHT)
{
	int size = towns.size();
	std::vector<Vector2d> pointInBetaSkeleton;
	bool hasATownInBetaSkeleton = false;
	int cmp = 0;
	for (int a = 0; a < size; ++a)
	{
		for (int b = cmp; b < size; ++b)
		{
			if (a == b) continue;
			bool hasATownInBetaSkeleton = false;
			for (int p = 0; p < size; ++p)
			{
				if (p != a && p != b && IsInBetaSkeleton(towns[p], towns[a], towns[b], gamma))
				{
					hasATownInBetaSkeleton = true;
				}

			}
			if (!hasATownInBetaSkeleton)
			{

				waysPoints.push_back(towns[a]);
				waysPoints.push_back(towns[b]);
				waysEdges.push_back(Vector2d(waysPoints.size() - 2, waysPoints.size() - 1));
			}

			for (float x = 0; x < WIDTH; x += STEP_X)
			{
				for (float y = 0; y < HEIGHT; y += STEP_Y)
				{
					Vector2d p(x, y);
					if (IsInMoonBetaSkeleton(p, towns[a], towns[b], gamma))
					{
						pointInBetaSkeleton.push_back(p);
					}
				}
			}

			AddWayFromPointList(pointInBetaSkeleton);
		}
		++cmp;
	}
}
Example #3
0
//typedef enum { Up, UpRight, Right, DownRight, Down, DownLeft, Left, UpLeft, None } Direction;
void Ship::PlayerUpdate()
{  
  // Be clever and arrange the enums so you can do a bit mask?
  if ( DPad == UpLeft || DPad == Left || DPad == DownLeft )
  {
    ShipRotation -= RotationRate * DeltaTime;
    ( ShipRotation > 360 ) ? ShipRotation -= 360 : ( ( ShipRotation < 0 ) ? ShipRotation += 360 : ShipRotation );
  }
  else if (DPad == UpRight || DPad == Right || DPad == DownRight )
  {
    ShipRotation += RotationRate * DeltaTime;
    ( ShipRotation > 360 ) ? ShipRotation -= 360 : ( ( ShipRotation < 0 ) ? ShipRotation += 360 : ShipRotation );
  }

  int rotation = ShipRotation / 45;
  ShipFacing = static_cast<Direction>( rotation );
  
  // 28,200 -> 28,138
  PlayerShip->BitMap = PlayerBitMaps[ShipFacing];
  
  // Friction
  if (! ( DPad == Up || DPad == UpRight || DPad == UpLeft ) )
  {
    Vector2d friction = *Velocity;
    friction = friction * -1.0f * ShipFriction * DeltaTime;
    *Velocity += friction;
  }

  Vector2d thrust = Vector2d( 0, 0 );
  if ( DPad == Up || DPad == UpRight || DPad == UpLeft )
    thrust = CalcThrust( ShipFacing );
  else if ( DPad == Down || DPad == DownRight || DPad == DownLeft )
    thrust = CalcThrust( ShipFacing ) * -0.4f;
  
  UpdateMovement( thrust );

  {
    TimeUntilNextRepair -= DeltaTime;
    if ( TimeUntilNextRepair <= 0 )
    {
      TimeUntilNextRepair = RepairTime;// + ( RepairTime * 10 - RepairTime * 10 * Crew / Max_Crew );
      RepairSystem();
    }
  }
}
Example #4
0
Vector2d ChartBase::convert_to_data(const Vector2d& point) const
{
    const Vector2d min = m_window_origin + m_margin;
    const Vector2d max = m_window_origin + m_window_size - m_margin - Vector2d(1.0);

    Vector2d p = point;

    if (p.x < min.x) p.x = min.x;
    if (p.x > max.x) p.x = max.x;
    if (p.y < min.y) p.y = min.y;
    if (p.y > max.y) p.y = max.y;

    Vector2d u = (p - min) / (max - min);

    u.y = 1.0 - u.y;

    return u * m_points_bbox.extent() + m_points_bbox.min;
}
//----------------------------------------------------------------------------
void RoughPlaneParticle1::OnIdle ()
{
#ifndef SINGLE_STEP
    if (mContinueSolving)
    {
        mModule.Update();
        if (mModule.GetX() > 0.0 && mModule.GetW() <= 0.0)
        {
            mContinueSolving = false;
            return;
        }

        mVFPositions.push_back(GetVFPosition(mModule.GetTime()));
        mSFPositions.push_back(Vector2d(mModule.GetX(), mModule.GetW()));
        OnDisplay();
    }
#endif
}
void VisualOdometry::setRef3DPoints()
{
    // select the features with depth measurements 
    pts_3d_ref_.clear();
    descriptors_ref_ = Mat();
    for ( size_t i=0; i<keypoints_curr_.size(); i++ )
    {
        double d = ref_->findDepth(keypoints_curr_[i]);               
        if ( d > 0)
        {
            Vector3d p_cam = ref_->camera_->pixel2camera(
                Vector2d(keypoints_curr_[i].pt.x, keypoints_curr_[i].pt.y), d
            );
            pts_3d_ref_.push_back( cv::Point3f( p_cam(0,0), p_cam(1,0), p_cam(2,0) ));
            descriptors_ref_.push_back(descriptors_curr_.row(i));
        }
    }
}
Example #7
0
// Cambia la posicion de la tabla y la de todos sus elementos de texto
void GUITable::setPosition( float x, float y )
{
	Clock clock;
	clock.start();

	this->position = Vector2d(x, y);
	Vector2d textPosition; // Texto de cada celda

	// El primer elemento se situa a la izquierda de la tabla
	// los siguientes de la fila van sumando el width de su anterior
	textPosition.x = this->position.x; 

	int columnIndex;

	// Calcular la posicion de cada elemento de texto para cada celda
	// Hemos de suponer que las celdas estan ordenadas por filas de izquierda a derecha
	for ( size_t i = 0; i < cells.size(); i++ )
	{
		columnIndex = cells[i].columnIndex;

		textPosition.y = this->position.y + (cells[i].rowIndex * ROW_HEIGHT);

		cells[i].text->setPosition(textPosition.x, textPosition.y);

		// Si estamos en la ultima celda de la fila, reseteamos la x
		if ( columnIndex == columns.size() - 1 )
		{
			textPosition.x = this->position.x;
		}// En caso contrario sumamos el width de esta celda para la siguiente
		else
		{
			textPosition.x += columns[columnIndex].width;
		}
	}

	// Titulos de las columnas encima de la tabla
	textPosition.x = this->position.x;
	textPosition.y = this->position.y - ROW_HEIGHT;
	for (size_t i = 0; i < columns.size(); i++)
	{
		columns[i].caption->setPosition(textPosition.x, textPosition.y);
		textPosition.x += columns[i].width;
	}
}
Example #8
0
void Tank::evalPfield(GameConstants &gc,
	Polygon &base,
	vector<Tank*> &tanks,
	vector<Flag*> &flags,
	vector<Tank*> &enemy_tanks,
	vector<Flag*> &enemy_flags,
	vector<Polygon*> &obstacles
){			
	double pi = 3.1415926435;
	Vector2d result = Vector2d(0);
	
	for (int i=0; i < obstacles.size(); i++){
		result += 0.4*obstacles[i]->potentialField(loc,dir);
	}
	/*for (int i=0; i < enemy_tanks.size(); i++)
	{
		result += enemy_tanks[i]->potentialField(loc,dir);
	}
	for (int i=0; i < enemy_flags.size(); i++)
	{
		result -= 30 * enemy_flags[i]->potentialField(loc,dir);
		cout << enemy_flags[i]->loc[0] << ", " << enemy_flags[i]->loc[1] << endl;
	}
	*/
	result -= 60*goals[goals.size()-1]->potentialField(loc,dir);	
	
	double desiredAngle = atan2(result[1], result[0]);
	double desiredMagnitude = result.length();
	double currentAngle = atan2(dir[1], dir[0]);
	
	Tank::protocol.speed(idx, 1); //desiredMagnitude*.4
	//cout << desiredMagnitude *.1 << endl;
	
	double angDiff = currentAngle - desiredAngle;
	while (angDiff < -1 * pi){
		angDiff += (2*pi);
	}
	while (angDiff > pi){
		angDiff -= (2*pi);
	}
	
	Tank::protocol.angvel(idx, -angDiff/pi);
	Tank::protocol.shoot(idx);
}
Example #9
0
Platform* MapGenerator::generatePlatform(Vector2d* startVector)
{
	// 1. get possible set
	// 2. get allowed set
	// 3. modify chance (using buffer & deltaY)
	// 4. select GeneratedBlock
	// 5. add platformblock to platform
	// 6. add used GeneratedBlock to buffer

	Platform* platform = new Platform();

	set<GeneratedBlock> possibleSet = allZeroes;
	set<GeneratedBlock> allowedSet = getAllowedSet(possibleSet, startVector);
	modifyChances(allowedSet, startVector);
	GeneratedBlock* selectedBlock = selectBlock(allowedSet);

	PlatformBlock* block = new PlatformBlock(selectedBlock->type, startVector);
	platform->addPlatformBlock(block);

	Vector2d* newStartVector = block->getEndVector();

	addToBuffer(*selectedBlock);

	int length = (PLATFORM_LENGTH_MIN - 1) + (rand() % (2 + PLATFORM_LENGTH_MAX - PLATFORM_LENGTH_MIN));

	for (int i = 0; i < length; i++) {

		possibleSet = getPossibleSet(selectedBlock);
		allowedSet = getAllowedSet(possibleSet, newStartVector);
		modifyChances(allowedSet, newStartVector);
		selectedBlock = selectBlock(allowedSet);

		*newStartVector+=Vector2d(0.f, selectedBlock->dy);

		block = new PlatformBlock(selectedBlock->type, newStartVector);
		platform->addPlatformBlock(block);

		newStartVector = block->getEndVector();

		addToBuffer(*selectedBlock);
	}

	return platform;
}
JNIEXPORT jintArray JNICALL Java_fr_myrddin_triangulate_Triangulate_jniTriangulate (JNIEnv *env, jobject obj, jintArray polygonArray)
{

	jint polygonCount; 
	polygonCount = env->GetArrayLength(polygonArray);
	
	Polygon polygon(polygonCount / 2);
	Polygon solution;

	jint buffer[polygonCount];
	jint i;
	env->GetIntArrayRegion(polygonArray, 0, polygonCount, buffer);
	for (i = 0; i < polygonCount; i += 2) 
	{
		polygon[i / 2] = Vector2d(buffer[i], buffer[i + 1]);
	}

	Triangulate::Process(polygon,solution);
	
	jint count = (int) solution.size();

	if (count > 0)
	{
		jintArray result;
		result = env->NewIntArray( count * 2);

		if (result == NULL) {
			return NULL;
		}

		jint fill[count * 2];
		for (int i = 0; i < count; i++) {
			// Push all the vertices into the array
			fill[i * 2] = solution[i].GetX();
			fill[i * 2 + 1] = solution[i].GetY();
		}
		// Insert the array into the returnArray
		env->SetIntArrayRegion(result, 0, count * 2,fill);
		
		return result;
	}
	return NULL;
}
Example #11
0
UpdateResult Turret::update2(int ms, GlobalState &GS)
{
	bool Firing = false;
	Vector2d ShootingDirection = Vector2d(0,0);
	Grid* G = GS.TheGrid;
	std::list<Cell*> NearbyCells;
	G->get_nearby_cells(NearbyCells, Pos, CellSize * 12);
	for (auto itr = NearbyCells.begin(); itr != NearbyCells.end(); ++itr)
	{
		for (auto itr2 = (*itr)->CreepList.begin(); itr2 != (*itr)->CreepList.end(); ++itr2)
		{
			if(CheckVisibility(Pos, (*itr)->getPos()))
				ShootingDirection += GetForce(Pos, (*itr)->getPos());
		}
	}
	if(ShootingDirection.x != 0 && ShootingDirection.y != 0)
	{
		Firing = true;
		TurnTo(Rot, atan2(ShootingDirection.y, ShootingDirection.x), 8 * (ms / 1000.0));
	}
	FireTimer -= ms;
	if(FireTimer < 0)
	{
		if(Firing)
		{

			FireTimer += FireRate;
			Projectile* new_projectile = ProjectileToFireOnDeath->clone();
			new_projectile->setPos(Pos);
			new_projectile->setRot(Rot);
			Parent->AddChild (new_projectile);
			//Out of ammo
			if(--Ammo == 0)
				return UPDATE_DELETE;
		}
		else
		{
			FireTimer = 0;
		}
	}

	return UPDATE_REDRAW;
}
//----------------------------------------------------------------------------
bool RoughPlaneParticle1::OnInitialize ()
{
    if (!WindowApplication2::OnInitialize())
    {
        return false;
    }

    // Set up the physics module.
    mModule.Gravity = 10.0;
    mModule.Mass = 10.0;
    mModule.Friction = 1.0;
    mModule.Angle = 0.125*Mathd::PI;

    // Initialize the differential equations.
    double time = 0.0;
    double deltaTime = 1.0/60.0;
    double x = 0.0;
    double w = 0.0;
    double xDer = 10.0;
    double wDer = 40.0;
    mModule.Initialize(time, deltaTime, x, w, xDer, wDer);

    // Initialize the coefficients for the viscous friction solution.
    mR = mModule.Friction/mModule.Mass;
    mA0 = -xDer/mR;
    mA1 = x - mA0;
    mB1 = -mModule.Gravity*Mathd::Sin(mModule.Angle)/mR;
    mB2 = (wDer + mR*w - mB1)/mR;
    mB0 = w - mB2;

    // Save path of motion.
    mVFPositions.push_back(GetVFPosition(time));
    mSFPositions.push_back(Vector2d(x, w));

    // Use right-handed coordinates.
    DoFlip(true);

    // Mass drawing might extend outside the application window.
    ClampToWindow() = true;

    OnDisplay();
    return true;
}
Example #13
0
// gets center of common arc of 2 lines if radii match inside maxSqerr range
Vector2d Printlines::arcCenter(const PLine l1, const PLine l2,
			       double maxSqerr) const
{
  Vector2d l1p1,l1p2;
  center_perpendicular(l1.from, l1.to, l1p1, l1p2);
  Vector2d l2p1,l2p2;
  center_perpendicular(l2.from, l2.to, l2p1, l2p2);
  Vector2d center, ip;
  double t0, t1;
  int is = intersect2D_Segments(l1p1, l1p2, l2p1, l2p2,
   				center, ip, t0,t1);
  if (is > 0) {
    // radii match?
    if (abs((l1p1-center).lengthSquared() -
	    (l2p1-center).lengthSquared()) < maxSqerr)
      return center;
  }
  return Vector2d(10000000,10000000);
}
Example #14
0
void CCutScene::createBackground()
{
    
    Point points[4] =
    {
        Point(0, 0), Point(0, 2048), Point(2048, 2048), Point(2048, 0)
    };
    Vector2dVector vcPoints;
    vcPoints.clear();
    for (int i = 0; i < 4; i++)
    {
        vcPoints.push_back(Vector2d(points[i].x, points[i].y));
    }
    
    PRFilledPolygon *filledPolygon = PRFilledPolygon::filledPolygonWithPointsAndTexture(vcPoints, "daanban.png");
    //filledPolygon->setPhysicsBody(PhysicsBody::createPolygon(points, 4));
    filledPolygon->setPosition(Vec2::ZERO + Vec2(0, (1536 - 2048) / 2));
    addChild(filledPolygon, 80);
}
Example #15
0
void trackKlt(
    FramePtr frame_ref,
    FramePtr frame_cur,
    vector<cv::Point2f>& px_ref,
    vector<cv::Point2f>& px_cur,
    vector<Vector3d>& f_ref,
    vector<Vector3d>& f_cur,
    vector<double>& disparities)
{
  const double klt_win_size = 30.0;
  const int klt_max_iter = 30;
  const double klt_eps = 0.001;
  vector<uchar> status;
  vector<float> error;
  vector<float> min_eig_vec;
  cv::TermCriteria termcrit(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, klt_max_iter, klt_eps);
  cv::calcOpticalFlowPyrLK(frame_ref->img_pyr_[0], frame_cur->img_pyr_[0],
                           px_ref, px_cur,
                           status, error,
                           cv::Size2i(klt_win_size, klt_win_size),
                           4, termcrit, cv::OPTFLOW_USE_INITIAL_FLOW);

  vector<cv::Point2f>::iterator px_ref_it = px_ref.begin();
  vector<cv::Point2f>::iterator px_cur_it = px_cur.begin();
  vector<Vector3d>::iterator f_ref_it = f_ref.begin();
  f_cur.clear(); f_cur.reserve(px_cur.size());
  disparities.clear(); disparities.reserve(px_cur.size());
  for(size_t i=0; px_ref_it != px_ref.end(); ++i)
  {
    if(!status[i])
    {
      px_ref_it = px_ref.erase(px_ref_it);
      px_cur_it = px_cur.erase(px_cur_it);
      f_ref_it = f_ref.erase(f_ref_it);
      continue;
    }
    f_cur.push_back(frame_cur->c2f(px_cur_it->x, px_cur_it->y));
    disparities.push_back(Vector2d(px_ref_it->x - px_cur_it->x, px_ref_it->y - px_cur_it->y).norm());
    ++px_ref_it;
    ++px_cur_it;
    ++f_ref_it;
  }
}
Example #16
0
DepthMap DepthMap::generatePlane(const ICamera * camera, const ScaleParameters & params, 
        Transformation<double> TcameraPlane, const Vector3dVec & polygonVec)
{
    DepthMap depth(camera, params);
    Vector3d t = TcameraPlane.trans();
    Vector3d z = TcameraPlane.rotMat().col(2);
    Vector3dVec polygonCamVec;
    TcameraPlane.transform(polygonVec, polygonCamVec);
    for (int v = 0; v < params.yMax; v++)
    {
        for (int u = 0; u < params.xMax; u++)
        {
            depth.at(u, v) = OUT_OF_RANGE;
            depth.sigma(u, v) = OUT_OF_RANGE;
            Vector3d vec; // the direction vector
            if (not camera->reconstructPoint(Vector2d(params.uConv(u), params.vConv(v)), vec)) continue;
            double zvec = z.dot(vec);
            if (zvec < 1e-3) 
            {
                continue;
            }
            bool inside = true;
            for (int i = 0; i < polygonCamVec.size(); i++)
            {
                int j = (i + 1) % polygonCamVec.size();
                Vector3d normal = polygonCamVec[i].cross(polygonCamVec[j]);
                if (vec.dot(normal) < 0)
                {
                    inside = false;
                    break;
                }
            }
            if (not inside) continue;
            double tz = t.dot(z);
            double alpha = tz / zvec;
            vec *= alpha;
            depth.at(u, v) = vec.norm();
            depth.sigma(u, v) = 1;
        }
    }
    return depth;
}
void mouse(int button, int state, int x, int y) {
    if (button == GLUT_LEFT_BUTTON) {
        if (state == GLUT_DOWN) {
            ::mouseForce.x = Vector2d(xmin + (double)x/w * (xmax - xmin),
                                      ymax - (double)y/h * (ymax - ymin));
            // find nearest particle
            double dmin = 0.2; // ignore particles farther than 0.2
            for (size_t i = 0; i < psys.particles.size(); i++) {
                Particle *p = psys.particles[i];
                double d = (p->x - ::mouseForce.x).norm();
                if (d < dmin) {
                    ::mouseForce.p = p;
                    dmin = d;
                }
            }
        } else if (state == GLUT_UP) {
            ::mouseForce.p = NULL;
        }
    }
}
EntityTransform::EntityTransform()
{
	//No hace falta hacerlo, ya lo hace automaticamente
	//transformMatrix = Matrix<float>();
	//auxMatrix = Matrix<float>();

	// Cargamos la identidad
	transformMatrix.setIdentity();

	setScale(1);
	setRotation(Vector3d(0,0,0));
	setTranslation(Vector3d(0,0,0));
	setTranslation(Vector2d(0,0));

	//La primera vez tiene que generar la matriz de transformacion
	dirty = true;
	visible = true;
	// Recogemos el graphics engine
	graphicsEngine = (GraphicsEngineTAG*)GameManager::getInstance()->getGraphicsEngine();
}
// Comprueba colision entre Colliders. Dos objetos se tocan/colisionan
void CollisionManager::checkCollisionBetween (ComponentCollider* currentCollider, ComponentCollider* targetCollider)
{
	GameObject *targetGameObject = targetCollider->getGameObject();

	//if(targetGameObject->isDead())
	//{
//		return;
//	}

	// Direccion entre objetos
	//Al hacerlo en una linea nos ahorramos crear un vector2d muchas veces
	float distance = (targetGameObject->position - currentCollider->getGameObject()->position).getSqrLength();              

	float sqrCollisionRadius = currentCollider->getSqrCollisionRadius();
	float sqrTargetRadius = targetCollider->getSqrCollisionRadius();

	// Colisionan. Se activa una colision en los dos objetos involucrados

	if(distance <= sqrCollisionRadius + sqrTargetRadius)
	{
		if(distance == 0)
		{
			targetGameObject->position += Vector2d(0,0.01);
			distance = (targetGameObject->position - currentCollider->getGameObject()->position).getSqrLength();              

		}
		Vector2d direction = targetGameObject->position - currentCollider->getGameObject()->position;
		direction.normalize();
		direction *= Math::sqrt(Math::abs(distance - (sqrCollisionRadius + sqrTargetRadius)));
		// La colision se envia con un objeto que es con el cual choca
		Collision collision;
		collision.collider = targetGameObject;
		collision.direction = direction;
		currentCollider->onCollision(collision);

		//La colision deberia llegar a los dos, si no, deberia ser checkVision...
		collision.collider = currentCollider->getGameObject();
		collision.direction = direction * -1;
		targetCollider->onCollision(collision);
	}
}
bool CReadWriteAsc::readAsc( const string& filename, vector<Vector2d>& points )
{

	std::ifstream fin(filename);
	std::vector<double> coefficients;

	std::string line;
	int nRow = 0;
	int nCol = 0;
	if( fin.fail() )
		return false;


	while( std::getline( fin, line ) )
	{
		std::stringstream ss(line);
		double d = 0;
		nCol = 0;
		while( ss >> d)
		{
			coefficients.push_back( d);
			++nCol;
		}
		++nRow;
	}
	fin.close();

	if( nCol < 2)
		return false;



	points.resize( nRow);
	int idx = 0;
	for( int i = 0; i!= nRow; ++i )
	{
		points[i] = Vector2d( coefficients[idx+0], coefficients[idx+1]);
		idx += nCol;
	}
	return true;
}
Example #21
0
void Race::HandleDeaths(){
    for (unsigned i=0; i<Player.size();i++)
    {
        if (Player[i].DeathSwitch==1)
        {
            continue;
        }
        Vector2u CurrentSquare=Player[i].getGridPosition();
        Tile* CurrentTile=track.getTile(CurrentSquare.x,CurrentSquare.y);
        Detect Detection=CurrentTile->Detection;
        vector<Vector2d> Bounding;
        if (CurrentTile->isSquare)
        {
            if( Detection.x.find(FALL)!=Detection.x.end())
            {
                Player[i].DeathSwitch=1;
                Bounding=track.getTileBounding(CurrentSquare.x,CurrentSquare.y);
            }
        }
        else{
            bool Orientation=CurrentTile->Orientation;
            if (!getTriangleHalf(Player[i].Position,Orientation) && Detection.x.find(FALL)!=Detection.x.end())
            {
                Player[i].DeathSwitch=1;
                Bounding=track.getTileBounding(CurrentSquare.x,CurrentSquare.y,0);
            }
            if(getTriangleHalf(Player[i].Position,Orientation) && Detection.y.find(FALL)!=Detection.y.end())
            {
                Player[i].DeathSwitch=1;
                Bounding=track.getTileBounding(CurrentSquare.x,CurrentSquare.y,1);
            }
        }
        if (Player[i].DeathSwitch==1)
        {
            Vector2d Average=accumulate(Bounding.begin(),Bounding.end(),Vector2d(0,0))/static_cast<double>(Bounding.size());
            Vector2d Difference=Average-Player[i].Position;
            Player[i].Velocity=Difference/Car::DeathDuration;
            Player[i].PositionBeforeDeath=Player[i].Position;
        }
    }
}
Example #22
0
bool DelaunayTriangulator::getAll(int i_index, std::vector<int>& neighborhood, std::vector<stk::Vector2d>& polygon)
{
	CGAL::Traits::Segment_2 s;

	CGAL::DelaunayTri* tri = (CGAL::DelaunayTri*) m_tri;
	std::vector<CGAL::VertexHandle>* vertices = (std::vector<CGAL::VertexHandle>*) m_vertices;
	
	if(tri->is_edge(vertices->at(i_index), tri->infinite_vertex())) return false;
	
	//List all incident vertices in delaunay triangulation
	{
		CGAL::VertexCirculator ec, start;
		ec = start = tri->incident_vertices(vertices->at(i_index));
		do
		{
			neighborhood.push_back(ec->info());
		}
		while ( ++ec != start );
	}
	
	//List all incident faces in delaunay triangulation
	{
		CGAL::FaceCirculator fc, start;
		fc = start = tri->incident_faces(vertices->at(i_index));
		if(fc != 0)
		{
			do
			{
				if(!tri->is_infinite(fc))
				{
					//The dual is a point in the voronoi polygon
					CGAL::Point currVert = tri->dual(fc);
					polygon.push_back(Vector2d(currVert.x(), currVert.y()));
				}
			}
			while (++fc != start);
		}
	}

	return true;
}
Example #23
0
void makeCube(std::vector<Vector3d>* vertices,
			std::vector<Vector4d>* colors,
			std::vector<Vector2d>* textures,
			std::vector<size_t>* triangles)
{
vertices->resize(numVertices);
colors->resize(numVertices);
textures->resize(numVertices);

double scale = 1.0;

for (int i=0; i<numVertices; ++i)
{
	(*vertices)[i] = Vector3d(vertexData[3*i]*scale, vertexData[3*i+1]*scale, vertexData[3*i+2]*scale);
	(*colors)[i] = Vector4d(colorData[4*i], colorData[4*i+1], colorData[4*i+2], colorData[4*i+3]);
	(*textures)[i] = Vector2d(textureData[2*i], textureData[2*i+1]);
}

triangles->resize(numTriangles*3);
std::copy(triangleData, triangleData+12*3,std::begin(*triangles));
}
Example #24
0
void LightSampler::sample_emitting_triangles(
    const Vector3d&         s,
    LightSample&            sample) const
{
    assert(m_emitting_triangle_cdf.valid());

    const EmitterCDF::ItemWeightPair result = m_emitting_triangle_cdf.sample(s[0]);
    const size_t emitter_index = result.first;
    const double emitter_prob = result.second;

    sample.m_light = 0;
    sample_emitting_triangle(
        Vector2d(s[1], s[2]),
        emitter_index,
        emitter_prob,
        sample);

    assert(sample.m_triangle);
    assert(sample.m_triangle->m_edf);
    assert(sample.m_probability > 0.0);
}
	PixelIterator::PixelIterator(const Vector2u&dims, const RectangleU&srcrect, const RectangleD&dstrect, const RectangleD&looprect, double xincrement, double yincrement, const TransformD&transform, const Vector2d&rat, bool mirrorHorizontal_arg, bool mirrorVertical_arg)
	{
		if(!dstrect.contains(looprect))
		{
			throw IllegalArgumentException("loopRect", "not within bounds of dstRect");
		}
		if((unsigned int)(srcrect.x + srcrect.width) > dims.x)
		{
			throw IllegalArgumentException("srcRect", "not within bounds of dimensions");
		}
		else if((unsigned int)(srcrect.y + srcrect.height) > dims.y)
		{
			throw IllegalArgumentException("srcRect", "not within bounds of dimensions");
		}
		usesTransform = true;
		started = false;
		dimensions = Vector2d((double)dims.x, (double)dims.y);
		srcRect = srcrect;
		srcRectD = RectangleD((double)srcRect.x, (double)srcRect.y, (double)srcRect.width, (double)srcRect.height);
		srcRectRight = srcRectD.x + srcRectD.width;
		srcRectBottom = srcRectD.y + srcRectD.height;
		dstRect = dstrect;
		loopRect = looprect;
		loopRectRel = RectD(loopRect.x-dstRect.x, loopRect.y-dstRect.y, loopRect.x+loopRect.width-dstRect.x, loopRect.y+loopRect.height-dstRect.y);
		ratio.x = rat.x;
		ratio.y = rat.y;
		incr.x = xincrement;
		incr.y = yincrement;
		incrpxl.x = incr.x*ratio.x;
		incrpxl.y = incr.y*ratio.y;
		inverseTransform = transform.getInverse();
		mirrorHorizontal = mirrorHorizontal_arg;
		mirrorVertical = mirrorVertical_arg;
		currentPoint.x = loopRect.x - dstRect.x;
		currentPoint.y = loopRect.y - dstRect.y;
		row = 0;
		lastRowStartIndex = 0;
		currentPixelIndex = calculatePixelIndex();
		lastRowStartIndex = currentPixelIndex;
	}
Example #26
0
Map Map::generate_random( const MapRandomConstraints& c, MapRandomResults& res ) {

	const int x_dimension = 75, y_dimension = 20;
	Map m( y_dimension, x_dimension );
	vector< Room > room_vector;

	size_t n_rooms = hack_range( 5, 12 );
	for( size_t i = 0; i < n_rooms; i++){

		Vector2d dim( hack_range( 5, 9 ), hack_range( 4, 8 ) );
		size_t tries = 0, j;

		while( tries < 20 ) {
			++ tries;

			Vector2d min_pt( hack_range( 1, x_dimension-dim.x-2 ), hack_range( 1, y_dimension-dim.y-2 ) );
			Vector2d max_pt = min_pt + dim;
			Room r( min_pt, max_pt );
			
			if( i != 0 ) {
				for( j = 0; j < room_vector.size(); j++ ) {
					if( r.overlaps( room_vector[j] ) )
						break;
				}

				if( j != room_vector.size() )	continue;
			}

			if( !room_vector.size() )
				res.player_location = r.min_pt + Vector2d( 2, 2 );

			room_vector.push_back( r );
			m.generate_room( r );
			break;
		}
	}

	return m;
}
Example #27
0
void LightSampler::sample_emitting_triangles(
    const ShadingRay::Time&             time,
    const Vector3d&                     s,
    LightSample&                        light_sample) const
{
    assert(m_emitting_triangles_cdf.valid());

    const EmitterCDF::ItemWeightPair result = m_emitting_triangles_cdf.sample(s[0]);
    const size_t emitter_index = result.first;
    const double emitter_prob = result.second;

    light_sample.m_light = 0;
    sample_emitting_triangle(
        time,
        Vector2d(s[1], s[2]),
        emitter_index,
        emitter_prob,
        light_sample);

    assert(light_sample.m_triangle);
    assert(light_sample.m_probability > 0.0);
}
Example #28
0
	EnvirInfo CalculateAbstractInfo(IEnvironment* env, Vector2d pos, float rotation) {
		EnvirInfo out;
		for(int i = 0; i < RAY_COUNT; ++i) {
			Vector2d orient = Vector2d(1,0);
			float angle = rotation + RAY_ANGLE / (RAY_COUNT - 1) * (i - RAY_COUNT / 2);
			orient.x = cos(angle *PI/180);
			orient.y = sin(angle *PI/180);
			EntityPtr ent = env->LineIntersect(pos, pos + orient, MAX_DIST, &out.ray_length[i]);
			if(ent != EntityPtr())
				out.ray_detail[i] = ent->Type();
			else
				out.ray_detail[i] = ET_NONE;

			if(out.ray_detail[i] == ET_BOT) {
				out.ray_udata[i] = ((Bot*)ent.get())->team;
			}
			rays[i] = pos + orient * out.ray_length[i];
			out.ray_pos[i].x = rays[i].x;
			out.ray_pos[i].y = rays[i].y;
		}
		return out;
	}
Example #29
0
PolygonSprite* PolygonSprite::initWithTexture(Texture2D* texture, b2Body* body, bool original)
{
	//gather all the vertices from our Box2D shape
	b2Fixture *originalFixture = body->GetFixtureList();
	b2PolygonShape *shape = (b2PolygonShape*)originalFixture->GetShape();
	int vertexCount = shape->GetVertexCount();

	Vector2dVector points;

	for(int i = 0; i < vertexCount; i++) {
		points.push_back( Vector2d(shape->GetVertex(i).x * PTM_RATIO, shape->GetVertex(i).y * PTM_RATIO) );
	}

	if(initWithPointsAndTexture(points, texture))
	{
		_body = body;
		_body->SetUserData(this);
		_original = original;
		// gets the center of the polygon
		_centroid = this->_body->GetLocalCenter();
		// assign an anchor point based on the center
		_anchorPoint = ccp(_centroid.x * PTM_RATIO / texture->getContentSize().width, 
								 _centroid.y * PTM_RATIO / texture->getContentSize().height);

		// more init stuff here later when you expand PolygonSprite

		// slice
		_sliceExited = false;
		_sliceEntered = false;
		_entryPoint.SetZero();
		_exitPoint.SetZero();
		_sliceEntryTime = 0;

		// fruits
		_state = kStateIdle;
	}

	return this;
}
Example #30
0
MgShape* MgCmdManagerImpl::addImageShape(const MgMotion* sender, const char* name,
                                         float xc, float yc, float w, float h)
{
    if (!name || *name == 0 || w < 1 || h < 1)
        return NULL;
    
    Vector2d size(Vector2d(w, h) * sender->view->xform()->displayToWorld());
    while (fabsf(size.x) > 200.f || fabsf(size.y) > 200.f) {
        size *= 0.95f;
    }
    size *= sender->view->xform()->worldToDisplay();
    
    Box2d rect(xc - size.x / 2, yc - size.y / 2, xc + size.x / 2, yc + size.y / 2);
    LOGD("addImageShape %s x:%.0f y:%.0f w:%.0f h:%.0f", 
         name, rect.xmin, rect.ymin, rect.width(), rect.height());
    rect *= sender->view->xform()->displayToModel();
    
    MgShapeT<MgImageShape> shape;
    MgImageShape* imagesp = (MgImageShape*)shape.shape();
    
    shape.context()->setLineStyle(kGiLineNull);         // 默认没有边框
    shape.context()->setFillColor(GiColor::White());    // 设为实填充,避免在中心无法点中
    imagesp->setName(name);
    imagesp->setRect2P(rect.leftTop(), rect.rightBottom());
    
    MgShapesLock locker(MgShapesLock::Add, sender->view);
    if (sender->view->shapeWillAdded(&shape)) {
        MgShape* newsp = sender->view->shapes()->addShape(shape);
        sender->view->shapeAdded(newsp);
        
        sender->view->setNewShapeID(newsp->getID());
        sender->toSelectCommand();
        
        return newsp;
    }
    
    return NULL;
}