DynamicOps/1.16

From Forge Community Wiki
Revision as of 03:58, 27 July 2021 by ShrimpBot (talk | contribs) (Copy DynamicOps to MC1.16 archive)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The DynamicOps class is part of mojang's DataFixerUpper serialization library; DynamicOps are used alongside codecs/1.16 to convert java objects to a serialized format and back. While Codecs describe how a java object is to be serialized, DynamicOps describe the format the object is to be serialized to.

The DataFixerUpper library includes several DynamicOps for serializing to json; vanilla minecraft also includes a DynamicOps for serializing to minecraft's NBT/1.16 format.

Builtin DynamicOps

JsonOps

The JsonOps DynamicOps are used to serialize and deserialize json data. These are instances of DynamicOps<JsonElement>, meaning that they are used to convert java objects to and from JsonElement instances. These can used in conjunction with codecs to serialize/deserialize objects from assets and datapacks.

There are two public instances of JsonOps: JsonOps.INSTANCE and JsonOps.COMPRESSED. Compressed data is represented as a single string to read/write. However, this is never used within vanilla itself.

NBTDynamicOps

The NBTDynamicOps.INSTANCE is an instance of DynamicOps<INBT>, meaning it is used to convert java objects to and from INBT instances. This can be used for serializing data into packets to send across networks, as well as serializing persistant data for entities and similar objects.

There is only one public instance of NBTDynamicOps: NBTDynamicOps.INSTANCE.

Using DynamicOps

Serializing and Deserializing

By combining a Codec<SomeJavaType> with a DynamicOps<SomeSerializedFormat>, the proper java object can be converted to the serialized form and back. See codecs/1.16 for details on this subject.

Format Conversion

By using the DynamicOps#convertTo instance method with a second DynamicOps instance, data can be converted between two different serialized formats, such as JsonElement to INBT and back.

// converting INBT to JsonElement
JsonElement someJsonElement = NBTDynamicOps.INSTANCE.convertTo(JsonOps.INSTANCE, someNBT);

// converting JsonElement to INBT
INBT someNBT = JsonOps.INSTANCE.convertTo(NBTDynamicOps.INSTANCE, someJsonElement);

Depending on the implementation of the DynamicOps used, this may throw an exception or return an empty object if the two formats are incompatible.

In particular, it is not safe to convert lists of numbers to NBT in this manner, due to the NBT format's strong typing and the way the NBTDynamicOps attempts to create lists of numbers.

External Links