Docs » Plugins and packs » Writing a plugin

Writing a plugin

A first plugin in Rust or Java, then the parts every plugin has: its manifest, its lifecycle, its settings and its limits. Choose the language at the foot of the side menu or on any code example.

Your first plugin

You need Rust (rustup) with the WebAssembly target, and the server's download, whose sdk/rust/ holds the plugin kit:

rustup target add wasm32-unknown-unknown

A plugin is a library crate built as a cdylib:

hello/
  Cargo.toml
  plugin.toml
  src/lib.rs

Cargo.toml:

[package]
name = "hello"
version = "1.0.0"
edition = "2024"

[lib]
crate-type = ["cdylib"]

[dependencies]
voxelmon-plugin-sdk = { path = "path/to/server/sdk/rust/voxelmon-plugin-sdk" }

[profile.release]
opt-level = "s"
lto = true
panic = "abort"
strip = true

plugin.toml is the manifest:

id = "hello"
name = "Hello"
version = "1.0.0"
api = "1"
needs = []

src/lib.rs:

use voxelmon_plugin_sdk::*;

struct Hello;

impl Plugin for Hello {
    fn enable(server: &Server) -> Self {
        let _ = server.events().on_player_joined(|event| {
            if let Ok(name) = event.player.called() {
                let _ = Server.log_info(&format!("Hello, {name}!"));
            }
        });
        Hello
    }
}

voxelmon_plugin!(Hello, "../plugin.toml");

Build it, and copy the .wasm into the server's plugins/ folder:

cargo build --release --target wasm32-unknown-unknown
cp target/wasm32-unknown-unknown/release/hello.wasm path/to/server/plugins/

Start the server, or type plugin reload hello in a running one. It lists the new plugin and what it needs. Type plugin approve hello and it loads. The build puts the manifest inside the .wasm file, so that one file is the whole plugin.

The download has a fuller example in sdk/examples/rust/spawn-guard. It counts joins in storage, keeps the blocks round spawn from being broken and adds a console command.

Your first plugin

You need a JDK, version 25 or newer, and the server's download, whose sdk/java/ holds voxelmon-api.jar (and its sources, for your editor). The server needs Java 25 too, to run Java plugins.

hello/
  plugin.toml
  src/com/example/hello/Hello.java

plugin.toml names the main class:

id = "hello"
name = "Hello"
version = "1.0.0"
api = "1"
main = "com.example.hello.Hello"
needs = []

Hello.java:

package com.example.hello;

import net.voxelmon.api.Server;
import net.voxelmon.api.VoxelmonPlugin;

public final class Hello extends VoxelmonPlugin {
    @Override
    public void enable(Server server) {
        server.events().onPlayerJoined(event ->
                server.logInfo("Hello, " + event.player().called() + "!"));
    }
}

Build the jar with plugin.toml at its root, and copy it into plugins/:

javac --release 25 -cp path/to/server/sdk/java/voxelmon-api.jar -d classes $(find src -name '*.java')
cp plugin.toml classes/
jar --create --file hello.jar -C classes .
cp hello.jar path/to/server/plugins/

Then type plugin approve hello. Java plugins start when the server starts, so a jar added to a running server waits for the next restart.

The download has a fuller example with a build script in sdk/examples/java/welcome.

Where plugins go

Each plugin is one file in the server's plugins/ folder: a .wasm file.a .jar file. The first time the server sees a new or changed file, it lists the file and what it needs and waits for the owner to type plugin approve ID. Approvals are kept in plugins/approved.toml, each for one file's SHA-256, so a file that changes has to be approved again.

Approved plugins load in the order their dependencies need. The owner manages them with the plugin commands: plugins, plugin approve, plugin reload and plugin disable.

The manifest

Every plugin carries a plugin.toml:

id = "warps"                # unique, lowercase letters, digits and dashes
name = "Warps"
version = "1.2.0"
api = "1"                   # the API version it was built for
authors = ["Karagra"]
description = "Named places players can travel to."
depends = []                # plugins that must load first
soft_depends = ["economy"]  # used if present
needs = ["files"]           # what it asks the server for (below)
internet_hosts = []         # with the internet need: the hosts it may reach
id = "warps"                # unique, lowercase letters, digits and dashes
name = "Warps"
version = "1.2.0"
api = "1"                   # the API version it was built for
authors = ["Karagra"]
description = "Named places players can travel to."
depends = []                # plugins that must load first
soft_depends = ["economy"]  # used if present
needs = ["files"]           # what it asks the server for (below)
internet_hosts = []         # with the internet need: the hosts it may reach
main = "com.example.warps.Warps"  # the main class

Needs

NeedAllows
filesReading and writing in its own folder, plugins/<id>/
internetHTTPS requests to the hosts listed in internet_hosts
world_editChanging blocks and placed objects
player_dataChanging players' bags, gear, coins, progress and teams
creaturesSpawning, changing and removing Voxelmon

Reading the world and players needs nothing. A call whose need the manifest does not list is refused.A Java plugin runs with the server's full trust, so its needs are a statement of what it means to do. The owner sees what each plugin needs before approving it.

Lifecycle

CallWhen
enable(server)The plugin has loaded. Listen for events and register commands and tasks here.
world_ready()worldReady()The world has loaded and players may join.
disable()The server is stopping or the plugin is being reloaded. Save anything the plugin keeps.

The server ticks 60 times a second, and plugin code runs on the tick between steps of the world, so a plugin never has to lock anything. A call into a plugin that takes too long is reported in the console (see Limits).

Settings and logging

A plugin's settings are a TOML file its server's owner can edit, plugins/<id>/config.toml. If the file is missing and the plugin's folder has a config.default.toml, the server copies that first. The plugin reads the file as one Value, a table.

CallWhat it does
server.config()The settings, as a table of values
server.reload_config()server.reloadConfig()Reads the file again
server.log_info(text)server.logInfo(text)A line in the server's console, marked with the plugin's name
server.log_warn(text)server.logWarn(text)A warning in the console
server.log_error(text)server.logError(text)An error in the console

Data the plugin saves for itself goes in Storage, not in its settings.

Values

Storage, settings and services between plugins hold a Value: text, a whole number, a number with a fraction, true or false, a list of values, or a table of named values. Tables and lists may hold values in turn, nested up to 32 deep.

KindRustJava
TextValue::Text(String)Value.of("text") / Value.Text
Whole numberValue::Int(i64)Value.of(5L) / Value.Int
NumberValue::Float(f64)Value.of(0.5) / Value.Float
True or falseValue::Bool(bool)Value.of(true) / Value.Bool
ListValue::List(Vec<Value>)new Value.ListValue(List.of(...))
TableValue::Table(Vec<(String, Value)>)new Value.Table(Map.of(...))

Reading one back: as_str(), as_int(), as_float(), as_bool() and get_key("name") for a table's entry, each an Option:

Reading one back: Value is a sealed interface, read with a switch or instanceof on its records:

let joins = server.storage().get("joins")?.and_then(|v| v.as_int()).unwrap_or(0);
server.storage().set("joins", Value::Int(joins + 1))?;
long joins = server.storage().get("joins")
        .map(v -> v instanceof Value.Int n ? n.value() : 0L).orElse(0L);
server.storage().set("joins", Value.of(joins + 1));

Your first menu

A Menu is a panel the player's game draws. It has tabs down its left side, and each tab holds rows of text, buttons, item tiles, toggles, sliders and Voxelmon portraits. Build it once, open it for a player, and listen for MenuPressed, which names the pressed element by the id you gave it. This menu shows the server's rules to each player as they join:

let rules = Menu::create("WELCOME, TRAINER")?;
rules
    .add_tab("rules", "RULES", None)?
    .heading("title", "SERVER RULES")?
    .row()?
    .text("one", "1. Be kind to other trainers.")?
    .row()?
    .button("ok", "GOT IT")?;
server.events().on_player_joined(move |event| {
    let _ = event.player.open_menu(rules);
})?;
server.events().on_menu_pressed(move |event| {
    if event.menu == rules && event.id == "ok" {
        let _ = event.player.close_menu();
    }
})?;
Menu rules = Menu.create("WELCOME, TRAINER");
rules.addTab("rules", "RULES", null)
        .heading("title", "SERVER RULES")
        .row()
        .text("one", "1. Be kind to other trainers.")
        .row()
        .button("ok", "GOT IT");
server.events().onPlayerJoined(event -> event.player().openMenu(rules));
server.events().onMenuPressed(event -> {
    if (event.menu().equals(rules) && event.id().equals("ok")) {
        event.player().closeMenu();
    }
});

Elements in one row sit side by side, and row() starts the next row. After grid(4), elements fill four columns and wrap until the next row(), which suits a shop's items. A toggle's or slider's new value arrives with the press, and the menu already shows it.

You can change a menu at any time. Whoever has it open sees the change at the end of the tick. set_anchorsetAnchor stands a menu in the world, like a notice board, where it opens for anyone who walks up to it. In the download's Rust example, the warps N and warp-board N commands show a menu of three tabs with buttons, a toggle, a slider, item tiles and a portrait.

Wrist tabs, HUD and boss bars

Besides menus, a plugin can show three things in a player's view. The Hud page has the calls.

WhatWhere the player sees itLimits
Wrist tab (set_wrist_tabsetWristTab)A menu's first tab, on the player's watch beside the watch's own pages. Pressed as on the menu.Two tabs a player, the tab's first 24 elements
HudA small scoreboard just below the watch face: a title and lines of text, each with a value at its right and an optional bar.One HUD a player, 12 lines
BossBarA title over a bar, above the player's view.Two a player

Each is sent only when it changes, so setting a line to what it already says costs nothing.

server.events().on_player_joined(move |event| {
    let _ = event.player.set_wrist_tab(0, Some(warps), "WARPS", ItemType::named("Torch").ok().flatten());
    if let Ok(hud) = Hud::create("SPAWN GUARD") {
        let _ = hud.set_line(0, "YOUR COINS", "1,250", Colour { r: 255, g: 210, b: 60 });
        let _ = hud.set_bar(0, 0.4, Colour { r: 80, g: 220, b: 120 });
        let _ = hud.show(event.player);
    }
})?;
server.events().onPlayerJoined(event -> {
    var bar = BossBar.create("WELCOME", new Colour(255, 200, 40));
    bar.show(event.player());
    server.scheduler().afterSeconds(5.0, () -> bar.setProgress(0.5));
    server.scheduler().afterSeconds(10.0, bar::remove);
});

Showing a player a second HUD takes the first away. Watch tabs and HUDs never show in the demo or in single-player. The example puts its warps menu on every watch and keeps a HUD of the players online and each player's coins.The example shows a boss bar to each player who joins.

When a call fails

Every call returns voxelmon_plugin_sdk::Result<T>, whose error is an Error:

A call that fails throws ApiException, whose kind() says which:

ErrorApiException.KindMeaning
GoneGONEWhat it was about is gone: a player who left, a creature beaten, a menu removed.
Denied(need)DENIEDThe plugin's manifest does not ask for the need this call has (needs); the text names it.
InvalidINVALIDAn argument was out of range or malformed: text too long, a stack over its limit, an unknown item.
LimitLIMITA limit was reached: too many tasks, commands or stored keys, a fill too large.
Failed(why)FAILEDIt could not be done, and the text says why. A call the server does not support yet fails this way and does nothing else.

A handler that panics stops the plugin: the server disables it and says why in the console. Handle the errors a call can return in ordinary play, such as Gone for a player who has just left.

An exception a handler lets out stops the plugin: the server disables it and prints the stack trace in the console. Catch ApiException where a call can fail in ordinary play, such as GONE for a player who has just left. Use the API only from the server's own calls into your plugin (handlers, commands, tasks), never from a thread you start.

One rule applies inside a handler for an event that can be stopped. A call there that changes the world and returns nothing is held until the event is over, then made. A call that changes the world and returns something fails, because its answer cannot be known yet.

Limits

Rust pluginsJava plugins
TimeA call into the plugin taking over 250 ms is stopped, and the plugin disabled.Over 20 ms is reported in the console; nothing can stop a Java call.
Memory64 MB at most.Java's own heap, shared by every Java plugin.
What it can reachOnly the server's calls, and only those its manifest's needs allow.The server's calls, and anything Java itself can do as the server's user.
Its datastorage() values are kept in plugins/<id>/data.bin; files (the files need) in plugins/<id>/files/.

A call into a plugin that takes over 20 ms is reported in either language, and the plugins command shows how much time each plugin has taken.