Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert "Revert "Upstreams"" #577

Merged
merged 1 commit into from
Nov 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 68 additions & 5 deletions Content.Client/Backmen/Body/BodySystem.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,83 @@
using Content.Shared.Body.Systems;
using Content.Shared.Body.Part;
using Content.Shared.Humanoid;
using Content.Shared.Humanoid.Markings;
using Robust.Client.GameObjects;
using Robust.Shared.Utility;
using Content.Shared.Body.Components;

namespace Content.Client.Body.Systems;

public sealed class BodySystem : SharedBodySystem
{
protected override void UpdateAppearance(EntityUid uid, BodyPartAppearanceComponent component)
[Dependency] private readonly MarkingManager _markingManager = default!;

private void ApplyMarkingToPart(MarkingPrototype markingPrototype,
IReadOnlyList<Color>? colors,
bool visible,
SpriteComponent sprite)
{
for (var j = 0; j < markingPrototype.Sprites.Count; j++)
{
var markingSprite = markingPrototype.Sprites[j];

if (markingSprite is not SpriteSpecifier.Rsi rsi)
{
continue;
}

var layerId = $"{markingPrototype.ID}-{rsi.RsiState}";

if (!sprite.LayerMapTryGet(layerId, out _))
{
var layer = sprite.AddLayer(markingSprite, j + 1);
sprite.LayerMapSet(layerId, layer);
sprite.LayerSetSprite(layerId, rsi);
}

sprite.LayerSetVisible(layerId, visible);

if (!visible)
{
continue;
}

// Okay so if the marking prototype is modified but we load old marking data this may no longer be valid
// and we need to check the index is correct.
// So if that happens just default to white?
if (colors != null && j < colors.Count)
{
sprite.LayerSetColor(layerId, colors[j]);
}
else
{
sprite.LayerSetColor(layerId, Color.White);
}
}
}

protected override void ApplyPartMarkings(EntityUid target, BodyPartAppearanceComponent component)
{
if (TryComp(uid, out SpriteComponent? sprite))
if (!TryComp(target, out SpriteComponent? sprite))
return;

if (component.Color != null)
sprite.Color = component.Color.Value;

foreach (var (visualLayer, markingList) in component.Markings)
{
if (component.Color != null)
foreach (var marking in markingList)
{
//TODO a few things need to be adjusted before this is ready to be used - also need to find a way to update the player sprite
//sprite.Color = component.Color.Value;
if (!_markingManager.TryGetMarking(marking, out var markingPrototype))
continue;

ApplyMarkingToPart(markingPrototype, marking.MarkingColors, marking.Visible, sprite);
}
}
}

protected override void RemovePartMarkings(EntityUid target, BodyPartAppearanceComponent partAppearance, HumanoidAppearanceComponent bodyAppearance)
{
return;
}
Comment on lines +79 to +82
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Реализуйте метод RemovePartMarkings или удалите его переопределение

Метод RemovePartMarkings переопределен, но содержит только пустой return;, не выполняя никакой логики. Если метод необходим, следует реализовать его функциональность. Если нет, можно удалить его переопределение, чтобы избежать потенциальной путаницы.

}
43 changes: 6 additions & 37 deletions Content.Client/Backmen/Surgery/SurgeryBui.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
using Robust.Shared.Utility;
using Robust.Shared.Timing;
using Robust.Client.Timing;
using static Robust.Client.UserInterface.Control;
using OpenToolkit.GraphicsLibraryFramework;

namespace Content.Client.Backmen.Surgery;

Expand All @@ -24,7 +26,6 @@ public sealed class SurgeryBui : BoundUserInterface
[Dependency] private readonly IGameTiming _timing = default!;

private readonly SurgerySystem _system;
private readonly HandsSystem _hands;
[ViewVariables]
private SurgeryWindow? _window;

Expand All @@ -37,25 +38,15 @@ public sealed class SurgeryBui : BoundUserInterface
public SurgeryBui(EntityUid owner, Enum uiKey) : base(owner, uiKey)
{
_system = _entities.System<SurgerySystem>();
_hands = _entities.System<HandsSystem>();

_system.OnStep += RefreshUI;
_hands.OnPlayerItemAdded += OnPlayerItemAdded;
}

private void OnPlayerItemAdded(string handName, EntityUid item)
protected override void ReceiveMessage(BoundUserInterfaceMessage message)
{
if (_throttling.handName.Equals(handName)
&& _throttling.item.Equals(item)
&& DateTime.UtcNow - _lastRefresh < TimeSpan.FromSeconds(0.2)
|| !_timing.IsFirstTimePredicted
|| _window == null
|| !_window.IsOpen)
if (_window == null)
return;

_throttling = (handName, item);
_lastRefresh = DateTime.UtcNow;
RefreshUI();
if (message is SurgeryBuiRefreshMessage)
RefreshUI();
}

protected override void UpdateState(BoundUserInterfaceState state)
Expand All @@ -69,8 +60,6 @@ protected override void Dispose(bool disposing)
base.Dispose(disposing);
if (disposing)
_window?.Dispose();

_system.OnStep -= RefreshUI;
}

private void Update(SurgeryBuiState state)
Expand Down Expand Up @@ -316,7 +305,6 @@ private void RefreshUI()
{
return;
}
Logger.Debug($"Running RefreshUI on {Owner}");
var next = _system.GetNextStep(Owner, _part.Value, _surgery.Value.Ent);
var i = 0;
foreach (var child in _window.Steps.Children)
Expand Down Expand Up @@ -357,26 +345,7 @@ private void RefreshUI()
if (_player.LocalEntity is { } player
&& status == StepStatus.Next
&& !_system.CanPerformStep(player, Owner, _part.Value, stepButton.Step, false, out var popup, out var reason, out _))
{
stepButton.ToolTip = popup;
stepButton.Button.Disabled = true;

switch (reason)
{
case StepInvalidReason.MissingSkills:
stepName.AddMarkup($" [color=red]{Loc.GetString("surgery-ui-window-steps-error-skills")}[/color]");
break;
case StepInvalidReason.NeedsOperatingTable:
stepName.AddMarkup($" [color=red]{Loc.GetString("surgery-ui-window-steps-error-table")}[/color]");
break;
case StepInvalidReason.Armor:
stepName.AddMarkup($" [color=red]{Loc.GetString("surgery-ui-window-steps-error-armor")}[/color]");
break;
case StepInvalidReason.MissingTool:
stepName.AddMarkup($" [color=red]{Loc.GetString("surgery-ui-window-steps-error-tools")}[/color]");
break;
}
}
}

var texture = _entities.GetComponentOrNull<SpriteComponent>(stepButton.Step)?.Icon?.Default;
Expand Down
9 changes: 0 additions & 9 deletions Content.Client/Backmen/Surgery/SurgerySystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,8 @@ namespace Content.Client.Backmen.Surgery;

public sealed class SurgerySystem : SharedSurgerySystem
{
public event Action? OnStep;

public override void Initialize()
{
base.Initialize();

SubscribeNetworkEvent<SurgeryUiRefreshEvent>(OnRefresh);
}

private void OnRefresh(SurgeryUiRefreshEvent ev)
{
OnStep?.Invoke();
}
}
8 changes: 5 additions & 3 deletions Content.Client/Humanoid/HumanoidAppearanceSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ private void UpdateLayers(HumanoidAppearanceComponent component, SpriteComponent
foreach (var (key, info) in component.CustomBaseLayers)
{
oldLayers.Remove(key);
SetLayerData(component, sprite, key, info.Id, sexMorph: false, color: info.Color);
// Shitmed modification: For whatever reason these weren't actually ignoring the skin color as advertised.
SetLayerData(component, sprite, key, info.Id, sexMorph: false, color: info.Color, overrideSkin: true);
}

// hide old layers
Expand All @@ -73,7 +74,8 @@ private void SetLayerData(
HumanoidVisualLayers key,
string? protoId,
bool sexMorph = false,
Color? color = null)
Color? color = null,
bool overrideSkin = false)
{
var layerIndex = sprite.LayerMapReserveBlank(key);
var layer = sprite[layerIndex];
Expand All @@ -91,7 +93,7 @@ private void SetLayerData(
var proto = _prototypeManager.Index<HumanoidSpeciesSpriteLayer>(protoId);
component.BaseLayers[key] = proto;

if (proto.MatchSkin)
if (proto.MatchSkin && !overrideSkin)
layer.Color = component.SkinColor.WithAlpha(proto.LayerAlpha);

if (proto.BaseSprite != null)
Expand Down
13 changes: 3 additions & 10 deletions Content.Server/Backmen/Surgery/SurgerySystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ public override void Initialize()
SubscribeLocalEvent<SurgeryStepAffixPartEffectComponent, SurgeryStepEvent>(OnStepAffixPartComplete);
SubscribeLocalEvent<SurgeryStepEmoteEffectComponent, SurgeryStepEvent>(OnStepScreamComplete);
SubscribeLocalEvent<SurgeryStepSpawnEffectComponent, SurgeryStepEvent>(OnStepSpawnComplete);

SubscribeLocalEvent<PrototypesReloadedEventArgs>(OnPrototypesReloaded);

LoadPrototypes();
}

Expand Down Expand Up @@ -80,15 +78,9 @@ protected override void RefreshUI(EntityUid body)
/*
Reason we do this is because when applying a BUI State, it rolls back the state on the entity temporarily,
which just so happens to occur right as we're checking for step completion, so we end up with the UI
not updating at all until you change tools or reopen the window.
not updating at all until you change tools or reopen the window. I love shitcode.
*/

var actors = _ui.GetActors(body, SurgeryUIKey.Key).ToArray();
if (actors.Length == 0)
return;

var filter = Filter.Entities(actors);
RaiseNetworkEvent(new SurgeryUiRefreshEvent(GetNetEntity(body)), filter);
_ui.ServerSendUiMessage(body, SurgeryUIKey.Key, new SurgeryBuiRefreshMessage());
}

private void SetDamage(EntityUid body,
Expand All @@ -114,6 +106,7 @@ private void OnToolAfterInteract(Entity<SurgeryToolComponent> ent, ref AfterInte
if (args.Handled
|| !args.CanReach
|| args.Target == null
|| !HasComp<SurgeryTargetComponent>(args.Target)
|| !TryComp<SurgeryTargetComponent>(args.User, out var surgery)
|| !surgery.CanOperate
|| !IsLyingDown(args.Target.Value, args.User))
Expand Down
28 changes: 25 additions & 3 deletions Content.Server/Body/Systems/BodySystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Content.Shared.Body.Part;
using Content.Shared.Body.Systems;
using Content.Shared.Damage;
using Content.Shared.Gibbing.Events;
using Content.Shared.Humanoid;
using Content.Shared.Mind;
using Content.Shared.Mobs.Systems;
Expand Down Expand Up @@ -108,7 +109,9 @@ public override HashSet<EntityUid> GibBody(
Vector2? splatDirection = null,
float splatModifier = 1,
Angle splatCone = default,
SoundSpecifier? gibSoundOverride = null)
SoundSpecifier? gibSoundOverride = null,
GibType gib = GibType.Gib,
GibContentsOption contents = GibContentsOption.Drop)
{
if (!Resolve(bodyId, ref body, logMissing: false)
|| TerminatingOrDeleted(bodyId)
Expand All @@ -122,7 +125,8 @@ public override HashSet<EntityUid> GibBody(
return new HashSet<EntityUid>();

var gibs = base.GibBody(bodyId, gibOrgans, body, launchGibs: launchGibs,
splatDirection: splatDirection, splatModifier: splatModifier, splatCone: splatCone);
splatDirection: splatDirection, splatModifier: splatModifier, splatCone: splatCone,
gib: gib, contents: contents);

var ev = new BeingGibbedEvent(gibs);
RaiseLocalEvent(bodyId, ref ev);
Expand Down Expand Up @@ -164,9 +168,27 @@ public override HashSet<EntityUid> GibPart(
}

// start-backmen: surgery
protected override void UpdateAppearance(EntityUid uid, BodyPartAppearanceComponent component)
/*protected override void UpdateAppearance(EntityUid uid, BodyPartAppearanceComponent component)
{
return;
}*/
Comment on lines +171 to +174
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Удалите закомментированный код

Вместо комментирования метода UpdateAppearance, его следует полностью удалить, если он больше не используется. Сохранение закомментированного кода затрудняет поддержку и создает путаницу.

-    /*protected override void UpdateAppearance(EntityUid uid, BodyPartAppearanceComponent component)
-    {
-        return;
-    }*/
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/*protected override void UpdateAppearance(EntityUid uid, BodyPartAppearanceComponent component)
{
return;
}*/


protected override void ApplyPartMarkings(EntityUid target, BodyPartAppearanceComponent component)
{
return;
}
Comment on lines +176 to +179
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Реализуйте метод ApplyPartMarkings

Пустая реализация метода ApplyPartMarkings требует доработки. Метод должен применять маркировки к частям тела, аналогично тому, как это реализовано в клиентской части.

Нужна помощь в реализации этого метода?


protected override void RemovePartMarkings(EntityUid target, BodyPartAppearanceComponent partAppearance, HumanoidAppearanceComponent bodyAppearance)
{
foreach (var (visualLayer, markingList) in partAppearance.Markings)
{
foreach (var marking in markingList)
{
_humanoidSystem.RemoveMarking(target, marking.MarkingId, sync: false, humanoid: bodyAppearance);
}
}

Dirty(target, bodyAppearance);
}
// end-backmen: surgery
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Content.Shared.Body.Components;
using Content.Shared.Gibbing.Events;
using JetBrains.Annotations;

namespace Content.Server.Destructible.Thresholds.Behaviors
Expand All @@ -7,13 +8,15 @@ namespace Content.Server.Destructible.Thresholds.Behaviors
[DataDefinition]
public sealed partial class GibBehavior : IThresholdBehavior
{
[DataField] public GibType GibType = GibType.Gib;
[DataField] public GibContentsOption GibContents = GibContentsOption.Drop;
[DataField("recursive")] private bool _recursive = true;

public void Execute(EntityUid owner, DestructibleSystem system, EntityUid? cause = null)
{
if (system.EntityManager.TryGetComponent(owner, out BodyComponent? body))
{
system.BodySystem.GibBody(owner, _recursive, body);
system.BodySystem.GibBody(owner, _recursive, body, gib: GibType, contents: GibContents);
}
}
}
Expand Down
27 changes: 23 additions & 4 deletions Content.Shared/Backmen/Surgery/Body/BodyPartAppearanceComponent.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,45 @@
using Content.Shared.Humanoid;
using Content.Shared.Humanoid.Prototypes;
using Content.Shared.Humanoid.Markings;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
using Robust.Shared.GameStates;

namespace Content.Shared.Body.Part;

[RegisterComponent, NetworkedComponent, AutoGenerateComponentState]
[RegisterComponent, NetworkedComponent, AutoGenerateComponentState(true)]
public sealed partial class BodyPartAppearanceComponent : Component
{
/// <summary>
/// HumanoidVisualLayer type for this body part.
/// </summary>
[DataField, AutoNetworkedField]
public HumanoidVisualLayers Type { get; set; }

/// <summary>
/// Relevant markings for this body part that will be applied on attachment.
/// </summary>
[DataField, AutoNetworkedField]
public Dictionary<HumanoidVisualLayers, List<Marking>> Markings = new();

/// <summary>
/// ID of this custom base layer. Must be a <see cref="HumanoidSpeciesSpriteLayer"/>.
/// </summary>
[DataField("id", customTypeSerializer: typeof(PrototypeIdSerializer<HumanoidSpeciesSpriteLayer>)), AutoNetworkedField]
[DataField(customTypeSerializer: typeof(PrototypeIdSerializer<HumanoidSpeciesSpriteLayer>)), AutoNetworkedField]
public string? ID { get; set; }

/// <summary>
/// Color of this custom base layer. Null implies skin colour if the corresponding <see cref="HumanoidSpeciesSpriteLayer"/> is set to match skin.
/// </summary>
[DataField("color"), AutoNetworkedField]
[DataField, AutoNetworkedField]
public Color? Color { get; set; }

[DataField("originalBody"), AutoNetworkedField]
/// <summary>
/// Color of this custom base eye layer. Null implies eye colour if the corresponding <see cref="HumanoidSpeciesSpriteLayer"/> is set to match skin.
/// </summary>
[DataField, AutoNetworkedField]
public Color? EyeColor { get; set; }
Comment on lines +36 to +40
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Добавление EyeColor требует синхронизации с существующим Color.

Новое свойство EyeColor дублирует логику Color. Рекомендуется объединить логику обработки цветов в отдельный метод.

Предлагаю создать вспомогательный метод для обработки цветов различных частей тела.


[DataField, AutoNetworkedField]
public EntityUid? OriginalBody { get; set; }

//TODO add other custom variables such as species and markings - in case someone decides to attach a lizard arm to a human for example
Expand Down
Loading
Loading