Skip to content

Commit

Permalink
Extract StoresResources from Harvester
Browse files Browse the repository at this point in the history
  • Loading branch information
PunkPun committed May 2, 2023
1 parent 8f511a3 commit cc1a2aa
Show file tree
Hide file tree
Showing 21 changed files with 288 additions and 101 deletions.
27 changes: 25 additions & 2 deletions OpenRA.Game/Traits/TraitsInterfaces.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,31 @@ public interface IVoiced
bool HasVoice(Actor self, string voice);
}

[RequireExplicitImplementation]
public interface IStoreResources { int Capacity { get; } }
public interface IStoresResourcesInfo : ITraitInfoInterface
{
string[] ResourceTypes { get; }
}

public interface IStoresResources
{
bool HasType(string resourceType);

/// <summary>The amount of resources that can be stored.</summary>
int Capacity { get; }

/// <summary>Stored resources.</summary>
/// <remarks>Dictionary key refers to resourceType, value refers to resource amount.</remarks>
IReadOnlyDictionary<string, int> Contents { get; }

/// <summary>A performance cheap method of getting the total sum of contents.</summary>
int ContentsSum { get; }

/// <summary>Returns the amount of <paramref name="value"/> that was not added.</summary>
int AddResource(string resourceType, int value);

/// <summary>Returns the amount of <paramref name="value"/> that was not removed.</summary>
int RemoveResource(string resourceType, int value);
}

public interface IEffectiveOwner
{
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Activities/HarvestResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public override bool Tick(Actor self)
if (resource.Type == null || resourceLayer.RemoveResource(resource.Type, self.Location) != 1)
return true;

harv.AcceptResource(self, resource.Type);
harv.AddResource(self, resource.Type);

foreach (var t in notifyHarvesterActions)
t.Harvested(self, resource.Type);
Expand Down
84 changes: 42 additions & 42 deletions OpenRA.Mods.Common/Traits/Harvester.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using OpenRA.Mods.Common.Activities;
using OpenRA.Mods.Common.Orders;
Expand All @@ -20,7 +19,7 @@

namespace OpenRA.Mods.Common.Traits
{
public class HarvesterInfo : ConditionalTraitInfo, Requires<MobileInfo>
public class HarvesterInfo : ConditionalTraitInfo, Requires<MobileInfo>, Requires<IStoresResourcesInfo>, IRulesetLoaded
{
public readonly HashSet<string> DeliveryBuildings = new();

Expand All @@ -30,9 +29,6 @@ public class HarvesterInfo : ConditionalTraitInfo, Requires<MobileInfo>
[Desc("Cell to move to when automatically unblocking DeliveryBuilding.")]
public readonly CVec UnblockCell = new(0, 4);

[Desc("How much resources it can carry.")]
public readonly int Capacity = 28;

public readonly int BaleLoadDelay = 4;

[Desc("How fast it can dump its bales.")]
Expand All @@ -44,7 +40,7 @@ public class HarvesterInfo : ConditionalTraitInfo, Requires<MobileInfo>
public readonly int HarvestFacings = 0;

[Desc("Which resources it can harvest.")]
public readonly HashSet<string> Resources = new();
public readonly string[] Resources = Array.Empty<string>();

[Desc("Percentage of maximum speed when fully loaded.")]
public readonly int FullyLoadedSpeed = 85;
Expand Down Expand Up @@ -102,17 +98,35 @@ public class HarvesterInfo : ConditionalTraitInfo, Requires<MobileInfo>
public readonly string HarvestCursor = "harvest";

public override object Create(ActorInitializer init) { return new Harvester(init.Self, this); }

void IRulesetLoaded<ActorInfo>.RulesetLoaded(Ruleset rules, ActorInfo info)
{
var resourceTypes = Resources.ToList();

if (resourceTypes.Count == 0)
throw new YamlException($"Harvester.{nameof(Resources)} is empty.");

foreach (var sr in info.TraitInfos<IStoresResourcesInfo>())
{
foreach (var type in sr.ResourceTypes)
{
if (Resources.Contains(type) && resourceTypes.Contains(type))
resourceTypes.Remove(type);
}
}

if (resourceTypes.Count != 0)
throw new YamlException($"Invalid Harvester.{nameof(Resources)} types: {string.Join(',', resourceTypes)}.");
}
}

public class Harvester : ConditionalTrait<HarvesterInfo>, IIssueOrder, IResolveOrder, IOrderVoice,
ISpeedModifier, ISync, INotifyCreated
{
public readonly IReadOnlyDictionary<string, int> Contents;

readonly Mobile mobile;
readonly IResourceLayer resourceLayer;
readonly ResourceClaimLayer claimLayer;
readonly Dictionary<string, int> contents = new();
readonly IStoresResources[] storesResources;
int conditionToken = Actor.InvalidConditionToken;

[Sync]
Expand All @@ -124,23 +138,11 @@ public class Harvester : ConditionalTrait<HarvesterInfo>, IIssueOrder, IResolveO
[Sync]
int currentUnloadTicks;

[Sync]
public int ContentHash
{
get
{
var value = 0;
foreach (var c in contents)
value += c.Value << c.Key.Length;
return value;
}
}

public Harvester(Actor self, HarvesterInfo info)
: base(info)
{
Contents = new ReadOnlyDictionary<string, int>(contents);
mobile = self.Trait<Mobile>();
storesResources = self.TraitsImplementing<IStoresResources>().Where(sr => info.Resources.Any(r => sr.HasType(r))).ToArray();
resourceLayer = self.World.WorldActor.Trait<IResourceLayer>();
claimLayer = self.World.WorldActor.Trait<ResourceClaimLayer>();
}
Expand Down Expand Up @@ -216,9 +218,9 @@ public Actor ClosestProc(Actor self, Actor ignore)
return null;
}

public bool IsFull => contents.Values.Sum() == Info.Capacity;
public bool IsEmpty => contents.Values.Sum() == 0;
public int Fullness => contents.Values.Sum() * 100 / Info.Capacity;
public bool IsFull => storesResources.All(sr => sr.ContentsSum >= sr.Capacity);
public bool IsEmpty => storesResources.All(sr => sr.ContentsSum == 0);
public int Fullness => storesResources.Sum(sr => sr.ContentsSum * 100 / sr.Capacity) / storesResources.Length;

void UpdateCondition(Actor self)
{
Expand All @@ -233,12 +235,11 @@ void UpdateCondition(Actor self)
conditionToken = self.RevokeCondition(conditionToken);
}

public void AcceptResource(Actor self, string resourceType)
public void AddResource(Actor self, string resourceType)
{
if (!contents.ContainsKey(resourceType))
contents[resourceType] = 1;
else
contents[resourceType]++;
foreach (var sr in storesResources)
if (sr.AddResource(resourceType, 1) == 0)
break;

UpdateCondition(self);
}
Expand All @@ -250,28 +251,27 @@ public virtual bool TickUnload(Actor self, Actor proc)
if (--currentUnloadTicks > 0)
return false;

if (contents.Keys.Count > 0)
var acceptResources = proc.Trait<IAcceptResources>();
foreach (var sr in storesResources)
{
var acceptResources = proc.Trait<IAcceptResources>();
foreach (var c in contents)
if (sr.ContentsSum == 0)
continue;

foreach (var c in sr.Contents)
{
var resourceType = c.Key;
var count = Math.Min(c.Value, Info.BaleUnloadAmount);
var accepted = acceptResources.AcceptResources(resourceType, count);
var accepted = acceptResources.AcceptResources(c.Key, count);
if (accepted == 0)
continue;

contents[resourceType] -= accepted;
if (contents[resourceType] <= 0)
contents.Remove(resourceType);

sr.RemoveResource(c.Key, accepted);
currentUnloadTicks = Info.BaleUnloadDelay;
UpdateCondition(self);
return false;
}
}

return contents.Count == 0;
return IsEmpty;
}

public bool CanHarvestCell(CPos cell)
Expand Down Expand Up @@ -368,14 +368,14 @@ void IResolveOrder.ResolveOrder(Actor self, Order order)

int ISpeedModifier.GetSpeedModifier()
{
return 100 - (100 - Info.FullyLoadedSpeed) * contents.Values.Sum() / Info.Capacity;
return 100 - (100 - Info.FullyLoadedSpeed) * Fullness / 100;
}

protected override void TraitDisabled(Actor self)
{
base.TraitDisabled(self);
LastLinkedProc = null;
LinkedProc = null;
contents.Clear();

if (conditionToken != Actor.InvalidConditionToken)
conditionToken = self.RevokeCondition(conditionToken);
Expand Down
4 changes: 2 additions & 2 deletions OpenRA.Mods.Common/Traits/Player/PlayerResources.cs
Original file line number Diff line number Diff line change
Expand Up @@ -204,12 +204,12 @@ public bool TakeCash(int num, bool notifyLowFunds = false)
return true;
}

public void AddStorage(int capacity)
public void AddStorageCapacity(int capacity)
{
ResourceCapacity += capacity;
}

public void RemoveStorage(int capacity)
public void RemoveStorageCapacity(int capacity)
{
ResourceCapacity -= capacity;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

namespace OpenRA.Mods.Common.Traits.Render
{
public class WithHarvesterPipsDecorationInfo : WithDecorationBaseInfo, Requires<HarvesterInfo>
public class WithStoresResourcesPipsDecorationInfo : WithDecorationBaseInfo, Requires<IStoresResourcesInfo>
{
[FieldLoader.Require]
[Desc("Number of pips to display how filled unit is.")]
Expand All @@ -42,26 +42,26 @@ public class WithHarvesterPipsDecorationInfo : WithDecorationBaseInfo, Requires<
[PaletteReference]
public readonly string Palette = "chrome";

public override object Create(ActorInitializer init) { return new WithHarvesterPipsDecoration(init.Self, this); }
public override object Create(ActorInitializer init) { return new WithStoresResourcesPipsDecoration(init.Self, this); }
}

public class WithHarvesterPipsDecoration : WithDecorationBase<WithHarvesterPipsDecorationInfo>
public class WithStoresResourcesPipsDecoration : WithDecorationBase<WithStoresResourcesPipsDecorationInfo>
{
readonly Harvester harvester;
readonly IStoresResources storesResources;
readonly Animation pips;

public WithHarvesterPipsDecoration(Actor self, WithHarvesterPipsDecorationInfo info)
public WithStoresResourcesPipsDecoration(Actor self, WithStoresResourcesPipsDecorationInfo info)
: base(self, info)
{
harvester = self.Trait<Harvester>();
storesResources = self.Trait<IStoresResources>();
pips = new Animation(self.World, info.Image);
}

string GetPipSequence(int i)
{
var n = i * harvester.Info.Capacity / Info.PipCount;
var n = i * storesResources.Capacity / Info.PipCount;

foreach (var rt in harvester.Contents)
foreach (var rt in storesResources.Contents)
{
if (n < rt.Value)
{
Expand Down
67 changes: 67 additions & 0 deletions OpenRA.Mods.Common/Traits/StoresPlayerResources.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#region Copyright & License Information
/*
* Copyright (c) The OpenRA Developers and Contributors
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion

using OpenRA.Primitives;
using OpenRA.Traits;

namespace OpenRA.Mods.Common.Traits
{
[Desc("Adds capacity to a player's harvested resource limit.")]
public class StoresPlayerResourcesInfo : TraitInfo
{
[FieldLoader.Require]
public readonly int Capacity = 0;

public override object Create(ActorInitializer init) { return new StoresPlayerResources(init.Self, this); }
}

public class StoresPlayerResources : INotifyOwnerChanged, INotifyCapture, INotifyKilled, INotifyAddedToWorld, INotifyRemovedFromWorld
{
readonly StoresPlayerResourcesInfo info;
PlayerResources player;

public int Stored => player.ResourceCapacity == 0 ? 0 : (int)((long)info.Capacity * player.Resources / player.ResourceCapacity);

public StoresPlayerResources(Actor self, StoresPlayerResourcesInfo info)
{
this.info = info;
player = self.Owner.PlayerActor.Trait<PlayerResources>();
}

void INotifyOwnerChanged.OnOwnerChanged(Actor self, Player oldOwner, Player newOwner)
{
player = newOwner.PlayerActor.Trait<PlayerResources>();
}

void INotifyCapture.OnCapture(Actor self, Actor captor, Player oldOwner, Player newOwner, BitSet<CaptureType> captureTypes)
{
var resources = Stored;
oldOwner.PlayerActor.Trait<PlayerResources>().TakeResources(resources);
newOwner.PlayerActor.Trait<PlayerResources>().GiveResources(resources);
}

void INotifyKilled.Killed(Actor self, AttackInfo e)
{
// Lose the stored resources.
player.TakeResources(Stored);
}

void INotifyAddedToWorld.AddedToWorld(Actor self)
{
player.AddStorageCapacity(info.Capacity);
}

void INotifyRemovedFromWorld.RemovedFromWorld(Actor self)
{
player.RemoveStorageCapacity(info.Capacity);
}
}
}

0 comments on commit cc1a2aa

Please sign in to comment.