38 lines
1.4 KiB
Kotlin
38 lines
1.4 KiB
Kotlin
package fr.nextstation.unmei.blocks
|
|
|
|
import com.ensarsarajcic.kotlinx.serialization.msgpack.MsgPack
|
|
import org.bukkit.Chunk
|
|
import org.bukkit.NamespacedKey
|
|
import org.bukkit.persistence.PersistentDataType
|
|
import org.bukkit.plugin.java.JavaPlugin
|
|
|
|
class ChunksDataManager(val plugin: JavaPlugin) {
|
|
companion object {
|
|
val CUSTOM_BLOCK_DATA = NamespacedKey("unmei", "custom_block")
|
|
}
|
|
|
|
val cache = mutableMapOf<Long, ChunksData>()
|
|
|
|
fun getBlocksData(chunk: Chunk): ChunksData {
|
|
val map = cache.computeIfAbsent(chunk.chunkKey) {
|
|
val buffer = chunk.persistentDataContainer.get(CUSTOM_BLOCK_DATA, PersistentDataType.BYTE_ARRAY)
|
|
?: return@computeIfAbsent ChunksData(HashMap())
|
|
try {
|
|
val data = MsgPack.decodeFromByteArray(ChunksData.serializer(), buffer)
|
|
return@computeIfAbsent data
|
|
} catch (error: Error) {
|
|
plugin.logger.warning("Failed to Decode chunk ${chunk.chunkKey}: ${error.message}")
|
|
return@computeIfAbsent ChunksData(HashMap())
|
|
}
|
|
}
|
|
return map
|
|
}
|
|
|
|
fun saveBlocksData(chunk: Chunk) {
|
|
val data = cache[chunk.chunkKey]?: return
|
|
|
|
val buffer = MsgPack.encodeToByteArray(ChunksData.serializer(), data)
|
|
|
|
chunk.persistentDataContainer.set(CUSTOM_BLOCK_DATA, PersistentDataType.BYTE_ARRAY, buffer)
|
|
}
|
|
} |