Merge branch 'master' into ed-17-07-2024-dungenagain

This commit is contained in:
Ed
2024-08-05 23:08:01 +03:00
committed by GitHub
1423 changed files with 219353 additions and 54715 deletions

View File

@@ -0,0 +1,22 @@
/*
* All right reserved to CrystallPunk.
*
* BUT this file is sublicensed under MIT License
*
*/
using Content.Server._CP14.BiomeSpawner.EntitySystems;
using Content.Shared.Parallax.Biomes;
using Robust.Shared.Prototypes;
namespace Content.Server._CP14.BiomeSpawner.Components;
/// <summary>
/// fills the tile in which it is located with the contents of the biome. Includes: tile, decals and entities
/// </summary>
[RegisterComponent, Access(typeof(CP14BiomeSpawnerSystem))]
public sealed partial class CP14BiomeSpawnerComponent : Component
{
[DataField]
public ProtoId<BiomeTemplatePrototype> Biome = "Grasslands";
}

View File

@@ -0,0 +1,92 @@
/*
* All right reserved to CrystallPunk.
*
* BUT this file is sublicensed under MIT License
*
*/
using System.Linq;
using Content.Server._CP14.BiomeSpawner.Components;
using Content.Server._CP14.RoundSeed;
using Content.Server.Decals;
using Content.Server.Parallax;
using Robust.Server.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Prototypes;
namespace Content.Server._CP14.BiomeSpawner.EntitySystems;
public sealed class CP14BiomeSpawnerSystem : EntitySystem
{
[Dependency] private readonly IPrototypeManager _proto = default!;
[Dependency] private readonly BiomeSystem _biome = default!;
[Dependency] private readonly TransformSystem _transform = default!;
[Dependency] private readonly SharedMapSystem _maps = default!;
[Dependency] private readonly DecalSystem _decals = default!;
[Dependency] private readonly EntityLookupSystem _lookup = default!;
[Dependency] private readonly CP14RoundSeedSystem _roundSeed = default!;
public override void Initialize()
{
SubscribeLocalEvent<CP14BiomeSpawnerComponent, MapInitEvent>(OnMapInit);
}
private void OnMapInit(Entity<CP14BiomeSpawnerComponent> ent, ref MapInitEvent args)
{
SpawnBiome(ent);
QueueDel(ent);
}
private void SpawnBiome(Entity<CP14BiomeSpawnerComponent> ent)
{
var biome = _proto.Index(ent.Comp.Biome);
var spawnerTransform = Transform(ent);
if (spawnerTransform.GridUid == null)
return;
var gridUid = spawnerTransform.GridUid.Value;
if (!TryComp<MapGridComponent>(gridUid, out var map))
return;
var seed = _roundSeed.GetSeed();
var vec = _transform.GetGridOrMapTilePosition(ent);
if (!_biome.TryGetTile(vec, biome.Layers, seed, map, out var tile))
return;
// Set new tile
_maps.SetTile(gridUid, map, vec, tile.Value);
var tileCenterVec = vec + map.TileSizeHalfVector;
// Remove old decals
var oldDecals = _decals.GetDecalsInRange(gridUid, tileCenterVec);
foreach (var (id, _) in oldDecals)
{
_decals.RemoveDecal(gridUid, id);
}
//Add decals
if (_biome.TryGetDecals(vec, biome.Layers, seed, map, out var decals))
{
foreach (var decal in decals)
{
_decals.TryAddDecal(decal.ID, new EntityCoordinates(gridUid, decal.Position), out _);
}
}
// Remove entities
var oldEntities = _lookup.GetEntitiesInRange(spawnerTransform.Coordinates, 0.48f);
// TODO: Replace this shit with GetEntitiesInBox2
foreach (var entToRemove in oldEntities.Concat(new[] { ent.Owner })) // Do not remove self
{
QueueDel(entToRemove);
}
if (_biome.TryGetEntity(vec, biome.Layers, tile.Value, seed, map, out var entityProto))
Spawn(entityProto, new EntityCoordinates(gridUid, tileCenterVec));
}
}

View File

@@ -1,11 +1,16 @@
using Content.Server._CP14.GameTicking.Rules.Components;
using Content.Server.Mind;
using Content.Shared.Random.Helpers;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
namespace Content.Server.GameTicking.Rules;
public sealed class CP14ExpeditionObjectivesRule : GameRuleSystem<CP14ExpeditionObjectivesRuleComponent>
{
[Dependency] private readonly MindSystem _mind = default!;
[Dependency] private readonly IPrototypeManager _proto = default!;
[Dependency] private readonly IRobustRandom _random = default!;
public override void Initialize()
{
@@ -25,9 +30,38 @@ public sealed class CP14ExpeditionObjectivesRule : GameRuleSystem<CP14Expedition
return;
}
foreach (var objective in expedition.Objectives)
foreach (var (job, groups) in expedition.RoleObjectives)
{
_mind.TryAddObjective(mindId.Value, mind, objective);
if (args.JobId is null || args.JobId != job)
continue;
foreach (var weightGroupProto in groups)
{
if (!_proto.TryIndex(weightGroupProto, out var weightGroup))
continue;
_mind.TryAddObjective(mindId.Value, mind, weightGroup.Pick(_random));
}
}
foreach (var (departmentProto, objectives) in expedition.DepartmentObjectives)
{
if (args.JobId is null)
continue;
if (!_proto.TryIndex(departmentProto, out var department))
continue;
if (!department.Roles.Contains(args.JobId))
continue;
foreach (var weightGroupProto in objectives)
{
if (!_proto.TryIndex(weightGroupProto, out var weightGroup))
continue;
_mind.TryAddObjective(mindId.Value, mind, weightGroup.Pick(_random));
}
}
}
}

View File

@@ -1,4 +1,6 @@
using Content.Server.GameTicking.Rules;
using Content.Shared.Random;
using Content.Shared.Roles;
using Robust.Shared.Prototypes;
namespace Content.Server._CP14.GameTicking.Rules.Components;
@@ -10,5 +12,8 @@ namespace Content.Server._CP14.GameTicking.Rules.Components;
public sealed partial class CP14ExpeditionObjectivesRuleComponent : Component
{
[DataField]
public List<EntProtoId> Objectives = new();
public Dictionary<ProtoId<JobPrototype>, List<ProtoId<WeightedRandomPrototype>>> RoleObjectives = new();
[DataField]
public Dictionary<ProtoId<DepartmentPrototype>, List<ProtoId<WeightedRandomPrototype>>> DepartmentObjectives = new();
}

View File

@@ -1,14 +1,10 @@
using System.Linq;
using Content.Server.GameTicking.Events;
using Content.Shared._CP14.LockKey;
using Content.Shared.Containers.ItemSlots;
using Content.Shared._CP14.LockKey.Components;
using Content.Shared.Examine;
using Content.Shared.Lock;
using Content.Shared.Popups;
using Content.Shared.GameTicking;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using CP14KeyComponent = Content.Shared._CP14.LockKey.Components.CP14KeyComponent;
using CP14LockComponent = Content.Shared._CP14.LockKey.Components.CP14LockComponent;
namespace Content.Server._CP14.LockKey;
@@ -16,9 +12,6 @@ public sealed partial class CP14KeyholeGenerationSystem : EntitySystem
{
[Dependency] private readonly IPrototypeManager _proto = default!;
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly SharedPopupSystem _popup = default!;
[Dependency] private readonly ItemSlotsSystem _itemSlots = default!;
[Dependency] private readonly LockSystem _lock = default!;
private Dictionary<ProtoId<CP14LockCategoryPrototype>, List<int>> _roundKeyData = new();
@@ -28,7 +21,7 @@ public sealed partial class CP14KeyholeGenerationSystem : EntitySystem
{
base.Initialize();
SubscribeLocalEvent<RoundStartingEvent>(OnRoundStart);
SubscribeLocalEvent<RoundRestartCleanupEvent>(OnRoundEnd);
SubscribeLocalEvent<CP14LockComponent, MapInitEvent>(OnLockInit);
SubscribeLocalEvent<CP14KeyComponent, MapInitEvent>(OnKeyInit);
@@ -37,7 +30,7 @@ public sealed partial class CP14KeyholeGenerationSystem : EntitySystem
}
#region Init
private void OnRoundStart(RoundStartingEvent ev)
private void OnRoundEnd(RoundRestartCleanupEvent ev)
{
_roundKeyData = new();
}
@@ -68,7 +61,7 @@ public sealed partial class CP14KeyholeGenerationSystem : EntitySystem
if (key.Comp.LockShape == null)
return;
var markup = Loc.GetString("cp-lock-examine-key", ("item", MetaData(key).EntityName));
var markup = Loc.GetString("cp14-lock-examine-key", ("item", MetaData(key).EntityName));
markup += " (";
foreach (var item in key.Comp.LockShape)
{

View File

@@ -0,0 +1,93 @@
using System.Numerics;
using Content.Server._CP14.MagicEnergy.Components;
using Content.Shared._CP14.MagicEnergy.Components;
namespace Content.Server._CP14.MagicEnergy;
public partial class CP14MagicEnergySystem
{
private void InitializeDraw()
{
SubscribeLocalEvent<CP14MagicEnergyDrawComponent, MapInitEvent>(OnDrawMapInit);
SubscribeLocalEvent<CP14RandomAuraNodeComponent, MapInitEvent>(OnRandomRangeMapInit);
}
private void OnRandomRangeMapInit(Entity<CP14RandomAuraNodeComponent> random, ref MapInitEvent args)
{
if (!TryComp<CP14AuraNodeComponent>(random, out var draw))
return;
draw.Energy = _random.NextFloat(random.Comp.MinDraw, random.Comp.MaxDraw);
draw.Range = _random.NextFloat(random.Comp.MinRange, random.Comp.MaxRange);
}
private void OnDrawMapInit(Entity<CP14MagicEnergyDrawComponent> ent, ref MapInitEvent args)
{
ent.Comp.NextUpdateTime = _gameTiming.CurTime + TimeSpan.FromSeconds(ent.Comp.Delay);
}
private void UpdateDraw(float frameTime)
{
UpdateEnergyContainer();
UpdateEnergyCrystalSlot();
UpdateEnergyRadiusDraw();
}
private void UpdateEnergyContainer()
{
var query = EntityQueryEnumerator<CP14MagicEnergyDrawComponent, CP14MagicEnergyContainerComponent>();
while (query.MoveNext(out var uid, out var draw, out var magicContainer))
{
if (draw.NextUpdateTime >= _gameTiming.CurTime)
continue;
draw.NextUpdateTime = _gameTiming.CurTime + TimeSpan.FromSeconds(draw.Delay);
ChangeEnergy(uid, magicContainer, draw.Energy, safe: draw.Safe);
}
}
private void UpdateEnergyCrystalSlot()
{
var query = EntityQueryEnumerator<CP14MagicEnergyDrawComponent, CP14MagicEnergyCrystalSlotComponent>();
while (query.MoveNext(out var uid, out var draw, out var slot))
{
if (!draw.Enable)
continue;
if (draw.NextUpdateTime >= _gameTiming.CurTime)
continue;
draw.NextUpdateTime = _gameTiming.CurTime + TimeSpan.FromSeconds(draw.Delay);
if (!_magicSlot.TryGetEnergyCrystalFromSlot(uid, out var energyEnt, out var energyComp))
continue;
ChangeEnergy(energyEnt.Value, energyComp, draw.Energy, draw.Safe);
}
}
private void UpdateEnergyRadiusDraw()
{
var query = EntityQueryEnumerator<CP14AuraNodeComponent>();
while (query.MoveNext(out var uid, out var draw))
{
if (!draw.Enable)
continue;
if (draw.NextUpdateTime >= _gameTiming.CurTime)
continue;
draw.NextUpdateTime = _gameTiming.CurTime + TimeSpan.FromSeconds(draw.Delay);
var containers = _lookup.GetEntitiesInRange<CP14MagicEnergyContainerComponent>(Transform(uid).Coordinates, draw.Range);
foreach (var container in containers)
{
var distance = Vector2.Distance(_transform.GetWorldPosition(uid), _transform.GetWorldPosition(container));
var energyDraw = draw.Energy * (1 - distance / draw.Range);
ChangeEnergy(container, container.Comp, energyDraw, true);
}
}
}
}

View File

@@ -0,0 +1,60 @@
using System.Numerics;
using Content.Server._CP14.MagicEnergy.Components;
using Content.Shared._CP14.MagicEnergy;
using Content.Shared._CP14.MagicEnergy.Components;
using Content.Shared.Examine;
using Content.Shared.FixedPoint;
using Content.Shared.Interaction.Events;
using Content.Shared.Inventory;
namespace Content.Server._CP14.MagicEnergy;
public partial class CP14MagicEnergySystem
{
private void InitializeScanner()
{
SubscribeLocalEvent<CP14MagicEnergyExaminableComponent, ExaminedEvent>(OnExamined);
SubscribeLocalEvent<CP14MagicEnergyScannerComponent, CP14MagicEnergyScanEvent>(OnMagicScanAttempt);
SubscribeLocalEvent<CP14MagicEnergyScannerComponent, InventoryRelayedEvent<CP14MagicEnergyScanEvent>>((e, c, ev) => OnMagicScanAttempt(e, c, ev.Args));
SubscribeLocalEvent<CP14AuraScannerComponent, UseInHandEvent>(OnAuraScannerUseInHand);
}
private void OnMagicScanAttempt(EntityUid uid, CP14MagicEnergyScannerComponent component, CP14MagicEnergyScanEvent args)
{
args.CanScan = true;
}
private void OnExamined(Entity<CP14MagicEnergyExaminableComponent> ent, ref ExaminedEvent args)
{
if (!TryComp<CP14MagicEnergyContainerComponent>(ent, out var magicContainer))
return;
var scanEvent = new CP14MagicEnergyScanEvent();
RaiseLocalEvent(args.Examiner, scanEvent);
if (!scanEvent.CanScan)
return;
args.PushMarkup(GetEnergyExaminedText(ent, magicContainer));
}
private void OnAuraScannerUseInHand(Entity<CP14AuraScannerComponent> scanner, ref UseInHandEvent args)
{
FixedPoint2 sumDraw = 0f;
var query = EntityQueryEnumerator<CP14AuraNodeComponent, TransformComponent>();
while (query.MoveNext(out var auraUid, out var node, out var xform))
{
if (xform.MapUid != Transform(scanner).MapUid)
continue;
var distance = Vector2.Distance(_transform.GetWorldPosition(auraUid), _transform.GetWorldPosition(scanner));
if (distance > node.Range)
continue;
sumDraw += node.Energy * (1 - distance / node.Range);
}
_popup.PopupCoordinates(Loc.GetString("cp14-magic-scanner", ("power", sumDraw)), Transform(scanner).Coordinates, args.User);
}
}

View File

@@ -1,152 +1,29 @@
using Content.Server._CP14.MagicEnergy.Components;
using Content.Server.Popups;
using Content.Shared._CP14.MagicEnergy;
using Content.Shared._CP14.MagicEnergy.Components;
using Content.Shared.Examine;
using Content.Shared.FixedPoint;
using Content.Shared.Inventory;
using Robust.Server.GameObjects;
using Robust.Shared.Random;
using Robust.Shared.Timing;
namespace Content.Server._CP14.MagicEnergy;
public sealed partial class CP14MagicEnergySystem : SharedCP14MagicEnergySystem
{
[Dependency] private readonly SharedTransformSystem _transform = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly PointLightSystem _light = default!;
[Dependency] private readonly CP14MagicEnergyCrystalSlotSystem _magicSlot = default!;
[Dependency] private readonly EntityLookupSystem _lookup = default!;
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly PopupSystem _popup = default!;
public override void Initialize()
{
SubscribeLocalEvent<CP14MagicEnergyDrawComponent, MapInitEvent>(OnMapInit);
SubscribeLocalEvent<CP14MagicEnergyPointLightControllerComponent, CP14MagicEnergyLevelChangeEvent>(OnEnergyChange);
SubscribeLocalEvent<CP14MagicEnergyExaminableComponent, ExaminedEvent>(OnExamined);
SubscribeLocalEvent<CP14MagicEnergyScannerComponent, CP14MagicEnergyScanEvent>(OnMagicScanAttempt);
SubscribeLocalEvent<CP14MagicEnergyScannerComponent, InventoryRelayedEvent<CP14MagicEnergyScanEvent>>((e, c, ev) => OnMagicScanAttempt(e, c, ev.Args));
InitializeDraw();
InitializeScanner();
}
private void OnEnergyChange(Entity<CP14MagicEnergyPointLightControllerComponent> ent, ref CP14MagicEnergyLevelChangeEvent args)
{
if (!TryComp<PointLightComponent>(ent, out var light))
return;
var lightEnergy = MathHelper.Lerp(ent.Comp.MinEnergy, ent.Comp.MaxEnergy, (float)(args.NewValue / args.MaxValue));
_light.SetEnergy(ent, lightEnergy, light);
}
private void OnMapInit(Entity<CP14MagicEnergyDrawComponent> ent, ref MapInitEvent args)
{
ent.Comp.NextUpdateTime = _gameTiming.CurTime + TimeSpan.FromSeconds(ent.Comp.Delay);
}
private void OnMagicScanAttempt(EntityUid uid, CP14MagicEnergyScannerComponent component, CP14MagicEnergyScanEvent args)
{
args.CanScan = true;
}
private void OnExamined(Entity<CP14MagicEnergyExaminableComponent> ent, ref ExaminedEvent args)
{
if (!TryComp<CP14MagicEnergyContainerComponent>(ent, out var magicContainer))
return;
var scanEvent = new CP14MagicEnergyScanEvent();
RaiseLocalEvent(args.Examiner, scanEvent);
if (!scanEvent.CanScan)
return;
args.PushMarkup(GetEnergyExaminedText(ent, magicContainer));
}
public override void Update(float frameTime)
{
base.Update(frameTime);
var query = EntityQueryEnumerator<CP14MagicEnergyDrawComponent, CP14MagicEnergyContainerComponent>();
while (query.MoveNext(out var uid, out var draw, out var magicContainer))
{
if (draw.NextUpdateTime >= _gameTiming.CurTime)
continue;
draw.NextUpdateTime = _gameTiming.CurTime + TimeSpan.FromSeconds(draw.Delay);
ChangeEnergy(uid, magicContainer, draw.Energy, safe: draw.Safe);
}
var query2 = EntityQueryEnumerator<CP14MagicEnergyDrawComponent, CP14MagicEnergyCrystalSlotComponent>();
while (query2.MoveNext(out var uid, out var draw, out var slot))
{
if (!draw.Enable)
continue;
if (draw.NextUpdateTime >= _gameTiming.CurTime)
continue;
draw.NextUpdateTime = _gameTiming.CurTime + TimeSpan.FromSeconds(draw.Delay);
if (!_magicSlot.TryGetEnergyCrystalFromSlot(uid, out var energyEnt, out var energyComp))
continue;
ChangeEnergy(energyEnt.Value, energyComp, draw.Energy, draw.Safe);
}
}
public bool TryConsumeEnergy(EntityUid uid, FixedPoint2 energy, CP14MagicEnergyContainerComponent? component = null, bool safe = false)
{
if (!Resolve(uid, ref component))
return false;
if (energy <= 0)
return true;
// Attempting to absorb more energy than is contained in the carrier will still waste all the energy
if (component.Energy < energy)
{
ChangeEnergy(uid, component, -component.Energy);
return false;
}
ChangeEnergy(uid, component, -energy, safe);
return true;
}
public void ChangeEnergy(EntityUid uid, CP14MagicEnergyContainerComponent component, FixedPoint2 energy, bool safe = false)
{
if (!safe)
{
//Overload
if (component.Energy + energy > component.MaxEnergy)
{
RaiseLocalEvent(uid, new CP14MagicEnergyOverloadEvent()
{
OverloadEnergy = (component.Energy + energy) - component.MaxEnergy,
});
}
//Burn out
if (component.Energy + energy < 0)
{
RaiseLocalEvent(uid, new CP14MagicEnergyBurnOutEvent()
{
BurnOutEnergy = -energy - component.Energy
});
}
}
var oldEnergy = component.Energy;
var newEnergy = Math.Clamp((float)component.Energy + (float)energy, 0, (float)component.MaxEnergy);
component.Energy = newEnergy;
if (oldEnergy != newEnergy)
{
RaiseLocalEvent(uid, new CP14MagicEnergyLevelChangeEvent()
{
OldValue = component.Energy,
NewValue = newEnergy,
MaxValue = component.MaxEnergy,
});
}
UpdateDraw(frameTime);
}
}

View File

@@ -0,0 +1,50 @@
using Content.Shared.FixedPoint;
namespace Content.Server._CP14.MagicEnergy.Components;
[RegisterComponent, Access(typeof(CP14MagicEnergySystem))]
public sealed partial class CP14AuraNodeComponent : Component
{
[DataField]
public bool Enable = true;
[DataField]
public FixedPoint2 Energy = 1f;
[DataField]
public float Range = 10f;
/// <summary>
/// If not safe, restoring or drawing power across boundaries call dangerous events, that may destroy crystals
/// </summary>
[DataField]
public bool Safe = true;
/// <summary>
/// how often objects will try to change magic energy. In Seconds
/// </summary>
[DataField]
public float Delay = 5f;
/// <summary>
/// the time of the next magic energy change
/// </summary>
[DataField]
public TimeSpan NextUpdateTime { get; set; } = TimeSpan.Zero;
}
[RegisterComponent, Access(typeof(CP14MagicEnergySystem))]
public sealed partial class CP14RandomAuraNodeComponent : Component
{
[DataField]
public float MinDraw = -2f;
[DataField]
public float MaxDraw = 2f;
[DataField]
public float MinRange = 5f;
[DataField]
public float MaxRange = 10f;
}

View File

@@ -0,0 +1,6 @@
namespace Content.Server._CP14.MagicEnergy.Components;
[RegisterComponent, Access(typeof(CP14MagicEnergySystem))]
public sealed partial class CP14AuraScannerComponent : Component
{
}

View File

@@ -0,0 +1,40 @@
using Content.Server.Chat.Systems;
using Content.Shared._CP14.MagicSpell;
using Content.Shared._CP14.MagicSpell.Components;
using Content.Shared._CP14.MagicSpell.Events;
using Robust.Server.GameObjects;
namespace Content.Server._CP14.MagicSpell;
public sealed partial class CP14MagicSystem : CP14SharedMagicSystem
{
[Dependency] private readonly ChatSystem _chat = default!;
[Dependency] private readonly TransformSystem _transform = default!;
public override void Initialize()
{
SubscribeLocalEvent<CP14MagicEffectVerbalAspectComponent, CP14VerbalAspectSpeechEvent>(OnSpellSpoken);
SubscribeLocalEvent<CP14MagicEffectCastingVisualComponent, CP14StartCastMagicEffectEvent>(OnSpawnMagicVisualEffect);
SubscribeLocalEvent<CP14MagicEffectCastingVisualComponent, CP14EndCastMagicEffectEvent>(OnDespawnMagicVisualEffect);
}
private void OnSpellSpoken(Entity<CP14MagicEffectVerbalAspectComponent> ent, ref CP14VerbalAspectSpeechEvent args)
{
if (args.Performer is not null && args.Speech is not null)
_chat.TrySendInGameICMessage(args.Performer.Value, args.Speech, InGameICChatType.Speak, true);
}
private void OnSpawnMagicVisualEffect(Entity<CP14MagicEffectCastingVisualComponent> ent, ref CP14StartCastMagicEffectEvent args)
{
var vfx = SpawnAttachedTo(ent.Comp.Proto, Transform(args.Performer).Coordinates);
_transform.SetParent(vfx, args.Performer);
ent.Comp.SpawnedEntity = vfx;
}
private void OnDespawnMagicVisualEffect(Entity<CP14MagicEffectCastingVisualComponent> ent, ref CP14EndCastMagicEffectEvent args)
{
QueueDel(ent.Comp.SpawnedEntity);
ent.Comp.SpawnedEntity = null;
}
}

View File

@@ -1,15 +0,0 @@
namespace Content.Server._CP14.MeleeWeapon;
/// <summary>
/// allows the object to become blunt with use
/// </summary>
[RegisterComponent, Access(typeof(CP14SharpeningSystem))]
public sealed partial class CP14SharpenedComponent : Component
{
[DataField]
public float Sharpness = 1f;
[DataField]
public float SharpnessDamageBy1Damage = 0.002f; //500 damage
}

View File

@@ -1,51 +0,0 @@
using Content.Shared.Damage;
using Robust.Shared.Audio;
namespace Content.Server._CP14.MeleeWeapon;
/// <summary>
/// component allows you to sharpen objects by restoring their damage.
/// </summary>
[RegisterComponent, Access(typeof(CP14SharpeningSystem))]
public sealed partial class CP14SharpeningStoneComponent : Component
{
/// <summary>
/// the amount of acuity recoverable per use
/// </summary>
[DataField]
public float SharpnessHeal = 0.05f;
/// <summary>
/// sound when used
/// </summary>
[DataField]
public SoundSpecifier SharpeningSound =
new SoundPathSpecifier("/Audio/_CP14/Items/sharpening_stone.ogg")
{
Params = AudioParams.Default.WithVariation(0.02f),
};
/// <summary>
/// the damage that the sharpening stone does to itself for use
/// </summary>
[DataField]
public DamageSpecifier SelfDamage = new()
{
DamageDict = new()
{
{ "Blunt", 1 }
}
};
/// <summary>
/// the damage the sharpening stone does to the target
/// </summary>
[DataField]
public DamageSpecifier TargetDamage = new()
{
DamageDict = new()
{
{ "Blunt", 1 }
}
};
}

View File

@@ -1,132 +0,0 @@
using System.Linq;
using Content.Shared.Damage;
using Content.Shared.Examine;
using Content.Shared.Interaction;
using Content.Shared.Placeable;
using Content.Shared.Timing;
using Content.Shared.Weapons.Melee.Events;
using Content.Shared.Wieldable;
using Robust.Shared.Audio.Systems;
namespace Content.Server._CP14.MeleeWeapon;
public sealed class CP14SharpeningSystem : EntitySystem
{
[Dependency] private readonly DamageableSystem _damageableSystem = default!;
[Dependency] private readonly UseDelaySystem _useDelay = default!;
[Dependency] private readonly SharedAudioSystem _audio = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<CP14SharpenedComponent, GetMeleeDamageEvent>(OnGetMeleeDamage, after: new[] { typeof(WieldableSystem) });
SubscribeLocalEvent<CP14SharpenedComponent, ExaminedEvent>(OnExamined);
SubscribeLocalEvent<CP14SharpenedComponent, MeleeHitEvent>(OnMeleeHit);
SubscribeLocalEvent<CP14SharpeningStoneComponent, AfterInteractEvent>(OnAfterInteract);
SubscribeLocalEvent<CP14SharpeningStoneComponent, ActivateInWorldEvent>(OnInteract);
}
private void OnMeleeHit(Entity<CP14SharpenedComponent> sharpened, ref MeleeHitEvent args)
{
if (!args.HitEntities.Any())
return;
sharpened.Comp.Sharpness = MathHelper.Clamp(sharpened.Comp.Sharpness - args.BaseDamage.GetTotal().Float() * sharpened.Comp.SharpnessDamageBy1Damage, 0.1f, 1f);
}
private void OnInteract(Entity<CP14SharpeningStoneComponent> stone, ref ActivateInWorldEvent args)
{
if (args.Handled)
return;
if (!TryComp<ItemPlacerComponent>(stone, out var itemPlacer))
return;
if (itemPlacer.PlacedEntities.Count <= 0)
return;
foreach (var item in itemPlacer.PlacedEntities)
{
if (!TryComp<CP14SharpenedComponent>(item, out var sharpened))
continue;
SharpThing(stone, item, sharpened, args.User);
return;
}
}
private void OnAfterInteract(Entity<CP14SharpeningStoneComponent> stone, ref AfterInteractEvent args)
{
if (!args.CanReach || args.Target == null || !TryComp<CP14SharpenedComponent>(args.Target, out var sharpened))
return;
if (TryComp<UseDelayComponent>(stone, out var useDelay) && _useDelay.IsDelayed( new Entity<UseDelayComponent>(stone, useDelay)))
return;
SharpThing(stone, args.Target.Value, sharpened, args.User);
}
private void SharpThing(Entity<CP14SharpeningStoneComponent> stone, EntityUid target, CP14SharpenedComponent component, EntityUid user)
{
var ev = new SharpingEvent()
{
User = user,
Target = target,
};
RaiseLocalEvent(stone, ev);
if (!ev.Canceled)
{
_audio.PlayPvs(stone.Comp.SharpeningSound, target);
Spawn("EffectSparks", Transform(target).Coordinates);
_damageableSystem.TryChangeDamage(stone, stone.Comp.SelfDamage);
_damageableSystem.TryChangeDamage(target, stone.Comp.TargetDamage);
component.Sharpness = MathHelper.Clamp01(component.Sharpness + stone.Comp.SharpnessHeal);
}
_useDelay.TryResetDelay(stone);
}
private void OnExamined(Entity<CP14SharpenedComponent> sharpened, ref ExaminedEvent args)
{
if (sharpened.Comp.Sharpness > 0.95f)
{
args.PushMarkup(Loc.GetString("sharpening-examined-95"));
return;
}
if (sharpened.Comp.Sharpness > 0.75f)
{
args.PushMarkup(Loc.GetString("sharpening-examined-75"));
return;
}
if (sharpened.Comp.Sharpness > 0.5f)
{
args.PushMarkup(Loc.GetString("sharpening-examined-50"));
return;
}
args.PushMarkup(Loc.GetString("sharpening-examined-25"));
}
private void OnGetMeleeDamage(Entity<CP14SharpenedComponent> sharpened, ref GetMeleeDamageEvent args)
{
args.Damage *= sharpened.Comp.Sharpness;
}
}
/// <summary>
/// Caused on a sharpening stone when someone tries to sharpen an object with it
/// </summary>
public sealed class SharpingEvent : EntityEventArgs
{
public bool Canceled = false;
public EntityUid User;
public EntityUid Target;
}

View File

@@ -0,0 +1,26 @@
using Content.Server._CP14.Objectives.Systems;
using Robust.Shared.Utility;
namespace Content.Server._CP14.Objectives.Components;
[RegisterComponent, Access(typeof(CP14CurrencyCollectConditionSystem))]
public sealed partial class CP14CurrencyCollectConditionComponent : Component
{
[DataField]
public int Currency = 1000;
/// <summary>
/// Limits the goal to collecting values from a specific category.
/// </summary>
[DataField]
public string? Category;
[DataField(required: true)]
public LocId ObjectiveText;
[DataField(required: true)]
public LocId ObjectiveDescription;
[DataField(required: true)]
public SpriteSpecifier ObjectiveSprite;
}

View File

@@ -0,0 +1,113 @@
using Content.Server._CP14.Objectives.Components;
using Content.Shared._CP14.Currency;
using Content.Shared.Mind;
using Content.Shared.Mind.Components;
using Content.Shared.Movement.Pulling.Components;
using Content.Shared.Objectives.Components;
using Content.Shared.Objectives.Systems;
using Robust.Shared.Containers;
namespace Content.Server._CP14.Objectives.Systems;
public sealed class CP14CurrencyCollectConditionSystem : EntitySystem
{
[Dependency] private readonly MetaDataSystem _metaData = default!;
[Dependency] private readonly SharedObjectivesSystem _objectives = default!;
[Dependency] private readonly CP14CurrencySystem _currency = default!;
private EntityQuery<ContainerManagerComponent> _containerQuery;
public override void Initialize()
{
base.Initialize();
_containerQuery = GetEntityQuery<ContainerManagerComponent>();
SubscribeLocalEvent<CP14CurrencyCollectConditionComponent, ObjectiveAssignedEvent>(OnAssigned);
SubscribeLocalEvent<CP14CurrencyCollectConditionComponent, ObjectiveAfterAssignEvent>(OnAfterAssign);
SubscribeLocalEvent<CP14CurrencyCollectConditionComponent, ObjectiveGetProgressEvent>(OnGetProgress);
}
private void OnAssigned(Entity<CP14CurrencyCollectConditionComponent> condition, ref ObjectiveAssignedEvent args)
{
}
private void OnAfterAssign(Entity<CP14CurrencyCollectConditionComponent> condition, ref ObjectiveAfterAssignEvent args)
{
_metaData.SetEntityName(condition.Owner, Loc.GetString(condition.Comp.ObjectiveText), args.Meta);
_metaData.SetEntityDescription(condition.Owner, Loc.GetString(condition.Comp.ObjectiveDescription, ("coins", _currency.GetPrettyCurrency(condition.Comp.Currency))), args.Meta);
_objectives.SetIcon(condition.Owner, condition.Comp.ObjectiveSprite);
}
private void OnGetProgress(Entity<CP14CurrencyCollectConditionComponent> condition, ref ObjectiveGetProgressEvent args)
{
args.Progress = GetProgress(args.Mind, condition);
}
private float GetProgress(MindComponent mind, CP14CurrencyCollectConditionComponent condition)
{
if (!_containerQuery.TryGetComponent(mind.OwnedEntity, out var currentManager))
return 0;
var containerStack = new Stack<ContainerManagerComponent>();
var count = 0;
//check pulling object
if (TryComp<PullerComponent>(mind.OwnedEntity, out var pull)) //TO DO: to make the code prettier? don't like the repetition
{
var pulledEntity = pull.Pulling;
if (pulledEntity != null)
{
CheckEntity(pulledEntity.Value, condition, ref containerStack, ref count);
}
}
// recursively check each container for the item
// checks inventory, bag, implants, etc.
do
{
foreach (var container in currentManager.Containers.Values)
{
foreach (var entity in container.ContainedEntities)
{
// check if this is the item
count += CheckCurrency(entity, condition);
// if it is a container check its contents
if (_containerQuery.TryGetComponent(entity, out var containerManager))
containerStack.Push(containerManager);
}
}
} while (containerStack.TryPop(out currentManager));
var result = count / (float) condition.Currency;
result = Math.Clamp(result, 0, 1);
return result;
}
private void CheckEntity(EntityUid entity, CP14CurrencyCollectConditionComponent condition, ref Stack<ContainerManagerComponent> containerStack, ref int counter)
{
// check if this is the item
counter += CheckCurrency(entity, condition);
//we don't check the inventories of sentient entity
if (!TryComp<MindContainerComponent>(entity, out _))
{
// if it is a container check its contents
if (_containerQuery.TryGetComponent(entity, out var containerManager))
containerStack.Push(containerManager);
}
}
private int CheckCurrency(EntityUid entity, CP14CurrencyCollectConditionComponent condition)
{
// check if this is the target
if (!TryComp<CP14CurrencyComponent>(entity, out var target))
return 0;
if (target.Category != condition.Category)
return 0;
return _currency.GetTotalCurrency(entity);
}
}

View File

@@ -0,0 +1,10 @@
using Robust.Shared.Audio;
namespace Content.Server._CP14.PersonalSignature;
[RegisterComponent]
public sealed partial class CP14PersonalSignatureComponent : Component
{
[DataField]
public SoundSpecifier? SignSound;
}

View File

@@ -0,0 +1,79 @@
using System.Diagnostics.CodeAnalysis;
using Content.Server.Mind;
using Content.Server.Paper;
using Content.Shared.Hands.Components;
using Content.Shared.Paper;
using Content.Shared.Verbs;
using Robust.Server.Audio;
using Robust.Shared.Audio;
using Robust.Shared.Player;
namespace Content.Server._CP14.PersonalSignature;
public sealed class CP14PersonalSignatureSystem : EntitySystem
{
[Dependency] private readonly AudioSystem _audio = default!;
[Dependency] private readonly MindSystem _mind = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<PaperComponent, GetVerbsEvent<AlternativeVerb>>(OnGetVerb);
}
private void OnGetVerb(Entity<PaperComponent> entity, ref GetVerbsEvent<AlternativeVerb> args)
{
if (!_mind.TryGetMind(args.User, out _, out var mind))
return;
if (mind.CharacterName is null)
return;
if (!CanSign(args.Using, out var signature))
return;
if (HasSign(entity, mind.CharacterName))
return;
args.Verbs.Add(new AlternativeVerb
{
Text = Loc.GetString("cp-sign-verb"),
Act = () =>
{
Sign(entity, mind.CharacterName, signature.SignSound);
},
});
}
private bool CanSign(EntityUid? item, [NotNullWhen(true)] out CP14PersonalSignatureComponent? personalSignature)
{
personalSignature = null;
return item is not null && TryComp(item, out personalSignature);
}
private bool HasSign(Entity<PaperComponent> entity, string sign)
{
foreach (var info in entity.Comp.StampedBy)
{
if (info.StampedName == sign)
return true;
}
return false;
}
private void Sign(Entity<PaperComponent> target, string name, SoundSpecifier? sound)
{
var info = new StampDisplayInfo
{
StampedName = name,
StampedColor = Color.Gray,
};
if (sound is not null)
_audio.PlayEntity(sound, Filter.Pvs(target), target, true);
target.Comp.StampedBy.Add(info);
}
}

View File

@@ -0,0 +1,21 @@
/*
* All right reserved to CrystallPunk.
*
* BUT this file is sublicensed under MIT License
*
*/
namespace Content.Server._CP14.RoundSeed;
/// <summary>
/// This is used for round seed
/// </summary>
[RegisterComponent, Access(typeof(CP14RoundSeedSystem))]
public sealed partial class CP14RoundSeedComponent : Component
{
[ViewVariables]
public static int MaxValue = 10000;
[ViewVariables]
public int Seed;
}

View File

@@ -0,0 +1,53 @@
/*
* All right reserved to CrystallPunk.
*
* BUT this file is sublicensed under MIT License
*
*/
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using Robust.Shared.Map;
using Robust.Shared.Random;
namespace Content.Server._CP14.RoundSeed;
/// <summary>
/// Provides a round seed for another systems
/// </summary>
public sealed class CP14RoundSeedSystem : EntitySystem
{
[Dependency] private readonly IRobustRandom _random = default!;
public override void Initialize()
{
SubscribeLocalEvent<CP14RoundSeedComponent, ComponentStartup>(OnComponentStartup);
}
private void OnComponentStartup(Entity<CP14RoundSeedComponent> ent, ref ComponentStartup args)
{
ent.Comp.Seed = _random.Next(CP14RoundSeedComponent.MaxValue);
}
private int SetupSeed()
{
return AddComp<CP14RoundSeedComponent>(Spawn(null, MapCoordinates.Nullspace)).Seed;
}
/// <summary>
/// Returns the round seed if assigned, otherwise assigns the round seed itself.
/// </summary>
/// <returns>seed of the round</returns>
public int GetSeed()
{
var query = EntityQuery<CP14RoundSeedComponent>();
foreach (var comp in query)
{
return comp.Seed;
}
var seed = SetupSeed();
Log.Warning($"Missing RoundSeed. Seed set to {seed}");
return seed;
}
}

View File

@@ -29,21 +29,31 @@ public sealed class CP14ExpeditionSystem : EntitySystem
/// </summary>
public float ArrivalTime { get; private set; }
/// <summary>
/// If enabled then spawns players on an expedition ship.
/// </summary>
public bool Enabled { get; private set; }
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<CP14StationExpeditionTargetComponent, StationPostInitEvent>(OnPostInitSetupExpeditionShip);
SubscribeLocalEvent<CP14StationExpeditionTargetComponent, FTLCompletedEvent>(OnArrivalsDocked);
SubscribeLocalEvent<CP14StationExpeditionTargetComponent, FTLCompletedEvent>(OnExpeditionShipLanded);
ArrivalTime = _cfgManager.GetCVar(CCVars.CP14ExpeditionArrivalTime);
_cfgManager.OnValueChanged(CCVars.CP14ExpeditionArrivalTime, time => ArrivalTime = time, true);
}
Enabled = _cfgManager.GetCVar(CCVars.CP14ExpeditionShip);
_cfgManager.OnValueChanged(CCVars.CP14ExpeditionArrivalTime, time => ArrivalTime = time, true);
_cfgManager.OnValueChanged(CCVars.CP14ExpeditionShip, value => Enabled = value, true);
}
private void OnPostInitSetupExpeditionShip(Entity<CP14StationExpeditionTargetComponent> station, ref StationPostInitEvent args)
{
if (!Enabled)
return;
if (!Deleted(station.Comp.Shuttle))
return;
@@ -76,7 +86,7 @@ public sealed class CP14ExpeditionSystem : EntitySystem
}
}
private void OnArrivalsDocked(Entity<CP14StationExpeditionTargetComponent> ent, ref FTLCompletedEvent args)
private void OnExpeditionShipLanded(Entity<CP14StationExpeditionTargetComponent> ent, ref FTLCompletedEvent args)
{
//Some announsement logic?
}
@@ -97,6 +107,9 @@ public sealed class CP14ExpeditionSystem : EntitySystem
public void HandlePlayerSpawning(PlayerSpawningEvent ev)
{
if (!Enabled)
return;
if (ev.SpawnResult != null)
return;
@@ -114,8 +127,10 @@ public sealed class CP14ExpeditionSystem : EntitySystem
var possiblePositions = new List<EntityCoordinates>();
while (points.MoveNext(out var uid, out var spawnPoint, out var xform))
{
if (ev.Job != null && spawnPoint.Job != ev.Job.Prototype)
continue;
if (spawnPoint.SpawnType != SpawnPointType.LateJoin || xform.GridUid != gridUid)
if (xform.GridUid != gridUid)
continue;
possiblePositions.Add(xform.Coordinates);

View File

@@ -1,15 +1,12 @@
using System.Numerics;
using Content.Server._CP14.Alchemy;
using Content.Server._CP14.MeleeWeapon;
using Content.Server.Popups;
using Content.Shared._CP14.MeleeWeapon.EntitySystems;
using Content.Shared._CP14.Skills;
using Content.Shared._CP14.Skills.Components;
using Content.Shared.Chemistry.Components;
using Content.Shared.Damage;
using Content.Shared.Examine;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Popups;
using Content.Shared.Stunnable;
using Content.Shared.Throwing;
using Content.Shared.Weapons.Melee;
using Content.Shared.Weapons.Melee.Events;

View File

@@ -3,7 +3,7 @@ using Robust.Shared.Utility;
namespace Content.Server._CP14.StationDungeonMap;
/// <summary>
/// Initializes a procedurally generated world with points of interest
/// Loads additional maps from the list at the start of the round.
/// </summary>
[RegisterComponent, Access(typeof(CP14StationAdditionalMapSystem))]
public sealed partial class CP14StationAdditionalMapComponent : Component

View File

@@ -9,5 +9,5 @@ namespace Content.Server._CP14.Temperature;
public sealed partial class CP14FlammableEntityHeaterComponent : Component
{
[DataField]
public float EnergyPerFireStack = 300f;
public float DegreesPerStack = 300f;
}

View File

@@ -3,7 +3,7 @@ namespace Content.Server._CP14.Temperature;
/// <summary>
/// allows you to heat the temperature of solutions depending on the number of stacks of fire
/// </summary>
[RegisterComponent, Access(typeof(CP14SolutionTemperatureSystem))]
[RegisterComponent, Access(typeof(CP14TemperatureSystem))]
public sealed partial class CP14FlammableSolutionHeaterComponent : Component
{
[DataField]

View File

@@ -3,7 +3,7 @@ namespace Content.Server._CP14.Temperature;
/// <summary>
/// passively returns the solution temperature to the standard
/// </summary>
[RegisterComponent, Access(typeof(CP14SolutionTemperatureSystem))]
[RegisterComponent, Access(typeof(CP14TemperatureSystem))]
public sealed partial class CP14SolutionTemperatureComponent : Component
{
[DataField]

View File

@@ -1,34 +1,60 @@
using Content.Server.Atmos.Components;
using Content.Server.Chemistry.Containers.EntitySystems;
using Content.Server.Temperature.Components;
using Content.Server.Temperature.Systems;
using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.FixedPoint;
using Content.Shared.Placeable;
using Robust.Shared.Timing;
namespace Content.Server._CP14.Temperature;
public sealed partial class CP14SolutionTemperatureSystem : EntitySystem
public sealed partial class CP14TemperatureSystem : EntitySystem
{
[Dependency] private readonly SolutionContainerSystem _solutionContainer = default!;
[Dependency] private readonly SharedSolutionContainerSystem _solutionContainer = default!;
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly TemperatureSystem _temperature = default!;
private TimeSpan _updateTick = TimeSpan.FromSeconds(1f);
private readonly TimeSpan _updateTick = TimeSpan.FromSeconds(1f);
private TimeSpan _timeToNextUpdate = TimeSpan.Zero;
public override void Update(float frameTime)
{
base.Update(frameTime);
FlammableEntityHeating(frameTime);
if (_timing.CurTime <= _timeToNextUpdate)
return;
_timeToNextUpdate = _timing.CurTime + _updateTick;
FlammableHeating();
NormalizeTemperature();
FlammableSolutionHeating();
NormalizeSolutionTemperature();
}
private void NormalizeTemperature()
private float GetTargetTemperature(FlammableComponent flammable, CP14FlammableSolutionHeaterComponent heater)
{
return flammable.FireStacks * heater.DegreesPerStack;
}
private void FlammableEntityHeating(float frameTime)
{
var flammableQuery = EntityQueryEnumerator<CP14FlammableEntityHeaterComponent, ItemPlacerComponent, FlammableComponent>();
while (flammableQuery.MoveNext(out var uid, out var heater, out var placer, out var flammable))
{
if (!flammable.OnFire)
return;
var energy = flammable.FireStacks * frameTime * heater.DegreesPerStack;
foreach (var ent in placer.PlacedEntities)
{
_temperature.ChangeHeat(ent, energy);
}
}
}
private void NormalizeSolutionTemperature()
{
var query = EntityQueryEnumerator<CP14SolutionTemperatureComponent, SolutionContainerManagerComponent>();
while (query.MoveNext(out var uid, out var temp, out var container))
@@ -40,7 +66,8 @@ public sealed partial class CP14SolutionTemperatureSystem : EntitySystem
}
}
}
private void FlammableHeating()
private void FlammableSolutionHeating()
{
var query =
EntityQueryEnumerator<CP14FlammableSolutionHeaterComponent, ItemPlacerComponent, FlammableComponent>();
@@ -54,10 +81,9 @@ public sealed partial class CP14SolutionTemperatureSystem : EntitySystem
if (!TryComp<SolutionContainerManagerComponent>(heatingEntity, out var container))
continue;
var targetT = flammable.FireStacks * heater.DegreesPerStack;
foreach (var (_, soln) in _solutionContainer.EnumerateSolutions((heatingEntity, container)))
{
if (TryAffectTemp(soln.Comp.Solution.Temperature, targetT, soln.Comp.Solution.Volume, out var newT))
if (TryAffectTemp(soln.Comp.Solution.Temperature, GetTargetTemperature(flammable, heater), soln.Comp.Solution.Volume, out var newT))
_solutionContainer.SetTemperature(soln, newT);
}
}
@@ -71,7 +97,7 @@ public sealed partial class CP14SolutionTemperatureSystem : EntitySystem
if (mass == 0)
return false;
newT = (float) (oldT + ((targetT - oldT) / mass) * power);
newT = (float) (oldT + (targetT - oldT) / mass * power);
return true;
}
}

View File

@@ -0,0 +1,19 @@
using Content.Shared._CP14.Workbench.Prototypes;
using Robust.Shared.Audio;
using Robust.Shared.Prototypes;
namespace Content.Server._CP14.Workbench;
[RegisterComponent]
[Access(typeof(CP14WorkbenchSystem))]
public sealed partial class CP14WorkbenchComponent : Component
{
[DataField]
public float CraftSpeed = 1f;
[DataField]
public List<ProtoId<CP14WorkbenchRecipePrototype>> Recipes = new();
[DataField]
public SoundSpecifier CraftSound = new SoundCollectionSpecifier("CP14Hammering");
}

View File

@@ -0,0 +1,229 @@
using Content.Server.Popups;
using Content.Shared._CP14.Workbench;
using Content.Shared._CP14.Workbench.Prototypes;
using Content.Shared.DoAfter;
using Content.Shared.Stacks;
using Content.Shared.Verbs;
using Robust.Shared.Audio.Systems;
using Robust.Shared.Prototypes;
namespace Content.Server._CP14.Workbench;
public sealed class CP14WorkbenchSystem : SharedCP14WorkbenchSystem
{
[Dependency] private readonly SharedAudioSystem _audio = default!;
[Dependency] private readonly SharedDoAfterSystem _doAfter = default!;
[Dependency] private readonly SharedStackSystem _stack = default!;
[Dependency] private readonly IPrototypeManager _proto = default!;
[Dependency] private readonly PopupSystem _popup = default!;
[Dependency] private readonly EntityLookupSystem _lookup = default!;
private EntityQuery<MetaDataComponent> _metaQuery;
private EntityQuery<StackComponent> _stackQuery;
private const float WorkbenchRadius = 0.5f;
public override void Initialize()
{
base.Initialize();
_metaQuery = GetEntityQuery<MetaDataComponent>();
_stackQuery = GetEntityQuery<StackComponent>();
SubscribeLocalEvent<CP14WorkbenchComponent, GetVerbsEvent<InteractionVerb>>(OnInteractionVerb);
SubscribeLocalEvent<CP14WorkbenchComponent, CP14CraftDoAfterEvent>(OnCraftFinished);
}
private void OnInteractionVerb(Entity<CP14WorkbenchComponent> ent, ref GetVerbsEvent<InteractionVerb> args)
{
if (!args.CanAccess || !args.CanInteract || args.Hands is null)
return;
var placedEntities = _lookup.GetEntitiesInRange(Transform(ent).Coordinates, WorkbenchRadius);
var user = args.User;
foreach (var craftProto in ent.Comp.Recipes)
{
if (!_proto.TryIndex(craftProto, out var craft))
continue;
if (!_proto.TryIndex(craft.Result, out var result))
continue;
args.Verbs.Add(new()
{
Act = () =>
{
StartCraft(ent, user, craft);
},
Text = result.Name,
Message = GetCraftRecipeMessage(result.Description, craft),
Category = VerbCategory.CP14Craft,
Disabled = !CanCraftRecipe(craft, placedEntities),
});
}
}
private void OnCraftFinished(Entity<CP14WorkbenchComponent> ent, ref CP14CraftDoAfterEvent args)
{
if (args.Cancelled || args.Handled)
return;
if (!_proto.TryIndex(args.Recipe, out var recipe))
return;
var placedEntities = _lookup.GetEntitiesInRange(Transform(ent).Coordinates, WorkbenchRadius);
if (!CanCraftRecipe(recipe, placedEntities))
{
_popup.PopupEntity(Loc.GetString("cp14-workbench-no-resource"), ent, args.User);
return;
}
foreach (var requiredIngredient in recipe.Entities)
{
var requiredCount = requiredIngredient.Value;
foreach (var placedEntity in placedEntities)
{
var placedProto = MetaData(placedEntity).EntityPrototype?.ID;
if (placedProto != null && placedProto == requiredIngredient.Key && requiredCount > 0)
{
requiredCount--;
QueueDel(placedEntity);
}
}
}
foreach (var requiredStack in recipe.Stacks)
{
var requiredCount = requiredStack.Value;
foreach (var placedEntity in placedEntities)
{
if (!_stackQuery.TryGetComponent(placedEntity, out var stack))
continue;
if (stack.StackTypeId != requiredStack.Key)
continue;
var count = (int)MathF.Min(requiredCount, stack.Count);
_stack.SetCount(placedEntity, stack.Count - count, stack);
requiredCount -= count;
}
}
Spawn(_proto.Index(args.Recipe).Result, Transform(ent).Coordinates);
args.Handled = true;
}
private void StartCraft(Entity<CP14WorkbenchComponent> workbench, EntityUid user, CP14WorkbenchRecipePrototype recipe)
{
var craftDoAfter = new CP14CraftDoAfterEvent
{
Recipe = recipe.ID,
};
var doAfterArgs = new DoAfterArgs(EntityManager,
user,
recipe.CraftTime * workbench.Comp.CraftSpeed,
craftDoAfter,
workbench,
workbench)
{
BreakOnMove = true,
BreakOnDamage = true,
NeedHand = true,
};
_doAfter.TryStartDoAfter(doAfterArgs);
_audio.PlayPvs(recipe.OverrideCraftSound ?? workbench.Comp.CraftSound, workbench);
}
private List<CP14WorkbenchRecipePrototype> GetPossibleCrafts(Entity<CP14WorkbenchComponent> workbench, HashSet<EntityUid> ingrediEnts)
{
List<CP14WorkbenchRecipePrototype> result = new();
if (ingrediEnts.Count == 0)
return result;
foreach (var recipeProto in workbench.Comp.Recipes)
{
var recipe = _proto.Index(recipeProto);
if (CanCraftRecipe(recipe, ingrediEnts))
{
result.Add(recipe);
}
}
return result;
}
private bool CanCraftRecipe(CP14WorkbenchRecipePrototype recipe, HashSet<EntityUid> entities)
{
var indexedIngredients = IndexIngredients(entities);
foreach (var requiredIngredient in recipe.Entities)
{
if (!indexedIngredients.TryGetValue(requiredIngredient.Key, out var availableQuantity) ||
availableQuantity < requiredIngredient.Value)
return false;
}
foreach (var (key, value) in recipe.Stacks)
{
var count = 0;
foreach (var ent in entities)
{
if (_stackQuery.TryGetComponent(ent, out var stack))
{
if (stack.StackTypeId != key)
continue;
count += stack.Count;
}
}
if (count < value)
return false;
}
return true;
}
private string GetCraftRecipeMessage(string desc, CP14WorkbenchRecipePrototype recipe)
{
var result = desc + "\n \n" + Loc.GetString("cp14-workbench-recipe-list")+ "\n";
foreach (var pair in recipe.Entities)
{
var proto = _proto.Index(pair.Key);
result += $"{proto.Name} x{pair.Value}\n";
}
foreach (var pair in recipe.Stacks)
{
var proto = _proto.Index(pair.Key);
result += $"{proto.Name} x{pair.Value}\n";
}
return result;
}
private Dictionary<EntProtoId, int> IndexIngredients(HashSet<EntityUid> ingredients)
{
var indexedIngredients = new Dictionary<EntProtoId, int>();
foreach (var ingredient in ingredients)
{
var protoId = _metaQuery.GetComponent(ingredient).EntityPrototype?.ID;
if (protoId == null)
continue;
if (indexedIngredients.ContainsKey(protoId))
indexedIngredients[protoId]++;
else
indexedIngredients[protoId] = 1;
}
return indexedIngredients;
}
}