Przyczyny zdarzenia

Eventy (wydarzenia) są świetne do dołączania dodatkowej logiki do akcji gry, ale mają wadę posiadania braku kontekstu co spowodowało dany event (wydarzenie). Obiekt Cause pozwala dostarczać i otrzymywać dodatkowe informacje na temat kontekstu eventu. Ta informacja może zostać później użyta do modyfikacji zachowania Twojego event listenera (nasłuchiwacza wydarzenia).

Dla przykładu, plugin ochraniający świat potrzebuje informacji o tym, jaki gracz wywołał wydarzenie ChangeBlockEvent zanim zdecyduje czy wydarzenie powinno zostać anulowane czy nie. Zamiast iść tradycyjną ścieżką tworzenia wielu subeventów (pod-wydarzeń) dla różnych warunków źródłowych, ta informacja jest przedstawiona w obiekcie Cause w evencie (wydarzeniu).

Każdy event (wydarzenie) posiada obiekt Cause, który może być wykorzystany w celu uzyskania informacji dotyczących przyczyn, dla których event został uruchomiony. Obiekt Cause (przyczyna) może zostać pobrany z eventu przy pomocy Event#getCause().

Przyczyna i Kontekst

Obiekt Cause zawiera dwa różne zestawy informacji, stos przyczyn i EventContext.

  • Stosem przyczyn zdarzenia są przyczyny przechwycone w kolejności ważności. Obiekty w stosie przyczyn (cause stack) nie posiadają dołączonych do nich nazw.

  • Kontekst eventu (wydarzenia) zawiera dodatkowe informacje dotyczące wydarzenia. Konteksty są dołączone do kluczy, ale nie są w kolejności, są równie ważne.

Jako przykład, jeśli owca należąca do gracza zje trochę trawy, to najbardziej bezpośrednią przyczyną tego jest owca. Gracz pojawi się w EventContext jako EventContextKeys#OWNER, dając konsumentom eventu dodatkowe informacje o tym w jaki sposób wydarzenie się pojawiło, ale niekoniecznie znajdzie się on w bezpośredniej przyczynie.

Innym przykładem, na który musisz uważać, jest sytuacja w której symulujesz gracza. Symulowany gracz nie może znajdować się w bezpośredniej przyczynie, ponieważ taki gracz nie mógł być zaangażowany w akcje, jednakże taki gracz może pojawić się w EventContext pod EventContextKeys#PLAYER_SIMULATED

Pobieranie Obiektów z Bezpośredniej Przyczyny

Strukturalnie obiekt Cause zawiera sekwencyjną listę obiektów. Istnieje kilka metod, które można wykorzystać do pobrania informacji z obiektu Przyczyny, które omówimy tutaj. Aby uzyskać kompletną listę zobacz Javadocs <https://jd.spongepowered.org>.

Informacja

The objects within a cause are ordered such that the first object is the most immediate cause of the event, and subsequent objects are of decreasing importance and/or may only provide contextual information.

Cause#root() returns the first object within the cause. This object is the most immediate or direct cause of the event. Since a Cause may not be empty, it is guaranteed to have a root.

Cause#first(Class) returns the first object in the cause chain whose type is either the same as or is a subtype of the given class. For example, given a cause which contained a player followed by an entity [Player, Entity, ...]

@Listener
public void onEvent(ExampleCauseEvent event) {
    Cause cause = event.getCause(); // [Player, Entity]
    Optional<Player> firstPlayer = cause.first(Player.class); // 1
    Optional<Entity> firstEntity = cause.first(Entity.class); // 2
}

Both optionals would contain the player object as its type directly matched request for a Player type and it matched the request for an Entity type as Player is a subtype of Entity.

Cause#last(Class) is similar to Cause#first(Class) except it returns the last value in the cause chain matching the type.

Continuing from the example above, if we instead changed it to call Cause#last(Class) the first optional would contain the player object still, but the second optional would now contain the entity that we passed in the second position of the cause.

Cause#containsType(Class) returns a boolean value and can be used to check if a cause chain contains any object matching the provided type.

Cause#all() simply returns all objects within the cause allowing more advanced handling.

Event Context

Sometimes the ordering of objects within the cause isn’t enough to get the proper idea of what an object represents in relation to the event. This is where EventContext comes in. The event context allows objects to be associated with unique names, in the form of EventContextKeys, allowing them to be easily identified and requested. Some examples of use cases for named causes is the Notifier of a ChangeBlockEvent.Grow or the Source of a DamageEntityEvent.

Unlike the cause stack, which makes no guarantees as to the objects contained witin it, an object associated with a EventContextKey is guaranteed to be of the type specified by the key.

Retrieving a entry from the context of a cause

@Listener
public void onGrow(ChangeBlockEvent.Grow event) {
    Optional<User> notifier = event.getCause().getContext().get(EventContextKeys.NOTIFIER);
}

This example makes use of EventContext#get(EventContextKey) which can be used to retrieve the expected object associated with a name if it is present within the context. Additionally EventContext#asMap() provides a Map<EventContextKey<?>, Object> which can be used to find all present EventContextKeys and their associated objects.

Informacja

Some common identifying names for EventContextKeys are present as static fields in the EventContextKeys class.

Creating Custom Causes

Creating a cause is easy, but depends on whether you are creating your cause on the main server thread or async.

Informacja

Cause objects are immutable therefore cannot be modified once created.

Using the CauseStackManager

Ostrzeżenie

The CauseStackManager only works on the main server thread. If you call it from a different thread, an IllegalStateException will be thrown. Ensure you are on the main server thread before calling methods on the CauseStackManager.

If you are creating your event on the main thread, then use the CauseStackManager, which can be found at Sponge#getCauseStackManager(). The CauseStackManager tracks the potential causes of events as the game runs, allowing for easy retrieval of the current Cause without effort. To see the current cause, call CauseStackManager#getCurrentCause(). You may notice that your plugin’s PluginContainer is already in the returned Cause, as plugins are one of the objects tracked by the manager. Using the CauseStackManager for creating causes removes the need for boilerplate-like code where you supply objects like your plugin container, so that you can concentrate on adding your own causes.

Before adding your own causes, you should push a cause stack frame to the manager. Adding a frame acts as a saved state, when you are done with your causes, the removal of the frame returns the manager to its original state.

Wskazówka

Adding a frame to the CauseStackManager does not remove what is already in the manager, so anything that is in the cause stack and contexts before a stack frame is added will be there afterwards. You can verify this by calling Sponge.getCauseStackManager().getCurrentCause() before and after the frame is pushed.

For example, if the cause stack contains a PluginContainer and a CommandSource when a frame is pushed, they will remain on the stack and will form part of the Cause if one is obtained from the frame.

For example, if you were to fire an event that was simulating another player in a sudo like command, you may want to add the player you are acting as in the cause and the GameProfile of the player that you are simulating in the context (as the simulated player is not directly responsible for the event being fired.)

Creating a custom Cause with the CauseStackManager

In this example, the variables would be populated, the cause would contain the playerToSimulate as the root cause, the sourceRunningSudo as the second object in the cause and the GameProfile as the EventContextKeys#PLAYER_SIMULATED context, in addition to anything already in the CauseStackManager. Your event code would be at the bottom of the method.

CommandSource sourceRunningSudo = ...;
Player playerToSimulate = ...;
try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {

  frame.pushCause(sourceRunningSudo);
  frame.pushCause(playerToSimulate);

  frame.addContext(EventContextKeys.PLAYER_SIMULATED, playerToSimulate.getProfile());

  Cause cause = frame.getCurrentCause();
}

Note that the last item you push to the cause stack will be the root of the Cause as stacks are „last in, first out” (LIFO) structures.

Wskazówka

For more information about the stack data type and why the order matters, see the Stack javadocs or this Wikipedia article.

Using the Cause Builder

If you are creating an event that does not fire on the main thread, you cannot use the CauseStackManager. Instead, you will need to create a Cause object manually.

Creating a cause object is easy using the Cause.Builder. You can obtain a builder by calling Cause.builder(). To add a cause to the builder, use the Cause.Builder#append(Object) method, but note that unlike the CauseStackManager, the first element you add will be the root, not the last.

If you wish to add contexts, there is a separate builder for those, the EventContext.Builder, accessed by calling EventContext#builder(). The EventContext can then be added using the Cause.Builder#build(EventContext) when you have finished building the Cause up.

Taking the previous example, this is how we would build it using the cause builder.

Creating a custom Cause with the Cause and EventContext builders

Note that in this example, the variables would be populated, and that the first entry appended to the cause would be the root cause.

CommandSource sourceRunningSudo = ...;
Player playerToSimulate = ...;
PluginContainer plugin = ...;

EventContext context = EventContext.builder()
  .add(EventContextKeys.PLAYER_SIMULATED, playerToSimulate.getProfile())
  .add(EventContextKeys.PLUGIN, plugin)
  .build();

Cause cause = Cause.builder()
  .append(playerToSimulate)
  .append(sourceRunningSudo)
  .append(plugin)
  .build(context);

Think carefully about what information to include in your cause. If you’re firing an event from your plugin which is usually triggered through other means, it is a good idea to include your PluginContainer in the cause so other plugins know that the event comes from your plugin. If you are firing the event on behalf of a player due to some action it’s usually a good idea to include that player in the cause.