double DescriptionFactory::GetBearing(const _Coordinate& A, const _Coordinate& B) const {
    double deltaLong = DegreeToRadian(B.lon/100000. - A.lon/100000.);

    double lat1 = DegreeToRadian(A.lat/100000.);
    double lat2 = DegreeToRadian(B.lat/100000.);

    double y = sin(deltaLong) * cos(lat2);
    double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(deltaLong);
    double result = RadianToDegree(atan2(y, x));
    while(result <= 0.)
        result += 360.;
    while(result >= 360.)
        result -= 360.;

    return result;
}
void ETHPhysicsEntityController::Update(const float lastFrameElapsedTime, ETHBucketManager& buckets)
{
	if (!m_body)
		return;

	if (!m_body->IsActive())
		return;

	GS2D_UNUSED_ARGUMENT(lastFrameElapsedTime);
	const Vector2 pos = ETHPhysicsSimulator::ScaleFromBox2D(m_body->GetPosition());
	const Vector2 oldPos = Vector2(m_pos.x, m_pos.y);
	if (oldPos != pos)
	{
		m_pos = Vector3(pos, GetPos().z);
		buckets.RequestBucketMove(static_cast<ETHEntity*>(m_body->GetUserData()), oldPos, pos);
	}
	m_angle =-RadianToDegree(m_body->GetAngle());
}
double DescriptionFactory::GetBearing(const FixedPointCoordinate &A, const FixedPointCoordinate &B)
    const
{
    double delta_long = DegreeToRadian(B.lon / COORDINATE_PRECISION - A.lon / COORDINATE_PRECISION);

    const double lat1 = DegreeToRadian(A.lat / COORDINATE_PRECISION);
    const double lat2 = DegreeToRadian(B.lat / COORDINATE_PRECISION);

    const double y = sin(delta_long) * cos(lat2);
    const double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(delta_long);
    double result = RadianToDegree(atan2(y, x));
    while (result < 0.)
    {
        result += 360.;
    }

    while (result >= 360.)
    {
        result -= 360.;
    }
    return result;
}
Exemple #4
0
bool msAnimation::LoadMilkshapeAsciiBones( CString sAniName, CString sPath )
{
	FixSlashesInPlace(sPath);
	const CString sDir = Dirname( sPath );

	RageFile f;
	if ( !f.Open(sPath) )
		RageException::Throw( "Model:: Could not open \"%s\": %s", sPath.c_str(), f.GetError().c_str() );

	CString sLine;
	int iLineNum = 0;

	msAnimation &Animation = *this;

	bool bLoaded = false;
    while( f.GetLine( sLine ) > 0 )
    {
		iLineNum++;

        if (!strncmp (sLine, "//", 2))
            continue;

        //
        // bones
        //
        int nNumBones = 0;
        if( sscanf (sLine, "Bones: %d", &nNumBones) != 1 )
			continue;

        char szName[MS_MAX_NAME];

        Animation.Bones.resize( nNumBones );

        for( int i = 0; i < nNumBones; i++ )
        {
			msBone& Bone = Animation.Bones[i];

            // name
			if( f.GetLine( sLine ) <= 0 )
				THROW;
            if (sscanf (sLine, "\"%[^\"]\"", szName) != 1)
				THROW;
            strcpy( Bone.szName, szName );

            // parent
			if( f.GetLine( sLine ) <= 0 )
				THROW;
            strcpy (szName, "");
            sscanf (sLine, "\"%[^\"]\"", szName);

            strcpy( Bone.szParentName, szName );

            // flags, position, rotation
            RageVector3 Position, Rotation;
			if( f.GetLine( sLine ) <= 0 )
				THROW;

			int nFlags;
            if (sscanf (sLine, "%d %f %f %f %f %f %f",
                &nFlags,
                &Position[0], &Position[1], &Position[2],
                &Rotation[0], &Rotation[1], &Rotation[2]) != 7)
            {
				THROW;
            }
			Rotation = RadianToDegree(Rotation);

			Bone.nFlags = nFlags;
            memcpy( &Bone.Position, &Position, sizeof(Bone.Position) );
            memcpy( &Bone.Rotation, &Rotation, sizeof(Bone.Rotation) );

            // position key count
			if( f.GetLine( sLine ) <= 0 )
				THROW;
            int nNumPositionKeys = 0;
            if (sscanf (sLine, "%d", &nNumPositionKeys) != 1)
				THROW;

            Bone.PositionKeys.resize( nNumPositionKeys );

            for( int j = 0; j < nNumPositionKeys; ++j )
            {
				if( f.GetLine( sLine ) <= 0 )
					THROW;

				float fTime;
                if (sscanf (sLine, "%f %f %f %f", &fTime, &Position[0], &Position[1], &Position[2]) != 4)
					THROW;

				msPositionKey key;
				key.fTime = fTime;
				key.Position = RageVector3( Position[0], Position[1], Position[2] );
				Bone.PositionKeys[j] = key;
            }

            // rotation key count
			if( f.GetLine( sLine ) <= 0 )
				THROW;
            int nNumRotationKeys = 0;
            if (sscanf (sLine, "%d", &nNumRotationKeys) != 1)
				THROW;

            Bone.RotationKeys.resize( nNumRotationKeys );

            for( int j = 0; j < nNumRotationKeys; ++j )
            {
				if( f.GetLine( sLine ) <= 0 )
					THROW;

				float fTime;
                if (sscanf (sLine, "%f %f %f %f", &fTime, &Rotation[0], &Rotation[1], &Rotation[2]) != 4)
					THROW;
				Rotation = RadianToDegree(Rotation);

				msRotationKey key;
				key.fTime = fTime;
				key.Rotation = RageVector3( Rotation[0], Rotation[1], Rotation[2] );
                Bone.RotationKeys[j] = key;
            }
        }

		// Ignore "Frames:" in file.  Calculate it ourself
		Animation.nTotalFrames = 0;
		for( int i = 0; i < (int)Animation.Bones.size(); i++ )
		{
			msBone& Bone = Animation.Bones[i];
			for( unsigned j = 0; j < Bone.PositionKeys.size(); ++j )
				Animation.nTotalFrames = max( Animation.nTotalFrames, (int)Bone.PositionKeys[j].fTime );
			for( unsigned j = 0; j < Bone.RotationKeys.size(); ++j )
				Animation.nTotalFrames = max( Animation.nTotalFrames, (int)Bone.RotationKeys[j].fTime );
		}
	}

	return bLoaded;
}
Exemple #5
0
bool ETHRenderEntity::DrawProjShadow(const float maxHeight, const float minHeight, const ETHSceneProperties& sceneProps, const ETHLight& light, ETHSpriteEntity *pParent,
									 const bool maxOpacity, const bool drawToTarget, const float targetAngle, const Vector3& v3TargetPos)
{
	if (!m_pSprite || IsHidden())
		return false;

	VideoPtr video = m_provider->GetVideo();
	ETHShaderManagerPtr shaderManager = m_provider->GetShaderManager();
	SpritePtr pShadow = shaderManager->GetProjShadow();

	Vector3 v3LightPos;
	Vector3 v3ParentPos(0,0,0);

	const Vector3 v3EntityPos = GetPosition();

	if (pParent)
	{
		v3ParentPos = pParent->GetPosition();
		v3LightPos = Vector3(v3ParentPos.x, v3ParentPos.y, 0) + light.pos;
	}
	else
	{
		v3LightPos = light.pos;
	}

	// if the object is higher than the light, then the shadow shouldn't be cast on the floor
	if (v3LightPos.z < v3EntityPos.z)
	{
		return true;
	}

	const float scale = (m_properties.shadowScale <= 0.0f) ? 1.0f : m_properties.shadowScale;
	const float opacity = (m_properties.shadowOpacity <= 0.0f) ? 1.0f : m_properties.shadowOpacity;
	const Vector2 v2Size = GetCurrentSize();
	Vector2 v2ShadowSize(v2Size.x, v2Size.y);
	Vector2 v2ShadowPos(v3EntityPos.x, v3EntityPos.y);

	// if we are drawing to a target of a rotated entity
	if (drawToTarget && targetAngle != 0)
	{
		// rotate the shadow position according to entity angle
		Matrix4x4 matRot = RotateZ(-DegreeToRadian(targetAngle));
		Vector3 newShadowPos(v2ShadowPos, 0);
		newShadowPos = newShadowPos - v3TargetPos;
		newShadowPos = Multiply(newShadowPos, matRot);
		newShadowPos = newShadowPos + v3TargetPos;
		v2ShadowPos.x = newShadowPos.x;
		v2ShadowPos.y = newShadowPos.y;

		// rotate the light source to cast it correctly
		Vector3 newPos = v3LightPos - v3TargetPos;
		newPos = Multiply(newPos, matRot);
		v3LightPos = newPos + v3TargetPos;
	}

	Vector3 diff = v3EntityPos - v3LightPos;
	const float squaredDist = DP3(diff, diff);
	float squaredRange = light.range * light.range;

	if (squaredDist > squaredRange)
	{
		return true;
	}

	v2ShadowSize.x *= _ETH_SHADOW_SCALEX * scale;

	// calculate the correct shadow length according to the light height
	if ((GetPosition().z+v2Size.y) < light.pos.z) // if the light is over the entity
	{
		const float planarDist = Distance(GetPositionXY(), ETHGlobal::ToVector2(v3LightPos));
		const float verticalDist = Abs((v3EntityPos.z+v2Size.y)-v3LightPos.z);
		const float totalDist = (planarDist/verticalDist)*Abs(v3LightPos.z);
		v2ShadowSize.y = totalDist-planarDist;

		// clamp shadow length to the object's height. This is not realistic
		// but it looks better for the real-time shadows.
		v2ShadowSize.y = Min(v2Size.y*_ETH_SHADOW_FAKE_STRETCH, v2ShadowSize.y);
	}
	else
	{
		v2ShadowSize.y *= ((drawToTarget) ? _ETH_SHADOW_SCALEY : _ETH_SHADOW_SCALEY/4);
	}

	// specify a minimum length for the shadow
	v2ShadowSize.y = Max(v2ShadowSize.y, v2Size.y);

	ShaderPtr pVS = video->GetVertexShader();
	pVS->SetConstant(GS_L("shadowLength"), v2ShadowSize.y * m_properties.shadowLengthScale);
	pVS->SetConstant(GS_L("entityZ"), Max(m_shadowZ, v3EntityPos.z));
	pVS->SetConstant(GS_L("shadowZ"), m_shadowZ);
	pVS->SetConstant(GS_L("lightPos"), v3LightPos);
	video->SetSpriteDepth(
		(GetType() == ETHEntityProperties::ET_VERTICAL) ?
		ETHEntity::ComputeDepth(m_shadowZ, maxHeight, minHeight)
		: Max(0.0f, ComputeDepth(maxHeight, minHeight) - m_layrableMinimumDepth));

	v2ShadowSize.y = 1.0f;

	Vector2 lightPos2(v3LightPos.x, v3LightPos.y);
	const float shadowAngle = ::GetAngle((lightPos2 - Vector2(v3EntityPos.x, v3EntityPos.y))) + DegreeToRadian(targetAngle);

	squaredRange = Max(squaredDist, squaredRange);
	float attenBias = 1;

	// adjust brightness according to ambient light
	if (!maxOpacity)
	{
		attenBias = (1-(squaredDist/squaredRange));
		//fade the color according to the light brightness
		const float colorLen = Max(Max(light.color.x, light.color.y), light.color.z);
		attenBias *= Min(colorLen, 1.0f);

		//fade the color according to the ambient light brightness
		const Vector3 &ambientColor = sceneProps.ambient;
		const float ambientColorLen = 1.0f-((ambientColor.x + ambientColor.y + ambientColor.z)/3.0f);
		attenBias = Min(attenBias*ambientColorLen, 1.0f);
		attenBias *= Max(Min((1-(GetPosition().z/Max(GetCurrentSize().y, 1.0f))), 1.0f), 0.0f);
	}

	GS_BYTE alpha = static_cast<GS_BYTE>(attenBias*255.0f*opacity);

	if (alpha < 8)
		return true;

	Color dwShadowColor(alpha,255,255,255);

	pShadow->SetOrigin(Vector2(0.5f, 0.79f));
	pShadow->SetRectMode(Sprite::RM_THREE_TRIANGLES);
	pShadow->DrawShaped(v2ShadowPos, v2ShadowSize,
		dwShadowColor, dwShadowColor, dwShadowColor, dwShadowColor,
		RadianToDegree(shadowAngle));

	return true;
}
  //--------------------------------------------------------------------------------------------------------
  //  Public:   AdaptiveSamplingZeroTemp
  //
  //   This is essetially depth first search, non-recursive
  //
  //--------------------------------------------------------------------------------------------------------
  std::pair<SMatrix3x3, Float>
  COrientationMC::AdaptiveSamplingZeroTemp( const SMatrix3x3 & oInitialOrientation,
                                            Float fCostFnAngularResolution,
                                            Float fSearchRegionAngularSideLength,
                                            COverlapFunction & oObjectiveFunction,
                                            Int nMaxMCStep,
                                            Int NumMaxStratifiedSamples,
                                            Float fConvergenceVariance,
                                            Float fMaxConvergenceCost )
  {
    SMatrix3x3 oGlobalOptimalState = oInitialOrientation;
    SMatrix3x3 oCurrentState =  oInitialOrientation;
    COverlapFunction::ValueType fGlobalMinCost = oObjectiveFunction( oInitialOrientation );
    
    Float InitialSubregionRadius  = tan( fSearchRegionAngularSideLength ) / sqrt( 48.0 ); // sqrt(48) = 4 * sqrt(3)   ( random start radius )
    
    Int nTotalStepTaken = 0;
    Int NumGlobalPointsTaken = 0;
    Float fCurrentVariance;
    Float SubregionRadius = InitialSubregionRadius;
    
    while( nTotalStepTaken < nMaxMCStep )
    {
      Int NumSubregionSteps = Int( pow( ceil(SubregionRadius / fCostFnAngularResolution), 2.7 ) ); // Number of steps it takes to adequately
                                                                                                 // sample each subregions without missing
                                                                                                 // a cost function (giving it less more steps)

      NumSubregionSteps = std::max( NumSubregionSteps, 10 ); // at least 20 steps
      Float fCurrentCost;
      SMatrix3x3 oTmpResOrient;
      
      boost::tie( oTmpResOrient, fCurrentCost, fCurrentVariance )
        =  ZeroTemperatureOptimizationWithVariance( oCurrentState, SubregionRadius, 
                                                    oObjectiveFunction, NumSubregionSteps );
      if( fCurrentVariance > fConvergenceVariance )
        nMaxMCStep += NumSubregionSteps;
      
      nTotalStepTaken += NumSubregionSteps;
      if( fCurrentCost >=  fGlobalMinCost )           // restart with new position
      {
        //----------
        // Backtrack/Reset search parameters
        //----------
        SubregionRadius = std::min( static_cast<Float>( 2.0 * SubregionRadius), fSearchRegionAngularSideLength );
        NumGlobalPointsTaken ++;
        
        Float fX =  GetRandomVariable( -SubregionRadius, SubregionRadius );
        Float fY =  GetRandomVariable( -SubregionRadius, SubregionRadius );
        Float fZ =  GetRandomVariable( -SubregionRadius, SubregionRadius );
        SQuaternion q = oUniformGridGen.GetNearIdentityPoint( fX, fY, fZ );
        SMatrix3x3 oDelta = q.GetRotationMatrix3x3();
        oCurrentState = oDelta * oInitialOrientation;
      }
      else                                   // continuation of search, with narrowing of steps size
      {
        fGlobalMinCost      = fCurrentCost;
        oGlobalOptimalState = oTmpResOrient;
        oCurrentState       = oTmpResOrient;
        SubregionRadius     *= Float( 0.5 );    // reduce step size
      }
      
      if( (fGlobalMinCost < fMaxConvergenceCost)  && fabs( fCurrentVariance ) < fConvergenceVariance )    // convergence  -- move criterion to user defined
        break;
    }
    
        
    std::cout << RADIAN_TO_DEGREE( LatticeSymmetry::GetMisorientation( LatticeSymmetry::CCubicSymmetry::Get(), oGlobalOptimalState, oInitialOrientation )  )
	      << "\t|R_0| " << RADIAN_TO_DEGREE( InitialSubregionRadius )
	      << "\t|Step | " << nTotalStepTaken 
	      << "\t|GlbPts| " << NumGlobalPointsTaken
	      << "\t|R_c| " << RADIAN_TO_DEGREE( SubregionRadius )
	      << "\t|MCS| " << nMaxMCStep 
	      << "\t|Var| " << fCurrentVariance 
	      << "\t|C_i| " << oObjectiveFunction( oInitialOrientation )
	      << "\t|C_f|" << fGlobalMinCost 
	      << "\t[ " << RadianToDegree( oInitialOrientation.GetEulerAngles() ) << "]"
	      << std::endl; 
    
    // Named return value optimization
    std::pair<SMatrix3x3, Float> oRes = std::make_pair( oGlobalOptimalState, fGlobalMinCost ); 
    return oRes;
  }
Exemple #7
0
int _tmain(int argc, _TCHAR* argv[])
{
	bool		result = false;
	TArgInfo	info;

	ParseArg(info,argc,argv);
	const std::string &m = info.m_mode;

	//printf("mode=%s\n", m.c_str());

	if("f32_hex" == m){
		result = Float32ToHex(info);
	}else if("f64_hex" == m){
		result = Float64ToHex(info);
	}else if("hex_f32" == m){
		result = HexToFloat32(info);
	}else if("hex_f64" == m){
		result = HexToFloat64(info);
	}else if("2_10" == m){
		result = ConvertNumber(info,10,2);
	}else if("2_16" == m){
		result = ConvertNumber(info,16,2);
	}else if("10_2" == m){
		result = ConvertNumber(info,2,10);
	}else if("10_16" == m){
		result = ConvertNumber(info,16,10);
	}else if("16_2" == m){
		result = ConvertNumber(info,2,16);
	}else if("16_10" == m){
		result = ConvertNumber(info,10,16);
	}else if("r_d" == m){
		result = RadianToDegree(info);
	}else if("d_r" == m){
		result = DegreeToRadian(info);
	}else if("v_h" == m){
		result = MatrixSub(info,FovVerticalToHorizontal,3);
	}else if("h_v" == m){
		result = MatrixSub(info,FovHorizontalToVertical,3);
	}else if("ql" == m){
		result = MatrixSub(info,QuatLength,4);
	}else if("qn" == m){
		result = MatrixSub(info,QuatNormalize,4);
	}else if("qi" == m){
		result = MatrixSub(info,QuatInverse,4);
	}else if("q_m33" == m){
		result = MatrixSub(info,QuatToMat,4);
	}else if("q_a" == m){
		result = MatrixSub(info,QuatToAAng,4);
	}else if("q_xyz" == m){
		result = MatrixSub(info,QuatToXYZ,4);
	}else if("m33_q" == m){
		result = MatrixSub(info,Mat33ToQuat,9);
	}else if("m33_a" == m){
		result = MatrixSub(info,Mat33ToAAng,9);
	}else if("m33t" == m){
		result = MatrixSub(info,Mat33Transpose,9);
	}else if("m33d" == m){
		result = MatrixSub(info,Mat33Determinant,9);
	}else if("m33i" == m){
		result = MatrixSub(info,Mat33Invert,9);
	}else if("m33_s" == m){
		result = MatrixSub(info,Mat33Scale,9);
	}else if("x_m33" == m){
		result = MatrixSub(info,Mat33RotX,1);
	}else if("y_m33" == m){
		result = MatrixSub(info,Mat33RotY,1);
	}else if("z_m33" == m){
		result = MatrixSub(info,Mat33RotZ,1);
	}else if("yxz_m33" == m){
		result = MatrixSub(info,Mat33RotYXZ,3);
	}else if("zxy_m33" == m){
		result = MatrixSub(info,Mat33RotZXY,3);
	}else if("zyx_m33" == m){
		result = MatrixSub(info,Mat33RotZYX,3);
	}else if("yzx_m33" == m){
		result = MatrixSub(info,Mat33RotYZX,3);
	}else if("xzy_m33" == m){
		result = MatrixSub(info,Mat33RotXZY,3);
	}else if("xyz_m33" == m){
		result = MatrixSub(info,Mat33RotXYZ,3);
	}else if("m33_yxz" == m){
		result = MatrixSub(info,Mat33EulerYXZ,9);
	}else if("m33_zxy" == m){
		result = MatrixSub(info,Mat33EulerZXY,9);
	}else if("m33_zyx" == m){
		result = MatrixSub(info,Mat33EulerZYX,9);
	}else if("m33_yzx" == m){
		result = MatrixSub(info,Mat33EulerYZX,9);
	}else if("m33_xzy" == m){
		result = MatrixSub(info,Mat33EulerXZY,9);
	}else if("m33_xyz" == m){
		result = MatrixSub(info,Mat33EulerXYZ,9);
	}else if("v3l" == m){
		result = MatrixSub(info,Vector3Length,3);
	}else if("v3n" == m){
		result = MatrixSub(info,Vector3Normalize,3);
	}

	if(result){
		return 0;
	}
	usage();

	return 1;
}
Exemple #8
0
//---------------------------------------------------------
//
//  Public: Write
//  
//  Action:  Write CMic to a file.
//
//---------------------------------------------------------
bool CMic::Write(const string &filename) const
{
  std::ofstream osOutFile;
  osOutFile.open( filename.c_str() );

  if( !osOutFile.good() )
    return false;

  osOutFile << fInitialSideLength << std::endl;
  
  // columns 1 -3: xyz location of left vertex of a triangle
  // column 4: 1/2 for triangle type -- 1 for upward pointing or 2 for downward
  // pointing
  // column 5: generation number -- triangle side length = a0/(2**generation),
  // generation = 0,1,2,...
  // column 6: 0/1 for phase -- 0 mean it wasn't (or hasn't yet) fitted to an
  // orientation, 1 means it was
  // columns 7 -9: Eulers in degrees
  // column 10: confidence parameter: fraction of simulated Bragg peaks that hit
  // experimental peaks
  
  for( Size_Type i = 0; i < oVoxelList.size(); i ++ )
  {
    Int nDir;
    Int nLeftMostVertex;

    //  Need to find the left most voxel
    //  to follow MIC files specification.
    nLeftMostVertex = GetLeftMostVertex( oVoxelList[i] );

    if ( oVoxelList[i].bVoxelPointsUp ){
      nDir = UP;
    }else{
      nDir = DOWN;
    }
    
    osOutFile << oVoxelList[i].pVertex[nLeftMostVertex].m_fX << " "
              << oVoxelList[i].pVertex[nLeftMostVertex].m_fY  << " "
              << oVoxelList[i].pVertex[nLeftMostVertex].m_fZ << " "

              << nDir << " "
              << oVoxelList[i].nGeneration << " "
              << oVoxelList[i].nPhase << " "
              << RadianToDegree( oVoxelList[i].oOrientMatrix.GetEulerAngles() ) << " "
              << oVoxelList[i].fConfidence
      
      //---------------------------------------------------------
      // newly added - to be put into property map
      //---------------------------------------------------------
              << " " << oVoxelList[i].fCost
              << " " << oVoxelList[i].fPixelOverlapRatio
              << " " << oVoxelList[i].fFittingTime
      
              << " " << oVoxelList[i].oDeformation.m[0][0]
              << " " << oVoxelList[i].oDeformation.m[1][1]
              << " " << oVoxelList[i].oDeformation.m[2][2]
              << " " << oVoxelList[i].oDeformation.m[1][0]
              << " " << oVoxelList[i].oDeformation.m[1][2]
              << " " << oVoxelList[i].oDeformation.m[2][0]
      
              << std::endl;;
  }

  osOutFile.close();

  return true;
}