/********插入元素************
** 参数 :pTreeNode root   //二叉排序树的根
		 int e   //要插入的元素
		 int pos //要插入元素的位置
*/
int Insert(pTreeNode root, int e, int pos)
{
	pTreeNode p = NULL ;
	FindedReturnValue value ;

	value = Find( root,  e);

	if(value.flag == 1)   //此数已经存在
	{
		value.tree->count++;
		AddPosition(value.tree, pos) ;	  
	}
	else  //未发现元素
	{
		p = (pTreeNode)calloc(1,sizeof(TreeNode));
		if( p == NULL ){
			perror("error in calloc in the func Insert()");
			return -1;
			}
		p->data = e;
		p->count = 1;
		AddPosition(p, pos) ;//构造节点

		if(value.tree->data < e)
			value.tree->right = p;
		else if(value.tree->data > e)
			value.tree->left = p;
	}
	return 1;
}
// --------------------------------------------------------------------------------
// Name        : AddRect
// Description : Add the given rect and updates anchor points
// --------------------------------------------------------------------------------
void CRectPlacement::AddRect  (const TRect &r)
{
  m_vRects.push_back(r);
  m_area += r.w*r.h;

  // Add two new anchor points
  AddPosition(TPos(r.x, r.y+r.h+m_margin));
  AddPosition(TPos(r.x+r.w+m_margin, r.y));
}
// gaussian elimination - main function
int WINAPI GaussianElimination(double ** ppMatrix, int iRows, int iColumns, GAUSSIAN_ELIMINATION_OUTPUT * pOutputBuffer)
{

	if(ppMatrix == NULL) {
		return -1;
	}

	if(pOutputBuffer->ppSMatrix != NULL) {
		iColumns += iRows;
	}
	SetMatrixDimensions(iRows, iColumns);
	double ** ppWorkMatrix;
	if(pOutputBuffer->ppSMatrix == NULL) {
		ppWorkMatrix = pOutputBuffer->ppReducedEcholonForm;
	} else {
		ppWorkMatrix = AllocateMatrixMemory(iColumns + iRows, iRows);
	}
	if(!ppWorkMatrix) {
		return -1;
	}

	if(pOutputBuffer->ppSMatrix != NULL) {
		for(int i = (iColumns - iRows); i < iColumns; i++) {
			for(int g = 0; g < iRows; g++) {
				if(g == i - iColumns + iRows) {
					ppWorkMatrix[i][g] = 1.0f;
				} else {
					ppWorkMatrix[i][g] = 0.0f;
				}
			}
		}
		CopyMatrix(ppWorkMatrix, ppMatrix, iRows, iColumns - iRows);
	} else {
		CopyMatrix(ppWorkMatrix, ppMatrix, iRows, iColumns);
	}

	POSITION posPivot = StepOne(ppWorkMatrix);
	//printf("%lf, %lf", ppWorkMatrix[0][0], ppWorkMatrix[0][1]);
	StepTwo(ppWorkMatrix, &posPivot);
	//printf("%lf, %lf", ppWorkMatrix[0][0], ppWorkMatrix[0][1]);
	if(StepThree(ppWorkMatrix, posPivot) != 0) {
		return -1;
	}
	//printf("%lf, %lf", ppWorkMatrix[0][0], ppWorkMatrix[0][1]);
	StepFour(ppWorkMatrix, posPivot);
	//printf("%lf, %lf", ppWorkMatrix[0][0], ppWorkMatrix[0][1]);
	POSITION_ARRAY pivots = StepFive(ppWorkMatrix, posPivot);
	//printf("%lf, %lf", ppWorkMatrix[0][0], ppWorkMatrix[0][1]);
	AddPosition(&pivots, posPivot);
	StepSix(ppWorkMatrix, pivots);
	//printf("%lf, %lf", ppWorkMatrix[0][0], ppWorkMatrix[0][1]);

	if(pOutputBuffer->ppSMatrix) {
		DivideOutputAndSMatrix(ppWorkMatrix, pOutputBuffer);
	} else {
		CopyMatrix(pOutputBuffer->ppReducedEcholonForm, ppWorkMatrix, iRows, iColumns);
	}

	return 0;
}
void MovableBuilder::MakeDefault ()
{
	AddPosition(VectorF());
	AddMovement(VectorF(0.0, 1.0), 0.0, 30.0);

	// Note that a body isn't created by default!
}
void PointCloud::AddPositions(const std::vector<FVector3>& positionsToAdd)
{
   for (const FVector3& position : positionsToAdd)
   {
      AddPosition(position);
   }
}
void WeatherRouting::AddPosition(double lat, double lon)
{
    wxTextEntryDialog pd( this, _("Enter Name"), _("New Position") );
    if(pd.ShowModal() == wxID_OK)
    {
        wxString name = pd.GetValue();
        for(std::list<RouteMapPosition>::iterator it = RouteMap::Positions.begin();
            it != RouteMap::Positions.end(); it++)
        {
            if((*it).Name == name)
            {
                wxMessageDialog mdlg(this, _("This name already exists, replace?\n"),
                                     _("Weather Routing"), wxYES | wxNO | wxICON_ERROR);
                if(mdlg.ShowModal() == wxID_YES)
                {
                    long index = m_lPositions->FindItem(0, name);
                    (*it).lat = lat;
                    (*it).lon = lon;
                    m_lPositions->SetItem(index, POSITION_LAT, wxString::Format(_T("%.5f"), lat));
                    m_lPositions->SetItem(index, POSITION_LON, wxString::Format(_T("%.5f"), lon));
                }

                UpdateConfigurations();
                return;
            }
        } // for
        AddPosition(lat, lon, name);
    }
}
void cFireworkEntity::HandlePhysics(float a_Dt, cChunk & a_Chunk)
{
	int RelX = POSX_TOINT - a_Chunk.GetPosX() * cChunkDef::Width;
	int RelZ = POSZ_TOINT - a_Chunk.GetPosZ() * cChunkDef::Width;
	int PosY = POSY_TOINT;

	if ((PosY < 0) || (PosY >= cChunkDef::Height))
	{
		goto setspeed;
	}

	if (m_IsInGround)
	{
		if (a_Chunk.GetBlock(RelX, POSY_TOINT + 1, RelZ) == E_BLOCK_AIR)
		{
			m_IsInGround = false;
		}
		else
		{
			return;
		}
	}
	else
	{
		if (a_Chunk.GetBlock(RelX, POSY_TOINT + 1, RelZ) != E_BLOCK_AIR)
		{
			OnHitSolidBlock(GetPosition(), BLOCK_FACE_YM);
			return;
		}
	}

setspeed:
	AddSpeedY(1);
	AddPosition(GetSpeed() * (a_Dt / 1000));
}
Exemple #8
0
 // ==================================================
 void Camera::MoveForward(MOVE_DIRECTION type)
 {
     float velocity = Global::cameraMoveSpeed * Global::delataTime;
     
     switch(type)
     {
         case MOVE_DIRECTION::FORWARD:
             AddPosition(m_front*velocity);
             break;
         case MOVE_DIRECTION::BACKWARD:
             AddPosition(-m_front*velocity);
             break;
         case MOVE_DIRECTION::RIGHT:
             AddPosition(m_right*velocity);
             break;
         case MOVE_DIRECTION::LEFT:
             AddPosition(-m_right*velocity);
             break;
         default:
             break;
     }
 }
Exemple #9
0
/*
================
sdGeneralMover::PostMapSpawn
================
*/
void sdGeneralMover::PostMapSpawn( void ) {
	sdScriptEntity::PostMapSpawn();

	const idKeyValue* kv = NULL;
	while ( kv = spawnArgs.MatchPrefix( "position_", kv ) ) {
		idEntity* other = gameLocal.FindEntity( kv->GetValue() );
		if ( !other ) {
			gameLocal.Warning( "sdGeneralMover::PostMapSpawn Couldn't Find Entity '%s'", kv->GetValue().c_str() );
			continue;
		}

		AddPosition( other->GetPhysics()->GetOrigin(), other->GetPhysics()->GetAxis().ToAngles() );
	}
}
	void ProjectileArc::Move(float gravity)
	{
		switch( moveType )
		{
		case ARC:
				AddPosition(velocity);
				model->AddPosition(velocity);
				velocity.y -= gravity;
				break;
		default: 
			std::cout << "Unknown Projectile Type\n";
			break;
		}
	}
Exemple #11
0
/** Update this game object by updating position, velocity and angle of object. */
void GameObject::Update(int t)
{
	// Calculate seconds since last update
	float dt = t / 1000.0f;
	// Update angle
	AddAngle(mRotation * dt);
	// Update position
	AddPosition(mVelocity * dt);
	// Update velocity
	AddVelocity(mAcceleration * dt);
	// Update sprite if one exists
	if (mSprite.GetPtr() != NULL) mSprite->Update(t);
	// If in world, wrap position const int zl = mGameWindow->GetZoomLevel();
	if (mWorld) { mWorld->WrapXY(mPosition.x, mPosition.y); }
}
Exemple #12
0
void WeatherRouting::OnNewPosition( wxCommandEvent& event )
{
    wxTextEntryDialog pd( this, _("Enter Latitude"), _("New Position") );
    if(pd.ShowModal() == wxID_OK)
    {
        wxString latitude = pd.GetValue();

        wxTextEntryDialog pd( this, _("Enter Longitude"), _("New Position") );
        if(pd.ShowModal() == wxID_OK)
        {
            wxString longitude = pd.GetValue();

            double lat, lon;
            latitude.ToDouble(&lat);
            longitude.ToDouble(&lon);
            AddPosition(lat, lon);
        }
    }
}
Exemple #13
0
void WeatherRouting::OnUpdateBoat( wxCommandEvent& event )
{
    double lat = m_weather_routing_pi.m_boat_lat;
    double lon = m_weather_routing_pi.m_boat_lon;

    long index = 0;
    for(std::list<RouteMapPosition>::iterator it = RouteMap::Positions.begin();
        it != RouteMap::Positions.end(); it++, index++)
        if((*it).Name == _("Boat"))
        {
            m_lPositions->SetItem(index, POSITION_LAT, wxString::Format(_T("%.5f"), lat));
            m_lPositions->SetItem(index, POSITION_LON, wxString::Format(_T("%.5f"), lon));

            (*it).lat = lat, (*it).lon = lon;
            UpdateConfigurations();
            return;
        }

    AddPosition(lat, lon, _("Boat"));
}
Exemple #14
0
void csMeshGeneratorGeometry::ResetManualPositions (int new_celldim)
{
  if (celldim == new_celldim)
    return;

  csArray<csVector2> tmp_pos;
  for (int i = 0; i < celldim; i++)
  {
    for (size_t j = 0; j < positions[i].GetSize (); j++)
    {
      tmp_pos.Push (positions[i][j]);
    }
  }

  delete[] positions;

  celldim = new_celldim;
  positions = new csArray<csVector2> [celldim*celldim];

  for (size_t i = 0; i < tmp_pos.GetSize (); i++)
  {
    AddPosition (tmp_pos[i]);
  }
}
Exemple #15
0
void csMeshGeneratorGeometry::AddPositionsFromMap (iTerraFormer* map,
	const csBox2 &region, uint resx, uint resy, float value,
	const csStringID & type)
{
  csRef<iTerraSampler> sampler = map->GetSampler (region, resx, resy);
  float stepx = (region.MaxX () - region.MinX ())/resx;
  float stepy = (region.MaxY () - region.MinY ())/resy;

  const float* map_values = sampler->SampleFloat (type);
  float curx = region.MinX (), cury = region.MinY ();
  for (uint i = 0; i < resx; i++)
  {
    for (uint j = 0; j < resy; j++)
    {
      if (map_values[i*resx + j] == value)
      {
        AddPosition (csVector2 (curx, cury));
      }
      curx += stepx;
    }
    curx = region.MinX ();
    cury += stepy;
  }
}
Exemple #16
0
void cFallingBlock::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
	// GetWorld()->BroadcastTeleportEntity(*this);  // Test position
	
	int BlockX = POSX_TOINT;
	int BlockY = (int)(GetPosY() - 0.5);
	int BlockZ = POSZ_TOINT;
	
	if (BlockY < 0)
	{
		// Fallen out of this world, just continue falling until out of sight, then destroy:
		if (BlockY < VOID_BOUNDARY)
		{
			Destroy(true);
		}
		return;
	}
	
	if (BlockY >= cChunkDef::Height)
	{
		// Above the world, just wait for it to fall back down
		return;
	}
	
	BLOCKTYPE BlockBelow = a_Chunk.GetBlock(BlockX - a_Chunk.GetPosX() * cChunkDef::Width, BlockY, BlockZ - a_Chunk.GetPosZ() * cChunkDef::Width);
	NIBBLETYPE BelowMeta = a_Chunk.GetMeta(BlockX - a_Chunk.GetPosX() * cChunkDef::Width, BlockY, BlockZ - a_Chunk.GetPosZ() * cChunkDef::Width);
	if (cSandSimulator::DoesBreakFallingThrough(BlockBelow, BelowMeta))
	{
		// Fallen onto a block that breaks this into pickups (e. g. half-slab)
		// Must finish the fall with coords one below the block:
		cSandSimulator::FinishFalling(m_World, BlockX, BlockY, BlockZ, m_BlockType, m_BlockMeta);
		Destroy(true);
		return;
	}
	else if (!cSandSimulator::CanContinueFallThrough(BlockBelow))
	{
		// Fallen onto a solid block
		/*
		LOGD(
			"Sand: Checked below at {%d, %d, %d} (rel {%d, %d, %d}), it's %s, finishing the fall.",
			BlockX, BlockY, BlockZ,
			BlockX - a_Chunk.GetPosX() * cChunkDef::Width, BlockY, BlockZ - a_Chunk.GetPosZ() * cChunkDef::Width,
			ItemTypeToString(BlockBelow).c_str()
		);
		*/

		if (BlockY < cChunkDef::Height - 1)
		{
			cSandSimulator::FinishFalling(m_World, BlockX, BlockY + 1, BlockZ, m_BlockType, m_BlockMeta);
		}
		Destroy(true);
		return;
	}
	
	float MilliDt = a_Dt.count() * 0.001f;
	AddSpeedY(MilliDt * -9.8f);
	AddPosition(GetSpeed() * MilliDt);

	// If not static (one billionth precision) broadcast movement
	if ((fabs(GetSpeedX()) > std::numeric_limits<double>::epsilon()) || (fabs(GetSpeedZ()) > std::numeric_limits<double>::epsilon()))
	{
		BroadcastMovementUpdate();
	}
}
Exemple #17
0
void cEntity::HandlePhysics(float a_Dt, cChunk & a_Chunk)
{
	int BlockX = POSX_TOINT;
	int BlockY = POSY_TOINT;
	int BlockZ = POSZ_TOINT;

	// Position changed -> super::HandlePhysics() called
	GET_AND_VERIFY_CURRENT_CHUNK(NextChunk, BlockX, BlockZ)

	// TODO Add collision detection with entities.
	a_Dt /= 1000;  // Convert from msec to sec
	Vector3d NextPos = Vector3d(GetPosX(), GetPosY(), GetPosZ());
	Vector3d NextSpeed = Vector3d(GetSpeedX(), GetSpeedY(), GetSpeedZ());
	
	if ((BlockY >= cChunkDef::Height) || (BlockY < 0))
	{
		// Outside of the world		
		AddSpeedY(m_Gravity * a_Dt);
		AddPosition(GetSpeed() * a_Dt);
		return;
	}
	
	int RelBlockX = BlockX - (NextChunk->GetPosX() * cChunkDef::Width);
	int RelBlockZ = BlockZ - (NextChunk->GetPosZ() * cChunkDef::Width);
	BLOCKTYPE BlockIn = NextChunk->GetBlock( RelBlockX, BlockY, RelBlockZ );
	BLOCKTYPE BlockBelow = (BlockY > 0) ? NextChunk->GetBlock(RelBlockX, BlockY - 1, RelBlockZ) : E_BLOCK_AIR;
	if (!cBlockInfo::IsSolid(BlockIn))  // Making sure we are not inside a solid block
	{
		if (m_bOnGround)  // check if it's still on the ground
		{
			if (!cBlockInfo::IsSolid(BlockBelow))  // Check if block below is air or water.
			{
				m_bOnGround = false;
			}
		}
	}
	else
	{
		// Push out entity.
		BLOCKTYPE GotBlock;

		static const struct
		{
			int x, y, z;
		} gCrossCoords[] =
		{
			{ 1, 0,  0},
			{-1, 0,  0},
			{ 0, 0,  1},
			{ 0, 0, -1},
		} ;

		bool IsNoAirSurrounding = true;
		for (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++)
		{
			if (!NextChunk->UnboundedRelGetBlockType(RelBlockX + gCrossCoords[i].x, BlockY, RelBlockZ + gCrossCoords[i].z, GotBlock))
			{
				// The pickup is too close to an unloaded chunk, bail out of any physics handling
				return;
			}
			if (!cBlockInfo::IsSolid(GotBlock))
			{
				NextPos.x += gCrossCoords[i].x;
				NextPos.z += gCrossCoords[i].z;
				IsNoAirSurrounding = false;
				break;
			}
		}  // for i - gCrossCoords[]
			
		if (IsNoAirSurrounding)
		{
			NextPos.y += 0.5;
		}

		m_bOnGround = true;

		/*
		// DEBUG:
		LOGD("Entity #%d (%s) is inside a block at {%d, %d, %d}",
			m_UniqueID, GetClass(), BlockX, BlockY, BlockZ
		);
		*/
	}

	if (!m_bOnGround)
	{
		float fallspeed;
		if (IsBlockWater(BlockIn))
		{
			fallspeed = m_Gravity * a_Dt / 3;  // Fall 3x slower in water.
		}
		else if (BlockIn == E_BLOCK_COBWEB)
		{
			NextSpeed.y *= 0.05;  // Reduce overall falling speed
			fallspeed = 0;  // No falling.
		}
		else
		{
			// Normal gravity
			fallspeed = m_Gravity * a_Dt;
		}
		NextSpeed.y += fallspeed;
	}
	else
	{
		// Friction
		if (NextSpeed.SqrLength() > 0.0004f)
		{
			NextSpeed.x *= 0.7f / (1 + a_Dt);
			if (fabs(NextSpeed.x) < 0.05)
			{
				NextSpeed.x = 0;
			}
			NextSpeed.z *= 0.7f / (1 + a_Dt);
			if (fabs(NextSpeed.z) < 0.05)
			{
				NextSpeed.z = 0;
			}
		}
	}

	// Adjust X and Z speed for COBWEB temporary. This speed modification should be handled inside block handlers since we
	// might have different speed modifiers according to terrain.
	if (BlockIn == E_BLOCK_COBWEB)
	{
		NextSpeed.x *= 0.25;
		NextSpeed.z *= 0.25;
	}
					
	//Get water direction
	Direction WaterDir = m_World->GetWaterSimulator()->GetFlowingDirection(BlockX, BlockY, BlockZ);

	m_WaterSpeed *= 0.9f;		//Reduce speed each tick

	switch(WaterDir)
	{
		case X_PLUS:
			m_WaterSpeed.x = 0.2f;
			m_bOnGround = false;
			break;
		case X_MINUS:
			m_WaterSpeed.x = -0.2f;
			m_bOnGround = false;
			break;
		case Z_PLUS:
			m_WaterSpeed.z = 0.2f;
			m_bOnGround = false;
			break;
		case Z_MINUS:
			m_WaterSpeed.z = -0.2f;
			m_bOnGround = false;
			break;
			
	default:
		break;
	}

	if (fabs(m_WaterSpeed.x) < 0.05)
	{
		m_WaterSpeed.x = 0;
	}

	if (fabs(m_WaterSpeed.z) < 0.05)
	{
		m_WaterSpeed.z = 0;
	}

	NextSpeed += m_WaterSpeed;

	if (NextSpeed.SqrLength() > 0.f)
	{
		cTracer Tracer(GetWorld());
		// Distance traced is an integer, so we round up from the distance we should go (Speed * Delta), else we will encounter collision detection failurse
		int DistanceToTrace = (int)(ceil((NextSpeed * a_Dt).SqrLength()) * 2);
		bool HasHit = Tracer.Trace(NextPos, NextSpeed, DistanceToTrace);

		if (HasHit)
		{
			// Oh noez! We hit something: verify that the (hit position - current) was smaller or equal to the (position that we should travel without obstacles - current)
			// This is because previously, we traced with a length that was rounded up (due to integer limitations), and in the case that something was hit, we don't want to overshoot our projected movement
			if ((Tracer.RealHit - NextPos).SqrLength() <= (NextSpeed * a_Dt).SqrLength())
			{
				// Block hit was within our projected path
				// Begin by stopping movement in the direction that we hit something. The Normal is the line perpendicular to a 2D face and in this case, stores what block face was hit through either -1 or 1.
				// For example: HitNormal.y = -1 : BLOCK_FACE_YM; HitNormal.y = 1 : BLOCK_FACE_YP
				if (Tracer.HitNormal.x != 0.f) NextSpeed.x = 0.f;
				if (Tracer.HitNormal.y != 0.f) NextSpeed.y = 0.f;
				if (Tracer.HitNormal.z != 0.f) NextSpeed.z = 0.f;

				if (Tracer.HitNormal.y == 1) // Hit BLOCK_FACE_YP, we are on the ground
				{
					m_bOnGround = true;
				}

				// Now, set our position to the hit block (i.e. move part way along our intended trajectory)
				NextPos.Set(Tracer.RealHit.x, Tracer.RealHit.y, Tracer.RealHit.z);
				NextPos.x += Tracer.HitNormal.x * 0.1;
				NextPos.y += Tracer.HitNormal.y * 0.05;
				NextPos.z += Tracer.HitNormal.z * 0.1;
			}
			else
			{
				// We have hit a block but overshot our intended trajectory, move normally, safe in the warm cocoon of knowledge that we won't appear to teleport forwards on clients,
				// and that this piece of software will come to be hailed as the epitome of performance and functionality in C++, never before seen, and of such a like that will never
				// be henceforth seen again in the time of programmers and man alike
				// </&sensationalist>
				NextPos += (NextSpeed * a_Dt);
			}
		}
		else
		{
			// We didn't hit anything, so move =]
			NextPos += (NextSpeed * a_Dt);
		}
	}

	SetPosition(NextPos);
	SetSpeed(NextSpeed);
}
BOOL CPolygon::AddPositions(SFloat3* psPos1, SFloat3* psPos2, SFloat3* psPos3)
{
	ReturnOnFalse(AddPosition(psPos1));
	ReturnOnFalse(AddPosition(psPos2));
	return AddPosition(psPos3);
}
Exemple #19
0
/*
============
sdGeneralMover::Event_AddPosition
============
*/
void sdGeneralMover::Event_AddPosition( const idVec3& pos, const idAngles& dir ) {
	sdProgram::ReturnInteger( AddPosition( pos, dir ) );
}
Exemple #20
0
bool WeatherRouting::OpenXML(wxString filename, bool reportfailure)
{
    TiXmlDocument doc;
    wxString error;

    wxFileName fn(filename);

    SetTitle(_("Weather Routing") + wxString(_T(" - ")) + fn.GetFullName());

    wxProgressDialog *progressdialog = NULL;
    wxDateTime start = wxDateTime::Now();

    if(!doc.LoadFile(filename.mb_str()))
        FAIL(_("Failed to load file."));
    else
    {
        TiXmlHandle root(doc.RootElement());

        if(strcmp(root.Element()->Value(), "OpenCPNWeatherRoutingConfiguration"))
            FAIL(_("Invalid xml file"));

        RouteMap::Positions.clear();

        int count = 0;
        for(TiXmlElement* e = root.FirstChild().Element(); e; e = e->NextSiblingElement())
            count++;

        int i=0;
        for(TiXmlElement* e = root.FirstChild().Element(); e; e = e->NextSiblingElement(), i++)
        {
            if(progressdialog)
            {
                if(!progressdialog->Update(i))
                    return true;
            } else {
                wxDateTime now = wxDateTime::Now();
                /* if it's going to take more than a half second, show a progress dialog */
                if((now-start).GetMilliseconds() > 250 && i < count/2)
                {
                    progressdialog = new wxProgressDialog(
                        _("Load"), _("Weather Routing"), count, this,
                        wxPD_CAN_ABORT | wxPD_ELAPSED_TIME | wxPD_REMAINING_TIME);
                }
            }

            if(!strcmp(e->Value(), "Position"))
            {
                wxString name = wxString::FromUTF8(e->Attribute("Name"));
                double lat = AttributeDouble(e, "Latitude", NAN);
                double lon = AttributeDouble(e, "Longitude", NAN);

                for(std::list<RouteMapPosition>::iterator it = RouteMap::Positions.begin();
                    it != RouteMap::Positions.end(); it++)
                {
                    if((*it).Name == name)
                    {
                        static bool warnonce = true;
                        if(warnonce)
                        {
                            warnonce = false;
                            wxMessageDialog mdlg(this, _("File contains duplicate position name, discaring\n"),
                                                _("Weather Routing"), wxOK | wxICON_WARNING);
                            mdlg.ShowModal();
                        }

                        goto skipadd;
                    }
                }
                AddPosition(lat, lon, name);

            } else
skipadd:
                if(!strcmp(e->Value(), "Configuration"))
                {
                    RouteMapConfiguration configuration;
                    configuration.Start = wxString::FromUTF8(e->Attribute("Start"));
                    wxDateTime date;
                    date.ParseDate(wxString::FromUTF8(e->Attribute("StartDate")));
                    wxDateTime time;
                    time.ParseTime(wxString::FromUTF8(e->Attribute("StartTime")));
                    if(date.IsValid())
                    {
                        if(time.IsValid())
                        {
                            date.SetHour(time.GetHour());
                            date.SetMinute(time.GetMinute());
                            date.SetSecond(time.GetSecond());
                        }
                        configuration.StartTime = date;
                    } else
                        configuration.StartTime = wxDateTime::Now();

                    configuration.End = wxString::FromUTF8(e->Attribute("End"));
                    configuration.dt = AttributeDouble(e, "dt", 0);

                    configuration.boatFileName = wxString::FromUTF8(e->Attribute("Boat"));

                    configuration.MaxDivertedCourse = AttributeDouble(e, "MaxDivertedCourse", 180);
                    configuration.MaxWindKnots = AttributeDouble(e, "MaxWindKnots", 100);
                    configuration.MaxSwellMeters = AttributeDouble(e, "MaxSwellMeters", 20);
                    configuration.MaxLatitude = AttributeDouble(e, "MaxLatitude", 90);
                    configuration.MaxTacks = AttributeDouble(e, "MaxTacks", -1);
                    configuration.TackingTime = AttributeDouble(e, "TackingTime", 0);

                    configuration.UseGrib = AttributeBool(e, "UseGrib", true);
                    configuration.UseClimatology = AttributeBool(e, "UseClimatology", true);
                    configuration.AllowDataDeficient = AttributeBool(e, "AllowDataDeficient", false);
                    configuration.DetectLand = AttributeBool(e, "DetectLand", true);
                    configuration.Currents = AttributeBool(e, "Currents", true);
                    configuration.InvertedRegions = AttributeBool(e, "InvertedRegions", false);
                    configuration.Anchoring = AttributeBool(e, "Anchoring", false);

                    wxString degreesteps = wxString::FromUTF8(e->Attribute("DegreeSteps"));
                    while(degreesteps.size())
                    {
                        double step;
                        if(degreesteps.BeforeFirst(';').ToDouble(&step))
                            configuration.DegreeSteps.push_back(step);
                        degreesteps = degreesteps.AfterFirst(';');
                    }
                    configuration.StartTime = date;
                } else
                    FAIL(_("Unrecognized xml node"));
        }
    }
    delete progressdialog;
    return true;
failed:

    if(reportfailure)
    {
        wxMessageDialog mdlg(this, error, _("Weather Routing"), wxOK | wxICON_ERROR);
        mdlg.ShowModal();
    }
    return false;
}
static POSITION_ARRAY StepFive(double ** ppMatrix, POSITION posPivot)
{
	POSITION_ARRAY pivots = {NULL, 0};
	int iRowsSave = iRows;
	int iColumnsSave = iColumns;

	if(iRows - 1 == 0) {
		return pivots; // Fertig
	}

	if(iColumns - posPivot.iColumn == 0) {
		return pivots; // Fertig
	}
	
	double ** ppSmallerMatrix = AllocateMatrixMemory(iColumns - posPivot.iColumn - 1, iRows - 1);

	for(int i = posPivot.iColumn + 1; i < iColumns; i++) {
		for(int g = 1; g < iRows; g++) {
			ppSmallerMatrix[i - posPivot.iColumn - 1][g - 1] = ppMatrix[i][g];
		}
	}

	iRows--; 
	iRowsOffset++;
	iColumns -= posPivot.iColumn + 1;
	iColumnsOffset += posPivot.iColumn + 1;

	POSITION posNewPivot = StepOne(ppSmallerMatrix);
	if(posNewPivot.iColumn == -1) {
		// Rücksetzen
		iRowsOffset -= (iRowsSave - iRows);
		iRows = iRowsSave;
		iRowsOffset -= (iColumnsSave - iColumns);
		iColumns = iColumnsSave;
		return pivots; // Fertig
	}
	
	StepTwo(ppSmallerMatrix, &posNewPivot);
	StepThree(ppSmallerMatrix, posNewPivot);
	StepFour(ppSmallerMatrix, posNewPivot);
	pivots = StepFive(ppSmallerMatrix, posNewPivot);

	AddPosition(&pivots, posNewPivot);

	for(int i = 0; i < pivots.iCount; i++) {
		pivots.pPositions[i].iColumn += posPivot.iColumn + 1; // Auf neue Grösse anpassen
		pivots.pPositions[i].iRow += 1;
	}

	// Rücksetzen
	iRowsOffset -= (iRowsSave - iRows);
	iRows = iRowsSave;
	iColumnsOffset -= (iColumnsSave - iColumns);
	iColumns = iColumnsSave;

	// Eingruppieren der neuen Matrix
	for(int i = posPivot.iColumn + 1; i < iColumns; i++) {
		for(int g = 1; g < iRows; g++) {
			ppMatrix[i][g] = ppSmallerMatrix[i - posPivot.iColumn - 1][g - 1];
		}
	}

	// Freigeben des Speichers
	FreeMatrixMemory(ppSmallerMatrix, iColumns - posPivot.iColumn - 1);

	return pivots;
}
void MovableBuilder::AddPosition (float x, float y)
{
	AddPosition(VectorF(x, y));
}
Exemple #23
0
void cMinecart::HandlePhysics(float a_Dt, cChunk & a_Chunk)
{
    if (IsDestroyed())  // Mainly to stop detector rails triggering again after minecart is dead
    {
        return;
    }

    int PosY = POSY_TOINT;
    if ((PosY <= 0) || (PosY >= cChunkDef::Height))
    {
        // Outside the world, just process normal falling physics
        super::HandlePhysics(a_Dt, a_Chunk);
        BroadcastMovementUpdate();
        return;
    }

    int RelPosX = POSX_TOINT - a_Chunk.GetPosX() * cChunkDef::Width;
    int RelPosZ = POSZ_TOINT - a_Chunk.GetPosZ() * cChunkDef::Width;
    cChunk * Chunk = a_Chunk.GetRelNeighborChunkAdjustCoords(RelPosX, RelPosZ);
    if (Chunk == NULL)
    {
        // Inside an unloaded chunk, bail out all processing
        return;
    }

    BLOCKTYPE InsideType;
    NIBBLETYPE InsideMeta;
    Chunk->GetBlockTypeMeta(RelPosX, PosY, RelPosZ, InsideType, InsideMeta);

    if (!IsBlockRail(InsideType))
    {
        Chunk->GetBlockTypeMeta(RelPosX, PosY + 1, RelPosZ, InsideType, InsideMeta);  // When an descending minecart hits a flat rail, it goes through the ground; check for this
        if (IsBlockRail(InsideType)) AddPosY(1);  // Push cart upwards
    }

    bool WasDetectorRail = false;
    if (IsBlockRail(InsideType))
    {
        if (InsideType == E_BLOCK_RAIL)
        {
            SnapToRail(InsideMeta);
        }
        else
        {
            SnapToRail(InsideMeta & 0x07);
        }

        switch (InsideType)
        {
        case E_BLOCK_RAIL:
            HandleRailPhysics(InsideMeta, a_Dt);
            break;
        case E_BLOCK_ACTIVATOR_RAIL:
            break;
        case E_BLOCK_POWERED_RAIL:
            HandlePoweredRailPhysics(InsideMeta);
            break;
        case E_BLOCK_DETECTOR_RAIL:
        {
            HandleDetectorRailPhysics(InsideMeta, a_Dt);
            WasDetectorRail = true;
            break;
        }
        default:
            VERIFY(!"Unhandled rail type despite checking if block was rail!");
            break;
        }

        AddPosition(GetSpeed() * (a_Dt / 1000));  // Commit changes; as we use our own engine when on rails, this needs to be done, whereas it is normally in Entity.cpp
    }
    else
    {
        // Not on rail, default physics
        SetPosY(floor(GetPosY()) + 0.35);  // HandlePhysics overrides this if minecart can fall, else, it is to stop ground clipping minecart bottom when off-rail
        super::HandlePhysics(a_Dt, *Chunk);
    }

    if (m_bIsOnDetectorRail && !Vector3i(POSX_TOINT, POSY_TOINT, POSZ_TOINT).Equals(m_DetectorRailPosition))
    {
        m_World->SetBlock(m_DetectorRailPosition.x, m_DetectorRailPosition.y, m_DetectorRailPosition.z, E_BLOCK_DETECTOR_RAIL, m_World->GetBlockMeta(m_DetectorRailPosition) & 0x07);
        m_bIsOnDetectorRail = false;
    }
    else if (WasDetectorRail)
    {
        m_bIsOnDetectorRail = true;
        m_DetectorRailPosition = Vector3i(POSX_TOINT, POSY_TOINT, POSZ_TOINT);
    }

    // Broadcast positioning changes to client
    BroadcastMovementUpdate();
}
void Ship::AddPosition(char x, char y)
{
	AddPosition(Point(x, y));
}