Entitas icon indicating copy to clipboard operation
Entitas copied to clipboard

Events aka Reactive-UI

Open sschmid opened this issue 8 years ago • 76 comments

Add new Attributes, Data Providers and Code Generators to generate what we know under the name Reactive UI (as explained in this Unite Talk video https://www.youtube.com/watch?v=Phx7IJ3XUzg)

[Event(false)]
public sealed class GameOverComponent : IComponent {
}

[Event(true)]
public sealed class PositionComponent : IComponent {
    public Vector3 value;
}

I plan to generate 2 different events, one that's independent from entities [Event(false)] and one that's bound to a specific entity [Event(true)]

public interface IGameOverListener {
    void OnGameOver(bool isGameOver);
}

public sealed class GameOverListenerComponent : IComponent {
    public IGameOverListener value;
}

public sealed class GameOverEventSystem : ReactiveSystem<GameEntity> {

    readonly IGroup<GameEntity> _listsners;

    public GameOverEventSystem(Contexts contexts) : base(contexts.game) {
        _listsners = contexts.game.GetGroup(GameMatcher.GameOverListener);
    }

    protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context) {
        return context.CreateCollector(GameMatcher.GameOver.AddedOrRemoved());
    }

    protected override bool Filter(GameEntity entity) {
        return true;
    }

    protected override void Execute(List<GameEntity> entities) {
        foreach (var e in entities) {
            foreach (var listener in _listsners) {
                listener.gameOverListener.value.OnGameOver(e.isGameOver);
            }
        }
    }
}
public interface IPositionListener {
    void OnPosition(Vector3 position);
}

public sealed class PositionListenerComponent : IComponent {
    public IPositionListener value;
}

public sealed class PositionEventSystem : ReactiveSystem<GameEntity> {

    public PositionEventSystem(Contexts contexts) : base(contexts.game) {
    }

    protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context) {
        return context.CreateCollector(GameMatcher.Position);
    }

    protected override bool Filter(GameEntity entity) {
        return entity.hasPosition && entity.hasPositionListener;
    }

    protected override void Execute(List<GameEntity> entities) {
        foreach (var e in entities) {
            e.positionListener.value.OnPosition(e.position.value);
        }
    }
}

This is the idea, the implementation might be different once I see it in action.

Discussion and feedback is welcome

sschmid avatar Jan 31 '18 14:01 sschmid

I would say you always want the entity from Event(true) despite it's unique. So the generator could handle that for you. Furthermore the OnPositionChanged(Vector3 position, GameEntity entity) Method should also be called when the Group of PositionEventComponent is changing so that the registered interface get directly called (as Group Event, not reactive so it won't get called the next tick). Finally a Remove Event would be good.

ghost avatar Jan 31 '18 15:01 ghost

Our team check this way and event handling like this is unprofitable in huge projects, while you can't subscribe for group of components. For example, 2 cases:

  • it's ok if you subscribing for PlayerDataComponent, but what if you need update UI only when group of components PlayerDataComponent and PlayerAvatarResourcesComponent added
  • if you need to update online badge near concrete user from 2 users in multiplayer session avatar when group of PlayerDataComponent and PlayerIsOnlineComponent added/removed

Also few features will be useful here:

  • filtering components (for example, subscribe only for StoreItemComponent with Gift in ItemType field)
  • subscribe to adding and removing of components
  • subscribing to components-flags

raslab avatar Jan 31 '18 15:01 raslab

Updated code

sschmid avatar Jan 31 '18 16:01 sschmid

Iteration 1 will contain generated

  • Interfaces
  • Components
  • Systems
  • One EventSystems class that contains all systems ordered by priority

sschmid avatar Jan 31 '18 23:01 sschmid

Test results can already be seen here https://github.com/sschmid/Entitas-CSharp/tree/develop/Tests/TestFixtures/Generated/Events

sschmid avatar Jan 31 '18 23:01 sschmid

For the attributes i would suggest to name them differently instead of [Event(true)] and [Event(false)]. Currently you would have to know if "false" is an Entity bound event or not instead of just seeing it at a glance. One could read the parameter as "is pure event" or as "is entity event" (which it currently is) Maybe call them [Event] and [EntityEvent] or something along these lines, to clearly differentiate them.

Draugor avatar Feb 01 '18 07:02 Draugor

I suggest can call it one-to-one event and one-to-many event.

optimisez avatar Feb 01 '18 13:02 optimisez

Current state: You can flag components with [Event(true)] or [Event(false)] [Event(bool bindToEntity)]

E.g.

[Unique, Event(false)]
public sealed class ScoreComponent : IComponent {
     public int value;
}

After generation you can use the IListener

public class GameHUDController : MonoBehaviour, IScoreListener {

    public Text scoreLabel;

    void Start() {
        Contexts.sharedInstance.game.CreateEntity().AddScoreListener(this);
    }

    public void OnScore(int value) {
        scoreLabel.text = value.ToString();
    }
}

The generated GameScoreEventSystem which notifies all IScoreListeners will be added to the generated EventSystems feature automatically.

When [Event(true)] the listener is on the same entity as the component of interest, e.g.

[Event(true)]
public sealed class PositionComponent : IComponent {
    public Vector3 value;
}

public class View : MonoBehaviour, IView, IPositionListener {

    public virtual Vector3 position { get { return transform.localPosition; } set { transform.localPosition = 

    public virtual void Link(IEntity entity, IContext context) {
        gameObject.Link(entity, context);
        var e = (GameEntity)entity;
        e.AddPositionListener(this);
    }

    public virtual void OnPosition(Vector3 value) {
        position = value;
    }
}

I will show this in the Shmup Part 3 video

sschmid avatar Feb 12 '18 21:02 sschmid

Forgot to mention:

It's really awesome! :)

sschmid avatar Feb 12 '18 21:02 sschmid

What if I want multiple listeners to [Event(true)]?

c0ffeeartc avatar Feb 13 '18 00:02 c0ffeeartc

[Event(true)] is bound to one entity, there can only be one. Try using [Event(false)] instead

sschmid avatar Feb 13 '18 00:02 sschmid

Event(true) usage is kind of narrow, will keep using entity.OnComponentAdded

Can it use Action under the hood to allow multiple listeners? Something like this:

[GameC]
public sealed class HealthCompListenerComponent : Entitas.IComponent {

    public Action<float> value;
}

public partial class GameCEntity {

    public HealthCompListenerComponent healthCompListener { get { return (HealthCompListenerComponent)GetComponent(GameCComponentsLookup.HealthCompListener); } }
    public bool hasHealthCompListener { get { return HasComponent(GameCComponentsLookup.HealthCompListener); } }

    public void AddHealthCompListener(IHealthCompListener listener) {
        if (!hasHealthCompListener) {
            var index = GameCComponentsLookup.HealthCompListener;
            var component = CreateComponent<HealthCompListenerComponent>(index);
            component.value += listener;
            AddComponent(index, component);
        }
        else {
            healthCompListener.value += listener;
            listener.OnHealthComp(healthComp.Value);
        }
    }

    public void RemoveHealthCompListener(IHealthCompListener listener) {
        healthCompListener.value -= listener;
        if (healthCompListener.value == null) {
            RemoveComponent(GameCComponentsLookup.HealthCompListener);
        }
    }
}

c0ffeeartc avatar Feb 13 '18 00:02 c0ffeeartc

Copied existing generators and changed to use Action Gist. It needs extension method for convenience, didn't write generator for it

public static void ListenHealthComp (this GameCEntity ent, Action<float> action) {
   if (!ent.hasHealthCompListener) {
       ent.AddHealthCompListener(null);
   }
   ent.healthCompListener.value	+= action;
   ent.ReplaceHealthCompListener(ent.healthCompListener.value);
}

Here are my thoughts after digging in event generators:

  • Event(false) and Event(true) serve quite different purposes, and having same interface gives drawbacks. For example ent.AddHealthListener(*) doesn't tell if health is entity event or a global event. Or if at some point developer chooses to switch (false) to (true)version there will be no compilation errors, but behaviour will be broken.
  • Event(false) and Event(true) generators are tightly coupled. Wanted to change one of them and had to change other too

c0ffeeartc avatar Feb 14 '18 17:02 c0ffeeartc

Agree, I'm not 100% happy with [Event(bool)]. Suggestions for names? [Event] and [EntityEvent]?

IXyzEntityListener could pass the entity instead of the value

sschmid avatar Feb 14 '18 17:02 sschmid

[Event] and [EntityEvent] sound good

c0ffeeartc avatar Feb 14 '18 17:02 c0ffeeartc

Or One-To-One Event and Many-To-One Event? Btw XyzEntityListener could pass the entity instead of the value? Do u mean passing the whole entity instead of based on the data from component?

optimisez avatar Feb 14 '18 17:02 optimisez

@optimisez

Do u mean passing the whole entity instead of the data from component?

yes

sschmid avatar Feb 14 '18 17:02 sschmid

but not sure if that's a good idea as it might encourage modifying the entity

sschmid avatar Feb 14 '18 17:02 sschmid

IXyzEntityListener could pass the entity instead of the value but not sure if that's a good decision as it might encourage modifying the entity

I'd use entity argument in both Event and EntityEvent, sometimes there are additional components on entities.

c0ffeeartc avatar Feb 14 '18 17:02 c0ffeeartc

[Event(false)]
public sealed class GameStateOverEventComponent : IComponent { }

public class UiController : MonoBehaviour, IGameStateOverEventListener
{
	......

    public void OnGameStateOverEvent(bool isGameStateOverEvent) // this paramenter is not needed
    {
        //do something
    }
}

feature request: empty parameter event function

roygear avatar Feb 15 '18 06:02 roygear