AFlareSpacecraft* UFlareSpacecraftNavigationSystem::GetNearestShip(AFlareSpacecraft* DockingStation) const
{
	// For now an host ship is a the nearest host ship with the following critera:
	// - Alive or not
	// - From any company
	// - Is the nearest
	// - Is not me

	FVector PilotLocation = Spacecraft->GetActorLocation();
	float MinDistanceSquared = -1;
	AFlareSpacecraft* NearestShip = NULL;

	for (int32 SpacecraftIndex = 0; SpacecraftIndex < Spacecraft->GetGame()->GetActiveSector()->GetSpacecrafts().Num(); SpacecraftIndex++)
	{
		AFlareSpacecraft* ShipCandidate = Spacecraft->GetGame()->GetActiveSector()->GetSpacecrafts()[SpacecraftIndex];

		if (ShipCandidate != Spacecraft && ShipCandidate != DockingStation)
		{

			if (DockingStation && (DockingStation->GetDockingSystem()->IsGrantedShip(ShipCandidate) || DockingStation->GetDockingSystem()->IsDockedShip(ShipCandidate)))
			{
				// Ignore ship docked or docking at the same station
				continue;
			}

			float DistanceSquared = (PilotLocation - ShipCandidate->GetActorLocation()).SizeSquared();

			if (NearestShip == NULL || DistanceSquared < MinDistanceSquared)
			{
				MinDistanceSquared = DistanceSquared;
				NearestShip = ShipCandidate;
			}
		}
	}
	return NearestShip;
}
void UFlareAsteroidComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
	float CollisionSize = GetCollisionShape().GetExtent().Size();
	EffectsUpdateTimer += DeltaTime;

	// Get player ship
	AFlareGame* Game = Cast<AFlareGame>(GetWorld()->GetAuthGameMode());
	FCHECK(Game);
	AFlarePlayerController* PC = Game->GetPC();
	FCHECK(PC);
	AFlareSpacecraft* ShipPawn = PC->GetShipPawn();

	// Update if close to player and visible
	if (ShipPawn
	 && (ShipPawn->GetActorLocation() - GetComponentLocation()).Size() < 500000
	 && (GetWorld()->TimeSeconds - LastRenderTime) < 0.5)
	{
		if (EffectsUpdateTimer > EffectsUpdatePeriod)
		{
			// World data
			FVector AsteroidLocation = GetComponentLocation();
			FVector SunDirection = Game->GetPlanetarium()->GetSunDirection();
			SunDirection.Normalize();
	
			// Compute new FX locations
			for (int32 Index = 0; Index < Effects.Num(); Index++)
			{
				FVector RandomDirection = FVector::CrossProduct(SunDirection, EffectsKernels[Index]);
				RandomDirection.Normalize();
				FVector StartPoint = AsteroidLocation + RandomDirection * CollisionSize;

				// Trace params
				FHitResult HitResult(ForceInit);
				FCollisionQueryParams TraceParams(FName(TEXT("Asteroid Trace")), false, NULL);
				TraceParams.bTraceComplex = true;
				TraceParams.bReturnPhysicalMaterial = false;
				ECollisionChannel CollisionChannel = ECollisionChannel::ECC_WorldDynamic;

				// Trace
				bool FoundHit = GetWorld()->LineTraceSingleByChannel(HitResult, StartPoint, AsteroidLocation, CollisionChannel, TraceParams);
				if (FoundHit && HitResult.Component == this && Effects[Index])
				{
					FVector EffectLocation = HitResult.Location;

					if (!Effects[Index]->IsActive())
					{
						Effects[Index]->Activate();
					}
					Effects[Index]->SetWorldLocation(EffectLocation);
					Effects[Index]->SetWorldRotation(SunDirection.Rotation());
				}
				else
				{
					Effects[Index]->Deactivate();
				}
			}

			EffectsUpdateTimer = 0;
		}
	}

	// Disable all
	else
	{
		for (int32 Index = 0; Index < Effects.Num(); Index++)
		{
			Effects[Index]->Deactivate();
		}
	}
}
AFlareSpacecraft* UFlareSector::LoadSpacecraft(UFlareSimulatedSpacecraft* ParentSpacecraft)
{
	AFlareSpacecraft* Spacecraft = NULL;
	FLOGV("UFlareSector::LoadSpacecraft : Start loading ('%s')", *ParentSpacecraft->GetImmatriculation().ToString());


	// Spawn parameters
	FActorSpawnParameters Params;
	Params.bNoFail = true;
	Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;



	// Create and configure the ship
	Spacecraft = GetGame()->GetWorld()->SpawnActor<AFlareSpacecraft>(ParentSpacecraft->GetDescription()->Template->GeneratedClass, ParentSpacecraft->GetData().Location, ParentSpacecraft->GetData().Rotation, Params);
	if (Spacecraft && !Spacecraft->IsPendingKillPending())
	{
		Spacecraft->Load(ParentSpacecraft);
		UPrimitiveComponent* RootComponent = Cast<UPrimitiveComponent>(Spacecraft->GetRootComponent());

		if (Spacecraft->IsStation())
		{
			SectorStations.Add(Spacecraft);
		}
		else
		{
			SectorShips.Add(Spacecraft);
		}
		SectorSpacecrafts.Add(Spacecraft);

		FLOGV("%s spawn mode = %d", *Spacecraft->GetImmatriculation().ToString(), ParentSpacecraft->GetData().SpawnMode+0)


		switch (ParentSpacecraft->GetData().SpawnMode)
		{
			// Already known to be correct
			case EFlareSpawnMode::Safe:

				FLOGV("UFlareSector::LoadSpacecraft : Safe spawn '%s' at (%f,%f,%f)",
					*ParentSpacecraft->GetImmatriculation().ToString(),
					ParentSpacecraft->GetData().Location.X, ParentSpacecraft->GetData().Location.Y, ParentSpacecraft->GetData().Location.Z);

				RootComponent->SetPhysicsLinearVelocity(ParentSpacecraft->GetData().LinearVelocity, false);
				RootComponent->SetPhysicsAngularVelocity(ParentSpacecraft->GetData().AngularVelocity, false);
				break;

			// First spawn
			case EFlareSpawnMode::Spawn:

				PlaceSpacecraft(Spacecraft, ParentSpacecraft->GetData().Location);
				{
					FVector NewLocation = Spacecraft->GetActorLocation();
					FLOGV("UFlareSector::LoadSpacecraft : Placing '%s' at (%f,%f,%f)",
						*ParentSpacecraft->GetImmatriculation().ToString(),
						NewLocation.X, NewLocation.Y, NewLocation.Z);
				}

				RootComponent->SetPhysicsLinearVelocity(FVector::ZeroVector, false);
				RootComponent->SetPhysicsAngularVelocity(FVector::ZeroVector, false);
				break;

			// Incoming in sector
			case EFlareSpawnMode::Travel:
			{

				FLOGV("UFlareSector::LoadSpacecraft : Travel '%s' at (%f, %f, %f)",
					*ParentSpacecraft->GetImmatriculation().ToString(),
					ParentSpacecraft->GetData().Location.X, ParentSpacecraft->GetData().Location.Y, ParentSpacecraft->GetData().Location.Z);

				FVector SpawnDirection;
				TArray<AFlareSpacecraft*> FriendlySpacecrafts = GetCompanySpacecrafts(Spacecraft->GetCompany());
				FVector FriendlyShipLocationSum = FVector::ZeroVector;
				int FriendlyShipCount = 0;

				for (int SpacecraftIndex = 0 ; SpacecraftIndex < FriendlySpacecrafts.Num(); SpacecraftIndex++)
				{
					AFlareSpacecraft *SpacecraftCandidate = FriendlySpacecrafts[SpacecraftIndex];
					if (!SpacecraftCandidate->IsStation() && SpacecraftCandidate != Spacecraft)
					{
						FriendlyShipLocationSum += SpacecraftCandidate->GetActorLocation();
						FriendlyShipCount++;
					}
				}

				if (FriendlyShipCount == 0)
				{
					FVector NotFriendlyShipLocationSum = FVector::ZeroVector;
					int NotFriendlyShipCount = 0;
					for (int SpacecraftIndex = 0 ; SpacecraftIndex < SectorShips.Num(); SpacecraftIndex++)
					{
						AFlareSpacecraft *SpacecraftCandidate = SectorShips[SpacecraftIndex];
						if (SpacecraftCandidate != Spacecraft && SpacecraftCandidate->GetCompany() != Spacecraft->GetCompany())
						{
							NotFriendlyShipLocationSum += SpacecraftCandidate->GetActorLocation();
							NotFriendlyShipCount++;
						}
					}

					if (NotFriendlyShipCount == 0)
					{
						SpawnDirection = FMath::VRand();
					}
					else
					{
						FVector	NotFriendlyShipLocationMean = NotFriendlyShipLocationSum / NotFriendlyShipCount;
						SpawnDirection = (GetSectorCenter() - NotFriendlyShipLocationMean).GetUnsafeNormal();
					}
				}
				else
				{
					FVector	FriendlyShipLocationMean = FriendlyShipLocationSum / FriendlyShipCount;
					SpawnDirection = (FriendlyShipLocationMean - GetSectorCenter()).GetUnsafeNormal() ;
				}

				float SpawnDistance = GetSectorRadius() + 1;

				if (GetSimulatedSector()->GetSectorBattleState(Spacecraft->GetCompany()) != EFlareSectorBattleState::NoBattle)
				{
					SpawnDistance += 500000; // 5 km
				}

				SpawnDistance = FMath::Min(SpawnDistance, GetSectorLimits());

				FVector Location = GetSectorCenter() + SpawnDirection * SpawnDistance;

				FVector CenterDirection = (GetSectorCenter() - Location).GetUnsafeNormal();
				Spacecraft->SetActorRotation(CenterDirection.Rotation());

				PlaceSpacecraft(Spacecraft, Location);

				float SpawnVelocity = 0;

				if (GetSimulatedSector()->GetSectorBattleState(Spacecraft->GetCompany()) != EFlareSectorBattleState::NoBattle)
				{
						SpawnVelocity = 10000;
				}

				RootComponent->SetPhysicsLinearVelocity(CenterDirection * SpawnVelocity, false);
				RootComponent->SetPhysicsAngularVelocity(FVector::ZeroVector, false);
			}
			break;
			case EFlareSpawnMode::Exit:
			{
				float SpawnDistance = GetSectorLimits() * 0.9;
				float SpawnVelocity = ParentSpacecraft->GetData().LinearVelocity.Size() * 0.6;
				FVector SpawnDirection = ParentSpacecraft->GetData().Location.GetUnsafeNormal();
				FVector Location = SpawnDirection * SpawnDistance;
				FVector CenterDirection = (GetSectorCenter() - Location).GetUnsafeNormal();

				FLOGV("UFlareSector::LoadSpacecraft : Exit '%s' at (%f, %f, %f)",
					*ParentSpacecraft->GetImmatriculation().ToString(),
					Location.X, Location.Y, Location.Z);

				PlaceSpacecraft(Spacecraft, Location);
				Spacecraft->SetActorRotation(CenterDirection.Rotation());

				RootComponent->SetPhysicsLinearVelocity(CenterDirection * SpawnVelocity, false);
				RootComponent->SetPhysicsAngularVelocity(FVector::ZeroVector, false);

			}
			break;
		}

		ParentSpacecraft->SetSpawnMode(EFlareSpawnMode::Safe);
	}