> For the complete documentation index, see [llms.txt](https://buildsystem.eintosti.de/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://buildsystem.eintosti.de/developer-portal/world-management.md).

# World Management API

Create, import, load, and delete worlds in code.

Programmatically create, import, and manage worlds using the `WorldService` and fluent builders.

***

## 1. World Creation & Import (Fluent API)

### Generating a Fresh World

To generate a new world, use `WorldService#newWorld(String)` which returns a `WorldBuilder` instance. Chain options and execute `.build()` synchronously:

```java
import de.eintosti.buildsystem.api.BuildSystem;
import de.eintosti.buildsystem.api.BuildSystemProvider;
import de.eintosti.buildsystem.api.world.BuildWorld;
import de.eintosti.buildsystem.api.world.WorldService;
import de.eintosti.buildsystem.api.world.data.BuildWorldType;
import org.bukkit.Difficulty;

WorldService worldService = BuildSystemProvider.get().getWorldService();

BuildWorld lobbyWorld = worldService.newWorld("Lobby_01")
    .type(BuildWorldType.NORMAL)
    .difficulty(Difficulty.PEACEFUL)
    .time(6000) // Noon
    .worldBorderSize(5000)
    .privateWorld(false) // false = public (EVERYONE), true = private (ADDED_PLAYERS)
    .build(); // Synchronous. Must run on Bukkit's main thread.
```

`build()` returns `null` when the world could not be created, for example because the name is already taken or a folder of that name already exists, the template does not exist, or a listener cancelled `BuildWorldCreateEvent`. Call `.notify(player)` before `build()` to have the reason sent to a player; without it, nothing is written to chat. Other options are `.template(String)` (with `BuildWorldType.TEMPLATE`), `.customGenerator(CustomGenerator)`, `.seed(long)`, `.creator(Builder)`, `.folder(Folder)` and `.creationDate(long)`. `build()` does not teleport anyone; call `buildWorld.getTeleporter().teleport(player)` for that. A template is copied on the calling thread, so a large one holds up the main thread. If the copy fails, the partly copied folder is deleted and `build()` returns `null`.

### Importing an Existing Directory

To register an existing world folder present in the server container:

```java
import de.eintosti.buildsystem.api.world.creation.WorldImporter;

BuildWorld importedWorld = worldService.importWorld("legacy_lobby")
    .privateWorld(true) // true = private (ADDED_PLAYERS)
    .build(); // Synchronous. Must run on Bukkit's main thread.
```

The importer takes `.creator(Builder)`, `.type(BuildWorldType)` (defaults to `IMPORTED`), `.customGenerator(CustomGenerator)` (without one the world loads with a void generator), `.folder(Folder)` and `.notify(Player)`. Like `WorldBuilder`, `build()` returns `null` on failure, for example when the world was saved by a newer Minecraft version than the server runs, or when a player is still creating a world of that name from a template.

### Namespaced World Names

Both `newWorld` and `importWorld` accept a [namespaced name](https://buildsystem.eintosti.de/getting-started/creating-a-world.md#world-namespaces) such as `maps:lobby`, which creates or imports `dimensions/maps/lobby`. Unlike a player's input, a name without a namespace always means `minecraft` in the API; `world.default-namespace` and the bare-name lookup only apply to what players type.

Both methods check the name before returning the builder:

* `IllegalArgumentException` for a reserved name, an invalid namespace, a name that is not a valid world id (`maps:my world`, or a second colon as in `minecraft:a:b`), a name that resolves outside the world container, or a name whose internal Bukkit name clashes with another world (`maps:lobby` next to a world called `maps_lobby`).
* `UnsupportedOperationException` for a namespace other than `minecraft` on a server that is not Paper.

`BuildWorld#getName()` returns `maps:lobby` for such a world, but Paper names its Bukkit world `maps_lobby`, so `Bukkit.getWorld(buildWorld.getName())` finds nothing. Use `buildWorld.getWorld()` instead. `WorldStorage#getBuildWorld(String)` takes the full name and ignores case; a name without a namespace there means `minecraft` too.

### Async Operations (Bulk Import, Delete, and Unimport)

Bulk imports, unimports, and deletion tasks operate asynchronously to protect tick timing.

```java
import de.eintosti.buildsystem.api.world.lifecycle.SaveBehavior;

// Bulk-import unregistered world directories (spread across ticks to prevent lag)
worldService.importWorlds().thenAccept(importedCount -> {
    getLogger().info("Successfully imported " + importedCount + " worlds.");
});

// Unimport (unload registry entries without deleting directory files)
worldService.unimportWorld(buildWorld, SaveBehavior.SAVE).thenRun(() -> {
    getLogger().info("Unimported world successfully.");
});

// NOTE: the count is successful imports only. Directories skipped because the name is already
// registered or contains an invalid character, and any that fail outright, are reported to the
// server log rather than returned. Compare against the directory count if you need the shortfall.
// Only one bulk import may run at a time; a second call fails with IllegalStateException.

// Delete (unload registry entries and permanently delete directory)
worldService.deleteWorld(buildWorld).thenRun(() -> {
    getLogger().info("Deleted world directory from disk.");
});
```

`deleteWorld` completes exceptionally with one of the `de.eintosti.buildsystem.api.exception` types when it cannot go ahead: `WorldNotFoundException` (the world is not registered), `WorldDirectoryNotFoundException` (its folder is missing), `WorldDeletionCancelledException` (a listener cancelled `BuildWorldDeleteEvent`) or `WorldDeletionException` (the files could not be deleted). All of them extend `WorldException`. `deleteWorld` and `unimportWorld` also fail with a plain `WorldException`, and change nothing, when the world is busy with another operation or cannot be unloaded, for example because a listener cancelled `BuildWorldUnloadEvent`. Only one delete, rename, restore, unimport, backup or download runs on a world at a time, and `getLoader().load()` does nothing while one is running.

***

## 2. Looking Up Worlds and Folders

`WorldService#getWorldStorage()` holds every registered world:

```java
import de.eintosti.buildsystem.api.storage.WorldStorage;

WorldStorage worldStorage = worldService.getWorldStorage();

BuildWorld byName = worldStorage.getBuildWorld("Lobby_01");      // null if unknown
BuildWorld byBukkit = worldStorage.getBuildWorld(player.getWorld()); // null if not a BuildSystem world
BuildWorld byId = worldStorage.getBuildWorld(uuid);               // BuildSystem's own id, not World#getUID()
Collection<BuildWorld> all = worldStorage.getBuildWorlds();
List<BuildWorld> own = worldStorage.getBuildWorldsCreatedByPlayer(player);
```

Folders live in `WorldService#getFolderStorage()`: `getFolders()`, `getFolder(String name)` and `createFolder(name, category, [parent,] creator)`.

### Loading, Unloading and Teleporting

Each `BuildWorld` carries its own helpers. All of them must be called on the main thread.

```java
buildWorld.getLoader().load();                            // load without messages
buildWorld.getUnloader().unload();                        // skipped if players are inside, or the world is blacklisted or the spawn world
buildWorld.getUnloader().forceUnload(SaveBehavior.SAVE);  // unload regardless
buildWorld.getTeleporter().teleport(player);              // loads the world first if needed
```

### Builders and Permissions

`buildWorld.getBuilders()` returns the world's `Builders`: `getCreator()` / `setCreator(Builder)`, `isBuilder(Player)`, `addBuilder(Builder)` and `removeBuilder(Builder | UUID)`. Create a `Builder` with `Builder.of(player)` or `Builder.of(uuid, name)`.

`buildWorld.getPermissions()` answers the access questions BuildSystem itself asks: `canEnter(Player)`, `canModify(Player)` and `canModify(Player, WorldSetting)`.

***

## 3. Accessing & Mutating World Data

`BuildWorld` represents the metadata of a world. You can access the live Bukkit `World` handle (if loaded) or read and change its settings through `WorldData`.

### Resolving the Bukkit World

```java
// Returns Optional.empty() if the world is currently unloaded
Optional<org.bukkit.World> bukkitWorldOpt = buildWorld.getWorld();
if (bukkitWorldOpt.isPresent()) {
    org.bukkit.World world = bukkitWorldOpt.get();
}
```

### World Settings (`WorldData`)

Every world setting is addressed through a typed `WorldDataKey<T>`: read it with `get(key)` and write it with `set(key, value)`. The key carries the value type, so no cast is needed at the call site. The built-in keys (`PERMISSION`, `PROJECT`, `STATUS`, `DIFFICULTY`, `MATERIAL`, `BLOCK_BREAKING`, `VISIBILITY`, …) live on `WorldDataKey`.

```java
import de.eintosti.buildsystem.api.world.data.WorldData;
import de.eintosti.buildsystem.api.world.data.WorldDataKey;
import de.eintosti.buildsystem.api.world.data.BuildWorldStatus;
import de.eintosti.buildsystem.api.world.data.WorldStatusRegistry;
import org.bukkit.Material;

WorldData data = buildWorld.getData();

// Read settings
boolean physicsEnabled = data.get(WorldDataKey.PHYSICS);
BuildWorldStatus status = data.get(WorldDataKey.STATUS);
boolean canBreak = data.get(WorldDataKey.BLOCK_BREAKING);

// Write settings (persisted with the world)
data.set(WorldDataKey.PHYSICS, false);
data.set(WorldDataKey.MATERIAL, Material.GRASS_BLOCK);
data.set(WorldDataKey.CUSTOM_SPAWN, "0.0;64.0;0.0;90.0;0.0"); // x;y;z;yaw;pitch

// Statuses are interfaces resolved via the registry (returns Optional)
WorldStatusRegistry registry = BuildSystemProvider.get().getStatusRegistry();
registry.get(WorldStatusRegistry.FINISHED_ID).ifPresent(s -> data.set(WorldDataKey.STATUS, s));
```

The custom spawn has a parsed helper, `data.getCustomSpawnLocation()`, returning a Bukkit `Location` (or `null` when unset/invalid).

The full set of built-in keys:

| Key                                                         | Type               | Meaning                                                       |
| ----------------------------------------------------------- | ------------------ | ------------------------------------------------------------- |
| `CUSTOM_SPAWN`                                              | `String`           | Custom spawn as `x;y;z;yaw;pitch`, empty when unset.          |
| `PERMISSION`                                                | `String`           | Permission needed to enter the world, `-` for none.           |
| `PROJECT`                                                   | `String`           | Project description.                                          |
| `DIFFICULTY`                                                | `Difficulty`       | World difficulty.                                             |
| `MATERIAL`                                                  | `Material`         | Navigator icon.                                               |
| `ICON_SKULL_TEXTURE`                                        | `String`           | Skull texture when the icon is a player head, empty for none. |
| `STATUS`                                                    | `BuildWorldStatus` | Current status.                                               |
| `BLOCK_BREAKING` / `BLOCK_PLACEMENT` / `BLOCK_INTERACTIONS` | `Boolean`          | Whether breaking, placing and interacting are allowed.        |
| `BUILDERS_ENABLED`                                          | `Boolean`          | Only the creator and added builders may build.                |
| `EXPLOSIONS`                                                | `Boolean`          | Explosions enabled.                                           |
| `MOB_AI`                                                    | `Boolean`          | Mobs have AI.                                                 |
| `PHYSICS`                                                   | `Boolean`          | Block physics enabled.                                        |
| `PINNED`                                                    | `Boolean`          | Pinned to the top of the navigator.                           |
| `VISIBILITY`                                                | `Visibility`       | Who may see and enter the world.                              |
| `TIME_SINCE_BACKUP`                                         | `Integer`          | Seconds since the last backup.                                |
| `LAST_EDITED` / `LAST_LOADED` / `LAST_UNLOADED`             | `Long`             | Epoch-millisecond timestamps.                                 |

`WorldData` only stores these keys and the physics exception keys below. A key you make yourself with `WorldDataKey.of(...)` is not stored, and `get` or `set` with it throws `IllegalArgumentException`.

### Physics Exceptions

While `PHYSICS` is off, single behaviors can be allowed again per world. Each `PhysicsCategory` (`BLOCK_UPDATES`, `CONNECTIONS`, `FALLING_BLOCKS`, `FLUID_FLOW`, `LEAF_DECAY`, `GROWTH`, `SPREADING`, `BLOCK_FORMING`, `BLOCK_FADING`) owns the key that stores its value. `true` lets the behavior run with physics off; the value is ignored while physics is on.

```java
import de.eintosti.buildsystem.api.world.data.PhysicsCategory;

data.set(WorldDataKey.PHYSICS, false);
data.set(PhysicsCategory.FLUID_FLOW.key(), true); // water and lava still flow
```

***

## 4. Save Behavior Configuration

When unloading or unimporting worlds, specify saving guidelines using the `SaveBehavior` enum:

* `SaveBehavior.SAVE`: Saves the world to disk before unloading it.
* `SaveBehavior.DISCARD`: Unloads without saving, so changes since the last save are lost.

***

## 5. API Enumerations Directory

### `BuildWorldType`

Exposed by `BuildWorld#getType()` and `BuildWorldCreateEvent#getType()`. Defines the dimension or generator layout:

| Enum Constant | Description                                                   |
| ------------- | ------------------------------------------------------------- |
| `NORMAL`      | Standard vanilla terrain generation.                          |
| `FLAT`        | Flatworld grid generation.                                    |
| `NETHER`      | Nether dimension layout.                                      |
| `END`         | End dimension layout.                                         |
| `VOID`        | Void chunk generation (empty space).                          |
| `CUSTOM`      | Chunk generation controlled by third-party generator plugins. |
| `IMPORTED`    | World directory adopted from an existing server folder.       |
| `TEMPLATE`    | World copied from a template source directory.                |
| `PRIVATE`     | World that defaults to creator-only modification access.      |
| `UNKNOWN`     | World type could not be determined or is not recognized.      |

### `BuildWorldStatus`

An interface representing the progress state of a world, resolved and managed via `WorldStatusRegistry` (`BuildSystemProvider.get().getStatusRegistry()`). Two statuses are equal when they share the same id, so compare with `equals()` (or `getId()`), never `==`. The built-in default status IDs are:

| ID                | Description                                                                                                                                                                             |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `not_started`     | Default status upon world generation.                                                                                                                                                   |
| `in_progress`     | Builder actions are underway.                                                                                                                                                           |
| `almost_finished` | Final detailing is active.                                                                                                                                                              |
| `finished`        | Project completed.                                                                                                                                                                      |
| `archive`         | Disables block modifications (`buildingAllowed = false`). Adventure mode enforcement is a separate config option (`settings.archive.change-gamemode`), not an inherent status property. |
| `hidden`          | Hides the world from default navigator listings.                                                                                                                                        |

### `Visibility`

An enum defining the access restrictions on a world:

* `Visibility.EVERYONE`: Visible to all players (public).
* `Visibility.ADDED_PLAYERS`: Restricted to the creator and added builders (private).

### `NavigatorCategory`

An interface representing navigator tab groupings, resolved and managed via `NavigatorCategoryRegistry` (`BuildSystemProvider.get().getNavigatorCategoryRegistry()`). Built-in defaults include `public`, `private`, and `archive`. Like statuses, categories are equal by id, so compare with `equals()`, not `==`. `getCategoryForWorld(BuildWorld)` returns the first category that groups a world, falling back to the default.

### Managing Statuses and Categories

Both registries share the `Registry<T>` methods:

* `getAll()`, `get(String id)` (returns `Optional`) and `getDefault()`.
* `create(String displayName)` adds a new entry. It starts hidden and without a slot, so call `setSlot(int)` and `setShown(true)` on it.
* Changing an entry does not save it. Call `persist(entry)` after your changes.
* `delete(String id)` removes an entry and clears every reference to it. The status registry refuses to delete its last status; the category registry may be emptied.
* `resetLayout()` puts the built-in entries back in their default slots and hides the rest. `resetToDefaults()` also discards every custom entry.

The built-in ids are constants on the registries, such as `WorldStatusRegistry.ARCHIVE_ID` and `NavigatorCategoryRegistry.PUBLIC_ID`.

### `WorldSetting`

Evaluated in custom code via `WorldPermissions#canModify(Player, WorldSetting)`. Each constant points at one of the world's boolean settings. Players in build mode and holders of `buildsystem.admin` always pass. Everyone else is checked in this order: a status that turns building off refuses them unless they hold `buildsystem.bypass.archive`; then the setting's bypass permission (`buildsystem.bypass.settings`) lets them through; then a setting that is turned off refuses them; and last the builder list applies when the world has it enabled. `canModify(Player)` runs the same checks without the setting step. BuildSystem's own listeners use these same rules:

* `WorldSetting.BLOCK_BREAKING`: breaking blocks (`WorldDataKey.BLOCK_BREAKING`).
* `WorldSetting.BLOCK_PLACEMENT`: placing blocks (`WorldDataKey.BLOCK_PLACEMENT`).
* `WorldSetting.BLOCK_INTERACTIONS`: door, trapdoor and container interactions (`WorldDataKey.BLOCK_INTERACTIONS`).
