<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-GB">
	<id>https://forge.gemwire.uk/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Random832</id>
	<title>Forge Community Wiki - User contributions [en-gb]</title>
	<link rel="self" type="application/atom+xml" href="https://forge.gemwire.uk/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Random832"/>
	<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/wiki/Special:Contributions/Random832"/>
	<updated>2026-04-30T16:28:04Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.35.0</generator>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=SimpleChannel&amp;diff=3375</id>
		<title>SimpleChannel</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=SimpleChannel&amp;diff=3375"/>
		<updated>2023-03-10T03:01:01Z</updated>

		<summary type="html">&lt;p&gt;Random832: /* Registering Packets */ fix errors and demonstrate new builder&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;SimpleChannel is the name given to the packet system that revolves around the &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;SimpleChannel&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; class. Using this system is by far the easiest way to send custom data between clients and the server.&lt;br /&gt;
&lt;br /&gt;
== Getting Started ==&lt;br /&gt;
&lt;br /&gt;
First you need to create your &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;SimpleChannel&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; object. We recommend that you do this in a separate class, possibly something like &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;ModidPacketHandler&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;. Create your &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;SimpleChannel&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; as a static field in this class, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
private static final String PROTOCOL_VERSION = &amp;quot;1&amp;quot;;&lt;br /&gt;
public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel(&lt;br /&gt;
    new ResourceLocation(&amp;quot;mymodid&amp;quot;, &amp;quot;main&amp;quot;),&lt;br /&gt;
    () -&amp;gt; PROTOCOL_VERSION,&lt;br /&gt;
    PROTOCOL_VERSION::equals,&lt;br /&gt;
    PROTOCOL_VERSION::equals&lt;br /&gt;
);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The first argument is a name for the channel. The second argument is a &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;Supplier&amp;lt;String&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; returning the current network protocol version. The third and fourth arguments respectively are &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;Predicate&amp;lt;String&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; checking whether an incoming connection protocol version is network-compatible with the client or server, respectively.&lt;br /&gt;
Here, we simply compare with the &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;PROTOCOL_VERSION&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; field directly, meaning that the client and server &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;PROTOCOL_VERSION&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;s must always match or FML will deny login.&lt;br /&gt;
&lt;br /&gt;
== Protocol Versions ==&lt;br /&gt;
If your mod does not require the other side to have a specific network channel, or to be a Forge instance at all, you should take care that you properly define your version compatibility checkers (the &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;Predicate&amp;lt;String&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; parameters) to handle additional &amp;quot;meta-versions&amp;quot; (defined in &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;NetworkRegistry&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;) that can be received by the version checker. These are:&lt;br /&gt;
* &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;ABSENT&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; - if this channel is missing on the other endpoint. Note that in this case, the endpoint is still a Forge endpoint, and may have other mods.&lt;br /&gt;
* &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;ACCEPTVANILLA&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; - if the endpoint is a vanilla (or non-Forge) endpoint.&lt;br /&gt;
&lt;br /&gt;
Returning &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;false&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; for both means that this channel must be present on the other endpoint. If you just copy the code above, this is what it does. Note that these values are also used during the list ping compatibility check, which is responsible for showing the green check / red cross in the multiplayer server select screen.&lt;br /&gt;
&lt;br /&gt;
== Registering Packets ==&lt;br /&gt;
&lt;br /&gt;
Next, we must declare the types of messages that we would like to send and receive. This is done using the &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;INSTANCE.registerMessage&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; method, which takes 5 parameters.&lt;br /&gt;
&lt;br /&gt;
* The first parameter is the discriminator for the packet. This is a per-channel unique ID for the packet. We recommend you use a local variable to hold the ID, and then call registerMessage using &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;id++&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;. This will guarantee 100% unique IDs.&lt;br /&gt;
* The second parameter is the actual packet class &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;MSG&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;.&lt;br /&gt;
* The third parameter is a &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;BiConsumer&amp;lt;MSG, FriendlyByteBuf&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; responsible for encoding the message into the provided &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;FriendlyByteBuf&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
* The fourth parameter is a &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;Function&amp;lt;FriendlyByteBuf, MSG&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; responsible for decoding the message from the provided &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;FriendlyByteBuf&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
* The final parameter is a &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;BiConsumer&amp;lt;MSG, Supplier&amp;lt;NetworkEvent.Context&amp;gt;&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; responsible for handling the message itself&lt;br /&gt;
&lt;br /&gt;
The last three parameters can be method references to either static or instance methods in Java. Remember that an instance method &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;MSG.encode(FriendlyByteBuf)&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; still satisfies &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;BiConsumer&amp;lt;MSG, FriendlyByteBuf&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;, the &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;MSG&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; simply becomes the implicit first argument.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
class MessagePacket {&lt;br /&gt;
   public void encoder(FriendlyByteBuf buffer) {&lt;br /&gt;
      // Write to buffer&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
   public static MessagePacket decoder(FriendlyByteBuf buffer) {&lt;br /&gt;
      // Create packet from buffer data&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
   public void messageConsumer(Supplier&amp;lt;NetworkEvent.Context&amp;gt; ctx) {&lt;br /&gt;
      // Handle message&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// Original direct registration syntax&lt;br /&gt;
INSTANCE.registerMessage(id, MessagePacket.class,&lt;br /&gt;
   MessagePacket::encoder,&lt;br /&gt;
   MessagePacket::decoder,&lt;br /&gt;
   MessagePacket::messageConsumer);&lt;br /&gt;
   // Consumer here must use enqueueWork and setPacketHandled&lt;br /&gt;
&lt;br /&gt;
// New builder-based definition&lt;br /&gt;
INSTANCE.messageBuilder(MessagePacket.class, id)&lt;br /&gt;
   .encoder(MessagePacket::encoder)&lt;br /&gt;
   .decoder(MessagePacket::decoder)&lt;br /&gt;
   .consumerMainThread(MessagePacket::messageConsumer);&lt;br /&gt;
// You can use consumerMainThread or consumerNetworkThread.&lt;br /&gt;
// If you use consumerMainThread, the builder will take care of the enqueueWork and setPacketHandled.&lt;br /&gt;
// With consumerNetworkThread, you can return a value instead of calling setPacketHandled.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Handling Packets ==&lt;br /&gt;
&lt;br /&gt;
There are a couple things to highlight in a packet handler. A packet handler has both the message object and the network context available to it. The context allows access to the player that sent the packet (if on the server), and a way to enqueue threadsafe work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static void handle(MyMessage msg, Supplier&amp;lt;NetworkEvent.Context&amp;gt; ctx) {&lt;br /&gt;
    ctx.get().enqueueWork(() -&amp;gt; {&lt;br /&gt;
        // Work that needs to be threadsafe (most work)&lt;br /&gt;
        ServerPlayer sender = ctx.get().getSender(); // the client that sent this packet&lt;br /&gt;
        // do stuff&lt;br /&gt;
    });&lt;br /&gt;
    ctx.get().setPacketHandled(true);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Packets sent from the server to the client should be handled in another class and wrapped via &amp;lt;code&amp;gt;DistExecutor#unsafeRunWhenOn&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// In Packet class&lt;br /&gt;
public static void handle(MyClientMessage msg, Supplier&amp;lt;NetworkEvent.Context&amp;gt; ctx) {&lt;br /&gt;
    ctx.get().enqueueWork(() -&amp;gt;&lt;br /&gt;
        // Make sure it's only executed on the physical client&lt;br /&gt;
        DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -&amp;gt; () -&amp;gt; ClientPacketHandlerClass.handlePacket(msg, ctx))&lt;br /&gt;
    );&lt;br /&gt;
    ctx.get().setPacketHandled(true);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// In ClientPacketHandlerClass&lt;br /&gt;
public static void handlePacket(MyClientMessage msg, Supplier&amp;lt;NetworkEvent.Context&amp;gt; ctx) {&lt;br /&gt;
    // Do stuff&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the presence of &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;#setPacketHandled&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;, which used to tell the network system that the packet has successfully completed handling.&lt;br /&gt;
&lt;br /&gt;
=== Common Packet Handling Pitfalls ===&lt;br /&gt;
&lt;br /&gt;
{{Colored box|title=Know that packets are by default handled on the network thread.|content=&lt;br /&gt;
That means that your handler can ''not'' interact with most game objects directly.&lt;br /&gt;
Forge provides a convenient way to make your code execute on the main thread through the supplied &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;NetworkEvent$Context&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;.&lt;br /&gt;
Simply call &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;NetworkEvent$Context#enqueueWork(Runnable)&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;, which will call the given &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;Runnable&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; on the main thread at the next opportunity.}}&lt;br /&gt;
&lt;br /&gt;
{{Colored box|title=Be defensive when handling packets on the server.|content=&lt;br /&gt;
A client could attempt to exploit the packet handling by sending unexpected data.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
A common problem is vulnerability to &amp;lt;code&amp;gt;arbitrary chunk generation&amp;lt;/code&amp;gt;. This typically happens when the server is trusting a block position sent by a client to access blocks and block entities. When accessing blocks and block entities in unloaded areas of the level, the server will either generate or load this area from disk, then promply write it to disk. This can be exploited to cause &amp;lt;code&amp;gt;catastrophic damage&amp;lt;/code&amp;gt; to a server's performance and storage space without leaving a trace.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
To avoid this problem, a general rule of thumb is to only access blocks and block entities if &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;Level#hasChunkAt&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; is true.}}&lt;br /&gt;
&lt;br /&gt;
{{Colored box|title=Register encoders on the physical client, as well as the physical server.|content=&lt;br /&gt;
If you only register an encoder for a clientbound packet on the physical server, your mod will likely crash or present unintended behaviour in single-player worlds. ''Forge will happily send packets that have no encoder defined, '''without a warning or error message!''''' They will be encoded as a 256-long byte buffer filled only with null bytes, by default.&lt;br /&gt;
&amp;lt;br&amp;gt;}}&lt;br /&gt;
&lt;br /&gt;
== Sending Packets ==&lt;br /&gt;
&lt;br /&gt;
=== Sending to the Server ===&lt;br /&gt;
&lt;br /&gt;
There is but one way to send a packet to the server. This is because there is only ever *one* server the client can be connected to at once. To do so, we must again use that &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;SimpleChannel&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; that was defined earlier. Simply call &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;INSTANCE.sendToServer(new MyMessage())&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;. The message will be sent to the handler for its type, if one exists.&lt;br /&gt;
&lt;br /&gt;
=== Sending to Clients ===&lt;br /&gt;
&lt;br /&gt;
Packets can be sent directly to a client using the &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;SimpleChannel&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;: &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;HANDLER.sendTo(MSG, serverPlayer.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT)&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;. However, this can be quite inconvenient. Forge has some convenience functions that can be used:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// Sending to one player&lt;br /&gt;
INSTANCE.send(PacketDistributor.PLAYER.with(serverPlayer), new MyMessage());&lt;br /&gt;
&lt;br /&gt;
// Send to all players tracking this level chunk&lt;br /&gt;
INSTANCE.send(PacketDistributor.TRACKING_CHUNK.with(levelChunk), new MyMessage());&lt;br /&gt;
&lt;br /&gt;
// Sending to all connected players&lt;br /&gt;
INSTANCE.send(PacketDistributor.ALL.noArg(), new MyMessage());&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There are additional &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;PacketDistributor&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; types available, check the documentation on the &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;PacketDistributor&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt; class for more details.&lt;/div&gt;</summary>
		<author><name>Random832</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=Template:!!&amp;diff=3374</id>
		<title>Template:!!</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=Template:!!&amp;diff=3374"/>
		<updated>2023-03-04T19:52:08Z</updated>

		<summary type="html">&lt;p&gt;Random832: Created page with &amp;quot;||&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;||&lt;/div&gt;</summary>
		<author><name>Random832</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=Capabilities&amp;diff=3373</id>
		<title>Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=Capabilities&amp;diff=3373"/>
		<updated>2023-03-04T19:49:45Z</updated>

		<summary type="html">&lt;p&gt;Random832: fix code snippet with workaround&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Capabilities''' are a Forge system that allows cross-mod interactions by allowing capability ''providers'' to&lt;br /&gt;
dynamically respect contracts and provide specialized behavior without requiring the implementation of many interfaces&lt;br /&gt;
or hard dependencies on mods.&lt;br /&gt;
&lt;br /&gt;
== History ==&lt;br /&gt;
In an ideal world, all that would be needed for a mod to provide the equivalent of a capability would be implementing an&lt;br /&gt;
interface. This is in fact how cross-mod interaction used to work prior to the introduction of capabilities.&lt;br /&gt;
&lt;br /&gt;
The real world, though, is often much more complicated: users wanted to be free to combine mods the way they wanted and&lt;br /&gt;
saw fit, and developers wanted to be able to declare ''soft'' dependencies on other mods, thus reducing the need of&lt;br /&gt;
having a huge mod pack just for testing.&lt;br /&gt;
&lt;br /&gt;
The first approach used by Forge was conditional stripping of interfaces and methods, but this proved to be problematic.&lt;br /&gt;
While the idea works well in theory, in practice the ASM editing of classes relied on complex mechanics and could lead&lt;br /&gt;
to hard to spot bugs.&lt;br /&gt;
&lt;br /&gt;
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.&lt;br /&gt;
&lt;br /&gt;
== The Concept ==&lt;br /&gt;
A capability allows any capability provider to conditionally expose a certain ability to do something, e.g. accepting&lt;br /&gt;
power or handling items. A capability provider, moreover, can decide to expose a capability only on certain sides,&lt;br /&gt;
allowing for easy interactions with hoppers, cables, etc.&lt;br /&gt;
&lt;br /&gt;
Capabilities may also be added and removed dynamically both from the &amp;quot;owner&amp;quot; of the capability provider and other mods,&lt;br /&gt;
allowing even easier cross-mod interaction. For example, a mod that isn't compatible with Forge Energy could be&lt;br /&gt;
converted into one by dynamically attaching the Forge Energy capability and handling the conversion to a third-party&lt;br /&gt;
energy system without having to alter the original mod.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
The high flexibility of the system comes with a cost, though, which is terminology. The following section wants to be a&lt;br /&gt;
dictionary of sorts, defining all the terms that you may come across when dealing with capabilities.&lt;br /&gt;
&lt;br /&gt;
In the rest of this article, we will refer to these terms frequently, so make sure you are familiar with them.&lt;br /&gt;
&lt;br /&gt;
; Capability&lt;br /&gt;
: the ability to perform something. In-code this is represented by the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; class.&lt;br /&gt;
; Capability Provider&lt;br /&gt;
: something that is able to support capabilities and provides a mean of accessing them. In-code they are represented by implementations of &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;. There are multiple kinds of capability providers:&lt;br /&gt;
:; Volatile Provider&lt;br /&gt;
:: a provider that doesn't persist data to disk; once the provider ceases to exist for any number of reasons, all capability data gets deleted.&lt;br /&gt;
:; Persistent Provider&lt;br /&gt;
:: a provider that requires all capabilities to serialize data to disk, in order to persist data even across game restarts. They implement the &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
:; Agnostic Provider&lt;br /&gt;
:: a provider that isn't neither volatile nor persistent, rather delegates the decision either to the capability directly or to sub-implementations. They also implement the &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
; Capability Interface&lt;br /&gt;
: the interface that defines the contract of the capability, so what operations the capability exposes.&lt;br /&gt;
; Capability Implementation&lt;br /&gt;
: one of the possibly many implementations of the capability interface, that actually carries out the work.&lt;br /&gt;
&lt;br /&gt;
The wary reader may note that both ''persistent'' and ''agnostic'' providers are represented the same way in code. In&lt;br /&gt;
fact, the only difference between them comes from pure semantics in how their serialization methods are designed. This&lt;br /&gt;
will be further discussed in their respective sections.&lt;br /&gt;
&lt;br /&gt;
Moreover, it is also common to refer to the capability interface as simply the ''capability''. While not strictly&lt;br /&gt;
correct, due to common usage we will also use this convention. So, to refer to the capability interface&lt;br /&gt;
&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt;, we will usually talk about the &amp;quot;&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities and Providers ==&lt;br /&gt;
In order to ensure mods can work together seamlessly, Forge provides a set of default capabilities and capability&lt;br /&gt;
providers.&lt;br /&gt;
&lt;br /&gt;
The default capability providers in a Forge environment are: &amp;lt;code&amp;gt;BlockEntity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entity&amp;lt;/code&amp;gt;,&lt;br /&gt;
&amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Level&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;LevelChunk&amp;lt;/code&amp;gt;. These are all agnostic providers, since they don't&lt;br /&gt;
mandate any sort of capability persistency requirements. Rather, it is the job of whoever subclasses these providers to&lt;br /&gt;
deal with either volatile or non-volatile capabilities.&lt;br /&gt;
&lt;br /&gt;
The default capabilities that forge provides are represented by the interfaces &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;,&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;. Each one of these capabilities will be discussed in the corresponding section.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IItemHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to have some sort of internal&lt;br /&gt;
'''inventory''' with a certain number of slots, from which items can be inserted and extracted. It is also possible,&lt;br /&gt;
though, to expose this capability even if no such inventory is present as long as the capability provider can emulate&lt;br /&gt;
its presence (e.g. tools that allow accessing remote inventories).&lt;br /&gt;
&lt;br /&gt;
This effectively '''replaces''' the vanilla interfaces &amp;lt;code&amp;gt;Container&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;WorldlyContainer&amp;lt;/code&amp;gt;. These&lt;br /&gt;
interfaces are in fact retained only to allow vanilla code to compile and should not be used in mod code. This extends&lt;br /&gt;
to anything that implements those vanilla interfaces, such as &amp;lt;code&amp;gt;RandomizableContainerBlockEntity&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to handle and store fluids&lt;br /&gt;
in one or multiple fluid tanks. It is effectively the equivalent in terms of fluids of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;&lt;br /&gt;
capability.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;TileFluidHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandlerItem&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt; capability refers to the ability for an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt; capability provider&lt;br /&gt;
to handle and store fluids in one or multiple fluid tanks. It is basically a specialized version of the&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability that allows &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s to define a custom container.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IEnergyStorage&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to store, consume, and&lt;br /&gt;
produce energy. This capability is the base capability for what's commonly known in the modded world as Forge Energy (or&lt;br /&gt;
FE), i.e. the energy system most mods use. Its internal design is heavily based on the (now defunct) Redstone Flux&lt;br /&gt;
Energy API, supporting both a push and pull system.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;EnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
== Working with Capabilities ==&lt;br /&gt;
&lt;br /&gt;
Both capability providers and users need to be able to provide and access capabilities through a common framework,&lt;br /&gt;
otherwise the ideal of dynamic and mod-agnostic would not really exist. For this reason, both capability providers and&lt;br /&gt;
capability ''accessors'' (which we define as everything that wants to access a capability), also known as '''clients''' or '''users''',&lt;br /&gt;
need to work together and with Forge to ensure that the common interface is used sensibly and correctly by all parties.&lt;br /&gt;
&lt;br /&gt;
=== Obtaining a Capability ===&lt;br /&gt;
&lt;br /&gt;
Before being able to work with a capability, it is necessary to obtain an instance of the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; object itself.&lt;br /&gt;
&lt;br /&gt;
A &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; can obtained at any time using &amp;lt;code&amp;gt;CapabilityManager#get&amp;lt;/code&amp;gt;. This takes in an anonymous &amp;lt;code&amp;gt;CapabilityToken&amp;lt;/code&amp;gt; to still allow for a soft dependency system while also keeping hold of any generic information needed. As such, you can always obtain a non-null capability.&lt;br /&gt;
&lt;br /&gt;
{{Tabs/Code Snippets&lt;br /&gt;
|java=&lt;br /&gt;
public static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER = CapabilityManager.get(new CapabilityToken&amp;lt;&amp;gt;(){});&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
The above code will let Forge know that the field &amp;lt;code&amp;gt;ITEM_HANDLER&amp;lt;/code&amp;gt; should be analogous with the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability. Note that this does not mean the capability is accessible or registered. To check if it is, call &amp;lt;code&amp;gt;Capability#isRegistered&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
This is, for obvious reasons, redundant, since that capability is also available through&lt;br /&gt;
&amp;lt;code&amp;gt;ForgeCapabilities&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Exposing a Capability ===&lt;br /&gt;
&lt;br /&gt;
Exposing a capability is a voluntary act by a capability provider that allows the capability to be discovered and&lt;br /&gt;
accessed by users.&lt;br /&gt;
&lt;br /&gt;
To do so, a capability provider needs to juggle a couple more moving pieces to ensure that the capability state remains&lt;br /&gt;
consistent and that the lookup remains fast. It is in fact possible for a capability provider to be asked to provide&lt;br /&gt;
many capabilities many times in the same tick. For this reason, a provider is asked to do the following:&lt;br /&gt;
&lt;br /&gt;
* the &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt;s that get returned '''must be cached''';&lt;br /&gt;
* if a capability changes exposure state (more on this later), all listeners '''must be notified''';&lt;br /&gt;
* if a capability gets invalidated (more on this later), all listeners '''must be notified'''&lt;br /&gt;
* the lookup inside &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; must be performed with '''an &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;-&amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; chain''';&lt;br /&gt;
* all unexposed but still present capabilities '''should be available''' if the provider is queried with a &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; direction (see ''Accessing a Capability'' for more information);&lt;br /&gt;
* if no capability of a given type is available or accessible, the provider '''must call &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; as long as it is possible to do so'''.&lt;br /&gt;
&lt;br /&gt;
Capability providers must also reflect changes in the ''exposure state'' of a capability, meaning that if the&lt;br /&gt;
accessibility of a capability from a certain &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt; changes (refer to&lt;br /&gt;
[[#Accessing a Capability|Accessing a Capability]] for more information), it is the provider's responsibility to trigger&lt;br /&gt;
a state response by invalidating the returned &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; and caching a new one. This should also be&lt;br /&gt;
performed when a capability gets ''invalidated'', such as when a capability provider gets removed.&lt;br /&gt;
&lt;br /&gt;
With all of the above in mind, part of a capability provider implementation may be similar to the following snippet:&lt;br /&gt;
&lt;br /&gt;
{{Tabs/Code Snippets&lt;br /&gt;
|java=&lt;br /&gt;
// suppose the presence of a field 'inventory' of type 'IItemHandler'&lt;br /&gt;
&lt;br /&gt;
private final LazyOptional&amp;lt;IItemhandler&amp;gt; inventoryOptional = LazyOptional.of(() -&amp;gt; this.inventory);&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; capability, @Nullable Direction direction) {&lt;br /&gt;
    if (capability == ForgeCapabilities.ITEM_HANDLER&lt;br /&gt;
            &amp;amp;&amp;amp; (direction == null {{!}}{{!}} direction == Direction.UP {{!}}{{!}} direction == Direction.DOWN)) {&lt;br /&gt;
        return this.inventoryOptional.cast();&lt;br /&gt;
    }&lt;br /&gt;
    return super.getCapability(capability, direction); // See note after snippet&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
    super.invalidateCaps();&lt;br /&gt;
    this.inventoryOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
This possible implementation of a capability provider exposes an &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability and restricts&lt;br /&gt;
access only to the &amp;lt;code&amp;gt;UP&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;DOWN&amp;lt;/code&amp;gt; directions. If we assume this capability provider is a&lt;br /&gt;
&amp;lt;code&amp;gt;BlockEntity&amp;lt;/code&amp;gt;, then we may also say that the inventory is only accessible from the top and the bottom of the&lt;br /&gt;
block.&lt;br /&gt;
&lt;br /&gt;
Moreover, the capability gets automatically invalidated when the provider gets invalidated. Assuming this is a&lt;br /&gt;
&amp;lt;code&amp;gt;BlockEntity&amp;lt;/code&amp;gt;, this usually happens when the block gets removed from the level or unloaded due to distance.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; call at the end of the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; method is extremely important, since it's what&lt;br /&gt;
allows Attaching external Capabilities to capability providers. Nevertheless, it is not always possible to invoke&lt;br /&gt;
&amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;: in those cases, an empty &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; should be returned.&lt;br /&gt;
&lt;br /&gt;
=== Attaching a Capability ===&lt;br /&gt;
&lt;br /&gt;
Attaching a Capability is a process by which external agents &amp;quot;modify&amp;quot; a Capability Provider, making it expose additional&lt;br /&gt;
capabilities other than the already available ones.&lt;br /&gt;
&lt;br /&gt;
To do so, the '''attaching agent''' (which means the thing that wants to attach a capability to another provider) must&lt;br /&gt;
listen to the &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;. The &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; in this case represents the capability&lt;br /&gt;
provider you want to attach the capability to. Note that the type of &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; '''must''' be the base type of the&lt;br /&gt;
capability provider, not a subclass. As an example, if you want to attach a capability to a &amp;lt;code&amp;gt;MyBlockEntity&amp;lt;/code&amp;gt;,&lt;br /&gt;
which extends &amp;lt;code&amp;gt;BlockEntity&amp;lt;/code&amp;gt;, you'll have to listen to &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;BlockEntity&amp;amp;gt;&amp;lt;/code&amp;gt;,&lt;br /&gt;
'''NOT''' to &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;MyBlockEntity&amp;amp;gt;&amp;lt;/code&amp;gt;, since the latter will never fire.&lt;br /&gt;
&lt;br /&gt;
The attaching agent can use the provided methods &amp;lt;code&amp;gt;getObject&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;addCapability&amp;lt;/code&amp;gt;, and &lt;br /&gt;
&amp;lt;code&amp;gt;addListener&amp;lt;/code&amp;gt; to check whether the capability should be attached to the current object and perform the&lt;br /&gt;
desired action.&lt;br /&gt;
&lt;br /&gt;
When attaching a capability, the attaching agent should also provide a name in the form of a&lt;br /&gt;
&amp;lt;code&amp;gt;ResourceLocation&amp;lt;/code&amp;gt;. The name '''must''' be under the attaching agent's namespace, but no restrictions are&lt;br /&gt;
placed on the actual name, as long as it is unique inside the given namespace.&lt;br /&gt;
&lt;br /&gt;
Maybe a little counter-intuitively, the process of attaching does not attach a capability nor a capability interface&lt;br /&gt;
directly. Rather, the attaching agent should create its own implementation of a '''Capability Provider''' and attach it&lt;br /&gt;
via the event. This is done so that the attaching agent can have control over when, how, and where its capabilities are&lt;br /&gt;
exposed, instead of relying on the game itself deciding these parameters. For this reason, all considerations given in&lt;br /&gt;
the [[#Exposing a Capability|Exposing a Capability]] section on how to correctly create a Capability Provider.&lt;br /&gt;
&lt;br /&gt;
With the above in mind, part of an attaching agent may be similar to the following snippet of code:&lt;br /&gt;
&lt;br /&gt;
{{Tabs/Code Snippets&lt;br /&gt;
|java=&lt;br /&gt;
@SubscribeEvent&lt;br /&gt;
public void onAttachingCapabilities(final AttachCapabilitiesEvent&amp;lt;BlockEntity&amp;gt; event) {&lt;br /&gt;
    if (!(event.getObject() instanceof EnergyBasedBlockEntity)) return;&lt;br /&gt;
&lt;br /&gt;
    EnergyStorage backend = new EnergyStorage(((EnergyBasedBlockEntity) event.getObject()).capacity);&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; optionalStorage = LazyOptional.of(() -&amp;gt; backend);&lt;br /&gt;
&lt;br /&gt;
    ICapabilityProvider provider = new ICapabilityProvider() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, @Nullable Direction direction) {&lt;br /&gt;
            if (cap == ForgeCapabilities.ENERGY) {&lt;br /&gt;
                return optionalStorage.cast();&lt;br /&gt;
            }&lt;br /&gt;
            return LazyOptional.empty();&lt;br /&gt;
        }&lt;br /&gt;
    };&lt;br /&gt;
&lt;br /&gt;
    event.addCapability(new ResourceLocation(&amp;quot;examplemod&amp;quot;, &amp;quot;fe_compatibility&amp;quot;), provider);&lt;br /&gt;
}&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
This example implementation of an attaching agent attaches a &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability to all&lt;br /&gt;
&amp;lt;code&amp;gt;BlockEntity&amp;lt;/code&amp;gt; instance that are a subclass of &amp;lt;code&amp;gt;EnergyBasedBlockEntity&amp;lt;/code&amp;gt;. It also sets up the&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; for invalidation if the parent capability provider gets invalidated.&lt;br /&gt;
&lt;br /&gt;
Note also the call of &amp;lt;code&amp;gt;LazyOptional.empty()&amp;lt;/code&amp;gt; rather than a &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;. This is needed because when&lt;br /&gt;
attaching a capability, the parent capability provider isn't known. For this reason, it is necessary to return an empty&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt;. The game will then handle automatic merging of the various different providers into a single&lt;br /&gt;
one.&lt;br /&gt;
&lt;br /&gt;
The above example is one of a '''Volatile''' Capability Provider. On the other hand, mods may want to persist their&lt;br /&gt;
data across sessions. In this case, they should attach a '''Persistent''' Capability Provider: this can be done either&lt;br /&gt;
by implementing the &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface along with &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; or by&lt;br /&gt;
implementing the &amp;lt;code&amp;gt;ICapabilitySerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
The previous example reworked to use a Persistent Capability Provider may be similar to the following snippet:&lt;br /&gt;
&lt;br /&gt;
{{Tabs/Code Snippets&lt;br /&gt;
|java=&lt;br /&gt;
@SubscribeEvent&lt;br /&gt;
public void onAttachingCapabilities(final AttachCapabilitiesEvent&amp;lt;BlockEntity&amp;gt; event) {&lt;br /&gt;
    if (!(event.getObject() instanceof EnergyBasedBlockEntity)) return;&lt;br /&gt;
&lt;br /&gt;
    EnergyStorage backend = new EnergyStorage(((EnergyBasedBlockEntity) event.getObject()).capacity);&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; optionalStorage = LazyOptional.of(() -&amp;gt; backend);&lt;br /&gt;
    Capability&amp;lt;IEnergyStorage&amp;gt; capability = ForgeCapabilities.ENERGY;&lt;br /&gt;
&lt;br /&gt;
    ICapabilityProvider provider = new ICapabilitySerializable&amp;lt;IntTag&amp;gt;() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, @Nullable Direction direction) {&lt;br /&gt;
            if (cap == capability) {&lt;br /&gt;
                return optionalStorage.cast();&lt;br /&gt;
            }&lt;br /&gt;
            return LazyOptional.empty();&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        @Override&lt;br /&gt;
        public IntTag serializeNBT() {&lt;br /&gt;
            return backend.serializeNBT();&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        @Override&lt;br /&gt;
        public void deserializeNBT(IntTag tag) {&lt;br /&gt;
            backend.deserializeNBT(tag);&lt;br /&gt;
        }&lt;br /&gt;
    };&lt;br /&gt;
&lt;br /&gt;
    event.addCapabilities(new ResourceLocation(&amp;quot;examplemod&amp;quot;, &amp;quot;fe_compatibility&amp;quot;), provider);&lt;br /&gt;
}&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Note that when using capabilities on entities, you should manually invalidate the capability via &amp;lt;code&amp;gt;invalidateCaps()&amp;lt;/code&amp;gt;, via etc. &amp;lt;code&amp;gt;PlayerEvent.Clone&amp;lt;/code&amp;gt;. This is due to the fact that players are recreated &amp;amp; copied when moving across dimensions, not simply moved.&lt;br /&gt;
&lt;br /&gt;
=== Accessing a Capability ===&lt;br /&gt;
&lt;br /&gt;
Accessing a Capability is the process by which a user is able to '''query''' a Capability Provider for a specific&lt;br /&gt;
instance of a capability.&lt;br /&gt;
&lt;br /&gt;
This is perhaps the second most important part of the entire capability system, since it is what allows cross-mod&lt;br /&gt;
interaction. To obtain an instance of a Capability, the user must first get a hold of the Capability Provider that&lt;br /&gt;
should be queried. This can be done in a variety of ways and is outside the scope of this article. The user should&lt;br /&gt;
then invoke the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; method passing the unique instance of the capability that should be queried&lt;br /&gt;
(see [[#Obtaining a Capability|Obtaining a Capability]] for more information) and the querying &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;,&lt;br /&gt;
if applicable.&lt;br /&gt;
&lt;br /&gt;
The returned object is a &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; wrapping the queried Capability, if the capability provider exposes&lt;br /&gt;
it, otherwise it will be empty. The &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; can be either unwrapped via an &amp;lt;code&amp;gt;orElse&amp;lt;/code&amp;gt; or&lt;br /&gt;
used directly via &amp;lt;code&amp;gt;ifPresent&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
It is '''highly suggested''' to cache the returned &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; to avoid querying the same provider every&lt;br /&gt;
time, in order to improve performance. The user should thus register itself to the invalidation listener via the&lt;br /&gt;
&amp;lt;code&amp;gt;addListener&amp;lt;/code&amp;gt; method. This ensures that the user will be able to react to the invalidation of the&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; and remove it from the cache.&lt;br /&gt;
&lt;br /&gt;
With the above in mind, part of an user may be similar to the following snippet of code:&lt;br /&gt;
&lt;br /&gt;
{{Tabs/Code Snippets&lt;br /&gt;
|java=&lt;br /&gt;
// note the use of EnumMap, which is much more performant than HashMap for enum keys&lt;br /&gt;
private final Map&amp;lt;Direction, LazyOptional&amp;lt;IEnergyStorage&amp;gt;&amp;gt; cache = new EnumMap&amp;lt;&amp;gt;(Direction.class);&lt;br /&gt;
&lt;br /&gt;
private void sendPowerTo(int power, Direction direction) {&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; targetCapability = cache.get(direction);&lt;br /&gt;
&lt;br /&gt;
    if (targetCapability == null) {&lt;br /&gt;
        ICapabilityProvider provider = level.getBlockEntity(pos.relative(direction));&lt;br /&gt;
        targetCapability = provider.getCapability(ForgeCapabilities.ENERGY, direction.getOpposite());&lt;br /&gt;
        cache.put(direction, targetCapability);&lt;br /&gt;
        targetCapability.addListener(self -&amp;gt; cache.put(direction, null));&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    targetCapability.ifPresent(storage -&amp;gt; storage.receiveEnergy(power, false));&lt;br /&gt;
}&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
This example implementation of an user is querying via a &amp;lt;code&amp;gt;BlockEntity&amp;lt;/code&amp;gt; the neighboring capability provider&lt;br /&gt;
for an &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability. Before obtaining the provider, the code performs a cache lookup for the&lt;br /&gt;
targeted capability. If the check succeeds, then no lookup is performed; if the check fails, the targeted Capability&lt;br /&gt;
Provider is obtained and queried for the Capability. The obtained &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; is then cached and a&lt;br /&gt;
listener is attached to it so that the cache would be emptied on invalidation. The code then continues with the&lt;br /&gt;
interaction with the capability, which is outside the scope of this article.&lt;br /&gt;
&lt;br /&gt;
== Creating Custom Capabilities ==&lt;br /&gt;
&lt;br /&gt;
While the various capabilities provided by Forge may satisfy the most common use cases, there is always the chance that&lt;br /&gt;
a mod may require a custom solution. For this reason, Forge provides a way to define a custom Capability.&lt;br /&gt;
&lt;br /&gt;
Defining a custom Capability requires the user to provide one main component: the Capability Interface. Optionally, a &lt;br /&gt;
Capability Implementation and Capability Provider can also be created. In this&lt;br /&gt;
case, the provider will be used as described in [[#Attaching a Capability|Attaching a Capability]]. The various details &lt;br /&gt;
for all these components are described in the respective sections of this article.&lt;br /&gt;
&lt;br /&gt;
In this section, we will refer to the implementation of a &amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability, that can be used to&lt;br /&gt;
store a single mutable &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Refer also to [[#Code Examples|Code Examples]] for an example on how the various components may be implemented in a&lt;br /&gt;
real-world scenario.&lt;br /&gt;
&lt;br /&gt;
=== The Capability Interface and the Capability Implementation ===&lt;br /&gt;
&lt;br /&gt;
The Capability Interface is one of the most important parts of a Capability: without it, the Capability effectively does&lt;br /&gt;
not exist. Designing a Capability Interface is exactly like designing any Java interface, so the particular details will&lt;br /&gt;
be glossed over in this section.&lt;br /&gt;
&lt;br /&gt;
The Capability Implementation, on the other hand, is the implementation of the previously defined Capability Interface.&lt;br /&gt;
Usual rules for interface implementations follow. There can be more than one Capability Implementation for each&lt;br /&gt;
capability. &lt;br /&gt;
&lt;br /&gt;
Note that a '''well-formed''' capability implementation should '''not store''' the Capability Provider inside of it: we&lt;br /&gt;
call the capability implementation ''provider-agnostic''. This is not a hard-requirement, though, rather it should act&lt;br /&gt;
more as a guideline. There are in fact certain situations where this cannot be avoided (e.g. attaching a client-synced&lt;br /&gt;
capability to an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
Given all of the above information, this may be an example implementation of both a Capability Interface and a&lt;br /&gt;
Capability Implementation:&lt;br /&gt;
&lt;br /&gt;
{{Tabs/Code Snippets&lt;br /&gt;
|java=&lt;br /&gt;
public interface MyCapability {&lt;br /&gt;
    String getValue();&lt;br /&gt;
    void setValue(String value);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class MyCapabilityImplementation implements MyCapability {&lt;br /&gt;
    private String value;&lt;br /&gt;
&lt;br /&gt;
    @Override&lt;br /&gt;
    public String getValue() {&lt;br /&gt;
        return this.value;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    @Override&lt;br /&gt;
    public void setValue(String value) {&lt;br /&gt;
        this.value = value;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
Note that in this case, only a single implementation is provided.&lt;br /&gt;
&lt;br /&gt;
=== The Capability Provider ===&lt;br /&gt;
&lt;br /&gt;
The Capability Provider is an optional component of the capability that allows the Capability to be attached to a&lt;br /&gt;
component. The details on how a Capability Provider should behave have already been discussed in the two previous&lt;br /&gt;
sections [[#Exposing a Capability|Exposing a Capability]] and [[#Attaching a Capability|Attaching a Capability]]: refer&lt;br /&gt;
to those for more information.&lt;br /&gt;
&lt;br /&gt;
=== Registering Capabilities ===&lt;br /&gt;
&lt;br /&gt;
Once all components of a Capability have been created, they must be registered so that the game is aware of the&lt;br /&gt;
capability's presence. The registration only requires the Capability Interface.&lt;br /&gt;
After registering, the created Capability will be automatically injected into all relevant fields and methods, see [[#Obtaining a Capability|Obtaining a Capability]] for more information.&lt;br /&gt;
As of Forge 1.19.2-43.1.1, there are two ways to register capabilities.&lt;br /&gt;
&lt;br /&gt;
==== AutoRegisterCapability annotation ====&lt;br /&gt;
On Forge 1.19.2-43.1.1 or higher, a quick and easy way to register a capability is by annotating the Capability Interface with &amp;lt;code&amp;gt;@AutoRegisterCapability&amp;lt;/code&amp;gt;. This would look like so:&lt;br /&gt;
&lt;br /&gt;
{{Tabs/Code Snippets&lt;br /&gt;
|java=&lt;br /&gt;
@AutoRegisterCapability&lt;br /&gt;
public interface MyCapability {&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
==== RegisterCapabilitiesEvent ====&lt;br /&gt;
An alternative way to register capabilities is by calling the &amp;lt;code&amp;gt;register&amp;lt;/code&amp;gt; method within the &amp;lt;code&amp;gt;RegisterCapabilitiesEvent&amp;lt;/code&amp;gt;. This event is fired on the &amp;lt;code&amp;gt;MOD&amp;lt;/code&amp;gt; event bus. For example:&lt;br /&gt;
&lt;br /&gt;
{{Tabs/Code Snippets&lt;br /&gt;
|java=&lt;br /&gt;
@SubscribeEvent&lt;br /&gt;
public void registerCaps(RegisterCapabilitiesEvent event) {&lt;br /&gt;
    event.register(MyCapability.class);&lt;br /&gt;
}&lt;br /&gt;
}}&lt;br /&gt;
&lt;br /&gt;
=== Class Diagram ===&lt;br /&gt;
&lt;br /&gt;
[[File:Custom Capability Class Diagram.svg|800px|thumb|center|Custom Capability Class Diagram]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram the green and red marked areas are classes from Minecraft and Forge respectively. The classes inside the purple area are only needed if you want to [[#Attaching a Capability|Attach a Capability]]. Furthermore this diagram models a persistent provider and its most basic form, for more information on how to create a more complex provider see [[#Custom Capability Providers|Custom Capability Providers]]. To create a volatile provider instead just do not implement &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
== Custom Capability Providers ==&lt;br /&gt;
&lt;br /&gt;
Much like custom Capabilities, Forge also allows the creation of custom Capability Providers. The main advantage of this&lt;br /&gt;
is allowing mods to create custom providers for their custom objects, in order to promote not only cross-mod&lt;br /&gt;
compatibility, but also uniformity in the way users may interact with different mod APIs.&lt;br /&gt;
&lt;br /&gt;
This section will only give the basic outline of what is necessary to implement a custom Capability Provider: for more&lt;br /&gt;
in-depth explanation, people are referred to the game code.&lt;br /&gt;
&lt;br /&gt;
By definition, a custom Capability Provider is everything that implements the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;&lt;br /&gt;
interface. In this section, though, we will only cover people that may want to replicate the functionality of one of&lt;br /&gt;
the default providers, such as &amp;lt;code&amp;gt;BlockEntity&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;LevelChunk&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The easiest way of doing this is extending the &amp;lt;code&amp;gt;CapabilityProvider&amp;lt;/code&amp;gt; class provided by Forge. This will&lt;br /&gt;
automatically set up an ''agnostic'' Capability Provider. To fully initialize the capability provider, the subclass&lt;br /&gt;
should then invoke the &amp;lt;code&amp;gt;gatherCapabilities&amp;lt;/code&amp;gt; method as the last instruction in its constructor, to ensure that&lt;br /&gt;
the game is able to recollect and attach all capabilities that other mods may want to attach to the capability provider.&lt;br /&gt;
&lt;br /&gt;
== Code Examples ==&lt;br /&gt;
&lt;br /&gt;
* [https://gist.github.com/TheCurle/6db954d680f6f067dcdc791355c32c89 A Gist showing a quick and dirty example on how to implement a Capability effectively]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Data Storage]]&lt;/div&gt;</summary>
		<author><name>Random832</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=Datageneration/Loot_Tables&amp;diff=3294</id>
		<title>Datageneration/Loot Tables</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=Datageneration/Loot_Tables&amp;diff=3294"/>
		<updated>2022-06-28T10:55:52Z</updated>

		<summary type="html">&lt;p&gt;Random832: Change to a different approach that is easier to use and works with current versions of Minecraft.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Under construction}}&lt;br /&gt;
&lt;br /&gt;
==The LootTableProvider class==&lt;br /&gt;
First you would need a new class that extends &amp;lt;code&amp;gt;LootTableProvider&amp;lt;/code&amp;gt;. In this class you will override the &amp;lt;code&amp;gt;getTables&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;validate&amp;lt;/code&amp;gt; methods.&lt;br /&gt;
You can optionally override &amp;lt;code&amp;gt;getName&amp;lt;/code&amp;gt; to return a name for the logs, if you have multiple providers and don't want to simply show up as &amp;quot;LootTables&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
None of the methods you will be overriding (either here or, where applicable, on the subproviders) should call the superclass methods - these superclass methods implement the vanilla data generation.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;getTables&amp;lt;/code&amp;gt; method will return a list of subproviders (explained further in the next section), the function signature looks a bit overwhelming but the actual method body is simple. Each subprovider will typically be a class, and you can simply use their constructors here. For more advanced scenarios (e.g. if you want to organize subproviders for multiple parameter sets into a single class), you can use a lambda that returns another lambda or a method reference.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
    @Override&lt;br /&gt;
    protected List&amp;lt;Pair&amp;lt;Supplier&amp;lt;Consumer&amp;lt;BiConsumer&amp;lt;ResourceLocation, LootTable.Builder&amp;gt;&amp;gt;&amp;gt;, LootContextParamSet&amp;gt;&amp;gt; getTables() {&lt;br /&gt;
        return List.of(&lt;br /&gt;
            Pair.of(MyBlockLoot::new, LootContextParamSets.BLOCK),&lt;br /&gt;
            Pair.of(MyEntityLoot::new, LootContextParamSets.ENTITY),&lt;br /&gt;
            Pair.of(MyChestLoot::new, LootContextParamSets.CHEST));&lt;br /&gt;
    }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;validate&amp;lt;/code&amp;gt; method needs to be overriden to eliminate the part of the vanilla code that verifies that the vanilla special loot tables have all been defined. If you have special loot tables (i.e. any loot table other than the main loot table for a block or entity), you may wish to add similar verification code here. The remaining code ensures that each table is consistent with the associated parameter set (e.g. that you're not trying to access a block state in an entity loot table).&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
    @Override&lt;br /&gt;
    protected void validate(Map&amp;lt;ResourceLocation, LootTable&amp;gt; map, ValidationContext validationtracker) {&lt;br /&gt;
        for (Map.Entry&amp;lt;ResourceLocation, LootTable&amp;gt; entry : map.entrySet())&lt;br /&gt;
            LootTables.validate(validationtracker, entry.getKey(), entry.getValue());&lt;br /&gt;
    }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Subproviders==&lt;br /&gt;
Each subprovider is a &amp;lt;code&amp;gt;Consumer&amp;lt;BiConsumer&amp;lt;ResourceLocation, LootTable.Builder&amp;gt;&amp;gt;&amp;lt;/code&amp;gt;. This is a fancy name that means that it has an accept function that is called with an argument containing another function that it can call with each loot table it wants to create.&lt;br /&gt;
&lt;br /&gt;
Each vanilla subprovider is a class. BlockLoot and EntityLoot contain helper methods to ensure that every block or entity has a primary loot table and to help generate certain types of loot tables. BlockLoot in particular has a large collection of helper functions that are extremely useful for implementing standard forms of loot tables for block types such as ores, doors, slabs, crops, or any block that simply always drops itself as an item.&lt;br /&gt;
&lt;br /&gt;
===Extending BlockLoot or EntityLoot===&lt;br /&gt;
If you are extending BlockLoot or EntityLoot, you will need to override the &amp;lt;code&amp;gt;addTables&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;getKnownBlocks&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;getKnownEntities&amp;lt;/code&amp;gt; methods. From the &amp;lt;code&amp;gt;addTables&amp;lt;/code&amp;gt; methods you will call the &amp;lt;code&amp;gt;add&amp;lt;/code&amp;gt; method for each of the tables you wish to create (a handful of the helper functions in BlockLoot including &amp;lt;code&amp;gt;dropSelf&amp;lt;/code&amp;gt; automatically add the tables they create).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
    @Override&lt;br /&gt;
    protected void addTables() {&lt;br /&gt;
        dropSelf(ModBlocks.BLOCK1.get());&lt;br /&gt;
        add(ModBlocks.BLOCK2.get(), ...);&lt;br /&gt;
    }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The second parameter to &amp;lt;code&amp;gt;BlockLoot.add&amp;lt;/code&amp;gt; may be a function that accepts the Block and returns a LootTable.Builder, or the LootTable.Builder itself. Many of the helper functions in BlockLoot work this way. For &amp;lt;code&amp;gt;EntityLoot.add&amp;lt;/code&amp;gt;, it must simply be the LootTable.Builder, but the first argument may be a ResourceLocation to create a special loot table rather than the primary loot table for the entity (this is used by vanilla for sheep colors).&lt;br /&gt;
&lt;br /&gt;
You must override &amp;lt;code&amp;gt;getKnownBlocks&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;getKnownEntities&amp;lt;/code&amp;gt;, respectively, to return only the blocks or entity types registered by your mod.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
    @Override&lt;br /&gt;
    protected Iterable&amp;lt;Block&amp;gt; getKnownBlocks() {&lt;br /&gt;
        return ModBlocks.BLOCKS.getEntries().stream().map(RegistryObject::get).toList();&lt;br /&gt;
    }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Implementing a simple subprovider===&lt;br /&gt;
The other vanilla subproviders don't have much worth extending for, so you can simply directly implement &amp;lt;code&amp;gt;Consumer&amp;lt;BiConsumer&amp;lt;ResourceLocation, LootTable.Builder&amp;gt;&amp;gt;&amp;lt;/code&amp;gt;.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
    public void accept(BiConsumer&amp;lt;ResourceLocation, LootTable.Builder&amp;gt; consumer) {&lt;br /&gt;
        consumer.accept({ResourceLocation}, {LootTable.Builder});&lt;br /&gt;
    }&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===The LootTable Builder===&lt;br /&gt;
This is where you actually make a loottable. You start with an empty &amp;lt;code&amp;gt;LootPool.Builder&amp;lt;/code&amp;gt; and add the necessary attributes to it.&lt;br /&gt;
* &amp;lt;code&amp;gt;.name&amp;lt;/code&amp;gt; is used for the pool name.&lt;br /&gt;
* &amp;lt;code&amp;gt;.setRolls&amp;lt;/code&amp;gt; is used for the amount.&lt;br /&gt;
* &amp;lt;code&amp;gt;.add&amp;lt;/code&amp;gt; is used to add an &amp;lt;code&amp;gt;LootPoolEntryContainer$Builder&amp;lt;/code&amp;gt;. You can have multiple entries.&lt;br /&gt;
&lt;br /&gt;
A &amp;lt;code&amp;gt;LootPoolEntryContainer$Builder&amp;lt;/code&amp;gt; defines what entry container is returned, and which functions and/or conditions are applied (see [https://minecraft.fandom.com/wiki/Loot_table Loot table] for the vanilla functions and conditions).&lt;br /&gt;
* &amp;lt;code&amp;gt;.when&amp;lt;/code&amp;gt; is used to apply a condition. These themselves can have multiple operations.&lt;br /&gt;
&lt;br /&gt;
After all attributes have been added the &amp;lt;code&amp;gt;LootPool.Builder&amp;lt;/code&amp;gt; can be used to make a &amp;lt;code&amp;gt;LootTable.Builder&amp;lt;/code&amp;gt;. This builder can then be used in the subproviders as discussed above.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;LootContextParamSet&amp;lt;/code&amp;gt; is automatically applied by the vanilla &amp;lt;code&amp;gt;LootTableProvider.run&amp;lt;/code&amp;gt; method.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
LootPool.Builder poolBuilder = LootPool.lootPool()&lt;br /&gt;
    .name(...)&lt;br /&gt;
    .setRolls(...)&lt;br /&gt;
    .add(LootItem.lootTableItem(...)&lt;br /&gt;
        .apply(function1)&lt;br /&gt;
        .apply(function2)&lt;br /&gt;
            .when(condition1)&lt;br /&gt;
            .when(condition2))&lt;br /&gt;
    );&lt;br /&gt;
LootTable.Builder tableBuilder = LootTable.lootTable().withPool(poolBuilder);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;[[Category:Data Generation]]&lt;/div&gt;</summary>
		<author><name>Random832</name></author>
	</entry>
</feed>