Plugin API: slots and hosted plugins

This page covers what a plugin can provide: replace a core system, add to one, offer a service, or host other plugins.

Slots: replacing a core system

The server's core systems sit in replaceable slots. Today a plugin can fill one of them: the world generator (chunk-generator). To fill a slot, declare it in plugin.toml:

provides = ["chunk-generator"]

and register a provider in load:

use vanillite_plugin::{ChunkBlocks, ChunkGenerator, ChunkGeneratorProvider, WorldInfo};

struct Flat { stone: u32 }

impl ChunkGeneratorProvider for Flat {
    // Called once per world. `None` keeps the built-in generator for that world.
    fn create(&self, world: &WorldInfo) -> Option<Box<dyn ChunkGenerator>> {
        (world.dimension == "minecraft:overworld").then(|| Box::new(FlatGen { stone: self.stone }) as _)
    }
}

struct FlatGen { stone: u32 }

impl ChunkGenerator for FlatGen {
    // Called from several threads at once, for new chunks only.
    fn generate(&self, chunk: &mut ChunkBlocks<'_>) {
        for y in chunk.min_y()..=chunk.min_y() + 10 {
            chunk.fill_layer(y, self.stone);
        }
    }
}

// in load():
let stone = registrar.server().block_state_id("minecraft:stone").unwrap_or(0);
registrar.chunk_generator(Flat { stone });
  • WorldInfo tells the dimension key, the world's name, the lowest block min_y, the height, the seed, for a named generator the generator_id, and (since ABI 1.17) biomes, the world's biome keys by numeric id (biome_id("minecraft:plains") finds one).
  • ChunkBlocks is a dense block array, pre-filled with air: set(x, y, z, state) (x and z in 0..16), get, fill_layer(y, state), chunk_x(), chunk_z(), min_y(), height().
  • Generators work with numeric block state ids, resolved with Server::block_state_id. That is the one place where a plugin is tied to a Minecraft data version.
  • By default you only write the blocks (Vanilla's noise step). The server lights and finishes the chunk. With steps you can also set biomes, and let Vanilla's own steps run around yours.
  • Make the provider switchable in config.toml: the hello-plugin only registers its generator when generator.enabled is set.

Without a plugin generator, generation by seed is built to match Vanilla (World generation, Known limits); a plugin generator replaces that for the worlds it takes.

Named generators: a choice per world (ABI 1.15)

registrar.chunk_generator(…) above takes the dimensions it likes. Since ABI 1.15 (Vanillite 0.1.0-beta.4) a plugin can instead register a generator by name, and each world chooses it in vanillite.toml. It needs no provides entry and replaces nothing for worlds that do not ask for it.

// in load(): the same provider type as above, registered under a name
registrar.generator("terra", Flat { stone });
[worlds."minecraft:overworld".generation]
generator = "plugin:terra:overworld"   # name "terra", id "overworld"
  • The name may hold letters, digits, _, - and .. The text after the name (overworld) is the id; the provider reads it as WorldInfo::generator_id.
  • create returns None for a world it does not serve. Then that world does not start: it is never generated with another generator.
  • The choice is stored in the world's level.dat at its first start and wins on every later start. A changed setting or profile does not switch an existing world unless generation.switch = true (World generators).
  • WorldCreator::generator("plugin:terra") creates a world with a named generator while the server runs.
  • Bukkit plugins: the Bukkit layer registers the named generator bukkit. A world with generator = "bukkit:<Plugin>[:<id>]" is generated by that plugin's getDefaultWorldGenerator(world, id), and WorldCreator.generator(...) takes the same path. A world without generation.generator takes the generator that worlds.<name>.generator names in a bukkit.yml in the server folder, so a server moved from Bukkit or Paper keeps its plugin generators (for the default world's Nether and End: <level-name>_nether and <level-name>_the_end). This is in the layer's source but not in a layer release yet: layer 0.1.3, which Vanillite 0.1.0-beta.4 installs, does not have it.

Generator steps (ABI 1.17)

By default a generator makes the terrain alone. Since ABI 1.17 it can say which steps it takes part in. In each step the built-in part runs first, then the generator's own part. This is what Bukkit's shouldGenerate* methods and generateNoise, generateSurface, generateBedrock and generateCaves map to.

impl ChunkGenerator for MyGen {
    fn steps(&self) -> GenSteps {
        GenSteps {
            built_in: Steps::NOISE | Steps::DECORATIONS | Steps::STRUCTURES,  // Vanilla runs these
            plugin: Steps::SURFACE | Steps::POPULATE,                         // I run these
        }
    }
    fn generate_step(&self, step: Steps, chunk: &mut ChunkBlocks<'_>) { /* surface */ }
    fn populate(&self, area: &mut ChunkBlocks<'_>) { /* after the features */ }
}
Step Built-in part Generator's part
BIOMES Vanilla's biomes biomes, before the terrain: set_biome(x, y, z, id) per 4×4×4 cell
NOISE Terrain shape generate
SURFACE Surface rules generate_step
BEDROCK none generate_step, after the surface
CAVES Carvers generate_step
DECORATIONS Features none
STRUCTURES Structure starts and their pieces none
MOBS The first animals of new chunks none
POPULATE none populate, after the features
  • In populate the ChunkBlocks covers the 3×3 chunks around the chunk: positions are relative to the centre chunk's corner, from -16 to 31, with set_at and get_at. Nothing outside that area is kept.
  • Without steps, generate fills the terrain alone, as before ABI 1.17.
  • The steps run on many world generation threads at once. A generator that works with built-in steps costs nothing extra on the normal path: the server only wraps its built-in generator when a generator asks for built-in parts.
  • The raw ABI has GenStepMask (steps) and run_step in the provider, gen_step flags, and biomes, radius, min_y and height in each GenChunk. Read stride before the fields after len.
  • The Bukkit layer uses it for its generators (see Bukkit layer for developers).

Populators: adding to generation

A populator changes chunks after a stage of the built-in generation. It is like Bukkit's BlockPopulator.

registrar.chunk_populator(abi::gen_stage::AFTER_FEATURES, MyPopulator);
Stage When
AFTER_SURFACE After terrain, surface and carvers, before the features
AFTER_FEATURES After the features (trees, ores, pieces of structures)

ChunkPopulator::populate gets the chunk's blocks as they are so far. It is called from many threads at once. A generator that needs the 3×3 area around a chunk (trees that cross chunk borders) uses the POPULATE step above instead.

Mob goals

A plugin can give a mob its own behaviour. A goal runs after the Vanilla goals, with a priority, during the mob's AI tick, so mobs without plugin goals keep Vanilla's AI untouched.

struct HomeGoal { home: Vec3 }

impl Goal for HomeGoal {
    fn can_use(&mut self, mob: &GoalMob) -> bool { /* far from home? */ true }
    fn can_continue(&mut self, mob: &GoalMob) -> bool { mob.navigating }
    fn tick(&mut self, _: &GoalMob) -> GoalAction {
        GoalAction { move_to: Some((self.home, 1.0)), look_at: Some(self.home), ..GoalAction::default() }
    }
}

// On the mob's owner:
ctx.add_goal(world, mob, 1, abi::goal_flag::MOVE, false, HomeGoal { home })?;

add_goal(world, mob, priority, flags, target_selector, goal): lower priorities run first and may interrupt higher ones. flags say what the goal controls (goal_flag::MOVE, LOOK, JUMP, TARGET). GoalMob shows the mob's position, rotation, health, target and the world's game time. GoalAction can walk (move_to, with path finding), look, jump, set the target or stop. remove_goal removes one goal, clear_goals(world, mob, goal_clear::GOALS | TARGETS) removes the Vanilla goals.

Services: plugins sharing functions

A plugin offers a table of functions, another plugin uses it. The table is repr(C), so plugins in any language can use it.

#[repr(C)]
pub struct GreeterApi { pub size: u32, pub greetings: extern "C" fn() -> u64 }
static GREETER: GreeterApi = GreeterApi { size: size_of::<GreeterApi>() as u32, greetings };

server.register_service("hello:greeter", 1, &GREETER)?;      // offering plugin

// SAFETY: T must be the layout the providing plugin documents for this name and version.
let api = unsafe { server.service::<GreeterApi>("hello:greeter") };   // using plugin

service returns the newest version offered and its table. unregister_service withdraws it. Start the table with its size so it can grow later.

Hosting other plugins (ABI 1.11)

A plugin can host other plugins, like the Bukkit layer hosts Java plugins. It tells the server about them with the ABI function set_hosted_plugins: for each one a name, version, description, authors, website, a group (/plugins lists them in these sections, such as Bukkit) and whether it is on. The server then shows them in /plugins, /version <plugin> and the Query answer, next to the native ones. You can set up to 4096 entries; a call replaces the previous list, and an invalid one leaves the old list in place. There is no Rust wrapper for it yet.

A hosting plugin usually also answers permission questions with permission_provider (Plugin API: commands and permissions), as the layer does.

See also: Plugin concepts, Plugin API: players, entities and worlds, World generators.

Next: Bukkit layer for developers.