CatStation/Content.Client/Power/Battery/BatteryMenu.xaml.cs
Dmitry 25c5e59248
Upstream (#3172)
Signed-off-by: Prole <172158352+Prole0@users.noreply.github.com>
Co-authored-by: PJBot <pieterjan.briers+bot@gmail.com>
Co-authored-by: ScarKy0 <106310278+ScarKy0@users.noreply.github.com>
Co-authored-by: Samuka-C <47865393+Samuka-C@users.noreply.github.com>
Co-authored-by: ArtisticRoomba <145879011+ArtisticRoomba@users.noreply.github.com>
Co-authored-by: Partmedia <kevinz5000@gmail.com>
Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>
Co-authored-by: themias <89101928+themias@users.noreply.github.com>
Co-authored-by: Victor Shen <71985089+Vexerot@users.noreply.github.com>
Co-authored-by: Ed <96445749+TheShuEd@users.noreply.github.com>
Co-authored-by: Milon <milonpl.git@proton.me>
Co-authored-by: Kirus59 <145689588+Kirus59@users.noreply.github.com>
Co-authored-by: Nemanja <98561806+EmoGarbage404@users.noreply.github.com>
Co-authored-by: Stomf <5dorkydorks@gmail.com>
Co-authored-by: drakewill-CRL <46307022+drakewill-CRL@users.noreply.github.com>
Co-authored-by: PraxisMapper <praxismapper@gmail.com>
Co-authored-by: EmoGarbage404 <retron404@gmail.com>
Co-authored-by: lzk <124214523+lzk228@users.noreply.github.com>
Co-authored-by: Princess Cheeseballs <66055347+Pronana@users.noreply.github.com>
Co-authored-by: IProduceWidgets <107586145+IProduceWidgets@users.noreply.github.com>
Co-authored-by: TytosB <54259736+TytosB@users.noreply.github.com>
Co-authored-by: abadaba695 <spacestation13thingy@gmail.com>
Co-authored-by: kosticia <kosticia46@gmail.com>
Co-authored-by: Thinbug <101073555+Thinbug0@users.noreply.github.com>
Co-authored-by: pathetic meowmeow <uhhadd@gmail.com>
Co-authored-by: SlamBamActionman <83650252+SlamBamActionman@users.noreply.github.com>
Co-authored-by: Boaz1111 <149967078+Boaz1111@users.noreply.github.com>
Co-authored-by: ActiveMammmoth <140334666+ActiveMammmoth@users.noreply.github.com>
Co-authored-by: Myra <vasilis@pikachu.systems>
Co-authored-by: Whatstone <166147148+whatston3@users.noreply.github.com>
Co-authored-by: Pieter-Jan Briers <pieterjan.briers+git@gmail.com>
Co-authored-by: K-Dynamic <20566341+K-Dynamic@users.noreply.github.com>
Co-authored-by: Gentleman-Bird <dcgreen406@gmail.com>
Co-authored-by: metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
Co-authored-by: BIGZi0348 <svalker0348@gmail.com>
Co-authored-by: LaCumbiaDelCoronavirus <90893484+LaCumbiaDelCoronavirus@users.noreply.github.com>
Co-authored-by: imatsoup <93290208+imatsoup@users.noreply.github.com>
Co-authored-by: Matthew Herber <32679887+happyrobot33@users.noreply.github.com>
Co-authored-by: Ertanic <36124833+Ertanic@users.noreply.github.com>
Co-authored-by: MissKay1994 <15877268+MissKay1994@users.noreply.github.com>
Co-authored-by: Errant <35878406+Errant-4@users.noreply.github.com>
Co-authored-by: eoineoineoin <helloworld@eoinrul.es>
Co-authored-by: Tiniest Shark <head.rebel@yahoo.com>
Co-authored-by: nikitosych <boriszyn@gmail.com>
Co-authored-by: Tayrtahn <tayrtahn@gmail.com>
Co-authored-by: Perry Fraser <perryprog@users.noreply.github.com>
Co-authored-by: YoungThug <ramialanbagy@gmail.com>
Co-authored-by: beck-thompson <107373427+beck-thompson@users.noreply.github.com>
Co-authored-by: metalgearsloth <comedian_vs_clown@hotmail.com>
Co-authored-by: Southbridge <7013162+southbridge-fur@users.noreply.github.com>
Co-authored-by: Vladislav Suchkov <20380250+murolem@users.noreply.github.com>
Co-authored-by: Prole <172158352+Prole0@users.noreply.github.com>
Co-authored-by: Unkn0wn_Gh0st <shadowstalkermll@gmail.com>
Co-authored-by: 3nderall <101940324+3nderall@users.noreply.github.com>
Co-authored-by: Radezolid <snappednexus@gmail.com>
Co-authored-by: J <billsmith116@gmail.com>
Co-authored-by: Ghagliiarghii <68826635+Ghagliiarghii@users.noreply.github.com>
Co-authored-by: chromiumboy <50505512+chromiumboy@users.noreply.github.com>
Co-authored-by: youtissoum <51883137+youtissoum@users.noreply.github.com>
Co-authored-by: Minemoder5000 <minemoder50000@gmail.com>
Co-authored-by: Spanky <scott@wearejacob.com>
Co-authored-by: Spessmann <156740760+Spessmann@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: brainfood1183 <113240905+brainfood1183@users.noreply.github.com>
Co-authored-by: Deerstop <edainturner@gmail.com>
Co-authored-by: B_Kirill <153602297+B-Kirill@users.noreply.github.com>
Co-authored-by: archee1 <archee3@hotmail.co.uk>
Co-authored-by: Cojoke <83733158+Cojoke-dot@users.noreply.github.com>
Co-authored-by: Quantum-cross <7065792+Quantum-cross@users.noreply.github.com>
Co-authored-by: poklj <compgeek223@gmail.com>
Co-authored-by: Krunklehorn <42424291+Krunklehorn@users.noreply.github.com>
Co-authored-by: OnyxTheBrave <131422822+OnyxTheBrave@users.noreply.github.com>
Co-authored-by: UpAndLeaves <92269094+Alpha-Two@users.noreply.github.com>
Co-authored-by: Flareguy <78941145+Flareguy@users.noreply.github.com>
Co-authored-by: Zalycon <84675130+Zalycon@users.noreply.github.com>
Co-authored-by: deltanedas <39013340+deltanedas@users.noreply.github.com>
Co-authored-by: Verm <32827189+Vermidia@users.noreply.github.com>
Co-authored-by: nikthechampiongr <32041239+nikthechampiongr@users.noreply.github.com>
Co-authored-by: ScarKy0 <scarky0@onet.eu>
Co-authored-by: Dmitry <57028746+dimm00n@users.noreply.github.com>
2025-05-24 11:00:17 +03:00

280 lines
10 KiB
C#

using System.Diagnostics.CodeAnalysis;
using Content.Client.Stylesheets;
using Content.Client.UserInterface.Controls;
using Content.Shared.Power;
using Content.Shared.Rounding;
using Robust.Client.AutoGenerated;
using Robust.Client.Graphics;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.XAML;
using Robust.Shared.Timing;
namespace Content.Client.Power.Battery;
/// <summary>
/// Interface control for batteries.
/// </summary>
/// <seealso cref="BatteryBoundUserInterface"/>
[GenerateTypedNameReferences]
public sealed partial class BatteryMenu : FancyWindow
{
// Cutoff for the ETA time to switch from "~" to ">" and cap out.
private const float MaxEtaValueMinutes = 60;
// Cutoff where ETA times likely don't make sense and it's better to just say "N/A".
private const float NotApplicableEtaHighCutoffMinutes = 1000;
private const float NotApplicableEtaLowCutoffMinutes = 0.01f;
// Fudge factor to ignore small charge/discharge values, that are likely caused by floating point rounding errors.
private const float PrecisionRoundFactor = 100_000;
// Colors used for the storage cell bar graphic.
private static readonly Color[] StorageColors =
[
StyleNano.DangerousRedFore,
Color.FromHex("#C49438"),
Color.FromHex("#B3BF28"),
StyleNano.GoodGreenFore,
];
// StorageColors but dimmed for "off" bars.
private static readonly Color[] DimStorageColors =
[
DimStorageColor(StorageColors[0]),
DimStorageColor(StorageColors[1]),
DimStorageColor(StorageColors[2]),
DimStorageColor(StorageColors[3]),
];
// Parameters for the sine wave pulsing animations for active power lines in the UI.
private static readonly Color ActivePowerLineHighColor = Color.FromHex("#CCC");
private static readonly Color ActivePowerLineLowColor = Color.FromHex("#888");
private const float PowerPulseFactor = 4;
// Dependencies
[Dependency] private readonly IEntityManager _entityManager = null!;
[Dependency] private readonly ILocalizationManager _loc = null!;
// Active and inactive style boxes for power lines.
// We modify _activePowerLineStyleBox's properties programmatically to implement the pulsing animation.
private readonly StyleBoxFlat _activePowerLineStyleBox = new();
private readonly StyleBoxFlat _inactivePowerLineStyleBox = new() { BackgroundColor = Color.FromHex("#555") };
// Style boxes for the storage cell bar graphic.
// We modify the properties of these to change the bars' colors.
private StyleBoxFlat[] _chargeMeterBoxes;
// State for the powerline pulsing animation.
private float _powerPulseValue;
// State for the storage cell bar graphic and its blinking effect.
private float _blinkPulseValue;
private bool _blinkPulse;
private int _storageLevel;
private bool _hasStorageDelta;
// The entity that this UI is for.
private EntityUid _entity;
// Used to avoid sending input events when updating slider values.
private bool _suppressSliderEvents;
// Events for the BUI to subscribe to.
public event Action<bool>? OnInBreaker;
public event Action<bool>? OnOutBreaker;
public event Action<float>? OnChargeRate;
public event Action<float>? OnDischargeRate;
public BatteryMenu()
{
RobustXamlLoader.Load(this);
IoCManager.InjectDependencies(this);
InitChargeMeter();
InBreaker.StateChanged += val => OnInBreaker?.Invoke(val);
OutBreaker.StateChanged += val => OnOutBreaker?.Invoke(val);
ChargeRateSlider.OnValueChanged += _ =>
{
if (!_suppressSliderEvents)
OnChargeRate?.Invoke(ChargeRateSlider.Value);
};
DischargeRateSlider.OnValueChanged += _ =>
{
if (!_suppressSliderEvents)
OnDischargeRate?.Invoke(DischargeRateSlider.Value);
};
}
public void SetEntity(EntityUid entity)
{
_entity = entity;
this.SetInfoFromEntity(_entityManager, _entity);
EntityView.SetEntity(entity);
}
[MemberNotNull(nameof(_chargeMeterBoxes))]
public void InitChargeMeter()
{
_chargeMeterBoxes = new StyleBoxFlat[StorageColors.Length];
for (var i = StorageColors.Length - 1; i >= 0; i--)
{
var styleBox = new StyleBoxFlat();
_chargeMeterBoxes[i] = styleBox;
for (var j = 0; j < ChargeMeter.Columns; j++)
{
var control = new PanelContainer
{
Margin = new Thickness(2),
PanelOverride = styleBox,
HorizontalExpand = true,
VerticalExpand = true,
};
ChargeMeter.AddChild(control);
}
}
}
public void Update(BatteryBuiState msg)
{
var inValue = msg.CurrentReceiving;
var outValue = msg.CurrentSupply;
var storageDelta = inValue - outValue;
// Mask rounding errors in power code.
if (Math.Abs(storageDelta) < msg.Capacity / PrecisionRoundFactor)
storageDelta = 0;
// Update power lines based on a ton of parameters.
SetPowerLineState(InPowerLine, msg.SupplyingNetworkHasPower);
SetPowerLineState(OutPowerLine, msg.LoadingNetworkHasPower);
SetPowerLineState(InSecondPowerLine, msg.SupplyingNetworkHasPower && msg.CanCharge);
SetPowerLineState(ChargePowerLine, msg.SupplyingNetworkHasPower && msg.CanCharge && storageDelta > 0);
SetPowerLineState(PassthroughPowerLine, msg.SupplyingNetworkHasPower && msg.CanCharge && msg.CanDischarge);
SetPowerLineState(OutSecondPowerLine,
msg.CanDischarge && (msg.Charge > 0 || msg.SupplyingNetworkHasPower && msg.CanCharge));
SetPowerLineState(DischargePowerLine, storageDelta < 0);
// Update breakers.
InBreaker.IsOn = msg.CanCharge;
OutBreaker.IsOn = msg.CanDischarge;
// Update various power values.
InValue.Text = FormatPower(inValue);
OutValue.Text = FormatPower(outValue);
PassthroughValue.Text = FormatPower(Math.Min(msg.CurrentReceiving, msg.CurrentSupply));
ChargeMaxValue.Text = FormatPower(msg.MaxChargeRate);
DischargeMaxValue.Text = FormatPower(msg.MaxSupply);
ChargeCurrentValue.Text = FormatPower(Math.Max(0, storageDelta));
DischargeCurrentValue.Text = FormatPower(Math.Max(0, -storageDelta));
// Update charge/discharge rate sliders.
_suppressSliderEvents = true;
ChargeRateSlider.MaxValue = msg.MaxMaxChargeRate;
ChargeRateSlider.MinValue = msg.MinMaxChargeRate;
ChargeRateSlider.Value = msg.MaxChargeRate;
DischargeRateSlider.MaxValue = msg.MaxMaxSupply;
DischargeRateSlider.MinValue = msg.MinMaxSupply;
DischargeRateSlider.Value = msg.MaxSupply;
_suppressSliderEvents = false;
// Update ETA display.
var storageEtaDiff = storageDelta > 0 ? (msg.Capacity - msg.Charge) * (1 / msg.Efficiency) : -msg.Charge;
var etaTimeSeconds = storageEtaDiff / storageDelta;
var etaTimeMinutes = etaTimeSeconds / 60.0;
EtaLabel.Text = _loc.GetString(
storageDelta > 0 ? "battery-menu-eta-full" : "battery-menu-eta-empty");
if (!double.IsFinite(etaTimeMinutes)
|| Math.Abs(etaTimeMinutes) > NotApplicableEtaHighCutoffMinutes
|| Math.Abs(etaTimeMinutes) < NotApplicableEtaLowCutoffMinutes)
{
EtaValue.Text = _loc.GetString("battery-menu-eta-value-na");
}
else
{
EtaValue.Text = _loc.GetString(
etaTimeMinutes > MaxEtaValueMinutes ? "battery-menu-eta-value-max" : "battery-menu-eta-value",
("minutes", Math.Min(Math.Ceiling(etaTimeMinutes), MaxEtaValueMinutes)));
}
// Update storage display.
StoredPercentageValue.Text = _loc.GetString(
"battery-menu-stored-percent-value",
("value", msg.Charge / msg.Capacity));
StoredEnergyValue.Text = _loc.GetString(
"battery-menu-stored-energy-value",
("value", msg.Charge));
// Update charge meter.
_storageLevel = ContentHelpers.RoundToNearestLevels(msg.Charge, msg.Capacity, _chargeMeterBoxes.Length);
_hasStorageDelta = Math.Abs(storageDelta) > 0;
}
private static Color DimStorageColor(Color color)
{
var hsv = Color.ToHsv(color);
hsv.Z /= 5;
return Color.FromHsv(hsv);
}
private void SetPowerLineState(PanelContainer control, bool value)
{
control.PanelOverride = value ? _activePowerLineStyleBox : _inactivePowerLineStyleBox;
}
private string FormatPower(float value)
{
return _loc.GetString("battery-menu-power-value", ("value", value));
}
protected override void FrameUpdate(FrameEventArgs args)
{
base.FrameUpdate(args);
// Pulse power lines.
_powerPulseValue += args.DeltaSeconds * PowerPulseFactor;
var color = Color.InterpolateBetween(
ActivePowerLineLowColor,
ActivePowerLineHighColor,
MathF.Sin(_powerPulseValue) / 2 + 1);
_activePowerLineStyleBox.BackgroundColor = color;
// Update storage indicator and blink it.
for (var i = 0; i < _chargeMeterBoxes.Length; i++)
{
var box = _chargeMeterBoxes[i];
if (_storageLevel > i)
{
// On
box.BackgroundColor = StorageColors[i];
}
else
{
box.BackgroundColor = DimStorageColors[i];
}
}
_blinkPulseValue += args.DeltaSeconds;
if (_blinkPulseValue > 1)
{
_blinkPulseValue -= 1;
_blinkPulse ^= true;
}
// If there is a storage delta (charging or discharging), we want to blink the highest bar.
if (_hasStorageDelta)
{
// If there is no highest bar (UI completely at 0), then blink bar 0.
var toBlink = Math.Max(0, _storageLevel - 1);
_chargeMeterBoxes[toBlink].BackgroundColor =
_blinkPulse ? StorageColors[toBlink] : DimStorageColors[toBlink];
}
}
}