Starting writing custom block api
This commit is contained in:
8 files changed
+193
-8
No files matched your search
@@ -0,0 +1,38 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user