Exemplo n.º 1
0
void GradientRangeEditor::setAngle( const qreal a )
{
	QLineF l = QLineF( _startPoint, _endPoint ) * QMatrix().rotate( a - angle() );
	setStartPoint( l.p1() );
	setEndPoint( l.p2() );
}
Exemplo n.º 2
0
CvSeq* EyeTracker::findSquares()
{
	CvSeq* contours;
	int i, N = 5;
	CvSize sz = cvSize( sceneImagePts->width, sceneImagePts->height);
	IplImage* gray = cvCreateImage( sz, 8, 1 );
	IplImage* tgray = cvCreateImage( sz, 8, 1 );
	CvSeq* result;
	double s, t;

	CvSeq* squares = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvPoint), squareStorage);

	cvCvtColor(sceneImagePts, tgray, CV_RGB2GRAY);

	// apply threshold if l!=0:
	//     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
	cvThreshold(tgray, gray, squareThreshold, 255, CV_THRESH_BINARY );

	// find contours and store them all as a list
	cvFindContours(gray, squareStorage, &contours, sizeof(CvContour),
				   CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));

	// test each contour
	while(contours)
	{
		// approximate contour with accuracy proportional
		// to the contour perimeter
		result = cvApproxPoly(contours, 
							  sizeof(CvContour), 
							  squareStorage,
							  CV_POLY_APPROX_DP, 
							  cvContourPerimeter(contours) * 0.02, 
							  0);

		// square contours should have 4 vertices after approximation
		// relatively large area (to filter out noisy contours)
		// and be convex.
		// Note: absolute value of an area is used because
		// area may be positive or negative - in accordance with the
		// contour orientation
		if(result->total == 4 &&
		   fabs(cvContourArea(result, CV_WHOLE_SEQ)) > 1000 &&
		   cvCheckContourConvexity(result))
		{
			s = 0;

			for(i = 0; i < 5; ++i)
			{
				// find minimum angle between joint
				// edges (maximum of cosine)
				if(i >= 2)
				{
					t = fabs(angle((CvPoint*)cvGetSeqElem(result, i),
								   (CvPoint*)cvGetSeqElem(result, i-2),
								   (CvPoint*)cvGetSeqElem(result, i-1)));
					s = s > t ? s : t;
				}
			}

			// if cosines of all angles are small
			// (all angles are ~90 degree) then write quandrange
			// vertices to resultant sequence
			if(s < 0.2)
			{
				CvSeqReader reader;

				// initialize reader of the sequence
				cvStartReadSeq(result, &reader, 0);
				CvPoint pt[4];

				CV_READ_SEQ_ELEM( pt[0], reader );
				CV_READ_SEQ_ELEM( pt[1], reader );
				CV_READ_SEQ_ELEM( pt[2], reader );
				CV_READ_SEQ_ELEM( pt[3], reader );

				for(int i = 1; i < 4; ++i)
				{
					for(int j = 0; j < 4 - i; ++j)
					{
						if(pt[j].x > pt[j+1].x)
						{
							CvPoint temp = pt[j+1];
							pt[j+1] = pt[j];
							pt[j] = temp;
						}
					}
				}

				if(pt[0].y > pt[1].y)
				{
					CvPoint temp = pt[1];
					pt[1] = pt[0];
					pt[0] = temp;
				}

				if(pt[2].y > pt[3].y)
				{
					CvPoint temp = pt[3];
					pt[3] = pt[2];
					pt[2] = temp;
				}

				if(abs(pt[0].y - pt[1].y) > 240)
				{
					sceneCorner[0] = pt[0];
					sceneCorner[1] = pt[1];
					sceneCorner[2] = pt[2];
					sceneCorner[3] = pt[3];

					for(int i = 0; i < 4; ++i)
						cvSeqPush(squares, (CvPoint*) cvGetSeqElem(result, i));

					break;
				}
			}
		}

		// take the next contour
		contours = contours->h_next;
	}

	// release all the temporary images
	cvReleaseImage(&gray);
	cvReleaseImage(&tgray);
	
	return squares;
}
Exemplo n.º 3
0
QPointF Body::fromLocal( const QPointF& p ) const {
    QTransform transform;
    transform.translate(position().x(),position().y());
    transform.rotateRadians(-angle());
    return transform.map(p);
}
Exemplo n.º 4
0
int shapeDetection(Mat src, int size) {

    // Do convex hull refinement
    vector<Point> hull = convexHullExtraction(src);

    ///*
    std::vector<Point> approx;
    Mat dst = src.clone();
    int shape = -1;

    // Approximate contour with accuracy proportional to the contour perimeter
    approxPolyDP(Mat(hull), approx, arcLength(Mat(hull), true)*0.3, true);

    //cout << approx.size() << endl;
    if (approx.size() == 4) {
        // Number of vertices of polygonal curve
        int vtc = approx.size();

        // Get the cosines of all corners
        std::vector<double> cos;
        for (int j = 2; j < vtc + 1; j++)
            cos.push_back(angle(approx[j%vtc], approx[j - 2], approx[j - 1]));

        // Sort ascending the cosine values
        std::sort(cos.begin(), cos.end());

        // Get the lowest and the highest cosine
        double mincos = cos.front();
        double maxcos = cos.back();

        // Use the degrees obtained above and the number of vertices
        // to determine the shape of the contour
        if (vtc == 4 && mincos >= -0.1 && maxcos <= 0.3) {
            setLabel(dst, "RECT", hull);
            shape = 4;
        }
        else if (vtc == 5 && mincos >= -0.34 && maxcos <= -0.27) {
            setLabel(dst, "PENTA", hull);
            shape = 5;
        }
        else if (vtc == 6 && mincos >= -0.55 && maxcos <= -0.45) {
            setLabel(dst, "HEXA", hull);
            shape = 6;
        }
    }
    else {
        // Detect and label circles
        double fillrate = FillingRate(src,size);// , hull);
        if (fillrate > 0.89) {
            setLabel(dst, "CIR", hull);
            shape = 0;
        }
        else if (fillrate < 0.78&&fillrate>0.7) {
            setLabel(dst, "HEART", hull);
            shape = 2;
        }
        else if (fillrate>0.78&&fillrate<0.89) {
            setLabel(dst, "FLOWER", hull);
            shape = 5;
        }
        else {
            setLabel(dst, "Rect", hull);
            shape = 4;
        }

    }
    if (recogintionShow) {
        //imshow("src", src);
        imshow("dst", dst);
        if (save)
            imwrite("Result.jpg", dst);
        waitKey(0);
    }
    return shape;
    //*/
}
Exemplo n.º 5
0
/*
* Фильтрация облачности
*/
int TFiltr::filtr_processing( struct TFiltrParams &p,
							  TBlk0_AVHRR &in_blk0,  short *in_data,
							  TBlk0_AVHRR &in2_blk0, short *in2_data,
							  TBlk0_AVHRR &in3_blk0, short *in3_data,
							  TBlk0_AVHRR &in4_blk0, short *in4_data,
							  TBlk0_AVHRR &in5_blk0, short *in5_data,
							  TBlk0_AVHRR &out_blk0, short *out_data,
							  int *filtr_stat ) {
	// Перевод параметров в статические члены класса
	TFiltr::p = p;
	TFiltr::in_blk0 = in_blk0;
	TFiltr::in2_blk0 = in2_blk0;
	TFiltr::in3_blk0 = in3_blk0;
	TFiltr::in4_blk0 = in4_blk0;
	TFiltr::in5_blk0 = in5_blk0;
	TFiltr::out_blk0 = out_blk0;
	TFiltr::in_data = in_data;
	TFiltr::in2_data = in2_data;
	TFiltr::in3_data = in3_data;
	TFiltr::in4_data = in4_data;
	TFiltr::in5_data = in5_data;
	TFiltr::out_data = out_data;
	TFiltr::cols = in_blk0.totalPixNum;
	TFiltr::scans = in_blk0.totalFrameNum;

	static const int step = 128;
	int length = scans * cols;

	// навигационная подсистема
	double julian_date;
	TStraightReferencer* r = navigationSystemInit( (TBlk0&)in_blk0, &julian_date );
	TAutoPtr<TStraightReferencer> a_t(r);

	for( int i = 0; i < length; i++ )
		out_data[i] = 0;

	for (int scan = 0; scan < scans; scan++) {
		int col1 = 0;
		int col2 = col1 + step;
		double ang1 = angle( scan, col1, *r, julian_date );
		double ang2 = angle( scan, col2, *r, julian_date );
		for (int j = 0; j < cols; j++) {
			// Определяем синус угла восхождения на Солнце
			double ang;
			if( j == col1 ) {
				ang = ang1;
			} else if ( j == col2 ) {
				ang = ang2;
			} else if ( j > col2 ) {
				col1 = col2;
				col2 = col1 + step;
				ang1 = ang2;
				ang2 = angle( scan, col2, *r, julian_date );
				ang =  ang1+(j-col1)*(ang2-ang1)/double(step);
			} else {
				ang = ang1+(j-col1)*(ang2-ang1)/double(step);
			}
			// синус угла восхождения на Солнце определен

			int ind = scan*cols + j;
			out_data[ind] = in_data[ind];
			if( in_data[ind] < 0 ) {
				out_data[ind] = in_data[ind];
				if( filtr_stat && in_data[ind] == multichLostValue ) {
					filtr_stat[MASK_MULTICH]++;
				}
			} else {
				//  маска, показывающая каким фильтрам удовлетворил
				//  текущий пиксель
				unsigned int mask_filtr = 0;

				//  Фильтрация по альбедо
				if (p.albedo_flag) {
					if( albedoTest( scan, j, ang ) ) {
						out_data[ind] = lostValue;
						mask_filtr = MASK_ALBEDO_FILTR;
					}
				}

				//  Фильтрация по температуре
				if (p.temp_flag) {
					if( tempTest( scan, j, ang ) ) {
						out_data[ind] = lostValue;
						mask_filtr |= MASK_TEMP_FILTR;
					}
				}

				//  Фильтрация по разности третьего - четвертого каналов
				if (p.day_delta34_flag || p.night_delta34_flag ) {
					if( delta34Test( scan, j, ang ) ) {
						out_data[ind] = lostValue;
						mask_filtr |= MASK_34_DELTA_FILTR;
					}
				}

				//  Фильтрация по разности третьего - пятого каналов
				if (p.day_delta35_flag || p.night_delta35_flag ) {
					if( delta35Test( scan, j, ang ) ) {
						out_data[ind] = lostValue;
						mask_filtr |= MASK_35_DELTA_FILTR;
					}
				}

				//  Фильтрация по разности эго - пятого каналов
				if (p.day_delta45_flag || p.night_delta45_flag ) {
					if( delta45Test( scan, j, ang ) ) {
						out_data[ind] = lostValue;
						mask_filtr |= MASK_45_DELTA_FILTR;
					}
				}

				//  Фильтрация по критерию пространственной неоднородности для температуры
				if (p.temp_uniformity_flag ) {
					if( scan > 0 && scan < scans && j > 0 && j < cols ) {
						if( tempUniformityTest( scan, j, ang ) ) {
							out_data[ind] = lostValue;
							mask_filtr |= MASK_TEMP_SMOOTH_FILTR;
						}
					}
				}

				if (p.albedo_uniformity_flag ) {
					if( scan > 0 && scan < scans && j > 0 && j < cols ) {
						if( albedoUniformityTest( scan, j, ang ) ) {
							out_data[ind] = lostValue;
							mask_filtr |= MASK_ALBEDO_SMOOTH_FILTR;
						}
					}
				}

				if( p.stat_flag && out_data[ind] == lostValue) {
					out_data[ind] = -mask_filtr-256;
				}

				if(filtr_stat )
					filtr_stat[mask_filtr]++;   // Для статистики
			}
		}
	}   // Конец большого цикла по всем пикселям

	if( p.cloud_border_flag ) {
		borderProcessing( p.cloud_border_win_size, p.max_filtered_percent, &(filtr_stat[MASK_BORDER_FILTR]) );
	}
	out_blk0.processLevel |= 4;
	return 0;
}
Exemplo n.º 6
0
/**
* TODO items for text:
* 1) Test multi-line text rendering
* 2) Accept color codes during text rendering in the form of \Cx (x is the index color)
* 3) Font selection
* For testing there is a lua script
*
* We can increase performance if we pre-calculate some values and cache them so that we
* don't have to keep calling text_extends and do some of the calculations
* also we shouldn't draw text smaller then XX pixels when rendered on screen.
*/
void LCVText::draw(LcPainter& painter, const LcDrawOptions &options, const lc::geo::Area& rect) const {
    bool modified = false;
    painter.font_size(height());
    painter.select_font_face("stick3.ttf");

    TextExtends te = painter.text_extends(text_value().c_str());
    double alignX = 0.0;
    double alignY = 0.0;

    //    double alignX, alignY;
    // The idea of height() * .2 is just a average basline offset. Don't this value to seriously,
    // we could get it from font exists but that sounds over exaggerating for the moment.
    switch (valign()) {
        case lc::TextConst::VAMiddle:
            alignX += 0.0;
            alignY += -height() / 2. + (height() * .2);
            break;

        case lc::TextConst::VABottom:
            alignX += 0.0;
            alignY += -height() + (height() * .2);
            break;

        case lc::TextConst::VABaseline:
            alignX += 0.0;
            alignY += 0.0;
            break;

        case lc::TextConst::VATop:
            alignX += 0.0;
            alignY += 0.0 + (height() * .2);
            break;

        default:
            break;
    }

    // Horizontal Align:
    switch (halign()) {
        case lc::TextConst::HALeft:
            alignX += - te.width;
            alignY += 0.;
            break;

        case lc::TextConst::HACenter:
            alignX += - te.width / 2.0;
            alignY += 0.;
            break;

        case lc::TextConst::HAMiddle:
            alignX += - te.width / 2.0;
            alignY += 0.;
            break;

        case lc::TextConst::HARight:
            alignX += 0.;
            alignY += 0.;
            break;

        default:
            break;
    }

    painter.save();
    painter.translate(insertion_point().x(), -insertion_point().y());
    painter.rotate(-angle());
    painter.translate(alignX, -alignY);
    painter.move_to(0., 0.);
    painter.text(text_value().c_str());
    painter.stroke();
    painter.restore();

    if (modified) {
        painter.restore();
    }

}
Exemplo n.º 7
0
void CCharacter::FireWeapon()
{
	if(m_ReloadTimer != 0)
		return;

	DoWeaponSwitch();
	vec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY));

	bool FullAuto = false;
	if(m_ActiveWeapon == WEAPON_GRENADE || m_ActiveWeapon == WEAPON_SHOTGUN || m_ActiveWeapon == WEAPON_LASER)
		FullAuto = true;


	// check if we gonna fire
	bool WillFire = false;
	if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses)
		WillFire = true;

	if(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_ActiveWeapon].m_Ammo)
		WillFire = true;

	if(!WillFire)
		return;

	// check for ammo
	if(!m_aWeapons[m_ActiveWeapon].m_Ammo)
	{
		// 125ms is a magical limit of how fast a human can click
		m_ReloadTimer = 125 * Server()->TickSpeed() / 1000;
		if(m_LastNoAmmoSound+Server()->TickSpeed() <= Server()->Tick())
		{
			GameServer()->CreateSound(m_Pos, SOUND_WEAPON_NOAMMO);
			m_LastNoAmmoSound = Server()->Tick();
		}
		return;
	}

	vec2 ProjStartPos = m_Pos+Direction*m_ProximityRadius*0.75f;

	switch(m_ActiveWeapon)
	{
		case WEAPON_HAMMER:
		{
			// reset objects Hit
			m_NumObjectsHit = 0;
			GameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE);

			CCharacter *apEnts[MAX_CLIENTS];
			int Hits = 0;
			int Num = GameServer()->m_World.FindEntities(ProjStartPos, m_ProximityRadius*0.5f, (CEntity**)apEnts,
														MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER);

			for (int i = 0; i < Num; ++i)
			{
				CCharacter *pTarget = apEnts[i];

				if ((pTarget == this) || GameServer()->Collision()->IntersectLine(ProjStartPos, pTarget->m_Pos, NULL, NULL))
					continue;

				// set his velocity to fast upward (for now)
				if(length(pTarget->m_Pos-ProjStartPos) > 0.0f)
					GameServer()->CreateHammerHit(pTarget->m_Pos-normalize(pTarget->m_Pos-ProjStartPos)*m_ProximityRadius*0.5f);
				else
					GameServer()->CreateHammerHit(ProjStartPos);

				vec2 Dir;
				if (length(pTarget->m_Pos - m_Pos) > 0.0f)
					Dir = normalize(pTarget->m_Pos - m_Pos);
				else
					Dir = vec2(0.f, -1.f);

				pTarget->TakeDamage(vec2(0.f, -1.f) + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage,
					m_pPlayer->GetCID(), m_ActiveWeapon);
				Hits++;
			}

			// if we Hit anything, we have to wait for the reload
			if(Hits)
				m_ReloadTimer = Server()->TickSpeed()/3;

		} break;

		case WEAPON_GUN:
		{
			CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GUN,
				m_pPlayer->GetCID(),
				ProjStartPos,
				Direction,
				(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime),
				g_pData->m_Weapons.m_Gun.m_pBase->m_Damage, false, 0, -1, WEAPON_GUN);

			// pack the Projectile and send it to the client Directly
			CNetObj_Projectile p;
			pProj->FillInfo(&p);

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(1);
			for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
				Msg.AddInt(((int *)&p)[i]);

			Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE);
		} break;

		case WEAPON_SHOTGUN:
		{
			int ShotSpread = 2;

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(ShotSpread*2+1);

			for(int i = -ShotSpread; i <= ShotSpread; ++i)
			{
				float Spreading[] = {-0.185f, -0.070f, 0, 0.070f, 0.185f};
				float a = angle(Direction);
				a += Spreading[i+2];
				float v = 1-(absolute(i)/(float)ShotSpread);
				float Speed = mix((float)GameServer()->Tuning()->m_ShotgunSpeeddiff, 1.0f, v);
				CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_SHOTGUN,
					m_pPlayer->GetCID(),
					ProjStartPos,
					vec2(cosf(a), sinf(a))*Speed,
					(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_ShotgunLifetime),
					g_pData->m_Weapons.m_Shotgun.m_pBase->m_Damage, false, 0, -1, WEAPON_SHOTGUN);

				// pack the Projectile and send it to the client Directly
				CNetObj_Projectile p;
				pProj->FillInfo(&p);

				for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
					Msg.AddInt(((int *)&p)[i]);
			}

			Server()->SendMsg(&Msg, 0,m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE);
		} break;

		case WEAPON_GRENADE:
		{
			CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GRENADE,
				m_pPlayer->GetCID(),
				ProjStartPos,
				Direction,
				(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime),
				g_pData->m_Weapons.m_Grenade.m_pBase->m_Damage, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE);

			// pack the Projectile and send it to the client Directly
			CNetObj_Projectile p;
			pProj->FillInfo(&p);

			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
			Msg.AddInt(1);
			for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
				Msg.AddInt(((int *)&p)[i]);
			Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());

			GameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE);
		} break;

		case WEAPON_LASER:
		{
			new CLaser(GameWorld(), m_Pos, Direction, GameServer()->Tuning()->m_LaserReach, m_pPlayer->GetCID());
			GameServer()->CreateSound(m_Pos, SOUND_LASER_FIRE);
		} break;

		case WEAPON_NINJA:
		{
			// reset Hit objects
			m_NumObjectsHit = 0;

			m_Ninja.m_ActivationDir = Direction;
			m_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * Server()->TickSpeed() / 1000;
			m_Ninja.m_OldVelAmount = length(m_Core.m_Vel);

			GameServer()->CreateSound(m_Pos, SOUND_NINJA_FIRE);
		} break;

	}

	m_AttackTick = Server()->Tick();

	if(m_aWeapons[m_ActiveWeapon].m_Ammo > 0) // -1 == unlimited
		m_aWeapons[m_ActiveWeapon].m_Ammo--;

	if(!m_ReloadTimer)
		m_ReloadTimer = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Firedelay * Server()->TickSpeed() / 1000;
}
Exemplo n.º 8
0
void IK_QJacobianSolver::ConstrainPoleVector(IK_QSegment *root, std::list<IK_QTask *>& tasks)
{
	// this function will be called before and after solving. calling it before
	// solving gives predictable solutions by rotating towards the solution,
	// and calling it afterwards ensures the solution is exact.

	if (!m_poleconstraint)
		return;
	
	// disable pole vector constraint in case of multiple position tasks
	std::list<IK_QTask *>::iterator task;
	int positiontasks = 0;

	for (task = tasks.begin(); task != tasks.end(); task++)
		if ((*task)->PositionTask())
			positiontasks++;
	
	if (positiontasks >= 2) {
		m_poleconstraint = false;
		return;
	}

	// get positions and rotations
	root->UpdateTransform(m_rootmatrix);

	const MT_Vector3 rootpos = root->GlobalStart();
	const MT_Vector3 endpos = m_poletip->GlobalEnd();
	const MT_Matrix3x3& rootbasis = root->GlobalTransform().getBasis();

	// construct "lookat" matrices (like gluLookAt), based on a direction and
	// an up vector, with the direction going from the root to the end effector
	// and the up vector going from the root to the pole constraint position.
	MT_Vector3 dir = normalize(endpos - rootpos);
	MT_Vector3 rootx = rootbasis.getColumn(0);
	MT_Vector3 rootz = rootbasis.getColumn(2);
	MT_Vector3 up = rootx * cos(m_poleangle) + rootz *sin(m_poleangle);

	// in post, don't rotate towards the goal but only correct the pole up
	MT_Vector3 poledir = (m_getpoleangle) ? dir : normalize(m_goal - rootpos);
	MT_Vector3 poleup = normalize(m_polegoal - rootpos);

	MT_Matrix3x3 mat, polemat;

	mat[0] = normalize(MT_cross(dir, up));
	mat[1] = MT_cross(mat[0], dir);
	mat[2] = -dir;

	polemat[0] = normalize(MT_cross(poledir, poleup));
	polemat[1] = MT_cross(polemat[0], poledir);
	polemat[2] = -poledir;

	if (m_getpoleangle) {
		// we compute the pole angle that to rotate towards the target
		m_poleangle = angle(mat[1], polemat[1]);

		if (rootz.dot(mat[1] * cos(m_poleangle) + mat[0] * sin(m_poleangle)) > 0.0)
			m_poleangle = -m_poleangle;

		// solve again, with the pole angle we just computed
		m_getpoleangle = false;
		ConstrainPoleVector(root, tasks);
	}
	else {
		// now we set as root matrix the difference between the current and
		// desired rotation based on the pole vector constraint. we use
		// transpose instead of inverse because we have orthogonal matrices
		// anyway, and in case of a singular matrix we don't get NaN's.
		MT_Transform trans(MT_Point3(0, 0, 0), polemat.transposed() * mat);
		m_rootmatrix = trans * m_rootmatrix;
	}
}
Exemplo n.º 9
0
int find_boundary(int n, double *x, double *y, double r, double (*r_function)(double, double), int n_contour,
                  int *contour)
{
  /*
   * Find the boundary of the `n` 2-dimensional points located at `x` and `y` using a ballpivot approach.
   * The indices of the contour points are stored in the `contour` array. There are several possibilities
   * to provide the ball radius used in the ballpivot algorithm:
   * - As a callback function (`r_function`) that returns the ball radius for the current position.
   * - As a constant ball radius `r`
   * - Automatically calculated / estimated from the data points
   *
   * If `r_function` is different from NULL it will be used to calculate the ball radius for each position.
   * In that case the parameter `r` is only used to set the cell size of the internal grid data structure storing
   * the points if it has a value greater 0.
   * If `r_function` is NULL and `r` is greater 0 it is used as a constant ball radius and determines the cell
   * size of the internal grid. Otherwise a (constant) ball radius is automatically calculated as 1.2 times the
   * the largest distance from a point to its nearest neighbor.
   *
   * If the algorithm is successful it returns the number of contour points that were written in `contour`.
   * Otherwise the return value is less than 0 indicating a too small (`FIND_BOUNDARY_BALL_TOO_SMALL`) or too
   * large (`FIND_BOUNDARY_BALL_TOO_LARGE`) ball radius, an invalid number of points (`FIND_BOUNDARY_INVALID_POINTS`)
   * or that the number of contour points exceed the available memory in `contour` given by `n_contour`.
   */
  double2 bb_bottom_left, bb_top_right;
  double2 *points;
  double cell_size;
  neighbor_point_list data;
  grid *grid_ptr;
  int i, start_point, current_index;
  int num_contour_points = 0;

  if (n < 2)
    {
      return FIND_BOUNDARY_INVALID_POINTS;
    }

  if (n_contour <= 1)
    {
      return FIND_BOUNDARY_MEMORY_EXCEEDED;
    }

  points = malloc(n * sizeof(double2));
  assert(points);
  for (i = 0; i < n; i++)
    {
      points[i].x = x[i];
      points[i].y = y[i];
      points[i].index = i;
    }
  calculate_bounding_box(n, points, &bb_bottom_left, &bb_top_right);
  if (r <= 0)
    {
      /* If no radius is given, estimate the cell size as 1/10 of the average of width and height of the data's
       * bounding box. */
      cell_size = ((bb_top_right.x - bb_bottom_left.x) + (bb_top_right.y - bb_bottom_left.y)) / 2. / 10.;
    }
  else
    {
      /* Scale radius by 1.1 to make sure that only direct neighbor cells have to be checked. */
      cell_size = r * 1.1;
    }
  grid_ptr = grid_create(n, points, cell_size);

  /* Start from the point closest to the bottom left corner of the bounding box*/
  start_point = grid_find_nearest_neighbor(grid_ptr, grid_ptr->bounding_box[0], -1, cell_size).index;
  contour[num_contour_points] = start_point;

  if (r <= 0 && r_function == NULL)
    { /* No radius given, calculate from data */
      for (i = 0; i < n; i++)
        {
          double nearest_neighbor = grid_find_nearest_neighbor(grid_ptr, grid_get_elem(grid_ptr, i), i, cell_size).x;
          if (nearest_neighbor > r)
            {
              /* Calculate r as the largest distance from one point to its nearest neighbor. This makes sure, that
               * at least one neighbor can be reached from each point. */
              r = nearest_neighbor;
            }
        }
      r = sqrt(r);
      r *= 1.2;
    }

  /* Initialize list structure that stores the possible neighbors in each step. */
  data.capacity = 10;
  data.point_list = malloc(data.capacity * sizeof(int));
  assert(data.point_list);

  current_index = start_point;
  while (num_contour_points == 0 || contour[num_contour_points] != contour[0])
    {
      double2 current_point;
      data.current = current_index;
      data.size = 0;
      data.num_points_reachable = 0;
      current_point = grid_get_elem(grid_ptr, current_index);

      if (num_contour_points >= n_contour)
        {
          return FIND_BOUNDARY_MEMORY_EXCEEDED;
        }

      if (r_function)
        {
          r = r_function(current_point.x, current_point.y);
          if (r <= 0)
            {
              return FIND_BOUNDARY_BALL_TOO_SMALL;
            }
        }

      /* Find the possible neighbors of `current_point` using the grid structure. */
      grid_apply_function(grid_ptr, current_point, 2 * r, grid_cb_find_possible_neighbors, (void *)&data, 1,
                          &current_index);
      if (data.size == 1)
        { /* Only one neighbor is possible */
          current_index = data.point_list[0];
          contour[++num_contour_points] = current_index;
        }
      else if (data.size > 1)
        { /* More than one point is a possible neighbor */
          int best_neighbor = 0;
          double best_angle = 0;
          int oldest = num_contour_points + 1;
          int unvisited_points = 0;

          /* If at least one possible neighbor is not included in the contour until now use the (unvisited) one
           * with the smallest angle. Otherwise use the one that was visited first to avoid (infinite) loops. */
          for (i = 0; i < (int)data.size; i++)
            {
              int contour_point_index = in_contour(data.point_list[i], num_contour_points, contour);
              if (contour_point_index < 0)
                {
                  double2 previous_contour_point = grid_get_elem(grid_ptr, contour[num_contour_points - 1]);
                  double2 possible_contour_point = grid_get_elem(grid_ptr, data.point_list[i]);
                  double a = angle(current_point, previous_contour_point, possible_contour_point);
                  if (a > best_angle)
                    {
                      best_angle = a;
                      best_neighbor = i;
                    }
                  unvisited_points++;
                }
              else if (!unvisited_points)
                {
                  if (contour_point_index < oldest)
                    {
                      oldest = contour_point_index;
                      best_neighbor = i;
                    }
                }
            }
          current_index = data.point_list[best_neighbor];
          contour[++num_contour_points] = current_index;
        }
      else
        { /* No possible neighbor is found. */
          if (data.num_points_reachable == 0)
            { /* No point was reachable -> ball too small */
              return FIND_BOUNDARY_BALL_TOO_SMALL;
            }
          else
            { /* No reachable point resulted in an empty ball -> ball too large */
              return FIND_BOUNDARY_BALL_TOO_LARGE;
            }
        }
    }
  /* The grid data structure reorders the points. Restore original indices of the contour points. */
  for (i = 0; i < num_contour_points; i++)
    {
      contour[i] = points[contour[i]].index;
    }

  free(points);
  free(data.point_list);
  grid_destroy(grid_ptr);

  return num_contour_points;
}
Exemplo n.º 10
0
//计算球面距离,r为球半径
inline double sphere_dist(double r,double lng1,double lat1,double lng2,double lat2)
{
	return r*angle(lng1,lat1,lng2,lat2);
}
Exemplo n.º 11
0
std::string MeasurementItem::angleStr() const {
  std::stringstream buffer;
  buffer << angle();
  return buffer.str();
}
Exemplo n.º 12
0
RatioPosition		RatioPosition::operator*(const Angle& a) const
{
  return (RatioPosition(a + angle(), distance()));
}
Exemplo n.º 13
0
//find rectangles on image
std::vector<Rect> findRect( const cv::Mat& image )
{
    std::vector<Rect> rect;
    rect.clear();
    cv::Mat gray = image.clone();
    std::vector<std::vector<cv::Point> > contours;

    //SLOWER
    //erote the image to fill holes 
    /*int erosion_size = 1;
    cv::Mat element = getStructuringElement( cv::MORPH_RECT,
                                       cv::Size( 2*erosion_size + 1, 2*erosion_size+1 ),
                                       cv::Point( -1, -1 ) );
    cv::erode(gray, gray, element);
    */
    /*
    cv::erode(gray, gray, cv::Mat(), cv::Point(-1,-1),1); //standard call
    //cv::dilate(gray, gray, cv::Mat(), cv::Point(-1,-1),2); //standard call
    std::string file = "/mnt/sdcard/Pictures/MyCameraApp/red_trans.jpeg";
    cv::imwrite(file,gray);
    */
    

    // find contours and store them all as a list
    cv::findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

    std::vector<cv::Point> approx;     
    // test each contour
    for( size_t i = 0; i < contours.size(); i++ )
    {
        // approximate contour with accuracy proportional
        // to the contour perimeter
        cv::approxPolyDP(cv::Mat(contours[i]), approx, arcLength(cv::Mat(contours[i]), true)*0.02, true);
                
        // square contours should have 4 vertices after approximation
        // relatively large area (to filter out noisy contours)
        // and be convex.
        // Note: absolute value of an area is used because
        // area may be positive or negative - in accordance with the
        // contour orientation
        if( approx.size() == 4 && fabs(cv::contourArea(cv::Mat(approx))) > MIN_RECT_SIZE &&
            cv::isContourConvex(cv::Mat(approx)) )
       {
            double maxCosine = 0;

            for( int j = 2; j < 5; j++ ) {
                // find the maximum cosine of the angle between joint edges
                double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                maxCosine = MAX(maxCosine, cosine);
            }

            // if cosines of all angles are small
            // (all angles are ~90 degree) then store quandrange
            // vertices to resultant sequence
            if( maxCosine < 0.3 ) {
                rect.push_back(extractRectData(approx));
            }
         }
    }

    return rect;
}
Exemplo n.º 14
0
bool EditTSCtrl::processCameraQuery(CameraQuery * query)
{
   if(mDisplayType == DisplayTypePerspective)
   {
      query->ortho = false;
   }
   else
   {
      query->ortho = true;
   }

   if (getCameraTransform(&query->cameraMatrix))
   {
      query->farPlane = gClientSceneGraph->getVisibleDistance() * smVisibleDistanceScale;
      query->nearPlane = gClientSceneGraph->getNearClip();
      query->fov = mDegToRad(smCamFOV);

      if(query->ortho)
      {
         MatrixF camRot(true);
         const F32 camBuffer = 1.0f;
         Point3F camPos = query->cameraMatrix.getPosition();

         F32 isocamplanedist = 0.0f;
         if(mDisplayType == DisplayTypeIsometric)
         {
            const RectI& vp = GFX->getViewport();
            isocamplanedist = 0.25 * vp.extent.y * mSin(mIsoCamAngle);
         }

         // Calculate the scene bounds
         Box3F sceneBounds;
         computeSceneBounds(sceneBounds);

         if(!sceneBounds.isValidBox())
         {
            sceneBounds.maxExtents = camPos + smMinSceneBounds;
            sceneBounds.minExtents = camPos - smMinSceneBounds;
         }
         else
         {
            query->farPlane = getMax(smMinSceneBounds.x * 2.0f, (sceneBounds.maxExtents - sceneBounds.minExtents).len() + camBuffer * 2.0f + isocamplanedist);
         }

         mRawCamPos = camPos;
         camPos += mOrthoCamTrans;

         switch(mDisplayType)
         {
            case DisplayTypeTop:
               camRot.setColumn(0, Point3F(1.0, 0.0,  0.0));
               camRot.setColumn(1, Point3F(0.0, 0.0, -1.0));
               camRot.setColumn(2, Point3F(0.0, 1.0,  0.0));
               camPos.z = getMax(camPos.z + smMinSceneBounds.z, sceneBounds.maxExtents.z + camBuffer);
               break;

            case DisplayTypeBottom:
               camRot.setColumn(0, Point3F(1.0,  0.0,  0.0));
               camRot.setColumn(1, Point3F(0.0,  0.0,  1.0));
               camRot.setColumn(2, Point3F(0.0, -1.0,  0.0));
               camPos.z = getMin(camPos.z - smMinSceneBounds.z, sceneBounds.minExtents.z - camBuffer);
               break;

            case DisplayTypeFront:
               camRot.setColumn(0, Point3F(-1.0,  0.0,  0.0));
               camRot.setColumn(1, Point3F( 0.0, -1.0,  0.0));
               camRot.setColumn(2, Point3F( 0.0,  0.0,  1.0));
               camPos.y = getMax(camPos.y + smMinSceneBounds.y, sceneBounds.maxExtents.y + camBuffer);
               break;

            case DisplayTypeBack:
               camRot.setColumn(0, Point3F(1.0,  0.0,  0.0));
               camRot.setColumn(1, Point3F(0.0,  1.0,  0.0));
               camRot.setColumn(2, Point3F(0.0,  0.0,  1.0));
               camPos.y = getMin(camPos.y - smMinSceneBounds.y, sceneBounds.minExtents.y - camBuffer);
               break;

            case DisplayTypeLeft:
               camRot.setColumn(0, Point3F( 0.0, -1.0,  0.0));
               camRot.setColumn(1, Point3F( 1.0,  0.0,  0.0));
               camRot.setColumn(2, Point3F( 0.0,  0.0,  1.0));
               camPos.x = getMin(camPos.x - smMinSceneBounds.x, sceneBounds.minExtents.x - camBuffer);
               break;

            case DisplayTypeRight:
               camRot.setColumn(0, Point3F( 0.0,  1.0,  0.0));
               camRot.setColumn(1, Point3F(-1.0,  0.0,  0.0));
               camRot.setColumn(2, Point3F( 0.0,  0.0,  1.0));
               camPos.x = getMax(camPos.x + smMinSceneBounds.x, sceneBounds.maxExtents.x + camBuffer);
               break;

            case DisplayTypeIsometric:
               camPos.z = sceneBounds.maxExtents.z + camBuffer + isocamplanedist;
               MatrixF angle(EulerF(mIsoCamAngle, 0, 0));
               MatrixF rot(mIsoCamRot);
               camRot.mul(rot, angle);
               break;
         }

         query->cameraMatrix = camRot;
         query->cameraMatrix.setPosition(camPos);
         query->fov = mOrthoFOV;
      }

      smCamMatrix = query->cameraMatrix;
      smCamMatrix.getColumn(3,&smCamPos);
      smCamOrtho = query->ortho;
      smCamNearPlane = query->nearPlane;

      return true;
   }
   return false;
}
Exemplo n.º 15
0
// returns sequence of squares detected on the image.
// the sequence is stored in the specified memory storage
CvSeq* findSquares4( IplImage* img, CvMemStorage* storage )
{
    CvSeq* contours;
    int i, c, l, N = 11;
	
    CvSize sz = cvSize( img->width & -2, img->height & -2 );
    IplImage* timg = cvCloneImage( img ); // make a copy of input image
    IplImage* gray = cvCreateImage( sz, 8, 1 ); 
    IplImage* pyr = cvCreateImage( cvSize(sz.width/2, sz.height/2), 8, 3 );
    IplImage* tgray;
    CvSeq* result;
    double s, t;
    // create empty sequence that will contain points -
    // 4 points per square (the square's vertices)
    CvSeq* squares = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPoint), storage );
    
    // select the maximum ROI in the image
    // with the width and height divisible by 2
    cvSetImageROI( timg, cvRect( 0, 0, sz.width, sz.height ));
    
    // down-scale and upscale the image to filter out the noise
    cvPyrDown( timg, pyr, 7 );
    cvPyrUp( pyr, timg, 7 );
    tgray = cvCreateImage( sz, 8, 1 );
    
    // find squares in every color plane of the image
    for( c = 0; c < 3; c++ )
    {
        // extract the c-th color plane
        cvSetImageCOI( timg, c+1 );
        cvCopy( timg, tgray, 0 );
        
        // try several threshold levels
        for( l = 0; l < N; l++ )
        {
            // hack: use Canny instead of zero threshold level.
            // Canny helps to catch squares with gradient shading   
            if( l == 0 )
            {
                // apply Canny. Take the upper threshold from slider
                // and set the lower to 0 (which forces edges merging) 
                cvCanny( tgray, gray, 0, thresh, 5 );
                // dilate canny output to remove potential
                // holes between edge segments 
                cvDilate( gray, gray, 0, 1 );
            }
            else
            {
                // apply threshold if l!=0:
                //     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
                cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
            }
            
            // find contours and store them all as a list
            cvFindContours( gray, storage, &contours, sizeof(CvContour),
                CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );
            
            // test each contour
            while( contours )
            {
                // approximate contour with accuracy proportional
                // to the contour perimeter
                result = cvApproxPoly( contours, sizeof(CvContour), storage,
                    CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );
                // square contours should have 4 vertices after approximation
                // relatively large area (to filter out noisy contours)
                // and be convex.
                // Note: absolute value of an area is used because
                // area may be positive or negative - in accordance with the
                // contour orientation
                if( result->total == 4 &&
                    fabs(cvContourArea(result,CV_WHOLE_SEQ)) > 1000 &&
                    cvCheckContourConvexity(result) )
                {
                    s = 0;
                    
                    for( i = 0; i < 5; i++ )
                    {
                        // find minimum angle between joint
                        // edges (maximum of cosine)
                        if( i >= 2 )
                        {
                            t = fabs(angle(
                            (CvPoint*)cvGetSeqElem( result, i ),
                            (CvPoint*)cvGetSeqElem( result, i-2 ),
                            (CvPoint*)cvGetSeqElem( result, i-1 )));
                            s = s > t ? s : t;
                        }
                    }
                    
                    // if cosines of all angles are small
                    // (all angles are ~90 degree) then write quandrange
                    // vertices to resultant sequence 
					if( s < 0.3 ){
						
						CvPoint *pt1 = (CvPoint*)cvGetSeqElem( result, 0 );
						CvPoint *pt2 = (CvPoint*)cvGetSeqElem( result, 1 );
						CvPoint *pt3 = (CvPoint*)cvGetSeqElem( result, 2 );
						CvPoint *pt4 = (CvPoint*)cvGetSeqElem( result, 3 );
						CvSeqReader reader;
						cvStartReadSeq( squares, &reader, 0 );
						CvPoint ptM[4];
						if (!squares->total)
						{	for( i = 0; i < 4; i++ )
								cvSeqPush( squares, (CvPoint*)cvGetSeqElem( result, i ));
						}
						else{
							// search if there are already similar square with POINTS_NEAR of tollerance
							int iNSquare = squares->total;
							bool bFound=false;
							for(i = 0; i < iNSquare && !bFound; i += 4)
							{
								// read 4 vertices
								CV_READ_SEQ_ELEM( ptM[0], reader );
								CV_READ_SEQ_ELEM( ptM[1], reader );
								CV_READ_SEQ_ELEM( ptM[2], reader );
								CV_READ_SEQ_ELEM( ptM[3], reader );
								if (abs(pt1->x-ptM[0].x)<POINTS_NEAR && abs(pt1->y-ptM[0].y)<POINTS_NEAR &&
									abs(pt2->x-ptM[1].x)<POINTS_NEAR && abs(pt2->y-ptM[1].y)<POINTS_NEAR &&
									abs(pt3->x-ptM[2].x)<POINTS_NEAR && abs(pt3->y-ptM[2].y)<POINTS_NEAR &&
									abs(pt4->x-ptM[3].x)<POINTS_NEAR && abs(pt4->y-ptM[3].y)<POINTS_NEAR)
								{	bFound=true;
								}
							}
							if (!bFound)
							{	cvSeqPush( squares, pt1);
								cvSeqPush( squares, pt2);
								cvSeqPush( squares, pt3);
								cvSeqPush( squares, pt4);
							}
						}
					}
                }
                
                // take the next contour
                contours = contours->h_next;
            }
        }
    }
    
    // release all the temporary images
    cvReleaseImage( &gray );
    cvReleaseImage( &pyr );
    cvReleaseImage( &tgray );
    cvReleaseImage( &timg );
	
    return squares;
}
void Structure::prepare_near_conductors()
{
  Node *n;
  conductor *s1, *s2, *chosen;
  int side, nep_tmp;
  double stretch;
  double h, additional_stretch;
  int sign1, sign2;
  
  for (n=list_defined_nodes.initialize(); n!=NULL;
       n=list_defined_nodes.iterate() )
    {
      List <conductor> *list_conductors_node_ptr;
      list_conductors_node_ptr = n->get_list_node_conductors_ptr();
      
      // operations necessary to this node
      if (list_conductors_node_ptr->size() > 1) {
	//test angle
	s1 = list_conductors_node_ptr->initialize();
	for (s2=list_conductors_node_ptr->iterate(); s2!=NULL;
	     s2=list_conductors_node_ptr->iterate())
	  {
	    //if ((paral((s1->vuw()),(s2->vuw())) +
	    //	 paral((s1->vuw()),(s2->vul())) +
	    // paral((s1->vuw()),(s2->vuh())) ) < 2)
	    //{
	    //fprintf (stderr, "Warning: Segments %s and %s share a common "
	    //	 "node not having a right\n\t\tangle between them.\n",
	    //	 s1->get_name(), s2->get_name());
	    //}
	  }
	
	
	// only 2 segments in the same direction
	s1 = list_conductors_node_ptr->initialize();
	s2 = list_conductors_node_ptr->iterate();
	if ((list_conductors_node_ptr->size() == 2) &&
	    paral(s1->vul(), s2->vul()) )
	  {
	    if (n==s1->node(1))
	      s1->set_nep1 (1);
	    else
	      s1->set_nep2 (1);
	    if (n==s2->node(1))
	      s2->set_nep1 (1);
	    else
	      s2->set_nep2 (1);
	  }
	
	// other cases
	else
	  {
	    // choose chosen
	    for (chosen=s1=list_conductors_node_ptr->initialize();
		 s1!=NULL;
		 s1=list_conductors_node_ptr->iterate() )
	      if (((s1->width()) * (s1->height())) >
		  ((chosen->width()) * (chosen->height()))) 
		chosen=s1;
	    
	    // list will contain only the non-chosen conductors
	    list_conductors_node_ptr->delete_element(chosen);
	    
	    // calculate stretch for chosen
	    stretch = 0;
	    nep_tmp = 0;
	    for (s1=list_conductors_node_ptr->initialize(); s1!=NULL;
		 s1=list_conductors_node_ptr->iterate() )
	      {
		if (paral(s1->vuw(), chosen->vul()))
		  if (((s1->width())/2) > stretch)
		    stretch = s1->width()/2;
		if (paral(s1->vuh(),chosen->vul()))
		  if (((s1->height())/2) > stretch)
		    stretch = s1->height()/2;
		if (paral(s1->vul(),chosen->vul()))
		  nep_tmp = 1;
	      }
	    if (n==chosen->node(1)) side = 1;
	    else side = 2;
	    
	    chosen->set_stretch (stretch, side);
	    if (n==chosen->node(1))
		chosen->set_nep1 (nep_tmp);
	    else
	      chosen->set_nep2 (nep_tmp);
	    
	    // operations on non-chosen conductors (will have negative stretch)
	    for (s1=list_conductors_node_ptr->initialize(); s1!=NULL;
		 s1=list_conductors_node_ptr->iterate() )
	      {
		if (n==s1->node(1))
		  side = 1;
		else
		  side = 2;
		
		if (paral(chosen->vuw(),s1->vul()))
		  s1->set_stretch (-(chosen->width())/2, side);
		else if (paral(chosen->vuh(), s1->vul()))
		  s1->set_stretch (-(chosen->height())/2, side);
		else if (paral (chosen->vul(), s1->vul()))
		  s1->set_stretch (-stretch, side);
		else
		  {
		    // Non-usual angle (different than 90 or 180 degrees).
		    // In this case, chosen is not stretch; there should be only one
		    // conductor to the same node; that other conductor will have
		    // a negative stretch of w_chosen/2*cos(angle between conds - PI/2)
		    if (list_conductors_node_ptr->size() > 2)
		      {
			printf ("Error: There should be only two conductors connected"
				" to node %s.\n", n->name_node());
			exit(-1);
		      }
		    // chosen is not stretch in this case
		      chosen->set_stretch (0, side);
		      if (n==chosen->node(1))
			chosen->set_nep1 (1);
		      else
			chosen->set_nep2 (1);
		      // fprintf (stderr, "Angle: %g\n", 180.0/PI*
		      //((chosen->get_vul()).get_angle_with(s1->get_vul())));
		      
		      
		      if (paral (chosen->vuh(), s1->vuh()))
			{
			  if (angle(s1->vul(), s2->vul()) > PI/2)
			    h =
			      cos((angle(chosen->vul(), s1->vul()))-PI/2)*
			      chosen->width() / 2;
			  else
			    {
			      h =
				sin(angle(chosen->vul(), s1->vul()))*
				chosen->width() / 2;
			      h = h + s1->width()/2 /
				tan (angle(chosen->vul(), s1->vul()));
			    }
			  if (fabs(h) > s1->length())
			    {
			      printf ("Errare humanum est: Structure::prepare_near_cond"
				      "uctors() - segment %s shortened %g of its length "
				      "(angle = %g).\n",
				      s1->get_name(), s1->length()/h, 180.0/PI*
				      (angle(chosen->vul(), s1->vul())));
			      exit(-1);
			    }
			  s1->set_stretch ((-h), side);
			}
		      
		      else if (paral(chosen->vuw(), s1->vuw()))
			{
			  if (angle(s1->vul(), s2->vul()) > PI/2)
			    h =
			      cos((angle(chosen->vul(), s1->vul()))-PI/2)*
			      chosen->height() / 2;
			  else
			    {
			      h =
				sin(angle (chosen->vul(), s1->vul()))*
				chosen->height() / 2;
			      h = h + s1->height()/2 /
				tan (angle(chosen->vul(), s1->vul()));
			    }
			  if (fabs(h) > s1->length())
			    {
			      printf ("Errare humanum est: Structure::prepare_near_cond"
				      "uctors() - segment %s shortened %g (angle = %g).\n",
				      s1->get_name(), s1->length()/h, 180.0/PI*
				      (angle(chosen->vul(), s1->vul())));
			      exit(-1);
			    }
			  s1->set_stretch ((-h), side);
			}
		      
		      else
			{
			  printf ("\t\tNon-usual angle between two conductors - length "
				  "directions have two be on the same plane.\n");
			  exit(-1);
			}
		      if (h!=0)
			fprintf (stderr, "\t\tSegment %s shortened 1/%4g of its "
                       "length (in terms of panels).\n",
				 s1->get_name(), s1->length()/h);
		    }
		  
		  if (n==s1->node(1))
		    s1->set_nep1 (1);
		  else
		    s1->set_nep2 (1);
		}
	    }
	}
  }
  
}
double orientedAngle(const Point2D & p0, const Point2D & p1, const Point2D & p2) {
    double unsignedAngle = angle(vector2D(p0, p1), vector2D(p0, p2));
    double area = doubleSignedTriangleArea(p0, p1, p2);

    return (area < 0) ? -unsignedAngle: unsignedAngle;
}
Exemplo n.º 18
0
/* draw an angle from the current point to b and then to c,
 * with a rounded corner of the given radius.
 */
void
KeyboardLayoutWidget::roundedCorner (QPainterPath& path,
        QPointF b, QPointF c, double radius)
{
    /* we may have 5 point here
     * a is the current point
     * c is the end point
     * and b is the corner
     * we will have a rounded corner with radious (maybe adjust by a,b,c position)
     *
     * a1 is on a-b, and c1 is on b-c
     */

    QPointF a = path.currentPosition();

    //qDebug() << "current" << a << b << c;

    /* make sure radius is not too large */
    double dist1 = distance (a, b);
    double dist2 = distance (b, c);

    //qDebug() << "dist" << dist1 << dist2 << radius;

    radius = qMin (radius, qMin (dist1, dist2));

    QPointF ba = a - b;
    QPointF bc = c - b;
    QVector2D na(ba);
    QVector2D nc(bc);
    na.normalize();
    nc.normalize();

    qreal cosine = QVector2D::dotProduct(na, nc);
    qreal halfcosine = qSqrt((1 + cosine) / 2);
    qreal halfsine = qSqrt( 1- halfcosine * halfcosine);
    qreal halftan = halfsine / halfcosine;
    QPointF a1 = b + na.toPointF() * (radius / halftan);
    QPointF c1 = b + nc.toPointF() * (radius / halftan);

    QVector2D n = na + nc;
    n.normalize();
    QPointF ctr = b + n.toPointF() * radius / halfsine;
    QRectF arcRect(ctr.x() - radius, ctr.y() - radius, 2 * radius, 2 * radius);

    qreal phiA, phiC;
    //qDebug() << c1 << ctr << a1;
    QVector2D ctra = QVector2D(a1 - ctr);
    QVector2D ctrc = QVector2D(c1 - ctr);
    ctra.normalize();
    ctrc.normalize();
    phiA = angle(ctra);
    phiC = angle(ctrc);

    qreal delta = phiC - phiA;
    while (delta > 0)
        delta -= 360;

    while (delta < -360)
        delta += 360;

    if (delta <- 180)
        delta += 360;

    //qDebug() << arcRect << ctra << ctrc << ctr << "degree" << phiA << phiC;

    path.lineTo(a1);
    path.arcTo(arcRect, phiA, delta);
    path.lineTo(c1);
    path.lineTo(c);
}
Exemplo n.º 19
0
void rv2coe
     (
       double r[3], double v[3], double mu,
       double& p, double& a, double& ecc, double& incl, double& omega, double& argp,
       double& nu, double& m, double& arglat, double& truelon, double& lonper
     )
     {
       double undefined, small, hbar[3], nbar[3], magr, magv, magn, ebar[3], sme,
              rdotv, infinite, temp, c1, hk, twopi, magh, halfpi, e;

       int i;
       char typeorbit[3];

     twopi  = 2.0 * pi;
     halfpi = 0.5 * pi;
     small  = 0.00000001;
     undefined = 999999.1;
     infinite  = 999999.9;

     // -------------------------  implementation   -----------------
     magr = mag( r );
     magv = mag( v );

     // ------------------  find h n and e vectors   ----------------
     cross( r,v, hbar );
     magh = mag( hbar );
     if ( magh > small )
       {
         nbar[0]= -hbar[1];
         nbar[1]=  hbar[0];
         nbar[2]=   0.0;
         magn = mag( nbar );
         c1 = magv*magv - mu /magr;
         rdotv = dot( r,v );
         for (i= 0; i <= 2; i++)
             ebar[i]= (c1*r[i] - rdotv*v[i])/mu;
         ecc = mag( ebar );

         // ------------  find a e and semi-latus rectum   ----------
         sme= ( magv*magv*0.5  ) - ( mu /magr );
         if ( fabs( sme ) > small )
             a= -mu  / (2.0 *sme);
           else
             a= infinite;
         p = magh*magh/mu;

         // -----------------  find inclination   -------------------
         hk= hbar[2]/magh;
         incl= acos( hk );

         // --------  determine type of orbit for later use  --------
         // ------ elliptical, parabolic, hyperbolic inclined -------
         strcpy(typeorbit,"ei");
         if ( ecc < small )
           {
             // ----------------  circular equatorial ---------------
             if  ((incl<small) | (fabs(incl-pi)<small))
                 strcpy(typeorbit,"ce");
               else
                 // --------------  circular inclined ---------------
                 strcpy(typeorbit,"ci");
           }
           else
           {
             // - elliptical, parabolic, hyperbolic equatorial --
             if  ((incl<small) | (fabs(incl-pi)<small))
                 strcpy(typeorbit,"ee");
           }

         // ----------  find longitude of ascending node ------------
         if ( magn > small )
           {
             temp= nbar[0] / magn;
             if ( fabs(temp) > 1.0  )
                 temp= sgn(temp);
             omega= acos( temp );
             if ( nbar[1] < 0.0  )
                 omega= twopi - omega;
           }
           else
             omega= undefined;

         // ---------------- find argument of perigee ---------------
         if ( strcmp(typeorbit,"ei") == 0 )
           {
             argp = angle( nbar,ebar);
             if ( ebar[2] < 0.0  )
                 argp= twopi - argp;
           }
           else
             argp= undefined;

         // ------------  find true anomaly at epoch    -------------
         if ( typeorbit[0] == 'e' )
           {
             nu =  angle( ebar,r);
             if ( rdotv < 0.0  )
                 nu= twopi - nu;
           }
           else
             nu= undefined;

         // ----  find argument of latitude - circular inclined -----
         if ( strcmp(typeorbit,"ci") == 0 )
           {
             arglat = angle( nbar,r );
             if ( r[2] < 0.0  )
                 arglat= twopi - arglat;
             m = arglat;
           }
           else
             arglat= undefined;

         // -- find longitude of perigee - elliptical equatorial ----
         if  (( ecc>small ) && (strcmp(typeorbit,"ee") == 0))
           {
             temp= ebar[0]/ecc;
             if ( fabs(temp) > 1.0  )
                 temp= sgn(temp);
             lonper= acos( temp );
             if ( ebar[1] < 0.0  )
                 lonper= twopi - lonper;
             if ( incl > halfpi )
                 lonper= twopi - lonper;
           }
           else
             lonper= undefined;

         // -------- find true longitude - circular equatorial ------
         if  (( magr>small ) && ( strcmp(typeorbit,"ce") == 0 ))
           {
             temp= r[0]/magr;
             if ( fabs(temp) > 1.0  )
                 temp= sgn(temp);
             truelon= acos( temp );
             if ( r[1] < 0.0  )
                 truelon= twopi - truelon;
             if ( incl > halfpi )
                 truelon= twopi - truelon;
             m = truelon;
           }
           else
             truelon= undefined;

         // ------------ find mean anomaly for all orbits -----------
         if ( typeorbit[0] == 'e' )
             newtonnu(ecc,nu,  e, m);
     }
      else
     {
        p    = undefined;
        a    = undefined;
        ecc  = undefined;
        incl = undefined;
        omega= undefined;
        argp = undefined;
        nu   = undefined;
        m    = undefined;
        arglat = undefined;
        truelon= undefined;
        lonper = undefined;
     }
   }  // end rv2coe
Exemplo n.º 20
0
void Car::apply_physics(Map &map)
{
	if(m_physicTimer.ticked())
	{
		//float currentSpeed = norm(m_speedVector);

		sf::Transformable::rotate(m_rotation/**(currentSpeed / m_maxSpeed)*/);
		float rotation = getRotation();
		float accelFactor = m_physicTimer.getFullWaitedDuration().asSeconds();

		//calculate the new speed with the acceleration
		m_speed += accelFactor*m_acceleration;
		if(m_speed > m_maxSpeed)
		{
			m_speed = m_maxSpeed;
			//std::cout<< "max attained\n";
		}
		else if(m_speed < -m_maxSpeed)
		{
			m_speed = -m_maxSpeed;
			//std::cout<< "min attained\n";
		}

		sf::Vector2f posOffset(
		m_speed*accelFactor*std::cos(rotation*M_PI/180)
		, m_speed*accelFactor*std::sin(rotation*M_PI/180)
		);

		//calculate the new position with the speed
		move(posOffset);


		//collisions tests
		bool collided = false;
		int i = 0;
		collision::LineHitBox lineBox;
		for(Map::iterator it = map.begin(); it != map.end() && !collided; it++)
		{	
			collided = collision::collision(getHitBox(), it->getHitBox(), lineBox);
		}
		if(collided)
		{
			move(-posOffset); //return to position before collision
			posOffset = collision::bounceVector(
			posOffset
			,collision::normale(lineBox, getPosition())
			);

			move(posOffset);
			setRotation(angle(posOffset));
			m_speed /= 4;
			std::cout<< getPosition().x<< " ; "<< getPosition().y<< '\n';
		}


		m_acceleration = 0;
		m_physicTimer.restart();

	}

	//draw the speed at the right place
	m_speedIndicator.setPosition(getPosition() - sf::Vector2f(400, 300));
	std::stringstream stream;
	stream<< int(m_speed);
	std::string indicatorString;
	stream>> indicatorString;

	m_speedIndicator.setString(indicatorString);
}
Exemplo n.º 21
0
double QgsVector::angle( QgsVector v ) const
{
  return v.angle() - angle();
}
Exemplo n.º 22
0
void TerrainGesture::UpdateKeyScroll(double secondsSinceLastUpdate)
{
	float limit = 40;
	if (_keyScrollLeft) _keyScrollMomentum.y += limit;
	if (_keyScrollRight) _keyScrollMomentum.y -= limit;
	if (_keyScrollForward) _keyScrollMomentum.x += limit;
	if (_keyScrollBackward) _keyScrollMomentum.x -= limit;

	TerrainView* terrainView = _hotspot->GetTerrainView();
	glm::vec3 pos = terrainView->GetTerrainViewport().GetCameraPosition();
	glm::vec3 dir = terrainView->GetTerrainViewport().GetCameraDirection();
	glm::vec2 delta = (float)secondsSinceLastUpdate * glm::log(2.0f + glm::max(0.0f, pos.z)) * rotate(_keyScrollMomentum, angle(dir.xy()));
	terrainView->MoveCamera(pos + glm::vec3(delta, 0));

	_keyScrollMomentum *= glm::exp2(-25.0f * (float)secondsSinceLastUpdate);
}
Exemplo n.º 23
0
dgUnsigned32 dgBallConstraint::JacobianDerivative(dgContraintDescritor& params)
{
  dgInt32 ret;
  dgFloat32 relVelocErr;
  dgFloat32 penetrationErr;
  dgMatrix matrix0;
  dgMatrix matrix1;

  if (m_jointUserCallback)
  {
    m_jointUserCallback(*this, params.m_timestep);
  }

  dgVector angle(CalculateGlobalMatrixAndAngle(matrix0, matrix1));
  m_angles = angle.Scale(-dgFloat32(1.0f));

  const dgVector& dir0 = matrix0.m_front;
  const dgVector& dir1 = matrix0.m_up;
  const dgVector& dir2 = matrix0.m_right;
  const dgVector& p0 = matrix0.m_posit;
  const dgVector& p1 = matrix1.m_posit;

  dgPointParam pointData;
  InitPointParam(pointData, m_stiffness, p0, p1);
  CalculatePointDerivative(0, params, dir0, pointData, &m_jointForce[0]);
  CalculatePointDerivative(1, params, dir1, pointData, &m_jointForce[1]);
  CalculatePointDerivative(2, params, dir2, pointData, &m_jointForce[2]);
  ret = 3;

  if (m_twistLimit)
  {
    if (angle.m_x > m_twistAngle)
    {
      dgVector p0(matrix0.m_posit + matrix0.m_up.Scale(MIN_JOINT_PIN_LENGTH));
      InitPointParam(pointData, m_stiffness, p0, p0);

      const dgVector& dir = matrix0.m_right;
      CalculatePointDerivative(ret, params, dir, pointData, &m_jointForce[ret]);

      dgVector velocError(pointData.m_veloc1 - pointData.m_veloc0);
      relVelocErr = velocError % dir;
      if (relVelocErr > dgFloat32(1.0e-3f))
      {
        relVelocErr *= dgFloat32(1.1f);
      }

      penetrationErr = MIN_JOINT_PIN_LENGTH * (angle.m_x - m_twistAngle);
      _ASSERTE(penetrationErr >= dgFloat32 (0.0f));

      params.m_forceBounds[ret].m_low = dgFloat32(0.0f);
      params.m_forceBounds[ret].m_normalIndex = DG_NORMAL_CONSTRAINT;
      params.m_forceBounds[ret].m_jointForce = &m_jointForce[ret];
//			params.m_jointAccel[ret] = (relVelocErr + penetrationErr) * params.m_invTimestep;
      SetMotorAcceleration(ret,
          (relVelocErr + penetrationErr) * params.m_invTimestep, params);
      ret++;
    }
    else if (angle.m_x < -m_twistAngle)
    {
      dgVector p0(matrix0.m_posit + matrix0.m_up.Scale(MIN_JOINT_PIN_LENGTH));
      InitPointParam(pointData, m_stiffness, p0, p0);
      dgVector dir(matrix0.m_right.Scale(-dgFloat32(1.0f)));
      CalculatePointDerivative(ret, params, dir, pointData, &m_jointForce[ret]);

      dgVector velocError(pointData.m_veloc1 - pointData.m_veloc0);
      relVelocErr = velocError % dir;
      if (relVelocErr > dgFloat32(1.0e-3f))
      {
        relVelocErr *= dgFloat32(1.1f);
      }

      penetrationErr = MIN_JOINT_PIN_LENGTH * (-m_twistAngle - angle.m_x);
      _ASSERTE(penetrationErr >= dgFloat32 (0.0f));

      params.m_forceBounds[ret].m_low = dgFloat32(0.0f);
      params.m_forceBounds[ret].m_normalIndex = DG_NORMAL_CONSTRAINT;
      params.m_forceBounds[ret].m_jointForce = &m_jointForce[ret];
//			params.m_jointAccel[ret] = (relVelocErr + penetrationErr) * params.m_invTimestep;
      SetMotorAcceleration(ret,
          (relVelocErr + penetrationErr) * params.m_invTimestep, params);
      ret++;
    }
  }

  if (m_coneLimit)
  {

    dgFloat32 coneCos;
    coneCos = matrix0.m_front % matrix1.m_front;
    if (coneCos < m_coneAngleCos)
    {
      dgVector p0(
          matrix0.m_posit + matrix0.m_front.Scale(MIN_JOINT_PIN_LENGTH));
      InitPointParam(pointData, m_stiffness, p0, p0);

      dgVector tangentDir(matrix0.m_front * matrix1.m_front);
      tangentDir = tangentDir.Scale(
          dgRsqrt ((tangentDir % tangentDir) + 1.0e-8f));
      CalculatePointDerivative(ret, params, tangentDir, pointData,
          &m_jointForce[ret]);
      ret++;

      dgVector normalDir(tangentDir * matrix0.m_front);

      dgVector velocError(pointData.m_veloc1 - pointData.m_veloc0);
      //restitution = contact.m_restitution;
      relVelocErr = velocError % normalDir;
      if (relVelocErr > dgFloat32(1.0e-3f))
      {
        relVelocErr *= dgFloat32(1.1f);
      }

      penetrationErr = MIN_JOINT_PIN_LENGTH
          * (dgAcos (GetMax (coneCos, dgFloat32(-0.9999f))) - m_coneAngle);
      _ASSERTE(penetrationErr >= dgFloat32 (0.0f));

      CalculatePointDerivative(ret, params, normalDir, pointData,
          &m_jointForce[ret]);
      params.m_forceBounds[ret].m_low = dgFloat32(0.0f);
      params.m_forceBounds[ret].m_normalIndex = DG_NORMAL_CONSTRAINT;
      params.m_forceBounds[ret].m_jointForce = &m_jointForce[ret];
//			params.m_jointAccel[ret] = (relVelocErr + penetrationErr) * params.m_invTimestep;
      SetMotorAcceleration(ret,
          (relVelocErr + penetrationErr) * params.m_invTimestep, params);
      ret++;
    }
  }

  return dgUnsigned32(ret);
}
Exemplo n.º 24
0
EXPORT void g_verbose_fprint_state(
	FILE	   *file,
	const char *name,
	Locstate   state)
{
	bool		bin_out;
	int		i, dim;
	float		p, c, S, v[SMAXD], speed;
	static	char	vname[3][3] = { "vx", "vy", "vz"};
	static	char	mname[3][3] = { "mx", "my", "mz"};

	if (name == NULL)
	    name = "";
	(void) fprintf(file,"\n%s:\n",name);
	(void) fprintf(file,"address %p\n",state);
	if (state == NULL || is_obstacle_state(state))
	{
	    (void) fprintf(file,"(OBSTACLE STATE)\n\n");
	    return;
	}
	dim = Params(state)->dim;

	p = pressure(state);
	c = sound_speed(state);
	S = entropy(state);

	(void) fprintf(file,"%-24s = %-"FFMT" %-24s = %-"FFMT"\n",
		       "density",Dens(state),
		       "specific internal energy",
		       specific_internal_energy(state));
	(void) fprintf(file,"%-24s = %-"FFMT" %-24s = %-"FFMT"\n","pressure",p,
		       "sound speed",c);
	(void) fprintf(file,"%-24s = %-"FFMT" %-24s = %-"FFMT"\n","temperature",
		       temperature(state),"specific entropy",S);

	speed = 0.0;
	for (i = 0; i < dim; i++)
	{
	    v[i] = vel(i,state);	speed += sqr(v[i]);
	    (void) fprintf(file,"%-24s = %-"FFMT" %-24s = %-"FFMT"\n",
			   mname[i],mom(i,state),vname[i],v[i]);
	}
	speed = sqrt(speed);

	(void) fprintf(file,"%-24s = %-"FFMT"","total energy",energy(state));
	if (c > 0. && Dens(state) > 0.)
	   (void) fprintf(file," %-24s = %-"FFMT"\n","Mach number",speed / c);
	else
	   (void) fprintf(file,"\n");

#if defined(TWOD)
	if (dim == 2)
	    (void) fprintf(file,"%-24s = %-"FFMT"\n","velocity angle",
			   degrees(angle(v[0],v[1])));
#endif /* defined(TWOD) */


	fprint_state_type(file,"State type = ",state_type(state));
	(void) fprintf(file,"Params state = %llu\n",
		       gas_param_number(Params(state)));

	bin_out = is_binary_output();
	set_binary_output(NO);
	if (debugging("prt_params"))
	    fprint_Gas_param(file,Params(state));
	else
	    (void) fprintf(file,"Gas_param = %llu\n",
		                gas_param_number(Params(state)));
	set_binary_output(bin_out);

	//if(p< -2000 || p>10000)
	//{
	//    printf("#huge pressure\n");
	//    clean_up(0);
	//}
#if !defined(COMBUSTION_CODE)
	(void) fprintf(file,"\n");
#else /* !defined(COMBUSTION_CODE) */
	if (Composition_type(state) == PURE_NON_REACTIVE)
	{
	    (void) fprintf(file,"\n");
	    return;
	}

	(void) fprintf(file,"%-24s = %-12s   %-24s = %-"FFMT"\n","burned",
		       Burned(state) ? "BURNED" : "UNBURNED",
		       "q",Params(state)->q);
	(void) fprintf(file,"%-24s = %-"FFMT"\n","t_crit",
		       Params(state)->critical_temperature);

	if (Composition_type(state) == PTFLAME)
	{
	    (void) fprintf(file,"\n");
	    return;
	}

	(void) fprintf(file,"%-24s = %-"FFMT"\n","product density",Prod(state));
	(void) fprintf(file,"%-24s = %-"FFMT"\n",
		       "reaction progress",React(state));

	if (Composition_type(state) == ZND)
	{
	    (void) fprintf(file,"\n");
	    return;
	}

	(void) fprintf(file,"%-24s = %-"FFMT"\n","rho1",Dens1(state));
#endif /* !defined(COMBUSTION_CODE) */
	(void) fprintf(file,"%-24s = %-24s %-24s = %-"FFMT"\n\n","gamma_set",
		      Local_gamma_set(state)?"YES" : "NO","local_gamma",
		      Local_gamma(state));
        if(g_composition_type() == MULTI_COMP_NON_REACTIVE)
        {
            if(Params(state) != NULL &&
               Params(state)->n_comps != 1)
            {
                for(i = 0; i < Params(state)->n_comps; i++)
                    (void) fprintf(file,"partial density[%2d] = %"FFMT"\n",
                       i,pdens(state)[i]);
                (void) fprintf(file,"\n");
                 /* TMP the following print is for the debuging display purpose */
                for(i = 0; i < Params(state)->n_comps; i++)
                    (void) fprintf(file,"[%d]Mass fraction = %-"FFMT"\n",
                             i, pdens(state)[i]/Dens(state));
                (void) fprintf(file,"\n");
            }
        }
}		/*end g_verbose_fprint_state*/
Exemplo n.º 25
0
 void handle(event me[2])
 {setviewport(5,5,5+440,5+height,1);
  clearviewport();
  if(is1(flag,0))
  {rad1=pow(m1/500,0.33333333);
   rad2=pow(m2/500,0.33333333);
   //
   if(is1(flag,12))
   {delete tms;
    set0(flag,12);
    if(is1(flag,7))
    {delete array[0];delete array[1];delete array[2];delete array[3];
     set0(flag,7);
    }
    if(is1(flag,6))
    {delete array[0];delete array[1];delete array[2];delete array[3];
     set0(flag,6);
    }
    if(is1(flag,5))
    {delete array[0];delete array[1];delete array[2];delete array[3];
     set0(flag,5);
    }
   }
   //
    if((me[1].b&1)==1)
    {vector vm2(me[2].x-5-220,height/2-me[2].y+5),
	     vm1(me[1].x-5-220,height/2-me[1].y+5);
     if((me[2].b&1)==0)
     { if((r1+v1-vm1).mod()<=5)
       set1(flag,8);
       else if((r2+v2-vm1).mod()<=5)
       set1(flag,9);
       else if((r1-vm1).mod()<=rad1)
       set1(flag,10);
       else if((r2-vm1).mod()<=rad2)
       set1(flag,11);
     }
     else if(me[1].x>5&&me[1].x<445&&me[1].y>5&&me[1].y<(5+height))
     { if(is1(flag,8))
	v1=vm1-r1;
       else if(is1(flag,9))
	v2=vm1-r2;
       else if(is1(flag,10))
	r1=vm1;
       else if(is1(flag,11))
	r2=vm1;
     }
    }
    else
    {set0(flag,8);set0(flag,9);set0(flag,10);set0(flag,11);
    }
    setcolor(COL1);
    setfillstyle(SOLID_FILL,COL1);
    fillellipse(r1.x+220,height/2-r1.y,rad1*10./9,rad1);
    setcolor(14);
    setfillstyle(SOLID_FILL,14);
    fillellipse(r2.x+220,height/2-r2.y,rad2*10./9,rad2);
    //
    setcolor(1);
    line(220+r1.x,height/2-r1.y,220+r1.x+v1.x,height/2-r1.y-v1.y);
    double ang=angle(v1.x,-v1.y);
    int pol[8];
    setfillstyle(SOLID_FILL,1);
    pol[0]=220+r1.x+v1.x;pol[1]=height/2-r1.y-v1.y;
    pol[2]=220+r1.x+v1.x+4*cos(ang+2.5);pol[3]=height/2-r1.y-v1.y+4*sin(ang+2.5);
    pol[4]=220+r1.x+v1.x+4*cos(ang-2.5);pol[5]=height/2-r1.y-v1.y+4*sin(ang-2.5);
    pol[6]=220+r1.x+v1.x;pol[7]=height/2-r1.y-v1.y;
    fillpoly(4,pol);
    //
    setcolor(2);
    line(220+r2.x,height/2-r2.y,220+r2.x+v2.x,height/2-r2.y-v2.y);
    ang=angle(v2.x,-v2.y);
    setfillstyle(SOLID_FILL,2);
    pol[0]=220+r2.x+v2.x;pol[1]=height/2-r2.y-v2.y;
    pol[2]=220+r2.x+v2.x+4*cos(ang+2.5);pol[3]=height/2-r2.y-v2.y+4*sin(ang+2.5);
    pol[4]=220+r2.x+v2.x+4*cos(ang-2.5);pol[5]=height/2-r2.y-v2.y+4*sin(ang-2.5);
    pol[6]=220+r2.x+v2.x;pol[7]=height/2-r2.y-v2.y;
    fillpoly(4,pol);
  }
  if(is1(flag,1))
  {if(is0(flag,12))
   {set1(flag,12);
    tms=new Two_Mass_System(m1,m2,r1,r2,v1,v2);
    if(is1(flag,13))
    {  setviewport(0,0,639,349,1);
       active
       setfillstyle(SOLID_FILL,7);
       bar(0,349-charheight-1,639,349);
       status("Wait...");
       active
       setviewport(5,5,5+440,5+height,1);
     if((tms->s->flag==2||tms->s->flag==3)&&tms->s->T*2/0.05<2000)
     {array[0]=new double[tms->s->T*2/0.05+25];
      array[1]=new double[tms->s->T*2/0.05+25];
      array[2]=new double[tms->s->T*2/0.05+25];
      array[3]=new double[tms->s->T*2/0.05+25];
      long i=0;
      for(double q=0;q<=tms->s->T*2+0.6;q+=0.05,i++)
      {tms->position_wrt_cm(q,w1,w2);
       array[0][i]=w1.x;
       array[1][i]=w1.y;
       array[2][i]=w2.x;
       array[3][i]=w2.y;
      }
      set1(flag,7);
     }
     if(tms->s->flag==1||tms->s->flag==4)
     {array[0]=new double[20/0.05+25];
      array[1]=new double[20/0.05+25];
      array[2]=new double[20/0.05+25];
      array[3]=new double[20/0.05+25];
      long i=0;
      for(double q=0;q<=20+0.5;q+=0.05,i++)
      {tms->position_wrt_cm(q,w1,w2);
       array[0][i]=w1.x;
       array[1][i]=w1.y;
       array[2][i]=w2.x;
       array[3][i]=w2.y;
      }
      set1(flag,6);
     }
     if(tms->s->flag==2&&tms->s->T*2/0.05>=2000)
     {array[0]=new double[40/0.05+25];
      array[1]=new double[40/0.05+25];
      array[2]=new double[40/0.05+25];
      array[3]=new double[40/0.05+25];
      long i=0;
      for(double q=-20-0.5;q<=20+0.5;q+=0.05,i++)
      {tms->position_wrt_cm(q,w1,w2);
       array[0][i]=w1.x;
       array[1][i]=w1.y;
       array[2][i]=w2.x;
       array[3][i]=w2.y;
      }
      set1(flag,5);
     }
    }
    t=0;
   }

   if(is1(flag,7))
   {setcolor(8);
    for(long i=2;i<t/0.05&&i*0.05<=tms->s->T*2+0.5;i++)
    {line(220+array[0][i],height/2-array[1][i]*0.9,220+array[0][i+1],height/2-array[1][i+1]*0.9);
     line(220+array[2][i],height/2-array[3][i]*0.9,220+array[2][i+1],height/2-array[3][i+1]*0.9);
    }
   }
   if(is1(flag,6))
   {setcolor(8);
     for(long i=2;i<t/0.05&&i*0.05<=20;i++)
     {line(220+array[0][i],height/2-array[1][i]*0.9,220+array[0][i+1],height/2-array[1][i+1]*0.9);
      line(220+array[2][i],height/2-array[3][i]*0.9,220+array[2][i+1],height/2-array[3][i+1]*0.9);
     }
   }
   if(is1(flag,5))
   {setcolor(8);
     for(long i=(20+0.5)/0.05;i*0.05-(20+0.5)<t&&i*0.05-(20+0.5)<=20;i++)
     {line(220+array[0][i],height/2-array[1][i]*0.9,220+array[0][i+1],height/2-array[1][i+1]*0.9);
      line(220+array[2][i],height/2-array[3][i]*0.9,220+array[2][i+1],height/2-array[3][i+1]*0.9);
     }
     for(i=0.5/0.05;i*0.05<(20+0.5)+t-tms->s->T*2&&i*0.05<=(20+0.5);i++)
     {line(220+array[0][i],height/2-array[1][i]*0.9,220+array[0][i+1],height/2-array[1][i+1]*0.9);
      line(220+array[2][i],height/2-array[3][i]*0.9,220+array[2][i+1],height/2-array[3][i+1]*0.9);
     }
   }
   if(is1(flag,13))
   { tms->position_wrt_cm(t,d1,d2);
     setviewport(0,0,639,349,1);
     if(tms->s->flag==1)status("Moving in Parabolic path");
     if(tms->s->flag==2)status("Moving in Elliptical path");
     if(tms->s->flag==3)status("Moving in Circular path");
     if(tms->s->flag==4)status("Moving in Hyperbolic path");
     setviewport(5,5,5+440,5+height,1);
   }
   else tms->position(t,d1,d2);
   setcolor(COL1);
   setfillstyle(SOLID_FILL,COL1);
   fillellipse(d1.x+220,height/2-d1.y*0.9,rad1*10./9,rad1);
   setcolor(COL2);
   setfillstyle(SOLID_FILL,COL2);
   fillellipse(d2.x+220,height/2-d2.y*0.9,rad2*10./9,rad2);
   t+=dt;
  }
  if(is1(flag,15))
  {setcolor(15);
   char str[100]="An Application by ";
   char ma[13];
   for(int i=0;i<13;i++)
    ma[i]=char(~st_[i]);
   strcat(str,ma);
   strcat(str," to obserb how a Mass  ");
   outtextxy(5,5, str );
   outtextxy(5,5+charheight+5,    "Body is affected in the Gravitational Feild developed" );
   outtextxy(5,5+2*(charheight+5),"by anoher Mass Body. ( Written in CPP )");
  }
  setviewport(0,0,639,349,1);
  setcolor(8);
  line(445,6,445,5+height);
  line(444,7,444,5+height);
  line(443,8,443,5+height);
  line(6,5+height,445,5+height);
  line(7,5+height-1,445,5+height-1);
  line(8,5+height-2,445,5+height-2);
 }
Exemplo n.º 26
0
EXPORT	void print_RP_node_states(
	const char	*message,
	float		*nod_v,
	RP_DATA		*RP,
	int		n_type)
{
	float	   M;
	float	   v[MAX_N_CURVES][MAXD];
	float	   q[MAX_N_CURVES], theta[MAX_N_CURVES];
	float	   dtheta;
	int	   i, j;
	int	   dim = Params(RP->state[0])->dim;
	int	   nangs;
	int	   iang[MAX_N_CURVES];
	int	   ist[MAX_N_CURVES];
	int	   num_sts;
	char	   mesg[80];
	const char *ang_names[7];

	set_prt_node_sts_params(RP,n_type,&num_sts,&nangs,ang_names,ist,iang);

	if (message != NULL)
	    (void) printf("%s\n",message);

	print_angle_direction("RP->ang_dir =",RP->ang_dir,"\n");
	(void) printf("Node velocity = <%"FFMT", %"FFMT">\n",nod_v[0],nod_v[1]);
	for (i = 0; i < num_sts; i++)
	{
	    M = mach_number(RP->state[ist[i]],nod_v);
	    (void) sprintf(mesg,"state%d is %s, M%d = %"FFMT,ist[i],
	    	(M >= 1.0) ? "supersonic" : "subsonic",ist[i],M);
	    verbose_print_state(mesg,RP->state[ist[i]]);
	}


	(void) printf("\nWave Angles:\n");
	for (i = 0; i < nangs; i++)
	{
	    (void) printf("RP->ang[%d],\n\t%s = %"FFMT" (%g degrees)\n",iang[i],
	    	          ang_names[iang[i]],RP->ang[iang[i]],
	    	          degrees(RP->ang[iang[i]]));
	    dtheta = RP->ang[iang[(i+1)%nangs]] - RP->ang[iang[i]];
	    (void) printf("\tRP->ang[%d] - RP->ang[%d] = ",
	    	          iang[(i+1)%nangs],iang[i]);
	    (void) printf("%"FFMT" (%g degrees)\n",dtheta,degrees(dtheta));
	}

	(void) printf("\nSteady state velocities\n");
	for (i = 0; i < num_sts; i++)
	{
	    q[i] = 0;
	    for (j = 0; j < dim; j++)
	    {
	    	v[i][j] = vel(j,RP->state[ist[i]]) - nod_v[j];
	    	q[i] += sqr(v[i][j]);
	    }
	    theta[i] = angle(v[i][0],v[i][1]);
	    q[i] = sqrt(q[i]);
	}
	for (i = 0; i < num_sts; i++)
	{
	    dtheta = theta[(i+1)%num_sts] - theta[i];
	    (void) printf("vel_ang(RP->state[%d]) - vel_ang(RP->state[%d]) = ",
			(ist[i]+1)%num_sts,ist[i]);
	    (void) printf("%"FFMT" (%g degrees)\n",dtheta,degrees(dtheta));
	    (void) printf("RP->state[%d],\n\t",ist[i]);
	    (void) printf("v = <");
	    for (j = 0; j < dim; j++)
	    	(void) printf("%"FFMT"%s",v[i][j],(j==(dim-1))?">, ":",");
	    (void) printf("q = %"FFMT", theta = %"FFMT" (%g degrees)\n",
			  q[i],theta[i],degrees(theta[i]));
	}
	(void) printf("\n");
}		/*end print_RP_node_states*/
Exemplo n.º 27
0
void MyGame::processNewGame()
{
	Vector2 startLocation = { SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 };
	player = new Player(100, startLocation, 0.0, 10);

	SDL_Rect initialMapDraw = { this->player->getPosition().x - (SCREEN_WIDTH / 2), this->player->getPosition().y - (SCREEN_HEIGHT / 2), SCREEN_WIDTH, SCREEN_HEIGHT };
	int mapWidth = mapTexture->getLocation().w;
	int mapHeight = mapTexture->getLocation().h;
	map = new MapScene(mapWidth, mapHeight, initialMapDraw);

	randomNumberGen.seed(SDL_GetTicks());
	std::uniform_int_distribution<int> xLocation(0, mapWidth);
	std::uniform_int_distribution<int> yLocation(0, mapHeight);
	std::uniform_int_distribution<int> objectType(1, 3);
	std::uniform_int_distribution<int> treeType(1, 3);
	obstacles.clear();
	for (int i = 0; i < 50; i++)
	{
		EnvironmentObject anObject;
		AABB collision;
		int x = xLocation(randomNumberGen);
		int y = yLocation(randomNumberGen);
		switch (objectType(randomNumberGen))
		{
		case 1:
		case 2:
			collision = { x - 20, y - 20, 30, 30 };
			switch (treeType(randomNumberGen))
			{
			case 1:
				anObject.init("tree1", x, y, collision, "treeTexture1");
				break;
			case 2:
				anObject.init("tree2", x, y, collision, "treeTexture2");
				break;
			case 3:
				anObject.init("tree3", x, y, collision, "treeTexture3");
				break;
			}
			break;
		case 3:
			collision = { x - 50, y - 45, 85, 90 };
			anObject.init("rock", x, y, collision, "rockTexture");
			break;
		}
		this->obstacles.push_back(anObject);
	}
	EnvironmentObject cave;
	int caveX = SCREEN_WIDTH / 2 - 150;
	int caveY = SCREEN_HEIGHT / 2 - 150;
	AABB caveCollision = { caveX - 60, caveY - 60, 120, 120 };
	cave.init("cave", caveX, caveY, caveCollision, "caveTexture");
	this->obstacles.push_back(cave);

	EnvironmentObject wife;
	int wifeX = xLocation(randomNumberGen);
	int wifeY = yLocation(randomNumberGen);
	AABB wifeCollision = { wifeX - 21, wifeY - 30, 42, 60 };
	wife.init("wife", wifeX, wifeY, wifeCollision, "wifeTexture");
	this->obstacles.push_back(wife);

	EnvironmentObject cage;
	AABB cageCollision = { wifeX - 24, wifeY - 32, 48, 64 };
	cage.init("cage", wifeX, wifeY, cageCollision, "cageTexture");
	this->obstacles.push_back(cage);

	for (int i = 0; i < enemies.size(); i++)
	{
		delete enemies[i];
		enemies[i] = nullptr;
	}
	enemies.clear();
	for (int i = 0; i < 15; i++){
		int hunterX = xLocation(randomNumberGen);
		int hunterY = yLocation(randomNumberGen);
		std::uniform_int_distribution<int> hunterSkin(1, 3);
		std::string textID;
		switch (hunterSkin(randomNumberGen))
		{
		case 1:
			textID = "hunterTexture1";
		case 2:
			textID = "hunterTexture2";
		case 3:
			textID = "hunterTexture3";
		}
		std::uniform_int_distribution<int> angle(0, 359);
		Vector2 location = { (double)hunterX, (double)hunterY };
		Hunter *hunter = new Hunter(30, location, angle(randomNumberGen), 5, textID);
		enemies.push_back(hunter);
	}

	keyDropped = false;
	keyCollected = false;

	gameState = RUNNING;
}
Exemplo n.º 28
0
void generateHistogram(const SurfaceMesh &mesh)
{
    // compute angle distribution
    std::array<double, 18> histogram;
    histogram.fill(0);
    for (auto face : mesh.get_level_id<3>())
    {
        auto   vertexIDs = mesh.get_name(face);
        // Unpack the ID's for convenience
        Vertex a = *mesh.get_simplex_up<1>({vertexIDs[0]});
        Vertex b = *mesh.get_simplex_up<1>({vertexIDs[1]});
        Vertex c = *mesh.get_simplex_up<1>({vertexIDs[2]});

        auto   binAngle = [&](double angle) -> int{
                return std::floor(angle/10);
            };
        histogram[binAngle(angle(a, b, c))]++;
        histogram[binAngle(angle(b, a, c))]++;
        histogram[binAngle(angle(c, a, b))]++;
    }

    int factor = mesh.size<3>()*3;
    std::for_each(histogram.begin(), histogram.end(), [&factor](double &n){
        n = 100.0*n/factor;
    });

    std::cout << "Angle Distribution:" << std::endl;
    for (int x = 0; x < 18; x++)
        std::cout << x*10 << "-" << (x+1)*10 << ": " << std::setprecision(2)
                  << std::fixed << histogram[x] << std::endl;
    std::cout << std::endl << std::endl;

    // compute the edge length distribution
    std::cout << "Edge Length Distribution:" << std::endl;
    std::vector<double> lengths;
    for (auto edge : mesh.get_level_id<2>())
    {
        auto   vertexIDs = mesh.down(edge);
        auto   t1  = *vertexIDs.cbegin();
        auto   t2  = *(++vertexIDs.cbegin());
        auto   v1  = *t1;
        auto   v2  = *t2;
        double len = magnitude(v2-v1);
        lengths.push_back(len);
    }
    std::sort(lengths.begin(), lengths.end());

    std::array<double, 20> histogramLength;
    histogramLength.fill(0);
    double                 interval = (lengths.back() - lengths.front())/20;
    double                 low = lengths.front();

    if (interval <= 0.0000001) // floating point roundoff prevention
    {
        std::cout << lengths.front() << ": " << 100 << std::endl << std::endl;
    }
    else
    {
        for (auto length : lengths)
        {
            histogramLength[std::floor((length-low)/interval)]++;
        }

        factor = mesh.size<2>();
        std::for_each(histogramLength.begin(), histogramLength.end(), [&factor](double &n){
            n = 100.0*n/factor;
        });

        for (int x = 0; x < 20; x++)
            std::cout << x*interval << "-" << (x+1)*interval << ": " << std::setprecision(2)
                      << std::fixed << histogramLength[x] << std::endl;
        std::cout << std::endl << std::endl;
    }

    // Compute the valence distribution
    std::array<double, 20> histogramValence;
    histogramValence.fill(0);

    for (auto vertexID : mesh.get_level_id<1>())
    {
        // TODO bounds checking here...
        histogramValence[getValence(mesh, vertexID)]++;
    }

    factor = mesh.size<1>();
    // std::for_each(histogramValence.begin(), histogramValence.end(),
    // [&factor](double& n){
    //         n = 100.0*n/factor;});
    std::cout << "Valence distribution:" << std::endl;
    for (int x = 0; x < 20; x++)
        std::cout << x << ": " << histogramValence[x] << std::endl;
    std::cout << std::endl << std::endl;
}
Exemplo n.º 29
0
QPointF Body::toLocal( const QPointF& p ) const {
    QTransform transform;
    //transform.translate(-position().x(),-position().y());
    transform.rotateRadians(-angle());
    return transform.map(p-position());
}
Exemplo n.º 30
0
void LCVText::draw(LcPainter* painter, LcDrawOptions* options, const lc::geo::Area& rect) const {



    bool modified = false;

    modified = true;
    painter->save();

    if (this->selected()) {
        painter->source_rgba(
            options->selectedColor().red(),
            options->selectedColor().green(),
            options->selectedColor().blue(),
            options->selectedColor().alpha()
        );
    } else {
        painter->source_rgba(
                layers().front()->color().red(),
                layers().front()->color().green(),
                layers().front()->color().blue(),
                layers().front()->color().alpha()
                );
    }

    //    double letterSpacing = 3.0;
    //    double wordSpacing = 6.75;
    //    double lineSpacingFactor = 1.0;

    //    lc::geo::Coordinate letterPos = lc::geo::Coordinate(0.0, -9.0);
    //    lc::geo::Coordinate letterSpace = lc::geo::Coordinate(letterSpacing, 0.0);
    //    lc::geo::Coordinate space = lc::geo::Coordinate(wordSpacing, 0.0);
    lc::geo::Coordinate textSize(Text::boundingBox().maxP() - Text::boundingBox().minP());

    // Vertical Align:
    double vSize = 9.0;

    double alignX = insertion_point().x();
    double alignY = insertion_point().y();

    //    double alignX, alignY;
    switch (valign()) {
        case Text::VAMiddle:
            alignX += 0.0;
            alignY += vSize / 2.0;
            break;

        case Text::VABottom:
            alignX += 0.0;
            alignY += vSize + 3;
            break;

        case Text::VABaseline:
            alignX += 0.0;
            alignY += vSize;
            break;

        default:
            break;
    }

    // Horizontal Align:
    switch (halign()) {
        case Text::HAMiddle:
            alignX += (0. - textSize.x() / 2.0);
            alignY += (0. - (vSize + textSize.y() / 2.0 + Text::boundingBox().minP().y()));
            break;

        case Text::HACenter:
            alignX += (0. - textSize.x() / 2.0);
            alignY += alignY + (0.0);
            break;

        case Text::HARight:
            alignX += alignX + (0. - textSize.x());
            alignY += alignY + (0.0);
            break;

        default:
            break;
    }

    double angle_;

    // Rotate:
    if (halign() == Text::HAAligned || halign() == Text::HAFit) {
        angle_ = insertion_point().angleTo(second_point());
    } else {
        angle_ = angle();
    }

    const char* str = text_value().c_str();

    painter->text(alignX, alignY, str, angle_, height());

    painter->stroke();

    if (modified) {
        painter->restore();
    }

}