diff --git a/Assets/GWConquest/Scripts/Battle.cs b/Assets/GWConquest/Scripts/Battle.cs index 57252ba..e3067ec 100644 --- a/Assets/GWConquest/Scripts/Battle.cs +++ b/Assets/GWConquest/Scripts/Battle.cs @@ -223,40 +223,43 @@ namespace GWConquest public void FixedUpdate() { - if(IsInPreparing) + if(IsServer) { - PreparingCooldown -= BoltNetwork.FrameDeltaTime; - if(PreparingCooldown <= 0) + if(IsInPreparing) { - PreparingCooldown = 0; + PreparingCooldown -= BoltNetwork.FrameDeltaTime; + if(PreparingCooldown <= 0) + { + PreparingCooldown = 0; + } } - } - else if(!IsOver) - { - var gm = GameManager.Instance; + else if(!IsOver) + { + var gm = GameManager.Instance; - var players = AllPlayers; - var playerCount = players.Count(); + var players = AllPlayers; + var playerCount = players.Count(); - if(playerCount <= 1) - { - if(playerCount <= 0) + if(playerCount <= 1) { - BoltLog.Info("No players in Battle {0}!", this); - } - else { - var finalPlayer = players.First(); - BoltLog.Info("Player {0} is only one left in Battle {1}!", finalPlayer, this); + if(playerCount <= 0) + { + BoltLog.Info("No players in Battle {0}!", this); + } + else { + var finalPlayer = players.First(); + BoltLog.Info("Player {0} is only one left in Battle {1}!", finalPlayer, this); + } + + Zone.CurrentBattle = null; + + SetBattleOver(); + //Destroy(gameObject); + } - Zone.CurrentBattle = null; - - SetBattleOver(); - //Destroy(gameObject); - + SimulateTurn(); } - - SimulateTurn(); } @@ -664,7 +667,8 @@ namespace GWConquest } } - public void MoveUnitToFlankRpc(NetworkBehaviourReference unit, NetworkBehaviourReference flank, int flankIndex) + [ServerRpc] + public void MoveUnitToFlankServerRpc(NetworkBehaviourReference unit, NetworkBehaviourReference flank, int flankIndex) { MoveUnitToFlank(unit.GetBehaviour(), flank.GetBehaviour(), flankIndex); } @@ -676,7 +680,8 @@ namespace GWConquest unit.SetActionCooldown(GameManager.Instance.MoveToReserveCooldown / movement); } - public void MoveUnitToReserveRpc(NetworkBehaviourReference unit) + [ServerRpc] + public void MoveUnitToReserveServerRpc(NetworkBehaviourReference unit) { MoveUnitToReserve(unit.GetBehaviour()); } diff --git a/Assets/GWConquest/Scripts/BattleFlank.cs b/Assets/GWConquest/Scripts/BattleFlank.cs index 57f7b4d..a332425 100644 --- a/Assets/GWConquest/Scripts/BattleFlank.cs +++ b/Assets/GWConquest/Scripts/BattleFlank.cs @@ -124,18 +124,21 @@ namespace GWConquest { public void FixedUpdate() { - for(int i = 0; i < MaxUnitCount; i++) + if(IsServer) { - if(GetDeathCooldown(i) > 0) + for(int i = 0; i < MaxUnitCount; i++) { - deathCooldowns[i] -= BoltNetwork.FrameDeltaTime; - if(GetDeathCooldown(i) <= 0) + if(GetDeathCooldown(i) > 0) { - var unit = GetUnit(i); - if(unit != null) + deathCooldowns[i] -= BoltNetwork.FrameDeltaTime; + if(GetDeathCooldown(i) <= 0) { - unit.CurrentFlank = null; - SetUnit(i, null); + var unit = GetUnit(i); + if(unit != null) + { + unit.CurrentFlank = null; + SetUnit(i, null); + } } } } diff --git a/Assets/GWConquest/Scripts/BattleLog.cs b/Assets/GWConquest/Scripts/BattleLog.cs index 9cad26e..578eb68 100644 --- a/Assets/GWConquest/Scripts/BattleLog.cs +++ b/Assets/GWConquest/Scripts/BattleLog.cs @@ -12,27 +12,27 @@ namespace GWConquest public struct BattleLogUnitEntry { - public NetworkId Id; - public string ClassName; + public NullableNetworkBehaviourReference Id; + public ushort ClassID; public int PlayerID; public UnitClass UnitClass { - get => UnitClass.FromName(ClassName); + get => UnitClass.FromID(ClassID); } public Unit Unit { - get => BoltNetwork.FindEntity(Id)?.GetComponent(); + get => Id.GetBehaviour(); } } public struct BattleLogBattleEntry { - public NetworkId Id; + public NullableNetworkBehaviourReference Id; public string BattleName; public string PlanetName; public Battle Battle { - get => BoltNetwork.FindEntity(Id)?.GetComponent(); + get => Id.GetBehaviour(); } } @@ -51,16 +51,16 @@ namespace GWConquest public BattleLogEntry(Unit unit, BattleLogAction action, Unit target = null, Battle battle = null) { Unit = new BattleLogUnitEntry() { - Id = unit.entity.NetworkId, - ClassName = unit.state.UnitClass, + Id = unit, + ClassID = unit.Class.ID, PlayerID = unit.Player.PlayerId }; Action = action; if(target != null) { Target = new BattleLogUnitEntry() { - Id = target.entity.NetworkId, - ClassName = target.state.UnitClass, + Id = target, + ClassID = target.Class.ID, PlayerID = target.Player.PlayerId }; } @@ -70,7 +70,7 @@ namespace GWConquest if(battle != null) { Battle = new BattleLogBattleEntry() { - Id = battle.entity.NetworkId, + Id = battle, BattleName = battle.name, PlanetName = battle.Zone.planet.name }; @@ -91,7 +91,7 @@ namespace GWConquest public IEnumerable GetEntriesForBattle(Battle battle) { - return Entries.Where(e => e.Battle.Id == battle.entity.NetworkId); + return Entries.Where(e => e.Battle.Battle == battle); } } } diff --git a/Assets/GWConquest/Scripts/District.cs b/Assets/GWConquest/Scripts/District.cs index 0607d1a..0d40e9e 100644 --- a/Assets/GWConquest/Scripts/District.cs +++ b/Assets/GWConquest/Scripts/District.cs @@ -298,31 +298,34 @@ namespace GWConquest public void FixedUpdate() { - CheckControllingChange(); - - if(ControllingPlayer != null) + if(IsServer) { - string producingItem = ProducingItem; + CheckControllingChange(); - bool producesCredits = DistrictType == DistrictType.Civil; + if(ControllingPlayer != null) + { + string producingItem = ProducingItem; - if(producingItem != null || producesCredits) { - if(itemProductionCooldown.Value <= 0f) - { - if(producingItem != null) - { - Inventory.AddItem(ItemRegistry.Instance.IDFromName(producingItem), 1); - } + bool producesCredits = DistrictType == DistrictType.Civil; - if(producesCredits) + if(producingItem != null || producesCredits) { + if(itemProductionCooldown.Value <= 0f) { - ControllingPlayer.Credits++; - } + if(producingItem != null) + { + Inventory.AddItem(ItemRegistry.Instance.IDFromName(producingItem), 1); + } - itemProductionCooldown.Value = ProducingCooldown; - } - else { - itemProductionCooldown.Value -= Time.fixedDeltaTime; + if(producesCredits) + { + ControllingPlayer.Credits++; + } + + itemProductionCooldown.Value = ProducingCooldown; + } + else { + itemProductionCooldown.Value -= Time.fixedDeltaTime; + } } } } diff --git a/Assets/GWConquest/Scripts/DistrictFactory.cs b/Assets/GWConquest/Scripts/DistrictFactory.cs index e1630bf..a16f050 100644 --- a/Assets/GWConquest/Scripts/DistrictFactory.cs +++ b/Assets/GWConquest/Scripts/DistrictFactory.cs @@ -43,6 +43,7 @@ namespace GWConquest public bool StartsBroken = false; public string[] SpecialUnits; + public int MaxQueueLength; private District _district; public District District @@ -152,19 +153,22 @@ namespace GWConquest } int length = ProductionQueueLength; - BoltLog.Info("Adding unit {0} to production queue on district {1}", buildable, gameObject.name); - - productionQueue.Add(new ProductionQueueEntry() { - UnitClass = buildable.ID, - TimeProduced = 0f, - PlayerID = player.PlayerId, - IsUpgrade = buildable is DistrictUpgrade - }); + if(length < MaxQueueLength) + { + BoltLog.Info("Adding unit {0} to production queue on district {1}", buildable, gameObject.name); + + productionQueue.Add(new ProductionQueueEntry() { + UnitClass = buildable.ID, + TimeProduced = 0f, + PlayerID = player.PlayerId, + IsUpgrade = buildable is DistrictUpgrade + }); + } } [ServerRpc] - public void AddProductionQueueEntryRpc(ushort buildableID, bool isUpgrade, NetworkBehaviourReference player) + public void AddProductionQueueEntryServerRpc(ushort buildableID, bool isUpgrade, NetworkBehaviourReference player) { IBuildable buildable = isUpgrade ? DistrictUpgrade.FromID(buildableID) : UnitClass.FromID(buildableID); AddProductionQueueEntry(buildable, player.GetBehaviour()); @@ -188,7 +192,7 @@ namespace GWConquest Zone zone = GetComponent(); if(zone != null) { - Unit.SpawnUnit(zone, buildable as UnitClass, productionQueue[0].Player); + GWNetworkManager.Instance.SpawnUnit(zone, buildable as UnitClass, productionQueue[0].Player); } else { diff --git a/Assets/GWConquest/Scripts/Formation.cs b/Assets/GWConquest/Scripts/Formation.cs index d0ee3d5..2315cf4 100644 --- a/Assets/GWConquest/Scripts/Formation.cs +++ b/Assets/GWConquest/Scripts/Formation.cs @@ -9,17 +9,19 @@ using Unity.Netcode; namespace GWConquest { - public struct Transition : INetworkSerializeByMemcpy + public struct Transition : INetworkSerializeByMemcpy { public int OriginZoneID; public int TargetZoneID; public float TransitionLength; public bool IsCurved; - public Zone OriginZone { + public Zone OriginZone + { get => Zone.GetFromId(OriginZoneID); } - public Zone TargetZone { + public Zone TargetZone + { get => Zone.GetFromId(TargetZoneID); } } @@ -66,25 +68,26 @@ namespace GWConquest } private void OnZoneChanged(int previousValue, int newValue) - { - if(previousValue != newValue) + { + if (previousValue != newValue) { Zone previousZone = Zone.GetFromId(previousValue); Zone newZone = Zone.GetFromId(newValue); - if(previousZone != null) + if (previousZone != null) { previousZone.OnFormationDeparting(this); } - if(newZone != null) + if (newZone != null) { newZone.OnFormationArrived(this); } - + BoltLog.Info("Current zone changed from {0} to {1} on formation {2}", previousZone, newZone, this); - } + } } - public ZoneType ZoneType { + public ZoneType ZoneType + { get => isSpace.Value ? ZoneType.Space : ZoneType.Ground; set => isSpace.Value = value == ZoneType.Space; } @@ -98,7 +101,8 @@ namespace GWConquest public string FormationName { get => formationName.Value; - set { + set + { formationName.Value = value; keepFormationName = true; } @@ -110,23 +114,28 @@ namespace GWConquest private Vector3 restingPosition; - public float AnimCompletion { + public float AnimCompletion + { get => animDistanceCovered / CurrentTransition.TransitionLength; } - public float AnimTimeLeft { + public float AnimTimeLeft + { get => (CurrentTransition.TransitionLength - animDistanceCovered) / movementSpeed; } - public IEnumerable Units { + public IEnumerable Units + { get => units.Select(r => r.GetBehaviour()); } - public IEnumerable SubFormations { + public IEnumerable SubFormations + { get => units.Select(r => r.GetBehaviour()); } - public int UnitCount { + public int UnitCount + { get => units.Count; } @@ -141,16 +150,19 @@ namespace GWConquest get => Units.SelectMany(u => u.Inventory); } - public IEnumerable PathQueue { + public IEnumerable PathQueue + { get => pathQueue.Select(id => Zone.GetFromId(id)); } - public Formation MovementTargetFormation { + public Formation MovementTargetFormation + { get => movementTargetFormation.Value.GetBehaviour(); set => movementTargetFormation.Value = value; } - public Formation MovementOriginFormation { + public Formation MovementOriginFormation + { get => movementOriginFormation.Value.GetBehaviour(); set => movementOriginFormation.Value = value; } @@ -165,61 +177,70 @@ namespace GWConquest get => currentTransition.Value; } - public bool IsEmbarked { + public bool IsEmbarked + { get => isEmbarked.Value; set => isEmbarked.Value = value; } - public Formation ParentFormation { + public Formation ParentFormation + { get => parentFormation.Value.GetBehaviour(); set => parentFormation.Value = value; } public const float MoraleCap = 27 * 3 * 100; - public float Morale { + public float Morale + { get => morale.Value; set => morale.Value = value; } - public float StartingMorale { + public float StartingMorale + { get => startingMorale.Value; set => startingMorale.Value = value; } - public FormationMovementState MovementState { + public FormationMovementState MovementState + { get => movementState.Value; set => movementState.Value = value; } - public bool IsMoving { + public bool IsMoving + { get => MovementState == FormationMovementState.Moving || MovementState == FormationMovementState.PreparingMovement || MovementState == FormationMovementState.FinishingMovement; } - - public float ActionCooldown { + + public float ActionCooldown + { get => actionCooldown.Value; } - public float ActionCooldownPercent { - get =>actionCooldown.Value / actionCooldownMax.Value; + public float ActionCooldownPercent + { + get => actionCooldown.Value / actionCooldownMax.Value; } public void SetActionCooldown(float value) { actionCooldown.Value = value; actionCooldownMax.Value = value; - } + } public GameObject movingArmyPrefab; public float movingArmyScale; - public GameObject movingArmyIcon {get; private set;} + public GameObject movingArmyIcon { get; private set; } private Vector3 arrivalPosition; - public float movementSpeed {get => GameManager.Instance.DefaultMovementSpeed;} + public float movementSpeed { get => GameManager.Instance.DefaultMovementSpeed; } - public int FormationNumber { + public int FormationNumber + { get => formationNumber.Value; set => formationNumber.Value = value; } @@ -233,18 +254,20 @@ namespace GWConquest get => !IsMoving; } - public Planet CurrentPlanet { - get { + public Planet CurrentPlanet + { + get + { var z = currentZone; - if(z != null) + if (z != null) { return z.planet; } - else if(CurrentTransition.OriginZoneID != -1) + else if (CurrentTransition.OriginZoneID != -1) { return CurrentTransition.OriginZone.planet; } - else return null; + else return null; } } @@ -252,7 +275,7 @@ namespace GWConquest public void TryMoveToPlanet(Planet planet) { - if(currentZone.zoneType == ZoneType.Space) + if (currentZone.zoneType == ZoneType.Space) { var targetZone = planet.GetMainZone(ZoneType.Space); @@ -265,27 +288,27 @@ namespace GWConquest var pathfindingGraph = targetZone.zoneType == ZoneType.Space ? Planet.PlanetPathfindingGraph : targetZone.planet.pathfindingGraph; var shortestPath = pathfindingGraph.FindShortestPath(this, currentZone, targetZone); - if(shortestPath != null) + if (shortestPath != null) { StartMovingOnPath(shortestPath.zones); } - else + else { BoltLog.Warn("No path found between {0} and {1}", currentZone, targetZone); } } - public void StartMovingOnPath(List path, Formation targetFormation=null) + public void StartMovingOnPath(List path, Formation targetFormation = null) { if (path.Count > 1 && IsOwner && CanMove) { - if(!CanMoveTo(path[0], path[1])) + if (!CanMoveTo(path[0], path[1])) { BoltLog.Info($"Formation {this} has not enough fuel for transition {path[0]} -> {path[1]}"); return; } - int[] zoneIDs = path.GetRange(1, path.Count-1).Select(z => Zone.GetZoneId(z)).ToArray(); + int[] zoneIDs = path.GetRange(1, path.Count - 1).Select(z => Zone.GetZoneId(z)).ToArray(); BeginMovementServerRpc(zoneIDs, targetFormation); } else @@ -297,22 +320,22 @@ namespace GWConquest public void BeginMovementServer(int[] zoneIDs, Formation targetFormation) { - - if(zoneIDs == null) + + if (zoneIDs == null) { throw new ArgumentNullException("Movement path is null!"); } Zone firstZone = Zone.GetFromId(zoneIDs[0]); - if(!CanMoveTo(currentZone,firstZone)) + if (!CanMoveTo(currentZone, firstZone)) { BoltLog.Info($"Formation {this} has not enough fuel for transition {currentZone} -> {firstZone}"); return; } - if(IsEmbarked) + if (IsEmbarked) { - if(ParentFormation != null) + if (ParentFormation != null) { MovementOriginFormation = ParentFormation; ParentFormation.RemoveSubFormation(this); @@ -321,7 +344,7 @@ namespace GWConquest pathQueue.SetEntries(zoneIDs); - if(targetFormation != null) + if (targetFormation != null) { MovementTargetFormation = targetFormation; } @@ -330,9 +353,9 @@ namespace GWConquest MovementState = FormationMovementState.PreparingMovement; } - public void BeginMovementServer(Zone targetZone, Formation targetFormation=null) + public void BeginMovementServer(Zone targetZone, Formation targetFormation = null) { - BeginMovementServer(new int[] {Zone.GetZoneId(targetZone)}, targetFormation: targetFormation); + BeginMovementServer(new int[] { Zone.GetZoneId(targetZone) }, targetFormation: targetFormation); } [ServerRpc] @@ -343,27 +366,28 @@ namespace GWConquest public void MoveToZone(Zone target) { - if(IsOwner && MovementState == FormationMovementState.PreparingMovement) + if (IsOwner && MovementState == FormationMovementState.PreparingMovement) { - if(!CanMoveTo(currentZone, target)) + if (!CanMoveTo(currentZone, target)) { BoltLog.Info($"Formation {this} has not enough fuel for transition {currentZone} -> {target}"); return; } int remainingFuel = 0; - foreach(Unit u in Units) + foreach (Unit u in Units) { int fuelRequired = u.GetFuelCostForJump(currentZone, target); int totalFuel = u.TotalFuel; - if(fuelRequired > 0) + if (fuelRequired > 0) { - if(totalFuel >= fuelRequired) + if (totalFuel >= fuelRequired) { u.ConsumeTotalFuel(fuelRequired); } - else { - int diff = fuelRequired -totalFuel; + else + { + int diff = fuelRequired - totalFuel; u.ConsumeTotalFuel(totalFuel); remainingFuel += diff; } @@ -371,32 +395,34 @@ namespace GWConquest } //consume remaining fuel from other ships - foreach(Unit u in Units) + foreach (Unit u in Units) { int totalFuel = u.TotalFuel; - if(totalFuel >= remainingFuel) + if (totalFuel >= remainingFuel) { u.ConsumeTotalFuel(remainingFuel); remainingFuel = 0; break; } - else { + else + { u.ConsumeTotalFuel(totalFuel); remainingFuel -= totalFuel; } } - if(remainingFuel != 0) + if (remainingFuel != 0) { BoltLog.Warn($"There is {remainingFuel} required fuel remaining after consuming everything, this should not happen!"); } - currentTransition.Value = new Transition() { + currentTransition.Value = new Transition() + { OriginZoneID = Zone.GetZoneId(currentZone), TargetZoneID = Zone.GetZoneId(target), TransitionLength = Zone.GetTransitionLength(currentZone, target), IsCurved = target.zoneType == ZoneType.Ground || currentZone.zoneType == ZoneType.Ground }; - + CoveredDistance = 0; currentZone = null; MovementState = FormationMovementState.Moving; @@ -425,7 +451,7 @@ namespace GWConquest private void OnTransitStateChanged(FormationMovementState previousValue, FormationMovementState newValue) { animDistanceCovered = 0; - if(newValue == FormationMovementState.Moving) + if (newValue == FormationMovementState.Moving) { var originZone = CurrentTransition.OriginZone; var targetZone = CurrentTransition.TargetZone; @@ -442,118 +468,120 @@ namespace GWConquest arrivalPosition = targetZone.planet.GetFleetArrivalPosition(originZone); } - if(originZone.planet == targetZone.planet) + if (originZone.planet == targetZone.planet) { originZone.planet.InTransitFormations.Add(this); } - + } else { var planet = currentZone.planet; - if(planet.InTransitFormations.Contains(this)) + if (planet.InTransitFormations.Contains(this)) { planet.InTransitFormations.Remove(this); } - + } } public void FixedUpdate() { - if(IsServer) + if (IsServer) { - if(IsEmbarked) - { - if(ParentFormation != null) + if (IsEmbarked) { - if(currentZone != ParentFormation.currentZone) + if (ParentFormation != null) { - currentZone = ParentFormation.currentZone; + if (currentZone != ParentFormation.currentZone) + { + currentZone = ParentFormation.currentZone; + } + } + else + { + BoltLog.Error("Formation {0} lost its parent formation {1}!", this, ParentFormation); + ParentFormation = null; + IsEmbarked = false; } } - else { - BoltLog.Error("Formation {0} lost its parent formation {1}!", this, ParentFormation); - ParentFormation = null; - IsEmbarked = false; - } - } - if(MovementState == FormationMovementState.Moving) - { - CoveredDistance += movementSpeed * BoltNetwork.FrameDeltaTime; - if (CoveredDistance >= CurrentTransition.TransitionLength) - { + if (MovementState == FormationMovementState.Moving) + { + CoveredDistance += movementSpeed * BoltNetwork.FrameDeltaTime; + if (CoveredDistance >= CurrentTransition.TransitionLength) + { - currentZone = CurrentTransition.TargetZone; + currentZone = CurrentTransition.TargetZone; - if(currentZone.zoneType == ZoneType.Space) - { - fleetRestingPoint.Value = currentZone.planet.GetFleetArrivalPosition(CurrentTransition.OriginZone); - } + if (currentZone.zoneType == ZoneType.Space) + { + fleetRestingPoint.Value = currentZone.planet.GetFleetArrivalPosition(CurrentTransition.OriginZone); + } - currentTransition.Value = new Transition() - { - OriginZoneID = -1, - TargetZoneID = -1, - TransitionLength = 0 - }; - CoveredDistance = 0; - MovementState = FormationMovementState.FinishingMovement; - - SetActionCooldown(GameManager.Instance.MovementFinishedCooldown); - - } - } + currentTransition.Value = new Transition() + { + OriginZoneID = -1, + TargetZoneID = -1, + TransitionLength = 0 + }; + CoveredDistance = 0; + MovementState = FormationMovementState.FinishingMovement; - if(ActionCooldown <= 0) - { - actionCooldown.Value = 0; + SetActionCooldown(GameManager.Instance.MovementFinishedCooldown); - if(MovementState == FormationMovementState.PreparingMovement) - { - Zone z = PathQueue.First(); - pathQueue.RemoveAt(0); - MoveToZone(z); + } } - else if(MovementState == FormationMovementState.FinishingMovement) + + if (ActionCooldown <= 0) { - if(pathQueue.Count > 0) + actionCooldown.Value = 0; + + if (MovementState == FormationMovementState.PreparingMovement) { - if(CanMoveTo(currentZone, PathQueue.First())) - { - SetActionCooldown(GameManager.Instance.MovementStartingCooldown); - MovementState = FormationMovementState.PreparingMovement; - } - else - { - BoltLog.Info($"Formation {this} has not enough fuel for transition {currentZone} -> {PathQueue.First()}"); - pathQueue.Clear(); - MovementState = FormationMovementState.Idle; - } - + Zone z = PathQueue.First(); + pathQueue.RemoveAt(0); + MoveToZone(z); } - else + else if (MovementState == FormationMovementState.FinishingMovement) { - if(MovementTargetFormation != null) + if (pathQueue.Count > 0) { - if(MovementTargetFormation.HasNetworkObject && MovementTargetFormation.currentZone == currentZone) + if (CanMoveTo(currentZone, PathQueue.First())) + { + SetActionCooldown(GameManager.Instance.MovementStartingCooldown); + MovementState = FormationMovementState.PreparingMovement; + } + else { - MovementTargetFormation.AddSubFormation(this); + BoltLog.Info($"Formation {this} has not enough fuel for transition {currentZone} -> {PathQueue.First()}"); + pathQueue.Clear(); + MovementState = FormationMovementState.Idle; } - MovementTargetFormation = null; + } - if(MovementOriginFormation != null) + else { - MovementOriginFormation = null; - } + if (MovementTargetFormation != null) + { + if (MovementTargetFormation.HasNetworkObject && MovementTargetFormation.currentZone == currentZone) + { + MovementTargetFormation.AddSubFormation(this); + } + MovementTargetFormation = null; + } + if (MovementOriginFormation != null) + { + MovementOriginFormation = null; + } - MovementState = FormationMovementState.Idle; + MovementState = FormationMovementState.Idle; + } } } - } - else { - actionCooldown.Value -= Time.fixedDeltaTime; - } + else + { + actionCooldown.Value -= Time.fixedDeltaTime; + } } } @@ -584,11 +612,12 @@ namespace GWConquest { if (currentZone != null && movingArmyIcon == null) { - if(currentZone.zoneType == ZoneType.Space) + if (currentZone.zoneType == ZoneType.Space) { MakeMovingIcon(IngameUI.Instance.MovingFleetsTransform); } - else { + else + { MakeMovingIcon(IngameUI.Instance.PlanetView.DistrictIcons); } } @@ -680,11 +709,11 @@ namespace GWConquest if (movingArmyIcon != null) { - if(ZoneType == ZoneType.Space) + if (ZoneType == ZoneType.Space) { if (!IngameUI.PlanetViewEnabled) { - if(GWCamera.Instance.ShowCircles || MovementState == FormationMovementState.Moving) + if (GWCamera.Instance.ShowCircles || MovementState == FormationMovementState.Moving) { movingArmyIcon.SetActive(true); var stick = movingArmyIcon.GetComponent(); @@ -698,10 +727,11 @@ namespace GWConquest movingArmyIcon.SetActive(false); } } - else { - if(IngameUI.PlanetViewEnabled && IngameUI.Instance.PlanetView.selectedPlanet == CurrentPlanet) + else + { + if (IngameUI.PlanetViewEnabled && IngameUI.Instance.PlanetView.selectedPlanet == CurrentPlanet) { - if(MovementState == FormationMovementState.Moving) + if (MovementState == FormationMovementState.Moving) { //movingArmyIcon.SetActive(true); var stick = movingArmyIcon.GetComponent(); @@ -720,7 +750,7 @@ namespace GWConquest private Vector3 GetRestingPosition() { - if(currentZone == null) + if (currentZone == null) return Vector3.zero; var planet = currentZone.planet; @@ -737,7 +767,7 @@ namespace GWConquest AllFormations.Add(this); - if(IsOwner) + if (IsOwner) { currentZoneID.Value = -1; MovementState = FormationMovementState.Idle; @@ -750,24 +780,27 @@ namespace GWConquest currentZoneID.OnValueChanged += OnZoneChanged; base.OnNetworkSpawn(); - + } - + public float GetFormationStrength() { - if(HasNetworkObject) + if (HasNetworkObject) { - return Units.Sum(unit => { - if(unit != null && unit.HasNetworkObject) + return Units.Sum(unit => + { + if (unit != null && unit.HasNetworkObject) { return unit.Class.UnitStrength; } - else { + else + { return 0f; } }); } - else { + else + { return 0f; } } @@ -776,31 +809,31 @@ namespace GWConquest public void OnUnitAdded(Unit unit) { BoltLog.Info("Unit {0} added to formation {1}", unit, this); - if(currentZone != null) + if (currentZone != null) { currentZone.OnFormationChanged(this); } - if(IsOwner) + if (IsOwner) { - if(!keepFormationName) + if (!keepFormationName) { ConstructName(); } - } + } OnUnitsChanged?.Invoke(); } public void OnUnitRemoved(Unit unit) { OnUnitsChanged?.Invoke(); - if(IsOwner) + if (IsOwner) { - if(!keepFormationName) + if (!keepFormationName) { ConstructName(); } - } + } } public void AddSubFormation(Formation f) @@ -825,7 +858,7 @@ namespace GWConquest public event Action OnUnitsChanged; - + public float GetModifierForTransition(Zone origin, Zone target) { return 1f; @@ -833,11 +866,12 @@ namespace GWConquest public bool CanMoveTo(Zone origin, Zone target) { - if(origin.zoneType == target.zoneType) + if (origin.zoneType == target.zoneType) { return Units.Sum(u => u.TotalFuel) >= GetFuelCostForJump(origin, target); } - else { + else + { //TODO Fuel für Landung?? return true; } @@ -850,23 +884,25 @@ namespace GWConquest public FormationCategory Category { - get { + get + { var units = Units; float totalUnits = units.Count(); - if(ZoneType == ZoneType.Space) + if (ZoneType == ZoneType.Space) { return FormationCategory.FleetBattle; } - else { - if(units.Count(u => u.Class.UnitType == UnitType.Vehicle) / totalUnits >= 0.3) + else + { + if (units.Count(u => u.Class.UnitType == UnitType.Vehicle) / totalUnits >= 0.3) { return FormationCategory.ArmyArmoured; } - else if(units.Count(u => u.Class.UnitType == UnitType.Artillery) / totalUnits >= 0.3) + else if (units.Count(u => u.Class.UnitType == UnitType.Artillery) / totalUnits >= 0.3) { return FormationCategory.ArmyArtillery; } - else if(units.Count(u => u.Class.UnitType == UnitType.Infantry) / totalUnits >= 0.5) + else if (units.Count(u => u.Class.UnitType == UnitType.Infantry) / totalUnits >= 0.5) { return FormationCategory.ArmyInfantry; } @@ -874,7 +910,7 @@ namespace GWConquest { return FormationCategory.ArmyCombined; } - } + } } } @@ -887,47 +923,48 @@ namespace GWConquest var units = Units; float totalUnits = units.Count(); - if(ZoneType == ZoneType.Ground) + if (ZoneType == ZoneType.Ground) { - if(totalUnits < 5) + if (totalUnits < 5) { name += "Company"; } - else if(totalUnits < 10) + else if (totalUnits < 10) { name += "Battalion"; } - else if(totalUnits < 20) + else if (totalUnits < 20) { name += "Division"; } - else if(totalUnits < 40) + else if (totalUnits < 40) { name += "Corps"; } - else if(totalUnits < 60) + else if (totalUnits < 60) { name += "Army"; } } - else { - if(totalUnits < 5) + else + { + if (totalUnits < 5) { name += "Squadron"; } - else if(totalUnits < 10) + else if (totalUnits < 10) { name += "Flotilla"; } - else if(totalUnits < 20) + else if (totalUnits < 20) { name += "Force"; } - else if(totalUnits < 40) + else if (totalUnits < 40) { name += "Fleet"; } - else if(totalUnits < 60) + else if (totalUnits < 60) { name += "Armada"; } @@ -943,13 +980,13 @@ namespace GWConquest public void TakeMoraleDamage(float moraleDamage) { - if(Morale > 0) + if (Morale > 0) { - if(DebugUI.LogBattleEvents) + if (DebugUI.LogBattleEvents) BoltLog.Info("Formation {0} took {1} points of morale damage", this, moraleDamage); Morale -= moraleDamage; - if(Morale <= 0) + if (Morale <= 0) { Morale = 0; BoltLog.Info("Formation {0} is demoralized and will flee!", this); @@ -957,15 +994,15 @@ namespace GWConquest BeginMovementServer(retreatZone); - foreach(Unit u in Units) + foreach (Unit u in Units) { - if(u.CurrentFlank != null) + if (u.CurrentFlank != null) { u.CurrentBattle.MoveUnitToReserve(u); } } - PlayFormationDemoralizedAnimation(); + PlayFormationDemoralizedAnimationClientRpc(); } } } @@ -973,11 +1010,12 @@ namespace GWConquest public Zone GetRetreatZone() { IEnumerable zones; - if(currentZone.zoneType == ZoneType.Ground) + if (currentZone.zoneType == ZoneType.Ground) { zones = currentZone.planet.pathfindingGraph.GetConnectedNodes(currentZone); } - else { + else + { zones = Planet.PlanetPathfindingGraph.GetConnectedNodes(currentZone); } var list = zones.ToList(); @@ -993,34 +1031,36 @@ namespace GWConquest bool isArriving = MovementState == FormationMovementState.FinishingMovement; GameManager gm = GameManager.Instance; - foreach(Unit u in Units) + foreach (Unit u in Units) { u.BattleState = isArriving ? BattleUnitState.Arriving : BattleUnitState.InReserve; u.ResetActionCooldown(); - - if(!battle.IsSpaceBattle && !u.Class.IsHero) + + if (!battle.IsSpaceBattle && !u.Class.IsHero) { - if(Battle.Check(gm.StartRevealChance)) + if (Battle.Check(gm.StartRevealChance)) { - if(Battle.Check(gm.StartFullRevealChance)) + if (Battle.Check(gm.StartFullRevealChance)) { u.RevealState = RevealState.Visible; } - else { + else + { u.RevealState = RevealState.ClassHidden; } } - else { + else + { u.RevealState = RevealState.FullHidden; } - } + } } } [ClientRpc] - public void PlayFormationDemoralizedAnimation() + public void PlayFormationDemoralizedAnimationClientRpc() { - if(HeroUnit != null && HeroUnit.CurrentIcon != null) + if (HeroUnit != null && HeroUnit.CurrentIcon != null) { HeroUnit.CurrentIcon.PlayDemoralizedAnim(); } @@ -1028,10 +1068,10 @@ namespace GWConquest public void RemoveDeadUnits() { - for(int i = units.Count-1; i >= 0; i--) + for (int i = units.Count - 1; i >= 0; i--) { var unit = units[i].GetBehaviour(); - if(unit.IsDead) + if (unit.IsDead) { units.RemoveAt(i); OnUnitRemoved(unit); @@ -1047,14 +1087,7 @@ namespace GWConquest units.Add(unit); } - public static Formation SpawnFormation(Zone zone, Player player) - { - BoltEntity formationEntity = BoltNetwork.Instantiate(BoltPrefabs.Formation); - player.AssignControl(formationEntity); - Formation playerFormation = formationEntity.GetComponent(); - playerFormation.Initialize(zone, player); - return playerFormation; - } + public void Initialize(Zone zone, Player player) { @@ -1063,7 +1096,7 @@ namespace GWConquest currentZone = zone; ZoneType = zone.zoneType; - if(ZoneType == ZoneType.Space) + if (ZoneType == ZoneType.Space) { Vector3 startPos = zone.planet.GetFleetRestingPosition(); fleetRestingPoint.Value = startPos; @@ -1071,7 +1104,7 @@ namespace GWConquest } [ServerRpc] - public void AssignLeaderRpc(NullableNetworkBehaviourReference unit) + public void AssignLeaderServerRpc(NullableNetworkBehaviourReference unit) { heroUnit.Value = unit; } @@ -1080,13 +1113,14 @@ namespace GWConquest { return FormationInventory; } - + } - public enum FormationMovementState { + public enum FormationMovementState + { Idle, PreparingMovement, FinishingMovement, Moving } - - + + } \ No newline at end of file diff --git a/Assets/GWConquest/Scripts/GWNetworkManager.cs b/Assets/GWConquest/Scripts/GWNetworkManager.cs new file mode 100644 index 0000000..1e61dc5 --- /dev/null +++ b/Assets/GWConquest/Scripts/GWNetworkManager.cs @@ -0,0 +1,163 @@ +using UnityEngine; +using Unity.Netcode; +using System.Linq; + +namespace GWConquest { + public class GWNetworkManager : NetworkBehaviour + { + + private static GWNetworkManager _instance; + public static GWNetworkManager Instance { + get { + if(_instance == null) + { + _instance = FindObjectOfType(); + } + return _instance; + } + } + + public GameObject UnitPrefab; + public GameObject FormationPrefab; + + public override void OnNetworkSpawn() + { + NetworkManager.SceneManager.OnSceneEvent += OnSceneEvent; + base.OnNetworkSpawn(); + } + + private void OnSceneEvent(SceneEvent sceneEvent) + { + if(IsServer) + { + if(sceneEvent.SceneEventType == SceneEventType.LoadComplete) + { + if(sceneEvent.ClientId == NetworkManager.ServerClientId) + { + ServerSceneLoadCompleteLocal(sceneEvent.SceneName); + } + else { + ServerSceneLoadCompleteRemote(sceneEvent.ClientId); + } + } + + } + else { + if(sceneEvent.SceneEventType == SceneEventType.LoadComplete) + { + ClientSceneLoadComplete(); + } + } + } + + public void ServerSceneLoadCompleteLocal(string scene) + { + if(scene != "GalaxyMap") + return; + + PlanetPlacement.Instance.PlacePlanets(); + + foreach(Planet planet in FindObjectsOfType()) + { + planet.FinishSetup(); + } + + Player serverPlayer = NetworkManager.SpawnManager.GetLocalPlayerObject().GetComponent(); + serverPlayer.SetFaction((ushort) GameManager.HostFactionIndex); + serverPlayer.AssignStartingPlanets(); + + GameManager.Instance.SceneLoadLocalDone(); + + //foreach(GameObject go in FindObjectsOfType()) { + // go.SendMessage("OnSceneLoadLocalDone", SendMessageOptions.DontRequireReceiver); + //} + + foreach(var spawner in FindObjectsOfType()) + { + spawner.SpawnUnits(); + } + + foreach(Zone z in Zone.AllZones) + { + z.CheckBattleStart(); + } + + Planet.SetupPlanetPathfinding(); + + GameManager.EntitiesLoaded = true; + + GameOptions.ApplyOptions(); + + LoadingScreen.Dismiss(); + + Debug.Log("Server scene loading done."); + } + + public void ServerSceneLoadCompleteRemote(ulong clientID) + { + Player clientPlayer = NetworkManager.SpawnManager.GetPlayerNetworkObject(clientID).GetComponent(); + + clientPlayer.SetFaction((ushort) ((GameManager.HostFactionIndex + 1) % 2)); + clientPlayer.AssignStartingPlanets(); + } + + public void ClientSceneLoadComplete() + { + GameOptions.ApplyOptions(); + } + + [ServerRpc] + public void MoveItemServerRpc(NetworkBehaviourReference origin, NetworkBehaviourReference target, ushort itemID, int itemAmount) + { + NetworkBehaviour originBeh = origin.GetBehaviour(); + NetworkBehaviour targetBeh = target.GetBehaviour(); + + if(originBeh is IHasInventory && targetBeh is IHasInventory) + { + IInventory originInv = (originBeh as IHasInventory).GetInventory(); + IInventory targetInv = (targetBeh as IHasInventory).GetInventory(); + + Inventory.MoveItem(originInv, targetInv, itemID, itemAmount); + } + else { + Debug.LogError("One of the specified behaviours is not an inventory"); + } + } + + public Unit SpawnUnit(Zone zone, UnitClass uc, Player player) + { + Formation playerFormation = zone.Formations.FirstOrDefault(f => f.Player == player); + if (playerFormation == null) + { + playerFormation = SpawnFormation(zone, player); + } + + GameObject go = Instantiate(UnitPrefab); + go.GetComponent().Spawn(); + + Unit unit = go.GetComponent(); + unit.InstantiateWithClass(uc); + unit.Formation = playerFormation; + playerFormation.AddUnit(unit); + + Debug.LogFormat("Spawned unit {0} for player {1} in formation {2}", unit, player, playerFormation); + + return unit; + } + + [ServerRpc] + public void SpawnUnitServerRpc(int zoneID, ushort unitClassID, int playerID) + { + SpawnUnit(Zone.GetFromId(zoneID), UnitClass.FromID(unitClassID), Player.GetPlayerById(playerID)); + } + + public Formation SpawnFormation(Zone zone, Player player) + { + GameObject go = Instantiate(FormationPrefab); + Formation playerFormation = go.GetComponent(); + playerFormation.Initialize(zone, player); + return playerFormation; + } + + } +} \ No newline at end of file diff --git a/Assets/GWConquest/Scripts/GlobalCallbacks.cs.meta b/Assets/GWConquest/Scripts/GWNetworkManager.cs.meta similarity index 83% rename from Assets/GWConquest/Scripts/GlobalCallbacks.cs.meta rename to Assets/GWConquest/Scripts/GWNetworkManager.cs.meta index ff6c9d2..9fb3e26 100644 --- a/Assets/GWConquest/Scripts/GlobalCallbacks.cs.meta +++ b/Assets/GWConquest/Scripts/GWNetworkManager.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 4cd2ea54c0e00384894169adbfdf6403 +guid: 1741c174eb1458047aa5ab35a3b0aec4 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/GWConquest/Scripts/GlobalCallbacks.cs b/Assets/GWConquest/Scripts/GlobalCallbacks.cs deleted file mode 100644 index 8798980..0000000 --- a/Assets/GWConquest/Scripts/GlobalCallbacks.cs +++ /dev/null @@ -1,69 +0,0 @@ -using Photon.Bolt; -using Photon.Bolt.Utils; -using UdpKit; -using UnityEngine; -using System.Linq; - -namespace GWConquest -{ - [BoltGlobalBehaviour] - public class GlobalCallbacks : GlobalEventListener - { - public override void BoltStartBegin() - { - Debug.Log("Calling global callbacks..."); - BoltNetwork.RegisterTokenClass(); - BoltNetwork.RegisterTokenClass(); - BoltNetwork.RegisterTokenClass(); - BoltNetwork.RegisterTokenClass(); - } - - public override void SceneLoadLocalDone(string scene, IProtocolToken token) - { - //BoltLog.Info("scene load token: {0}", token); - - GameOptions.ApplyOptions(); - - } - - public override void SessionConnected(UdpSession session, IProtocolToken token) - { - BoltLog.Info("Session connected."); - } - - public override void OnEvent(ServerConfigEvent evnt) - { - if(BoltNetwork.IsClient) - { - GameManager.InitialEntityCount = evnt.EntityCount; - BoltLog.Info("Initial entity count is {0}", GameManager.InitialEntityCount); - if(!GameManager.EntitiesLoaded && GameManager.InitialEntityCount <= BoltNetwork.Entities.Count()) - { - BoltLog.Info("All entities retrieved!"); - GameManager.Instance.SetEntitiesLoaded(); - } - } - } - - public override void EntityReceived(BoltEntity entity) - { - if(BoltNetwork.IsClient && !GameManager.EntitiesLoaded) - { - var ecount = BoltNetwork.Entities.Count(); - if(ecount >= GameManager.InitialEntityCount) - { - BoltLog.Info("All entities retrieved!"); - GameManager.Instance.SetEntitiesLoaded(); - } - } - } - - - - - - - - - } -} \ No newline at end of file diff --git a/Assets/GWConquest/Scripts/Player.cs b/Assets/GWConquest/Scripts/Player.cs index 4267c26..fb22826 100644 --- a/Assets/GWConquest/Scripts/Player.cs +++ b/Assets/GWConquest/Scripts/Player.cs @@ -86,6 +86,11 @@ namespace GWConquest BoltLog.Info("Current player is {0} with connection ID {1}", this, OwnerClientId); } + public void SetFaction(ushort ind) + { + factionIndex.Value = ind; + } + public NetworkClient Client { get @@ -161,12 +166,6 @@ namespace GWConquest } } } - - [ServerRpc] - public void BuildUnit(int zoneID, ushort unitClassID) - { - Unit.SpawnUnit(Zone.GetFromId(zoneID), UnitClass.FromID(unitClassID), this); - } } [System.Serializable] diff --git a/Assets/GWConquest/Scripts/ServerCallbacks.cs b/Assets/GWConquest/Scripts/ServerCallbacks.cs deleted file mode 100644 index cd18399..0000000 --- a/Assets/GWConquest/Scripts/ServerCallbacks.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System.Linq; -using UnityEngine; -using UdpKit; -using Photon.Bolt; -using Photon.Bolt.Utils; -using Unity.Netcode; - -namespace GWConquest -{ - [BoltGlobalBehaviour(BoltNetworkModes.Server)] - public class ServerCallbacks : NetworkBehaviour - { - - private static ServerCallbacks _instance; - public static ServerCallbacks Instance { - get { - if(_instance == null) - { - _instance = FindObjectOfType(); - } - return _instance; - } - } - - public override void SceneLoadLocalDone(string scene, IProtocolToken token) - { - if(scene != "GalaxyMap") - return; - - PlanetPlacement.Instance.PlacePlanets(); - - foreach(Planet planet in FindObjectsOfType()) - { - planet.FinishSetup(); - } - - BoltEntity playerEntity = BoltNetwork.Instantiate(BoltPrefabs.Player); - Debug.Log("Player entity instantiated"); - IPlayerState playerState = playerEntity.GetState(); - playerState.IsHost = true; - playerState.FactionIndex = GameManager.HostFactionIndex; - playerEntity.GetComponent().AssignStartingPlanets(); - playerEntity.TakeControl(); - - GameManager.Instance.SceneLoadLocalDone(); - - //foreach(GameObject go in FindObjectsOfType()) { - // go.SendMessage("OnSceneLoadLocalDone", SendMessageOptions.DontRequireReceiver); - //} - - foreach(var spawner in FindObjectsOfType()) - { - spawner.SpawnUnits(); - } - - foreach(Zone z in Zone.AllZones) - { - z.CheckBattleStart(); - } - - Planet.SetupPlanetPathfinding(); - - GameManager.EntitiesLoaded = true; - - LoadingScreen.Dismiss(); - - BoltLog.Info("Server scene loading done."); - } - - public override void SceneLoadRemoteDone(BoltConnection connection, IProtocolToken token) - { - BoltEntity playerEntity = BoltNetwork.Instantiate(BoltPrefabs.Player); - IPlayerState playerState = playerEntity.GetState(); - playerState.ConnectionId = (int)connection.ConnectionId; - playerState.IsHost = false; - playerState.FactionIndex = (GameManager.HostFactionIndex + 1) % 2; - playerEntity.GetComponent().AssignStartingPlanets(); - playerEntity.AssignControl(connection); - - var ecount = BoltNetwork.Entities.Count(); - var configEvnt = ServerConfigEvent.Create(connection); - configEvnt.EntityCount = ecount; - configEvnt.Send(); - } - - public override void ConnectRequest(UdpEndPoint endpoint, IProtocolToken token) - { - BoltLog.Info("Connect request recieved"); - if(GameManager.EntitiesLoaded) - { - BoltLog.Info("Accepting connect request"); - BoltNetwork.Accept(endpoint); - } - else { - BoltLog.Info("Refusing connect request"); - BoltNetwork.Refuse(endpoint); - } - } - - public override void Connected(BoltConnection connection) - { - BoltLog.Info("Client connected"); - - } - - [ServerRpc] - public void MoveItemRpc(NetworkBehaviourReference origin, NetworkBehaviourReference target, ushort itemID, int itemAmount) - { - NetworkBehaviour originBeh = origin.GetBehaviour(); - NetworkBehaviour targetBeh = target.GetBehaviour(); - - if(originBeh is IHasInventory && targetBeh is IHasInventory) - { - IInventory originInv = (originBeh as IHasInventory).GetInventory(); - IInventory targetInv = (targetBeh as IHasInventory).GetInventory(); - - Inventory.MoveItem(originInv, targetInv, itemID, itemAmount); - } - else { - BoltLog.Error("One of the specified behaviours is not an inventory"); - } - } - } -} \ No newline at end of file diff --git a/Assets/GWConquest/Scripts/ServerCallbacks.cs.meta b/Assets/GWConquest/Scripts/ServerCallbacks.cs.meta deleted file mode 100644 index a4395ab..0000000 --- a/Assets/GWConquest/Scripts/ServerCallbacks.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b7ac2246de5adcc4eb245fff9adac55e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/GWConquest/Scripts/SpawnAIUnits.cs b/Assets/GWConquest/Scripts/SpawnAIUnits.cs index bdf21d5..34cd68b 100644 --- a/Assets/GWConquest/Scripts/SpawnAIUnits.cs +++ b/Assets/GWConquest/Scripts/SpawnAIUnits.cs @@ -23,7 +23,7 @@ namespace GWConquest { { for(int i = 0; i < unitCount; i++) { - var unit = Unit.SpawnUnit(zone, UnitClass.FromName(unitName), player); + var unit = GWNetworkManager.Instance.SpawnUnit(zone, UnitClass.FromName(unitName), player); if(assignAsLeader) { unit.Formation.HeroUnit = unit; diff --git a/Assets/GWConquest/Scripts/UI/BattleArmyPanel.cs b/Assets/GWConquest/Scripts/UI/BattleArmyPanel.cs index 250d7e6..731d03c 100644 --- a/Assets/GWConquest/Scripts/UI/BattleArmyPanel.cs +++ b/Assets/GWConquest/Scripts/UI/BattleArmyPanel.cs @@ -237,7 +237,7 @@ namespace GWConquest { var fui = icon.GetComponentInParent(); if(fui != null && target == fui.LeaderIcon) { - icon.Unit.Formation.AssignLeaderRpc(icon.Unit); + icon.Unit.Formation.AssignLeaderServerRpc(icon.Unit); } } else if(icon.Unit.BattleState == BattleUnitState.InReserve && icon.Unit.CanGoToFlank) @@ -250,7 +250,7 @@ namespace GWConquest { if(flankUI.BattleFlank.GetUnit(flankIndex) == null) { - Battle.MoveUnitToFlankRpc(icon.Unit, flankUI.BattleFlank, flankIndex); + Battle.MoveUnitToFlankServerRpc(icon.Unit, flankUI.BattleFlank, flankIndex); } diff --git a/Assets/GWConquest/Scripts/UI/BattleFlankUI.cs b/Assets/GWConquest/Scripts/UI/BattleFlankUI.cs index 0378e6c..48aa090 100644 --- a/Assets/GWConquest/Scripts/UI/BattleFlankUI.cs +++ b/Assets/GWConquest/Scripts/UI/BattleFlankUI.cs @@ -107,7 +107,7 @@ namespace GWConquest { { if(icon.Unit.BattleState == BattleUnitState.OnFlank) { - battleUI.Battle.MoveUnitToReserveRpc(icon.Unit); + battleUI.Battle.MoveUnitToReserveServerRpc(icon.Unit); } } diff --git a/Assets/GWConquest/Scripts/UI/BattleUI.cs b/Assets/GWConquest/Scripts/UI/BattleUI.cs index e5ff1d1..7be2f71 100644 --- a/Assets/GWConquest/Scripts/UI/BattleUI.cs +++ b/Assets/GWConquest/Scripts/UI/BattleUI.cs @@ -480,7 +480,7 @@ namespace GWConquest if (hasTarget) { - SelectingTargetUnit.StartShellingRpc(flank); + SelectingTargetUnit.StartShellingServerRpc(flank); } EndTargetSelection(); diff --git a/Assets/GWConquest/Scripts/UI/DebugUI.cs b/Assets/GWConquest/Scripts/UI/DebugUI.cs index 7e2ecbb..06fbe5b 100644 --- a/Assets/GWConquest/Scripts/UI/DebugUI.cs +++ b/Assets/GWConquest/Scripts/UI/DebugUI.cs @@ -59,7 +59,7 @@ namespace GWConquest for(int i = 0; i < amount; i++) { - Unit.SpawnUnit(zone, uc, player); + GWNetworkManager.Instance.SpawnUnit(zone, uc, player); } } diff --git a/Assets/GWConquest/Scripts/UI/ItemMoveTooltip.cs b/Assets/GWConquest/Scripts/UI/ItemMoveTooltip.cs index 7d5f815..76f3549 100644 --- a/Assets/GWConquest/Scripts/UI/ItemMoveTooltip.cs +++ b/Assets/GWConquest/Scripts/UI/ItemMoveTooltip.cs @@ -76,7 +76,7 @@ namespace GWConquest { NetworkBehaviour originBeh = Origin.Type == TransportUIElement.ObjectType.District ? Origin.District : Origin.Formation; NetworkBehaviour targetBeh = Target.Type == TransportUIElement.ObjectType.District ? Target.District : Target.Formation; - ServerCallbacks.Instance.MoveItemRpc(originBeh, targetBeh, MovedItem.ItemName, current); + GWNetworkManager.Instance.MoveItemServerRpc(originBeh, targetBeh, MovedItem.ItemName, current); } else { BoltLog.Error("Amount {0} of item {1} is not transferable ({2})", current, MovedItem.ItemName, transferable); diff --git a/Assets/GWConquest/Scripts/UI/ProductionMenu.cs b/Assets/GWConquest/Scripts/UI/ProductionMenu.cs index efebe15..ebdd36a 100644 --- a/Assets/GWConquest/Scripts/UI/ProductionMenu.cs +++ b/Assets/GWConquest/Scripts/UI/ProductionMenu.cs @@ -130,20 +130,7 @@ namespace GWConquest { if(DebugUI.FreeBuild || buildable.BuildCost == null || factory.District.CanBuild(buildable)) { - AddProductionEvent ev = AddProductionEvent.Create(GlobalTargets.OnlyServer); - ev.Factory = factory.entity; - if(buildable is UnitClass) - { - ev.UnitClass = (buildable as UnitClass).ShortName; - ev.IsUpgrade = false; - } - else if(buildable is DistrictUpgrade) - { - ev.UnitClass = (buildable as DistrictUpgrade).ShortName; - ev.IsUpgrade = true; - } - ev.Player = Player.CurrentPlayer.entity; - ev.Send(); + factory.AddProductionQueueEntryServerRpc(buildable.ID, buildable is DistrictUpgrade, Player.CurrentPlayer); } } diff --git a/Assets/GWConquest/Scripts/UI/TransportUIUnitIcon.cs b/Assets/GWConquest/Scripts/UI/TransportUIUnitIcon.cs index 62a54bd..361f2cc 100644 --- a/Assets/GWConquest/Scripts/UI/TransportUIUnitIcon.cs +++ b/Assets/GWConquest/Scripts/UI/TransportUIUnitIcon.cs @@ -41,7 +41,7 @@ namespace GWConquest var LeaderIcon = ParentElement.DragTransform; if (RectTransformUtility.RectangleContainsScreenPoint(LeaderIcon, Input.mousePosition)) { - ParentElement.Formation.AssignLeaderRpc(Unit); + ParentElement.Formation.AssignLeaderServerRpc(Unit); } } diff --git a/Assets/GWConquest/Scripts/Unit.cs b/Assets/GWConquest/Scripts/Unit.cs index 4e770da..5b0c33b 100644 --- a/Assets/GWConquest/Scripts/Unit.cs +++ b/Assets/GWConquest/Scripts/Unit.cs @@ -223,7 +223,7 @@ namespace GWConquest Inventory.StorageCapacity = newClass.InventorySlots; Equipment.StorageCapacity = newClass.EquipmentSlots; - if(IsOwner) + if(IsServer) { Fuel = newClass.FuelCapacity; Food = newClass.FoodCapacity; @@ -253,26 +253,6 @@ namespace GWConquest Morale = uc.Morale; } - public static Unit SpawnUnit(Zone zone, UnitClass uc, Player player) - { - Formation playerFormation = zone.Formations.FirstOrDefault(f => f.Player == player); - if (playerFormation == null) - { - playerFormation = Formation.SpawnFormation(zone, player); - } - - BoltEntity unitEntity = BoltNetwork.Instantiate(BoltPrefabs.Unit); - player.AssignControl(unitEntity); - Unit unit = unitEntity.GetComponent(); - unit.InstantiateWithClass(uc); - unit.Formation = playerFormation; - playerFormation.AddUnit(unit); - - BoltLog.Info("Spawned unit {0} for player {1} in formation {2}", unit, player, playerFormation); - - return unit; - } - public void TakeDamage(int damage, Unit attacker, bool isGlancingHit=false, WeaponStats weapon=null, WeaponType weaponType=WeaponType.Light) { int remainingDamage = damage; @@ -365,7 +345,7 @@ namespace GWConquest { animType = DamageAnimationType.GlancingHit; } - PlayUnitDamageAnimation(weaponType, animType, attacker); + PlayUnitDamageAnimationClientRpc(weaponType, animType, attacker); if(Hitpoints <= 0) { @@ -383,7 +363,7 @@ namespace GWConquest } [ClientRpc] - public void PlayUnitDamageAnimation(WeaponType weaponType, DamageAnimationType animationType, NullableNetworkBehaviourReference attacker) + public void PlayUnitDamageAnimationClientRpc(WeaponType weaponType, DamageAnimationType animationType, NullableNetworkBehaviourReference attacker) { if(IconEnabled) { @@ -453,77 +433,79 @@ namespace GWConquest public void FixedUpdate() { - var battle = CurrentBattle; - if(!IsDead && battle != null && !battle.IsInPreparing) + if (IsServer) { - if(BattleState == BattleUnitState.Arriving) + var battle = CurrentBattle; + if (!IsDead && battle != null && !battle.IsInPreparing) { - if(!Formation.IsMoving) + if (BattleState == BattleUnitState.Arriving) { - BattleState = BattleUnitState.InReserve; - } - } - - if (ActionCooldown <= 0) - { - actionCooldown.Value = 0; - if (BattleState == BattleUnitState.MovingToFlank) - { - BattleState = BattleUnitState.OnFlank; - - int requiredFuel = GetFuelCostForFlank(); - if(requiredFuel <= TotalFuel) + if (!Formation.IsMoving) { - ConsumeTotalFuel(requiredFuel); + BattleState = BattleUnitState.InReserve; } } - else if (BattleState == BattleUnitState.MovingToReserve) + + if (ActionCooldown <= 0) { - BattleState = BattleUnitState.InReserve; - CurrentFlank.RemoveUnit(this); - CurrentFlank = null; + actionCooldown.Value = 0; + if (BattleState == BattleUnitState.MovingToFlank) + { + BattleState = BattleUnitState.OnFlank; - int requiredFuel = GetFuelCostForFlank(); - if(requiredFuel <= TotalFuel) + int requiredFuel = GetFuelCostForFlank(); + if (requiredFuel <= TotalFuel) + { + ConsumeTotalFuel(requiredFuel); + } + } + else if (BattleState == BattleUnitState.MovingToReserve) { - ConsumeTotalFuel(requiredFuel); + BattleState = BattleUnitState.InReserve; + CurrentFlank.RemoveUnit(this); + CurrentFlank = null; + + int requiredFuel = GetFuelCostForFlank(); + if (requiredFuel <= TotalFuel) + { + ConsumeTotalFuel(requiredFuel); + } + } + else if (BattleState == BattleUnitState.StartingShelling) + { + BattleState = BattleUnitState.Shelling; + } + else if (BattleState == BattleUnitState.StoppingShelling) + { + BattleState = BattleUnitState.InReserve; + FlankTarget = null; } } - else if(BattleState == BattleUnitState.StartingShelling) - { - BattleState = BattleUnitState.Shelling; - } - else if(BattleState == BattleUnitState.StoppingShelling) + else { - BattleState = BattleUnitState.InReserve; - FlankTarget = null; + actionCooldown.Value -= Time.fixedDeltaTime; } - } - else - { - actionCooldown.Value -= Time.fixedDeltaTime; - } - if(ShieldsCooldown > 0) - { - ShieldsCooldown -= Time.fixedDeltaTime; - if(ShieldsCooldown <= 0) + if (ShieldsCooldown > 0) { - ShieldsCooldown = 0; + ShieldsCooldown -= Time.fixedDeltaTime; + if (ShieldsCooldown <= 0) + { + ShieldsCooldown = 0; + } } - } - if(ShieldsCooldown == 0 && Shields < Class.Shields) - { - float regRate = Class.ShieldRegeneration / GameManager.Instance.BattleTurnLength; - Shields += regRate * BoltNetwork.FrameDeltaTime; - if(Shields > Class.Shields) + if (ShieldsCooldown == 0 && Shields < Class.Shields) { - Shields = Class.Shields; + float regRate = Class.ShieldRegeneration / GameManager.Instance.BattleTurnLength; + Shields += regRate * BoltNetwork.FrameDeltaTime; + if (Shields > Class.Shields) + { + Shields = Class.Shields; + } } } } - } //TODO shelling auch auf Flanke! @@ -561,7 +543,7 @@ namespace GWConquest } [ServerRpc] - public void StartShellingRpc(NetworkBehaviourReference target) + public void StartShellingServerRpc(NetworkBehaviourReference target) { StartShelling(target.GetBehaviour()); }