Remove ComponentFamily, remove "game" components. (#281)

* Remove ComponentFamily, remove "game" components.

The entire ComponentFamily system has been removed entirely.
Components now require explicit registration into the IComponentFactory.
This registration spawns the component as dummy and checks reads some data off it like name, netID...
"Reference" types can also be registered using RegisterReference<TTarget, TInterface>().
These references allow you to get components from entities too, so you can reference by interfaces.
This should allow us to inverse the direct fetching and provide a component API available from Shared.
Note that these reference CANNOT be used to spawn a new component. Only a concrete registration can.

Targeted component family messaging no longer exists.
The messaging system still exist, but it's always to ALL components.
The system should probably be killed completely later.
To fill the gap, all cases where family-targeted messaging was used, it now uses references and simple interfaces.

To reference components accross the network, the component now needs to define a "Net ID".
These net IDs should be unique (but matching between client and server).
I made a set of constants for these IDs too in NetIDs.cs

Names are no longer used in netcode (replaced by net IDs). Should reduce bandwidth usage from string names.

Because a LOT of code got in the way, most "game" content was cut. This includes (among others) items and interaction.
This had to be reimplemented in content, and most of the code was terrible anyways.

Also removed the messaging profiling system. It got in my way and I don't understand it (and I doubt anybody does).
It's in the git history if somebody cares.

Fixes #262, Fixes #250, Fixes #74.

* Attempt to fix unit tests, not yet done.

* Fix unit tests, properly.

* Remove debug message.

* Fix rendering on WearableAnimatedSprite.

It wasn't being registered as ISpriteRenderableComponent because of a typo. The ComponentFactory now detects this error too.
This commit is contained in:
Pieter-Jan Briers
2017-07-24 12:27:28 +02:00
committed by GitHub
parent 9727f67b8c
commit 8cac0c1039
209 changed files with 1448 additions and 9410 deletions

View File

@@ -101,7 +101,7 @@ namespace SS14.Client.Collision
/// <returns></returns>
public bool TryCollide(IEntity entity, Vector2f offset, bool bump = true)
{
var collider = (ColliderComponent)entity.GetComponent(ComponentFamily.Collider);
var collider = entity.GetComponent<ColliderComponent>();
if (collider == null) return false;
var ColliderAABB = collider.WorldAABB;

View File

@@ -0,0 +1,101 @@
using SFML.Graphics;
using SS14.Client.GameObjects;
using SS14.Client.Interfaces.Console;
using SS14.Client.Interfaces.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.GameObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SS14.Client.Console
{
class DumpEntitiesCommand : IConsoleCommand
{
public string Command => "dumpentities";
public string Help => "Dump entity list";
public string Description => "Dumps entity list of UIDs and prototype.";
public bool Execute(IDebugConsole console, params string[] args)
{
var entitymanager = IoCManager.Resolve<IEntityManager>();
foreach (IEntity e in entitymanager.GetEntities(new EntityQuery()))
{
console.AddLine($"entity {e.Uid}, {e.Prototype.Name}.", Color.White);
}
return false;
}
}
class DumpRenderables : IConsoleCommand
{
public string Command => "dumprenderables";
public string Help => "Dump renderables list";
public string Description => "Dumps renderables list with component type.";
public bool Execute(IDebugConsole console, params string[] args)
{
var componentManager = IoCManager.Resolve<IComponentManager>();
IEnumerable<IComponent> components = componentManager.GetComponents<ISpriteRenderableComponent>()
.Cast<IComponent>()
.Union(componentManager.GetComponents<ParticleSystemComponent>());
foreach (var component in components)
{
console.AddLine($"{component.Owner.Uid}: {component.GetType()}", Color.White);
}
return false;
}
}
class GetComponentRegistrationCommand : IConsoleCommand
{
public string Command => "getcomponentregistration";
public string Help => "";
public string Description => "";
public bool Execute(IDebugConsole console, params string[] args)
{
if (args.Length < 1)
{
console.AddLine($"Not enough arguments.", Color.Red);
return false;
}
var componentFactory = IoCManager.Resolve<IComponentFactory>();
try
{
var registration = componentFactory.GetRegistration(args[0]);
var message = new StringBuilder($"'{registration.Name}': (type: {registration.Type}, ");
if (registration.NetID == null)
{
message.Append("no Net ID");
}
else
{
message.Append($"net ID: {registration.NetID}");
}
message.Append($", NSE: {registration.NetworkSynchronizeExistence}, references:");
console.AddLine(message.ToString(), Color.White);
foreach (Type type in registration.References)
{
console.AddLine($" {type}", Color.White);
}
}
catch (UnknownComponentException)
{
console.AddLine($"No registration found for '{args[0]}'", Color.Red);
}
return false;
}
}
}

View File

@@ -6,7 +6,6 @@ using SS14.Client.Graphics.Event;
using SS14.Client.Graphics.Render;
using SS14.Client.Interfaces.Input;
using SS14.Client.Interfaces.Map;
using SS14.Client.Interfaces.MessageLogging;
using SS14.Client.Interfaces.Network;
using SS14.Client.Interfaces.Resource;
using SS14.Client.Interfaces.State;
@@ -48,8 +47,6 @@ namespace SS14.Client
[Dependency]
readonly private IResourceManager _resourceManager;
[Dependency]
readonly private IMessageLogger _messageLogger;
[Dependency]
readonly private IEntityNetworkManager _entityNetworkManager;
[Dependency]
readonly private ITileDefinitionManager _tileDefinitionManager;
@@ -79,8 +76,6 @@ namespace SS14.Client
CleanupSplashScreen();
//Initialization of private members
_messageLogger.Initialize();
_entityNetworkManager.Initialize();
_tileDefinitionManager.InitializeResources();
_serializer.Initialize();

View File

@@ -1,3 +1,4 @@
using SS14.Client.Interfaces.GameObjects;
using SS14.Shared.GameObjects;
using System.Collections.Generic;
@@ -5,13 +6,57 @@ namespace SS14.Client.GameObjects
{
public class ClientComponentFactory : ComponentFactory
{
protected override HashSet<string> IgnoredComponentNames { get; } = new HashSet<string>()
public ClientComponentFactory()
{
"BasicInteractable",
"BasicDoor",
"WallMounted",
"Worktop",
"BasicLargeObject"
};
Register<CollidableComponent>();
Register<TriggerableComponent>();
Register<IconComponent>();
Register<ContextMenuComponent>();
Register<KeyBindingInputComponent>();
Register<PointLightComponent>();
Register<PhysicsComponent>();
Register<ColliderComponent>();
Register<TransformComponent>();
Register<DirectionComponent>();
Register<BasicMoverComponent>();
RegisterReference<BasicMoverComponent, IMoverComponent>();
Register<SlaveMoverComponent>();
RegisterReference<SlaveMoverComponent, IMoverComponent>();
Register<PlayerInputMoverComponent>();
RegisterReference<PlayerInputMoverComponent, IMoverComponent>();
Register<HitboxComponent>();
Register<VelocityComponent>();
Register<AnimatedSpriteComponent>();
RegisterReference<AnimatedSpriteComponent, IClickTargetComponent>();
RegisterReference<AnimatedSpriteComponent, ISpriteRenderableComponent>();
Register<WearableAnimatedSpriteComponent>();
RegisterReference<WearableAnimatedSpriteComponent, IClickTargetComponent>();
RegisterReference<WearableAnimatedSpriteComponent, ISpriteRenderableComponent>();
Register<SpriteComponent>();
RegisterReference<SpriteComponent, ISpriteComponent>();
RegisterReference<SpriteComponent, IClickTargetComponent>();
RegisterReference<SpriteComponent, ISpriteRenderableComponent>();
Register<ItemSpriteComponent>();
RegisterReference<ItemSpriteComponent, ISpriteComponent>();
RegisterReference<ItemSpriteComponent, IClickTargetComponent>();
RegisterReference<ItemSpriteComponent, ISpriteRenderableComponent>();
Register<MobSpriteComponent>();
RegisterReference<MobSpriteComponent, ISpriteComponent>();
RegisterReference<MobSpriteComponent, IClickTargetComponent>();
RegisterReference<MobSpriteComponent, ISpriteRenderableComponent>();
Register<ParticleSystemComponent>();
RegisterReference<ParticleSystemComponent, IParticleSystemComponent>();
Register<ClickableComponent>();
}
}
}

View File

@@ -21,7 +21,7 @@ namespace SS14.Client.GameObjects
return from e in _entities.Values
where
(position -
e.GetComponent<TransformComponent>(ComponentFamily.Transform).Position).
e.GetComponent<TransformComponent>().Position).
LengthSquared() < Range
select e;
}

View File

@@ -1,6 +1,5 @@
using Lidgren.Network;
using NetSerializer;
using SS14.Client.Interfaces.MessageLogging;
using SS14.Client.Interfaces.Network;
using SS14.Shared;
using SS14.Shared.GameObjects;
@@ -14,23 +13,10 @@ using SS14.Shared.Interfaces.Network;
namespace SS14.Client.GameObjects
{
public class ClientEntityNetworkManager : IEntityNetworkManager, IPostInjectInit
public class ClientEntityNetworkManager : IEntityNetworkManager
{
private bool _messageProfiling = false;
[Dependency]
private readonly IClientNetManager _networkManager;
[Dependency]
private readonly IConfigurationManager _configManager;
public void PostInject()
{
_configManager.RegisterCVar("ent.logging", false);
}
public void Initialize()
{
_messageProfiling = _configManager.GetCVar<bool>("ent.logging");
}
#region IEntityNetworkManager Members
@@ -59,16 +45,11 @@ namespace SS14.Client.GameObjects
newMsg.Write((int)stream.Length);
newMsg.Write(stream.ToArray());
if (_messageProfiling)
{
//Log the message
}
//Send the message
_networkManager.ClientSendMessage(newMsg, method);
}
public void SendDirectedComponentNetworkMessage(IEntity sendingEntity, ComponentFamily family,
public void SendDirectedComponentNetworkMessage(IEntity sendingEntity, uint netID,
NetDeliveryMethod method, NetConnection recipient,
params object[] messageParams)
{
@@ -83,23 +64,16 @@ namespace SS14.Client.GameObjects
/// <param name="family">Family of the component sending the message</param>
/// <param name="method">Net delivery method -- if null, defaults to NetDeliveryMethod.ReliableUnordered</param>
/// <param name="messageParams">Parameters of the message</param>
public void SendComponentNetworkMessage(IEntity sendingEntity, ComponentFamily family,
public void SendComponentNetworkMessage(IEntity sendingEntity, uint netID,
NetDeliveryMethod method = NetDeliveryMethod.ReliableUnordered,
params object[] messageParams)
{
NetOutgoingMessage message = CreateEntityMessage();
message.Write((byte)EntityMessage.ComponentMessage);
message.Write(sendingEntity.Uid); //Write this entity's UID
message.Write((byte)family);
message.Write(netID);
PackParams(message, messageParams);
if (_messageProfiling)
{
//Log the message
var logger = IoCManager.Resolve<IMessageLogger>();
logger.LogOutgoingComponentNetMessage(sendingEntity.Uid, family, messageParams);
}
//Send the message
_networkManager.ClientSendMessage(message, method);
}
@@ -202,20 +176,6 @@ namespace SS14.Client.GameObjects
}
}
/// <summary>
/// Sends an SVar to the server to be set on the server-side entity.
/// </summary>
/// <param name="sendingEntity"></param>
/// <param name="svar"></param>
public void SendSVar(IEntity sendingEntity, MarshalComponentParameter svar)
{
NetOutgoingMessage message = CreateEntityMessage();
message.Write((byte)EntityMessage.SetSVar);
message.Write(sendingEntity.Uid);
svar.Serialize(message);
_networkManager.ClientSendMessage(message, NetDeliveryMethod.ReliableUnordered);
}
#endregion Sending
#region Receiving
@@ -239,15 +199,6 @@ namespace SS14.Client.GameObjects
result = new IncomingEntityMessage(uid, EntityMessage.ComponentMessage, messageContent,
message.SenderConnection);
if (_messageProfiling)
{
//Log the message
var logger = IoCManager.Resolve<IMessageLogger>();
logger.LogIncomingComponentNetMessage(result.Uid, result.MessageType,
messageContent.ComponentFamily,
messageContent.MessageParameters.ToArray());
}
break;
case EntityMessage.SystemMessage: //TODO: Not happy with this resolving the entmgr everytime a message comes in.
var manager = IoCManager.Resolve<IEntitySystemManager>();
@@ -257,10 +208,6 @@ namespace SS14.Client.GameObjects
uid = message.ReadInt32();
//TODO: Handle position messages!
break;
case EntityMessage.GetSVars:
uid = message.ReadInt32();
result = new IncomingEntityMessage(uid, EntityMessage.GetSVars, message, message.SenderConnection);
break;
}
return result;
}
@@ -272,7 +219,7 @@ namespace SS14.Client.GameObjects
/// <returns>An IncomingEntityComponentMessage object</returns>
public IncomingEntityComponentMessage HandleEntityComponentNetworkMessage(NetIncomingMessage message)
{
var componentFamily = (ComponentFamily)message.ReadByte();
var netID = message.ReadUInt32();
var messageParams = new List<object>();
while (message.Position < message.LengthBits)
{
@@ -323,7 +270,7 @@ namespace SS14.Client.GameObjects
break;
}
}
return new IncomingEntityComponentMessage(componentFamily, messageParams);
return new IncomingEntityComponentMessage(netID, messageParams);
}
#endregion Receiving

View File

@@ -1,6 +1,8 @@
using Lidgren.Network;
using SFML.System;
using SS14.Client.Interfaces.GameObjects;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.IoC;
namespace SS14.Client.GameObjects
@@ -9,10 +11,7 @@ namespace SS14.Client.GameObjects
{
public override string Name => "Clickable";
public ClickableComponent()
{
Family = ComponentFamily.Click;
}
public override uint? NetID => NetIDs.CLICKABLE;
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
@@ -33,17 +32,10 @@ namespace SS14.Client.GameObjects
public bool CheckClick(Vector2f worldPos, out int drawdepth)
{
ComponentReplyMessage reply = Owner.SendMessage(this, ComponentFamily.Renderable,
ComponentMessageType.CheckSpriteClick, worldPos);
var component = Owner.GetComponent<IClickTargetComponent>();
if (reply.MessageType == ComponentMessageType.SpriteWasClicked && (bool)reply.ParamsList[0])
{
drawdepth = (int)reply.ParamsList[1];
return (bool)reply.ParamsList[0];
}
drawdepth = -1;
return false;
drawdepth = (int)component.DrawDepth;
return component.WasClicked(worldPos);
}
public void DispatchClick(int userUID, int clickType)

View File

@@ -44,11 +44,16 @@ namespace SS14.Client.GameObjects
[Obsolete("Getting rid of this messaging paradigm.")]
public void SendComponentInstantiationMessage()
{
if (NetID == null)
{
return;
}
var manager = IoCManager.Resolve<IEntityNetworkManager>();
manager.SendEntityNetworkMessage(
Owner,
EntityMessage.ComponentInstantiationMessage,
Family);
NetID.Value);
}
}
}

View File

@@ -1,9 +1,11 @@
using Lidgren.Network;
using SFML.Graphics;
using SS14.Client.Interfaces.Collision;
using SS14.Client.Interfaces.GameObjects;
using SS14.Client.Interfaces.Map;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Collidable;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
@@ -18,6 +20,7 @@ namespace SS14.Client.GameObjects
public class CollidableComponent : ClientComponent, ICollidable
{
public override string Name => "Collidable";
public override uint? NetID => NetIDs.COLLIDABLE;
public SFML.Graphics.Color DebugColor { get; set; } = Color.Red;
@@ -25,16 +28,7 @@ namespace SS14.Client.GameObjects
private FloatRect currentAABB;
protected bool isHardCollidable = true;
public CollidableComponent()
{
Family = ComponentFamily.Collidable;
}
public override Type StateType
{
get { return typeof(CollidableComponentState); }
}
public override Type StateType => typeof(CollidableComponentState);
/// <summary>
/// X - Top | Y - Right | Z - Bottom | W - Left
@@ -45,10 +39,7 @@ namespace SS14.Client.GameObjects
{
get
{
var ownerTransform = Owner.GetComponent<TransformComponent>(ComponentFamily.Transform);
// Return tweaked AABB
if (ownerTransform != null)
if (Owner.TryGetComponent<TransformComponent>(out var ownerTransform))
{
return
new FloatRect(
@@ -145,12 +136,6 @@ namespace SS14.Client.GameObjects
cm.UpdateCollidable(this);
}
break;
case ComponentMessageType.DisableCollision:
DisableCollision();
break;
case ComponentMessageType.EnableCollision:
EnableCollision();
break;
}
return reply;
@@ -221,18 +206,14 @@ namespace SS14.Client.GameObjects
/// </summary>
private void GetAABB()
{
ComponentReplyMessage reply = Owner.SendMessage(this, ComponentFamily.Renderable,
ComponentMessageType.GetAABB);
if (reply.MessageType == ComponentMessageType.CurrentAABB)
{
var tileSize = IoCManager.Resolve<IMapManager>().TileSize;
currentAABB = (FloatRect)reply.ParamsList[0];
currentAABB = new FloatRect(
currentAABB.Left / tileSize,
currentAABB.Top / tileSize,
currentAABB.Width / tileSize,
currentAABB.Height / tileSize);
}
var component = Owner.GetComponent<ISpriteRenderableComponent>();
var tileSize = IoCManager.Resolve<IMapManager>().TileSize;
currentAABB = new FloatRect(
component.AABB.Left / tileSize,
component.AABB.Top / tileSize,
component.AABB.Width / tileSize,
component.AABB.Height / tileSize);
}
public override void HandleComponentState(dynamic state)

View File

@@ -1,10 +1,11 @@
using SS14.Shared.IoC;
using SS14.Shared.GameObjects.Components;
namespace SS14.Client.GameObjects
{
public class TriggerableComponent : CollidableComponent
{
public override string Name => "Triggerable";
public override uint? NetID => NetIDs.TRIGGERABLE;
public TriggerableComponent()
{
isHardCollidable = false;

View File

@@ -4,6 +4,7 @@ using SS14.Client.Interfaces.Collision;
using SS14.Client.Interfaces.GameObjects;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
using System.Collections.Generic;
@@ -14,32 +15,33 @@ namespace SS14.Client.GameObjects
public class ColliderComponent : ClientComponent
{
public override string Name => "Collider";
public SFML.Graphics.Color DebugColor { get; set; }
public override uint? NetID => NetIDs.COLLIDER;
public SFML.Graphics.Color DebugColor { get; set; } = Color.Blue;
private FloatRect AABB
{
get
{
if (Owner.HasComponent(ComponentFamily.Hitbox))
return Owner.GetComponent<HitboxComponent>(ComponentFamily.Hitbox).AABB;
else if (Owner.HasComponent(ComponentFamily.Renderable))
return Owner.GetComponent<IRenderableComponent>(ComponentFamily.Renderable).AverageAABB;
if (Owner.HasComponent<HitboxComponent>())
{
return Owner.GetComponent<HitboxComponent>().AABB;
}
else if (Owner.HasComponent<IRenderableComponent>())
{
return Owner.GetComponent<IRenderableComponent>().AverageAABB;
}
else
{
return new FloatRect();
}
}
}
public ColliderComponent()
{
Family = ComponentFamily.Collider;
DebugColor = Color.Blue;
}
public FloatRect WorldAABB
{
get
{
var trans = Owner.GetComponent<TransformComponent>(ComponentFamily.Transform);
var trans = Owner.GetComponent<TransformComponent>();
if (trans == null)
{
return AABB;

View File

@@ -1,45 +0,0 @@
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Damageable;
using SS14.Shared.IoC;
using System;
namespace SS14.Client.GameObjects
{
/// <summary>
/// Basic damageable component only tracks whether its dead or not
/// </summary>
public class DamageableComponent : ClientComponent
{
public override string Name => "Damageable";
//Used for things that are binary. Either broken or not broken. (windows?)
protected bool IsDead;
public DamageableComponent()
{
Family = ComponentFamily.Damageable;
}
public override Type StateType
{
get { return typeof(DamageableComponentState); }
}
protected virtual void Die()
{
if (IsDead) return;
IsDead = true;
Owner.SendMessage(this, ComponentMessageType.Die);
}
public override void HandleComponentState(dynamic state)
{
dynamic newIsDeadState = state.IsDead;
if (newIsDeadState && !IsDead)
{
Die();
}
}
}
}

View File

@@ -1,41 +0,0 @@
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Damageable.Health;
using SS14.Shared.IoC;
using System;
namespace SS14.Client.GameObjects
{
/// <summary>
/// Behaves like the damageable component but tracks health as well
/// </summary>
public class HealthComponent : DamageableComponent
{
public override string Name => "Health";
//Useful for objects that need to show different stages of damage clientside.
protected float Health;
protected float MaxHealth;
public override Type StateType
{
get { return typeof (HealthComponentState); }
}
public virtual float GetMaxHealth()
{
return MaxHealth;
}
public virtual float GetHealth()
{
return Health;
}
public override void HandleComponentState(dynamic state)
{
base.HandleComponentState((HealthComponentState) state);
Health = state.Health;
MaxHealth = state.MaxHealth;
}
}
}

View File

@@ -1,6 +1,7 @@
using SFML.System;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Direction;
using SS14.Shared.Maths;
using SS14.Shared.Interfaces.GameObjects;
@@ -12,36 +13,27 @@ namespace SS14.Client.GameObjects
public class DirectionComponent : ClientComponent
{
public override string Name => "Direction";
public override uint? NetID => NetIDs.DIRECTION;
private Direction _lastDeterminedDirection = Direction.South;
public Direction Direction { get; set; } = Direction.South;
public DirectionComponent()
{
Direction = Direction.South;
Family = ComponentFamily.Direction;
}
public Direction Direction { get; set; }
public override Type StateType
{
get { return typeof(DirectionComponentState); }
}
public override Type StateType => typeof(DirectionComponentState);
public override void OnAdd(IEntity owner)
{
base.OnAdd(owner);
owner.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove += HandleOnMove;
owner.GetComponent<TransformComponent>().OnMove += HandleOnMove;
}
public override void OnRemove()
{
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove -= HandleOnMove;
Owner.GetComponent<TransformComponent>().OnMove -= HandleOnMove;
base.OnRemove();
}
public void HandleOnMove(object sender, VectorEventArgs args)
{
if (!(Owner.GetComponent(ComponentFamily.Mover) is PlayerInputMoverComponent))
if (!Owner.HasComponent<PlayerInputMoverComponent>())
{
return;
}

View File

@@ -1,64 +0,0 @@
using Lidgren.Network;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.EntityStats;
using SS14.Shared.IoC;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SS14.Client.GameObjects
{
public class EntityStatsComp : ClientComponent
{
public override string Name => "EntityStats";
private Dictionary<DamageType, int> armorStats = new Dictionary<DamageType, int>();
public EntityStatsComp()
{
Family = ComponentFamily.EntityStats;
}
public override Type StateType
{
get { return typeof(EntityStatsComponentState); }
}
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection sender)
{
var type = (ComponentMessageType)message.MessageParameters[0];
switch (type)
{
case (ComponentMessageType.ReturnArmorValues):
if (!armorStats.Keys.Contains((DamageType)message.MessageParameters[1]))
armorStats.Add((DamageType)message.MessageParameters[1], (int)message.MessageParameters[2]);
else
armorStats[(DamageType)message.MessageParameters[1]] = (int)message.MessageParameters[2];
break;
default:
base.HandleNetworkMessage(message, sender);
break;
}
}
public void PullFullUpdate() //Add proper message for this.
{
foreach (object curr in Enum.GetValues(typeof(DamageType)))
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableUnordered,
ComponentMessageType.GetArmorValues, (int)curr);
}
public int GetArmorValue(DamageType damType)
{
if (armorStats.ContainsKey(damType)) return armorStats[damType];
else return 0;
}
public override void HandleComponentState(dynamic state)
{
armorStats = state.ArmorStats;
}
}
}

View File

@@ -1,126 +0,0 @@
using Lidgren.Network;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Equipment;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SS14.Client.GameObjects
{
public class EquipmentComponent : ClientComponent
{
public override string Name => "Equipment";
public List<EquipmentSlot> ActiveSlots = new List<EquipmentSlot>();
public Dictionary<EquipmentSlot, IEntity> EquippedEntities = new Dictionary<EquipmentSlot, IEntity>();
public EquipmentComponent()
{
Family = ComponentFamily.Equipment;
}
public override Type StateType
{
get { return typeof(EquipmentComponentState); }
}
public void DispatchEquip(int uid)
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered, ComponentMessageType.EquipItem,
uid);
}
public void DispatchEquipFromHand()
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered,
ComponentMessageType.EquipItemInHand);
}
public void DispatchUnEquipToHand(int uid)
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered,
ComponentMessageType.UnEquipItemToHand, uid);
}
public void DispatchUnEquipItemToSpecifiedHand(int uid, InventoryLocation hand)
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered,
ComponentMessageType.UnEquipItemToSpecifiedHand, uid, hand);
}
public void DispatchUnEquipToFloor(int uid)
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered,
ComponentMessageType.UnEquipItemToFloor, uid);
}
private void EquipItem(EquipmentSlot part, int uid)
{
if (!IsEmpty(part))
// Uh oh we are confused about something! But it's better to just do what the server says
{
UnEquipItem(part);
}
EquippedEntities.Add(part, Owner.EntityManager.GetEntity(uid));
}
private void UnEquipItem(EquipmentSlot part)
{
EquippedEntities.Remove(part);
}
public void UnEquipItem(IEntity entity)
{
if (EquippedEntities.ContainsValue(entity))
EquippedEntities.Remove(EquippedEntities.Where(x => x.Value == entity).Select(x => x.Key).First());
}
public bool IsEmpty(EquipmentSlot part)
{
if (EquippedEntities.ContainsKey(part))
return false;
return true;
}
public bool IsEquipped(IEntity entity, EquipmentSlot slot)
{
return EquippedEntities.ContainsKey(slot) && EquippedEntities[slot] == entity;
}
public bool IsEquipped(IEntity entity)
{
return EquippedEntities.ContainsValue(entity);
}
public override void HandleComponentState(dynamic state)
{
foreach (KeyValuePair<EquipmentSlot, int> curr in state.EquippedEntities)
{
IEntity retEnt = Owner.EntityManager.GetEntity(curr.Value);
if (retEnt == null && !IsEmpty(curr.Key))
{
UnEquipItem(curr.Key);
}
else if (retEnt != null && !IsEquipped(retEnt, curr.Key))
{
if (IsEquipped(retEnt))
{
UnEquipItem(retEnt);
}
EquipItem(curr.Key, retEnt.Uid);
}
}
var removed = EquippedEntities.Keys.Where(x => !state.EquippedEntities.ContainsKey(x)).ToArray();
foreach (EquipmentSlot rem in removed)
{
UnEquipItem(rem);
}
//Find differences and raise event?
ActiveSlots = state.ActiveSlots;
}
}
}

View File

@@ -1,25 +0,0 @@
using SS14.Shared;
using SS14.Shared.IoC;
using SS14.Shared.GameObjects;
namespace SS14.Client.GameObjects
{
public class HumanEquipmentComponent : EquipmentComponent
{
public override string Name => "HumanEquipment";
public HumanEquipmentComponent()
{
//These shit lines allow the fucking shit to be added to the shit
ActiveSlots.Add(EquipmentSlot.Back);
ActiveSlots.Add(EquipmentSlot.Belt);
ActiveSlots.Add(EquipmentSlot.Ears);
ActiveSlots.Add(EquipmentSlot.Eyes);
ActiveSlots.Add(EquipmentSlot.Feet);
ActiveSlots.Add(EquipmentSlot.Hands);
ActiveSlots.Add(EquipmentSlot.Head);
ActiveSlots.Add(EquipmentSlot.Inner);
ActiveSlots.Add(EquipmentSlot.Mask);
ActiveSlots.Add(EquipmentSlot.Outer);
}
}
}

View File

@@ -1,72 +0,0 @@
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Equippable;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
namespace SS14.Client.GameObjects
{
public class EquippableComponent : ClientComponent
{
public override string Name => "Equippable";
/// <summary>
/// Where is this equipment being worn
/// </summary>
public EquipmentSlot wearloc;
/// <summary>
/// What entity is wearing this equipment
/// </summary>
public IEntity currentWearer { get; set; }
public EquippableComponent()
{
Family = ComponentFamily.Equippable;
}
public override System.Type StateType
{
get { return typeof(EquippableComponentState); }
}
/// <summary>
/// Handles equipped state change
/// </summary>
/// <param name="uid"></param>
/// <param name="wearloc"></param>
private void EquippedBy(int uid, EquipmentSlot wearloc)
{
currentWearer = Owner.EntityManager.GetEntity(uid);
this.wearloc = wearloc;
}
/// <summary>
/// Handles unequipped state change
/// </summary>
private void UnEquipped()
{
currentWearer = null;
wearloc = EquipmentSlot.None;
}
/// <summary>
/// Handles incoming component state
/// </summary>
/// <param name="state"></param>
public override void HandleComponentState(dynamic state)
{
int? holderUid = currentWearer != null ? currentWearer.Uid : (int?)null;
if (state.Holder != holderUid)
{
if (state.Holder == null)
{
UnEquipped();
}
else
{
EquippedBy((int)state.Holder, state.WearLocation);
}
}
}
}
}

View File

@@ -1,153 +0,0 @@
using Lidgren.Network;
using SS14.Client.Interfaces.UserInterface;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Hands;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using System.Collections.Generic;
using System.Linq;
namespace SS14.Client.GameObjects
{
public class HumanHandsComponent : ClientComponent
{
public override string Name => "HumanHands";
public Dictionary<InventoryLocation, IEntity> HandSlots { get; private set; }
public InventoryLocation CurrentHand { get; private set; }
public HumanHandsComponent()
{
HandSlots = new Dictionary<InventoryLocation, IEntity>();
Family = ComponentFamily.Hands;
}
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection sender)
{
var type = (ComponentMessageType)message.MessageParameters[0];
int entityUid;
InventoryLocation usedHand;
IEntity item;
switch (type)
{
case (ComponentMessageType.EntityChanged):
//This is not sent atm. Commented out serverside for later use.
entityUid = (int)message.MessageParameters[1];
usedHand = (InventoryLocation)message.MessageParameters[2];
item = Owner.EntityManager.GetEntity(entityUid);
if (HandSlots.Keys.Contains(usedHand))
HandSlots[usedHand] = item;
else
HandSlots.Add(usedHand, item);
break;
case (ComponentMessageType.HandsDroppedItem):
//entityUid = (int)message.MessageParameters[1];
usedHand = (InventoryLocation)message.MessageParameters[2];
//item = EntityManager.Singleton.GetEntity(entityUid);
//item.SendMessage(this, ComponentMessageType.Dropped, null);
HandSlots.Remove(usedHand);
break;
case (ComponentMessageType.HandsPickedUpItem):
entityUid = (int)message.MessageParameters[1];
usedHand = (InventoryLocation)message.MessageParameters[2];
item = Owner.EntityManager.GetEntity(entityUid);
//item.SendMessage(this, ComponentMessageType.PickedUp, null, usedHand);
HandSlots.Add(usedHand, item);
break;
case ComponentMessageType.ActiveHandChanged:
SwitchHandTo((InventoryLocation)message.MessageParameters[1]);
break;
}
IoCManager.Resolve<IUserInterfaceManager>().ComponentUpdate(GuiComponentType.HandsUi);
}
public override System.Type StateType
{
get
{
return typeof(HandsComponentState);
}
}
public void SendSwitchHands(InventoryLocation hand)
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered,
ComponentMessageType.ActiveHandChanged, hand);
}
public void SendDropEntity(IEntity ent)
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered,
ComponentMessageType.DropEntityInHand, ent.Uid);
}
public bool IsHandEmpty(InventoryLocation hand)
{
return !HandSlots.ContainsKey(hand);
}
public void SendDropFromHand(InventoryLocation hand)
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered,
ComponentMessageType.DropItemInHand, hand);
}
private void SwitchHandTo(InventoryLocation hand)
{
CurrentHand = hand;
}
public override void HandleComponentState(dynamic state)
{
SetNewState(state);
}
private void SetNewState(HandsComponentState state)
{
bool changed = false;
var currentHand = state.ActiveHand;
if (CurrentHand != currentHand)
{
changed = true;
CurrentHand = currentHand;
}
foreach (var handSlot in state.Slots.Keys)
{
var hand = handSlot;
if (!HandSlots.ContainsKey(hand))
{
HandSlots.Add(hand, null);
changed = true;
}
var existingSlotUid = HandSlots[hand] == null ? null : (int?)HandSlots[hand].Uid;
var newSlotUid = state.Slots[handSlot];
if (existingSlotUid == null)
{
if (newSlotUid != null)
{
HandSlots[hand] = Owner.EntityManager.GetEntity((int)newSlotUid);
changed = true;
}
}
else
{
if (newSlotUid != existingSlotUid)
{
if (newSlotUid != null)
HandSlots[hand] = Owner.EntityManager.GetEntity((int)newSlotUid);
else
HandSlots[hand] = null;
changed = true;
}
}
}
if (changed)
{
IoCManager.Resolve<IUserInterfaceManager>().ComponentUpdate(GuiComponentType.HandsUi);
}
}
}
}

View File

@@ -1,6 +1,7 @@
using SFML.Graphics;
using SFML.System;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Hitbox;
using SS14.Shared.IoC;
using System;
@@ -10,6 +11,7 @@ namespace SS14.Client.GameObjects
public class HitboxComponent : ClientComponent
{
public override string Name => "Hitbox";
public override uint? NetID => NetIDs.HITBOX;
public FloatRect AABB { get; set; }
public Vector2f Size
{
@@ -46,7 +48,6 @@ namespace SS14.Client.GameObjects
public HitboxComponent()
{
Family = ComponentFamily.Hitbox;
Size = new Vector2f();
Offset = new Vector2f();
}

View File

@@ -13,15 +13,9 @@ namespace SS14.Client.GameObjects
public override string Name => "Icon";
public Sprite Icon;
public IconComponent()
{
Family = ComponentFamily.Icon;
}
public override void LoadParameters(YamlMappingNode mapping)
{
YamlNode node;
if (mapping.TryGetNode("icon", out node))
if (mapping.TryGetNode("icon", out YamlNode node))
{
SetIcon(node.AsString());
}

View File

@@ -16,11 +16,6 @@ namespace SS14.Client.GameObjects
public override string Name => "ContextMenu";
private readonly List<ContextMenuEntry> _entries = new List<ContextMenuEntry>();
public ContextMenuComponent()
{
Family = ComponentFamily.ContextMenu;
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{

View File

@@ -2,6 +2,7 @@
using SS14.Client.Interfaces.Input;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using System.Collections.Generic;
@@ -13,6 +14,7 @@ namespace SS14.Client.GameObjects
public class KeyBindingInputComponent : ClientComponent
{
public override string Name => "KeyBindingInput";
public override uint? NetID => NetIDs.KEY_BINDING_INPUT;
#region Delegates
@@ -27,8 +29,6 @@ namespace SS14.Client.GameObjects
public KeyBindingInputComponent()
{
Family = ComponentFamily.Input;
_keyStates = new Dictionary<BoundKeyFunctions, bool>();
_keyHandlers = new Dictionary<BoundKeyFunctions, KeyEvent>();
//Set up keystates

View File

@@ -1,98 +0,0 @@
using Lidgren.Network;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Inventory;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SS14.Client.GameObjects
{
public class InventoryComponent : ClientComponent
{
public override string Name => "Inventory";
#region Delegates
public delegate void InventoryComponentUpdateHandler(
InventoryComponent sender, int maxSlots, List<IEntity> entities);
#endregion Delegates
public InventoryComponent()
{
Family = ComponentFamily.Inventory;
ContainedEntities = new List<IEntity>();
}
public List<IEntity> ContainedEntities { get; private set; }
public int MaxSlots { get; private set; }
public override Type StateType
{
get { return typeof(InventoryComponentState); }
}
public event InventoryComponentUpdateHandler Changed;
public bool ContainsEntity(IEntity entity)
{
return ContainedEntities.Contains(entity);
}
public bool ContainsEntity(string templatename)
{
return ContainedEntities.Exists(x => x.Prototype.ID == templatename);
}
public IEntity GetEntity(string templatename)
{
return ContainedEntities.FirstOrDefault(x => x.Prototype.ID == templatename);
}
// TODO raise an event to be handled by a clientside InventorySystem, which will send the event through to the server?
public void SendInventoryAdd(IEntity ent)
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableUnordered,
ComponentMessageType.InventoryAdd, ent.Uid);
}
public override void HandleComponentState(dynamic state)
{
var theState = state as InventoryComponentState;
var stateChanged = false;
if (MaxSlots != theState.MaxSlots)
{
MaxSlots = theState.MaxSlots;
stateChanged = true;
}
var newEntities = new List<int>(theState.ContainedEntities);
var toRemove = new List<IEntity>();
foreach (var e in ContainedEntities)
{
if (newEntities.Contains(e.Uid))
{
newEntities.Remove(e.Uid);
}
else
{
toRemove.Add(e);
}
}
stateChanged = stateChanged || toRemove.Any() || newEntities.Any();
foreach (var e in toRemove)
{
ContainedEntities.Remove(e);
}
foreach (var uid in newEntities)
{
ContainedEntities.Add(Owner.EntityManager.GetEntity(uid));
}
if (stateChanged && Changed != null) Changed(this, MaxSlots, ContainedEntities);
}
}
}

View File

@@ -1,44 +0,0 @@
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Item;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
namespace SS14.Client.GameObjects
{
public class BasicItemComponent : ClientComponent
{
public override string Name => "BasicItem";
public IEntity Holder;
public InventoryLocation HoldingHand;
public BasicItemComponent()
{
Family = ComponentFamily.Item;
}
public override System.Type StateType
{
get { return typeof(ItemComponentState); }
}
public override void HandleComponentState(dynamic state)
{
SetNewState(state);
}
private void SetNewState(ItemComponentState state)
{
if (state.Holder != null && (Holder == null || Holder.Uid != state.Holder))
{
Holder = Owner.EntityManager.GetEntity((int)state.Holder);
HoldingHand = state.InventoryLocation;
}
if (Holder != null && state.Holder == null)
{
Holder = null;
HoldingHand = state.InventoryLocation;
}
}
}
}

View File

@@ -1,100 +0,0 @@
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
namespace SS14.Client.GameObjects
{
public class FlashLightComponent : PointLightComponent
{
public override string Name => "FlashLight";
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
ComponentReplyMessage reply = base.RecieveMessage(sender, type, list);
if (sender == this)
return reply;
switch (type)
{
case ComponentMessageType.MoveDirection:
var movedir = (Direction)list[0];
LightMoveDir(movedir);
break;
}
return reply;
}
public override void OnAdd(IEntity owner)
{
base.OnAdd(owner);
_light.SetState(LightState.Off);
}
private void LightMoveDir(Direction movedir)
{
switch (movedir)
{
case Direction.East:
SetMask("flashlight_mask");
_light.LightArea.Rot90 = true;
_light.LightArea.MaskFlipX = true;
_light.LightArea.MaskFlipY = false;
_light.LightArea.Calculated = false;
break;
case Direction.SouthEast:
SetMask("flashlight_mask_diag");
_light.LightArea.Rot90 = false;
_light.LightArea.MaskFlipX = false;
_light.LightArea.MaskFlipY = true;
_light.LightArea.Calculated = false;
break;
case Direction.North:
SetMask("flashlight_mask");
_light.LightArea.Rot90 = false;
_light.LightArea.MaskFlipX = false;
_light.LightArea.MaskFlipY = false;
_light.LightArea.Calculated = false;
break;
case Direction.NorthEast:
SetMask("flashlight_mask_diag");
_light.LightArea.Rot90 = false;
_light.LightArea.MaskFlipX = false;
_light.LightArea.MaskFlipY = false;
_light.LightArea.Calculated = false;
break;
case Direction.West:
SetMask("flashlight_mask");
_light.LightArea.Rot90 = true;
_light.LightArea.MaskFlipX = false;
_light.LightArea.MaskFlipY = false;
_light.LightArea.Calculated = false;
break;
case Direction.NorthWest:
SetMask("flashlight_mask_diag");
_light.LightArea.Rot90 = false;
_light.LightArea.MaskFlipX = true;
_light.LightArea.MaskFlipY = false;
_light.LightArea.Calculated = false;
break;
case Direction.South:
SetMask("flashlight_mask");
_light.LightArea.Rot90 = false;
_light.LightArea.MaskFlipX = false;
_light.LightArea.MaskFlipY = true;
_light.LightArea.Calculated = false;
break;
case Direction.SouthWest:
SetMask("flashlight_mask_diag");
_light.LightArea.Rot90 = false;
_light.LightArea.MaskFlipX = true;
_light.LightArea.MaskFlipY = true;
_light.LightArea.Calculated = false;
break;
}
}
}
}

View File

@@ -3,6 +3,7 @@ using SFML.System;
using SS14.Client.Interfaces.Lighting;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Light;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
@@ -16,6 +17,7 @@ namespace SS14.Client.GameObjects
public class PointLightComponent : ClientComponent
{
public override string Name => "PointLight";
public override uint? NetID => NetIDs.POINT_LIGHT;
//Contains a standard light
public ILight _light;
public Vector3f _lightColor = new Vector3f(190, 190, 190);
@@ -24,15 +26,7 @@ namespace SS14.Client.GameObjects
protected string _mask = "";
public LightModeClass _mode = LightModeClass.Constant;
public PointLightComponent()
{
Family = ComponentFamily.Light;
}
public override Type StateType
{
get { return typeof(LightComponentState); }
}
public override Type StateType => typeof(PointLightComponentState);
//When added, set up the light.
public override void OnAdd(IEntity owner)
@@ -44,21 +38,9 @@ namespace SS14.Client.GameObjects
_light.SetRadius(_lightRadius);
_light.SetColor(255, (int)_lightColor.X, (int)_lightColor.Y, (int)_lightColor.Z);
_light.Move(Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position + _lightOffset);
_light.Move(Owner.GetComponent<TransformComponent>().Position + _lightOffset);
_light.SetMask(_mask);
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove += OnMove;
}
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection sender)
{
base.HandleNetworkMessage(message, sender);
var type = (ComponentMessageType)message.MessageParameters[0];
switch (type)
{
case ComponentMessageType.SetLightMode:
SetMode((LightModeClass)message.MessageParameters[1]);
break;
}
Owner.GetComponent<TransformComponent>().OnMove += OnMove;
}
public override void LoadParameters(YamlMappingNode mapping)
@@ -112,14 +94,14 @@ namespace SS14.Client.GameObjects
public override void OnRemove()
{
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove -= OnMove;
Owner.GetComponent<TransformComponent>().OnMove -= OnMove;
IoCManager.Resolve<ILightManager>().RemoveLight(_light);
base.OnRemove();
}
private void OnMove(object sender, VectorEventArgs args)
{
_light.Move(Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position + _lightOffset);
_light.Move(Owner.GetComponent<TransformComponent>().Position + _lightOffset);
}
public override void Update(float frameTime)

View File

@@ -1,5 +1,7 @@
using SFML.System;
using SS14.Client.Interfaces.GameObjects;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Mover;
using SS14.Shared.IoC;
using System;
@@ -9,25 +11,18 @@ namespace SS14.Client.GameObjects
/// <summary>
/// Recieves movement data from the server and updates the entity's position accordingly.
/// </summary>
public class BasicMoverComponent : ClientComponent
public class BasicMoverComponent : ClientComponent, IMoverComponent
{
public override string Name => "BasicMover";
public override uint? NetID => NetIDs.BASIC_MOVER;
public override bool NetworkSynchronizeExistence => true;
private bool interpolating;
private float movedtime; // Amount of time we've been moving since the last update packet.
private const float movetime = 0.05f; // Milliseconds it should take to move.
private Vector2f startPosition;
private Vector2f targetPosition;
public BasicMoverComponent()
{
Family = ComponentFamily.Mover;
}
public override Type StateType
{
get { return typeof(MoverComponentState); }
}
public override void Update(float frameTime)
{
base.Update(frameTime);
@@ -36,7 +31,7 @@ namespace SS14.Client.GameObjects
movedtime = movedtime + frameTime;
if (movedtime >= movetime)
{
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position = targetPosition;
Owner.GetComponent<TransformComponent>().Position = targetPosition;
startPosition = targetPosition;
interpolating = false;
}
@@ -44,7 +39,7 @@ namespace SS14.Client.GameObjects
{
float X = Ease(movedtime, startPosition.X, targetPosition.X, movetime);
float Y = Ease(movedtime, startPosition.Y, targetPosition.Y, movetime);
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position = new Vector2f(X, Y);
Owner.GetComponent<TransformComponent>().Position = new Vector2f(X, Y);
}
}
}

View File

@@ -1,20 +1,25 @@
using Lidgren.Network;
using SFML.System;
using SS14.Client.Interfaces.GameObjects;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.IoC;
namespace SS14.Client.GameObjects
{
//Moves an entity based on key binding input
public class PlayerInputMoverComponent : ClientComponent
public class PlayerInputMoverComponent : ClientComponent, IMoverComponent
{
public override string Name => "PlayerInputMover";
public override uint? NetID => NetIDs.PLAYER_INPUT_MOVER;
public override bool NetworkSynchronizeExistence => true;
private const float BaseMoveSpeed = Constants.HumanWalkSpeed;
public const float FastMoveSpeed = Constants.HumanRunSpeed;
private const float MoveRateLimit = .06666f; // 15 movements allowed to be sent to the server per second.
private float _currentMoveSpeed;
private float _currentMoveSpeed = BaseMoveSpeed;
private bool _moveDown;
private bool _moveLeft;
@@ -23,17 +28,10 @@ namespace SS14.Client.GameObjects
private bool _moveUp;
public bool ShouldSendPositionUpdate;
public PlayerInputMoverComponent()
{
Family = ComponentFamily.Mover;
;
_currentMoveSpeed = BaseMoveSpeed;
}
private Vector2f Velocity
{
get { return Owner.GetComponent<VelocityComponent>(ComponentFamily.Velocity).Velocity; }
set { Owner.GetComponent<VelocityComponent>(ComponentFamily.Velocity).Velocity = value; }
get => Owner.GetComponent<VelocityComponent>().Velocity;
set => Owner.GetComponent<VelocityComponent>().Velocity = value;
}
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection sender)
@@ -172,12 +170,13 @@ namespace SS14.Client.GameObjects
public virtual void SendPositionUpdate(Vector2f nextPosition)
{
var velocity = Owner.GetComponent<VelocityComponent>();
Owner.SendComponentNetworkMessage(this,
NetDeliveryMethod.ReliableUnordered,
nextPosition.X,
nextPosition.Y,
Owner.GetComponent<VelocityComponent>(ComponentFamily.Velocity).Velocity.X,
Owner.GetComponent<VelocityComponent>(ComponentFamily.Velocity).Velocity.Y);
velocity.Velocity.X,
velocity.Velocity.Y);
}
}
}

View File

@@ -1,6 +1,8 @@
using SFML.System;
using SS14.Client.Interfaces.GameObjects;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Mover;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
@@ -11,20 +13,14 @@ namespace SS14.Client.GameObjects
/// <summary>
/// Mover component that responds to movement by an entity.
/// </summary>
public class SlaveMoverComponent : ClientComponent
public class SlaveMoverComponent : ClientComponent, IMoverComponent
{
public override string Name => "SlaveMover";
public override uint? NetID => NetIDs.SLAVE_MOVER;
public override bool NetworkSynchronizeExistence => true;
private IEntity _master;
public SlaveMoverComponent()
{
Family = ComponentFamily.Mover;
}
public override Type StateType
{
get { return typeof(MoverComponentState); }
}
public override Type StateType => typeof(SlaveMoverComponentState);
public override void OnRemove()
{
@@ -36,15 +32,15 @@ namespace SS14.Client.GameObjects
{
_master = Owner.EntityManager.GetEntity(uid);
// TODO handle this using event queue so that these sorts of interactions are deferred until we can be sure the target entity exists
_master.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove += HandleOnMove;
Translate(_master.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
_master.GetComponent<TransformComponent>().OnMove += HandleOnMove;
Translate(_master.GetComponent<TransformComponent>().Position);
}
private void Detach()
{
if (_master == null) return;
_master.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove -= HandleOnMove;
_master.GetComponent<TransformComponent>().OnMove -= HandleOnMove;
_master = null;
}
@@ -55,7 +51,7 @@ namespace SS14.Client.GameObjects
private void Translate(Vector2f toPosition)
{
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position = toPosition;
Owner.GetComponent<TransformComponent>().Position = toPosition;
}
public override void HandleComponentState(dynamic state)
@@ -63,7 +59,7 @@ namespace SS14.Client.GameObjects
SetNewState(state);
}
private void SetNewState(MoverComponentState state)
private void SetNewState(SlaveMoverComponentState state)
{
if (_master == null && state.Master != null)
{

View File

@@ -1,4 +1,5 @@
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Physics;
using SS14.Shared.IoC;
using System;
@@ -8,16 +9,10 @@ namespace SS14.Client.GameObjects
internal class PhysicsComponent : ClientComponent
{
public override string Name => "Physics";
public override uint? NetID => NetIDs.PHYSICS;
public float Mass { get; set; }
public override Type StateType
{
get { return typeof(PhysicsComponentState); }
}
public PhysicsComponent()
{
Family = ComponentFamily.Physics;
}
public override Type StateType => typeof(PhysicsComponentState);
public override void HandleComponentState(dynamic state)
{

View File

@@ -1,189 +0,0 @@
using Lidgren.Network;
using SFML.System;
using SS14.Client.Interfaces.GOC;
using SS14.Shared;
using SS14.Shared.GameObjects;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SS14.Client.GameObjects
{
[IoCTarget]
public class PlayerActionComp : Component
{
public override string Name => "PlayerAction";
#region Delegates
public delegate void PlayerActionsChangedHandler(PlayerActionComp sender);
#endregion
public List<IPlayerAction> Actions = new List<IPlayerAction>();
public PlayerActionComp()
{
Family = ComponentFamily.PlayerActions;
}
public event PlayerActionsChangedHandler Changed;
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection sender)
{
var type = (ComponentMessageType) message.MessageParameters[0];
switch (type)
{
case (ComponentMessageType.AddAction):
var typeName = (string) message.MessageParameters[1];
var uid = (uint) message.MessageParameters[2];
AddAction(typeName, uid);
break;
case (ComponentMessageType.RemoveAction):
var uid2 = (uint) message.MessageParameters[1];
RemoveAction(uid2);
break;
case (ComponentMessageType.RequestActionList):
UnpackFullListing(message);
break;
case (ComponentMessageType.GetActionChecksum):
CheckFullUpdate((uint) message.MessageParameters[1]);
break;
case (ComponentMessageType.CooldownAction):
var uidCd = (uint) message.MessageParameters[1];
var secCd = (uint) message.MessageParameters[2];
SetCooldown(uidCd, secCd);
break;
default:
base.HandleNetworkMessage(message, sender);
break;
}
}
public void CheckActionList()
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableUnordered,
ComponentMessageType.GetActionChecksum);
}
private void SetCooldown(uint uid, uint seconds)
{
IPlayerAction toSet = Actions.FirstOrDefault(x => x.Uid == uid);
if (toSet != null)
toSet.CooldownExpires = DateTime.Now.AddSeconds(seconds);
}
private void CheckFullUpdate(uint checksum) //This should never happen. This just exists in case it desynchs.
{
long sum = Actions.Sum(x => x.Uid)*Actions.Count;
//Absolutely not perfect or safe. If this causes problems later (unlikely) we can still change it.
if (sum != checksum)
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableUnordered,
ComponentMessageType.RequestActionList);
}
public void SendDoAction(IPlayerAction action, object target)
{
if (!Actions.Contains(action)) return;
double cdLeft = action.CooldownExpires.Subtract(DateTime.Now).TotalSeconds;
if (cdLeft > 0) return;
switch (action.TargetType)
{
case PlayerActionTargetType.Any:
{
var trg = (Entity) target;
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableUnordered,
ComponentMessageType.DoAction, action.Uid, action.TargetType,
trg.Uid);
break;
}
case PlayerActionTargetType.None:
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableUnordered,
ComponentMessageType.DoAction, action.Uid, action.TargetType,
Owner.Uid);
break;
}
case PlayerActionTargetType.Other:
{
var trg = (Entity) target;
if (trg == Owner) return;
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableUnordered,
ComponentMessageType.DoAction, action.Uid, action.TargetType,
trg.Uid);
break;
}
case PlayerActionTargetType.Point:
{
var trg = (Vector2f) target;
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableUnordered,
ComponentMessageType.DoAction, action.Uid, action.TargetType,
trg.X, trg.Y);
break;
}
}
}
private void Reset()
{
Actions.Clear();
if (Changed != null) Changed(this);
}
private void UnpackFullListing(IncomingEntityComponentMessage message)
{
Reset();
var numPacks = (uint) message.MessageParameters[1];
for (int i = 0; i < numPacks; i++)
{
var uid = (uint) message.MessageParameters[2 + (i*2)];
var typeName = (string) message.MessageParameters[3 + (i*2)];
AddAction(typeName, uid);
}
}
public override void Update(float frameTime)
{
base.Update(frameTime);
}
private void AddAction(string typeName, uint uid)
//Don't manually use this clientside. The server adds and removes what is needed.
{
Type t = Type.GetType("CGO." + typeName);
if (t == null || !t.IsSubclassOf(typeof (PlayerAction))) return;
var newAction = (PlayerAction) Activator.CreateInstance(t, new object[] {uid, this});
Actions.Add(newAction);
if (Changed != null) Changed(this);
}
private void RemoveAction(uint uid)
//Don't manually use this clientside. The server adds and removes what is needed.
{
IPlayerAction toRemove = Actions.FirstOrDefault(x => x.Uid == uid);
if (toRemove != null)
{
Actions.Remove(toRemove);
if (Changed != null) Changed(this);
}
}
public bool HasAction(string typeName)
{
foreach (IPlayerAction act in Actions)
if (act.GetType().Name.Equals(typeName, StringComparison.InvariantCultureIgnoreCase))
return true;
return false;
}
}
}

View File

@@ -8,6 +8,7 @@ using SS14.Client.Interfaces.Map;
using SS14.Client.Interfaces.Resource;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Renderable;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
@@ -19,34 +20,26 @@ using YamlDotNet.RepresentationModel;
namespace SS14.Client.GameObjects
{
public class AnimatedSpriteComponent : ClientComponent, IRenderableComponent
public class AnimatedSpriteComponent : ClientComponent, ISpriteRenderableComponent, IClickTargetComponent
{
public override string Name => "AnimatedSprite";
public override uint? NetID => NetIDs.ANIMATED_SPRITE;
protected string baseSprite;
protected string currentSprite;
protected AnimatedSprite sprite;
protected IRenderableComponent master;
protected List<IRenderableComponent> slaves;
protected List<IRenderableComponent> slaves = new List<IRenderableComponent>();
protected bool visible = true;
public DrawDepth DrawDepth { get; set; }
private SpeechBubble _speechBubble;
public AnimatedSpriteComponent()
{
Family = ComponentFamily.Renderable;
slaves = new List<IRenderableComponent>();
}
public override Type StateType
{
get { return typeof(AnimatedSpriteComponentState); }
}
public override Type StateType => typeof(AnimatedSpriteComponentState);
public float Bottom
{
get
{
return Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y +
return Owner.GetComponent<TransformComponent>().Position.Y +
(sprite.AABB.Height / 2);
}
}
@@ -123,16 +116,6 @@ namespace SS14.Client.GameObjects
switch (type)
{
case ComponentMessageType.CheckSpriteClick:
reply = new ComponentReplyMessage(ComponentMessageType.SpriteWasClicked,
WasClicked((Vector2f)list[0]), DrawDepth);
break;
case ComponentMessageType.GetAABB:
reply = new ComponentReplyMessage(ComponentMessageType.CurrentAABB, AABB);
break;
case ComponentMessageType.GetSprite:
reply = new ComponentReplyMessage(ComponentMessageType.CurrentSprite, sprite.GetCurrentSprite());
break;
case ComponentMessageType.SlaveAttach:
SetMaster(Owner.EntityManager.GetEntity((int)list[0]));
break;
@@ -192,7 +175,12 @@ namespace SS14.Client.GameObjects
DrawDepth = p;
}
protected virtual bool WasClicked(Vector2f worldPos)
public Sprite GetCurrentSprite()
{
return sprite.GetCurrentSprite();
}
public virtual bool WasClicked(Vector2f worldPos)
{
if (sprite == null || !visible) return false;
@@ -201,9 +189,9 @@ namespace SS14.Client.GameObjects
var AABB =
new FloatRect(
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.X -
Owner.GetComponent<TransformComponent>().Position.X -
(bounds.Width / 2),
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y -
Owner.GetComponent<TransformComponent>().Position.Y -
(bounds.Height / 2), bounds.Width, bounds.Height);
if (!AABB.Contains(worldPos.X, worldPos.Y)) return false;
@@ -265,7 +253,7 @@ namespace SS14.Client.GameObjects
if (!visible) return;
if (sprite == null) return;
var ownerPos = Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position;
var ownerPos = Owner.GetComponent<TransformComponent>().Position;
Vector2f renderPos = CluwneLib.WorldToScreen(ownerPos);
SetSpriteCenter(renderPos);
@@ -297,7 +285,7 @@ namespace SS14.Client.GameObjects
//CluwneLib.CurrentRenderTarget.Rectangle(renderPos.X - aabb.Width/2, renderPos.Y - aabb.Height / 2, aabb.Width, aabb.Height, Color.Lime);
if (_speechBubble != null)
_speechBubble.Draw(CluwneLib.WorldToScreen(Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position),
_speechBubble.Draw(CluwneLib.WorldToScreen(Owner.GetComponent<TransformComponent>().Position),
new Vector2f(), aabb);
}
@@ -347,9 +335,9 @@ namespace SS14.Client.GameObjects
UnsetMaster();
return;
}
if (!m.HasComponent(ComponentFamily.Renderable))
if (!m.HasComponent<ISpriteRenderableComponent>())
return;
var mastercompo = m.GetComponent<IRenderableComponent>(ComponentFamily.Renderable);
var mastercompo = m.GetComponent<ISpriteRenderableComponent>();
//If there's no sprite component, then FUCK IT
if (mastercompo == null)
return;

View File

@@ -4,6 +4,7 @@ using SFML.System;
using SS14.Client.Interfaces.Resource;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Renderable;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
@@ -16,6 +17,7 @@ namespace SS14.Client.GameObjects
public class ItemSpriteComponent : SpriteComponent
{
public override string Name => "ItemSprite";
public override uint? NetID => NetIDs.ITEM_SPRITE;
private bool IsInHand;
private string basename = "";
private InventoryLocation holdingHand = InventoryLocation.None;
@@ -190,7 +192,7 @@ namespace SS14.Client.GameObjects
}
}
protected override bool WasClicked(Vector2f worldPos)
public override bool WasClicked(Vector2f worldPos)
{
return !IsInHand && base.WasClicked(worldPos);
}

View File

@@ -3,6 +3,7 @@ using SFML.System;
using SS14.Client.Graphics;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Renderable;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
@@ -15,6 +16,7 @@ namespace SS14.Client.GameObjects
public class MobSpriteComponent : SpriteComponent
{
public override string Name => "MobSprite";
public override uint? NetID => NetIDs.MOB_SPRITE;
private string _basename;
private SpeechBubble _speechBubble;
@@ -131,17 +133,25 @@ namespace SS14.Client.GameObjects
public override void Render(Vector2f topLeft, Vector2f bottomRight)
{
if (!visible) return;
if (Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.X < topLeft.X
|| Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.X > bottomRight.X
|| Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y < topLeft.Y
|| Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y > bottomRight.Y)
if (!visible)
{
return;
}
var position = Owner.GetComponent<TransformComponent>().Position;
if (position.X < topLeft.X
|| position.X > bottomRight.X
|| position.Y < topLeft.Y
|| position.Y > bottomRight.Y)
{
return;
}
base.Render(topLeft, bottomRight);
if (_speechBubble != null)
_speechBubble.Draw(CluwneLib.WorldToScreen(Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position),
_speechBubble.Draw(CluwneLib.WorldToScreen(position),
new Vector2f(), currentBaseSprite);
}

View File

@@ -5,6 +5,7 @@ using SS14.Client.Interfaces.GameObjects;
using SS14.Client.Interfaces.Resource;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Particles;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
@@ -17,12 +18,13 @@ namespace SS14.Client.GameObjects
public class ParticleSystemComponent : ClientComponent, IParticleSystemComponent, IRenderableComponent
{
public override string Name => "ParticleSystem";
public override uint? NetID => NetIDs.PARTICLE_SYSTEM;
#region Variables.
private Dictionary<string, ParticleSystem> _emitters = new Dictionary<string, ParticleSystem>(); // List of particle emitters.
protected IRenderableComponent master;
protected List<IRenderableComponent> slaves = new List<IRenderableComponent>();
public DrawDepth DrawDepth { get; set; }
public DrawDepth DrawDepth { get; set; } = DrawDepth.ItemsOnTables;
#endregion Variables.
#region Properties
@@ -37,16 +39,8 @@ namespace SS14.Client.GameObjects
}
#endregion Properties
public ParticleSystemComponent()
{
Family = ComponentFamily.Particles;
DrawDepth = DrawDepth.ItemsOnTables;
}
public override Type StateType
{
get { return typeof(ParticleSystemComponentState); }
}
public override Type StateType => typeof(ParticleSystemComponentState);
public void OnMove(object sender, VectorEventArgs args)
{
@@ -62,13 +56,13 @@ namespace SS14.Client.GameObjects
public override void OnAdd(IEntity owner)
{
base.OnAdd(owner);
var transform = Owner.GetComponent<TransformComponent>(ComponentFamily.Transform);
var transform = Owner.GetComponent<TransformComponent>();
transform.OnMove += OnMove;
}
public override void OnRemove()
{
var transform = Owner.GetComponent<TransformComponent>(ComponentFamily.Transform);
var transform = Owner.GetComponent<TransformComponent>();
transform.OnMove -= OnMove;
base.OnRemove();
}
@@ -85,7 +79,7 @@ namespace SS14.Client.GameObjects
public virtual void Render(Vector2f topLeft, Vector2f bottomRight)
{
Vector2f renderPos = CluwneLib.WorldToScreen(
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
Owner.GetComponent<TransformComponent>().Position);
foreach (KeyValuePair<string, ParticleSystem> particleSystem in _emitters)
{
@@ -98,7 +92,7 @@ namespace SS14.Client.GameObjects
{
get
{
return Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y;
return Owner.GetComponent<TransformComponent>().Position.Y;
//return Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y +
// (_particleSprite.Height / 2);
}
@@ -111,9 +105,9 @@ namespace SS14.Client.GameObjects
public void SetMaster(IEntity m)
{
if (!m.HasComponent(ComponentFamily.Renderable))
if (!m.HasComponent<IRenderableComponent>())
return;
var mastercompo = m.GetComponent<SpriteComponent>(ComponentFamily.Renderable);
var mastercompo = m.GetComponent<IRenderableComponent>();
//If there's no sprite component, then FUCK IT
if (mastercompo == null)
return;

View File

@@ -7,6 +7,7 @@ using SS14.Client.Interfaces.GameObjects;
using SS14.Client.Interfaces.Resource;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Renderable;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
@@ -18,47 +19,34 @@ using YamlDotNet.RepresentationModel;
namespace SS14.Client.GameObjects
{
public class SpriteComponent : ClientComponent, IRenderableComponent, ISpriteComponent
public class SpriteComponent : ClientComponent, ISpriteRenderableComponent, ISpriteComponent, IClickTargetComponent
{
public override string Name => "Sprite";
public override uint? NetID => NetIDs.SPRITE;
protected Sprite currentBaseSprite;
protected string currentBaseSpriteKey;
protected Dictionary<string, Sprite> dirSprites;
protected Dictionary<string, Sprite> dirSprites = new Dictionary<string, Sprite>();
protected bool HorizontalFlip { get; set; }
protected IRenderableComponent master;
protected List<IRenderableComponent> slaves;
protected Dictionary<string, Sprite> sprites;
protected List<IRenderableComponent> slaves = new List<IRenderableComponent>();
protected Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();
protected bool visible = true;
public DrawDepth DrawDepth { get; set; }
public SpriteComponent()
{
Family = ComponentFamily.Renderable;
sprites = new Dictionary<string, Sprite>();
dirSprites = new Dictionary<string, Sprite>();
slaves = new List<IRenderableComponent>();
}
public override Type StateType
{
get { return typeof(SpriteComponentState); }
}
public override Type StateType => typeof(SpriteComponentState);
public float Bottom
{
get
{
return Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y +
return Owner.GetComponent<TransformComponent>().Position.Y +
(GetActiveDirectionalSprite().GetLocalBounds().Height / 2);
}
}
#region ISpriteComponent Members
public FloatRect AverageAABB
{
get { return AABB; }
}
public FloatRect AverageAABB => AABB;
public FloatRect AABB
{
@@ -179,13 +167,6 @@ namespace SS14.Client.GameObjects
switch (type)
{
case ComponentMessageType.CheckSpriteClick:
reply = new ComponentReplyMessage(ComponentMessageType.SpriteWasClicked,
WasClicked((Vector2f)list[0]), DrawDepth);
break;
case ComponentMessageType.GetAABB:
reply = new ComponentReplyMessage(ComponentMessageType.CurrentAABB, AABB);
break;
case ComponentMessageType.GetSprite:
reply = new ComponentReplyMessage(ComponentMessageType.CurrentSprite, GetBaseSprite());
break;
@@ -222,7 +203,7 @@ namespace SS14.Client.GameObjects
string dirName =
(currentBaseSpriteKey + "_" +
Owner.GetComponent<DirectionComponent>(ComponentFamily.Direction).Direction.ToString()).
Owner.GetComponent<DirectionComponent>().Direction.ToString()).
ToLowerInvariant();
if (dirSprites.ContainsKey(dirName))
@@ -231,7 +212,7 @@ namespace SS14.Client.GameObjects
return sprite;
}
protected virtual bool WasClicked(Vector2f worldPos)
public virtual bool WasClicked(Vector2f worldPos)
{
if (currentBaseSprite == null || !visible) return false;
@@ -240,8 +221,8 @@ namespace SS14.Client.GameObjects
var AABB =
new FloatRect(
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.X - (bounds.Width / 2),
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y - (bounds.Height / 2), bounds.Width, bounds.Height);
Owner.GetComponent<TransformComponent>().Position.X - (bounds.Width / 2),
Owner.GetComponent<TransformComponent>().Position.Y - (bounds.Height / 2), bounds.Width, bounds.Height);
if (!AABB.Contains(worldPos.X, worldPos.Y)) return false;
// Get the sprite's position within the texture
@@ -311,14 +292,14 @@ namespace SS14.Client.GameObjects
Sprite spriteToRender = GetActiveDirectionalSprite();
Vector2f renderPos = CluwneLib.WorldToScreen(Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
Vector2f renderPos = CluwneLib.WorldToScreen(Owner.GetComponent<TransformComponent>().Position);
var bounds = spriteToRender.GetLocalBounds();
SetSpriteCenter(spriteToRender, renderPos);
if (Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.X + bounds.Left + bounds.Width < topLeft.X
|| Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.X > bottomRight.X
|| Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y + bounds.Top + bounds.Height < topLeft.Y
|| Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y > bottomRight.Y)
if (Owner.GetComponent<TransformComponent>().Position.X + bounds.Left + bounds.Width < topLeft.X
|| Owner.GetComponent<TransformComponent>().Position.X > bottomRight.X
|| Owner.GetComponent<TransformComponent>().Position.Y + bounds.Top + bounds.Height < topLeft.Y
|| Owner.GetComponent<TransformComponent>().Position.Y > bottomRight.Y)
return;
spriteToRender.Scale = new Vector2f(HorizontalFlip ? -1 : 1, 1);
@@ -361,9 +342,9 @@ namespace SS14.Client.GameObjects
public void SetMaster(IEntity m)
{
if (!m.HasComponent(ComponentFamily.Renderable))
if (!m.HasComponent<ISpriteRenderableComponent>())
return;
var mastercompo = m.GetComponent<SpriteComponent>(ComponentFamily.Renderable);
var mastercompo = m.GetComponent<ISpriteRenderableComponent>();
//If there's no sprite component, then FUCK IT
if (mastercompo == null)
return;

View File

@@ -3,6 +3,7 @@ using SFML.System;
using SS14.Client.Graphics;
using SS14.Client.Interfaces.Resource;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Renderable;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
@@ -16,16 +17,14 @@ namespace SS14.Client.GameObjects
public class WearableAnimatedSpriteComponent : AnimatedSpriteComponent
{
public override string Name => "WearableAnimatedSprite";
public override uint? NetID => NetIDs.WEARABLE_ANIMATED_SPRITE;
public bool IsCurrentlyWorn;
public Sprite NotWornSprite;
public bool IsCurrentlyCarried;
public string CarriedSprite;
public override Type StateType
{
get { return typeof(WearableAnimatedSpriteComponentState); }
}
public override Type StateType => typeof(WearableAnimatedSpriteComponentState);
public override void HandleComponentState(dynamic state)
{
@@ -93,14 +92,14 @@ namespace SS14.Client.GameObjects
var bounds = spriteToRender.GetLocalBounds();
Vector2f renderPos = CluwneLib.WorldToScreen(
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
Owner.GetComponent<TransformComponent>().Position);
spriteToRender.Position = new SFML.System.Vector2f(renderPos.X - (bounds.Width / 2),
renderPos.Y - (bounds.Height / 2));
if (Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.X + bounds.Left + bounds.Width < topLeft.X
|| Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.X > bottomRight.X
|| Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y + bounds.Top + bounds.Height < topLeft.Y
|| Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y > bottomRight.Y)
if (Owner.GetComponent<TransformComponent>().Position.X + bounds.Left + bounds.Width < topLeft.X
|| Owner.GetComponent<TransformComponent>().Position.X > bottomRight.X
|| Owner.GetComponent<TransformComponent>().Position.Y + bounds.Top + bounds.Height < topLeft.Y
|| Owner.GetComponent<TransformComponent>().Position.Y > bottomRight.Y)
return;
spriteToRender.Scale = new SFML.System.Vector2f(HorizontalFlip ? -1 : 1, 1);

View File

@@ -1,62 +0,0 @@
using Lidgren.Network;
using SS14.Client.Interfaces.GameObjects;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.IoC;
using System;
using System.Collections.Generic;
namespace SS14.Client.GameObjects
{
public class SVarsComponent : ClientComponent, ISVarsComponent
{
public override string Name => "SVars";
public SVarsComponent()
{
Family = ComponentFamily.SVars;
}
#region ISVarsComponent Members
public event EventHandler<GetSVarsEventArgs> GetSVarsCallback;
public void DoSetSVar(MarshalComponentParameter svar)
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableUnordered, ComponentMessageType.SetSVar,
svar.Serialize());
}
public void DoGetSVars()
{
Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableUnordered, ComponentMessageType.GetSVars);
}
#endregion ISVarsComponent Members
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection sender)
{
switch ((ComponentMessageType)message.MessageParameters[0])
{
case ComponentMessageType.GetSVars:
HandleGetSVars(message);
break;
}
}
public void HandleGetSVars(IncomingEntityComponentMessage message)
{
//If nothing's listening, then why bother with this shit?
if (GetSVarsCallback == null)
return;
var count = (int)message.MessageParameters[1];
var svars = new List<MarshalComponentParameter>();
for (int i = 2; i < count + 2; i++)
{
svars.Add(MarshalComponentParameter.Deserialize((byte[])message.MessageParameters[i]));
}
GetSVarsCallback(this, new GetSVarsEventArgs(svars));
GetSVarsCallback = null;
}
}
}

View File

@@ -1,6 +1,7 @@
using SFML.System;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Transform;
using SS14.Shared.Interfaces.Configuration;
using SS14.Shared.IoC;
@@ -13,15 +14,12 @@ namespace SS14.Client.GameObjects
public class TransformComponent : ClientComponent
{
public override string Name => "Transform";
public override uint? NetID => NetIDs.TRANSFORM;
private Vector2f _position = new Vector2f();
private List<TransformComponentState> states = new List<TransformComponentState>();
private TransformComponentState lastState;
public TransformComponentState lerpStateFrom;
public TransformComponentState lerpStateTo;
public TransformComponent()
{
Family = ComponentFamily.Transform;
}
public Vector2f Position
{
@@ -31,7 +29,7 @@ namespace SS14.Client.GameObjects
Vector2f oldPosition = _position;
_position = value;
if (OnMove != null) OnMove(this, new VectorEventArgs(oldPosition, _position));
OnMove?.Invoke(this, new VectorEventArgs(oldPosition, _position));
}
}

View File

@@ -1,5 +1,6 @@
using SFML.System;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Velocity;
using SS14.Shared.IoC;
using System;
@@ -9,13 +10,14 @@ namespace SS14.Client.GameObjects
public class VelocityComponent : ClientComponent
{
public override string Name => "Velocity";
public override uint? NetID => NetIDs.VELOCITY;
private VelocityComponentState _lastState;
private VelocityComponentState _previousState;
private Vector2f _velocity = new Vector2f();
private Vector2f _velocity = new Vector2f(0, 0);
public VelocityComponent()
{
Family = ComponentFamily.Velocity;
Velocity = new Vector2f(0, 0);
}
@@ -49,7 +51,7 @@ namespace SS14.Client.GameObjects
public override void HandleComponentState(dynamic state)
{
if (Owner.GetComponent<PlayerInputMoverComponent>(ComponentFamily.Mover) == null)
if (!Owner.HasComponent<PlayerInputMoverComponent>())
SetNewState(state);
}

View File

@@ -18,25 +18,23 @@ namespace SS14.Client.GameObjects.EntitySystems
var entities = EntityManager.GetEntities(EntityQuery);
foreach (var entity in entities)
{
var inputs = entity.GetComponent<KeyBindingInputComponent>(ComponentFamily.Input);
var inputs = entity.GetComponent<KeyBindingInputComponent>();
//Animation setting
if (entity.GetComponent(ComponentFamily.Renderable) is AnimatedSpriteComponent)
if (entity.TryGetComponent<AnimatedSpriteComponent>(out var component))
{
var animation = entity.GetComponent<AnimatedSpriteComponent>(ComponentFamily.Renderable);
//Char is moving
if (inputs.GetKeyState(BoundKeyFunctions.MoveRight) ||
inputs.GetKeyState(BoundKeyFunctions.MoveDown) ||
inputs.GetKeyState(BoundKeyFunctions.MoveLeft) ||
inputs.GetKeyState(BoundKeyFunctions.MoveUp))
{
animation.SetAnimationState(inputs.GetKeyState(BoundKeyFunctions.Run) ? "run" : "walk");
component.SetAnimationState(inputs.GetKeyState(BoundKeyFunctions.Run) ? "run" : "walk");
}
//Char is not moving
else
{
animation.SetAnimationState("idle");
component.SetAnimationState("idle");
}
}
}

View File

@@ -1,14 +0,0 @@
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.System;
using SS14.Shared.IoC;
namespace SS14.Client.GameObjects.EntitySystems
{
public class InventorySystem : EntitySystem
{
public InventorySystem()
{
EntityQuery = new EntityQuery();
}
}
}

View File

@@ -23,7 +23,7 @@ namespace SS14.Client.GameObjects.EntitySystems
private Vector2f? calculateNewPosition(IEntity entity, Vector2f newPosition, TransformComponent transform)
{
//Check for collision
var collider = entity.GetComponent<ColliderComponent>(ComponentFamily.Collider);
var collider = entity.GetComponent<ColliderComponent>();
bool collided = collider.TryCollision(newPosition - transform.Position, true);
if (!collided)
{
@@ -68,9 +68,9 @@ namespace SS14.Client.GameObjects.EntitySystems
foreach (var entity in entities)
{
//Get transform component
var transform = entity.GetComponent<TransformComponent>(ComponentFamily.Transform);
var transform = entity.GetComponent<TransformComponent>();
//Check if the entity has a keyboard input mover component
bool isLocallyControlled = entity.GetComponent<PlayerInputMoverComponent>(ComponentFamily.Mover) != null
bool isLocallyControlled = entity.HasComponent<PlayerInputMoverComponent>()
&& IoCManager.Resolve<IPlayerManager>().ControlledEntity == entity;
//Pretend that the current point in time is actually 100 or more milliseconds in the past depending on the interp constant
@@ -113,8 +113,7 @@ namespace SS14.Client.GameObjects.EntitySystems
if (isLocallyControlled)
{
//var playerPosition = transform.Position +
var velocityComponent = entity.GetComponent<VelocityComponent>(ComponentFamily.Velocity);
if (velocityComponent != null)
if (entity.TryGetComponent<VelocityComponent>(out var velocityComponent))
{
var movement = velocityComponent.Velocity * frametime;
var playerPosition = movement + transform.Position;
@@ -137,7 +136,7 @@ namespace SS14.Client.GameObjects.EntitySystems
{
//Only for components with a keyboard input mover component, and a collider component
// Check for collision so we don't get shit stuck in objects
if (entity.GetComponent<ColliderComponent>(ComponentFamily.Collider) != null)
if (entity.HasComponent<ColliderComponent>())
{
Vector2f? _newPosition = calculateNewPosition(entity, newPosition, transform);
if (_newPosition != null)
@@ -155,7 +154,7 @@ namespace SS14.Client.GameObjects.EntitySystems
{
transform.TranslateTo(newPosition);
if (isLocallyControlled)
entity.GetComponent<PlayerInputMoverComponent>(ComponentFamily.Mover).SendPositionUpdate(newPosition);
entity.GetComponent<PlayerInputMoverComponent>().SendPositionUpdate(newPosition);
}
}
}

View File

@@ -1,6 +1,7 @@
using SFML.Graphics;
using SFML.System;
using SS14.Client.GameObjects;
using SS14.Client.Interfaces.GameObjects;
using SS14.Client.Interfaces.Map;
using SS14.Client.Interfaces.Resource;
using SS14.Shared.GameObjects;
@@ -12,51 +13,14 @@ namespace SS14.Client.Helpers
{
internal static class Utilities
{
public static string GetObjectSpriteName(Type type)
{
return type.IsSubclassOf(typeof (ITileDefinition)) ? "tilebuildoverlay" : "nosprite";
}
public static Sprite GetSpriteComponentSprite(IEntity entity)
{
ComponentReplyMessage reply = entity.SendMessage(entity, ComponentFamily.Renderable,
ComponentMessageType.GetSprite);
if (reply.MessageType == ComponentMessageType.CurrentSprite)
{
var sprite = (Sprite) reply.ParamsList[0];
return sprite;
}
return null;
}
public static Sprite GetIconSprite(IEntity entity)
{
if(entity.HasComponent(ComponentFamily.Icon))
Sprite icon = null;
if (entity.TryGetComponent<IconComponent>(out var component))
{
var icon = entity.GetComponent<IconComponent>(ComponentFamily.Icon).Icon;
if (icon == null)
return IoCManager.Resolve<IResourceManager>().GetNoSprite();
return icon;
icon = component.Icon;
}
return IoCManager.Resolve<IResourceManager>().GetNoSprite();
}
public static bool SpritePixelHit(Sprite toCheck, Vector2f clickPos)
{
var clickPoint = new Vector2f(clickPos.X, clickPos.Y);
if (!toCheck.GetLocalBounds().Contains(clickPoint.X, clickPoint.Y)) return false;
var spritePosition = new Vector2u((uint) clickPos.X - (uint) toCheck.Position.X ,//+ (int) toCheck.ImageOffset.X,
(uint) clickPos.Y - (uint) toCheck.Position.Y ); //+ (int) toCheck.ImageOffset.Y);
Image imgData = toCheck.Texture.CopyToImage();
//imgData.Lock(false);
Color pixColour = imgData.GetPixel(spritePosition.X, spritePosition.Y);
imgData.Dispose();
//imgData.Unlock();
return pixColour.A != 0;
return icon ?? IoCManager.Resolve<IResourceManager>().GetNoSprite();
}
}
}

View File

@@ -1,16 +0,0 @@
using SS14.Shared.GameObjects;
using System;
using System.Collections.Generic;
namespace SS14.Client.Interfaces.GameObjects
{
public class GetSVarsEventArgs : EventArgs
{
public List<MarshalComponentParameter> SVars;
public GetSVarsEventArgs(List<MarshalComponentParameter> sVars)
{
SVars = sVars;
}
}
}

View File

@@ -0,0 +1,15 @@
using SFML.System;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
namespace SS14.Client.Interfaces.GameObjects
{
/// <summary>
/// A component that can be clicked on. Handles whether a coordinate is a valid place to click us on.
/// </summary>
public interface IClickTargetComponent : IComponent
{
bool WasClicked(Vector2f worldPos);
DrawDepth DrawDepth { get; }
}
}

View File

@@ -0,0 +1,11 @@
using SS14.Shared.Interfaces.GameObjects;
namespace SS14.Client.Interfaces.GameObjects
{
// Does nothing except ensure uniqueness between mover components.
// There can only be one.
public interface IMoverComponent : IComponent
{
}
}

View File

@@ -1,12 +0,0 @@
using SS14.Shared.GameObjects;
using System;
namespace SS14.Client.Interfaces.GameObjects
{
public interface ISVarsComponent
{
event EventHandler<GetSVarsEventArgs> GetSVarsCallback;
void DoSetSVar(MarshalComponentParameter svar);
void DoGetSVars();
}
}

View File

@@ -1,9 +1,10 @@
using SFML.Graphics;
using SS14.Shared.Interfaces.GameObjects;
using System.Collections.Generic;
namespace SS14.Client.Interfaces.GameObjects
{
public interface ISpriteComponent
public interface ISpriteComponent : IComponent
{
FloatRect AABB { get; }
Sprite GetCurrentSprite();

View File

@@ -0,0 +1,9 @@
using SFML.Graphics;
namespace SS14.Client.Interfaces.GameObjects
{
public interface ISpriteRenderableComponent : IRenderableComponent
{
Sprite GetCurrentSprite();
}
}

View File

@@ -1,18 +0,0 @@
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.IoC;
namespace SS14.Client.Interfaces.MessageLogging
{
public interface IMessageLogger
{
void Initialize();
void LogOutgoingComponentNetMessage(int uid, ComponentFamily family, object[] parameters);
void LogIncomingComponentNetMessage(int uid, EntityMessage entityMessage, ComponentFamily componentFamily,
object[] parameters);
void LogComponentMessage(int uid, ComponentFamily senderfamily, string sendertype, ComponentMessageType type);
void Ping();
}
}

View File

@@ -1,125 +0,0 @@
using SS14.Client.Interfaces.MessageLogging;
using SS14.Shared;
using SS14.Shared.Configuration;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.Configuration;
using SS14.Shared.IoC;
using System;
using System.ServiceModel;
using System.Timers;
namespace SS14.Client.MessageLogging
{
public class MessageLogger : IMessageLogger, IPostInjectInit
{
[Dependency]
private readonly IConfigurationManager _configurationManager;
private Timer _pingTimer;
private MessageLoggerServiceClient _loggerServiceClient;
private bool _logging;
public void PostInject()
{
_configurationManager.RegisterCVar("log.enabled", false);
}
public void Initialize()
{
_logging = _configurationManager.GetCVar<bool>("log.enabled");
if (_logging)
{
_loggerServiceClient = new MessageLoggerServiceClient("NetNamedPipeBinding_IMessageLoggerService");
Ping();
_pingTimer = new Timer(5000);
_pingTimer.Elapsed += CheckServer;
_pingTimer.Enabled = true;
}
}
#region IMessageLogger Members
/// <summary>
/// Check to see if the server is still running
/// </summary>
public void Ping()
{
bool failed = false;
try
{
bool up = _loggerServiceClient.ServiceStatus();
}
catch (CommunicationException)
{
failed = true;
}
finally
{
if (failed)
_logging = false;
}
}
public void LogOutgoingComponentNetMessage(int uid, ComponentFamily family, object[] parameters)
{
if (!_logging)
return;
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i] is Enum)
parameters[i] = (int) parameters[i];
}
try
{
_loggerServiceClient.LogClientOutgoingNetMessage(uid, (int) family, parameters);
}
catch (CommunicationException)
{
}
}
public void LogIncomingComponentNetMessage(int uid, EntityMessage entityMessage, ComponentFamily componentFamily,
object[] parameters)
{
if (!_logging)
return;
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i] is Enum)
parameters[i] = (int) parameters[i];
}
try
{
_loggerServiceClient.LogClientIncomingNetMessage(uid, (int) entityMessage, (int) componentFamily,
parameters);
}
catch (CommunicationException)
{
}
}
public void LogComponentMessage(int uid, ComponentFamily senderfamily, string sendertype,
ComponentMessageType type)
{
if (!_logging)
return;
try
{
_loggerServiceClient.LogClientComponentMessage(uid, (int) senderfamily, sendertype, (int) type);
}
catch (CommunicationException)
{
}
}
#endregion
public static void CheckServer(object source, ElapsedEventArgs e)
{
IoCManager.Resolve<IMessageLogger>().Ping();
}
}
}

View File

@@ -1,112 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="IMessageLoggerService")]
public interface IMessageLoggerService
{
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMessageLoggerService/LogServerIncomingNetMessage", ReplyAction="http://tempuri.org/IMessageLoggerService/LogServerIncomingNetMessageResponse")]
[System.ServiceModel.ServiceKnownTypeAttribute(typeof(object[]))]
void LogServerIncomingNetMessage(long clientUID, int uid, int entityMessageType, int componentFamily, object[] parameters);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMessageLoggerService/LogServerOutgoingNetMessage", ReplyAction="http://tempuri.org/IMessageLoggerService/LogServerOutgoingNetMessageResponse")]
[System.ServiceModel.ServiceKnownTypeAttribute(typeof(object[]))]
void LogServerOutgoingNetMessage(long clientUID, int uid, int family, object[] parameters);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMessageLoggerService/LogClientIncomingNetMessage", ReplyAction="http://tempuri.org/IMessageLoggerService/LogClientIncomingNetMessageResponse")]
[System.ServiceModel.ServiceKnownTypeAttribute(typeof(object[]))]
void LogClientIncomingNetMessage(int uid, int entityMessageType, int componentFamily, object[] parameters);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMessageLoggerService/LogClientOutgoingNetMessage", ReplyAction="http://tempuri.org/IMessageLoggerService/LogClientOutgoingNetMessageResponse")]
[System.ServiceModel.ServiceKnownTypeAttribute(typeof(object[]))]
void LogClientOutgoingNetMessage(int uid, int family, object[] parameters);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMessageLoggerService/LogServerComponentMessage", ReplyAction="http://tempuri.org/IMessageLoggerService/LogServerComponentMessageResponse")]
void LogServerComponentMessage(int senderid, int senderFamily, string senderType, int componentMessageType);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMessageLoggerService/LogClientComponentMessage", ReplyAction="http://tempuri.org/IMessageLoggerService/LogClientComponentMessageResponse")]
void LogClientComponentMessage(int senderid, int senderFamily, string senderType, int componentMessageType);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMessageLoggerService/ServiceStatus", ReplyAction="http://tempuri.org/IMessageLoggerService/ServiceStatusResponse")]
bool ServiceStatus();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IMessageLoggerServiceChannel : IMessageLoggerService, System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class MessageLoggerServiceClient : System.ServiceModel.ClientBase<IMessageLoggerService>, IMessageLoggerService
{
public MessageLoggerServiceClient()
{
}
public MessageLoggerServiceClient(string endpointConfigurationName) :
base(endpointConfigurationName)
{
}
public MessageLoggerServiceClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public MessageLoggerServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress)
{
}
public MessageLoggerServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress)
{
}
public void LogServerIncomingNetMessage(long clientUID, int uid, int entityMessageType, int componentFamily, object[] parameters)
{
base.Channel.LogServerIncomingNetMessage(clientUID, uid, entityMessageType, componentFamily, parameters);
}
public void LogServerOutgoingNetMessage(long clientUID, int uid, int family, object[] parameters)
{
base.Channel.LogServerOutgoingNetMessage(clientUID, uid, family, parameters);
}
public void LogClientIncomingNetMessage(int uid, int entityMessageType, int componentFamily, object[] parameters)
{
base.Channel.LogClientIncomingNetMessage(uid, entityMessageType, componentFamily, parameters);
}
public void LogClientOutgoingNetMessage(int uid, int family, object[] parameters)
{
base.Channel.LogClientOutgoingNetMessage(uid, family, parameters);
}
public void LogServerComponentMessage(int senderid, int senderFamily, string senderType, int componentMessageType)
{
base.Channel.LogServerComponentMessage(senderid, senderFamily, senderType, componentMessageType);
}
public void LogClientComponentMessage(int senderid, int senderFamily, string senderType, int componentMessageType)
{
base.Channel.LogClientComponentMessage(senderid, senderFamily, senderType, componentMessageType);
}
public bool ServiceStatus()
{
return base.Channel.ServiceStatus();
}
}

View File

@@ -1,29 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<netNamedPipeBinding>
<binding name="NetNamedPipeBinding_IMessageLoggerService" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" transactionFlow="false" transferMode="Buffered"
transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288"
maxBufferSize="65536" maxConnections="10" maxReceivedMessageSize="65536">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
<security mode="Transport">
<transport protectionLevel="EncryptAndSign" />
</security>
</binding>
</netNamedPipeBinding>
</bindings>
<client>
<endpoint address="net.pipe://messageloggerservice/log" binding="netNamedPipeBinding"
bindingConfiguration="NetNamedPipeBinding_IMessageLoggerService" contract="IMessageLoggerService"
name="NetNamedPipeBinding_IMessageLoggerService">
<identity>
<userPrincipalName value="Arxus-64\William Schaller" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>

View File

@@ -40,7 +40,7 @@ namespace SS14.Client.Placement.Modes
var rangeSquared = pManager.CurrentPermission.Range * pManager.CurrentPermission.Range;
if (rangeSquared > 0)
if (
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform)
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>()
.Position - mouseWorld).LengthSquared() > rangeSquared) return false;
currentTile = currentMap.GetTileRef(mouseWorld);

View File

@@ -2,6 +2,7 @@ using SFML.Graphics;
using SFML.System;
using SS14.Client.GameObjects;
using SS14.Client.Graphics;
using SS14.Client.Helpers;
using SS14.Client.Interfaces.GameObjects;
using SS14.Client.Interfaces.Map;
using SS14.Shared.GameObjects;
@@ -44,7 +45,7 @@ namespace SS14.Client.Placement.Modes
var rangeSquared = pManager.CurrentPermission.Range * pManager.CurrentPermission.Range;
if (rangeSquared > 0)
if (
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform)
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>()
.Position - mouseWorld).LengthSquared() > rangeSquared) return false;
var manager = IoCManager.Resolve<IClientEntityManager>();
@@ -54,29 +55,22 @@ namespace SS14.Client.Placement.Modes
where entity.Prototype == pManager.CurrentPrototype
orderby
(entity.GetComponent<TransformComponent>(
ComponentFamily.Transform).Position - mouseWorld).LengthSquared()
).Position - mouseWorld).LengthSquared()
ascending
select entity;
if (snapToEntities.Any())
{
IEntity closestEntity = snapToEntities.First();
ComponentReplyMessage reply = closestEntity.SendMessage(this, ComponentFamily.Renderable,
ComponentMessageType.GetSprite);
//if(replies.Any(x => x.messageType == SS13_Shared.GO.ComponentMessageType.CurrentSprite))
//{
// Sprite closestSprite = (Sprite)replies.Find(x => x.messageType == SS13_Shared.GO.ComponentMessageType.CurrentSprite).paramsList[0]; //This is safer but slower.
if (reply.MessageType == ComponentMessageType.CurrentSprite)
if (closestEntity.TryGetComponent<ISpriteRenderableComponent>(out var component))
{
var closestSprite = (Sprite)reply.ParamsList[0]; //This is faster but kinda unsafe.
var closestSprite = component.GetCurrentSprite();
var closestBounds = closestSprite.GetLocalBounds();
var closestRect =
new FloatRect(
closestEntity.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.X - closestBounds.Width / 2f,
closestEntity.GetComponent<TransformComponent>(ComponentFamily.Transform).Position.Y - closestBounds.Height / 2f,
closestEntity.GetComponent<TransformComponent>().Position.X - closestBounds.Width / 2f,
closestEntity.GetComponent<TransformComponent>().Position.Y - closestBounds.Height / 2f,
closestBounds.Width, closestBounds.Height);
var sides = new List<Vector2f>

View File

@@ -33,7 +33,7 @@ namespace SS14.Client.Placement.Modes
var rangeSquared = pManager.CurrentPermission.Range * pManager.CurrentPermission.Range;
if (rangeSquared > 0)
if (
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform)
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>()
.Position - mouseWorld).LengthSquared() > rangeSquared)
return false;

View File

@@ -34,7 +34,7 @@ namespace SS14.Client.Placement.Modes
var rangeSquared = pManager.CurrentPermission.Range * pManager.CurrentPermission.Range;
if (rangeSquared > 0)
if (
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform)
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>()
.Position - mouseWorld).LengthSquared() > rangeSquared)
return false;

View File

@@ -34,7 +34,7 @@ namespace SS14.Client.Placement.Modes
var rangeSquared = pManager.CurrentPermission.Range * pManager.CurrentPermission.Range;
if (rangeSquared > 0)
if (
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform)
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>()
.Position - mouseWorld).LengthSquared() > rangeSquared)
return false;

View File

@@ -34,7 +34,7 @@ namespace SS14.Client.Placement.Modes
var rangeSquared = pManager.CurrentPermission.Range * pManager.CurrentPermission.Range;
if (rangeSquared > 0)
if (
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform)
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>()
.Position - mouseWorld).LengthSquared() > rangeSquared)
return false;

View File

@@ -40,7 +40,7 @@ namespace SS14.Client.Placement.Modes
var rangeSquared = pManager.CurrentPermission.Range * pManager.CurrentPermission.Range;
if (rangeSquared > 0)
if (
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform)
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>()
.Position - mouseWorld).LengthSquared() > rangeSquared)
return false;
@@ -70,7 +70,7 @@ namespace SS14.Client.Placement.Modes
var range = pManager.CurrentPermission.Range;
if (range > 0)
if (
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform)
(pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>()
.Position - mouseWorld).LengthSquared() > range * range)
return false;

View File

@@ -176,7 +176,7 @@ namespace SS14.Client.Placement
if (CurrentPermission != null && CurrentPermission.Range > 0)
{
var pos = CluwneLib.WorldToScreen(PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
var pos = CluwneLib.WorldToScreen(PlayerManager.ControlledEntity.GetComponent<TransformComponent>().Position);
CluwneLib.drawCircle(pos.X,
pos.Y,
CurrentPermission.Range,

View File

@@ -1,5 +1,6 @@
using Lidgren.Network;
using SFML.Window;
using SS14.Client.Interfaces.GameObjects;
using SS14.Client.GameObjects;
using SS14.Client.Graphics.Render;
using SS14.Client.Interfaces.Network;
@@ -52,11 +53,15 @@ namespace SS14.Client.Player
var factory = IoCManager.Resolve<IComponentFactory>();
ControlledEntity = newEntity;
ControlledEntity.AddComponent(ComponentFamily.Input, factory.GetComponent<KeyBindingInputComponent>());
ControlledEntity.AddComponent(ComponentFamily.Mover, factory.GetComponent<PlayerInputMoverComponent>());
ControlledEntity.AddComponent(ComponentFamily.Collider, factory.GetComponent<ColliderComponent>());
ControlledEntity.AddComponent(factory.GetComponent<KeyBindingInputComponent>());
if (ControlledEntity.HasComponent<IMoverComponent>())
{
ControlledEntity.RemoveComponent<IMoverComponent>();
}
ControlledEntity.AddComponent(factory.GetComponent<PlayerInputMoverComponent>());
ControlledEntity.AddComponent(factory.GetComponent<ColliderComponent>());
ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove += PlayerEntityMoved;
ControlledEntity.GetComponent<TransformComponent>().OnMove += PlayerEntityMoved;
}
public void ApplyEffects(RenderImage image)
@@ -71,12 +76,14 @@ namespace SS14.Client.Player
{
if (ControlledEntity != null && ControlledEntity.Initialized)
{
ControlledEntity.RemoveComponent(ComponentFamily.Input);
ControlledEntity.RemoveComponent(ComponentFamily.Mover);
ControlledEntity.RemoveComponent(ComponentFamily.Collider);
var transform = ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform);
ControlledEntity.RemoveComponent<KeyBindingInputComponent>();
ControlledEntity.RemoveComponent<PlayerInputMoverComponent>();
ControlledEntity.RemoveComponent<ColliderComponent>();
var transform = ControlledEntity.GetComponent<TransformComponent>();
if (transform != null)
{
transform.OnMove -= PlayerEntityMoved;
}
}
ControlledEntity = null;
}

View File

@@ -7,7 +7,6 @@ using SS14.Client.Interfaces.GameObjects;
using SS14.Client.Interfaces.Input;
using SS14.Client.Interfaces.Lighting;
using SS14.Client.Interfaces.Map;
using SS14.Client.Interfaces.MessageLogging;
using SS14.Client.Interfaces.Network;
using SS14.Client.Interfaces.Placement;
using SS14.Client.Interfaces.Player;
@@ -17,7 +16,6 @@ using SS14.Client.Interfaces.UserInterface;
using SS14.Client.Interfaces.Utility;
using SS14.Client.Lighting;
using SS14.Client.Map;
using SS14.Client.MessageLogging;
using SS14.Client.Network;
using SS14.Client.Placement;
using SS14.Client.Player;
@@ -67,46 +65,6 @@ namespace SS14.Client
IoCManager.Clear();
}
/// <summary>
/// Registers all the types into the <see cref="IoCManager"/> with <see cref="IoCManager.Register{TInterface, TImplementation}"/>
/// </summary>
private static void RegisterIoC()
{
// Shared stuff.
IoCManager.Register<IComponentManager, ComponentManager>();
IoCManager.Register<IPrototypeManager, PrototypeManager>();
IoCManager.Register<IEntitySystemManager, EntitySystemManager>();
IoCManager.Register<ILogManager, LogManager>();
IoCManager.Register<IConfigurationManager, ConfigurationManager>();
IoCManager.Register<INetManager, NetManager>();
IoCManager.Register<IGameTiming, GameTiming>();
// Client stuff.
IoCManager.Register<IRand, Rand>();
IoCManager.Register<IStateManager, StateManager>();
IoCManager.Register<INetworkGrapher, NetworkGrapher>();
IoCManager.Register<IKeyBindingManager, KeyBindingManager>();
IoCManager.Register<IUserInterfaceManager, UserInterfaceManager>();
IoCManager.Register<ITileDefinitionManager, TileDefinitionManager>();
IoCManager.Register<IMessageLogger, MessageLogger>();
IoCManager.Register<ICollisionManager, CollisionManager>();
IoCManager.Register<IEntityManager, ClientEntityManager>();
IoCManager.Register<IClientEntityManager, ClientEntityManager>();
IoCManager.Register<IClientNetManager, NetManager>();
IoCManager.Register<IReflectionManager, ClientReflectionManager>();
IoCManager.Register<IPlacementManager, PlacementManager>();
IoCManager.Register<ILightManager, LightManager>();
IoCManager.Register<IResourceManager, ResourceManager>();
IoCManager.Register<ISS14Serializer, SS14Serializer>();
IoCManager.Register<IMapManager, MapManager>();
IoCManager.Register<IEntityNetworkManager, ClientEntityNetworkManager>();
IoCManager.Register<IPlayerManager, PlayerManager>();
IoCManager.Register<IGameController, GameController>();
IoCManager.Register<IComponentFactory, ClientComponentFactory>();
IoCManager.BuildGraph();
}
private static void LoadAssemblies()
{
var assemblies = new List<Assembly>(4)
@@ -146,5 +104,51 @@ namespace SS14.Client
IoCManager.Resolve<IReflectionManager>().LoadAssemblies(assemblies);
}
/// <summary>
/// Registers all the types into the <see cref="IoCManager"/> with <see cref="IoCManager.Register{TInterface, TImplementation}"/>
/// </summary>
private static void RegisterIoC()
{
// Shared stuff.
IoCManager.Register<IComponentManager, ComponentManager>();
IoCManager.Register<IPrototypeManager, PrototypeManager>();
IoCManager.Register<IEntitySystemManager, EntitySystemManager>();
IoCManager.Register<ILogManager, LogManager>();
IoCManager.Register<IConfigurationManager, ConfigurationManager>();
IoCManager.Register<INetManager, NetManager>();
IoCManager.Register<IGameTiming, GameTiming>();
// Client stuff.
IoCManager.Register<IRand, Rand>();
IoCManager.Register<IStateManager, StateManager>();
IoCManager.Register<INetworkGrapher, NetworkGrapher>();
IoCManager.Register<IKeyBindingManager, KeyBindingManager>();
IoCManager.Register<IUserInterfaceManager, UserInterfaceManager>();
IoCManager.Register<ITileDefinitionManager, TileDefinitionManager>();
IoCManager.Register<ICollisionManager, CollisionManager>();
IoCManager.Register<IEntityManager, ClientEntityManager>();
IoCManager.Register<IClientEntityManager, ClientEntityManager>();
IoCManager.Register<IClientNetManager, NetManager>();
IoCManager.Register<IReflectionManager, ClientReflectionManager>();
IoCManager.Register<IPlacementManager, PlacementManager>();
IoCManager.Register<ILightManager, LightManager>();
IoCManager.Register<IResourceManager, ResourceManager>();
IoCManager.Register<ISS14Serializer, SS14Serializer>();
IoCManager.Register<IMapManager, MapManager>();
IoCManager.Register<IEntityNetworkManager, ClientEntityNetworkManager>();
IoCManager.Register<IPlayerManager, PlayerManager>();
IoCManager.Register<IGameController, GameController>();
IoCManager.Register<IComponentFactory, ClientComponentFactory>();
IoCManager.BuildGraph();
}
private static void RegisterComponents()
{
var factory = IoCManager.Resolve<IComponentFactory>();
factory.Register<BasicMoverComponent>();
}
}
}

View File

@@ -205,20 +205,10 @@
<Compile Include="GameObjects\Component\Collidable\CollidableComponent.cs" />
<Compile Include="GameObjects\Component\Collidable\TriggerableComponent.cs" />
<Compile Include="GameObjects\Component\Collider\ColliderComponent.cs" />
<Compile Include="GameObjects\Component\Damageable\DamageableComponent.cs" />
<Compile Include="GameObjects\Component\Direction\DirectionComponent.cs" />
<Compile Include="GameObjects\Component\EntityStats\EntityStatsCompC.cs" />
<Compile Include="GameObjects\Component\Equipment\EquipmentComponent.cs" />
<Compile Include="GameObjects\Component\Equipment\HumanEquipmentComponent.cs" />
<Compile Include="GameObjects\Component\Equippable\EquippableComponent.cs" />
<Compile Include="GameObjects\Component\Hands\HumanHandsComponent.cs" />
<Compile Include="GameObjects\Component\Hitbox\HitboxComponent.cs" />
<Compile Include="GameObjects\Component\Damageable\Health\HealthComponent.cs" />
<Compile Include="GameObjects\Component\Icon\IconComponent.cs" />
<Compile Include="GameObjects\Component\Input\ContextMenuComponent.cs" />
<Compile Include="GameObjects\Component\Inventory\InventoryComponent.cs" />
<Compile Include="GameObjects\Component\Item\BasicItemComponent.cs" />
<Compile Include="GameObjects\Component\Light\FlashLightComponent.cs" />
<Compile Include="GameObjects\Component\Light\PointLightComponent.cs" />
<Compile Include="GameObjects\Component\Mover\PlayerInputMoverComponent.cs" />
<Compile Include="GameObjects\Component\Mover\BasicMoverComponent.cs" />
@@ -232,13 +222,11 @@
<Compile Include="GameObjects\Component\Renderable\ItemSpriteComponent.cs" />
<Compile Include="GameObjects\Component\Renderable\MobSpriteComponent.cs" />
<Compile Include="GameObjects\Component\Renderable\SpriteComponent.cs" />
<Compile Include="GameObjects\Component\SVars\SVarsComponent.cs" />
<Compile Include="GameObjects\Component\Transform\TransformComponent.cs" />
<Compile Include="GameObjects\Component\Velocity\VelocityComponent.cs" />
<Compile Include="GameObjects\ContextMenuEntry.cs" />
<Compile Include="GameObjects\EntitySystems\ParticleSystem.cs" />
<Compile Include="GameObjects\EntitySystems\InputSystem.cs" />
<Compile Include="GameObjects\EntitySystems\InventorySystem.cs" />
<Compile Include="GameObjects\EntitySystems\TransformSystem.cs" />
<Compile Include="GameObjects\ClientEntityManager.cs" />
<Compile Include="GameObjects\ClientEntityNetworkManager.cs" />
@@ -257,6 +245,7 @@
<Compile Include="Console\HelpCommands.cs" />
<Compile Include="Console\ParticleCommands.cs" />
<Compile Include="Console\QuitCommand.cs" />
<Compile Include="Console\Debug.cs" />
<Compile Include="GameStates\GameStateManager.cs" />
<Compile Include="Helpers\GaussianBlur.cs" />
<Compile Include="Helpers\InterpolationPacket.cs" />
@@ -268,10 +257,11 @@
<Compile Include="Interfaces\Collision\ICollisionManager.cs" />
<Compile Include="Interfaces\Console\IConsoleCommand.cs" />
<Compile Include="Interfaces\Console\IDebugConsole.cs" />
<Compile Include="Interfaces\GameObjects\GetSVarsEventArgs.cs" />
<Compile Include="Interfaces\GameObjects\IMoverComponent.cs" />
<Compile Include="Interfaces\GameObjects\ISpriteRenderableComponent.cs" />
<Compile Include="Interfaces\GameObjects\IParticleSystemComponent.cs" />
<Compile Include="Interfaces\GameObjects\IRenderableComponent.cs" />
<Compile Include="Interfaces\GameObjects\ISVarsComponent.cs" />
<Compile Include="Interfaces\GameObjects\IClickTargetComponent.cs" />
<Compile Include="Interfaces\GameObjects\ISpriteComponent.cs" />
<Compile Include="Interfaces\GameStates\IGameStateManager.cs" />
<Compile Include="Interfaces\Input\IKeyBindingManager.cs" />
@@ -286,7 +276,6 @@
<Compile Include="Interfaces\Map\ITileDefinitionManager.cs" />
<Compile Include="Interfaces\Map\Tile.cs" />
<Compile Include="Interfaces\Map\TileRef.cs" />
<Compile Include="Interfaces\MessageLogging\IMessageLogger.cs" />
<Compile Include="Interfaces\Network\INetworkGrapher.cs" />
<Compile Include="Interfaces\Placement\IPlacementManager.cs" />
<Compile Include="Interfaces\Player\IPlayerManager.cs" />
@@ -308,9 +297,6 @@
<Compile Include="Map\MapManager.cs" />
<Compile Include="Map\TileDefinition.cs" />
<Compile Include="Map\TileDefinitionManager.cs" />
<Compile Include="MessageLogging\MessageLogger.cs" />
<Compile Include="MessageLogging\MessageLoggerService.cs" />
<None Include="MessageLogging\messageLoggerService.config" />
<Compile Include="Network\NetworkGrapher.cs" />
<Compile Include="Placement\PlacementManager.cs" />
<Compile Include="Placement\PlacementMode.cs" />
@@ -335,8 +321,6 @@
<Compile Include="State\States\OptionsMenu.cs" />
<Compile Include="UserInterface\DragDropInfo.cs" />
<Compile Include="UserInterface\UserInterfaceManager.cs" />
<Compile Include="UserInterface\Components\ArmorInfoLabel.cs" />
<Compile Include="UserInterface\Components\BlueprintButton.cs" />
<Compile Include="UserInterface\Components\Button.cs" />
<Compile Include="UserInterface\Components\Chatbox.cs" />
<Compile Include="UserInterface\Components\Checkbox.cs" />
@@ -348,15 +332,12 @@
<Compile Include="UserInterface\Components\ExamineWindow.cs" />
<Compile Include="UserInterface\Components\FloatingDeco.cs" />
<Compile Include="UserInterface\Components\GuiComponent.cs" />
<Compile Include="UserInterface\Components\HandsGui.cs" />
<Compile Include="UserInterface\Components\HealthPanel.cs" />
<Compile Include="UserInterface\Components\ImageButton.cs" />
<Compile Include="UserInterface\Components\Label.cs" />
<Compile Include="UserInterface\Components\Listbox.cs" />
<Compile Include="UserInterface\Components\MenuWindow.cs" />
<Compile Include="UserInterface\Components\ProgressBar.cs" />
<Compile Include="UserInterface\Components\PropEditWindow.cs" />
<Compile Include="UserInterface\Components\SVarEditWindow.cs" />
<Compile Include="UserInterface\Components\ScrollableContainer.cs" />
<Compile Include="UserInterface\Components\Scrollbar.cs" />
<Compile Include="UserInterface\Components\Showcase.cs" />
@@ -366,10 +347,6 @@
<Compile Include="UserInterface\Components\TileSpawnPanel.cs" />
<Compile Include="UserInterface\Components\TimerBar.cs" />
<Compile Include="UserInterface\Components\Window.cs" />
<Compile Include="UserInterface\Inventory\EquipmentSlotUi.cs" />
<Compile Include="UserInterface\Inventory\HumanComboGUI.cs" />
<Compile Include="UserInterface\Inventory\InventorySlotUi.cs" />
<Compile Include="UserInterface\Inventory\InventoryViewer.cs" />
<Compile Include="UserInterface\LobbyState\LobbyShowcase.cs" />
<Compile Include="UserInterface\LobbyState\PlayerLstTab.cs" />
<Compile Include="UserInterface\LobbyState\TabContainer.cs" />
@@ -392,4 +369,4 @@
<PropertyGroup>
<DefineConstants Condition="Exists('Microsoft.VisualStudio.DebuggerVisualizers.dll') ">$(DefineConstants);VS_DEBUGGERVISUALIZERS_EXISTS</DefineConstants>
</PropertyGroup>
</Project>
</Project>

View File

@@ -17,7 +17,6 @@ using SS14.Client.Interfaces.State;
using SS14.Client.Helpers;
using SS14.Client.Lighting;
using SS14.Client.UserInterface.Components;
using SS14.Client.UserInterface.Inventory;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameStates;
@@ -88,12 +87,6 @@ namespace SS14.Client.State.States
private MenuWindow _menu;
private Chatbox _gameChat;
private HandsGui _handsGui;
private HumanComboGui _combo;
private HealthPanel _healthPanel;
private ImageButton _inventoryButton;
private ImageButton _statusButton;
private ImageButton _menuButton;
#endregion UI Variables
#region Lighting
@@ -273,21 +266,6 @@ namespace SS14.Client.State.States
private void UpdateGUIPosition()
{
_gameChat.Position = new Vector2i((int)CluwneLib.Screen.Size.X - _gameChatSize.X - 10, 10);
int hotbar_pos_y = (int)CluwneLib.Screen.Size.Y - 88;
_handsGui.Position = new Vector2i(5, hotbar_pos_y + 7);
// 712 is width of hotbar background I think?
_combo.Position = new Vector2i(712 - _combo.ClientArea.Width + 5,
hotbar_pos_y - _combo.ClientArea.Height - 5);
_healthPanel.Position = new Vector2i(712 - 1, hotbar_pos_y + 11);
_inventoryButton.Position = new Vector2i(172, hotbar_pos_y + 2);
_statusButton.Position = new Vector2i(_inventoryButton.ClientArea.Right(), _inventoryButton.Position.Y);
_menuButton.Position = new Vector2i(_statusButton.ClientArea.Right(), _statusButton.Position.Y);
}
private void InitializeGUI()
@@ -301,53 +279,6 @@ namespace SS14.Client.State.States
_gameChat = new Chatbox("gamechat", _gameChatSize, ResourceManager);
_gameChat.TextSubmitted += ChatTextboxTextSubmitted;
UserInterfaceManager.AddComponent(_gameChat);
//UserInterfaceManager.AddComponent(new StatPanelComponent(ConfigurationManager.GetPlayerName(), PlayerManager, NetClientManager, ResourceManager));
int hotbar_pos_y = (int)CluwneLib.Screen.Size.Y - 88;
_handsGui = new HandsGui();
_handsGui.Position = new Vector2i(5, hotbar_pos_y + 7);
UserInterfaceManager.AddComponent(_handsGui);
_combo = new HumanComboGui(PlayerManager, NetworkManager, ResourceManager, UserInterfaceManager);
_combo.Position = new Vector2i(712 - _combo.ClientArea.Width + 5,
hotbar_pos_y - _combo.ClientArea.Height - 5);
_combo.Update(0);
UserInterfaceManager.AddComponent(_combo);
_healthPanel = new HealthPanel();
_healthPanel.Position = new Vector2i(711, hotbar_pos_y + 11);
_healthPanel.Update(0);
UserInterfaceManager.AddComponent(_healthPanel);
_inventoryButton = new ImageButton
{
ImageNormal = "button_inv",
Position = new Vector2i(172, hotbar_pos_y + 2)
};
_inventoryButton.Update(0);
_inventoryButton.Clicked += inventoryButton_Clicked;
UserInterfaceManager.AddComponent(_inventoryButton);
_statusButton = new ImageButton
{
ImageNormal = "button_status",
Position =
new Vector2i(_inventoryButton.ClientArea.Right(), _inventoryButton.Position.Y)
};
_statusButton.Update(0);
_statusButton.Clicked += statusButton_Clicked;
UserInterfaceManager.AddComponent(_statusButton);
_menuButton = new ImageButton
{
ImageNormal = "button_menu",
Position = new Vector2i(_statusButton.ClientArea.Right(), _statusButton.Position.Y)
};
_menuButton.Update(0);
_menuButton.Clicked += menuButton_Clicked;
UserInterfaceManager.AddComponent(_menuButton);
}
private void InitalizeLighting()
@@ -409,7 +340,7 @@ namespace SS14.Client.State.States
if (PlayerManager.ControlledEntity != null)
{
CluwneLib.WorldCenter = PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform).Position;
CluwneLib.WorldCenter = PlayerManager.ControlledEntity.GetComponent<TransformComponent>().Position;
MousePosWorld = CluwneLib.ScreenToWorld(MousePosScreen); // Use WorldCenter to calculate, so we need to update again
}
}
@@ -518,14 +449,12 @@ namespace SS14.Client.State.States
if (CluwneLib.Debug.DebugColliders)
{
var colliders =
_componentManager.GetComponents(ComponentFamily.Collider)
.OfType<ColliderComponent>()
_componentManager.GetComponents<ColliderComponent>()
.Select(c => new { Color = c.DebugColor, AABB = c.WorldAABB })
.Where(c => !c.AABB.IsEmpty() && c.AABB.Intersects(viewport));
var collidables =
_componentManager.GetComponents(ComponentFamily.Collidable)
.OfType<CollidableComponent>()
_componentManager.GetComponents<CollidableComponent>()
.Select(c => new { Color = c.DebugColor, AABB = c.AABB })
.Where(c => !c.AABB.IsEmpty() && c.AABB.Intersects(viewport));
@@ -546,7 +475,7 @@ namespace SS14.Client.State.States
Color.Blue.WithAlpha(64));
// Player position debug
Vector2f playerWorldOffset = PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform).Position;
Vector2f playerWorldOffset = PlayerManager.ControlledEntity.GetComponent<TransformComponent>().Position;
Vector2f playerTile = CluwneLib.WorldToTile(playerWorldOffset);
Vector2f playerScreen = CluwneLib.WorldToScreen(playerWorldOffset);
CluwneLib.drawText(15, 15, "Postioning Debug", 14, Color.White);
@@ -714,7 +643,7 @@ namespace SS14.Client.State.States
// Find all the entities near us we could have clicked
IEnumerable<IEntity> entities =
_entityManager.GetEntitiesInRange(
PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform).Position,
PlayerManager.ControlledEntity.GetComponent<TransformComponent>().Position,
checkDistance);
// See which one our click AABB intersected with
@@ -722,7 +651,7 @@ namespace SS14.Client.State.States
var clickedWorldPoint = new Vector2f(MousePosWorld.X, MousePosWorld.Y);
foreach (IEntity entity in entities)
{
var clickable = (ClickableComponent)entity.GetComponent(ComponentFamily.Click);
var clickable = entity.GetComponent<ClickableComponent>();
if (clickable == null) continue;
if (clickable.CheckClick(clickedWorldPoint, out int drawdepthofclicked))
clickedEntities.Add(new ClickData(entity, drawdepthofclicked));
@@ -741,7 +670,7 @@ namespace SS14.Client.State.States
IEntity entToClick = (from cd in clickedEntities
orderby cd.Drawdepth ascending,
cd.Clicked.GetComponent<TransformComponent>(ComponentFamily.Transform).Position
cd.Clicked.GetComponent<TransformComponent>().Position
.Y ascending
select cd.Clicked).Last();
@@ -755,11 +684,11 @@ namespace SS14.Client.State.States
switch (e.Button)
{
case Mouse.Button.Left:
c = (ClickableComponent)entToClick.GetComponent(ComponentFamily.Click);
c = entToClick.GetComponent<ClickableComponent>();
c.DispatchClick(PlayerManager.ControlledEntity.Uid, MouseClickType.Left);
break;
case Mouse.Button.Right:
c = (ClickableComponent)entToClick.GetComponent(ComponentFamily.Click);
c = entToClick.GetComponent<ClickableComponent>();
c.DispatchClick(PlayerManager.ControlledEntity.Uid, MouseClickType.Right);
break;
case Mouse.Button.Middle:
@@ -1258,7 +1187,7 @@ namespace SS14.Client.State.States
// I think this should be transparent? Maybe it should be black for the player occlusion...
// I don't remember. --volundr
playerOcclusionTarget.Clear(Color.Black);
playerVision.Move(PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
playerVision.Move(PlayerManager.ControlledEntity.GetComponent<TransformComponent>().Position);
LightArea area = GetLightArea(RadiusToShadowMapSize(playerVision.Radius));
area.LightPosition = playerVision.Position; // Set the light position
@@ -1387,8 +1316,9 @@ namespace SS14.Client.State.States
/// <param name="frametime">time since the last frame was rendered.</param>
private void RenderComponents(float frameTime, FloatRect viewPort)
{
IEnumerable<IComponent> components = _componentManager.GetComponents(ComponentFamily.Renderable)
.Union(_componentManager.GetComponents(ComponentFamily.Particles));
IEnumerable<IComponent> components = _componentManager.GetComponents<ISpriteRenderableComponent>()
.Cast<IComponent>()
.Union(_componentManager.GetComponents<ParticleSystemComponent>());
IEnumerable<IRenderableComponent> floorRenderables = from IRenderableComponent c in components
orderby c.Bottom ascending, c.DrawDepth ascending

View File

@@ -1,108 +0,0 @@
using SFML.Graphics;
using SFML.System;
using SS14.Client.GameObjects;
using SS14.Client.Graphics;
using SS14.Client.Graphics.Sprite;
using SS14.Client.Interfaces.Player;
using SS14.Client.Interfaces.Resource;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using System;
namespace SS14.Client.UserInterface.Components
{
internal class ArmorInfoLabel : GuiComponent
{
private readonly IResourceManager _resourceManager;
private readonly DamageType resAssigned;
private Sprite icon;
private TextSprite text;
public ArmorInfoLabel(DamageType resistance, IResourceManager resourceManager)
{
_resourceManager = resourceManager;
resAssigned = resistance;
text = new TextSprite("StatInfoLabel" + resistance, "", _resourceManager.GetFont("CALIBRI"))
{ Color = Color.White };
switch (resistance)
{
case DamageType.Bludgeoning:
icon = resourceManager.GetSprite("res_blunt");
break;
case DamageType.Burn:
icon = resourceManager.GetSprite("res_burn");
break;
case DamageType.Freeze:
icon = resourceManager.GetSprite("res_freeze");
break;
case DamageType.Piercing:
icon = resourceManager.GetSprite("res_pierce");
break;
case DamageType.Shock:
icon = resourceManager.GetSprite("res_shock");
break;
case DamageType.Slashing:
icon = resourceManager.GetSprite("res_slash");
break;
case DamageType.Suffocation:
icon = resourceManager.GetSprite("statusbar_switch");
break;
case DamageType.Toxin:
icon = resourceManager.GetSprite("res_tox");
break;
case DamageType.Untyped:
icon = resourceManager.GetSprite("statusbar_switch");
break;
}
Update(0);
}
public override void Update(float frameTime)
{
var bounds = icon.GetLocalBounds();
icon.Position = new Vector2f(Position.X, Position.Y);
text.Position = new Vector2i(Position.X + (int)bounds.Width + 5,
Position.Y + (int)(bounds.Height / 2f) - (int)(text.Height / 2f));
ClientArea = new IntRect(Position,
new Vector2i((int)text.Width + (int)bounds.Width + 5,
(int)Math.Max(bounds.Height, text.Height)));
var playerMgr = IoCManager.Resolve<IPlayerManager>();
if (playerMgr != null)
{
IEntity playerEnt = playerMgr.ControlledEntity;
if (playerEnt != null)
{
var statsComp = (EntityStatsComp)playerEnt.GetComponent(ComponentFamily.EntityStats);
if (statsComp != null)
{
text.Text = Enum.GetName(typeof(DamageType), resAssigned) + " : " +
statsComp.GetArmorValue(resAssigned);
}
else text.Text = Enum.GetName(typeof(DamageType), resAssigned) + " : n/a";
}
else text.Text = Enum.GetName(typeof(DamageType), resAssigned) + " : n/a";
}
else text.Text = Enum.GetName(typeof(DamageType), resAssigned) + " : n/a";
}
public override void Render()
{
icon.Draw();
text.Draw();
}
public override void Dispose()
{
text = null;
icon = null;
base.Dispose();
GC.SuppressFinalize(this);
}
}
}

View File

@@ -1,116 +0,0 @@
using SFML.Graphics;
using SFML.System;
using SFML.Window;
using SS14.Client.Graphics;
using SS14.Client.Graphics.Sprite;
using SS14.Client.Interfaces.Resource;
using System;
namespace SS14.Client.UserInterface.Components
{
internal class BlueprintButton : GuiComponent
{
#region Delegates
public delegate void BlueprintButtonPressHandler(BlueprintButton sender);
#endregion
private readonly IResourceManager _resourceManager;
public string Compo1;
public string Compo1Name;
public string Compo2;
public string Compo2Name;
public TextSprite Label;
public string Result;
public string ResultName;
private SFML.Graphics.Color _bgcol = Color.Transparent;
private Sprite _icon;
public BlueprintButton(string c1, string c1N, string c2, string c2N, string res, string resname,
IResourceManager resourceManager)
{
_resourceManager = resourceManager;
Compo1 = c1;
Compo1Name = c1N;
Compo2 = c2;
Compo2Name = c2N;
Result = res;
ResultName = resname;
_icon = _resourceManager.GetSprite("blueprint");
Label = new TextSprite("blueprinttext", "", _resourceManager.GetFont("CALIBRI"))
{
Color = new SFML.Graphics.Color(248, 248, 255),
ShadowColor = new SFML.Graphics.Color(105, 105, 105),
ShadowOffset = new Vector2f(1, 1),
Shadowed = true
};
Update(0);
}
public event BlueprintButtonPressHandler Clicked;
public override void Update(float frameTime)
{
var bounds = _icon.GetLocalBounds();
ClientArea = new IntRect(Position,
new Vector2i((int) (Label.Width + bounds.Width),
(int) Math.Max(Label.Height, bounds.Height)));
Label.Position = new Vector2i(Position.X + (int)bounds.Width, Position.Y);
_icon.Position = new Vector2f(Position.X, Position.Y + (Label.Height / 2f - bounds.Height / 2f));
Label.Text = Compo1Name + " + " + Compo2Name + " = " + ResultName;
}
public override void Render()
{
if (_bgcol != Color.Transparent)
{
CluwneLib.drawRectangle(ClientArea.Left, ClientArea.Top, ClientArea.Width,
ClientArea.Height, _bgcol);
}
_icon.Draw();
Label.Draw();
}
public override void Dispose()
{
Label = null;
_icon = null;
Clicked = null;
base.Dispose();
GC.SuppressFinalize(this);
}
public override bool MouseDown(MouseButtonEventArgs e)
{
if (ClientArea.Contains(e.X, e.Y))
{
if (Clicked != null) Clicked(this);
return true;
}
return false;
}
public override bool MouseUp(MouseButtonEventArgs e)
{
return false;
}
public override void MouseMove(MouseMoveEventArgs e)
{
_bgcol = ClientArea.Contains(e.X, e.Y)
? new SFML.Graphics.Color(70, 130, 180)
: Color.Transparent;
}
}
}

View File

@@ -50,14 +50,6 @@ namespace SS14.Client.UserInterface.Components
examineButton.Update(0);
}
var sVarButton =
new ContextMenuButton(
new ContextMenuEntry { ComponentMessage = "svars", EntryName = "SVars", IconName = "context_eye" },
_buttonSize, _resourceManager);
sVarButton.Selected += ContextSelected;
_buttons.Add(sVarButton);
sVarButton.Update(0);
foreach (ContextMenuEntry entry in entries)
{
var newButton = new ContextMenuButton(entry, _buttonSize, _resourceManager);
@@ -84,17 +76,10 @@ namespace SS14.Client.UserInterface.Components
_userInterfaceManager.AddComponent(newExamine);
newExamine.Position = new Vector2i(ClientArea.Left, ClientArea.Top);
}
else if ((string)sender.UserData == "svars")
else
{
var newSVars = new SVarEditWindow(new Vector2i(350, 400), _owningEntity);
_userInterfaceManager.AddComponent(newSVars);
newSVars.Position = new Vector2i(ClientArea.Left, ClientArea.Top);
_owningEntity.GetComponent<ISVarsComponent>(ComponentFamily.SVars).GetSVarsCallback +=
newSVars.GetSVarsCallback;
_owningEntity.GetComponent<ISVarsComponent>(ComponentFamily.SVars).DoGetSVars();
_owningEntity.SendMessage(this, ComponentMessageType.ContextMessage, (string)sender.UserData);
}
else _owningEntity.SendMessage(this, ComponentMessageType.ContextMessage, (string)sender.UserData);
}
public override void Update(float frameTime)

View File

@@ -1,6 +1,7 @@
using SFML.Graphics;
using SFML.System;
using SS14.Client.Graphics;
using SS14.Client.Interfaces.GameObjects;
using SS14.Client.Interfaces.Resource;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.GameObjects;
@@ -19,20 +20,19 @@ namespace SS14.Client.UserInterface.Components
components.Add(_entityDescription);
ComponentReplyMessage reply = entity.SendMessage(entity, ComponentFamily.Renderable,
ComponentMessageType.GetSprite);
SetVisible(true);
if (reply.MessageType == ComponentMessageType.CurrentSprite)
if (entity.TryGetComponent<ISpriteRenderableComponent>(out var component))
{
_entitySprite = (Sprite) reply.ParamsList[0];
_entitySprite = component.GetCurrentSprite();
_entityDescription.Position = new Vector2i(10,
(int)_entitySprite.GetLocalBounds().Height +
_entityDescription.ClientArea.Height + 10);
(int)_entitySprite.GetLocalBounds().Height +
_entityDescription.ClientArea.Height + 10);
}
else
{
_entityDescription.Position = new Vector2i(10, 10);
}
}
public override void Render()

View File

@@ -1,310 +0,0 @@
using Lidgren.Network;
using SFML.Graphics;
using SFML.Window;
using SS14.Client.GameObjects;
using SS14.Client.Graphics;
using SS14.Client.Interfaces.Player;
using SS14.Client.Interfaces.Resource;
using SS14.Client.Interfaces.UserInterface;
using SS14.Client.Helpers;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using System;
using System.Linq;
namespace SS14.Client.UserInterface.Components
{
public struct UiHandInfo
{
public IEntity Entity;
public InventoryLocation Hand;
public Sprite HeldSprite;
}
public class HandsGui : GuiComponent
{
private readonly Color _inactiveColor = new Color(90, 90, 90);
private readonly IPlayerManager _playerManager = IoCManager.Resolve<IPlayerManager>();
private readonly IUserInterfaceManager _userInterfaceManager = IoCManager.Resolve<IUserInterfaceManager>();
private readonly Sprite handSlot;
private readonly int spacing = 1;
public UiHandInfo LeftHand;
public UiHandInfo RightHand;
private IntRect handL;
private IntRect handR;
public HandsGui()
{
var _resMgr = IoCManager.Resolve<IResourceManager>();
ComponentClass = GuiComponentType.HandsUi;
handSlot = _resMgr.GetSprite("hand");
ZDepth = 5;
}
public override void ComponentUpdate(params object[] args)
{
base.ComponentUpdate(args);
UpdateHandIcons();
}
public override void Update(float frameTime)
{
var slotBounds = handSlot.GetLocalBounds();
handL = new IntRect(Position.X, Position.Y, (int)slotBounds.Width, (int)slotBounds.Height);
handR = new IntRect(Position.X + (int)slotBounds.Width + spacing, Position.Y, (int)slotBounds.Width, (int)slotBounds.Height);
ClientArea = new IntRect(Position.X, Position.Y, (int)((slotBounds.Width * 2) + spacing), (int)slotBounds.Height);
}
public override void Render()
{
if (_playerManager == null || _playerManager.ControlledEntity == null)
return;
IEntity entity = _playerManager.ControlledEntity;
var hands = (HumanHandsComponent)entity.GetComponent(ComponentFamily.Hands);
if (hands.CurrentHand == InventoryLocation.HandLeft)
{
handSlot.Color = Color.White;
handSlot.SetTransformToRect(handL);
handSlot.Draw();
handSlot.Color = _inactiveColor;
handSlot.SetTransformToRect(handR);
handSlot.Draw();
}
else
{
handSlot.Color = Color.White;
handSlot.SetTransformToRect(handR);
handSlot.Draw();
handSlot.Color = _inactiveColor;
handSlot.SetTransformToRect(handL);
handSlot.Draw();
}
if (LeftHand.Entity != null && LeftHand.HeldSprite != null)
{
var bounds = LeftHand.HeldSprite.GetLocalBounds();
LeftHand.HeldSprite.SetTransformToRect(
new IntRect(handL.Left + (int)(handL.Width / 2f - bounds.Width / 2f),
handL.Top + (int)(handL.Height / 2f - bounds.Height / 2f),
(int)bounds.Width, (int)bounds.Height));
LeftHand.HeldSprite.Draw();
}
if (RightHand.Entity != null && RightHand.HeldSprite != null)
{
var bounds = RightHand.HeldSprite.GetLocalBounds();
RightHand.HeldSprite.SetTransformToRect(
new IntRect(handR.Left + (int)(handR.Width / 2f - bounds.Width / 2f),
handR.Top + (int)(handR.Height / 2f - bounds.Height / 2f),
(int)bounds.Width, (int)bounds.Height));
RightHand.HeldSprite.Draw();
}
}
public override void Resize()
{
}
public override void Dispose()
{
base.Dispose();
GC.SuppressFinalize(this);
}
public override void HandleNetworkMessage(NetIncomingMessage message)
{
}
public void UpdateHandIcons()
{
if (_playerManager.ControlledEntity == null)
return;
IEntity entity = _playerManager.ControlledEntity;
var hands = (HumanHandsComponent)entity.GetComponent(ComponentFamily.Hands);
if (hands == null) return;
if (hands.HandSlots.Keys.Contains(InventoryLocation.HandLeft) && hands.HandSlots[InventoryLocation.HandLeft] != null)
{
if (LeftHand.Entity == null || LeftHand.Entity.Uid != hands.HandSlots[InventoryLocation.HandLeft].Uid)
{
IEntity entityL = hands.HandSlots[InventoryLocation.HandLeft];
LeftHand.Entity = entityL;
LeftHand.HeldSprite = Utilities.GetIconSprite(entityL);
}
}
else
{
LeftHand.Entity = null;
LeftHand.HeldSprite = null;
}
if (hands.HandSlots.Keys.Contains(InventoryLocation.HandRight) && hands.HandSlots[InventoryLocation.HandRight] != null)
{
if (RightHand.Entity == null || RightHand.Entity.Uid != hands.HandSlots[InventoryLocation.HandRight].Uid)
{
IEntity entityR = hands.HandSlots[InventoryLocation.HandRight];
RightHand.Entity = entityR;
RightHand.HeldSprite = Utilities.GetIconSprite(entityR);
}
}
else
{
RightHand.Entity = null;
RightHand.HeldSprite = null;
}
}
private void SendSwitchHandTo(InventoryLocation hand)
{
var _playerManager = IoCManager.Resolve<IPlayerManager>();
IEntity playerEntity = _playerManager.ControlledEntity;
var equipComponent = (HumanHandsComponent)playerEntity.GetComponent(ComponentFamily.Hands);
equipComponent.SendSwitchHands(hand);
}
public override bool MouseDown(MouseButtonEventArgs e)
{
switch (e.Button)
{
case Mouse.Button.Right:
if (handL.Contains(e.X, e.Y))
{
SendSwitchHandTo(InventoryLocation.HandLeft);
return true;
}
if (handR.Contains(e.X, e.Y))
{
SendSwitchHandTo(InventoryLocation.HandRight);
return true;
}
break;
}
return false;
}
public override bool MouseUp(MouseButtonEventArgs e)
{
if (ClientArea.Contains(e.X, e.Y))
{
if (_playerManager.ControlledEntity == null)
return false;
IEntity entity = _playerManager.ControlledEntity;
var equipment = (EquipmentComponent)entity.GetComponent(ComponentFamily.Equipment);
var hands = (HumanHandsComponent)entity.GetComponent(ComponentFamily.Hands);
if (hands == null || entity == null) return false;
if (_userInterfaceManager.DragInfo.IsEntity && _userInterfaceManager.DragInfo.IsActive)
{
if (handL.Contains(e.X, e.Y))
{
if (hands.HandSlots.ContainsKey(InventoryLocation.HandLeft) && hands.HandSlots[InventoryLocation.HandLeft] == null)
{
if (hands.HandSlots.ContainsValue(_userInterfaceManager.DragInfo.DragEntity))
{
if (
hands.HandSlots.First(x => x.Value == _userInterfaceManager.DragInfo.DragEntity).Key ==
InventoryLocation.HandLeft) //From me to me, dropped back on same hand.
return false;
hands.SendDropEntity(_userInterfaceManager.DragInfo.DragEntity); //Other hand to me.
}
equipment.DispatchUnEquipItemToSpecifiedHand(_userInterfaceManager.DragInfo.DragEntity.Uid,
InventoryLocation.HandLeft);
}
_userInterfaceManager.DragInfo.Reset();
return true;
}
else if (handR.Contains(e.X, e.Y))
{
if (hands.HandSlots.ContainsKey(InventoryLocation.HandRight) && hands.HandSlots[InventoryLocation.HandRight] == null)
{
if (hands.HandSlots.ContainsValue(_userInterfaceManager.DragInfo.DragEntity))
{
if (
hands.HandSlots.First(x => x.Value == _userInterfaceManager.DragInfo.DragEntity).Key ==
InventoryLocation.HandRight) //From me to me, dropped back on same hand
return false;
hands.SendDropEntity(_userInterfaceManager.DragInfo.DragEntity); //Other hand to me.
}
equipment.DispatchUnEquipItemToSpecifiedHand(_userInterfaceManager.DragInfo.DragEntity.Uid,
InventoryLocation.HandRight);
}
_userInterfaceManager.DragInfo.Reset();
return true;
}
}
else
{
if (handL.Contains(e.X, e.Y) &&
hands.HandSlots.ContainsKey(InventoryLocation.HandLeft) && hands.HandSlots[InventoryLocation.HandRight] != null)
{
hands.HandSlots[InventoryLocation.HandLeft].SendMessage(this, ComponentMessageType.ClickedInHand,
_playerManager.ControlledEntity.Uid);
}
else if (handR.Contains(e.X, e.Y) &&
hands.HandSlots.ContainsKey(InventoryLocation.HandRight) && hands.HandSlots[InventoryLocation.HandRight] != null)
{
hands.HandSlots[InventoryLocation.HandRight].SendMessage(this, ComponentMessageType.ClickedInHand,
_playerManager.ControlledEntity.Uid);
}
}
}
return false;
}
public void MouseMove(MouseButtonEventArgs e)
{
if (ClientArea.Contains(e.X, e.Y))
{
IEntity entity = _playerManager.ControlledEntity;
var hands = (HumanHandsComponent)entity.GetComponent(ComponentFamily.Hands);
switch (e.Button)
{
case Mouse.Button.Left:
if (handL.Contains(e.X, e.Y))
{
if (hands.HandSlots.Keys.Contains(InventoryLocation.HandLeft) && hands.HandSlots[InventoryLocation.HandLeft] != null)
{
IEntity entityL = hands.HandSlots[InventoryLocation.HandLeft];
_userInterfaceManager.DragInfo.StartDrag(entityL);
}
}
if (handR.Contains(e.X, e.Y))
{
if (hands.HandSlots.Keys.Contains(InventoryLocation.HandRight) && hands.HandSlots[InventoryLocation.HandRight] != null)
{
IEntity entityR = hands.HandSlots[InventoryLocation.HandRight];
_userInterfaceManager.DragInfo.StartDrag(entityR);
}
}
break;
}
}
}
public override bool MouseWheelMove(MouseWheelEventArgs e)
{
return false;
}
public override bool KeyDown(KeyEventArgs e)
{
return false;
}
}
}

View File

@@ -1,201 +0,0 @@
using Lidgren.Network;
using SFML.Graphics;
using SFML.System;
using SFML.Window;
using SS14.Client.GameObjects;
using SS14.Client.Graphics;
using SS14.Client.Interfaces.Player;
using SS14.Client.Interfaces.Resource;
using SS14.Client.Interfaces.UserInterface;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.Maths;
using System;
namespace SS14.Client.UserInterface.Components
{
public class HealthPanel : GuiComponent
{
private readonly Color ColCritical = new Color(83, 19, 2);
private readonly Color ColHealthy = new Color(11, 83, 2);
private readonly Sprite _backgroundSprite;
private readonly IPlayerManager _playerManager = IoCManager.Resolve<IPlayerManager>();
private readonly IResourceManager _resMgr = IoCManager.Resolve<IResourceManager>();
private readonly Sprite healthMeterBg;
private readonly Sprite healthMeterGrid;
private readonly Sprite healthMeterOverlay;
private readonly Label healthPc;
private readonly Sprite panelBG;
private IUserInterfaceManager _userInterfaceManager = IoCManager.Resolve<IUserInterfaceManager>();
private int blipSpeed = 60;
private double blipTime;
private int blipWidth = 20;
private IntRect healthMeterInner;
private float healthPct;
private Color interpCol = Color.Transparent;
public HealthPanel()
{
ComponentClass = GuiComponentType.Undefined;
healthMeterBg = _resMgr.GetSprite("healthMeterBg");
healthMeterOverlay = _resMgr.GetSprite("healthMeterOverlay");
healthMeterGrid = _resMgr.GetSprite("healthMeterGrid");
panelBG = _resMgr.GetSprite("healthBg");
_backgroundSprite = _resMgr.GetSprite("blip");
healthPc = new Label("100", "CALIBRI", _resMgr);
healthPc.Text.ShadowOffset = new Vector2f(1, 1);
healthPc.Text.Shadowed = true;
healthPc.Text.Color = new SFML.Graphics.Color(255, 250, 240);
}
public override void ComponentUpdate(params object[] args)
{
}
public override void Update(float frameTime)
{
const int x_inner = 4;
const int y_inner = 25;
const int dec_inner = 7;
panelBG.Position = new Vector2f(Position.X, Position.Y);
healthMeterBg.Position = new Vector2f(Position.X + x_inner, Position.Y + y_inner);
healthMeterOverlay.Position = new Vector2f(Position.X + x_inner, Position.Y + y_inner);
healthMeterGrid.Position = new Vector2f(Position.X + x_inner, Position.Y + y_inner);
var panelBounds = panelBG.GetLocalBounds();
ClientArea = new FloatRect(panelBounds.Left, panelBounds.Top, panelBounds.Width, panelBounds.Height).Round();
var healthMeterBounds = healthMeterOverlay.GetLocalBounds();
healthMeterInner = new IntRect(Position.X + x_inner + dec_inner, Position.Y + y_inner + dec_inner,
(int)(healthMeterBounds.Width - (2 * dec_inner)),
(int)(healthMeterBounds.Height - (2 * dec_inner)));
healthPc.Position = new Vector2i(healthMeterInner.Left + 5,
(int)
(healthMeterInner.Top + (healthMeterInner.Height / 2f) -
(healthPc.ClientArea.Height / 2f)) - 2);
healthPc.Update(frameTime);
IEntity entity = _playerManager.ControlledEntity;
if (entity != null && entity.HasComponent(ComponentFamily.Damageable))
{
var comp = (HealthComponent)entity.GetComponent(ComponentFamily.Damageable);
healthPct = comp.GetHealth() / comp.GetMaxHealth();
if (float.IsNaN(healthPct)) healthPct = 1; //This can happen when the components are not ready yet.
interpCol = ColorUtils.InterpolateBetween(ColCritical, ColHealthy, healthPct);
healthPc.Text.Text = Math.Round((healthPct * 100)).ToString() + "%";
}
blipTime += frameTime;
}
public override void Render()
{
panelBG.Draw();
healthMeterBg.Draw();
CluwneLib.drawRectangle(healthMeterInner.Left, healthMeterInner.Top, healthMeterInner.Width, healthMeterInner.Height, interpCol);
healthPc.Render();
healthMeterGrid.Draw();
RenderBlip();
healthMeterOverlay.Draw();
}
private void RenderBlip()
{
int x_off = 38;
int y_off = 17;
int blipMaxArea = 90;
int blipUp = 45;
int blipDown = 57;
if (blipTime * blipSpeed > blipMaxArea)
blipTime = 0;
var bs = (int)Math.Floor(blipTime * blipSpeed);
CluwneLib.BlendingMode = BlendingModes.Modulated;
for (int i = bs; i < (bs + blipWidth); i++)
{
float sweepPct = (float)i / (bs + blipWidth);
float alpha =
Math.Min(Math.Max((1 - (Math.Abs((blipMaxArea / 2f) - i) / (blipMaxArea / 2f))) * (300f * sweepPct), 0f), 255f);
Color temp = ColorUtils.InterpolateBetween(new Color(255, 165, 0, (byte)alpha), new Color(124, 252, 0, (byte)alpha), healthPct);
_backgroundSprite.Color = temp;
float blipHeightUp = Math.Max(((blipUp - Math.Abs(blipUp - i)) / (float)blipUp) - 0.80f, 0f);
float blipHeightDown = Math.Max(((blipDown - Math.Abs(blipDown - i)) / (float)blipDown) - 0.93f, 0f);
if (i <= blipMaxArea)
{
_backgroundSprite.SetTransformToRect(new IntRect(healthMeterInner.Left + x_off + i,
healthMeterInner.Top + y_off -
(int)((blipHeightUp * 65) * ((healthPct > 0f) ? Math.Max(healthPct, 0.30f) : 0)) +
(int)((blipHeightDown * 65) * ((healthPct > 0f) ? Math.Max(healthPct, 0.45f) : 0)),
3, 3));
_backgroundSprite.Draw();
}
}
CluwneLib.BlendingMode = BlendingModes.None;
}
public override void Resize()
{
}
public override void Dispose()
{
base.Dispose();
GC.SuppressFinalize(this);
}
public override void HandleNetworkMessage(NetIncomingMessage message)
{
}
public override bool MouseDown(MouseButtonEventArgs e)
{
if (ClientArea.Contains(e.X, e.Y))
{
return true;
}
return false;
}
public override bool MouseUp(MouseButtonEventArgs e)
{
if (ClientArea.Contains(e.X, e.Y))
{
return true;
}
return false;
}
public override void MouseMove(MouseMoveEventArgs e)
{
}
public override bool MouseWheelMove(MouseWheelEventArgs e)
{
return false;
}
public override bool KeyDown(KeyEventArgs e)
{
return false;
}
}
}

View File

@@ -1,103 +0,0 @@
using SFML.System;
using SS14.Client.Interfaces.GameObjects;
using SS14.Client.Interfaces.Resource;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.Maths;
using System;
using System.Collections.Generic;
namespace SS14.Client.UserInterface.Components
{
internal sealed class SVarEditWindow : Window
{
private readonly IEntity _owner;
private List<MarshalComponentParameter> _sVars;
public SVarEditWindow(Vector2i size, IEntity owner)
: base("Entity SVars : " + owner.Name, size, IoCManager.Resolve<IResourceManager>())
{
_owner = owner;
}
public void GetSVarsCallback(object sender, GetSVarsEventArgs args)
{
_sVars = args.SVars;
int off_y = 5;
components.Clear();
foreach (MarshalComponentParameter svar in _sVars)
{
var newLabel = new Label(svar.Family.ToString() + " : " + svar.Parameter.MemberName + " = ", "CALIBRI",
_resourceManager);
newLabel.Update(0);
newLabel.Position = new Vector2i(5, off_y);
newLabel.DrawBorder = true;
newLabel.DrawBackground = true;
GuiComponent newComp = CreateEditField(svar);
newComp.Update(0);
newComp.Position = new Vector2i(newLabel.ClientArea.Right() + 8, off_y);
off_y += newLabel.ClientArea.Height + 5;
components.Add(newLabel);
components.Add(newComp);
}
}
private GuiComponent CreateEditField(MarshalComponentParameter compPar)
{
if (compPar.Parameter.ParameterType == typeof(float) || compPar.Parameter.ParameterType == typeof(int) ||
compPar.Parameter.ParameterType == typeof(String))
{
var editTxt = new Textbox(100, _resourceManager);
editTxt.ClearOnSubmit = false;
editTxt.UserData = compPar;
editTxt.Text = compPar.Parameter.Parameter.ToString();
editTxt.OnSubmit += editTxt_OnSubmit;
return editTxt;
}
else if (compPar.Parameter.ParameterType == typeof(Boolean))
{
var editBool = new Checkbox(_resourceManager);
editBool.UserData = compPar;
editBool.Value = ((Boolean)compPar.Parameter.Parameter);
editBool.ValueChanged += editBool_ValueChanged;
return editBool;
}
return null;
}
private void editBool_ValueChanged(bool newValue, Checkbox sender)
{
var assigned = (MarshalComponentParameter)sender.UserData;
assigned.Parameter.Parameter = newValue;
_owner.GetComponent<ISVarsComponent>(ComponentFamily.SVars).DoSetSVar(assigned);
}
private void editTxt_OnSubmit(string text, Textbox sender)
{
var assigned = (MarshalComponentParameter)sender.UserData;
if (assigned.Parameter.ParameterType == typeof(string))
{
assigned.Parameter.Parameter = text;
_owner.GetComponent<ISVarsComponent>(ComponentFamily.SVars).DoSetSVar(assigned);
}
else if (assigned.Parameter.ParameterType == typeof(int))
{
assigned.Parameter.Parameter = int.Parse(text);
_owner.GetComponent<ISVarsComponent>(ComponentFamily.SVars).DoSetSVar(assigned);
}
else if (assigned.Parameter.ParameterType == typeof(float))
{
assigned.Parameter.Parameter = float.Parse(text);
_owner.GetComponent<ISVarsComponent>(ComponentFamily.SVars).DoSetSVar(assigned);
}
}
}
}

View File

@@ -1,187 +0,0 @@
using SFML.Graphics;
using SFML.System;
using SFML.Window;
using SS14.Client.GameObjects;
using SS14.Client.Graphics;
using SS14.Client.Graphics.Sprite;
using SS14.Client.Interfaces.Player;
using SS14.Client.Interfaces.Resource;
using SS14.Client.Interfaces.UserInterface;
using SS14.Client.Helpers;
using SS14.Client.UserInterface.Components;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using System;
namespace SS14.Client.UserInterface.Inventory
{
internal class EquipmentSlotUi : GuiComponent
{
#region Delegates
public delegate void InventorySlotUiDropHandler(EquipmentSlotUi sender, IEntity dropped);
#endregion Delegates
private readonly IPlayerManager _playerManager;
private readonly IResourceManager _resourceManager;
private readonly TextSprite _textSprite;
private readonly IUserInterfaceManager _userInterfaceManager;
private Sprite _buttonSprite;
private Color _color;
private Sprite _currentEntSprite;
public EquipmentSlotUi(EquipmentSlot slot, IPlayerManager playerManager, IResourceManager resourceManager,
IUserInterfaceManager userInterfaceManager)
{
_playerManager = playerManager;
_resourceManager = resourceManager;
_userInterfaceManager = userInterfaceManager;
_color = Color.White;
AssignedSlot = slot;
_buttonSprite = _resourceManager.GetSprite("slot");
_textSprite = new TextSprite(slot + "UIElementSlot", slot.ToString(),
_resourceManager.GetFont("CALIBRI"))
{
ShadowColor = Color.Black,
ShadowOffset = new Vector2f(1, 1),
Shadowed = true,
Color = Color.White
};
Update(0);
}
public EquipmentSlot AssignedSlot { get; private set; }
public IEntity CurrentEntity { get; private set; }
public event InventorySlotUiDropHandler Dropped;
public override sealed void Update(float frameTime)
{
_buttonSprite.Position = new Vector2f(Position.X, Position.Y);
var bounds = _buttonSprite.GetLocalBounds();
ClientArea = new IntRect(Position,
new Vector2i((int)bounds.Width, (int)bounds.Height));
_textSprite.Position = Position;
if (_playerManager.ControlledEntity == null)
return;
IEntity entity = _playerManager.ControlledEntity;
var equipment = (EquipmentComponent)entity.GetComponent(ComponentFamily.Equipment);
if (equipment.EquippedEntities.ContainsKey(AssignedSlot))
{
if ((CurrentEntity == null || CurrentEntity.Uid != equipment.EquippedEntities[AssignedSlot].Uid))
{
CurrentEntity = equipment.EquippedEntities[AssignedSlot];
_currentEntSprite = Utilities.GetIconSprite(CurrentEntity);
}
}
else
{
CurrentEntity = null;
_currentEntSprite = null;
}
}
public override void Render()
{
_buttonSprite.Color = _color;
_buttonSprite.Position = new Vector2f(Position.X, Position.Y);
_buttonSprite.Draw();
_buttonSprite.Color = Color.White;
if (_currentEntSprite != null && CurrentEntity != null)
{
var btnBounds = _buttonSprite.GetLocalBounds();
var entBounds = _currentEntSprite.GetLocalBounds();
_currentEntSprite.SetTransformToRect(
new IntRect((int)(Position.X + btnBounds.Width / 2f - entBounds.Width / 2f),
(int)(Position.Y + btnBounds.Height / 2f - entBounds.Height / 2f),
(int)entBounds.Width, (int)entBounds.Height));
_currentEntSprite.Draw();
}
_textSprite.Draw();
}
public override void Dispose()
{
_buttonSprite = null;
Dropped = null;
base.Dispose();
GC.SuppressFinalize(this);
}
public override bool MouseDown(MouseButtonEventArgs e)
{
if (ClientArea.Contains(e.X, e.Y))
{
if (_playerManager.ControlledEntity == null)
return false;
IEntity entity = _playerManager.ControlledEntity;
var equipment = (EquipmentComponent)entity.GetComponent(ComponentFamily.Equipment);
if (equipment.EquippedEntities.ContainsKey(AssignedSlot))
_userInterfaceManager.DragInfo.StartDrag(equipment.EquippedEntities[AssignedSlot]);
return true;
}
return false;
}
public override bool MouseUp(MouseButtonEventArgs e)
{
if (ClientArea.Contains(e.X, e.Y))
{
if (_playerManager.ControlledEntity == null)
return false;
IEntity entity = _playerManager.ControlledEntity;
var equipment = (EquipmentComponent)entity.GetComponent(ComponentFamily.Equipment);
var hands = (HumanHandsComponent)entity.GetComponent(ComponentFamily.Hands);
if (CurrentEntity != null && CurrentEntity == _userInterfaceManager.DragInfo.DragEntity &&
hands.IsHandEmpty(hands.CurrentHand)) //Dropped from us to us. (Try to) unequip it to active hand.
{
_userInterfaceManager.DragInfo.Reset();
equipment.DispatchUnEquipToHand(CurrentEntity.Uid);
return true;
}
if (CurrentEntity == null && _userInterfaceManager.DragInfo.IsEntity &&
_userInterfaceManager.DragInfo.IsActive)
{
Dropped?.Invoke(this, _userInterfaceManager.DragInfo.DragEntity);
return true;
}
}
return false;
}
public override void MouseMove(MouseMoveEventArgs e)
{
_color = ClientArea.Contains(e.X, e.Y)
? new SFML.Graphics.Color(176, 196, 222)
: Color.White;
}
private bool IsEmpty()
{
if (_playerManager.ControlledEntity == null)
return false;
IEntity entity = _playerManager.ControlledEntity;
var equipment = (EquipmentComponent)entity.GetComponent(ComponentFamily.Equipment);
return equipment.IsEmpty(AssignedSlot);
}
}
}

View File

@@ -1,608 +0,0 @@
using Lidgren.Network;
using SFML.Graphics;
using SFML.System;
using SFML.Window;
using SS14.Client.GameObjects;
using SS14.Client.Graphics;
using SS14.Client.Graphics.Sprite;
using SS14.Client.Interfaces.Network;
using SS14.Client.Interfaces.Player;
using SS14.Client.Interfaces.Resource;
using SS14.Client.Interfaces.UserInterface;
using SS14.Client.UserInterface.Components;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using SS14.Shared.Interfaces.Network;
namespace SS14.Client.UserInterface.Inventory
{
public class HumanComboGui : GuiComponent
{
#region Inventory UI
private readonly EquipmentSlotUi _slotBack;
private readonly EquipmentSlotUi _slotBelt;
private readonly EquipmentSlotUi _slotEars;
private readonly EquipmentSlotUi _slotEyes;
private readonly EquipmentSlotUi _slotFeet;
private readonly EquipmentSlotUi _slotHands;
private readonly EquipmentSlotUi _slotHead;
private readonly EquipmentSlotUi _slotInner;
private readonly EquipmentSlotUi _slotMask;
private readonly EquipmentSlotUi _slotOuter;
private Dictionary<EquipmentSlot, EquipmentSlotUi> _equipmentSlots =
new Dictionary<EquipmentSlot, EquipmentSlotUi>();
private InventoryViewer _inventory;
#endregion
#region Status UI
private readonly ArmorInfoLabel _ResBlunt;
private readonly ArmorInfoLabel _ResBurn;
private readonly ArmorInfoLabel _ResFreeze;
private readonly ArmorInfoLabel _ResPierce;
private readonly ArmorInfoLabel _ResShock;
private readonly ArmorInfoLabel _ResSlash;
private readonly ArmorInfoLabel _ResTox;
#endregion
private readonly Sprite _comboBg;
private readonly ImageButton _comboClose;
private readonly Sprite _equipBg;
private readonly Color _inactiveColor = new Color(90, 90, 90);
private readonly IClientNetManager _networkManager;
private readonly IPlayerManager _playerManager;
private readonly IResourceManager _resourceManager;
private readonly ImageButton _tabEquip;
private readonly ImageButton _tabHealth;
private readonly TextSprite _txtDbg;
private readonly IUserInterfaceManager _userInterfaceManager;
private byte _currentTab = 1; //1 = Inventory, 2 = Health, 3 = Crafting
private bool _showTabbedWindow;
public HumanComboGui(IPlayerManager playerManager, IClientNetManager networkManager,
IResourceManager resourceManager, IUserInterfaceManager userInterfaceManager)
{
_networkManager = networkManager;
_playerManager = playerManager;
_resourceManager = resourceManager;
_userInterfaceManager = userInterfaceManager;
ComponentClass = GuiComponentType.ComboGui;
#region Status UI
_ResBlunt = new ArmorInfoLabel(DamageType.Bludgeoning, resourceManager);
_ResBurn = new ArmorInfoLabel(DamageType.Burn, resourceManager);
_ResFreeze = new ArmorInfoLabel(DamageType.Freeze, resourceManager);
_ResPierce = new ArmorInfoLabel(DamageType.Piercing, resourceManager);
_ResShock = new ArmorInfoLabel(DamageType.Shock, resourceManager);
_ResSlash = new ArmorInfoLabel(DamageType.Slashing, resourceManager);
_ResTox = new ArmorInfoLabel(DamageType.Toxin, resourceManager);
#endregion
_equipBg = _resourceManager.GetSprite("outline");
_comboBg = _resourceManager.GetSprite("combo_bg");
_comboClose = new ImageButton
{
ImageNormal = "button_closecombo",
};
_tabEquip = new ImageButton
{
ImageNormal = "tab_equip",
};
_tabEquip.Clicked += TabClicked;
_tabHealth = new ImageButton
{
ImageNormal = "tab_health",
};
_tabHealth.Clicked += TabClicked;
_comboClose.Clicked += ComboCloseClicked;
//Left Side - head, eyes, outer, hands, feet
_slotHead = new EquipmentSlotUi(EquipmentSlot.Head, _playerManager, _resourceManager, _userInterfaceManager);
_slotHead.Dropped += SlotDropped;
_slotEyes = new EquipmentSlotUi(EquipmentSlot.Eyes, _playerManager, _resourceManager, _userInterfaceManager);
_slotEyes.Dropped += SlotDropped;
_slotOuter = new EquipmentSlotUi(EquipmentSlot.Outer, _playerManager, _resourceManager,
_userInterfaceManager);
_slotOuter.Dropped += SlotDropped;
_slotHands = new EquipmentSlotUi(EquipmentSlot.Hands, _playerManager, _resourceManager,
_userInterfaceManager);
_slotHands.Dropped += SlotDropped;
_slotFeet = new EquipmentSlotUi(EquipmentSlot.Feet, _playerManager, _resourceManager, _userInterfaceManager);
_slotFeet.Dropped += SlotDropped;
//Right Side - mask, ears, inner, belt, back
_slotMask = new EquipmentSlotUi(EquipmentSlot.Mask, _playerManager, _resourceManager, _userInterfaceManager);
_slotMask.Dropped += SlotDropped;
_slotEars = new EquipmentSlotUi(EquipmentSlot.Ears, _playerManager, _resourceManager, _userInterfaceManager);
_slotEars.Dropped += SlotDropped;
_slotInner = new EquipmentSlotUi(EquipmentSlot.Inner, _playerManager, _resourceManager,
_userInterfaceManager);
_slotInner.Dropped += SlotDropped;
_slotBelt = new EquipmentSlotUi(EquipmentSlot.Belt, _playerManager, _resourceManager, _userInterfaceManager);
_slotBelt.Dropped += SlotDropped;
_slotBack = new EquipmentSlotUi(EquipmentSlot.Back, _playerManager, _resourceManager, _userInterfaceManager);
_slotBack.Dropped += SlotDropped;
_txtDbg = new TextSprite("comboDlgDbg", "Combo Debug", _resourceManager.GetFont("CALIBRI"));
}
private void SlotDropped(EquipmentSlotUi sender, IEntity dropped)
{
_userInterfaceManager.DragInfo.Reset();
if (_playerManager.ControlledEntity == null)
return;
IEntity entity = _playerManager.ControlledEntity;
var equipment = (EquipmentComponent) entity.GetComponent(ComponentFamily.Equipment);
equipment.DispatchEquip(dropped.Uid); //Serverside equip component will equip and remove from hands.
}
public override void ComponentUpdate(params object[] args)
{
switch ((ComboGuiMessage) args[0])
{
case ComboGuiMessage.ToggleShowPage:
var page = (int) args[1];
if (page == _currentTab) _showTabbedWindow = !_showTabbedWindow;
else
{
_showTabbedWindow = true;
ActivateTab(page);
}
break;
}
}
public void ActivateTab(int tabNum)
{
switch (tabNum)
{
case 1: //Equip
_currentTab = 1;
break;
case 2: //Status
if (_playerManager.ControlledEntity != null) //TEMPORARY SOLUTION.
{
IEntity resEntity = _playerManager.ControlledEntity;
var entStats = (EntityStatsComp) resEntity.GetComponent(ComponentFamily.EntityStats);
entStats.PullFullUpdate();
}
_currentTab = 2;
break;
case 3: //Craft
_currentTab = 3;
break;
}
}
private void TabClicked(ImageButton sender)
{
if (sender == _tabEquip) ActivateTab(1);
if (sender == _tabHealth) ActivateTab(2);
}
private void ComboOpenClicked(ImageButton sender)
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
{
_showTabbedWindow = !_showTabbedWindow;
}
private void ComboCloseClicked(ImageButton sender)
{
_showTabbedWindow = false;
}
public override bool KeyDown(KeyEventArgs e)
{
if (e.Code == Keyboard.Key.I)
{
_showTabbedWindow = !_showTabbedWindow;
return true;
}
return false;
}
public override void Render()
{
if (_showTabbedWindow)
{
_comboBg.Draw();
_comboClose.Render();
_tabHealth.Render();
_tabEquip.Render();
_txtDbg.Position = new Vector2i(Position.X + 20, Position.Y + 15);
_txtDbg.Color = new Color(255, 222, 173);
if (_currentTab == 1) _txtDbg.Text = "Equipment";
if (_currentTab == 2) _txtDbg.Text = "Status";
_txtDbg.Draw();
switch (_currentTab)
{
case (1): //Equip tab
{
#region Equip
_equipBg.Draw();
//Left Side - head, eyes, outer, hands, feet
_slotHead.Render();
_slotEyes.Render();
_slotOuter.Render();
_slotHands.Render();
_slotFeet.Render();
//Right Side - mask, ears, inner, belt, back
_slotMask.Render();
_slotEars.Render();
_slotInner.Render();
_slotBelt.Render();
_slotBack.Render();
if (_inventory != null) _inventory.Render();
break;
#endregion
}
case (2): //Health tab
{
#region Status
_ResBlunt.Render();
_ResPierce.Render();
_ResSlash.Render();
_ResBurn.Render();
_ResFreeze.Render();
_ResShock.Render();
_ResTox.Render();
break;
#endregion
}
}
}
}
public override void Update(float frameTime)
{
if (_inventory == null && _playerManager != null)
//Gotta do this here because the vars are null in the constructor.
if (_playerManager.ControlledEntity != null)
if (_playerManager.ControlledEntity.HasComponent(ComponentFamily.Inventory))
{
var invComp =
(InventoryComponent) _playerManager.ControlledEntity.GetComponent(ComponentFamily.Inventory);
_inventory = new InventoryViewer(invComp, _userInterfaceManager, _resourceManager);
}
_comboBg.Position = new Vector2f (Position.X, Position.Y);
var bounds = _comboBg.GetLocalBounds();
var equipBgPos = Position;
_equipBg.Position = new Vector2f (Position.X,Position.Y);
equipBgPos += new Vector2i((int)(bounds.Width / 2f - _equipBg.GetLocalBounds().Width / 2f), 40);
_equipBg.Position = new Vector2f(equipBgPos.X,equipBgPos.Y);
var comboClosePos = Position;
comboClosePos += new Vector2i(264, 11); //Magic photoshop ruler numbers.
_comboClose.Position = comboClosePos;
_comboClose.Update(frameTime);
var tabEquipPos = Position;
tabEquipPos += new Vector2i(-26, 76); //Magic photoshop ruler numbers.
_tabEquip.Position = tabEquipPos;
_tabEquip.Color = _currentTab == 1 ? Color.White :_inactiveColor;
_tabEquip.Update(frameTime);
var tabHealthPos = tabEquipPos;
tabHealthPos += new Vector2i(0, 3 + _tabEquip.ClientArea.Height);
_tabHealth.Position = tabHealthPos;
_tabHealth.Color = _currentTab == 2 ? Color.White : _inactiveColor;
_tabHealth.Update(frameTime);
ClientArea = new IntRect(Position.X, Position.Y, (int)bounds.Width, (int)bounds.Height);
switch (_currentTab)
{
case (1): //Equip tab
{
#region Equip
//Only set position for topmost 2 slots directly. Rest uses these to position themselves.
var slotLeftStart = Position;
slotLeftStart += new Vector2i(28, 40);
_slotHead.Position = slotLeftStart;
_slotHead.Update(frameTime);
var slotRightStart = Position;
slotRightStart += new Vector2i((int) (bounds.Width - _slotMask.ClientArea.Width - 28), 40);
_slotMask.Position = slotRightStart;
_slotMask.Update(frameTime);
int vertSpacing = 6 + _slotHead.ClientArea.Height;
//Left Side - head, eyes, outer, hands, feet
slotLeftStart.Y += vertSpacing;
_slotEyes.Position = slotLeftStart;
_slotEyes.Update(frameTime);
slotLeftStart.Y += vertSpacing;
_slotOuter.Position = slotLeftStart;
_slotOuter.Update(frameTime);
slotLeftStart.Y += vertSpacing;
_slotHands.Position = slotLeftStart;
_slotHands.Update(frameTime);
slotLeftStart.Y += vertSpacing;
_slotFeet.Position = slotLeftStart;
_slotFeet.Update(frameTime);
//Right Side - mask, ears, inner, belt, back
slotRightStart.Y += vertSpacing;
_slotEars.Position = slotRightStart;
_slotEars.Update(frameTime);
slotRightStart.Y += vertSpacing;
_slotInner.Position = slotRightStart;
_slotInner.Update(frameTime);
slotRightStart.Y += vertSpacing;
_slotBelt.Position = slotRightStart;
_slotBelt.Update(frameTime);
slotRightStart.Y += vertSpacing;
_slotBack.Position = slotRightStart;
_slotBack.Update(frameTime);
if (_inventory != null)
{
_inventory.Position = new Vector2i(Position.X + 12, Position.Y + 315);
_inventory.Update(frameTime);
}
break;
#endregion
}
case (2): //Health tab
{
#region Status
var resLinePos = new Vector2i(Position.X + 35, Position.Y + 70);
const int spacing = 8;
_ResBlunt.Position = resLinePos;
resLinePos.Y += _ResBlunt.ClientArea.Height + spacing;
_ResBlunt.Update(frameTime);
_ResPierce.Position = resLinePos;
resLinePos.Y += _ResPierce.ClientArea.Height + spacing;
_ResPierce.Update(frameTime);
_ResSlash.Position = resLinePos;
resLinePos.Y += _ResSlash.ClientArea.Height + spacing;
_ResSlash.Update(frameTime);
_ResBurn.Position = resLinePos;
resLinePos.Y += _ResBurn.ClientArea.Height + spacing;
_ResBurn.Update(frameTime);
_ResFreeze.Position = resLinePos;
resLinePos.Y += _ResFreeze.ClientArea.Height + spacing;
_ResFreeze.Update(frameTime);
_ResShock.Position = resLinePos;
resLinePos.Y += _ResShock.ClientArea.Height + spacing;
_ResShock.Update(frameTime);
_ResTox.Position = resLinePos;
_ResTox.Update(frameTime);
break;
#endregion
}
}
//Needs to update even when its not on the crafting tab so it continues to count.
}
public override void Dispose()
{
//TODO dispose me
base.Dispose();
}
public override bool MouseDown(MouseButtonEventArgs e)
{
if (_showTabbedWindow)
{
if (_comboClose.MouseDown(e)) return true;
if (_tabEquip.MouseDown(e)) return true;
if (_tabHealth.MouseDown(e)) return true;
switch (_currentTab)
{
case (1): //Equip tab
{
#region Equip
//Left Side - head, eyes, outer, hands, feet
if (_slotHead.MouseDown(e)) return true;
if (_slotEyes.MouseDown(e)) return true;
if (_slotOuter.MouseDown(e)) return true;
if (_slotHands.MouseDown(e)) return true;
if (_slotFeet.MouseDown(e)) return true;
//Right Side - mask, ears, inner, belt, back
if (_slotMask.MouseDown(e)) return true;
if (_slotEars.MouseDown(e)) return true;
if (_slotInner.MouseDown(e)) return true;
if (_slotBelt.MouseDown(e)) return true;
if (_slotBack.MouseDown(e)) return true;
if (_inventory != null) if (_inventory.MouseDown(e)) return true;
break;
#endregion
}
case (2): //Health tab
{
#region Status
break;
#endregion
}
}
}
return false;
}
private void SendSwitchHandTo(InventoryLocation hand)
{
IEntity playerEntity = _playerManager.ControlledEntity;
var equipComponent = (HumanHandsComponent) playerEntity.GetComponent(ComponentFamily.Hands);
equipComponent.SendSwitchHands(hand);
}
public override bool MouseUp(MouseButtonEventArgs e)
{
var mouseAABB = new Vector2i(e.X, e.Y);
switch (_currentTab)
{
case (1): //Equip tab
{
#region Equip
//Left Side - head, eyes, outer, hands, feet
if (_slotHead.MouseUp(e)) return true;
if (_slotEyes.MouseUp(e)) return true;
if (_slotOuter.MouseUp(e)) return true;
if (_slotHands.MouseUp(e)) return true;
if (_slotFeet.MouseUp(e)) return true;
//Right Side - mask, ears, inner, belt, back
if (_slotMask.MouseUp(e)) return true;
if (_slotEars.MouseUp(e)) return true;
if (_slotInner.MouseUp(e)) return true;
if (_slotBelt.MouseUp(e)) return true;
if (_slotBack.MouseUp(e)) return true;
if (_inventory != null) if (_inventory.MouseUp(e)) return true;
if (_comboBg.GetLocalBounds().Contains(mouseAABB.X, mouseAABB.Y) && _userInterfaceManager.DragInfo.IsEntity &&
_userInterfaceManager.DragInfo.IsActive)
{
//Should be refined to only trigger in the equip area. Equip it if they drop it anywhere on the thing. This might make the slots obsolete if we keep it.
if (_playerManager.ControlledEntity == null)
return false;
IEntity entity = _playerManager.ControlledEntity;
var equipment = (EquipmentComponent) entity.GetComponent(ComponentFamily.Equipment);
equipment.DispatchEquip(_userInterfaceManager.DragInfo.DragEntity.Uid);
_userInterfaceManager.DragInfo.Reset();
return true;
}
break;
#endregion
}
case (2): //Health tab
{
#region Status
break;
#endregion
}
}
return false;
}
public override void MouseMove(MouseMoveEventArgs e)
{
switch (_currentTab)
{
case (1): //Equip tab
{
#region Equip
//Left Side - head, eyes, outer, hands, feet
_slotHead.MouseMove(e);
_slotEyes.MouseMove(e);
_slotOuter.MouseMove(e);
_slotHands.MouseMove(e);
_slotFeet.MouseMove(e);
//Right Side - mask, ears, inner, belt, back
_slotMask.MouseMove(e);
_slotEars.MouseMove(e);
_slotInner.MouseMove(e);
_slotBelt.MouseMove(e);
_slotBack.MouseMove(e);
if (_inventory != null) _inventory.MouseMove(e);
break;
#endregion
}
case (2): //Health tab
{
#region Status
break;
#endregion
}
}
}
public override bool MouseWheelMove(MouseWheelEventArgs e)
{
if (_currentTab == 1 || _currentTab == 3)
{
if (_inventory.MouseWheelMove(e)) return true;
}
return false;
}
}
}

View File

@@ -1,97 +0,0 @@
using SFML.Graphics;
using SFML.System;
using SFML.Window;
using SS14.Client.Graphics;
using SS14.Client.Interfaces.Resource;
using SS14.Client.Helpers;
using SS14.Client.UserInterface.Components;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using System;
namespace SS14.Client.UserInterface.Inventory
{
internal class InventorySlotUi : GuiComponent
{
#region Delegates
public delegate void InventoryClickHandler(InventorySlotUi sender);
#endregion Delegates
private readonly Sprite _entitySprite;
private readonly IResourceManager _resourceManager;
private readonly Sprite _slotSprite;
public IEntity ContainingEntity;
private Color _currentColor;
public InventorySlotUi(IEntity containingEnt, IResourceManager resourceManager)
{
_currentColor = Color.White;
_resourceManager = resourceManager;
ContainingEntity = containingEnt;
if (ContainingEntity != null) _entitySprite = Utilities.GetIconSprite(ContainingEntity);
_slotSprite = _resourceManager.GetSprite("slot");
}
public event InventoryClickHandler Clicked;
public override void Update(float frameTime)
{
var bounds = _slotSprite.GetLocalBounds();
ClientArea = new IntRect(Position, new Vector2i((int)bounds.Width, (int)bounds.Height));
}
public override void Render()
{
_slotSprite.Color = _currentColor;
_slotSprite.Position = new Vector2f(Position.X, Position.Y);
_slotSprite.Draw();
if (_entitySprite != null)
{
var slotBounds = _slotSprite.GetLocalBounds();
var entBounds = _entitySprite.GetLocalBounds();
_entitySprite.SetTransformToRect(
new IntRect((int)(Position.X + slotBounds.Width / 2f - entBounds.Width / 2f),
(int)(Position.Y + slotBounds.Height / 2f - entBounds.Height / 2f),
(int)entBounds.Width, (int)entBounds.Height));
_entitySprite.Draw();
}
_slotSprite.Color = Color.White;
}
public override void Dispose()
{
base.Dispose();
GC.SuppressFinalize(this);
}
public override bool MouseDown(MouseButtonEventArgs e)
{
if (ClientArea.Contains(e.X, e.Y))
{
if (Clicked != null) Clicked(this);
return true;
}
return false;
}
public override bool MouseUp(MouseButtonEventArgs e)
{
if (ClientArea.Contains(e.X, e.Y))
{
return true;
}
return false;
}
public override void MouseMove(MouseMoveEventArgs e)
{
_currentColor = ClientArea.Contains(e.X, e.Y)
? new SFML.Graphics.Color(176, 196, 222)
: Color.White;
}
}
}

View File

@@ -1,154 +0,0 @@
using SFML.System;
using SFML.Window;
using SS14.Client.GameObjects;
using SS14.Client.Interfaces.Resource;
using SS14.Client.Interfaces.UserInterface;
using SS14.Client.UserInterface.Components;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using System;
using System.Collections.Generic;
namespace SS14.Client.UserInterface.Inventory
{
internal class InventoryViewer : GuiComponent
{
private readonly InventoryComponent _inventoryComponent;
private readonly ScrollableContainer _inventoryContainer;
private readonly IResourceManager _resourceManager;
private readonly IUserInterfaceManager _userInterfaceManager;
public InventoryViewer(InventoryComponent assignedCompo, IUserInterfaceManager userInterfaceManager,
IResourceManager resourceManager)
{
_userInterfaceManager = userInterfaceManager;
_resourceManager = resourceManager;
_inventoryContainer = new ScrollableContainer(assignedCompo.Owner.Uid + "InvViewer", new Vector2i(270, 125),
_resourceManager);
_inventoryComponent = assignedCompo;
_inventoryComponent.Changed += ComponentChanged;
RebuildInventoryView(_inventoryComponent.MaxSlots, _inventoryComponent.ContainedEntities);
}
private void ComponentChanged(InventoryComponent sender, int maxSlots, List<IEntity> entities)
{
RebuildInventoryView(maxSlots, entities);
}
public void RebuildInventoryView(int maxSlots, List<IEntity> entities)
{
int currX = 0;
int currY = 0;
const int spacing = 50;
const int xOffset = 12;
const int yOffset = 5;
_inventoryContainer.components.Clear();
foreach (IEntity entity in entities)
{
var slot = new InventorySlotUi(entity, _resourceManager)
{
Position = new Vector2i(currX * spacing + xOffset, currY * spacing + yOffset)
};
slot.Clicked += SlotClicked;
_inventoryContainer.components.Add(slot);
currX++;
if (currX < 5) continue;
currX = 0;
currY++;
}
for (int i = 0; i < (maxSlots - entities.Count); i++)
{
var slot = new InventorySlotUi(null, _resourceManager)
{
Position = new Vector2i(currX * spacing + xOffset, currY * spacing + yOffset)
};
slot.Clicked += SlotClicked;
_inventoryContainer.components.Add(slot);
currX++;
if (currX < 5) continue;
currX = 0;
currY++;
}
_inventoryContainer.ResetScrollbars();
}
private void SlotClicked(InventorySlotUi sender)
{
if (sender.ContainingEntity != null)
_userInterfaceManager.DragInfo.StartDrag(sender.ContainingEntity);
}
public override void Update(float frameTime)
{
_inventoryContainer.Position = Position;
_inventoryContainer.Update(frameTime);
}
public override void Render()
{
_inventoryContainer.Render();
}
public override void Dispose()
{
_inventoryComponent.Changed -= ComponentChanged;
_inventoryContainer.Dispose();
base.Dispose();
GC.SuppressFinalize(this);
}
public override bool MouseDown(MouseButtonEventArgs e)
{
if (_inventoryContainer.MouseDown(e))
return true;
return false;
}
public override bool MouseUp(MouseButtonEventArgs e)
{
//If dropped on container add to inventory.
if (_inventoryContainer.MouseUp(e)) return true;
if (_inventoryContainer.ClientArea.Contains(e.X, e.Y) &&
_userInterfaceManager.DragInfo.IsEntity && _userInterfaceManager.DragInfo.IsActive)
{
if (!_inventoryComponent.ContainsEntity(_userInterfaceManager.DragInfo.DragEntity))
{
_inventoryComponent.SendInventoryAdd(_userInterfaceManager.DragInfo.DragEntity);
_userInterfaceManager.DragInfo.Reset();
}
else
{
_userInterfaceManager.DragInfo.Reset();
}
return true;
}
return false;
}
public override void MouseMove(MouseMoveEventArgs e)
{
_inventoryContainer.MouseMove(e);
}
public override bool MouseWheelMove(MouseWheelEventArgs e)
{
return _inventoryContainer.MouseWheelMove(e);
}
}
}

View File

@@ -207,7 +207,7 @@ namespace SS14.Server.Chat
return;
List<INetChannel> recipients = IoCManager.Resolve<IPlayerManager>()
.GetPlayersInRange(entityManager.GetEntity((int) entityId)
.GetComponent<ITransformComponent>(ComponentFamily.Transform).Position, withinRange)
.GetComponent<ITransformComponent>().Position, withinRange)
.Select(p => p.ConnectedClient).ToList();
IoCManager.Resolve<IServerNetManager>().ServerSendToMany(message, recipients);

View File

@@ -12,11 +12,6 @@ namespace SS14.Server.GameObjects
public override string Name => "BasicActor";
public IPlayerSession playerSession { get; internal set; }
public BasicActorComponent()
{
Family = ComponentFamily.Actor;
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{

View File

@@ -1,6 +1,7 @@
using Lidgren.Network;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.IoC;
namespace SS14.Server.GameObjects
@@ -8,10 +9,7 @@ namespace SS14.Server.GameObjects
public class ClickableComponent : Component
{
public override string Name => "Clickable";
public ClickableComponent()
{
Family = ComponentFamily.Click;
}
public override uint? NetID => NetIDs.CLICKABLE;
/// <summary>
/// NetMessage handler
@@ -19,18 +17,15 @@ namespace SS14.Server.GameObjects
/// <param name="message"></param>
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection client)
{
if (message.ComponentFamily == ComponentFamily.Click)
var type = (ComponentMessageType) message.MessageParameters[0];
var uid = (int) message.MessageParameters[1];
var mouseClickType = MouseClickType.None;
if(type == ComponentMessageType.LeftClick || type == ComponentMessageType.RightClick || type == ComponentMessageType.ClickedInHand)
{
var type = (ComponentMessageType) message.MessageParameters[0];
var uid = (int) message.MessageParameters[1];
var mouseClickType = MouseClickType.None;
if(type == ComponentMessageType.LeftClick || type == ComponentMessageType.RightClick || type == ComponentMessageType.ClickedInHand)
{
Owner.SendMessage(this, type, uid);
mouseClickType = MouseClickType.ConvertComponentMessageTypeToClickType(type);
}
Owner.RaiseEvent(new ClickedOnEntityEventArgs { Clicked = Owner.Uid, Clicker = uid, MouseButton = mouseClickType });
Owner.SendMessage(this, type, uid);
mouseClickType = MouseClickType.ConvertComponentMessageTypeToClickType(type);
}
Owner.RaiseEvent(new ClickedOnEntityEventArgs { Clicked = Owner.Uid, Clicker = uid, MouseButton = mouseClickType });
}
}
}

View File

@@ -1,6 +1,7 @@
using Lidgren.Network;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Collidable;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
@@ -10,34 +11,9 @@ namespace SS14.Server.GameObjects
public class CollidableComponent : Component
{
public override string Name => "Collidable";
public override uint? NetID => NetIDs.COLLIDABLE;
private bool _collisionEnabled = true;
public CollidableComponent()
{
Family = ComponentFamily.Collidable;
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
ComponentReplyMessage reply = base.RecieveMessage(sender, type, list);
if (sender == this)
return ComponentReplyMessage.Empty;
switch (type)
{
case ComponentMessageType.DisableCollision:
_collisionEnabled = false;
break;
case ComponentMessageType.EnableCollision:
_collisionEnabled = true;
break;
}
return reply;
}
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection client)
{
switch ((ComponentMessageType)message.MessageParameters[0])

View File

@@ -1,160 +0,0 @@
using Lidgren.Network;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using YamlDotNet.RepresentationModel;
namespace SS14.Server.GameObjects
{
public class DamageableComponent : Component
{
public override string Name => "Damageable";
private readonly List<DamageHistoryItem> _damageHistory = new List<DamageHistoryItem>();
public float currentHealth = 100;
protected bool isDead;
public float maxHealth = 100;
public DamageableComponent()
{
Family = ComponentFamily.Damageable;
RegisterSVar("MaxHealth", typeof(int));
RegisterSVar("CurrentHealth", typeof(int));
}
// TODO use state system
public override void HandleInstantiationMessage(NetConnection netConnection)
{
SendHealthUpdate(netConnection);
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
ComponentReplyMessage reply = base.RecieveMessage(sender, type, list);
if (sender == this)
return ComponentReplyMessage.Empty;
switch (type)
{
case ComponentMessageType.Damage:
ApplyDamage((IEntity)list[0], (int)list[1], (DamageType)list[2]);
break;
}
return reply;
}
public virtual float GetMaxHealth()
{
return maxHealth;
}
public virtual float GetHealth()
{
return currentHealth;
}
protected virtual void SendHealthUpdate()
{
SendHealthUpdate(null);
}
[Obsolete("This is old and should be removed. Everything that calls this should instead trigger Die() if necessary.")]
protected virtual void SendHealthUpdate(NetConnection client)
{
if (currentHealth <= 0 && !isDead)
{
Die();
}
}
protected virtual void ApplyDamage(IEntity damager, int damageamount, DamageType damType)
{
if (!isDead)
{
int damagetoapply = Math.Max(damageamount - GetArmor(damType), 0); //No negative damage right now
currentHealth -= damagetoapply;
DamagedBy(damager, damageamount, damType);
}
SendHealthUpdate();
}
protected virtual int GetArmor(DamageType damType)
{
var entStats = (EntityStatsComp)Owner.GetComponent(ComponentFamily.EntityStats);
if (entStats != null) return entStats.GetArmorValue(damType);
else return 0;
}
protected virtual void ApplyDamage(int p)
{
ApplyDamage(null, p, DamageType.Untyped);
}
protected virtual void Die()
{
if (!isDead) isDead = true;
else
{
return;
}
//Send a message that whatever last damaged us killed us.
_damageHistory.Last().Damager.SendMessage(this, ComponentMessageType.KilledEntity, this);
Owner.SendMessage(this, ComponentMessageType.Die);
}
protected void DamagedBy(IEntity damager, int amount, DamageType damType)
{
_damageHistory.Add(new DamageHistoryItem(damager, amount, damType));
}
public override void LoadParameters(YamlMappingNode mapping)
{
YamlNode node;
if (mapping.TryGetNode("maxHealth", out node))
{
maxHealth = node.AsInt();
currentHealth = maxHealth;
}
if (mapping.TryGetNode("currentHealth", out node))
{
currentHealth = node.AsInt();
}
}
public override IList<ComponentParameter> GetParameters()
{
IList<ComponentParameter> cparams = base.GetParameters();
cparams.Add(new ComponentParameter("MaxHealth", (int)maxHealth));
cparams.Add(new ComponentParameter("CurrentHealth", (int)currentHealth));
return cparams;
}
}
public struct DamageHistoryItem
{
public int Amount;
public DamageType DamType;
public IEntity Damager;
public DateTime When;
public DamageHistoryItem(IEntity damager, int amount, DamageType damType)
{
Damager = damager;
Amount = amount;
DamType = damType;
When = DateTime.Now;
}
}
}

View File

@@ -1,35 +0,0 @@
using Lidgren.Network;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Damageable.Health;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
namespace SS14.Server.GameObjects
{
public class HealthComponent : DamageableComponent
{
public override string Name => "Health";
// TODO use state system
public override void HandleInstantiationMessage(NetConnection netConnection)
{
SendHealthUpdate(netConnection);
}
protected override void ApplyDamage(IEntity damager, int damageamount, DamageType damType)
{
base.ApplyDamage(damager, damageamount, damType);
SendHealthUpdate();
}
protected override void ApplyDamage(int p)
{
base.ApplyDamage(p);
SendHealthUpdate();
}
public override ComponentState GetComponentState()
{
return new HealthComponentState(isDead, GetHealth(), maxHealth);
}
}
}

View File

@@ -2,6 +2,7 @@
using SS14.Server.Interfaces.GameObjects;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Direction;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
@@ -13,14 +14,9 @@ namespace SS14.Server.GameObjects
public class DirectionComponent : Component, IDirectionComponent
{
public override string Name => "Direction";
public override uint? NetID => NetIDs.DIRECTION;
private Direction _lastDeterminedDirection = Direction.South;
public DirectionComponent()
{
Direction = Direction.South;
Family = ComponentFamily.Direction;
}
#region IDirectionComponent Members
public Direction Direction { get; set; }
@@ -30,12 +26,12 @@ namespace SS14.Server.GameObjects
public override void OnAdd(IEntity owner)
{
base.OnAdd(owner);
owner.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove += HandleOnMove;
owner.GetComponent<TransformComponent>().OnMove += HandleOnMove;
}
public override void OnRemove()
{
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove -= HandleOnMove;
Owner.GetComponent<TransformComponent>().OnMove -= HandleOnMove;
base.OnRemove();
}

View File

@@ -1,111 +0,0 @@
using Lidgren.Network;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.EntityStats;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using YamlDotNet.RepresentationModel;
namespace SS14.Server.GameObjects
{
public class EntityStatsComp : Component
{
public override string Name => "EntityStats";
private readonly Dictionary<DamageType, int> armorStats = new Dictionary<DamageType, int>();
public EntityStatsComp()
{
Family = ComponentFamily.EntityStats;
foreach (object dmgType in Enum.GetValues(typeof(DamageType)))
{
if (!armorStats.Keys.Contains((DamageType)dmgType))
armorStats.Add((DamageType)dmgType, 0);
}
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
switch (type)
{
case ComponentMessageType.GetArmorValues:
var dmgType = (DamageType)list[0];
return new ComponentReplyMessage(ComponentMessageType.ReturnArmorValues, GetArmorValue(dmgType));
default:
return base.RecieveMessage(sender, type, list);
}
}
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection client)
{
var type = (ComponentMessageType)message.MessageParameters[0];
switch (type)
{
case (ComponentMessageType.GetArmorValues): //Add message for sending complete listing.
//Owner.SendComponentNetworkMessage(this, NetDeliveryMethod.ReliableUnordered, client, ComponentMessageType.ReturnArmorValues, (int)((DamageType)message.MessageParameters[1]), GetArmorValue((DamageType)message.MessageParameters[1]));
break;
default:
base.HandleNetworkMessage(message, client);
break;
}
}
public override void LoadParameters(YamlMappingNode mapping)
{
YamlNode node;
if (mapping.TryGetNode("armor", out node))
{
foreach (KeyValuePair<YamlNode, YamlNode> stat in (YamlMappingNode)node)
{
var type = stat.Key.AsEnum<DamageType>();
//Add check for parsing. Handle exceptions if invalid name.
int value = stat.Value.AsInt(); //See comment above.
armorStats[type] = value;
}
}
}
public void SetArmorValue(DamageType damType, int value)
{
if (armorStats.ContainsKey(damType))
armorStats[damType] = value;
else
armorStats.Add(damType, value);
}
public int GetArmorValue(DamageType damType)
{
int armorVal = 0;
var eqComp = (EquipmentComponent)Owner.GetComponent(ComponentFamily.Equipment);
if (eqComp != null)
{
foreach (IEntity ent in eqComp.equippedEntities.Values)
{
var entStatComp = (EntityStatsComp)ent.GetComponent(ComponentFamily.EntityStats);
if (entStatComp != null)
armorVal += entStatComp.GetArmorValue(damType);
}
}
if (armorStats.ContainsKey(damType))
armorVal += armorStats[damType];
return armorVal;
}
public override ComponentState GetComponentState()
{
return new EntityStatsComponentState(armorStats);
}
}
}

View File

@@ -1,340 +0,0 @@
using Lidgren.Network;
using SS14.Server.GameObjects.Events;
using SS14.Server.GameObjects.Item.ItemCapability;
using SS14.Server.Interfaces.GameObjects;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Equipment;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using System.Collections.Generic;
using System.Linq;
namespace SS14.Server.GameObjects
{
public class EquipmentComponent : Component, IEquipmentComponent
{
public override string Name => "Equipment";
protected List<EquipmentSlot> activeSlots = new List<EquipmentSlot>();
public Dictionary<EquipmentSlot, IEntity> equippedEntities = new Dictionary<EquipmentSlot, IEntity>();
public EquipmentComponent()
{
Family = ComponentFamily.Equipment;
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
ComponentReplyMessage reply = base.RecieveMessage(sender, type, list);
if (sender == this)
return ComponentReplyMessage.Empty;
switch (type)
{
case ComponentMessageType.DisassociateEntity:
UnEquipEntity((IEntity)list[0]);
break;
}
return reply;
}
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection client)
{
// TODO change these things to flow to the server via a system instead of via this component
if (message.ComponentFamily == ComponentFamily.Equipment)
{
var type = (ComponentMessageType)message.MessageParameters[0];
switch (type) //Why does this send messages to itself THIS IS DUMB AND WILL BREAK THINGS. BZZZ
{
case ComponentMessageType.EquipItem:
RaiseEquipItem(Owner.EntityManager.GetEntity((int)message.MessageParameters[1]));
break;
case ComponentMessageType.EquipItemInHand:
RaiseEquipItemInHand();
break;
case ComponentMessageType.UnEquipItemToFloor:
RaiseUnEquipItemToFloor(Owner.EntityManager.GetEntity((int)message.MessageParameters[1]));
break;
case ComponentMessageType.UnEquipItemToHand:
RaiseUnEquipItemToHand(Owner.EntityManager.GetEntity((int)message.MessageParameters[1]));
break;
case ComponentMessageType.UnEquipItemToSpecifiedHand:
RaiseUnEquipItemToSpecifiedHand(Owner.EntityManager.GetEntity((int)message.MessageParameters[1]), (InventoryLocation)message.MessageParameters[2]);
break;
}
}
}
public void RaiseEquipItem(IEntity item)
{
Owner.EntityManager.RaiseEvent(this, new InventoryEquipItemEventArgs
{
Actor = Owner,
Item = item
});
}
public void RaiseEquipItemInHand()
{
Owner.EntityManager.RaiseEvent(this, new InventoryEquipItemInHandEventArgs
{
Actor = Owner
});
}
public void RaiseUnEquipItemToFloor(IEntity item)
{
Owner.EntityManager.RaiseEvent(this, new InventoryUnEquipItemToFloorEventArgs
{
Actor = Owner,
Item = item
});
}
public void RaiseUnEquipItemToHand(IEntity item)
{
Owner.EntityManager.RaiseEvent(this, new InventoryUnEquipItemToHandEventArgs
{
Actor = Owner,
Item = item
});
}
public void RaiseUnEquipItemToSpecifiedHand(IEntity item, InventoryLocation hand)
{
Owner.EntityManager.RaiseEvent(this, new InventoryUnEquipItemToSpecifiedHandEventArgs
{
Actor = Owner,
Item = item,
Hand = hand
});
}
// Equips Entity e to Part part
public void EquipEntityToPart(EquipmentSlot part, IEntity e)
{
if (equippedEntities.ContainsValue(e)) //Its already equipped? Unequip first. This shouldnt happen.
UnEquipEntity(e);
if (CanEquip(e)) //If the part is empty, the part exists on this mob, and the entity specified is not null
{
RemoveFromOtherComps(e);
equippedEntities.Add(part, e);
e.SendMessage(this, ComponentMessageType.ItemEquipped, Owner);
//Owner.SendDirectedComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered, null,
// EquipmentComponentNetMessage.ItemEquipped, part, e.Uid);
}
}
// Equips Entity e and automatically finds the appropriate part
public void EquipEntity(IEntity e)
{
if (equippedEntities.ContainsValue(e)) //Its already equipped? Unequip first. This shouldnt happen.
UnEquipEntity(e);
if (CanEquip(e))
{
ComponentReplyMessage reply = e.SendMessage(this, ComponentFamily.Equippable,
ComponentMessageType.GetWearLoc);
if (reply.MessageType == ComponentMessageType.ReturnWearLoc)
{
RemoveFromOtherComps(e);
EquipEntityToPart((EquipmentSlot)reply.ParamsList[0], e);
}
}
}
// Equips whatever we currently have in our active hand
public void EquipEntityInHand()
{
if (!Owner.HasComponent(ComponentFamily.Hands))
{
return; //TODO REAL ERROR MESSAGE OR SOME FUCK SHIT
}
//Get the item in the hand
ComponentReplyMessage reply = Owner.SendMessage(this, ComponentFamily.Hands,
ComponentMessageType.GetActiveHandItem);
if (reply.MessageType == ComponentMessageType.ReturnActiveHandItem && CanEquip((IEntity)reply.ParamsList[0]))
{
RemoveFromOtherComps((IEntity)reply.ParamsList[0]);
//Equip
EquipEntity((IEntity)reply.ParamsList[0]);
}
}
// Unequips the entity from Part part
public void UnEquipEntity(EquipmentSlot part)
{
if (!IsEmpty(part)) //If the part is not empty
{
equippedEntities[part].SendMessage(this, ComponentMessageType.ItemUnEquipped);
//Owner.SendDirectedComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered, null,
// EquipmentComponentNetMessage.ItemUnEquipped, part,
// equippedEntities[part].Uid);
equippedEntities.Remove(part);
}
}
public void UnEquipEntityToHand(IEntity e)
{
UnEquipEntity(e);
//HumanHandsComponent hh = (HumanHandsComponent)Owner.GetComponent(ComponentFamily.Hands);
Owner.SendMessage(this, ComponentMessageType.PickUpItem, e);
}
public void UnEquipEntityToHand(IEntity e, InventoryLocation h)
{
ComponentReplyMessage reply = Owner.SendMessage(this, ComponentFamily.Hands,
ComponentMessageType.IsHandEmpty, h);
if (reply.MessageType == ComponentMessageType.IsHandEmptyReply && (bool)reply.ParamsList[0])
{
UnEquipEntity(e);
Owner.SendMessage(this, ComponentMessageType.PickUpItemToHand, e, h);
}
}
public bool IsEquipped(IEntity e)
{
return equippedEntities.ContainsValue(e);
}
// Unequips entity e
public void UnEquipEntity(IEntity e)
{
EquipmentSlot key;
foreach (var kvp in equippedEntities)
{
if (kvp.Value == e)
{
key = kvp.Key;
UnEquipEntity(key);
break;
}
}
}
private bool IsItem(IEntity e)
{
if (e.HasComponent(ComponentFamily.Item)) //We can only equip items derp
return true;
return false;
}
private bool IsEmpty(EquipmentSlot part)
{
if (equippedEntities.ContainsKey(part))
return false;
return true;
}
private void RemoveFromOtherComps(IEntity entity)
{
IEntity holder = null;
if (entity.HasComponent(ComponentFamily.Item))
holder = ((BasicItemComponent)entity.GetComponent(ComponentFamily.Item)).CurrentHolder;
if (holder == null && entity.HasComponent(ComponentFamily.Equippable))
holder = ((EquippableComponent)entity.GetComponent(ComponentFamily.Equippable)).currentWearer;
if (holder != null) holder.SendMessage(this, ComponentMessageType.DisassociateEntity, entity);
else Owner.SendMessage(this, ComponentMessageType.DisassociateEntity, entity);
}
private bool CanEquip(IEntity e)
{
if (!e.HasComponent(ComponentFamily.Equippable))
return false;
ComponentReplyMessage reply = e.SendMessage(this, ComponentFamily.Equippable,
ComponentMessageType.GetWearLoc);
return reply.MessageType == ComponentMessageType.ReturnWearLoc
&& IsItem(e)
&& IsEmpty((EquipmentSlot)reply.ParamsList[0])
&& activeSlots.Contains((EquipmentSlot)reply.ParamsList[0]);
}
public List<ItemCapability> GetEquipmentCapabilities()
{
var caps = new List<ItemCapability>();
var replies = new List<ComponentReplyMessage>();
foreach (IEntity ent in equippedEntities.Values)
{
ent.SendMessage(this, ComponentMessageType.ItemGetAllCapabilities, replies);
}
foreach (ComponentReplyMessage reply in replies)
{
caps.AddRange((ItemCapability[])reply.ParamsList[0]);
}
return caps;
}
public bool HasInternals()
{
return false;
}
public bool RemoveEntity(IEntity user, IEntity toRemove)
{
if (equippedEntities.Any(x => x.Value == toRemove))
{
EquippableComponent eqCompo = toRemove.GetComponent<EquippableComponent>(ComponentFamily.Equippable);
if (eqCompo != null)
eqCompo.currentWearer = null;
equippedEntities.Remove(equippedEntities.First(x => x.Value == toRemove).Key);
return true;
}
else
{
return false;
}
}
public bool CanAddEntity(IEntity user, IEntity toAdd)
{
if (equippedEntities.Any(x => x.Value == toAdd) || !toAdd.HasComponent(ComponentFamily.Equippable))
{
return false;
}
var eqCompo = toAdd.GetComponent<EquippableComponent>(ComponentFamily.Equippable);
if (!activeSlots.Contains(eqCompo.wearloc) || equippedEntities.ContainsKey(eqCompo.wearloc))
{
return false;
}
return true;
}
public bool AddEntity(IEntity user, IEntity toAdd)
{
if (equippedEntities.Any(x => x.Value == toAdd))
return false;
else
{
EquippableComponent eqCompo = toAdd.GetComponent<EquippableComponent>(ComponentFamily.Equippable);
if (eqCompo != null)
{
if (activeSlots.Contains(eqCompo.wearloc) && !equippedEntities.ContainsKey(eqCompo.wearloc))
{
equippedEntities.Add(eqCompo.wearloc, toAdd);
eqCompo.currentWearer = Owner;
return true;
}
else
return false;
}
else
return false;
}
}
public override ComponentState GetComponentState()
{
Dictionary<EquipmentSlot, int> equipped = equippedEntities.Select(x => new KeyValuePair<EquipmentSlot, int>(x.Key, x.Value.Uid)).ToDictionary(key => key.Key, va => va.Value);
return new EquipmentComponentState(equipped, activeSlots);
}
}
}

View File

@@ -1,25 +0,0 @@
using SS14.Shared;
using SS14.Shared.IoC;
using SS14.Shared.GameObjects;
namespace SS14.Server.GameObjects
{
public class HumanEquipmentComponent : EquipmentComponent
{
public override string Name => "HumanEquipment";
public HumanEquipmentComponent()
{
//These shit lines allow the fucking shit to be added to the shit
activeSlots.Add(EquipmentSlot.Back);
activeSlots.Add(EquipmentSlot.Belt);
activeSlots.Add(EquipmentSlot.Ears);
activeSlots.Add(EquipmentSlot.Eyes);
activeSlots.Add(EquipmentSlot.Feet);
activeSlots.Add(EquipmentSlot.Hands);
activeSlots.Add(EquipmentSlot.Head);
activeSlots.Add(EquipmentSlot.Inner);
activeSlots.Add(EquipmentSlot.Mask);
activeSlots.Add(EquipmentSlot.Outer);
}
}
}

View File

@@ -1,56 +0,0 @@
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Equippable;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
using System;
using System.Collections.Generic;
using YamlDotNet.RepresentationModel;
namespace SS14.Server.GameObjects
{
public class EquippableComponent : Component
{
public override string Name => "Equippable";
public EquipmentSlot wearloc;
public IEntity currentWearer { get; set; }
public EquippableComponent()
{
Family = ComponentFamily.Equippable;
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
ComponentReplyMessage reply = base.RecieveMessage(sender, type, list);
if (sender == this)
return ComponentReplyMessage.Empty;
switch (type)
{
case ComponentMessageType.GetWearLoc:
reply = new ComponentReplyMessage(ComponentMessageType.ReturnWearLoc, wearloc);
break;
}
return reply;
}
public override void LoadParameters(YamlMappingNode mapping)
{
if (mapping.TryGetNode("wearloc", out YamlNode node))
{
wearloc = node.AsEnum<EquipmentSlot>();
}
}
public override ComponentState GetComponentState()
{
return new EquippableComponentState(wearloc, currentWearer?.Uid);
}
}
}

View File

@@ -1,390 +0,0 @@
using Lidgren.Network;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Hands;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using YamlDotNet.RepresentationModel;
namespace SS14.Server.GameObjects
{
public class HumanHandsComponent : Component, IInventoryContainer
{
public override string Name => "HumanHands";
public readonly Dictionary<InventoryLocation, IEntity> Handslots = new Dictionary<InventoryLocation, IEntity>();
public InventoryLocation CurrentHand = InventoryLocation.HandLeft;
public HumanHandsComponent()
{
Family = ComponentFamily.Hands;
}
public override void LoadParameters(YamlMappingNode mapping)
{
if (mapping.TryGetNode<YamlSequenceNode>("slots", out var sequence))
{
foreach (YamlNode slot in sequence)
{
Handslots.Add(slot.AsEnum<InventoryLocation>(), null);
}
}
}
/*
/// <summary>
/// Recieve a component message
/// </summary>
/// <param name="sender"></param>
/// <param name="type"></param>
/// <param name="replies"></param>
/// <param name="list"></param>
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
ComponentReplyMessage reply = base.RecieveMessage(sender, type, list);
if (sender == this)
return ComponentReplyMessage.Empty;
switch (type)
{
case ComponentMessageType.DisassociateEntity:
var entDrop = (Entity) list[0];
Drop(entDrop);
break;
case ComponentMessageType.ActiveHandChanged:
SwitchHandsTo((Hand) list[0]);
break;
case ComponentMessageType.IsCurrentHandEmpty:
reply = new ComponentReplyMessage(ComponentMessageType.IsCurrentHandEmpty, IsEmpty(CurrentHand));
break;
case ComponentMessageType.IsHandEmpty:
reply = new ComponentReplyMessage(ComponentMessageType.IsHandEmptyReply, IsEmpty((Hand) list[0]));
break;
case ComponentMessageType.PickUpItem:
Pickup((Entity) list[0]);
break;
case ComponentMessageType.PickUpItemToHand:
Pickup((Entity) list[0], (Hand) list[1]);
break;
case ComponentMessageType.DropItemInCurrentHand:
Drop(CurrentHand);
break;
case ComponentMessageType.DropItemInHand:
var hand = (Hand) list[0];
Drop(hand);
break;
case ComponentMessageType.DropEntityInHand:
var ent = (Entity) list[0];
Drop(ent);
break;
case ComponentMessageType.BoundKeyChange:
if ((BoundKeyFunctions) list[0] == BoundKeyFunctions.Drop &&
(BoundKeyState) list[1] == BoundKeyState.Up)
Drop();
if ((BoundKeyFunctions) list[0] == BoundKeyFunctions.SwitchHands &&
(BoundKeyState) list[1] == BoundKeyState.Up)
{
SwitchHands();
}
if ((BoundKeyFunctions) list[0] == BoundKeyFunctions.ActivateItemInHand &&
(BoundKeyState) list[1] == BoundKeyState.Up)
ActivateItemInHand();
break;
case ComponentMessageType.GetActiveHandItem:
if (!IsEmpty(CurrentHand))
reply = new ComponentReplyMessage(ComponentMessageType.ReturnActiveHandItem,
Handslots[CurrentHand]);
break;
case ComponentMessageType.Die:
DropAll();
break;
}
return reply;
}*/
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection client)
{
if (message.ComponentFamily == ComponentFamily.Hands)
{
var type = (ComponentMessageType)message.MessageParameters[0];
switch (type)
{
case ComponentMessageType.ActiveHandChanged:
var hand = (InventoryLocation)message.MessageParameters[1];
SwitchHandsTo(hand);
break;
case ComponentMessageType.DropEntityInHand:
Drop(Owner.EntityManager.GetEntity((int)message.MessageParameters[1]));
break;
case ComponentMessageType.DropItemInHand:
var dhand = (InventoryLocation)message.MessageParameters[1];
Drop(dhand);
break;
}
}
}
/// <summary>
/// Change the currently selected hand
/// </summary>
public void SwitchHands()
{
if (CurrentHand == InventoryLocation.HandLeft)
SwitchHandsTo(InventoryLocation.HandRight);
else
SwitchHandsTo(InventoryLocation.HandLeft);
}
private void SwitchHandsTo(InventoryLocation hand)
{
CurrentHand = hand;
Owner.SendDirectedComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered, null,
ComponentMessageType.ActiveHandChanged, hand);
}
/// <summary>
/// Get the entity in the specified hand
/// </summary>
/// <param name="hand"></param>
/// <returns></returns>
public IEntity GetEntity(InventoryLocation hand)
{
if (!IsEmpty(hand))
return Handslots[hand];
else
return null;
}
/// <summary>
/// Get the entity in the specified hand
/// </summary>
/// <param name="hand"></param>
/// <returns></returns>
public InventoryLocation GetHand(IEntity entity)
{
foreach (var kvp in Handslots)
{
if (kvp.Value == entity)
return kvp.Key;
}
return InventoryLocation.None;
}
/// <summary>
/// Get the currently selected hand
/// </summary>
/// <returns></returns>
private InventoryLocation GetCurrentHand()
{
return CurrentHand;
}
private void ActivateItemInHand()
{
InventoryLocation h = GetCurrentHand();
if (!IsEmpty(h))
{
IEntity e = GetEntity(h);
if (e != null)
{
e.SendMessage(this, ComponentFamily.Item, ComponentMessageType.Activate);
}
}
}
/// <summary>
/// Set the entity in the specified hand
/// </summary>
/// <param name="hand"></param>
/// <param name="entity"></param>
private void SetEntity(InventoryLocation hand, IEntity entity)
{
if (entity != null && IsEmpty(hand))
{
Handslots.Add(hand, entity);
//Owner.SendComponentNetworkMessage(this, Lidgren.Network.NetDeliveryMethod.ReliableOrdered, null, ComponentMessageType.EntityChanged, entity.Uid, hand); Maybe for later use?
}
}
/// <summary>
/// Put the specified entity in the currently selected hand
/// </summary>
/// <param name="entity"></param>
private void Pickup(IEntity entity)
{
if (entity != null && IsEmpty(CurrentHand))
{
RemoveFromOtherComps(entity);
SetEntity(CurrentHand, entity);
Owner.SendDirectedComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered, null,
ComponentMessageType.HandsPickedUpItem, entity.Uid,
CurrentHand);
entity.SendMessage(this, ComponentMessageType.PickedUp, Owner, CurrentHand);
}
}
/// <summary>
/// Put the specified entity in the specified hand
/// </summary>
/// <param name="entity"></param>
private void Pickup(IEntity entity, InventoryLocation hand)
{
if (entity != null && IsEmpty(hand))
{
RemoveFromOtherComps(entity);
SetEntity(hand, entity);
Owner.SendDirectedComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered, null,
ComponentMessageType.HandsPickedUpItem, entity.Uid, hand);
entity.SendMessage(this, ComponentMessageType.PickedUp, Owner, hand);
}
}
/// <summary>
/// Drop the item in the currently selected hand
/// </summary>
private void Drop()
{
Drop(CurrentHand);
}
private void RemoveFromOtherComps(IEntity entity)
{
IEntity holder = null;
if (entity.HasComponent(ComponentFamily.Item))
holder = ((BasicItemComponent)entity.GetComponent(ComponentFamily.Item)).CurrentHolder;
if (holder == null && entity.HasComponent(ComponentFamily.Equippable))
holder = ((EquippableComponent)entity.GetComponent(ComponentFamily.Equippable)).currentWearer;
if (holder != null) holder.SendMessage(this, ComponentMessageType.DisassociateEntity, entity);
else Owner.SendMessage(this, ComponentMessageType.DisassociateEntity, entity);
}
/// <summary>
/// Drop an item from a hand.
/// </summary>
/// <param name="hand"></param>
private void Drop(InventoryLocation hand)
{
if (!IsEmpty(hand))
{
GetEntity(hand).SendMessage(this, ComponentMessageType.Dropped);
Owner.SendDirectedComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered, null,
ComponentMessageType.HandsDroppedItem, GetEntity(hand).Uid,
hand);
Handslots.Remove(hand);
}
}
/// <summary>
/// Drop an entity.
/// </summary>
/// <param name="hand"></param>
private void Drop(IEntity ent)
{
if (Handslots.ContainsValue(ent))
{
InventoryLocation holding = Handslots.First(x => x.Value == ent).Key;
Drop(holding);
}
}
private void DropAll()
{
Drop(InventoryLocation.HandLeft);
Drop(InventoryLocation.HandRight);
}
/// <summary>
/// Check if the specified hand is empty
/// </summary>
/// <param name="hand"></param>
/// <returns></returns>
public bool IsEmpty(InventoryLocation hand)
{
if (Handslots.ContainsKey(hand) && Handslots[hand] != null)
return false;
return true;
}
public bool RemoveEntity(IEntity actor, IEntity toRemove, InventoryLocation location = InventoryLocation.Any)
{
if (Handslots.Any(x => x.Value == toRemove))
{
Handslots[Handslots.First(x => x.Value == toRemove).Key] = null;
return true;
}
else
{
return false;
}
}
public bool CanAddEntity(IEntity actor, IEntity toAdd, InventoryLocation location = InventoryLocation.Any)
{
if (Handslots.Any(x => x.Value == toAdd) || (location == InventoryLocation.Any && Handslots[CurrentHand] != null) || !Handslots.ContainsKey(location) || Handslots[location] != null)
{
return false;
}
return true;
}
public bool AddEntity(IEntity actor, IEntity toAdd, InventoryLocation location = InventoryLocation.Any)
{
if (Handslots.Any(x => x.Value == toAdd))
{
return false;
}
else
{
if (location == InventoryLocation.Any)
{
if (Handslots[CurrentHand] != null)
return false;
else
{
Handslots[CurrentHand] = toAdd;
}
}
else
{
if (Handslots[location] == null)
{
Handslots[location] = toAdd;
}
else
{
return false;
}
}
return true;
}
}
public IEnumerable<IEntity> GetEntitiesInInventory()
{
return Handslots.Values;
}
public override ComponentState GetComponentState()
{
//Oh man , what
//Yes man, this!
var entities = Handslots.Select(x => new KeyValuePair<InventoryLocation, int?>(x.Key, x.Value != null ? (int?)x.Value.Uid : null)).ToDictionary(key => key.Key, va => va.Value);
return new HandsComponentState(CurrentHand, entities);
}
public bool IsInHand(IEntity e)
{
return Handslots.ContainsValue(e);
}
}
}

View File

@@ -1,6 +1,7 @@
using SFML.Graphics;
using SS14.Server.Interfaces.Map;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.GameObjects.Components.Hitbox;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
@@ -13,13 +14,8 @@ namespace SS14.Server.GameObjects
public class HitboxComponent : Component
{
public override string Name => "Hitbox";
public FloatRect AABB { get; set; }
public HitboxComponent()
{
Family = ComponentFamily.Hitbox;
AABB = new FloatRect();
}
public override uint? NetID => NetIDs.HITBOX;
public FloatRect AABB { get; set; } = new FloatRect();
public override ComponentState GetComponentState()
{

View File

@@ -1,13 +0,0 @@
using SS14.Shared;
using SS14.Shared.Interfaces.GameObjects;
using System.Collections.Generic;
namespace SS14.Server.GameObjects
{
interface IInventoryContainer
{
bool RemoveEntity(IEntity actor, IEntity toRemove, InventoryLocation location = InventoryLocation.Any);
bool AddEntity(IEntity actor, IEntity toAdd, InventoryLocation location = InventoryLocation.Any);
IEnumerable<IEntity> GetEntitiesInInventory();
}
}

View File

@@ -2,6 +2,7 @@
using SS14.Server.GameObjects.Events;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components;
using SS14.Shared.IoC;
using System.Collections.Generic;
@@ -13,6 +14,7 @@ namespace SS14.Server.GameObjects
public class KeyBindingInputComponent : Component
{
public override string Name => "KeyBindingInput";
public override uint? NetID => NetIDs.KEY_BINDING_INPUT;
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection client)
{
var keyFunction = (BoundKeyFunctions) message.MessageParameters[0];
@@ -27,11 +29,6 @@ namespace SS14.Server.GameObjects
private readonly Dictionary<BoundKeyFunctions, bool> _keyStates = new Dictionary<BoundKeyFunctions, bool>();
public KeyBindingInputComponent()
{
Family = ComponentFamily.Input;
}
protected void SetKeyState(BoundKeyFunctions k, bool state)
{
// Check to see if we have a keyhandler for the key that's been pressed. Discard invalid keys.

View File

@@ -1,14 +0,0 @@
using SS14.Shared.GameObjects;
using SS14.Shared.IoC;
namespace SS14.Server.GameObjects
{
public class BasicInteractableComponent : Component
{
public override string Name => "BasicInteractable";
public BasicInteractableComponent()
{
Family = ComponentFamily.Interactable;
}
}
}

View File

@@ -1,178 +0,0 @@
using Lidgren.Network;
using SS14.Server.GameObjects.Events;
using SS14.Server.Interfaces.GameObjects;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Inventory;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using YamlDotNet.RepresentationModel;
namespace SS14.Server.GameObjects
{
public class InventoryComponent : Component, IInventoryComponent, IInventoryContainer
{
public override string Name => "Inventory";
public InventoryComponent()
{
Family = ComponentFamily.Inventory;
containedEntities = new List<IEntity>();
}
#region IInventoryComponent Members
public List<IEntity> containedEntities { get; private set; }
public int maxSlots { get; private set; }
public bool containsEntity(IEntity entity)
{
if (containedEntities.Contains(entity)) return true;
else return false;
}
#endregion IInventoryComponent Members
public override void HandleNetworkMessage(IncomingEntityComponentMessage message, NetConnection client)
{
switch ((ComponentMessageType)message.MessageParameters[0])
{
//TODO route these through the InventorySystem
case ComponentMessageType.InventoryAdd:
IEntity entAdd = Owner.EntityManager.GetEntity((int)message.MessageParameters[1]);
if (entAdd != null)
AddToInventory(entAdd);
//AddToInventory(entAdd);
break;
}
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
ComponentReplyMessage reply = base.RecieveMessage(sender, type, list);
if (sender == this)
return ComponentReplyMessage.Empty;
switch (type)
{
case ComponentMessageType.DisassociateEntity:
RemoveFromInventory((IEntity)list[0]);
break;
case ComponentMessageType.InventoryAdd:
// TODO Refactor craftingmanager to access this component directly, not using a message
AddToInventory((IEntity)list[0]);
break;
case ComponentMessageType.InventorySetSize:
maxSlots = (int)list[0];
break;
}
return reply;
}
public bool containsEntity(string templatename)
{
return containedEntities.Exists(x => x.Prototype.ID == templatename);
}
public override void LoadParameters(YamlMappingNode mapping)
{
YamlNode node;
if (mapping.TryGetNode("size", out node))
{
maxSlots = node.AsInt();
}
// TODO: Add support for objects that are created inside inventories (Lockers, crates etc)
}
//Adds item to inventory and dispatches hide message to sprite compo.
// TODO this method should be renamed to reflect what it really does
private void AddToInventory(IEntity entity)
{
Owner.EntityManager.RaiseEvent(this, new InventoryAddItemToInventoryEventArgs
{
Actor = Owner,
Item = entity
});
}
//Removes item from inventory and dispatches unhide message to sprite compo.
public bool RemoveFromInventory(IEntity entity)
{
if (containedEntities.Contains(entity))
{
containedEntities.Remove(entity);
}
HandleRemoved(entity);
return true;
}
private void HandleAdded(IEntity entity)
{
entity.SendMessage(this, ComponentMessageType.PickedUp, Owner, InventoryLocation.None);
entity.SendMessage(this, ComponentMessageType.SetVisible, false);
}
private void HandleRemoved(IEntity entity)
{
entity.SendMessage(this, ComponentMessageType.Dropped);
entity.SendMessage(this, ComponentMessageType.SetVisible, true);
}
public bool RemoveEntity(IEntity actor, IEntity toRemove, InventoryLocation location = InventoryLocation.Any)
{
if (containedEntities.Contains(toRemove))
{
containedEntities.Remove(toRemove);
return true;
}
else
{
return false;
}
}
public bool CanAddEntity(IEntity actor, IEntity toAdd, InventoryLocation location = InventoryLocation.Any)
{
if (containedEntities.Contains(toAdd))
{
return false;
}
// Todo check if inventory is full
return true;
}
public bool AddEntity(IEntity actor, IEntity toAdd, InventoryLocation location = InventoryLocation.Any)
{
if (!CanAddEntity(actor, toAdd, location))
{
return false;
}
else
{
containedEntities.Add(toAdd);
return true;
}
}
public IEnumerable<IEntity> GetEntitiesInInventory()
{
return containedEntities;
}
public override ComponentState GetComponentState()
{
List<int> entities = containedEntities.Select(x => x.Uid).ToList();
return new InventoryComponentState(maxSlots, entities);
}
}
}

View File

@@ -1,325 +0,0 @@
using SS14.Server.GameObjects.Item.ItemCapability;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Item;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using YamlDotNet.RepresentationModel;
namespace SS14.Server.GameObjects
{
public class BasicItemComponent : Component
{
public override string Name => "BasicItem";
private readonly Dictionary<string, ItemCapability> capabilities;
public InventoryLocation HoldingHand = InventoryLocation.None;
public bool CanBePickedUp = true;
public IEntity CurrentHolder { get; set; }
public BasicItemComponent()
{
Family = ComponentFamily.Item;
capabilities = new Dictionary<string, ItemCapability>();
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
ComponentReplyMessage reply = base.RecieveMessage(sender, type, list);
if (sender == this)
return ComponentReplyMessage.Empty;
switch (type)
{
/*case ComponentMessageType.ReceiveEmptyHandToItemInteraction:
HandleEmptyHandToItemInteraction((Entity) list[0]);
// param 0 is the actor entity, param 1 is the source actor entity
break;*/
case ComponentMessageType.ReceiveItemToItemInteraction:
//This message means we were clicked on by an actor with an item in hand
HandleItemToItemInteraction((IEntity)list[0]);
// param 0 is the actor entity, param 1 is the source actor entity
break;
case ComponentMessageType.EnactItemToActorInteraction:
ApplyTo((IEntity)list[0], InteractsWith.Actor, (IEntity)list[1]);
break;
case ComponentMessageType.EnactItemToItemInteraction:
ApplyTo((IEntity)list[0], InteractsWith.Item, (IEntity)list[1]);
break;
case ComponentMessageType.EnactItemToLargeObjectInteraction:
ApplyTo((IEntity)list[0], InteractsWith.LargeObject, (IEntity)list[1]);
break;
/*case ComponentMessageType.PickedUp:
HandlePickedUp((IEntity) list[0], (Hand) list[1]);
break;*/
case ComponentMessageType.Dropped:
HandleDropped();
break;
case ComponentMessageType.ItemGetCapability:
ItemCapability[] itemcaps = GetCapability((ItemCapabilityType)list[0]);
if (itemcaps != null)
reply = new ComponentReplyMessage(ComponentMessageType.ItemReturnCapability, itemcaps);
break;
case ComponentMessageType.ItemGetCapabilityVerbPairs:
var verbpairs = new List<KeyValuePair<ItemCapabilityType, ItemCapabilityVerb>>();
foreach (ItemCapability capability in capabilities.Values)
{
foreach (
ItemCapabilityVerb verb in
(from v in capability.verbs orderby v.Key descending select v.Value))
{
verbpairs.Add(
new KeyValuePair<ItemCapabilityType, ItemCapabilityVerb>(capability.CapabilityType, verb));
}
}
//if(verbpairs.Count > 0)
reply = new ComponentReplyMessage(ComponentMessageType.ItemReturnCapabilityVerbPairs,
verbpairs.ToLookup(v => v.Key, v => v.Value));
break;
case ComponentMessageType.CheckItemHasCapability:
reply = new ComponentReplyMessage(ComponentMessageType.ItemHasCapability,
HasCapability((ItemCapabilityType)list[0]));
break;
case ComponentMessageType.ItemGetAllCapabilities:
reply = new ComponentReplyMessage(ComponentMessageType.ItemReturnCapability,
(object)GetAllCapabilities());
break;
case ComponentMessageType.Activate:
Activate();
break;
case ComponentMessageType.ClickedInHand:
Activate();
break;
case ComponentMessageType.ItemEquipped:
HandleDropped();
break;
}
return reply;
}
/// <summary>
/// Applies this item to the target entity.
/// </summary>
/// <param name="targetEntity">Target entity</param>
/// <param name="targetType">Type of entity, Item, LargeObject, or Actor</param>
public virtual void ApplyTo(IEntity targetEntity, InteractsWith targetType, IEntity sourceActor)
{
//can be overridden in children to sort of bypass the capability system if needed.
ApplyCapabilities(targetEntity, targetType, sourceActor);
}
public void HandleDropped()
{
CurrentHolder = null;
HoldingHand = InventoryLocation.None;
}
public void HandlePickedUp(IEntity entity, InventoryLocation holdingHand)
{
CurrentHolder = entity;
HoldingHand = holdingHand;
/*Owner.AddComponent(ComponentFamily.Mover,
Owner.EntityManager.ComponentFactory.GetComponent("SlaveMoverComponent"));
Owner.SendMessage(this, ComponentMessageType.SlaveAttach, entity.Uid);
Owner.SendDirectedComponentNetworkMessage(this, NetDeliveryMethod.ReliableOrdered, null,
ItemComponentNetMessage.PickedUp, entity.Uid, holdingHand);*/
}
/// <summary>
/// Entry point for interactions between an item and this item
/// Basically, the actor uses an item on this item
/// </summary>
/// <param name="entity">The actor entity</param>
protected virtual void HandleItemToItemInteraction(IEntity actor)
{
//Get the item
//Apply actions based on the item's types
//Message the item to tell it to apply whatever it needs to do as well
}
/// <summary>
/// Entry point for interactions between an empty hand and this item
/// Basically, the actor touches this item with an empty hand
/// </summary>
/// <param name="actor"></param>
public virtual void HandleEmptyHandToItemInteraction(IEntity actor)
{
//Pick up the item
actor.SendMessage(this, ComponentMessageType.PickUpItem, Owner);
}
private void Activate()
{
Owner.SendMessage(this, ComponentMessageType.Activate);
ActivateCapabilities();
}
/// <summary>
/// Apply this item's capabilities to a target entity
/// This finds all onboard capability modules that can interact with a given object type,
/// sorted by priority. Only one thing will actually execute, depending on priority.
/// ApplyTo returns true if it successfully interacted with the target, false if not.
/// </summary>
/// <param name="target">Target entity for interaction</param>
protected virtual void ApplyCapabilities(IEntity target, InteractsWith targetType, IEntity sourceActor)
{
IOrderedEnumerable<ItemCapability> capstoapply = from c in capabilities.Values
where (c.interactsWith & targetType) == targetType
orderby c.priority descending
select c;
foreach (ItemCapability capability in capstoapply)
{
if (capability.ApplyTo(target, sourceActor))
break;
}
}
/// <summary>
/// Executes a query to get the capabilities of this item.
/// This enables us to ask things like, "is the item a tool?"
/// You can have items that have more than one tool capability module, and return them both via a query.
/// This is mostly useful for the object that is receiving an action from the item.
/// </summary>
/// <param name="query">ItemCapabilityQuery object</param>
/// <returns></returns>
protected ItemCapabilityQueryResult ExecuteCapabilityQuery(ItemCapabilityQuery query)
{
var result = new ItemCapabilityQueryResult();
result.ResultStatus = ItemCapabilityQueryResult.ItemCapabilityQueryResultType.Error;
switch (query.queryType)
{
case ItemCapabilityQuery.ItemCapabilityQueryType.GetAllCapabilities:
//Get all the capabilities of the object. Not particularly useful.
foreach (ItemCapability c in capabilities.Values)
result.AddCapability(c);
if (capabilities.Any())
result.ResultStatus = ItemCapabilityQueryResult.ItemCapabilityQueryResultType.Success;
else
result.ResultStatus = ItemCapabilityQueryResult.ItemCapabilityQueryResultType.Empty;
break;
case ItemCapabilityQuery.ItemCapabilityQueryType.GetCapability:
//Get the capabilities that match a particular capability type
IEnumerable<ItemCapability> caps = from c in capabilities.Values
where (c.CapabilityType == query.capabilityType)
select c;
foreach (ItemCapability c in caps)
result.AddCapability(c);
if (caps.Any())
result.ResultStatus = ItemCapabilityQueryResult.ItemCapabilityQueryResultType.Success;
else
result.ResultStatus = ItemCapabilityQueryResult.ItemCapabilityQueryResultType.Empty;
break;
case ItemCapabilityQuery.ItemCapabilityQueryType.HasCapability:
//Check if the item has a capability of a certain type.
IEnumerable<ItemCapability> hascap = from c in capabilities.Values
where (c.CapabilityType == query.capabilityType)
select c;
if (hascap.Any())
result.ResultStatus = ItemCapabilityQueryResult.ItemCapabilityQueryResultType.True;
else
result.ResultStatus = ItemCapabilityQueryResult.ItemCapabilityQueryResultType.False;
break;
}
if (result.ResultStatus == ItemCapabilityQueryResult.ItemCapabilityQueryResultType.Error)
result.ErrorMessage = "No Result";
return result;
}
private ItemCapability[] GetCapability(ItemCapabilityType type)
{
ItemCapabilityQueryResult result =
ExecuteCapabilityQuery(new ItemCapabilityQuery(
ItemCapabilityQuery.ItemCapabilityQueryType.GetCapability, type));
if (result.ResultStatus == ItemCapabilityQueryResult.ItemCapabilityQueryResultType.Success)
return result.Capabilities;
else
return null;
}
private ItemCapability[] GetAllCapabilities()
{
ItemCapabilityQueryResult result =
ExecuteCapabilityQuery(
new ItemCapabilityQuery(ItemCapabilityQuery.ItemCapabilityQueryType.GetAllCapabilities,
ItemCapabilityType.None));
if (result.ResultStatus == ItemCapabilityQueryResult.ItemCapabilityQueryResultType.Empty)
return new ItemCapability[0];
else
return result.Capabilities;
}
private void ActivateCapabilities()
{
foreach (ItemCapability c in GetAllCapabilities())
{
c.Activate();
}
}
private bool HasCapability(ItemCapabilityType type)
{
ItemCapabilityQueryResult result =
ExecuteCapabilityQuery(new ItemCapabilityQuery(
ItemCapabilityQuery.ItemCapabilityQueryType.HasCapability, type));
if (result.ResultStatus == ItemCapabilityQueryResult.ItemCapabilityQueryResultType.True)
return true;
else
return false;
}
public void AddCapability(ItemCapability cap)
{
capabilities.Add(cap.capabilityName, cap);
cap.owner = this;
}
public override void LoadParameters(YamlMappingNode yaml)
{
/*
TODO: figure something out for this cancerous mess.
Yeah it's basically ANOTHER FUCKING COMPONENT SYSTEM built into the item component.
foreach (XElement itemcapability in extendedParameters.Descendants("ItemCapability"))
{
IEnumerable<XElement> Verbs = itemcapability.Descendants("ItemCapabilityVerb");
IEnumerable<XElement> Parameters = itemcapability.Descendants("ItemCapabilityParameter");
ItemCapability cap = null;
if (cap == null) // TODO: make this method actually do something because right now it always returns
return;
foreach (XElement verb in Verbs)
{
cap.AddVerb(int.Parse(verb.Attribute("priority").Value),
(ItemCapabilityVerb)
Enum.Parse(typeof (ItemCapabilityVerb), verb.Attribute("name").Value));
}
foreach (XElement parameter in Parameters)
{
string name = parameter.Attribute("name").Value;
Type type = EntityTemplate.TranslateType(parameter.Attribute("type").Value);
object value = Convert.ChangeType(parameter.Attribute("value").Value, type);
var cparam = new ComponentParameter(name, value);
cap.SetParameter(cparam);
}
AddCapability(cap);
}
*/
}
public override ComponentState GetComponentState()
{
return new ItemComponentState(CurrentHolder != null ? (int?)CurrentHolder.Uid : null, HoldingHand);
}
}
}

View File

@@ -1,144 +0,0 @@
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using System.Collections.Generic;
using System.Linq;
namespace SS14.Server.GameObjects.Item.ItemCapability
{
public class ItemCapability
{
public string capabilityName;
protected ItemCapabilityType capabilityType;
public InteractsWith interactsWith; //What types of shit this interacts with
public IComponent owner;
public int priority; //Where in the stack this puppy is
/// <summary>
/// dictionary of priority -> verb -- lower priority verbs execute first
/// </summary>
public Dictionary<int, ItemCapabilityVerb> verbs;
public ItemCapability()
{
verbs = new Dictionary<int, ItemCapabilityVerb>();
}
public ItemCapabilityType CapabilityType
{
get { return capabilityType; }
protected set { capabilityType = value; }
}
public virtual bool ApplyTo(IEntity target, IEntity sourceActor)
{
return false;
}
public void AddVerb(int priority, ItemCapabilityVerb verb)
{
if (verbs.ContainsKey(priority))
//Shuffle the list to insert the specified verb and move the one in that spot down.
{
ItemCapabilityVerb tverb = verbs[priority];
RemoveVerb(priority);
AddVerb(priority, verb);
AddVerb(priority + 1, tverb);
}
else
verbs.Add(priority, verb);
}
public void RemoveVerb(int priority)
{
verbs.Remove(priority);
}
/// <summary>
/// This allows setting of the component's parameters once it is instantiated.
/// This should basically be overridden by every inheriting component, as parameters will be different
/// across the board.
/// </summary>
/// <param name="parameter">ComponentParameter object describing the parameter and the value</param>
public virtual void SetParameter(ComponentParameter parameter)
{
}
public virtual void Activate()
{
}
}
/// <summary>
/// Query datatype
/// </summary>
public struct ItemCapabilityQuery
{
#region ItemCapabilityQueryType enum
public enum ItemCapabilityQueryType
{
HasCapability,
GetCapability,
GetAllCapabilities,
}
#endregion ItemCapabilityQueryType enum
public ItemCapabilityType capabilityType;
public ItemCapabilityQueryType queryType;
public ItemCapabilityQuery(ItemCapabilityQueryType _queryType, ItemCapabilityType _capabilityType)
{
queryType = _queryType;
capabilityType = _capabilityType;
}
}
/// <summary>
/// Query result datatype
/// </summary>
public class ItemCapabilityQueryResult
{
#region ItemCapabilityQueryResultType enum
/// <summary>
/// Types of results
/// </summary>
public enum ItemCapabilityQueryResultType
{
True,
False,
Success,
Empty,
Error,
Null
}
#endregion ItemCapabilityQueryResultType enum
private ItemCapability[] returnedCapabilities;
public ItemCapabilityQueryResultType ResultStatus { get; set; }
public string ErrorMessage { get; set; }
public ItemCapability[] Capabilities
{
get { return returnedCapabilities; }
}
/// <summary>
/// Adds a capability to the query result to be returned.
/// </summary>
/// <param name="cap"></param>
public void AddCapability(ItemCapability cap)
{
List<ItemCapability> retcap;
if (returnedCapabilities == null || returnedCapabilities.Length == 0)
retcap = new List<ItemCapability>();
else
retcap = returnedCapabilities.ToList();
retcap.Add(cap);
returnedCapabilities = retcap.ToArray();
}
}
}

View File

@@ -1,221 +0,0 @@
using SFML.System;
using SS14.Server.Interfaces.Chat;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
using System.Collections.Generic;
using System.Linq;
using YamlDotNet.RepresentationModel;
namespace SS14.Server.GameObjects
{
public class BasicDoorComponent : BasicLargeObjectComponent
{
public override string Name => "BasicDoor";
private bool Open;
private bool autoclose = true;
private string closedSprite = "";
private bool disabled;
private float openLength = 5000;
private string openSprite = "";
private bool openonbump;
private float timeOpen;
public BasicDoorComponent()
{
Family = ComponentFamily.LargeObject;
RegisterSVar("OpenOnBump", typeof(bool));
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
ComponentReplyMessage reply = base.RecieveMessage(sender, type, list);
if (sender == this)
return ComponentReplyMessage.Empty;
switch (type)
{
case ComponentMessageType.Bumped:
if (openonbump)
OpenDoor();
break;
}
return reply;
}
public override void Update(float frameTime)
{
base.Update(frameTime);
if (disabled) return;
if (Open && autoclose)
{
timeOpen += frameTime;
if (timeOpen >= openLength)
CloseDoor();
}
}
public override void OnAdd(IEntity owner)
{
base.OnAdd(owner);
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove += OnMove;
}
public override void OnRemove()
{
Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).OnMove -= OnMove;
base.OnRemove();
}
private void OnMove(object sender, VectorEventArgs args)
{
SetPermeable(args.VectorFrom);
SetImpermeable(args.VectorTo);
}
protected override void RecieveItemInteraction(IEntity actor, IEntity item,
Lookup<ItemCapabilityType, ItemCapabilityVerb> verbs)
{
base.RecieveItemInteraction(actor, item, verbs);
if (verbs[ItemCapabilityType.Tool].Contains(ItemCapabilityVerb.Pry))
{
ToggleDoor(true);
}
else if (verbs[ItemCapabilityType.Tool].Contains(ItemCapabilityVerb.Hit))
{
var cm = IoCManager.Resolve<IChatManager>();
cm.SendChatMessage(ChatChannel.Default,
actor.Name + " hit the " + Owner.Name + " with a " + item.Name + ".", null, item.Uid);
}
else if (verbs[ItemCapabilityType.Tool].Contains(ItemCapabilityVerb.Emag))
{
OpenDoor();
disabled = true;
}
}
/// <summary>
/// Entry point for interactions between an empty hand and this object
/// Basically, actor "uses" this object
/// </summary>
/// <param name="actor">The actor entity</param>
protected override void HandleEmptyHandToLargeObjectInteraction(IEntity actor)
{
ToggleDoor(true);
}
private void ToggleDoor(bool forceToggle = false)
{
//Apply actions
if (Open)
{
CloseDoor(forceToggle);
}
else
{
OpenDoor(forceToggle);
}
}
private void OpenDoor(bool force = false)
{
if (disabled && !force) return;
//var map = IoCManager.Resolve<IMapManager>();
//Tile t = (Tile)map.GetFloorAt(Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
Open = true;
Owner.SendMessage(this, ComponentMessageType.DisableCollision);
Owner.SendMessage(this, ComponentMessageType.SetSpriteByKey, openSprite);
//if(t != null)
// t.GasPermeable = true; // Gotta find another way to do this.
}
private void CloseDoor(bool force = false)
{
if (disabled && !force) return;
//var map = IoCManager.Resolve<IMapManager>();
//Tile t = (Tile)map.GetFloorAt(Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
Open = true;
Open = false;
timeOpen = 0;
Owner.SendMessage(this, ComponentMessageType.EnableCollision);
Owner.SendMessage(this, ComponentMessageType.SetSpriteByKey, closedSprite);
//if (t != null)
// t.GasPermeable = false; // Gotta find another way to do this.
}
private void SetImpermeable()
{
//var map = IoCManager.Resolve<IMapManager>();
//Tile t = (Tile)map.GetFloorAt(Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
//if (t != null)
// t.GasPermeable = false;
}
private void SetImpermeable(Vector2f position)
{
//var map = IoCManager.Resolve<IMapManager>();
//Tile t = (Tile)map.GetFloorAt(Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
//if (t != null)
// t.GasPermeable = false;
}
private void SetPermeable(Vector2f position)
{
//var map = IoCManager.Resolve<IMapManager>();
//Tile t = (Tile)map.GetFloorAt(Owner.GetComponent<TransformComponent>(ComponentFamily.Transform).Position);
//if (t != null)
// t.GasPermeable = true;
}
public override void LoadParameters(YamlMappingNode mapping)
{
YamlNode node;
if (mapping.TryGetNode("openSprite", out node))
{
openSprite = node.AsString();
}
if (mapping.TryGetNode("closedSprite", out node))
{
closedSprite = node.AsString();
}
if (mapping.TryGetNode("openOnBump", out node))
{
openonbump = node.AsBool();
}
if (mapping.TryGetNode("autoCloseInterval", out node))
{
var autocloseinterval = node.AsInt();
if (autocloseinterval == 0)
{
autoclose = false;
}
else
{
autoclose = true;
openLength = autocloseinterval;
}
}
}
public override IList<ComponentParameter> GetParameters()
{
IList<ComponentParameter> cparams = base.GetParameters();
cparams.Add(new ComponentParameter("OpenOnBump", openonbump));
return cparams;
}
}
}

View File

@@ -1,91 +0,0 @@
using SS14.Shared.GameObjects;
using SS14.Shared.Interfaces.GameObjects;
using SS14.Shared.IoC;
using System.Linq;
namespace SS14.Server.GameObjects
{
public class BasicLargeObjectComponent : Component
{
public override string Name => "BasicLargeObject";
public BasicLargeObjectComponent()
{
Family = ComponentFamily.LargeObject;
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
ComponentReplyMessage reply = base.RecieveMessage(sender, type, list);
if (sender == this)
return ComponentReplyMessage.Empty;
switch (type)
{
case ComponentMessageType.ReceiveEmptyHandToLargeObjectInteraction:
HandleEmptyHandToLargeObjectInteraction((IEntity)list[0]);
break;
case ComponentMessageType.ReceiveItemToLargeObjectInteraction:
HandleItemToLargeObjectInteraction((IEntity)list[0]);
break;
}
return reply;
}
/// <summary>
/// Entry point for interactions between an item and this object
/// Basically, the actor uses an item on this object
/// </summary>
/// <param name="actor">the actor entity</param>
protected void HandleItemToLargeObjectInteraction(IEntity actor)
{
//Get the item
ComponentReplyMessage reply = actor.SendMessage(this, ComponentFamily.Hands,
ComponentMessageType.GetActiveHandItem);
if (reply.MessageType != ComponentMessageType.ReturnActiveHandItem)
return; // No item in actor's active hand. This shouldn't happen.
var item = (Entity)reply.ParamsList[0];
reply = item.SendMessage(this, ComponentFamily.Item, ComponentMessageType.ItemGetCapabilityVerbPairs);
if (reply.MessageType == ComponentMessageType.ItemReturnCapabilityVerbPairs)
{
var verbs = (Lookup<ItemCapabilityType, ItemCapabilityVerb>)reply.ParamsList[0];
if (verbs.Count == 0 || verbs == null)
RecieveItemInteraction(actor, item);
else
RecieveItemInteraction(actor, item, verbs);
}
}
/// <summary>
/// Recieve an item interaction. woop.
/// </summary>
/// <param name="item"></param>
protected virtual void RecieveItemInteraction(IEntity actor, IEntity item,
Lookup<ItemCapabilityType, ItemCapabilityVerb> verbs)
{
}
/// <summary>
/// Recieve an item interaction. woop. NO VERBS D:
/// </summary>
/// <param name="item"></param>
protected virtual void RecieveItemInteraction(IEntity actor, IEntity item)
{
}
/// <summary>
/// Entry point for interactions between an empty hand and this object
/// Basically, actor "uses" this object
/// </summary>
/// <param name="actor">The actor entity</param>
protected virtual void HandleEmptyHandToLargeObjectInteraction(IEntity actor)
{
//Apply actions
}
}
}

View File

@@ -1,100 +0,0 @@
using SS14.Server.Interfaces.Chat;
using SS14.Shared;
using SS14.Shared.GameObjects;
using SS14.Shared.GameObjects.Components.Light;
using SS14.Shared.IoC;
using SS14.Shared.Utility;
using System;
using System.Collections.Generic;
using YamlDotNet.RepresentationModel;
namespace SS14.Server.GameObjects
{
public class LightComponent : Component
{
public override string Name => "Light";
private int _colorB = 200;
private int _colorG = 200;
private int _colorR = 200;
private LightModeClass _mode = LightModeClass.Constant;
private LightState _state = LightState.On;
public LightComponent()
{
Family = ComponentFamily.Light;
}
public override void LoadParameters(YamlMappingNode mapping)
{
YamlNode node;
if (mapping.TryGetNode("startState", out node))
{
_state = node.AsEnum<LightState>();
}
if (mapping.TryGetNode("lightColorR", out node))
{
_colorR = node.AsInt();
}
if (mapping.TryGetNode("lightColorG", out node))
{
_colorG = node.AsInt();
}
if (mapping.TryGetNode("lightColorB", out node))
{
_colorB = node.AsInt();
}
}
public override ComponentReplyMessage RecieveMessage(object sender, ComponentMessageType type,
params object[] list)
{
ComponentReplyMessage reply = base.RecieveMessage(sender, type, list);
if (sender == this)
return reply;
switch (type)
{
case ComponentMessageType.Die:
SetState(LightState.Broken);
break;
case ComponentMessageType.Activate:
HandleClickedInHand();
break;
}
return reply;
}
private void HandleClickedInHand()
{
switch (_state)
{
case LightState.On:
SetState(LightState.Off);
break;
case LightState.Off:
SetState(LightState.On);
break;
case LightState.Broken:
IoCManager.Resolve<IChatManager>().SendChatMessage(ChatChannel.Damage,
"You fiddle with it, but nothing happens. It must be broken.",
Owner.Name, Owner.Uid);
break;
}
}
private void SetState(LightState state)
{
_state = state;
}
public override ComponentState GetComponentState()
{
return new LightComponentState(_state, _colorR, _colorG, _colorB, _mode);
}
}
}

Some files were not shown because too many files have changed in this diff Show More