diff --git a/src/main/kotlin/ru/dbotthepony/mc/otm/core/util/Savetables.kt b/src/main/kotlin/ru/dbotthepony/mc/otm/core/util/Savetables.kt index ce92d4f66..1948ff68f 100644 --- a/src/main/kotlin/ru/dbotthepony/mc/otm/core/util/Savetables.kt +++ b/src/main/kotlin/ru/dbotthepony/mc/otm/core/util/Savetables.kt @@ -1,5 +1,6 @@ package ru.dbotthepony.mc.otm.core.util +import com.mojang.serialization.Codec import net.minecraft.nbt.ByteTag import net.minecraft.nbt.CompoundTag import net.minecraft.nbt.DoubleTag @@ -7,6 +8,7 @@ import net.minecraft.nbt.FloatTag import net.minecraft.nbt.IntTag import net.minecraft.nbt.ListTag import net.minecraft.nbt.LongTag +import net.minecraft.nbt.NbtOps import net.minecraft.nbt.NumericTag import net.minecraft.nbt.StringTag import net.minecraft.nbt.Tag @@ -17,12 +19,14 @@ import ru.dbotthepony.mc.otm.core.asGetterSetter import ru.dbotthepony.mc.otm.core.math.Decimal import ru.dbotthepony.mc.otm.core.math.Vector import ru.dbotthepony.mc.otm.core.nbt.set +import ru.dbotthepony.mc.otm.data.getOrNull import java.util.function.Supplier import kotlin.reflect.KMutableProperty0 import kotlin.reflect.KProperty0 /** * Utility class to manage serialization and deserialization of properties + * of mutable class */ class Savetables : INBTSerializable { private val entries = ArrayList>() @@ -175,6 +179,26 @@ class Savetables : INBTSerializable { .withDeserializer { map.invoke(it.asString) } } + fun codecNullable(prop: GetterSetter, codec: Codec, name: String): Stateless { + return Stateless(prop, name, Tag::class.java) + .withSerializer { prop.get()?.let { codec.encode(it, NbtOps.INSTANCE, NbtOps.INSTANCE.empty()).getOrThrow(false) { throw IllegalStateException("Failed to write NBT data for $name: $it") } } } + .withDeserializer { codec.decode(NbtOps.INSTANCE, it).getOrThrow(false) { throw IllegalStateException("Failed to read NBT data for $name: $it") }.first } + } + + fun codecNullable(prop: KMutableProperty0, codec: Codec, name: String = prop.name): Stateless { + return codecNullable(prop.asGetterSetter(), codec, name) + } + + fun codec(prop: GetterSetter, codec: Codec, name: String): Stateless { + return Stateless(prop, name, Tag::class.java) + .withSerializer { codec.encode(prop.get(), NbtOps.INSTANCE, NbtOps.INSTANCE.empty()).getOrThrow(false) { throw IllegalStateException("Failed to write NBT data for $name: $it") } } + .withDeserializer { codec.decode(NbtOps.INSTANCE, it).getOrThrow(false) { throw IllegalStateException("Failed to read NBT data for $name: $it") }.first } + } + + fun codec(prop: KMutableProperty0, codec: Codec, name: String = prop.name): Stateless { + return codec(prop.asGetterSetter(), codec, name) + } + fun vector(prop: GetterSetter, name: String, default: Vector = Vector.ZERO): Stateless { return Stateless(prop, name, ListTag::class.java) .withSerializer { ListTag().also { l ->