Coder Social home page Coder Social logo

kotlinnbt's Introduction

Build Status Kotlin JitPack License: MIT Donation

KotlinNBT

Type-safe Named Binary Tags (NBT) implementation in Kotlin for reading and writing files/streams with a simple and concise builder API.

This project is based on the original NBT specification by Notch (Wayback Machine) with the most recent additions by Mojang (Minecraft Wiki and Wiki.vg).

Installation

Maven:

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>
<dependency>
    <groupId>com.github.MrPNG</groupId>
    <artifactId>KotlinNBT</artifactId>
    <version>Tag</version>
</dependency>

Gradle Groovy:

repositories {
    maven { url 'https://jitpack.io' }
}
dependencies {
    implementation 'com.github.MrPNG:KotlinNBT:1.0.0'
}

Gradle Kotlin:

repositories {
    maven("https://jitpack.io")
}
dependencies {
    implementation("com.github.MrPNG:KotlinNBT:1.0.0")
}

Usage

The object NbtIO is used similarly to javax.imageio.ImageIO to read/write a NBT TagCompound. The available compression methods are: GZIP, ZLIB and NONE (no compression).

Reading from file

val file = File("test.nbt")
val compression = NbtIO.Compression.GZIP

val tagCompound = NbtIO.read(file, compression)

Writing to file

val file = File("test.nbt")
val compression = NbtIO.Compression.GZIP

NbtIO.write(someTagCompound, file, compression)

NBT builder

val nbt = nbt("root") {
    compound("testCompound") {
        intArray["fibonacciWithoutZero"] = intArrayOf(1, 1, 2, 3, 5, 8, 13, 21)
    }
    list["testList"] = listOf(
        compound {
            string["firstString"] = "I'm the first String :)"
            string["secondString"] = "I'm the second String, but order is not guaranteed :/"
            int["justAnInteger"] = 1
        }
    )
    long["timestamp"] = System.currentTimeMillis()
}

Using println(nbt) will print a Kotlin-styled tree:

root: Compound = {
    testCompound: Compound = {
        fibonacciWithoutZero: IntArray = [1, 1, 2, 3, 5, 8, 13, 21]
    },
    testList: List<Compound> = [
        Compound = {
            firstString: String = "I'm the first String :)",
            justAnInteger: Int = 1,
            secondString: String = "I'm the second String, but order is not guaranteed :/"
        }
    ],
    timestamp: Long = 1591470914831L
}

Important: according to the NBT specification, the order of the displayed/read tags is not guaranteed. KotlinNBT prints a TagCompound using a schema based on the way NBTExplorer does it.

Type safety

In the example above, the typed values can be obtained with type-safe accessors:

val fibonacci: IntArray = nbt["testCompound"].asTagCompound["fibonacciWithoutZero"].asIntArray
val message: String = nbt["testList"].asTagList[0].asTagCompound["firstString"].asString
val timestamp: Long = nbt["timestamp"].asLong
	
println(fibonacci.toList())
println(message)
println(timestamp)

prints

[1, 1, 2, 3, 5, 8, 13, 21]
I'm the first String :)
1591470914831

To check the tag types before accessing them (whether they exist or not), properties isTagX can be used, where X is a tag type:

println(nbt["testCompound"].isTagCompound)
println(nbt["timestamp"].isTagFloat)
println(nbt["world"].isTagString)

prints

true
false
false

Cloning tags

The provided Tag<T>.clone() functions deep copy the tag (that is, the tag itself and its children are cloned recursively) while keeping the type safety:

nbt.clone() // to keep the same name, "root"
nbt.clone("rootClone") // to change the root tag name
nbt["testList"]?.clone("actualList")

Donate

KotlinNBT is free and open-source for everyone to enjoy.

If you wish to support the continuous development of this and other projects, you can donate! Of course, I'm always providing support for anyone independently on the donations.

Everyone loves open-source <3

kotlinnbt's People

Contributors

luizrcs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kotlinnbt's Issues

[Feature] Full-blown entity mapping?

Hi, I just found this project by chance on wiki.vg and I'm looking forward to using it in my own project!

For my first (and most important) use-cases it will suffice, but I've been thinking about an addition: It might be very practical to add entity mapping to this project, so that you can write model classes for NBT files and serialize/deserialize right to/from those classes. This would be similar to popular (JSON) serialization libraries, like Jackson, GSON, Moshi or kotlinx.serialization.

There would be three general ideas of how to conceptually achieve this:

  1. Runtime Reflection: Inspect classes at runtime, inspect elements and annotations and produce entity gateways for interacting with arbitrary objects.
  2. Compile-time Reflection: Inspect classes at compile-time and generate mapping code.
  3. Plug into existing kotlinx.serialization: The official kotlinx.serialization provides the possibility to extend it for custom backend formats, and it has been done by the community for a few formats (like HOCON or XML).

At this point I'd like to mention that I'd be willing to contribute to this project by working on this issue. So, if you'd need any help with it, I could work on it as well.

  • ad 1: I've done a similar thing before (in Java) and have a little bit of experience with it. However, compile-time reflection is probably better.
  • ad 2: From what I've heard, the annotation processing ecosystem of Kotlin is basically inexistent. One would have to use the regular javax / google solutions and apparently it is quite tedious to work with Kotlin definitions from a Java annotation processing context.
  • ad 3: I think this might be the best solution, since it plugs right into the official serialization API, processes at compile-time, is multiplatform and does not require to work with the Java annotation processing environment. Also, there's a lot of work that is already done, and extending it would not mean too much work. I was actually a bit involved in the development of kotlinx-serialization-properties and I know that it'll probably be quite easy to extend it with an NBT format backend.

Thanks for considering my issue, and as said before, if you accept contribution to your project, I'd be happy to get involved!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.