Compare commits

..
Author SHA1 Message Date
piexel 8a8abc1c9c Merge branch 't3/port-studio-v4' into feat/zed-editor-support 2026-11-25 11:12:24 +01:00
piexel 36b352ea05 Serve scene views and their editors from a scene layer
- Features list their views in SceneViews, the studio adds objects and procedural objects
- Edit, write and create scene entries' files from the studio
2026-11-25 11:06:45 +01:00
piexel 2455359550 Merge branch 't3/port-studio-v4' into feat/zed-editor-support 2026-11-25 10:17:09 +01:00
piexel ef24f2e8b2 Merge remote-tracking branch 'origin/master' into t3/port-studio-v4 2026-11-25 10:12:16 +01:00
piexel a51802c487 Use lucide icons across the studio
- Add lucide-react and give every icon one shared size and stroke from a provider
- Replace the IntelliJ-style SVG files and their loader with lucide components
- Give every view id an icon, including caves, and a distinct fallback
- Take icon colour from currentColor so the light and dark twins are gone
2026-11-25 09:45:03 +01:00
piexel 5040d32cb8 Name a node's connectors sockets
- Rename the node connector names and their data attribute
2026-11-25 09:44:27 +01:00
piexel d8c0c2cc61 Drop the reset zoom key from the canvas menu
- The node editor does not handle that key, so the menu no longer shows it
2026-11-25 09:44:27 +01:00
piexel 1efb4c14db Fix node drops on fast drags and tidy node menus
- Work out a drop from the release itself, so a quick drag still regrows or moves the node
- Draw the chosen node above the others
- Write curves spaced like the rest of the file
- Keep focus off a node's controls after its menu closes
- Size dropdown rows like the context menu's
2026-11-25 09:44:27 +01:00
piexel 8fe8942f5d Edit procedural settings inside the node boxes
- Draw each node with a kind stripe, role chips, sockets and a row per set setting
- Edit values in place: text with suggestions, checkboxes, choice menus and curves
- Fold object and list settings, add and remove list items, add settings from a menu
- Lay nodes out on a grid with roots in the first column and parts growing right
- Drag nodes to place them, kept per file, and drag a part's ring onto a node to regrow it
- Add part, duplicate and delete from node menus, arrange and fit from the canvas menu
- Open the curve editor from a curve value, with draggable points on its plot
- Remove the side settings panel and its field rows
2026-11-25 09:44:27 +01:00
piexel fadbcb8bb5 Suggest roles for procedural settings by their class names
- Match ProceduralPart, ProceduralMaterial and ProceduralDecoration in art.arcane.iris.generation.procedural.part
2026-11-25 09:44:26 +01:00
piexel 9489ffd4ad Download the studio app at startup
- Bundle the built app in the Bukkit jar
- Fetch the pinned Electron build when the host has a display
- Add studio.downloadApp to turn it off
2026-11-25 09:26:56 +01:00
piexel c6a7225fa8 Build the studio link button in core
- Keep relocated Adventure types out of the plugin module
2026-11-25 09:26:55 +01:00
piexel 2ae765ca16 Tell the player why the studio app did not open
- Hand over a copy button for the studio link
2026-11-24 14:55:03 +01:00
piexel 72852b1300 Detect the studio editor by default 2026-11-24 12:05:15 +01:00
piexel 1e04f61957 Keep custom leaves from decaying and from cutting logs
- Implement the log and leaves checks added in https://github.com/VolmitSoftware/VolmLib/pull/4 so master compiles against the current VolmLib again
- Let external providers make a block persistent and report block tags
- Make CraftEngine leaves with a persistent property keep their leaves when decay is prevented
- Count CraftEngine blocks with the logs and leaves tags as logs and leaves
- Skip leaf placements that would replace a log another object placed
- Make object placement persist leaves by their persistent property, not their distance property
2026-11-23 23:31:03 +01:00
Brian Fopiano 435ed10648 Merge pull request #1264 from VolmitSoftware/fix/fracture-mirror
Stop fractured noise from mirroring across x = z
2026-11-23 13:42:18 -05:00
piexel 98cd73bc8f Merge studio into zed editor support
# Conflicts:
#	adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandEdit.java
#	adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandStudio.java
#	core/src/main/java/art/arcane/iris/configuration/IrisSettings.java
#	core/src/main/java/art/arcane/iris/pack/loading/IrisRegistrant.java
#	core/src/main/java/art/arcane/iris/studio/map/PackFileOpener.java
#	core/src/main/java/art/arcane/iris/studio/workspace/IrisCodeWorkspace.java
2026-11-19 18:06:54 +01:00
piexel 4079e0a708 Drop old class names from studio comments 2026-11-15 11:17:34 +01:00
piexel 2cfb3d8dcc Replace the Swing studio with the studio app
- Open the app from map, noise and imagemap commands and from pregeneration
- Delete the Swing windows, GPU renderers and their tests
- Keep tile rendering, sampling, palettes and object sources as plain logic
- Open files through FileOpener instead of AWT Desktop
2026-11-15 11:17:34 +01:00
piexel 98e296b666 Add image maps and pregeneration views to the studio
- List the pack's image maps with a preview over the area they cover
- Show the running pregeneration's chunk map, progress and pause
2026-11-15 11:17:34 +01:00
piexel 3532c16906 Serve object and procedural views from the studio bridge
- List pack objects and baked procedural objects as scene views
- Time one bake per request for the bake meter
2026-11-15 11:17:34 +01:00
piexel dd7d838c6b Serve noise and palette views from the studio bridge
- Port the noise tile sources and lattice sampling to art.arcane.iris.studio.noise
- Lay out biome palettes as pattern tiles for the Palettes view
2026-11-15 11:17:34 +01:00
piexel a8470c8178 Add height, biome layer and load map views to the studio
- Serve the seven Swing tile views from the bridge
- Colour the height view in the app from tile heights
2026-11-15 11:17:34 +01:00
piexel 8afbff4b42 Add profile views to the studio
- Add Cave, Tree, Formation and Fluid profile views beside the scene viewer
- Add a settings form panel that changes the preview only
- Pass typed values with scene requests
- Add view icons in the studio's icon style
2026-11-15 11:17:34 +01:00
piexel 05984cf64a Serve config profile views from the studio bridge
- List cave, tree, formation and fluid profiles as scene views with settings forms
- Carve cave profiles with the engine's own carver in a throwaway mantle
- Bake tree and formation presets into objects and draw fluids in a lined pool
- Apply typed form values to a copy so pack files stay untouched
- Serve Minecraft client assets from the cached client jar
- Add ProfileForm unit tests
2026-11-15 11:17:34 +01:00
piexel aafbb879df Add Rivers view to the studio
- Show hydrology features as colored labels with a water legend
- Reuse the Swing studio's rivers icon and key colors
- Show the no-hydrology empty state
- List only views the V4 bridge serves
2026-11-15 11:17:34 +01:00
piexel 86ce2856e8 Add studio bridge server for the Iris Studio app
- Serve world, tiles, hover, regions, players and events over a loopback HTTP bridge
- Draw biome, region and river tiles with the Swing map's renderer
- Add /iris std app to open the studio on a world
- Add studioApp and electron studio settings
- Close the bridges when the studio service stops
2026-11-15 11:17:34 +01:00
piexel 564dcdcc72 Add Iris Studio app
- Add the Electron studio (electron-vite, React, three)
- Ignore node_modules and build output under studio/
2026-11-15 11:17:34 +01:00
piexel ed44db5497 Stop fractured noise from mirroring across x = z
- Read each composite fracture axis from its own reseeded generator at unswapped coordinates in IrisNoiseGenerator and the batched NoiseLayerProgram
- Read the datapack exporter's z warps at unswapped coordinates
- Add a mirror test for the composite fracture and move the fracture test reference to per-axis seeds
- Retake NoiseSeedCohesionTest (Linux/Windows digest), IrisCaveCarver3DCellKernelTest PACK_SHARED and three IrisMathNoiseHotPathParityTest values
2026-11-14 17:32:08 +01:00
piexel ca5cdff5ea Reload Zed schemas and ignore .zed in pack hotload
Also covers modded studios and the editor command
2026-11-14 15:39:12 +01:00
piexel bbb3833e29 Add configurable studio editor with Zed support 2026-11-14 15:38:56 +01:00
piexel 4e8b151320 Accept JSONC comments in pack files and editors 2026-11-14 15:36:30 +01:00
piexel f0b7b14db7 Mirror pack schemas into Zed project settings 2026-11-14 15:36:30 +01:00
Brian Fopiano 832070cd69 Fix foundation cell lookup
- Call lowestFoundationCells in NMS surface terrain tests
- Match the renamed VolmLib occupancy method
2026-11-11 01:08:33 -05:00
491 changed files with 35847 additions and 31160 deletions

No files matched your search

+6 -1
View File
@@ -147,11 +147,16 @@ Plugin:
```
/iris studio create name=<name> [template=<pack>]
/iris studio open <pack> [seed=1337]
/iris studio vscode [dimension=<pack>]
/iris studio editor [dimension=<pack>]
/iris studio update [dimension=<pack>]
/iris studio close
```
`studio.editor` in `iris.json` picks the editor the studio opens: `auto` (default), `vscode`, `zed` or `none`.
`auto` uses Zed when it is on the `PATH` and VSCode (`code` or `codium`) is not, otherwise VSCode.
Zed is started through its CLI (`zed`, `zeditor` or `zedit` on the `PATH`) with the pack folder as
the project. `/iris studio vscode` still works as an alias.
Mod:
```
@@ -570,7 +570,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertTrue(state(blocks, 4, 96, 0).isAir());
assertEquals(1, pathGround.size());
@@ -619,7 +619,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -675,7 +675,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -570,7 +570,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertTrue(state(blocks, 4, 96, 0).isAir());
assertEquals(1, pathGround.size());
@@ -619,7 +619,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -675,7 +675,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -21,6 +21,7 @@ package art.arcane.iris;
import art.arcane.iris.api.terrain.IrisTerrainService;
import art.arcane.iris.command.CommandSVC;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.studio.app.StudioAppInstaller;
import art.arcane.iris.configuration.SettingsHotloadWatch;
import art.arcane.iris.diagnostics.LogFilterSVC;
import art.arcane.iris.diagnostics.splash.IrisSplashComposer;
@@ -976,6 +977,7 @@ public final class IrisRuntime implements IrisPluginRuntime {
return;
}
BukkitGuiHost.install();
StudioAppInstaller.installInBackground();
// super.onEnable() already registers this instance as a listener.
plugin.enablePlugin();
if (IrisStartupValidation.isRestartRequired()) {
@@ -23,15 +23,14 @@ import art.arcane.iris.studio.StudioSVC;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.iris.studio.workspace.StudioEditor;
import art.arcane.iris.studio.workspace.StudioEditorLauncher;
import art.arcane.volmlib.util.director.DirectorOrigin;
import art.arcane.volmlib.util.director.annotations.Director;
import art.arcane.volmlib.util.director.annotations.Param;
import art.arcane.iris.localization.C;
import java.awt.Desktop;
import java.awt.GraphicsEnvironment;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.BukkitCommandMessagesExtended;
import art.arcane.volmlib.util.localization.MessageArgument;
@@ -50,19 +49,34 @@ public class CommandEdit implements DirectorExecutor {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_YOU_MUST_BE_STUDIO_WORLD));
return true;
}
return editorUnavailable();
}
if (GraphicsEnvironment.isHeadless()) {
private boolean editorUnavailable() {
StudioEditor editor = StudioEditorLauncher.resolvedEditor();
if (editor == StudioEditor.NONE) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_NO_EDITOR_CONFIGURED));
return true;
}
if (!StudioEditorLauncher.canLaunch(editor)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_OPEN_FILES_HEADLESS_ENVIRONMENTS));
return true;
}
if (!Desktop.isDesktopSupported()) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_DESKTOP_IS_NOT_SUPPORTED_BY_THIS_ENVIRONMENT));
return true;
}
return false;
}
private void openInEditor(IrisRegistrant registrant) {
MessageArgument editorName = MessageArgument.untrusted("editor", StudioEditorLauncher.resolvedEditor().getDisplayName());
if (!StudioEditorLauncher.openFile(registrant.getLoader().getDataFolder(), registrant.getLoadFile())) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_COULD_NOT_OPEN_EDITOR, editorName));
return;
}
String fileName = registrant.getLoadFile().getName().split("\\Q.\\E")[0];
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_IN_EDITOR,
MessageArgument.untrusted("value", registrant.getTypeName()), MessageArgument.untrusted("value2", fileName), editorName));
}
@Director(description = "Edit the biome you specified", descriptionKey = "iris.director.commandedit.director.edit_biome_you_specified", aliases = {"b"}, origin = DirectorOrigin.PLAYER)
public void biome(@Param(contextual = false, description = "The biome to edit", descriptionKey = "iris.director.commandedit.param.biome_edit") IrisBiome biome) {
@@ -74,8 +88,7 @@ public class CommandEdit implements DirectorExecutor {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM));
return;
}
Desktop.getDesktop().open(biome.getLoadFile());
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE, MessageArgument.untrusted("value", biome.getTypeName()), MessageArgument.untrusted("value2", biome.getLoadFile().getName().split("\\Q.\\E")[0])));
openInEditor(biome);
} catch (Throwable e) {
Iris.reportError(e);
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST));
@@ -92,8 +105,7 @@ public class CommandEdit implements DirectorExecutor {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_2));
return;
}
Desktop.getDesktop().open(region.getLoadFile());
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE_2, MessageArgument.untrusted("value", region.getTypeName()), MessageArgument.untrusted("value2", region.getLoadFile().getName().split("\\Q.\\E")[0])));
openInEditor(region);
} catch (Throwable e) {
Iris.reportError(e);
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST_2));
@@ -110,8 +122,7 @@ public class CommandEdit implements DirectorExecutor {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_3));
return;
}
Desktop.getDesktop().open(dimension.getLoadFile());
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE_3, MessageArgument.untrusted("value", dimension.getTypeName()), MessageArgument.untrusted("value2", dimension.getLoadFile().getName().split("\\Q.\\E")[0])));
openInEditor(dimension);
} catch (Throwable e) {
Iris.reportError(e);
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST_3));
@@ -21,12 +21,17 @@ package art.arcane.iris.command;
import art.arcane.iris.Iris;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.studio.map.MapWindow;
import art.arcane.iris.studio.map.PaletteExplorerStart;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.pack.PackDownloader;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.studio.bridge.StudioBridge;
import art.arcane.iris.studio.bridge.StudioBridges;
import art.arcane.iris.studio.bridge.StudioLaunch;
import art.arcane.iris.studio.bridge.StudioWindow;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.studio.workspace.IrisProject;
import art.arcane.iris.studio.workspace.IrisCodeWorkspace;
import art.arcane.iris.studio.workspace.StudioEditor;
import art.arcane.iris.studio.workspace.StudioEditorLauncher;
import art.arcane.iris.localization.RuntimeUiMessages;
import art.arcane.iris.platform.bukkit.BoardSVC;
import art.arcane.iris.studio.StudioSVC;
@@ -104,6 +109,7 @@ import java.util.function.Consumer;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.BukkitCommandMessages;
import art.arcane.volmlib.util.localization.MessageArgument;
import art.arcane.volmlib.util.localization.TextKey;
import art.arcane.volmlib.util.localization.LanguageAudience;
import art.arcane.iris.localization.BukkitCommandMessagesExtended;
@Director(name = "studio", aliases = {"std", "s"}, description = "Studio Commands", descriptionKey = "iris.director.commandstudio.director.studio_commands")
@@ -166,13 +172,36 @@ public class CommandStudio implements DirectorExecutor {
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_TREES_OBJECTS_ARE_UNDER_OBJECTS_VANILLA_REFERENCE_THEM_FROM_BIOME));
}
@Director(description = "Open VSCode for a dimension", descriptionKey = "iris.director.commandstudio.director.open_vscode_dimension", aliases = {"vsc"})
public void vscode(
@Param(defaultValue = "default", description = "The dimension to open VSCode for", descriptionKey = "iris.director.commandstudio.param.dimension_open_vscode", aliases = "dim", customHandler = DimensionHandler.class)
@Director(description = "Open the configured editor for a dimension", descriptionKey = "iris.director.commandstudio.director.open_editor_dimension", aliases = {"vscode", "vsc"})
public void editor(
@Param(defaultValue = "null", description = "The dimension to open the editor for", descriptionKey = "iris.director.commandstudio.param.dimension_open_editor", aliases = "dim", customHandler = NullableDimensionHandler.class)
IrisDimension dimension
) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_VSCODE_PACK, MessageArgument.untrusted("value", dimension.getName())));
Iris.service(StudioSVC.class).openVSCode(sender(), dimension.getLoadKey());
StudioSVC studio = Iris.service(StudioSVC.class);
String pack = dimension != null ? dimension.getLoadKey() : packForEditor(studio);
if (!PackDownloader.isPackPresent(studio.getWorkspaceFolder(), pack)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_COULD_NOT_RESOLVE_PACK_DIMENSION, MessageArgument.untrusted("value", pack)));
return;
}
StudioEditor editor = StudioEditorLauncher.resolvedEditor();
if (editor == StudioEditor.NONE) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_NO_EDITOR_CONFIGURED));
return;
}
if (!StudioEditorLauncher.canLaunch(editor)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_OPEN_FILES_HEADLESS_ENVIRONMENTS));
return;
}
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_EDITOR_PACK,
MessageArgument.untrusted("editor", editor.getDisplayName()), MessageArgument.untrusted("value", pack)));
studio.openEditor(sender(), pack);
}
private static String packForEditor(StudioSVC studio) {
if (studio.isProjectOpen()) {
return studio.getActiveProject().getName();
}
return IrisSettings.get().getGenerator().getDefaultWorldType();
}
@Director(description = "Close an open studio project", descriptionKey = "iris.director.commandstudio.director.close_open_studio_project", aliases = {"x"}, sync = true)
@@ -267,16 +296,10 @@ public class CommandStudio implements DirectorExecutor {
@Director(description = "Open the noise explorer (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_noise_explorer_external_gui", aliases = {"nmap"})
public void noise(
@Param(description = "Optional pack generator to preview", descriptionKey = "iris.director.commandstudio.param.optional_pack_generator_preview", defaultValue = "null", contextual = true, contextualOverride = true)
IrisGenerator generator,
@Param(description = "The seed to preview the generator with", descriptionKey = "iris.director.commandstudio.param.seed_preview_generator_with", defaultValue = "12345")
long seed
@Param(name = "world", description = "The Iris world whose pack the noise explorer reads", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true)
World world
) {
if (noGUI()) return;
VolmitSender commandSender = sender();
UUID openerId = commandSender.isPlayer() ? commandSender.player().getUniqueId() : null;
MapWindow.NoiseSelection selection = new MapWindow.NoiseSelection(generator == null ? null : generator.getLoadKey(), generator, seed);
withPlayerContext(opener -> openNoiseAtPlayer(commandSender, openerId, opener, selection));
openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER);
}
@Director(description = "Open the image-map studio (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_image_map_studio_external_gui", aliases = {"imap"})
@@ -284,16 +307,7 @@ public class CommandStudio implements DirectorExecutor {
@Param(name = "world", description = "The Iris world whose active pack receives image-map exports", descriptionKey = "iris.director.commandstudio.param.world_open_image_map_studio", contextual = true, contextualOverride = true)
World world
) {
if (noGUI()) {
return;
}
if (!IrisToolbelt.isIrisWorld(world)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
return;
}
requestMapStart(world, MapWindow::openImageMaps);
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO));
openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO);
}
@Director(description = "Show loot if a chest were right here", descriptionKey = "iris.director.commandstudio.director.show_loot_if_chest_were_right_here", origin = DirectorOrigin.PLAYER, sync = true)
@@ -425,66 +439,45 @@ public class CommandStudio implements DirectorExecutor {
@Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true)
World world
) {
if (noGUI()) return;
openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP);
}
@Director(description = "Open the Iris Studio app on a world", descriptionKey = "iris.director.commandstudio.director.render_world_map_external_gui", aliases = "app")
public void studioApp(
@Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true)
World world
) {
openStudioApp(world, BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP);
}
/** Opens the app on the world; when it can't, tells the sender why and hands over the link to connect by hand. */
private void openStudioApp(World world, TextKey openedMessage) {
if (!IrisToolbelt.isIrisWorld(world)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
return;
}
requestMapStart(world, MapWindow::openMap);
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP));
}
// The map opens where the player stands when they are in that world, otherwise at the world origin.
private PaletteExplorerStart mapStartIn(World world, Player opener, UUID openerId) {
Location center = opener != null && opener.getWorld().equals(world) ? opener.getLocation() : null;
return new PaletteExplorerStart(
IrisToolbelt.access(world).getEngine(),
world.getUID(),
openerId,
null,
center == null ? 0D : center.getX(),
center == null ? 0D : center.getZ()
);
}
private void requestMapStart(World world, Consumer<PaletteExplorerStart> launch) {
UUID openerId = sender().isPlayer() ? player().getUniqueId() : null;
withPlayerContext(opener -> launch.accept(mapStartIn(world, opener, openerId)));
}
private void openNoiseAtPlayer(VolmitSender commandSender, UUID openerId, Player opener, MapWindow.NoiseSelection selection) {
World world = opener == null ? null : opener.getWorld();
PlatformChunkGenerator worldGenerator = world == null ? null : IrisToolbelt.access(world);
Engine engine = worldGenerator == null ? GuiHost.get().findActiveEngine() : worldGenerator.getEngine();
if (engine == null) {
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
PlatformChunkGenerator generator = IrisToolbelt.access(world);
StudioBridge bridge;
try {
bridge = StudioBridges.open(world.getName(), generator::getEngine, openerId);
} catch (IOException error) {
IrisLogging.warn("Could not open the studio bridge: %s", error.getMessage());
return;
}
PaletteExplorerStart start = worldGenerator == null
? new PaletteExplorerStart(engine, null, openerId, null, 0D, 0D)
: mapStartIn(world, opener, openerId);
MapWindow.openNoise(start, selection);
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER));
}
private void withPlayerContext(Consumer<Player> action) {
Player opener = sender().isPlayer() ? player() : null;
if (opener == null) {
action.accept(null);
StudioLaunch launch = StudioWindow.show(bridge);
if (launch.opened()) {
sender().sendMessage(IrisLanguage.text(openedMessage));
return;
}
AtomicBoolean completed = new AtomicBoolean();
Consumer<Player> complete = player -> {
if (completed.compareAndSet(false, true)) {
action.accept(player);
}
};
Runnable retired = () -> complete.accept(null);
if (!J.runEntity(opener, () -> complete.accept(opener.isOnline() ? opener : null), 0, retired)) {
retired.run();
}
IrisLogging.info("Iris Studio link for %s: %s", world.getName(), bridge.link());
sendStudioLink(launch, bridge.link());
}
private void sendStudioLink(StudioLaunch launch, String link) {
sender().sendMessage(C.RED + IrisLanguage.text(launch.failureMessage()));
sender().sendCopyButton(IrisLanguage.text(RuntimeUiMessages.STUDIO_LINK_COPY_BUTTON),
IrisLanguage.text(RuntimeUiMessages.STUDIO_LINK_COPY_HOVER), link);
}
@Director(description = "Profiles the performance of a dimension", descriptionKey = "iris.director.commandstudio.director.profiles_performance_dimension", origin = DirectorOrigin.PLAYER)
@@ -953,21 +946,6 @@ public class CommandStudio implements DirectorExecutor {
}
}
/**
* @return true if server GUIs are not enabled
*/
private boolean noGUI() {
if (!IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_MUST_HAVE_SERVER_LAUNCHED_GUIS_ENABLED_SETTINGS));
return true;
}
if (!GuiHost.isAvailable()) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_DESKTOP_UNAVAILABLE));
return true;
}
return false;
}
/**
* @return true if no studio is open or the player is not in one
*/
@@ -27,6 +27,15 @@ public class CommandStudioCreationContractTest {
assertEquals(NullableDimensionHandler.class, template.customHandler());
}
@Test
public void editorDimensionIsOptionalSoTheOpenStudioCanBeUsed() throws NoSuchMethodException {
Method command = CommandStudio.class.getDeclaredMethod("editor", IrisDimension.class);
Param dimension = command.getParameters()[0].getAnnotation(Param.class);
assertEquals("null", dimension.defaultValue());
assertEquals(NullableDimensionHandler.class, dimension.customHandler());
}
@Test
public void openExposesAnOptInForceFlag() throws NoSuchMethodException {
Method command = CommandStudio.class.getDeclaredMethod(
@@ -1,83 +0,0 @@
package art.arcane.iris.command;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import art.arcane.iris.studio.view.GuiHost;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CommandStudioDesktopTest {
private IrisSettings previousSettings;
private boolean previousSuppressed;
private RecordingSender sender;
private CommandStudio command;
@Before
public void setup() {
previousSettings = IrisSettings.settings;
previousSuppressed = GuiHost.isDesktopSuppressed();
IrisSettings.settings = new IrisSettings();
IrisSettings.settings.getGui().setUseServerLaunchedGuis(true);
GuiHost.suppressDesktop(true);
sender = new RecordingSender();
command = new TestCommand(sender);
}
@After
public void restore() {
IrisSettings.settings = previousSettings;
GuiHost.suppressDesktop(previousSuppressed);
}
@Test
public void mapReportsMissingDisplayBeforeAccessingWorld() {
command.map(null);
assertDisplayMessage();
}
@Test
public void imageMapReportsMissingDisplayInsteadOfDisabledSetting() {
command.imagemap(null);
assertDisplayMessage();
}
private void assertDisplayMessage() {
assertEquals(1, sender.messages.size());
assertTrue(sender.messages.getFirst(), sender.messages.getFirst().contains("display"));
}
private static final class TestCommand extends CommandStudio {
private final VolmitSender sender;
private TestCommand(VolmitSender sender) {
this.sender = sender;
}
@Override
public VolmitSender sender() {
return sender;
}
}
private static final class RecordingSender extends VolmitSender {
private final List<String> messages = new ArrayList<>();
private RecordingSender() {
super(null);
}
@Override
public void sendMessage(String message) {
messages.add(message);
}
}
}
@@ -1,99 +0,0 @@
package art.arcane.iris.command;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import art.arcane.iris.platform.generation.PlatformChunkGenerator;
import art.arcane.iris.studio.map.MapWindow;
import art.arcane.iris.studio.map.PaletteExplorerStart;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.world.IrisToolbelt;
import art.arcane.iris.world.task.J;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.junit.Test;
import org.mockito.MockedStatic;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
public class StudioMapPositionTest {
@Test
public void mapCapturesItsStartingPositionOnThePlayerScheduler() {
IrisSettings previous = IrisSettings.settings;
IrisSettings.settings = new IrisSettings();
IrisSettings.settings.getGui().setUseServerLaunchedGuis(true);
World world = mock(World.class);
Player player = mock(Player.class);
VolmitSender sender = mock(VolmitSender.class);
PlatformChunkGenerator generator = mock(PlatformChunkGenerator.class);
Engine engine = mock(Engine.class);
UUID playerId = UUID.randomUUID();
UUID worldId = UUID.randomUUID();
AtomicBoolean owned = new AtomicBoolean();
AtomicReference<Runnable> task = new AtomicReference<>();
AtomicReference<PaletteExplorerStart> start = new AtomicReference<>();
when(world.getUID()).thenReturn(worldId);
when(player.getUniqueId()).thenReturn(playerId);
when(player.isOnline()).thenReturn(true);
when(player.getWorld()).thenAnswer(invocation -> {
assertTrue("world read must use the player scheduler", owned.get());
return world;
});
when(player.getLocation()).thenAnswer(invocation -> {
assertTrue("location read must use the player scheduler", owned.get());
return new Location(world, 33.25D, 91D, -72.5D);
});
when(sender.isPlayer()).thenReturn(true);
when(sender.player()).thenReturn(player);
when(generator.getEngine()).thenReturn(engine);
CommandStudio command = new CommandStudio() {
@Override
public VolmitSender sender() {
return sender;
}
};
try (MockedStatic<GuiHost> host = mockStatic(GuiHost.class);
MockedStatic<IrisToolbelt> toolbelt = mockStatic(IrisToolbelt.class);
MockedStatic<J> scheduling = mockStatic(J.class);
MockedStatic<MapWindow> windows = mockStatic(MapWindow.class)) {
host.when(GuiHost::isAvailable).thenReturn(true);
toolbelt.when(() -> IrisToolbelt.isIrisWorld(world)).thenReturn(true);
toolbelt.when(() -> IrisToolbelt.access(world)).thenReturn(generator);
scheduling.when(() -> J.runEntity(same(player), any(Runnable.class), eq(0), any(Runnable.class)))
.thenAnswer(invocation -> {
task.set(invocation.getArgument(1));
return true;
});
windows.when(() -> MapWindow.openMap(any(PaletteExplorerStart.class))).thenAnswer(invocation -> {
start.set(invocation.getArgument(0));
return null;
});
command.map(world);
assertNull(start.get());
owned.set(true);
task.get().run();
assertEquals(engine, start.get().engine());
assertEquals(playerId, start.get().playerId());
assertEquals(worldId, start.get().worldId());
assertEquals(33.25D, start.get().centerX(), 0D);
assertEquals(-72.5D, start.get().centerZ(), 0D);
} finally {
IrisSettings.settings = previous;
}
}
}
@@ -46,6 +46,7 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeEntityBehavior;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeStateMerger;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.ModdedServerAccess;
import art.arcane.iris.studio.app.StudioAppInstaller;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.generation.decoration.DecoratorPlatformHooks;
@@ -492,6 +493,7 @@ public final class ModdedEngineBootstrap {
GuiHost.Provider previousGuiHost = GuiHost.get();
ModdedGuiHost.install();
rollback.add(() -> GuiHost.set(previousGuiHost));
StudioAppInstaller.installInBackground();
ModdedDecoratorHooks decoratorHooks = new ModdedDecoratorHooks();
DecoratorPlatformHooks.Bindings previousDecoratorBindings = DecoratorPlatformHooks.bind(decoratorHooks, decoratorHooks);
@@ -23,7 +23,8 @@ import art.arcane.iris.pack.loading.ResourceLoader;
import art.arcane.iris.pack.schema.SchemaBuilder;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.world.task.J;
import art.arcane.iris.studio.workspace.SchemaFiles;
import art.arcane.iris.studio.workspace.ZedProjectSettings;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.format.Form;
import art.arcane.volmlib.util.io.IO;
@@ -32,6 +33,9 @@ import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public final class ModdedWorkspaceGenerator {
private ModdedWorkspaceGenerator() {
@@ -42,17 +46,29 @@ public final class ModdedWorkspaceGenerator {
}
public static File writeWorkspace(IrisData data, File folder, boolean immediateSchemas) throws IOException {
JSONObject workspaceConfig = buildWorkspace(data, immediateSchemas);
List<CompletableFuture<String>> schemaWrites = new ArrayList<>();
JSONObject workspaceConfig = buildWorkspace(data, immediateSchemas, schemaWrites);
File workspace = new File(folder, folder.getName() + ".code-workspace");
IO.writeAll(workspace, workspaceConfig.toString(4));
JSONArray schemas = workspaceConfig.getJSONObject("settings").getJSONArray("json.schemas");
writeZedSettings(folder, schemas, schemaWrites);
return workspace;
}
public static JSONObject buildWorkspace(IrisData data) {
return buildWorkspace(data, false);
return buildWorkspace(data, false, new ArrayList<>());
}
private static JSONObject buildWorkspace(IrisData data, boolean immediateSchemas) {
private static void writeZedSettings(File folder, JSONArray schemas, List<CompletableFuture<String>> schemaWrites) {
try {
new ZedProjectSettings(folder).writeIrisSettings(schemas, SchemaFiles.awaitTexts(schemaWrites));
} catch (Throwable e) {
IrisLogging.reportError(e);
IrisLogging.warn("Could not update Zed schema mappings for " + folder.getAbsolutePath() + "; VSCode workspace generation will continue.");
}
}
private static JSONObject buildWorkspace(IrisData data, boolean immediateSchemas, List<CompletableFuture<String>> schemaWrites) {
JSONObject ws = new JSONObject();
JSONArray folders = new JSONArray();
JSONObject folder = new JSONObject();
@@ -82,17 +98,20 @@ public final class ModdedWorkspaceGenerator {
json.put("editor.suggest.insertMode", "replace");
settings.put("[json]", json);
settings.put("json.maxItemsComputed", 30000);
settings.put("json.schemas", buildSchemas(data, immediateSchemas));
settings.put("json.schemas", buildSchemas(data, immediateSchemas, schemaWrites));
ws.put("settings", settings);
return ws;
}
private static JSONArray buildSchemas(IrisData data, boolean immediateSchemas) {
private static JSONArray buildSchemas(IrisData data, boolean immediateSchemas, List<CompletableFuture<String>> schemaWrites) {
JSONArray schemas = new JSONArray();
// The shared instance keeps its file listings across edits, so files added, moved or removed since would be missing.
data.clearLists();
for (ResourceLoader<?> loader : data.getLoaders().v()) {
if (loader.supportsSchemas()) {
schemas.put(immediateSchemas ? loader.buildSchemaImmediately() : loader.buildSchema());
schemas.put(loader.schemaMapping());
schemaWrites.add(loader.writeSchemaFile(immediateSchemas));
}
}
@@ -110,17 +129,7 @@ public final class ModdedWorkspaceGenerator {
entry.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json");
schemas.put(entry);
File schemaFile = new File(data.getDataFolder(), ".iris/schema/snippet/" + snipType + "-schema.json");
if (immediateSchemas) {
IO.writeAll(schemaFile, new SchemaBuilder(snippetClass, data).construct().toString(4));
} else {
J.attemptAsync(() -> {
try {
IO.writeAll(schemaFile, new SchemaBuilder(snippetClass, data).construct().toString(4));
} catch (Throwable e) {
IrisLogging.reportError(e);
}
});
}
schemaWrites.add(SchemaFiles.write(schemaFile, () -> new SchemaBuilder(snippetClass, data).construct().toString(4), immediateSchemas));
} catch (Throwable e) {
if (immediateSchemas) {
throw new IllegalStateException("Could not write snippet schema for " + snippetClass.getName(), e);
@@ -31,7 +31,7 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandSource;
import art.arcane.volmlib.nativelib.terrain.NativeBlockPoint;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeEditPlayer;
import java.awt.Desktop;
import art.arcane.iris.studio.workspace.FileOpener;
import java.io.File;
final class ModdedEditCommands {
@@ -110,7 +110,7 @@ final class ModdedEditCommands {
}
private static int openJson(NativeCommandSource source, IrisRegistrant registrant) {
if (!GuiHost.isAvailable() || !Desktop.isDesktopSupported()) {
if (!GuiHost.isAvailable() || !FileOpener.isDesktopAvailable()) {
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_CANNOT_OPEN_FILES_HERE, MessageArgument.untrusted("value", ModdedGuiHost.guiUnavailableReason())));
return 0;
}
@@ -120,7 +120,7 @@ final class ModdedEditCommands {
}
File file = registrant.getLoadFile();
try {
Desktop.getDesktop().open(file);
FileOpener.open(file);
} catch (Throwable e) {
ModdedIrisLog.error("Iris edit failed to open {}", file, e);
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_COULD_NOT_OPEN, MessageArgument.untrusted("value", file.getName()), MessageArgument.untrusted("value2", e.getClass().getSimpleName())));
@@ -23,8 +23,11 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeWorldView;
import art.arcane.iris.modded.ModdedIrisLog;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.studio.map.MapWindow;
import art.arcane.iris.studio.map.PaletteExplorerStart;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.studio.bridge.StudioBridge;
import art.arcane.iris.studio.bridge.StudioBridges;
import art.arcane.iris.studio.bridge.StudioLaunch;
import art.arcane.iris.studio.bridge.StudioWindow;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.StructurePackageClosure;
@@ -74,7 +77,7 @@ import art.arcane.volmlib.nativelib.terrain.NativeWorld;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeProtocolPlayer;
import org.zeroturnaround.zip.ZipUtil;
import java.awt.Desktop;
import art.arcane.iris.studio.workspace.FileOpener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@@ -93,6 +96,9 @@ import java.util.regex.Pattern;
import java.util.stream.Stream;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.RuntimeUiMessages;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandText;
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandText.Format;
import art.arcane.iris.modded.localization.ModdedCommandMessages;
import art.arcane.volmlib.util.localization.LanguageAudience;
import art.arcane.volmlib.util.localization.MessageArgument;
@@ -226,11 +232,7 @@ public final class ModdedStudioCommands {
private static LiteralArgumentBuilder<NativeCommandSource> noiseTree(String name) {
return NativeCommandRegistration.literal(name)
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource(), null, 12345L)))
.then(NativeCommandRegistration.argument("generator", StringArgumentType.word()).suggests(GENERATOR_KEYS)
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource(), StringArgumentType.getString(context, "generator"), 12345L)))
.then(NativeCommandRegistration.argument("seed", LongArgumentType.longArg())
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource(), StringArgumentType.getString(context, "generator"), LongArgumentType.getLong(context, "seed"))))));
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource())));
}
private static LiteralArgumentBuilder<NativeCommandSource> mapTree(String name) {
@@ -243,88 +245,77 @@ public final class ModdedStudioCommands {
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> imageMap(context.getSource())));
}
private static int noise(NativeCommandSource source, String generatorKey, long seed) {
NativeWorld level = source.world();
Engine engine = IrisModdedCommands.engineFor(level);
if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
IrisModdedCommands.fail(source, guiUnavailableMessage());
return 0;
}
if (engine != null) {
NativeProtocolPlayer player = source.player();
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id());
}
Engine mapEngine = engine != null ? engine : GuiHost.get().findActiveEngine();
if ((generatorKey == null || generatorKey.isBlank()) && mapEngine != null) {
MapWindow.openNoise(mapStart(mapEngine, source.player()), new MapWindow.NoiseSelection(null, null, seed));
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_ON_SERVER_DISPLAY));
return 1;
}
private static int noise(NativeCommandSource source) {
Engine engine = IrisModdedCommands.engineFor(source.world());
if (engine == null) {
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_RUN_IRIS_STUDIO));
return 0;
}
IrisGenerator generator = engine.getData().getGeneratorLoader().load(generatorKey.trim());
if (generator == null) {
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_UNKNOWN_GENERATOR_PACK, MessageArgument.untrusted("generatorKey", generatorKey), MessageArgument.untrusted("value", engine.getDimension().getLoadKey())));
return 0;
}
String selectedGeneratorKey = generatorKey.trim();
MapWindow.openNoise(mapStart(engine, source.player()), new MapWindow.NoiseSelection(selectedGeneratorKey, generator, seed));
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_GENERATOR_SEED, MessageArgument.untrusted("value", generatorKey.trim()), MessageArgument.untrusted("seed", seed)));
return 1;
return openStudioApp(source, engine, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_ON_SERVER_DISPLAY));
}
private static int map(NativeCommandSource source) {
NativeWorld level = source.world();
Engine engine = IrisModdedCommands.engineFor(level);
Engine engine = IrisModdedCommands.engineFor(source.world());
if (engine == null) {
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_STAND_IRIS_STUDIO));
return 0;
}
if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
IrisModdedCommands.fail(source, guiUnavailableMessage());
return 0;
}
NativeProtocolPlayer player = source.player();
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id());
MapWindow.openMap(mapStart(engine, player));
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_VISION_MAP_ON_SERVER_DISPLAY, MessageArgument.untrusted("value", level.name())));
return 1;
}
// Modded worlds have no Bukkit world id; the map finds the engine again through the bound GUI context.
private static PaletteExplorerStart mapStart(Engine engine, NativeProtocolPlayer player) {
IrisWorld world = engine.getWorld();
NativeWorld level = world == null ? null : world.platformWorld();
boolean inWorld = player != null && player.connected() && level != null && player.inWorld(level);
return new PaletteExplorerStart(engine, null, player == null ? null : player.id(), null,
inWorld ? player.x() : 0D, inWorld ? player.z() : 0D);
return openStudioApp(source, engine, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_VISION_MAP_ON_SERVER_DISPLAY, MessageArgument.untrusted("value", source.world().name())));
}
private static int imageMap(NativeCommandSource source) {
NativeWorld level = source.world();
Engine engine = IrisModdedCommands.engineFor(level);
Engine engine = IrisModdedCommands.engineFor(source.world());
if (engine == null) {
IrisModdedCommands.fail(source, IrisLanguage.plain(
ModdedCommandMessages.MODDED_STUDIO_COMMANDS_IMAGE_MAP_REQUIRES_IRIS_DIMENSION
));
return 0;
}
if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
return openStudioApp(source, engine, IrisLanguage.plain(
ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_IMAGE_MAP_STUDIO_ON_SERVER_DISPLAY,
MessageArgument.untrusted("value", source.world().name())
));
}
/** Opens the studio app on the source's world; when it can't, tells the source why and hands over the link to connect by hand. */
private static int openStudioApp(NativeCommandSource source, Engine engine, String openedMessage) {
if (GuiHost.isDesktopSuppressed()) {
IrisModdedCommands.fail(source, guiUnavailableMessage());
return 0;
}
NativeWorld level = source.world();
NativeProtocolPlayer player = source.player();
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id());
MapWindow.openImageMaps(mapStart(engine, player));
IrisModdedCommands.ok(source, IrisLanguage.plain(
ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_IMAGE_MAP_STUDIO_ON_SERVER_DISPLAY,
MessageArgument.untrusted("value", level.name())
));
UUID openerId = player == null ? null : player.id();
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, openerId);
StudioBridge bridge;
try {
bridge = StudioBridges.open(level.name(), () -> engine, openerId);
} catch (IOException error) {
IrisModdedCommands.fail(source, "Could not open the studio bridge: " + error.getMessage());
return 0;
}
StudioLaunch launch = StudioWindow.show(bridge);
if (!launch.opened()) {
IrisLogging.info("Iris Studio link for %s: %s", level.name(), bridge.link());
sendStudioLink(source, launch, bridge.link());
return 0;
}
IrisModdedCommands.ok(source, openedMessage);
return 1;
}
private static void sendStudioLink(NativeCommandSource source, StudioLaunch launch, String link) {
IrisModdedCommands.fail(source, IrisLanguage.plain(launch.failureMessage()));
if (source.player() == null) {
return;
}
NativeCommandText hover = NativeCommandText.literal(IrisLanguage.plain(RuntimeUiMessages.STUDIO_LINK_COPY_HOVER));
NativeCommandText button = NativeCommandText.literal(IrisLanguage.plain(RuntimeUiMessages.STUDIO_LINK_COPY_BUTTON))
.withStyle(Format.GREEN)
.withStyle(style -> style.copyToClipboard(link).hover(hover));
IrisModdedCommands.ok(source, button);
}
private static LiteralArgumentBuilder<NativeCommandSource> workspaceTree(String name, boolean open) {
return NativeCommandRegistration.literal(name)
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> workspace(context.getSource(), null, open)))
@@ -349,12 +340,12 @@ public final class ModdedStudioCommands {
if (!open) {
return 1;
}
if (!GuiHost.isAvailable() || !Desktop.isDesktopSupported()) {
if (!GuiHost.isAvailable() || !FileOpener.isDesktopAvailable()) {
IrisModdedCommands.fail(source, guiUnavailableMessage());
return 0;
}
try {
Desktop.getDesktop().open(workspace);
FileOpener.open(workspace);
} catch (Throwable e) {
ModdedIrisLog.error("Iris workspace open failed for {}", workspace, e);
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_COULD_NOT_OPEN, MessageArgument.untrusted("value", workspace.getName()), MessageArgument.untrusted("value2", e.getClass().getSimpleName())));
@@ -21,6 +21,7 @@ package art.arcane.iris.modded.service;
import art.arcane.iris.modded.ModdedIrisLog;
import art.arcane.iris.studio.view.PregeneratorJob;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.studio.workspace.PackHotloadFolder;
import art.arcane.iris.world.WorldMaintenance;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.world.history.SavedTerrainChunk;
@@ -364,12 +365,10 @@ public final class ModdedStudioHotloadService implements ModdedTickableService,
if (watch.engine != engine) {
watch.close();
watch.engine = engine;
watch.folder = new ReactiveFolder(
watch.folder = PackHotloadFolder.watch(
engine.getData().getDataFolder(),
(KList<File> created, KList<File> changed, KList<File> deleted) -> hotload(dimensionId, engine),
new KList<>(".iob", ".json"),
new KList<>(".iris"),
new KList<>());
(KList<File> created, KList<File> changed, KList<File> deleted) -> hotload(dimensionId, engine));
return;
}
ReactiveFolder folder = watch.folder;
+65
View File
@@ -190,6 +190,63 @@ def generateNoiseNatives = tasks.register('generateNoiseNatives') {
}
}
}
// The studio app ships inside the Bukkit jar. The Electron build it runs on is 100+ MB per platform, so it stays out
// and is pinned instead: StudioAppInstaller downloads the host's archive from Electron's release at startup and
// checks it against these checksums.
File studioAppDirectory = file('studio')
List<String> electronPlatforms = ['linux-x64', 'linux-arm64', 'win32-x64', 'win32-arm64', 'darwin-x64', 'darwin-arm64']
Provider<String> electronVersion = providers.fileContents(layout.projectDirectory.file('studio/package-lock.json')).asText.map { String lock ->
(String) ((Map) ((Map) new groovy.json.JsonSlurper().parseText(lock)).packages).get('node_modules/electron').version
}
List<String> npmCommand = System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('win') ? ['cmd', '/c', 'npm'] : ['npm']
def installStudioDependencies = tasks.register('installStudioDependencies', Exec) {
inputs.files('studio/package.json', 'studio/package-lock.json')
outputs.file('studio/node_modules/.package-lock.json')
workingDir(studioAppDirectory)
commandLine(npmCommand + ['ci', '--no-audit', '--no-fund'])
}
def buildStudioApp = tasks.register('buildStudioApp', Exec) {
dependsOn(installStudioDependencies)
inputs.dir('studio/src')
inputs.files('studio/package.json', 'studio/package-lock.json', 'studio/electron.vite.config.ts', 'studio/tsconfig.json', 'studio/components.json')
outputs.dir('studio/out')
workingDir(studioAppDirectory)
commandLine(npmCommand + ['run', 'build'])
}
def bundleStudioApp = tasks.register('bundleStudioApp', Zip) {
from(buildStudioApp) {
into('out')
}
from('studio/package.json')
archiveFileName.set('studio-app.zip')
destinationDirectory.set(layout.buildDirectory.dir('generated/studio-app'))
preserveFileTimestamps = false
reproducibleFileOrder = true
}
def pinElectronRuntime = tasks.register('pinElectronRuntime') {
inputs.property('electronVersion', electronVersion)
inputs.property('platforms', electronPlatforms)
def pins = layout.buildDirectory.file('generated/studio-app-pins/studio-app.properties')
outputs.file(pins)
doLast {
String version = electronVersion.get()
String checksums = URI.create("https://github.com/electron/electron/releases/download/v${version}/SHASUMS256.txt")
.toURL().getText('UTF-8')
Map<String, String> checksumByArchive = checksums.readLines().collectEntries { String line ->
def match = line.trim() =~ /^([0-9a-f]{64}) \*?(\S+)$/
match.matches() ? [(match.group(2)): match.group(1)] : [:]
}
List<String> lines = ["electron.version=${version}".toString()]
electronPlatforms.each { String platform ->
String checksum = checksumByArchive.get("electron-v${version}-${platform}.zip".toString())
if (checksum == null) {
throw new GradleException("Electron ${version} publishes no ${platform} archive")
}
lines.add("${platform}.sha256=${checksum}".toString())
}
pins.get().asFile.setText(lines.join('\n') + '\n', 'UTF-8')
}
}
def jarJar = configurations.create('jarJar')
dependencies {
add('included', project(path: ':core', configuration: 'shadow'))
@@ -208,6 +265,12 @@ tasks.named('jar', Jar).configure {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
includeEmptyDirs = false
from(jarJar)
from(bundleStudioApp) {
into('META-INF/iris')
}
from(pinElectronRuntime) {
into('META-INF/iris')
}
from(provider { included.resolve().collect { zipTree(it) } }) {
exclude('META-INF/INDEX.LIST')
exclude('languages/**')
@@ -529,6 +592,8 @@ List<String> requiredBukkitArtifactEntries = [
'slimjar-resolutions.dat',
'META-INF/iris/native-runtime.properties',
NoiseNativeArtifacts.MANIFEST,
'META-INF/iris/studio-app.zip',
'META-INF/iris/studio-app.properties',
'META-INF/volmit/volmlib.properties',
'iris-language-source.properties',
'agent.jar',
@@ -28,6 +28,7 @@ import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Entity;
@@ -35,6 +36,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import java.util.List;
import java.util.Map;
@@ -196,6 +198,68 @@ public class CraftEngineDataProviderTest {
}
}
@Test
public void decayingCustomLeavesAreMadePersistentAndKeepTheirCustomIdentity() {
BooleanProperty persistent = BooleanProperty.create("persistent", false);
BlockDefinition definition = mock(BlockDefinition.class);
ImmutableBlockState decaying = blockState(definition, "test:leaves[persistent=false]");
ImmutableBlockState kept = blockState(definition, "test:leaves[persistent=true]");
BlockData base = mock(BlockData.class);
BlockData keptBase = mock(BlockData.class);
doReturn(persistent).when(decaying).getProperty("persistent");
doReturn(false).when(decaying).get(persistent);
when(decaying.with(persistent, true)).thenReturn(kept);
try (MockedStatic<CraftEngineBlocks> blocks = mockStatic(CraftEngineBlocks.class)) {
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(base)).thenReturn(decaying);
blocks.when(() -> CraftEngineBlocks.getBukkitBlockData(kept)).thenReturn(keptBase);
IrisCustomData result = (IrisCustomData) new CraftEngineDataProvider()
.withoutDecay(IrisCustomData.of(base, new Identifier("craftengine", "test/leaves[persistent=false]")));
assertSame(keptBase, result.getBase());
assertEquals(new Identifier("test", "leaves[persistent=true]"), result.getCustom());
}
}
@Test
public void persistentOrDecaylessCustomBlocksAreKeptAsTheyAre() {
BooleanProperty persistent = BooleanProperty.create("persistent", false);
BlockDefinition definition = mock(BlockDefinition.class);
ImmutableBlockState alreadyPersistent = blockState(definition, "test:leaves[persistent=true]");
ImmutableBlockState withoutProperty = blockState(definition, "test:log");
BlockData persistentData = mock(BlockData.class);
BlockData logData = mock(BlockData.class);
BlockData vanilla = mock(BlockData.class);
doReturn(persistent).when(alreadyPersistent).getProperty("persistent");
doReturn(true).when(alreadyPersistent).get(persistent);
try (MockedStatic<CraftEngineBlocks> blocks = mockStatic(CraftEngineBlocks.class)) {
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(persistentData)).thenReturn(alreadyPersistent);
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(logData)).thenReturn(withoutProperty);
CraftEngineDataProvider provider = new CraftEngineDataProvider();
assertSame(persistentData, provider.withoutDecay(persistentData));
assertSame(logData, provider.withoutDecay(logData));
assertSame(vanilla, provider.withoutDecay(vanilla));
}
}
@Test
public void customBlocksCarryTheTagsTheirSettingsListEvenWhenWrapped() {
ImmutableBlockState state = mock(ImmutableBlockState.class, Mockito.RETURNS_DEEP_STUBS);
BlockData base = mock(BlockData.class);
BlockData vanilla = mock(BlockData.class);
when(state.settings().tags()).thenReturn(Set.of(Key.of("minecraft:logs")));
try (MockedStatic<CraftEngineBlocks> blocks = mockStatic(CraftEngineBlocks.class)) {
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(base)).thenReturn(state);
CraftEngineDataProvider provider = new CraftEngineDataProvider();
BlockData wrapped = IrisCustomData.of(base, new Identifier("craftengine", "test/log"));
assertTrue(provider.hasBlockTag(wrapped, NamespacedKey.minecraft("logs")));
assertFalse(provider.hasBlockTag(wrapped, NamespacedKey.minecraft("leaves")));
assertFalse(provider.hasBlockTag(vanilla, NamespacedKey.minecraft("logs")));
}
}
@Test
public void unknownOrInvalidBlockPropertiesFailBeforeNativeConversion() {
Identifier id = new Identifier("test", "lamp");
@@ -23,7 +23,9 @@ import art.arcane.iris.world.IrisPaperLikeBackendMode;
import art.arcane.iris.world.IrisRuntimeSchedulerMode;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.studio.workspace.StudioEditor;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.volmlib.util.io.IO;
import art.arcane.volmlib.util.json.JSONException;
@@ -110,6 +112,7 @@ public class IrisSettings {
if (parsed != null) {
loaded = parsed;
}
loaded.migrateLegacySettings();
try {
IO.writeAll(s, new JSONObject(new Gson().toJson(loaded)).toString(4));
@@ -169,6 +172,7 @@ public class IrisSettings {
}
parsed.fillMissingSections();
parsed.migrateLegacySettings();
return parsed;
}
@@ -196,6 +200,12 @@ public class IrisSettings {
}
}
private void migrateLegacySettings() {
if (studio != null) {
studio.migrateLegacyOpenVSCode();
}
}
private void fillMissingSections() {
general = general == null ? new IrisSettingsGeneral() : general;
world = world == null ? new IrisSettingsWorld() : world;
@@ -399,11 +409,31 @@ public class IrisSettings {
@Data
public static class IrisSettingsStudio {
public boolean openVSCode = true;
public StudioEditor editor = StudioEditor.AUTO;
// Read-only bridge for iris.json files written before `editor` existed; Gson omits it again on save.
@SerializedName("openVSCode")
public Boolean legacyOpenVSCode = null;
public boolean blendChanges = true;
public boolean disableTimeAndWeather = true;
public boolean entitySpawning = true;
public boolean autoStartDefaultStudio = false;
public boolean downloadApp = true;
public String studioApp = "";
public String electron = "electron";
public StudioEditor getEditor() {
return editor == null ? StudioEditor.AUTO : editor;
}
private void migrateLegacyOpenVSCode() {
if (legacyOpenVSCode == null) {
return;
}
if (!legacyOpenVSCode) {
editor = StudioEditor.NONE;
}
legacyOpenVSCode = null;
}
}
@Data
@@ -84,6 +84,14 @@ public class B {
return state != null && state.isTreeBlock();
}
public static boolean isLog(NativeBlockState state) {
return state != null && state.isLog();
}
public static boolean isLeaves(NativeBlockState state) {
return state != null && state.isLeaves();
}
public static boolean isFoliagePlantable(NativeBlockState state) {
return state != null && state.isFoliagePlantable();
}
@@ -0,0 +1,136 @@
package art.arcane.iris.generation.cave;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.mantle.CaveProfilePreview;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.studio.scene.SceneBlocks;
import art.arcane.iris.studio.scene.SceneEntry;
import art.arcane.iris.studio.scene.SceneRequest;
import art.arcane.iris.studio.scene.SceneSizes;
import art.arcane.iris.studio.scene.SceneView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
/** The carved space of each enabled cave profile, as blocks coloured by depth. */
public final class CaveProfileSceneView implements SceneView {
private static final SceneSizes SIZES = new SceneSizes(List.of(64, 128, 256), 128);
private static final int VARIANTS = 4;
private static final int VARIANT_SPACING_BLOCKS = 4096;
private static final int SURFACE_ABOVE_SEA_BLOCKS = 48;
private static final int MAX_DEPTH_BLOCKS = 160;
private static final String DIMENSION_KEY = "dimension";
private static final String REGION_PREFIX = "region/";
private static final String BIOME_PREFIX = "biome/";
private static final String[] DEPTH_BANDS = {"minecraft:yellow_concrete", "minecraft:lime_concrete", "minecraft:light_blue_concrete",
"minecraft:purple_concrete"};
private static final int[][] NEIGHBOURS = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};
@Override
public String id() {
return "caveProfiles";
}
@Override
public String label() {
return "Cave profiles";
}
@Override
public String description() {
return "The carved space of each enabled cave profile of the dimension, its regions and its biomes";
}
@Override
public SceneSizes sizes() {
return SIZES;
}
@Override
public List<SceneEntry> entries(Engine engine) {
IrisData data = engine.getData();
IrisDimension dimension = engine.getDimension();
List<SceneEntry> entries = new ArrayList<>();
if (dimension.getCaveProfile().isEnabled()) {
entries.add(new SceneEntry(DIMENSION_KEY, dimension.getName(), "Dimension", VARIANTS));
}
for (IrisRegion region : data.getRegionLoader().loadAll(data.getRegionLoader().getPossibleKeys())) {
if (region != null && region.getCaveProfile().isEnabled()) {
entries.add(new SceneEntry(REGION_PREFIX + region.getLoadKey(), region.getName(), "Regions", VARIANTS));
}
}
for (IrisBiome biome : data.getBiomeLoader().loadAll(data.getBiomeLoader().getPossibleKeys())) {
if (biome != null && biome.getCaveProfile().isEnabled()) {
entries.add(new SceneEntry(BIOME_PREFIX + biome.getLoadKey(), biome.getName(), "Biomes", VARIANTS));
}
}
return entries;
}
@Override
public SceneBlocks scene(Engine engine, SceneRequest request) throws IOException {
IrisCaveProfile profile = profileOf(engine, request.key());
int size = request.size();
int surfaceY = Math.min(engine.getHeight() - 1, engine.getDimension().getFluidHeight() + SURFACE_ABOVE_SEA_BLOCKS);
int bottomY = Math.max(0, Math.max((int) Math.floor(profile.getVerticalRange().getMin()), surfaceY - MAX_DEPTH_BLOCKS));
int originX = Math.floorMod(request.variant(), VARIANTS) * VARIANT_SPACING_BLOCKS;
boolean[] carved = CaveProfilePreview.carve(engine, profile, originX, size, bottomY, surfaceY);
return outsideOf(carved, size, surfaceY - bottomY + 1);
}
private static IrisCaveProfile profileOf(Engine engine, String key) {
IrisData data = engine.getData();
IrisCaveProfile profile = null;
if (DIMENSION_KEY.equals(key)) {
profile = engine.getDimension().getCaveProfile();
} else if (key.startsWith(REGION_PREFIX)) {
IrisRegion region = data.getRegionLoader().load(key.substring(REGION_PREFIX.length()));
profile = region == null ? null : region.getCaveProfile();
} else if (key.startsWith(BIOME_PREFIX)) {
IrisBiome biome = data.getBiomeLoader().load(key.substring(BIOME_PREFIX.length()));
profile = biome == null ? null : biome.getCaveProfile();
}
if (profile == null) {
throw new NoSuchElementException("No cave profile " + key);
}
return profile;
}
// Only the carved blocks on the outside of the space are kept, as the inside could not be seen.
private static SceneBlocks outsideOf(boolean[] carved, int size, int height) {
SceneBlocks scene = new SceneBlocks();
for (int y = 0; y < height; y++) {
String band = DEPTH_BANDS[Math.min(DEPTH_BANDS.length - 1, (height - 1 - y) * DEPTH_BANDS.length / height)];
for (int z = 0; z < size; z++) {
for (int x = 0; x < size; x++) {
if (carved[cellOf(x, y, z, size)] && touchesRock(carved, x, y, z, size, height)) {
scene.add(x, y, z, band);
}
}
}
}
return scene;
}
private static boolean touchesRock(boolean[] carved, int x, int y, int z, int size, int height) {
for (int[] step : NEIGHBOURS) {
int nx = x + step[0];
int ny = y + step[1];
int nz = z + step[2];
boolean inside = nx >= 0 && ny >= 0 && nz >= 0 && nx < size && ny < height && nz < size;
if (!inside || !carved[cellOf(nx, ny, nz, size)]) {
return true;
}
}
return false;
}
private static int cellOf(int x, int y, int z, int size) {
return (y * size + z) * size + x;
}
}
@@ -0,0 +1,72 @@
package art.arcane.iris.generation.decoration.formation;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.studio.scene.SceneBlocks;
import art.arcane.iris.studio.scene.SceneEntry;
import art.arcane.iris.studio.scene.SceneForm;
import art.arcane.iris.studio.scene.SceneRequest;
import art.arcane.iris.studio.scene.SceneView;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/** How each formation profile shapes a formation's width from base to top. */
public final class FormationProfileSceneView implements SceneView {
private static final Set<String> HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "mode", "carvingSupport",
"surfaceSupportBuffer", "underwater", "profile");
@Override
public String id() {
return "formationProfiles";
}
@Override
public String label() {
return "Formation profiles";
}
@Override
public String description() {
return "How each formation profile shapes a formation's width from base to top";
}
@Override
public List<SceneEntry> entries(Engine engine) {
int variants = new IrisFormation().getVariants();
return Arrays.stream(IrisFormationProfile.values()).map(profile -> SceneEntry.preset(profile, variants)).toList();
}
@Override
public boolean hasForm() {
return true;
}
@Override
public SceneForm form(Engine engine, String key, Map<String, String> overrides) {
return SceneForm.of("Formation", formationOf(key, overrides), HIDDEN, overrides,
List.of(SceneForm.describe(profileOf(key)), "Values typed here change the preview only"));
}
@Override
public SceneBlocks scene(Engine engine, SceneRequest request) {
IrisFormation formation = formationOf(request.key(), request.overrides());
return SceneBlocks.ofVariant(formation.getVariantObjects(engine.getData()), request.variant(), "formation");
}
private static IrisFormation formationOf(String key, Map<String, String> overrides) {
IrisFormation formation = SceneForm.withOverrides(new IrisFormation(), overrides);
formation.setProfile(profileOf(key));
return formation;
}
private static IrisFormationProfile profileOf(String key) {
try {
return IrisFormationProfile.valueOf(key);
} catch (IllegalArgumentException unknown) {
throw new NoSuchElementException("No formation profile " + key);
}
}
}
@@ -0,0 +1,72 @@
package art.arcane.iris.generation.decoration.tree;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.studio.scene.SceneBlocks;
import art.arcane.iris.studio.scene.SceneEntry;
import art.arcane.iris.studio.scene.SceneForm;
import art.arcane.iris.studio.scene.SceneRequest;
import art.arcane.iris.studio.scene.SceneView;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/** The canopy shape each tree profile gives a procedural tree. */
public final class TreeProfileSceneView implements SceneView {
private static final Set<String> HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "plausible", "mode",
"carvingSupport", "underwater", "profile");
@Override
public String id() {
return "treeProfiles";
}
@Override
public String label() {
return "Tree profiles";
}
@Override
public String description() {
return "The canopy shape each tree profile gives a procedural tree";
}
@Override
public List<SceneEntry> entries(Engine engine) {
int variants = new IrisProceduralTree().getVariants();
return Arrays.stream(IrisTreeProfile.values()).map(profile -> SceneEntry.preset(profile, variants)).toList();
}
@Override
public boolean hasForm() {
return true;
}
@Override
public SceneForm form(Engine engine, String key, Map<String, String> overrides) {
return SceneForm.of("Tree", treeOf(key, overrides), HIDDEN, overrides,
List.of(SceneForm.describe(profileOf(key)), "Values typed here change the preview only"));
}
@Override
public SceneBlocks scene(Engine engine, SceneRequest request) {
IrisProceduralTree tree = treeOf(request.key(), request.overrides());
return SceneBlocks.ofVariant(tree.getVariantObjects(engine.getData()), request.variant(), "tree");
}
private static IrisProceduralTree treeOf(String key, Map<String, String> overrides) {
IrisProceduralTree tree = SceneForm.withOverrides(new IrisProceduralTree(), overrides);
tree.setProfile(profileOf(key));
return tree;
}
private static IrisTreeProfile profileOf(String key) {
try {
return IrisTreeProfile.valueOf(key);
} catch (IllegalArgumentException unknown) {
throw new NoSuchElementException("No tree profile " + key);
}
}
}
@@ -0,0 +1,99 @@
package art.arcane.iris.generation.hydrology.config;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.studio.scene.SceneBlocks;
import art.arcane.iris.studio.scene.SceneEntry;
import art.arcane.iris.studio.scene.SceneForm;
import art.arcane.iris.studio.scene.SceneRequest;
import art.arcane.iris.studio.scene.SceneSizes;
import art.arcane.iris.studio.scene.SceneView;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
/** The blocks of each named fluid of the dimension's hydrology, in a pool lined with its seam. */
public final class FluidProfileSceneView implements SceneView {
private static final SceneSizes SIZES = new SceneSizes(List.of(16, 32, 64), 32);
private static final int VARIANTS = 4;
private static final int VARIANT_SPACING_BLOCKS = 1024;
private static final int DEPTH_BLOCKS = 3;
private static final String BASIN_BLOCK = "minecraft:stone";
@Override
public String id() {
return "fluidProfiles";
}
@Override
public String label() {
return "Fluid profiles";
}
@Override
public String description() {
return "The blocks of each named fluid of the dimension's hydrology, in a pool lined with its seam";
}
@Override
public SceneSizes sizes() {
return SIZES;
}
@Override
public List<SceneEntry> entries(Engine engine) {
return fluids(engine).stream().map(fluid -> new SceneEntry(fluid.getName(), fluid.getName(), "Fluids", VARIANTS)).toList();
}
@Override
public boolean hasForm() {
return true;
}
@Override
public SceneForm form(Engine engine, String key, Map<String, String> overrides) {
IrisFluidProfile fluid = fluidOf(engine, key);
IrisData data = engine.getData();
List<String> notes = new ArrayList<>();
notes.add("Blocks: " + String.join(", ", fluid.getPalette().getBlockData(data).stream().map(state -> state.key()).toList()));
notes.add("Seam: " + (fluid.getSeam() == null ? "none" : fluid.getSeam()));
return new SceneForm("Fluid", List.of(), notes);
}
@Override
public SceneBlocks scene(Engine engine, SceneRequest request) {
IrisData data = engine.getData();
IrisFluidProfile fluid = fluidOf(engine, request.key());
IrisFluidProfile seam = fluid.getSeam() == null ? null : fluidOf(engine, fluid.getSeam());
int size = request.size();
int offset = Math.floorMod(request.variant(), VARIANTS) * VARIANT_SPACING_BLOCKS;
RNG rng = new RNG(offset + 1L);
SceneBlocks scene = new SceneBlocks();
for (int z = 0; z < size; z++) {
for (int x = 0; x < size; x++) {
scene.add(x, 0, z, BASIN_BLOCK);
boolean wall = x == 0 || z == 0 || x == size - 1 || z == size - 1;
boolean seamRing = seam != null && (x == 1 || z == 1 || x == size - 2 || z == size - 2);
for (int y = 1; y <= DEPTH_BLOCKS; y++) {
IrisFluidProfile filling = seamRing ? seam : fluid;
scene.add(x, y, z, wall ? BASIN_BLOCK : filling.getPalette().get(rng, x + offset, y, z, data).key());
}
}
}
return scene;
}
private static KList<IrisFluidProfile> fluids(Engine engine) {
return engine.getDimension().getHydrology().getFluids();
}
private static IrisFluidProfile fluidOf(Engine engine, String key) {
Optional<IrisFluidProfile> found = fluids(engine).stream().filter(fluid -> key.equals(fluid.getName())).findFirst();
return found.orElseThrow(() -> new NoSuchElementException("No fluid profile " + key));
}
}
@@ -0,0 +1,106 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisEngineMantle;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.Stream;
/**
* Carves one cave profile with the engine's own carver over a square of flat ground, in a mantle of its own so the
* world's is left alone, and says which blocks it opened.
*/
public final class CaveProfilePreview {
private static final int CHUNK_BLOCKS = 16;
private static final int CHUNK_COLUMNS = CHUNK_BLOCKS * CHUNK_BLOCKS;
private static final int PREFETCH_CHUNKS = 0;
private static final int ACCESS_CHUNKS = 1;
private CaveProfilePreview() {
}
/**
* The carved space of a square, {@code size} blocks across and a whole number of chunks, from {@code bottomY} up to
* and including {@code surfaceY}, both in engine-local Y (0 is the bottom of the dimension).
*
* @return one flag per block, {@code (y - bottomY) * size² + z * size + x}
*/
public static boolean[] carve(Engine engine, IrisCaveProfile profile, int originX, int size, int bottomY, int surfaceY)
throws IOException {
int height = surfaceY - bottomY + 1;
boolean[] carved = new boolean[height * size * size];
Path folder = Files.createTempDirectory("iris-cave-preview");
Mantle<Matter> mantle = IrisEngineMantle.createMantle(engine, folder, engine::getData);
try {
IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile);
int[] surface = new int[CHUNK_COLUMNS];
Arrays.fill(surface, surfaceY);
double[] weights = new double[CHUNK_COLUMNS];
Arrays.fill(weights, 1D);
int firstChunkX = Math.floorDiv(originX, CHUNK_BLOCKS);
int chunks = size / CHUNK_BLOCKS;
for (int chunkZ = 0; chunkZ < chunks; chunkZ++) {
for (int chunkX = 0; chunkX < chunks; chunkX++) {
int worldChunkX = firstChunkX + chunkX;
try (MantleWriter writer = new MantleWriter(engine.getMantle(), mantle, worldChunkX, chunkZ, PREFETCH_CHUNKS, ACCESS_CHUNKS, false)) {
carver.carve(writer, worldChunkX, chunkZ, weights, 0D, 0D, null, surface);
}
readCarved(mantle, carved, worldChunkX, chunkZ, chunkX, chunkZ, size, bottomY, surfaceY);
}
}
} finally {
mantle.close();
deleteQuietly(folder);
}
return carved;
}
private static void readCarved(Mantle<Matter> mantle, boolean[] carved, int worldChunkX, int worldChunkZ, int chunkX, int chunkZ,
int size, int bottomY, int surfaceY) {
for (int y = bottomY; y <= surfaceY; y++) {
for (int z = 0; z < CHUNK_BLOCKS; z++) {
for (int x = 0; x < CHUNK_BLOCKS; x++) {
MatterCavern cavern = mantle.get(worldChunkX * CHUNK_BLOCKS + x, y, worldChunkZ * CHUNK_BLOCKS + z, MatterCavern.class);
if (cavern == null) {
continue;
}
int cell = (y - bottomY) * size * size + (chunkZ * CHUNK_BLOCKS + z) * size + chunkX * CHUNK_BLOCKS + x;
carved[cell] = true;
}
}
}
}
private static void deleteQuietly(Path folder) {
try (Stream<Path> paths = Files.walk(folder)) {
paths.sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete());
} catch (IOException ignored) {
}
}
}
@@ -62,6 +62,9 @@ public class IrisNoiseGenerator {
private static final long GENERATOR_SEED_SALT = 33_955_677L;
private static final int MINIMUM_FRACTURE_DEPTH = 4;
private static final int MAXIMUM_FRACTURE_NODES = 32;
// Fracture axes as CNG.reseededForAxis numbers them for a 2D read: x is axis 0, z is axis 1.
static final int X_AXIS = 0;
static final int Z_AXIS = 1;
private static final ThreadLocal<FractureSamples> FRACTURE_SAMPLES = ThreadLocal.withInitial(FractureSamples::new);
@Getter(AccessLevel.NONE)
@@ -144,6 +147,14 @@ public class IrisNoiseGenerator {
}
double getNoise(long superSeed, double xv, double zv, IrisData data, Engine engine) {
return getNoiseForAxis(superSeed, xv, zv, data, engine, X_AXIS);
}
/**
* This layer read as the fracture of one axis. Each axis samples this layer's generator reseeded for that axis at
* the same coordinates, so the x and z warps are uncorrelated instead of mirror images of each other.
*/
private double getNoiseForAxis(long superSeed, double xv, double zv, IrisData data, Engine engine, int axis) {
if (!enabled) {
return offsetY;
}
@@ -154,7 +165,7 @@ public class IrisNoiseGenerator {
samples.active = true;
try {
if (samples.prepare(this, superSeed, data, engine)) {
return samples.sample(xv, zv);
return samples.sample(xv, zv, axis);
}
} finally {
samples.clear();
@@ -169,13 +180,13 @@ public class IrisNoiseGenerator {
for (IrisNoiseGenerator i : fracture) {
if (i.isEnabled()) {
double fractureOffset = i.getOpacity() / 2D;
x += i.getNoise(superSeed + seed + g, xv, zv, data, engine) - fractureOffset;
z += i.getNoise(superSeed + seed + g, zv, xv, data, engine) - fractureOffset;
x += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, X_AXIS) - fractureOffset;
z += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, Z_AXIS) - fractureOffset;
}
g += 819;
}
return sample(getGenerator(superSeed, data, engine), x, z);
return sample(getGenerator(superSeed, data, engine).reseededForAxis(axis), x, z);
}
boolean supportsBatch() {
@@ -200,6 +211,10 @@ public class IrisNoiseGenerator {
}
NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine) {
return compileProgram(superSeed, data, engine, false);
}
private NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine, boolean readAsFracture) {
if (!enabled) {
return NoiseLayerProgram.disabled(this);
}
@@ -215,13 +230,14 @@ public class IrisNoiseGenerator {
int compiled = 0;
for (IrisNoiseGenerator child : fracture) {
if (child.isEnabled()) {
children[compiled] = child.compileProgram(superSeed + seed + salt, data, engine);
children[compiled] = child.compileProgram(superSeed + seed + salt, data, engine, true);
offsets[compiled++] = child.getOpacity() / 2D;
}
salt += 819;
}
CNG generator = Objects.requireNonNull(getGenerator(superSeed, data, engine), "Noise layer generator");
return NoiseLayerProgram.of(this, NoiseProgram.compile2D(generator), children, offsets);
NoiseProgram zAxisProgram = readAsFracture ? NoiseProgram.compile2D(generator.reseededForAxis(Z_AXIS)) : null;
return NoiseLayerProgram.of(this, NoiseProgram.compile2D(generator), zAxisProgram, children, offsets);
}
public KList<IrisNoiseGenerator> getAllComposites() {
@@ -357,20 +373,26 @@ public class IrisNoiseGenerator {
return false;
}
private double sample(double x, double z) {
/**
* Both axes of a fracture node read the same warped coordinates, since a reseeded generator shares the
* node's own fracture, so each level samples its generator once per axis.
*/
private double sample(double x, double z, int rootAxis) {
int leaf = size - 1;
double forward = nodes[leaf].sample(generators[leaf], x, z);
double reverse = nodes[leaf].sample(generators[leaf], z, x);
for (int index = leaf - 1; index >= 0; index--) {
double offset = nodes[index + 1].opacity / 2D;
double forwardX = x + (forward - offset);
double forwardZ = z + (reverse - offset);
forward = nodes[index].sample(generators[index], forwardX, forwardZ);
if (index > 0) {
reverse = nodes[index].sample(generators[index], forwardZ, forwardX);
}
if (leaf == 0) {
return nodes[0].sample(generators[0].reseededForAxis(rootAxis), x, z);
}
return forward;
double warpX = nodes[leaf].sample(generators[leaf], x, z);
double warpZ = nodes[leaf].sample(generators[leaf].reseededForAxis(Z_AXIS), x, z);
for (int index = leaf - 1; index > 0; index--) {
double offset = nodes[index + 1].opacity / 2D;
double warpedX = x + (warpX - offset);
double warpedZ = z + (warpZ - offset);
warpX = nodes[index].sample(generators[index], warpedX, warpedZ);
warpZ = nodes[index].sample(generators[index].reseededForAxis(Z_AXIS), warpedX, warpedZ);
}
double offset = nodes[1].opacity / 2D;
return nodes[0].sample(generators[0].reseededForAxis(rootAxis), x + (warpX - offset), z + (warpZ - offset));
}
private void clear() {
@@ -9,6 +9,7 @@ public final class NoiseLayerProgram {
private final boolean enabled;
private final double offsetY;
private final NoiseProgram program;
private final NoiseProgram zAxisProgram;
private final double zoom;
private final double opacity;
private final double offsetX;
@@ -21,10 +22,12 @@ public final class NoiseLayerProgram {
private final NoiseLayerProgram[] children;
private final double[] childOffsets;
private NoiseLayerProgram(IrisNoiseGenerator layer, NoiseProgram program, NoiseLayerProgram[] children, double[] childOffsets) {
private NoiseLayerProgram(IrisNoiseGenerator layer, NoiseProgram program, NoiseProgram zAxisProgram,
NoiseLayerProgram[] children, double[] childOffsets) {
this.enabled = program != null;
this.offsetY = layer.getOffsetY();
this.program = program;
this.zAxisProgram = zAxisProgram;
this.zoom = layer.getZoom();
this.opacity = layer.getOpacity();
this.offsetX = layer.getOffsetX();
@@ -39,11 +42,16 @@ public final class NoiseLayerProgram {
}
static NoiseLayerProgram disabled(IrisNoiseGenerator layer) {
return new NoiseLayerProgram(layer, null, new NoiseLayerProgram[0], new double[0]);
return new NoiseLayerProgram(layer, null, null, new NoiseLayerProgram[0], new double[0]);
}
static NoiseLayerProgram of(IrisNoiseGenerator layer, NoiseProgram program, NoiseLayerProgram[] children, double[] childOffsets) {
return new NoiseLayerProgram(layer, program, children, childOffsets);
/**
* zAxisProgram is the layer's generator reseeded for the z axis; only a layer read as a fracture needs it, and the
* root layer passes null.
*/
static NoiseLayerProgram of(IrisNoiseGenerator layer, NoiseProgram program, NoiseProgram zAxisProgram,
NoiseLayerProgram[] children, double[] childOffsets) {
return new NoiseLayerProgram(layer, program, zAxisProgram, children, childOffsets);
}
public void evaluate(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] out) {
@@ -53,143 +61,110 @@ public final class NoiseLayerProgram {
}
int mark = scratch.mark();
try {
fill(scratch, xs, zs, count, out);
double[] sampleX = scratch.buffer(count);
double[] sampleZ = scratch.buffer(count);
warpedSampleCoordinates(scratch, xs, zs, count, sampleX, sampleZ);
program.fill2D(scratch.noise(), sampleX, sampleZ, count, out);
applyPost(out, count);
} finally {
scratch.reset(mark);
}
}
private void fill(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] out) {
double[] sampleX = scratch.buffer(count);
double[] sampleZ = scratch.buffer(count);
if (children.length == 0) {
for (int index = 0; index < count; index++) {
sampleX[index] = (xs[index] / zoom) + offsetX;
sampleZ[index] = (zs[index] / zoom) + offsetZ;
}
} else {
System.arraycopy(xs, 0, sampleX, 0, count);
System.arraycopy(zs, 0, sampleZ, 0, count);
double[] forward = scratch.buffer(count);
double[] reverse = scratch.buffer(count);
for (int child = 0; child < children.length; child++) {
children[child].evaluatePair(scratch, xs, zs, count, forward, reverse);
double offset = childOffsets[child];
for (int index = 0; index < count; index++) {
sampleX[index] += forward[index] - offset;
sampleZ[index] += reverse[index] - offset;
}
}
for (int index = 0; index < count; index++) {
sampleX[index] = (sampleX[index] / zoom) + offsetX;
sampleZ[index] = (sampleZ[index] / zoom) + offsetZ;
}
}
program.fill2D(scratch.noise(), sampleX, sampleZ, count, out);
for (int index = 0; index < count; index++) {
out[index] = post(out[index]);
}
}
void evaluatePair(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] forward, double[] reverse) {
/** Fills this layer read as a fracture: the x warp from its generator, the z warp from its z-axis generator. */
void evaluateAxes(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] xWarp, double[] zWarp) {
if (!enabled) {
Arrays.fill(forward, 0, count, offsetY);
Arrays.fill(reverse, 0, count, offsetY);
Arrays.fill(xWarp, 0, count, offsetY);
Arrays.fill(zWarp, 0, count, offsetY);
return;
}
int mark = scratch.mark();
try {
fillPair(scratch, xs, zs, count, forward, reverse);
double[] sampleX = scratch.buffer(count);
double[] sampleZ = scratch.buffer(count);
warpedSampleCoordinates(scratch, xs, zs, count, sampleX, sampleZ);
program.fill2D(scratch.noise(), sampleX, sampleZ, count, xWarp);
zAxisProgram.fill2D(scratch.noise(), sampleX, sampleZ, count, zWarp);
applyPost(xWarp, count);
applyPost(zWarp, count);
} finally {
scratch.reset(mark);
}
}
private void fillPair(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] forward, double[] reverse) {
int pairs = count * 2;
double[] sampleX = scratch.buffer(pairs);
double[] sampleZ = scratch.buffer(pairs);
private void warpedSampleCoordinates(TerrainBatchScratch scratch, double[] xs, double[] zs, int count,
double[] sampleX, double[] sampleZ) {
System.arraycopy(xs, 0, sampleX, 0, count);
System.arraycopy(zs, 0, sampleZ, 0, count);
System.arraycopy(zs, 0, sampleX, count, count);
System.arraycopy(xs, 0, sampleZ, count, count);
if (children.length > 0) {
double[] childForward = scratch.buffer(count);
double[] childReverse = scratch.buffer(count);
double[] childX = scratch.buffer(count);
double[] childZ = scratch.buffer(count);
for (int child = 0; child < children.length; child++) {
children[child].evaluatePair(scratch, xs, zs, count, childForward, childReverse);
children[child].evaluateAxes(scratch, xs, zs, count, childX, childZ);
double offset = childOffsets[child];
for (int index = 0; index < count; index++) {
sampleX[index] += childForward[index] - offset;
sampleZ[index] += childReverse[index] - offset;
sampleX[count + index] += childReverse[index] - offset;
sampleZ[count + index] += childForward[index] - offset;
sampleX[index] += childX[index] - offset;
sampleZ[index] += childZ[index] - offset;
}
}
}
for (int index = 0; index < pairs; index++) {
for (int index = 0; index < count; index++) {
sampleX[index] = (sampleX[index] / zoom) + offsetX;
sampleZ[index] = (sampleZ[index] / zoom) + offsetZ;
}
double[] values = scratch.buffer(pairs);
program.fill2D(scratch.noise(), sampleX, sampleZ, pairs, values);
for (int index = 0; index < count; index++) {
forward[index] = post(values[index]);
reverse[index] = post(values[count + index]);
}
}
public double sample(TerrainBatchScratch scratch, double x, double z) {
if (!enabled) {
return offsetY;
}
double sampleX = x;
double sampleZ = z;
if (children.length > 0) {
int mark = scratch.mark();
try {
double[] pair = scratch.buffer(2);
for (int child = 0; child < children.length; child++) {
children[child].samplePair(scratch, x, z, pair);
double offset = childOffsets[child];
sampleX += pair[0] - offset;
sampleZ += pair[1] - offset;
}
} finally {
scratch.reset(mark);
}
int mark = scratch.mark();
try {
double[] sampleCoordinates = scratch.buffer(2);
warpedSampleCoordinate(scratch, x, z, sampleCoordinates);
return post(program.sample2D(sampleCoordinates[0], sampleCoordinates[1]));
} finally {
scratch.reset(mark);
}
return post(program.sample2D((sampleX / zoom) + offsetX, (sampleZ / zoom) + offsetZ));
}
private void samplePair(TerrainBatchScratch scratch, double x, double z, double[] out) {
private void sampleAxes(TerrainBatchScratch scratch, double x, double z, double[] out) {
if (!enabled) {
out[0] = offsetY;
out[1] = offsetY;
return;
}
double forwardX = x;
double forwardZ = z;
double reverseX = z;
double reverseZ = x;
int mark = scratch.mark();
try {
double[] sampleCoordinates = scratch.buffer(2);
warpedSampleCoordinate(scratch, x, z, sampleCoordinates);
out[0] = post(program.sample2D(sampleCoordinates[0], sampleCoordinates[1]));
out[1] = post(zAxisProgram.sample2D(sampleCoordinates[0], sampleCoordinates[1]));
} finally {
scratch.reset(mark);
}
}
private void warpedSampleCoordinate(TerrainBatchScratch scratch, double x, double z, double[] out) {
double sampleX = x;
double sampleZ = z;
if (children.length > 0) {
int mark = scratch.mark();
try {
double[] pair = scratch.buffer(2);
for (int child = 0; child < children.length; child++) {
children[child].samplePair(scratch, x, z, pair);
double offset = childOffsets[child];
forwardX += pair[0] - offset;
forwardZ += pair[1] - offset;
reverseX += pair[1] - offset;
reverseZ += pair[0] - offset;
}
} finally {
scratch.reset(mark);
double[] warp = scratch.buffer(2);
for (int child = 0; child < children.length; child++) {
children[child].sampleAxes(scratch, x, z, warp);
double offset = childOffsets[child];
sampleX += warp[0] - offset;
sampleZ += warp[1] - offset;
}
}
out[0] = post(program.sample2D((forwardX / zoom) + offsetX, (forwardZ / zoom) + offsetZ));
out[1] = post(program.sample2D((reverseX / zoom) + offsetX, (reverseZ / zoom) + offsetZ));
out[0] = (sampleX / zoom) + offsetX;
out[1] = (sampleZ / zoom) + offsetZ;
}
private void applyPost(double[] values, int count) {
for (int index = 0; index < count; index++) {
values[index] = post(values[index]);
}
}
private double post(double raw) {
@@ -14,6 +14,7 @@ import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
@@ -128,6 +129,25 @@ public abstract class ExternalDataProvider {
return false;
}
/**
* @param data The block to keep, possibly an {@link IrisCustomData} this provider returned from {@link #getBlockData}
* @return The block made to never decay, like custom leaves, or {@code data} itself when it is not one of the
* provider's decaying blocks
*/
@NotNull
public BlockData withoutDecay(@NotNull BlockData data) {
return data;
}
/**
* @param data The block to check, possibly an {@link IrisCustomData} this provider returned from {@link #getBlockData}
* @param tag A block tag, like {@code minecraft:logs}
* @return Whether the block is one of the provider's blocks and carries that tag
*/
public boolean hasBlockTag(@NotNull BlockData data, @NotNull NamespacedKey tag) {
return false;
}
/**
* Spawns a mob in the specified location using the given engine and entity identifier.
*
@@ -30,6 +30,7 @@ import art.arcane.volmlib.util.collection.KMap;
import art.arcane.iris.platform.bukkit.plugin.IrisService;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Entity;
@@ -193,6 +194,26 @@ public class ExternalDataSVC implements IrisService {
return blockData;
}
/** The block made to never decay by the provider it belongs to, or {@code data} itself. */
public BlockData withoutDecay(BlockData data) {
for (ExternalDataProvider provider : activeProviders) {
BlockData kept = provider.withoutDecay(data);
if (kept == data) {
continue;
}
if (kept instanceof IrisCustomData custom && data instanceof IrisCustomData) {
return IrisCustomData.of(custom.getBase(), qualifyBlockId(provider, custom.getCustom()));
}
return kept;
}
return data;
}
/** Whether {@code data} is a provider's block carrying {@code tag}. */
public boolean hasBlockTag(BlockData data, NamespacedKey tag) {
return activeProviders.stream().anyMatch(provider -> provider.hasBlockTag(data, tag));
}
public Optional<BlockData> getBlockData(final Identifier key) {
Pair<Identifier, KMap<String, String>> pair;
try {
@@ -30,6 +30,7 @@ import net.momirealms.craftengine.core.util.Key;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Entity;
@@ -57,6 +58,7 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis
BlockProperty.ofBoolean("randomPitch", false),
BlockProperty.ofDouble("pitch", 0, 0, 360f, false, true)
);
private static final String PERSISTENT_PROPERTY = "persistent";
private static final ContentRegistry EMPTY_CONTENT = new ContentRegistry(Set.of(), Set.of(), false);
private volatile ContentRegistry content = EMPTY_CONTENT;
@@ -131,6 +133,32 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis
return state == null || state.isEmpty() ? Optional.empty() : Optional.of(Identifier.fromString(state.toString()));
}
@Override
public @NotNull BlockData withoutDecay(@NotNull BlockData data) {
ImmutableBlockState state = customStateOf(data);
if (state == null) {
return data;
}
Property<Boolean> persistent = state.getProperty(PERSISTENT_PROPERTY);
if (persistent == null || persistent.valueClass() != Boolean.class || state.get(persistent)) {
return data;
}
ImmutableBlockState kept = state.with(persistent, true);
return IrisCustomData.of(CraftEngineBlocks.getBukkitBlockData(kept), Identifier.fromString(kept.toString()));
}
@Override
public boolean hasBlockTag(@NotNull BlockData data, @NotNull NamespacedKey tag) {
ImmutableBlockState state = customStateOf(data);
return state != null && state.settings().tags().contains(Key.of(tag.getNamespace(), tag.getKey()));
}
private static ImmutableBlockState customStateOf(BlockData data) {
BlockData nativeData = data instanceof IrisCustomData custom ? custom.getBase() : data;
ImmutableBlockState state = CraftEngineBlocks.getCustomBlockState(nativeData);
return state == null || state.isEmpty() ? null : state;
}
@Override
public boolean placeBlock(@NotNull Block block, @NotNull Identifier blockId) {
Pair<Identifier, KMap<String, String>> parsed = ExternalDataSVC.parseState(blockId);
@@ -94,9 +94,17 @@ public final class BukkitCommandMessagesExtended {
"iris.bukkit.commandedit.cannot_find_file_perhaps_it_was_not_loaded_directly_from",
C.GOLD + "Cannot find the file; Perhaps it was not loaded directly from a file?"
);
public static final TextKey COMMAND_EDIT_OPENING_VSCODE = TextKey.of(
"iris.bukkit.commandedit.opening_vscode",
C.GREEN + "Opening " + "{value}" + " " + "{value2}" + " in VSCode! "
public static final TextKey COMMAND_EDIT_OPENING_IN_EDITOR = TextKey.of(
"iris.bukkit.commandedit.opening_in_editor",
C.GREEN + "Opening " + "{value}" + " " + "{value2}" + " in " + "{editor}" + "!"
);
public static final TextKey COMMAND_EDIT_COULD_NOT_OPEN_EDITOR = TextKey.of(
"iris.bukkit.commandedit.could_not_open_editor",
C.RED + "Could not open " + "{editor}" + ". Check the console."
);
public static final TextKey COMMAND_EDIT_NO_EDITOR_CONFIGURED = TextKey.of(
"iris.bukkit.commandedit.no_editor_configured",
C.RED + "No editor configured. Set studio.editor to vscode or zed in iris.json."
);
public static final TextKey COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST = TextKey.of(
"iris.bukkit.commandedit.cant_find_file_registrant_does_not_exist",
@@ -106,10 +114,6 @@ public final class BukkitCommandMessagesExtended {
"iris.bukkit.commandedit.cannot_find_file_perhaps_it_was_not_loaded_directly_from_2",
C.GOLD + "Cannot find the file; Perhaps it was not loaded directly from a file?"
);
public static final TextKey COMMAND_EDIT_OPENING_VSCODE_2 = TextKey.of(
"iris.bukkit.commandedit.opening_vscode_2",
C.GREEN + "Opening " + "{value}" + " " + "{value2}" + " in VSCode! "
);
public static final TextKey COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST_2 = TextKey.of(
"iris.bukkit.commandedit.cant_find_file_registrant_does_not_exist_2",
C.RED + "Cant find the file. Or registrant does not exist"
@@ -118,10 +122,6 @@ public final class BukkitCommandMessagesExtended {
"iris.bukkit.commandedit.cannot_find_file_perhaps_it_was_not_loaded_directly_from_3",
C.GOLD + "Cannot find the file; Perhaps it was not loaded directly from a file?"
);
public static final TextKey COMMAND_EDIT_OPENING_VSCODE_3 = TextKey.of(
"iris.bukkit.commandedit.opening_vscode_3",
C.GREEN + "Opening " + "{value}" + " " + "{value2}" + " in VSCode! "
);
public static final TextKey COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST_3 = TextKey.of(
"iris.bukkit.commandedit.cant_find_file_registrant_does_not_exist_3",
C.RED + "Cant find the file. Or registrant does not exist"
@@ -555,9 +555,9 @@ public final class BukkitCommandMessagesExtended {
"iris.bukkit.commandstudio.could_not_resolve_pack_dimension",
C.RED + "Could not resolve the pack for dimension " + "{value}"
);
public static final TextKey COMMAND_STUDIO_OPENING_VSCODE_PACK = TextKey.of(
"iris.bukkit.commandstudio.opening_vscode_pack",
C.GREEN + "Opening VSCode for the \"" + "{value}" + "\" pack"
public static final TextKey COMMAND_STUDIO_OPENING_EDITOR_PACK = TextKey.of(
"iris.bukkit.commandstudio.opening_editor_pack",
C.GREEN + "Opening " + "{editor}" + " for the \"" + "{value}" + "\" pack"
);
public static final TextKey COMMAND_STUDIO_PACK_HAS_VERSION = TextKey.of(
"iris.bukkit.commandstudio.pack_has_version",
@@ -787,13 +787,13 @@ public final class BukkitCommandMessagesExtended {
COMMAND_EDIT_CANNOT_OPEN_FILES_HEADLESS_ENVIRONMENTS,
COMMAND_EDIT_DESKTOP_IS_NOT_SUPPORTED_BY_THIS_ENVIRONMENT,
COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM,
COMMAND_EDIT_OPENING_VSCODE,
COMMAND_EDIT_OPENING_IN_EDITOR,
COMMAND_EDIT_COULD_NOT_OPEN_EDITOR,
COMMAND_EDIT_NO_EDITOR_CONFIGURED,
COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST,
COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_2,
COMMAND_EDIT_OPENING_VSCODE_2,
COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST_2,
COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_3,
COMMAND_EDIT_OPENING_VSCODE_3,
COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST_3,
COMMAND_FIND_NOT_IRIS_WORLD,
COMMAND_FIND_NOT_IRIS_WORLD_2,
@@ -901,7 +901,7 @@ public final class BukkitCommandMessagesExtended {
COMMAND_STUDIO_OPENING_STUDIO_PACK_SEED,
COMMAND_STUDIO_PROVIDE_DIMENSION_PACK_IRIS_STD_IMPORTVANILLA_PACK_DIMENSION,
COMMAND_STUDIO_COULD_NOT_RESOLVE_PACK_DIMENSION,
COMMAND_STUDIO_OPENING_VSCODE_PACK,
COMMAND_STUDIO_OPENING_EDITOR_PACK,
COMMAND_STUDIO_PACK_HAS_VERSION,
COMMAND_STUDIO_OPENING_NOISE_EXPLORER,
COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO,
@@ -777,13 +777,13 @@ public final class DirectorCommandMessages {
"iris.director.commandstudio.param.also_import_vanilla_datapack_structures_jigsaw_into_pack",
"Also import vanilla & datapack structures/jigsaw into the pack"
);
public static final TextKey COMMAND_STUDIO_DIRECTOR_OPEN_VSCODE_DIMENSION = TextKey.of(
"iris.director.commandstudio.director.open_vscode_dimension",
"Open VSCode for a dimension"
public static final TextKey COMMAND_STUDIO_DIRECTOR_OPEN_EDITOR_DIMENSION = TextKey.of(
"iris.director.commandstudio.director.open_editor_dimension",
"Open the configured editor for a dimension"
);
public static final TextKey COMMAND_STUDIO_PARAM_DIMENSION_OPEN_VSCODE = TextKey.of(
"iris.director.commandstudio.param.dimension_open_vscode",
"The dimension to open VSCode for"
public static final TextKey COMMAND_STUDIO_PARAM_DIMENSION_OPEN_EDITOR = TextKey.of(
"iris.director.commandstudio.param.dimension_open_editor",
"The dimension to open the editor for"
);
public static final TextKey COMMAND_STUDIO_DIRECTOR_HOTLOAD_ACTIVE_STUDIO_PACK = TextKey.of(
"iris.director.commandstudio.director.hotload_active_studio_pack",
@@ -1134,8 +1134,8 @@ public final class DirectorCommandMessages {
COMMAND_STUDIO_PARAM_DIMENSION_PACK_IMPORT_VANILLA_CONTENT_INTO,
COMMAND_STUDIO_PARAM_HOW_MANY_VARIANTS_CAPTURE_PER_TREE_OBJECT_FEATURE,
COMMAND_STUDIO_PARAM_ALSO_IMPORT_VANILLA_DATAPACK_STRUCTURES_JIGSAW_INTO_PACK,
COMMAND_STUDIO_DIRECTOR_OPEN_VSCODE_DIMENSION,
COMMAND_STUDIO_PARAM_DIMENSION_OPEN_VSCODE,
COMMAND_STUDIO_DIRECTOR_OPEN_EDITOR_DIMENSION,
COMMAND_STUDIO_PARAM_DIMENSION_OPEN_EDITOR,
COMMAND_STUDIO_DIRECTOR_CLOSE_OPEN_STUDIO_PROJECT,
COMMAND_STUDIO_DIRECTOR_HOTLOAD_ACTIVE_STUDIO_PACK,
COMMAND_STUDIO_DIRECTOR_TOGGLE_YOUR_STUDIO_DEBUG_SCOREBOARD,
@@ -116,6 +116,7 @@ final class IrisLanguageGuide {
Map.entry("dumpPath", "Location of the saved cleanup or restore data."),
Map.entry("duration", "Formatted duration of the operation."),
Map.entry("e", "Exception text from a failed structure-template scan."),
Map.entry("editor", "Name of the studio editor Iris opens, such as VSCode or Zed."),
Map.entry("elapsed", "Formatted time elapsed since the operation started."),
Map.entry("engines", "Number of active Iris generation engines or dimensions."),
Map.entry("entity", "Entity type selected by the inspected spawner."),
@@ -78,6 +78,14 @@ public final class RuntimeUiMessages {
public static final TextKey DUST_OBJECTS_IN_CHUNK = TextKey.of("iris.runtime.dust.objects_in_chunk", "Objects in chunk: {objects}");
public static final TextKey DUST_COPY_BUTTON = TextKey.of("iris.runtime.dust.copy_button", "[Click to copy these stats]");
public static final TextKey DUST_COPY_HOVER = TextKey.of("iris.runtime.dust.copy_hover", "Copy block stats to clipboard");
public static final TextKey STUDIO_APP_DOWNLOAD_OFF = TextKey.of("iris.runtime.studio.app_download_off", "Studio app download is off: set studio.downloadApp to true in iris.json.");
public static final TextKey STUDIO_APP_NO_DISPLAY = TextKey.of("iris.runtime.studio.app_no_display", "This server has no display to open the studio app on.");
public static final TextKey STUDIO_APP_DOWNLOADING = TextKey.of("iris.runtime.studio.app_downloading", "Studio app is still downloading; try again in a moment.");
public static final TextKey STUDIO_APP_UNAVAILABLE = TextKey.of("iris.runtime.studio.app_unavailable", "Studio app unavailable; see the console.");
public static final TextKey STUDIO_APP_NOT_BUILT = TextKey.of("iris.runtime.studio.app_not_built", "Studio app not built: run npm run build in its folder.");
public static final TextKey STUDIO_APP_FAILED_TO_START = TextKey.of("iris.runtime.studio.app_failed_to_start", "Studio app failed to start; see the console.");
public static final TextKey STUDIO_LINK_COPY_BUTTON = TextKey.of("iris.runtime.studio.link_copy_button", "[Copy studio link]");
public static final TextKey STUDIO_LINK_COPY_HOVER = TextKey.of("iris.runtime.studio.link_copy_hover", "Paste it into the studio app's connect screen");
public static final TextKey DUST_REVEAL_FAILED = TextKey.of("iris.runtime.dust.reveal_failed", "Object reveal failed; see the console for details.");
public static final TextKey DUST_BIOME_LOADING = TextKey.of("iris.runtime.dust.biome_loading", "Saved biome information is loading. Try revealing this block again shortly.");
public static final TextKey WHAT_MATERIAL = TextKey.of("iris.runtime.what.material", "Material: {material}");
@@ -196,6 +204,14 @@ public final class RuntimeUiMessages {
DUST_OBJECTS_IN_CHUNK,
DUST_COPY_BUTTON,
DUST_COPY_HOVER,
STUDIO_APP_DOWNLOAD_OFF,
STUDIO_APP_NO_DISPLAY,
STUDIO_APP_DOWNLOADING,
STUDIO_APP_UNAVAILABLE,
STUDIO_APP_NOT_BUILT,
STUDIO_APP_FAILED_TO_START,
STUDIO_LINK_COPY_BUTTON,
STUDIO_LINK_COPY_HOVER,
DUST_REVEAL_FAILED,
DUST_BIOME_LOADING,
WHAT_MATERIAL,
@@ -63,7 +63,6 @@ public final class IrisDatapackCompiler {
private static final int INPUT_FINGERPRINT_SCHEMA = 4;
private static final int INPUT_BUFFER_BYTES = 64 * 1024;
private static final int WORLD_PACK_SCAN_DEPTH = 8;
private static final String DIMENSION_TYPE_FOLDER = "data/iris/dimension_type";
private static final Pattern REGISTRY_KEY_PATTERN = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+");
private static final List<String> INPUT_DIRECTORIES = List.of("dimensions", "biomes", "snippet");
private static final String FLAT_VOID_LEVEL_STEM = """
@@ -211,7 +210,16 @@ public final class IrisDatapackCompiler {
if (aliasContext.retainedContract() != null) {
data.bindGenerationRegistryContract(aliasContext.retainedContract());
}
for (IrisDimension dimension : loadPack(data).dimensions()) {
ResourceLoader<IrisDimension> loader = data.getDimensionLoader();
String[] possibleKeys = loader.getPossibleKeys();
if (possibleKeys == null || possibleKeys.length == 0) {
throw new IOException("Iris pack has no dimension definitions: " + packRoot);
}
for (String possibleKey : possibleKeys) {
IrisDimension dimension = loader.load(possibleKey);
if (dimension == null) {
throw new IOException("Unable to load Iris dimension '" + possibleKey + "' from " + packRoot);
}
collectRegistryRequirements(
requirements,
biomeTags,
@@ -447,7 +455,6 @@ public final class IrisDatapackCompiler {
Map<String, KSet<String>> biomes = new LinkedHashMap<>();
Map<String, List<DimensionCandidate>> dimensions = new LinkedHashMap<>();
Map<Path, GenerationHistory.PackInspection> histories = new LinkedHashMap<>();
PackUse packUse = new PackUse(packRoots, normalizedBindings);
int packCount = 0;
int dimensionCount = 0;
for (File packRoot : packRoots) {
@@ -461,8 +468,18 @@ public final class IrisDatapackCompiler {
if (aliasContext.retainedContract() != null) {
data.bindGenerationRegistryContract(aliasContext.retainedContract());
}
ResourceLoader<IrisDimension> loader = data.getDimensionLoader();
String[] possibleKeys = loader.getPossibleKeys();
if (possibleKeys == null || possibleKeys.length == 0) {
throw new IOException("Iris pack has no dimension definitions: " + packRoot);
}
int installedDimensions = 0;
for (IrisDimension dimension : dimensionsOfUsedPack(packRoot, loadPack(data), packUse)) {
for (String possibleKey : possibleKeys) {
IrisDimension dimension = loader.load(possibleKey);
if (dimension == null) {
throw new IOException("Unable to load Iris dimension '" + possibleKey + "' from " + packRoot);
}
IrisLogging.debug(" Compiling Dimension " + dimension.getLoadFile().getPath());
height.merge(dimension);
dimensions.computeIfAbsent(dimension.getLoadKey(), ignored -> new ArrayList<>())
@@ -497,73 +514,12 @@ public final class IrisDatapackCompiler {
}
IrisDimension.writeShared(datapackRoots, height, adjustVanillaHeight);
createDimensionTypeFolders(datapackRoots);
installRetainedRegistrySources(packRoots, datapackRoots, fixer, histories);
installLevelStemBindings(normalizedBindings, dimensions, datapackRoots);
validateOutputs(datapackRoots, dimensionCount, normalizedBindings.size());
return new CompilationResult(packCount, dimensionCount, countBiomes(biomes));
}
/**
* A pack that cannot load stops the compile when a world uses it, so the server never starts that world without
* its dimension; a pack no world uses is left out with a warning.
*/
private static List<IrisDimension> dimensionsOfUsedPack(File packRoot, LoadedPack pack, PackUse packUse)
throws IOException {
if (pack.loads()) {
return pack.dimensions();
}
List<String> users = packUse.worldsUsing(packRoot, pack.dimensionKeys());
if (!users.isEmpty()) {
throw new IOException("Iris pack " + packRoot + " cannot load (" + pack.refusal() + ") and world(s) "
+ String.join(", ", users) + " use it. Fix the pack, then start the server again.");
}
IrisLogging.warn("Iris pack %s cannot load (%s). No world uses it, so it is left out and the server starts.",
packRoot, pack.refusal());
return List.of();
}
/** Every dimension of the pack, or none with the reason when any of them cannot load; never part of a pack. */
private static LoadedPack loadPack(IrisData data) {
ResourceLoader<IrisDimension> loader = data.getDimensionLoader();
String[] possibleKeys = loader.getPossibleKeys();
if (possibleKeys == null || possibleKeys.length == 0) {
return LoadedPack.refused(List.of(), "it has no dimension definitions");
}
List<String> dimensionKeys = List.of(possibleKeys);
List<IrisDimension> loaded = new ArrayList<>();
for (String key : dimensionKeys) {
IrisDimension dimension;
try {
dimension = loader.load(key);
} catch (RuntimeException failure) {
return LoadedPack.refused(dimensionKeys, "its dimension '" + key + "' failed to load: " + failure.getMessage());
}
if (dimension == null) {
return LoadedPack.refused(dimensionKeys, "its dimension '" + key + "' failed to load; the error above says why");
}
loaded.add(dimension);
}
return new LoadedPack(dimensionKeys, List.copyOf(loaded), null);
}
private record LoadedPack(List<String> dimensionKeys, List<IrisDimension> dimensions, String refusal) {
static LoadedPack refused(List<String> dimensionKeys, String refusal) {
return new LoadedPack(dimensionKeys, List.of(), refusal);
}
boolean loads() {
return refusal == null;
}
}
/** The dimension type folder exists in every compiled datapack, so one built only from left-out packs reads as complete. */
private static void createDimensionTypeFolders(Collection<File> datapackRoots) throws IOException {
for (File datapackRoot : datapackRoots) {
Files.createDirectories(datapackRoot.toPath().resolve(DIMENSION_TYPE_FOLDER));
}
}
public static void installRetainedRegistrySources(List<File> packRoots, Collection<File> datapackRoots,
IDataFixer fixer) throws IOException {
installRetainedRegistrySources(packRoots, datapackRoots, fixer, new LinkedHashMap<>());
@@ -1032,7 +988,7 @@ public final class IrisDatapackCompiler {
if (!Files.isRegularFile(root.resolve("pack.mcmeta"))) {
throw new IOException("Iris datapack metadata was not generated at " + root);
}
if (dimensionCount > 0 && !Files.isDirectory(root.resolve(DIMENSION_TYPE_FOLDER))) {
if (dimensionCount > 0 && !Files.isDirectory(root.resolve("data/iris/dimension_type"))) {
throw new IOException("Iris dimension types were not generated at " + root);
}
if (levelStemCount > 0 && !Files.isDirectory(root.resolve("data/iris/dimension"))) {
@@ -1,111 +0,0 @@
package art.arcane.iris.pack.datapack;
import art.arcane.iris.world.WorldSlotKey;
import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration.IrisGeneratorBinding;
import java.io.File;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Which worlds use a pack the startup datapack is compiled from. A pack copied into a world's folder
* ({@code <world>/iris/pack} or {@code <world>/iris/generation/epochs/<epoch>/pack}) belongs to that world, configured
* or not. A pack installed in Iris's own folder is used by every bound world that selects one of its dimensions and
* has no copy of its own.
*/
final class PackUse {
private static final String DIMENSIONS_FOLDER = "dimensions";
private static final String WORLD_IRIS_FOLDER = "iris";
private static final String WORLD_PACK_FOLDER = "pack";
private static final String GENERATION_FOLDER = "generation";
private static final String EPOCHS_FOLDER = "epochs";
private final Set<WorldSlotKey> worldsWithOwnPack;
private final List<IrisGeneratorBinding> bindings;
PackUse(Collection<File> packRoots, List<IrisGeneratorBinding> bindings) {
this.worldsWithOwnPack = packRoots.stream()
.map(root -> worldFolderOwning(root.toPath()))
.flatMap(Optional::stream)
.map(PackUse::slotKeyOf)
.flatMap(Optional::stream)
.collect(Collectors.toUnmodifiableSet());
this.bindings = List.copyOf(bindings);
}
/** The names of the worlds that use the pack at {@code packRoot}, which defines {@code dimensions}. */
List<String> worldsUsing(File packRoot, Collection<String> dimensions) {
Optional<Path> ownerFolder = worldFolderOwning(packRoot.toPath());
if (ownerFolder.isPresent()) {
return List.of(nameOfWorld(ownerFolder.get()));
}
return bindings.stream()
.filter(binding -> dimensions.contains(binding.dimension()))
.filter(binding -> !worldsWithOwnPack.contains(binding.worldKey()))
.map(IrisGeneratorBinding::configuredWorldName)
.toList();
}
private String nameOfWorld(Path worldFolder) {
Optional<WorldSlotKey> worldKey = slotKeyOf(worldFolder);
if (worldKey.isEmpty()) {
return nameOf(worldFolder);
}
return bindings.stream()
.filter(binding -> binding.worldKey().equals(worldKey.get()))
.map(IrisGeneratorBinding::configuredWorldName)
.findFirst()
.orElse(worldKey.get().toString());
}
/** The folder of the world whose copy the pack at {@code packRoot} is, or empty for a pack installed outside any world. */
static Optional<Path> worldFolderOwning(Path packRoot) {
Path pack = packRoot.toAbsolutePath().normalize();
if (!WORLD_PACK_FOLDER.equals(nameOf(pack))) {
return Optional.empty();
}
Path parent = pack.getParent();
if (WORLD_IRIS_FOLDER.equals(nameOf(parent))) {
return Optional.ofNullable(parent.getParent());
}
Path epochs = parentOf(parent);
Path generation = parentOf(epochs);
Path iris = parentOf(generation);
if (EPOCHS_FOLDER.equals(nameOf(epochs))
&& GENERATION_FOLDER.equals(nameOf(generation))
&& WORLD_IRIS_FOLDER.equals(nameOf(iris))) {
return Optional.ofNullable(iris.getParent());
}
return Optional.empty();
}
/** The key of a world stored at {@code <level>/dimensions/<namespace>/<key>}, or empty for the level's own folder. */
static Optional<WorldSlotKey> slotKeyOf(Path worldFolder) {
for (Path namespace = parentOf(worldFolder); namespace != null; namespace = namespace.getParent()) {
if (DIMENSIONS_FOLDER.equals(nameOf(namespace.getParent()))) {
return slotKey(nameOf(namespace), namespace.relativize(worldFolder));
}
}
return Optional.empty();
}
private static Optional<WorldSlotKey> slotKey(String namespace, Path world) {
try {
return Optional.of(new WorldSlotKey(namespace, world.toString().replace(File.separatorChar, '/')));
} catch (IllegalArgumentException notAWorldKey) {
return Optional.empty();
}
}
private static Path parentOf(Path path) {
return path == null ? null : path.getParent();
}
private static String nameOf(Path path) {
return path == null || path.getFileName() == null ? null : path.getFileName().toString();
}
}
@@ -143,7 +143,7 @@ public final class NoiseStyleCompiler implements StyleCompiler {
Field center = new Field.Const(-child.getOpacity() / 2.0);
String childPath = path + "/f" + index + "_" + child.getSeed();
warpX = sum(warpX, binary(Field.BinaryOp.ADD, layer(child, domain, emit, childPath + "x"), center));
warpZ = sum(warpZ, binary(Field.BinaryOp.ADD, layer(child, domain.swapped(), emit, childPath + "z"), center));
warpZ = sum(warpZ, binary(Field.BinaryOp.ADD, layer(child, domain, emit, childPath + "z"), center));
}
Domain sampled = domain.layer(positive(layer.getZoom(), "layer zoom"), layer.getOffsetX(), layer.getOffsetZ(), warpX, warpZ);
Field value = style(layer.getStyle(), layer.getOctaves(), sampled, emit, path);
@@ -208,7 +208,7 @@ public final class NoiseStyleCompiler implements StyleCompiler {
Displacement leafDisplacement = displacement;
if (warped(cng)) {
Field warpX = displacement(node(cng.getFracture(), displacement, emit, path + "/x"), cng.getFscale());
Field warpZ = displacement(node(cng.getFracture(), displacement.swapped(), emit, path + "/z"), cng.getFscale());
Field warpZ = displacement(node(cng.getFracture(), displacement, emit, path + "/z"), cng.getFscale());
leafDisplacement = displacement.warped(warpX, warpZ);
}
value = leaf(type, cng.getOct(), cng.getEffectiveScale() * multiplier, leafDisplacement, emit, path);
@@ -483,19 +483,11 @@ public final class NoiseStyleCompiler implements StyleCompiler {
sum(warpX, layerWarpX == null ? null : scaled(layerWarpX, zoom)),
sum(warpZ, layerWarpZ == null ? null : scaled(layerWarpZ, zoom)));
}
private Domain swapped() {
return new Domain(zoom, offsetZ, offsetX, warpZ, warpX);
}
}
private record Displacement(double offsetX, double offsetZ, Field warpX, Field warpZ) {
private static final Displacement NONE = new Displacement(0.0, 0.0, null, null);
private Displacement swapped() {
return new Displacement(offsetZ, offsetX, warpZ, warpX);
}
private Displacement warped(Field addedX, Field addedZ) {
return new Displacement(offsetX, offsetZ, sum(warpX, addedX), sum(warpZ, addedZ));
}
@@ -25,6 +25,7 @@ import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.Strictness;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
@@ -954,6 +955,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
File f = new File(getDataFolder(), r + ".json");
if (f.exists()) {
try (JsonReader snippetReader = new JsonReader(new FileReader(f))){
snippetReader.setStrictness(Strictness.LENIENT);
return adapter.read(snippetReader);
} catch (IrisEngineStreamType.UnknownStreamException unknownStream) {
throw unknownStream;
@@ -22,10 +22,10 @@ import art.arcane.iris.pack.validation.CompatStatus;
import art.arcane.iris.pack.validation.ContentGate;
import com.google.gson.GsonBuilder;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.studio.workspace.StudioEditorLauncher;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.awt.Desktop;
import java.io.File;
@Data
@@ -62,9 +62,9 @@ public abstract class IrisRegistrant {
}
public File openInVSCode() {
public File openInEditor() {
try {
Desktop.getDesktop().open(getLoadFile());
StudioEditorLauncher.openFile(getLoader().getDataFolder(), getLoadFile());
} catch (Throwable e) {
IrisLogging.reportError(e);
}
@@ -25,6 +25,7 @@ import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.pack.schema.SchemaBuilder;
import art.arcane.iris.pack.PackValidator;
import art.arcane.iris.studio.workspace.SchemaFiles;
import art.arcane.iris.generation.runtime.PreservationRegistry;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.runtime.Engine;
@@ -66,8 +67,10 @@ import java.util.Comparator;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -75,6 +78,7 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
@@ -92,7 +96,7 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
private static final int PREFETCH_KEY_LENGTH_LIMIT = 1_024;
private static final long PREFETCH_FILE_SIZE_LIMIT = 4L * 1_024L * 1_024L;
private static volatile ExecutorService schemaBuildExecutor;
private static final Set<String> schemaBuildQueue = ConcurrentHashMap.newKeySet();
private static final Map<String, CompletableFuture<String>> schemaBuildQueue = new ConcurrentHashMap<>();
protected final AtomicCache<KList<File>> folderCache;
protected volatile KSet<String> firstAccess;
protected File root;
@@ -144,7 +148,7 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
private static synchronized ExecutorService schemaBuildExecutor() {
ExecutorService current = schemaBuildExecutor;
if (current == null || current.isShutdown()) {
schemaBuildQueue.clear();
abandonQueuedSchemaBuilds();
current = Executors.newSingleThreadExecutor(runnable -> {
Thread thread = new Thread(runnable, "Iris-Schema-Builder");
thread.setDaemon(true);
@@ -160,16 +164,12 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
return current;
}
public JSONObject buildSchema() {
return buildSchema(false);
private static void abandonQueuedSchemaBuilds() {
schemaBuildQueue.values().forEach(build -> build.complete(SchemaFiles.FAILED_SCHEMA_TEXT));
schemaBuildQueue.clear();
}
public JSONObject buildSchemaImmediately() {
return buildSchema(true);
}
private JSONObject buildSchema(boolean immediate) {
IrisLogging.debug("Building Schema " + objectClass.getSimpleName() + " " + root.getPath());
public JSONObject schemaMapping() {
JSONObject o = new JSONObject();
KList<String> fm = new KList<>();
@@ -179,39 +179,40 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
o.put("fileMatch", new JSONArray(fm.toArray()));
o.put("url", "./.iris/schema/" + getFolderName() + "-schema.json");
File a = new File(getManager().getDataFolder(), ".iris/schema/" + getFolderName() + "-schema.json");
if (immediate) {
try {
IO.writeAll(a, new SchemaBuilder(objectClass, manager).construct().toString(4));
} catch (IOException e) {
throw new IllegalStateException("Could not write schema " + a.getAbsolutePath(), e);
}
return o;
}
String schemaPath = a.getAbsolutePath();
if (schemaBuildQueue.add(schemaPath)) {
try {
schemaBuildExecutor().execute(() -> {
try {
IO.writeAll(a, new SchemaBuilder(objectClass, manager).construct().toString(4));
} catch (Throwable e) {
IrisLogging.reportError(e);
} finally {
schemaBuildQueue.remove(schemaPath);
}
});
} catch (RejectedExecutionException rejected) {
// Never let a dead pool leak the queue entry or escape into workspace
// generation (which would delete the user's .code-workspace on the way out).
schemaBuildQueue.remove(schemaPath);
IrisLogging.warn("Schema build skipped (executor unavailable): " + schemaPath);
}
}
return o;
}
public CompletableFuture<String> writeSchemaFile(boolean immediate) {
IrisLogging.debug("Building Schema " + objectClass.getSimpleName() + " " + root.getPath());
File schemaFile = new File(getManager().getDataFolder(), ".iris/schema/" + getFolderName() + "-schema.json");
Supplier<String> schemaText = () -> new SchemaBuilder(objectClass, manager).construct().toString(4);
if (immediate) {
return SchemaFiles.write(schemaFile, schemaText, true);
}
String schemaPath = schemaFile.getAbsolutePath();
CompletableFuture<String> build = new CompletableFuture<>();
CompletableFuture<String> queued = schemaBuildQueue.putIfAbsent(schemaPath, build);
if (queued != null) {
return queued;
}
try {
schemaBuildExecutor().execute(() -> {
String text = SchemaFiles.writeReporting(schemaFile, schemaText);
schemaBuildQueue.remove(schemaPath, build);
build.complete(text);
});
} catch (RejectedExecutionException rejected) {
// Never let a dead pool leak the queue entry or escape into workspace
// generation (which would delete the user's .code-workspace on the way out).
schemaBuildQueue.remove(schemaPath, build);
build.complete(SchemaFiles.FAILED_SCHEMA_TEXT);
IrisLogging.warn("Schema build skipped (executor unavailable): " + schemaPath);
}
return build;
}
public File findFile(String name) {
if (name == null || name.trim().isEmpty()) {
return null;
@@ -24,7 +24,6 @@ import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import java.awt.GraphicsEnvironment;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
@@ -35,6 +34,7 @@ final class SchemaRegistryCatalog {
/** Namespaced key or family/namespace prefix: "minecraft:village_plains", "minecraft:village", "nova_structures:". */
static final String VANILLA_STRUCTURE_PREFIX_PATTERN = "^[a-z0-9_.-]+:[a-z0-9_./-]*$";
private static final String MINECRAFT_NAMESPACE = "minecraft:";
private static final String[] LOGICAL_FONT_FAMILIES = {"Dialog", "DialogInput", "Monospaced", "SansSerif", "Serif"};
private static volatile JSONArray fontTypes;
private final SchemaBuilder builder;
private JSONArray potionTypes;
@@ -44,18 +44,13 @@ final class SchemaRegistryCatalog {
this.builder = builder;
}
/**
* Font families are only used for schema completion. Enumerating them touches AWT, which can fail outright on a
* headless or mod-loader JVM - a failure degrades to no completion, never to a broken schema.
*/
/** The logical font families every Java runtime has; listing the installed ones would need AWT, which headless and mod-loader JVMs may lack. */
static JSONArray fontTypes() {
JSONArray cached = fontTypes;
if (cached != null) {
return cached;
}
JSONArray built = CapabilityProbe.attempt("java.awt font families",
() -> new JSONArray(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()),
new JSONArray());
JSONArray built = new JSONArray(LOGICAL_FONT_FAMILIES);
fontTypes = built;
return built;
}
@@ -129,6 +129,16 @@ public final class MissingBlockState implements NativeBlockState {
return false;
}
@Override
public boolean isLog() {
return false;
}
@Override
public boolean isLeaves() {
return false;
}
@Override
public boolean isFoliagePlantable() {
return false;
@@ -100,8 +100,12 @@ public final class BukkitBlockResolution {
}
Identifier key = Identifier.fromString(ix);
Optional<BlockData> bd = IrisServices.get(ExternalDataSVC.class).getBlockData(key);
ExternalDataSVC external = IrisServices.get(ExternalDataSVC.class);
Optional<BlockData> bd = external.getBlockData(key);
debug("Loading block data " + key);
if (bd.isPresent() && shouldPreventLeafDecay()) {
return external.withoutDecay(bd.get());
}
return bd.orElse(null);
}
@@ -27,9 +27,11 @@ import art.arcane.volmlib.nativelib.terrain.BlockStateKey;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.iris.generation.block.IrisCustomData;
import art.arcane.iris.generation.geometry.IrisBlockVector;
import art.arcane.iris.spi.IrisServices;
import art.arcane.volmlib.util.collection.KMap;
import org.bukkit.Axis;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
@@ -75,6 +77,8 @@ public final class BukkitBlockState implements NativeBlockState {
private byte updatable;
private byte foliage;
private byte treeBlock;
private byte log;
private byte leaves;
private byte foliagePlantable;
private byte decorant;
private byte storage;
@@ -318,12 +322,41 @@ public final class BukkitBlockState implements NativeBlockState {
public boolean isTreeBlock() {
byte cached = treeBlock;
if (cached == UNKNOWN) {
cached = flag(Tag.LOGS.isTagged(data.getMaterial()) || Tag.LEAVES.isTagged(data.getMaterial()));
cached = flag(isLog() || isLeaves());
treeBlock = cached;
}
return cached == TRUE;
}
@Override
public boolean isLog() {
byte cached = log;
if (cached == UNKNOWN) {
cached = flag(hasTag(Tag.LOGS));
log = cached;
}
return cached == TRUE;
}
@Override
public boolean isLeaves() {
byte cached = leaves;
if (cached == UNKNOWN) {
cached = flag(hasTag(Tag.LEAVES));
leaves = cached;
}
return cached == TRUE;
}
// A plugin's custom block shows up as some other material, so the plugin is asked for its own tags too.
private boolean hasTag(Tag<Material> tag) {
if (tag.isTagged(data.getMaterial())) {
return true;
}
ExternalDataSVC external = IrisServices.getOrNull(ExternalDataSVC.class);
return external != null && external.hasBlockTag(data, tag.getKey());
}
@Override
public boolean isFoliagePlantable() {
byte cached = foliagePlantable;
@@ -32,6 +32,9 @@ import art.arcane.volmlib.util.math.M;
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Server;
import org.bukkit.Sound;
@@ -326,6 +329,17 @@ public class VolmitSender implements CommandSender {
deliver(ComponentText.component(component));
}
/** A green line that copies {@code payload} to a player's clipboard when clicked; a console gets nothing. */
public void sendCopyButton(String label, String hover, String payload) {
if (!isPlayer()) {
return;
}
sendComponent(Component.text(label)
.color(NamedTextColor.GREEN)
.clickEvent(ClickEvent.copyToClipboard(payload))
.hoverEvent(HoverEvent.showText(Component.text(hover))));
}
private void deliver(ComponentText message) {
ComponentMessenger.send(s, message);
}
@@ -39,6 +39,7 @@ import art.arcane.iris.studio.object.ObjectStudioLayout;
import art.arcane.iris.studio.jigsaw.JigsawStudioActivation;
import art.arcane.iris.studio.jigsaw.JigsawStudioSession;
import art.arcane.iris.studio.StudioSVC;
import art.arcane.iris.studio.workspace.PackHotloadFolder;
import art.arcane.iris.world.IrisToolbelt;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.IrisEngine;
@@ -189,13 +190,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
this.dataLocation = dataLocation;
this.dimensionKey = dimensionKey;
this.generationHistory = generationHistory;
this.folder = new ReactiveFolder(
dataLocation,
(_a, _b, _c) -> hotloadFromWatcher(),
new KList<>(".iob", ".json", ".png"),
new KList<>(".iris"),
new KList<>()
);
this.folder = PackHotloadFolder.watch(dataLocation, new KList<>(".iob", ".json", ".png"), (_a, _b, _c) -> hotloadFromWatcher());
this.initializationFailure = null;
this.jigsawStudioActive = false;
this.validatedDimension = null;
@@ -141,8 +141,9 @@ final class ObjectBlockPass {
private boolean handleCustomData(NativeBlockState data, boolean air, TileData tile, String marker, int xx, int yy, int zz) {
// Short-circuit order matters for cost only: the mantle read is paid solely
// for vine blocks. Both operands are pure, so the value is unchanged.
boolean wouldReplace = !is(ObjectPlaceMode.STRUCTURE_PIECE) && B.isVineBlock(data) && B.isSolid(state.placer.get(xx, yy, zz));
// for vine blocks and leaves. Both operands are pure, so the value is unchanged.
boolean wouldReplace = !is(ObjectPlaceMode.STRUCTURE_PIECE) && readsExistingBlock(data)
&& keepsExisting(data, state.placer.get(xx, yy, zz));
boolean place = shouldPlaceObjectBlock(is(ObjectPlaceMode.STRUCTURE_PIECE), air, wouldReplace);
if (data.isCustom() || place) {
state.placer.set(xx, yy, zz, data);
@@ -160,6 +161,15 @@ final class ObjectBlockPass {
return false;
}
private static boolean readsExistingBlock(NativeBlockState data) {
return B.isVineBlock(data) || B.isLeaves(data);
}
/** Vines never replace solid blocks, and leaves never cut a log: the trunk above the cut would float. */
static boolean keepsExisting(NativeBlockState data, NativeBlockState existing) {
return B.isVineBlock(data) ? B.isSolid(existing) : B.isLeaves(data) && B.isLog(existing);
}
private EditResult applyEdits(double[] exact, int index, NativeBlockState data, TileData tile) {
double exactX = exact[index * 3];
double exactY = exact[index * 3 + 1];
@@ -70,8 +70,7 @@ final class PlacementPalette {
NativeBlockState resolved = decayed[entry];
if (resolved == null) {
NativeBlockState data = source(entry);
resolved = preventingDecay && IrisProceduralBlocks.hasProperty(data, "distance")
&& "false".equals(IrisProceduralBlocks.propertyValue(data, "persistent"))
resolved = preventingDecay && "false".equals(IrisProceduralBlocks.propertyValue(data, "persistent"))
? data.withProperty("persistent", "true") : data;
decayed[entry] = resolved;
}
@@ -42,6 +42,7 @@ import art.arcane.iris.pack.PackValidationRegistry;
import art.arcane.iris.pack.PackValidationCache;
import art.arcane.iris.pack.PackValidationResult;
import art.arcane.iris.pack.PackValidator;
import art.arcane.iris.studio.bridge.StudioBridges;
import art.arcane.iris.studio.workspace.IrisProject;
import art.arcane.iris.studio.workspace.IrisPackageCompiler;
import art.arcane.iris.studio.workspace.IrisCodeWorkspace;
@@ -161,6 +162,7 @@ public class StudioSVC implements IrisService {
@Override
public void onDisable() {
quiesceDownloadsForShutdown();
StudioBridges.closeAll();
IrisLogging.debug("Studio Mode Active: Closing Projects");
boolean stopping = IrisToolbelt.isServerStopping();
LinkedHashSet<String> worldNamesToDelete = new LinkedHashSet<>(TransientWorldCleanupSupport.collectTransientStudioWorldNames(IrisWorldStorage.levelRoot()));
@@ -1043,8 +1045,8 @@ public class StudioSVC implements IrisService {
});
}
public void openVSCode(VolmitSender sender, String dim) {
new IrisCodeWorkspace(new IrisProject(new File(getWorkspaceFolder(), dim))).openVSCode(sender);
public void openEditor(VolmitSender sender, String dim) {
new IrisCodeWorkspace(new IrisProject(new File(getWorkspaceFolder(), dim))).openEditor(sender);
}
public File getWorkspaceFolder(String... sub) {
@@ -0,0 +1,63 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
/** The studio app the jar carries, unpacked into a folder named by its checksum so each build gets its own copy. */
final class BundledStudioApp {
static final String RESOURCE = "META-INF/iris/studio-app.zip";
private static final String FOLDER_PREFIX = "app-";
private static final int FOLDER_CHECKSUM_LENGTH = 12;
private BundledStudioApp() {
}
static Path install(Path root, ClassLoader resources) throws IOException {
Path archive = root.resolve("studio-app.zip.part");
try {
copyResource(resources, archive);
Path folder = root.resolve(FOLDER_PREFIX + ElectronRuntime.sha256(archive).substring(0, FOLDER_CHECKSUM_LENGTH));
if (!Files.isRegularFile(folder.resolve("package.json"))) {
ZipArchives.extract(archive, folder);
}
return folder;
} finally {
Files.deleteIfExists(archive);
}
}
static boolean isAppFolder(Path folder) {
return folder.getFileName().toString().startsWith(FOLDER_PREFIX);
}
private static void copyResource(ClassLoader resources, Path archive) throws IOException {
try (InputStream input = resources.getResourceAsStream(RESOURCE)) {
if (input == null) {
throw new IOException("this build does not bundle the studio app; point studio.studioApp at a studio checkout");
}
Files.createDirectories(archive.getParent());
Files.copy(input, archive, StandardCopyOption.REPLACE_EXISTING);
}
}
}
@@ -0,0 +1,179 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.HexFormat;
import java.util.Locale;
import java.util.Properties;
/**
* The Electron build the studio app runs on. The build pins its version and each platform's SHA-256 in the studio app
* manifest; the archive comes from Electron's own GitHub release and is unpacked once into the studio folder.
*/
final class ElectronRuntime {
private static final String RELEASE_ROOT = "https://github.com/electron/electron/releases/download/";
private static final String VERSION_KEY = "electron.version";
private static final String CHECKSUM_SUFFIX = ".sha256";
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10);
private static final Duration DOWNLOAD_TIMEOUT = Duration.ofMinutes(15);
private final String version;
private final Platform platform;
private final String sha256;
private ElectronRuntime(String version, Platform platform, String sha256) {
this.version = version;
this.platform = platform;
this.sha256 = sha256;
}
static ElectronRuntime pinned(Properties manifest, Platform platform) throws IOException {
String version = manifest.getProperty(VERSION_KEY);
String sha256 = manifest.getProperty(platform.name() + CHECKSUM_SUFFIX);
if (version == null || sha256 == null) {
throw new IOException("no Electron build is pinned for " + platform.name());
}
return new ElectronRuntime(version, platform, sha256.toLowerCase(Locale.ROOT));
}
String folderName() {
return "electron-v" + version + "-" + platform.name();
}
URI source() {
return URI.create(RELEASE_ROOT + "v" + version + "/" + folderName() + ".zip");
}
/** The Electron executable under {@code root}, downloaded, checked and unpacked first when it is not there yet. */
Path install(Path root, Downloader downloader) throws IOException {
Path executable = root.resolve(folderName()).resolve(platform.executable());
if (Files.isRegularFile(executable)) {
return executable;
}
Path archive = root.resolve(folderName() + ".zip.part");
try {
downloader.download(source(), archive);
requireChecksum(archive);
if (platform.macOS()) {
ZipArchives.extractWithDitto(archive, root.resolve(folderName()));
} else {
ZipArchives.extract(archive, root.resolve(folderName()));
}
} finally {
Files.deleteIfExists(archive);
}
if (!Files.isRegularFile(executable)) {
throw new IOException(source() + " has no " + platform.executable());
}
return executable;
}
private void requireChecksum(Path archive) throws IOException {
String actual = sha256(archive);
if (!actual.equals(sha256)) {
throw new IOException(source() + " failed its checksum (expected " + sha256 + ", got " + actual + ")");
}
}
static String sha256(Path file) throws IOException {
try (InputStream input = Files.newInputStream(file)) {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] buffer = new byte[1 << 16];
int read;
while ((read = input.read(buffer)) >= 0) {
digest.update(buffer, 0, read);
}
return HexFormat.of().formatHex(digest.digest());
} catch (NoSuchAlgorithmException missing) {
throw new IllegalStateException(missing);
}
}
@FunctionalInterface
interface Downloader {
void download(URI source, Path target) throws IOException;
static Downloader http() {
return (source, target) -> {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(CONNECT_TIMEOUT)
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder(source)
.timeout(DOWNLOAD_TIMEOUT)
.header("User-Agent", "Iris")
.build();
try {
HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFile(target));
if (response.statusCode() != 200) {
throw new IOException(source + " answered HTTP " + response.statusCode());
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new IOException("download of " + source + " was interrupted", interrupted);
}
};
}
}
/** An Electron release platform, named as its archives are, and where the executable sits inside them. */
record Platform(String name, String executable) {
static Platform current() {
return of(System.getProperty("os.name", ""), System.getProperty("os.arch", ""));
}
/** Null for a system Electron publishes no build for. */
static Platform of(String operatingSystem, String architecture) {
String os = operatingSystem.toLowerCase(Locale.ROOT);
String arch = switch (architecture) {
case "aarch64", "arm64" -> "arm64";
case "amd64", "x86_64" -> "x64";
default -> null;
};
if (arch == null) {
return null;
}
if (os.contains("linux")) {
return new Platform("linux-" + arch, "electron");
}
if (os.contains("win")) {
return new Platform("win32-" + arch, "electron.exe");
}
if (os.contains("mac")) {
return new Platform("darwin-" + arch, "Electron.app/Contents/MacOS/Electron");
}
return null;
}
boolean macOS() {
return name.startsWith("darwin");
}
}
}
@@ -1,6 +1,6 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,10 +16,10 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
package art.arcane.iris.studio.app;
/**
* A rectangle of a terrain's columns and rows, from the first up to but not including the last.
*/
record ColumnArea(int fromColumn, int fromRow, int toColumn, int toRow) {
import java.nio.file.Path;
/** A studio app ready to start: the Electron executable and the app folder it runs. */
public record StudioAppInstall(Path electron, Path app) {
}
@@ -0,0 +1,168 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.studio.view.GuiHost;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Stream;
/**
* Installs the studio app into the Iris data folder in the background at startup: the app from the jar, and the
* Electron build it runs on from Electron's release. Servers without a display skip it, since the window could not
* open there anyway.
*/
public final class StudioAppInstaller {
static final String MANIFEST = "META-INF/iris/studio-app.properties";
private static final String DATA_FOLDER = "studio";
private static final String STAGING_SUFFIX = ".part";
private static StudioAppState state = StudioAppState.NOT_STARTED;
private static StudioAppInstall installed;
private static String unavailableReason = "";
private StudioAppInstaller() {
}
/** Starts the install unless it is done, running, or off; the state it leaves, for a caller about to open the app. */
public static synchronized StudioAppState installInBackground() {
if (state == StudioAppState.DOWNLOADING || state == StudioAppState.READY || state == StudioAppState.UNAVAILABLE) {
return state;
}
state = blockedState();
if (state != StudioAppState.DOWNLOADING) {
return state;
}
Thread.ofPlatform().daemon().name("Iris Studio install").start(StudioAppInstaller::install);
return state;
}
public static synchronized StudioAppInstall installed() {
return installed;
}
public static synchronized String unavailableReason() {
return unavailableReason;
}
static boolean hasDisplay(String operatingSystem, Map<String, String> environment) {
String os = operatingSystem.toLowerCase(Locale.ROOT);
if (os.contains("win") || os.contains("mac")) {
return true;
}
return isSet(environment.get("DISPLAY")) || isSet(environment.get("WAYLAND_DISPLAY"));
}
private static StudioAppState blockedState() {
if (!IrisSettings.get().getStudio().isDownloadApp()) {
return StudioAppState.DOWNLOAD_OFF;
}
if (GuiHost.isDesktopSuppressed() || !hasDisplay(System.getProperty("os.name", ""), System.getenv())) {
return StudioAppState.NO_DISPLAY;
}
return StudioAppState.DOWNLOADING;
}
private static void install() {
long startedNanos = System.nanoTime();
try {
ElectronRuntime.Platform platform = ElectronRuntime.Platform.current();
if (platform == null) {
throw new IOException("Electron has no build for " + System.getProperty("os.name") + " " + System.getProperty("os.arch"));
}
ElectronRuntime electron = ElectronRuntime.pinned(manifest(), platform);
Path root = IrisPlatforms.get().dataFolder(DATA_FOLDER).toPath();
Path executable = installElectron(electron, root);
Path app = BundledStudioApp.install(root, StudioAppInstaller.class.getClassLoader());
removeStaleInstalls(root, List.of(app, root.resolve(electron.folderName())));
ready(new StudioAppInstall(executable, app), (System.nanoTime() - startedNanos) / 1_000_000L);
} catch (IOException | RuntimeException error) {
unavailable(error.getMessage() == null ? error.getClass().getSimpleName() : error.getMessage());
}
}
private static Path installElectron(ElectronRuntime electron, Path root) throws IOException {
if (!Files.isDirectory(root.resolve(electron.folderName()))) {
IrisLogging.info("Downloading the studio app runtime from %s", electron.source());
}
return electron.install(root, ElectronRuntime.Downloader.http());
}
private static Properties manifest() throws IOException {
Properties manifest = new Properties();
try (InputStream input = StudioAppInstaller.class.getClassLoader().getResourceAsStream(MANIFEST)) {
if (input == null) {
throw new IOException("this build does not bundle the studio app; point studio.studioApp at a studio checkout");
}
manifest.load(input);
}
return manifest;
}
/** Drops the Electron builds and app copies earlier versions left, and any half-finished download or unpack. */
private static void removeStaleInstalls(Path root, List<Path> current) {
try (Stream<Path> children = Files.list(root)) {
for (Path child : children.toList()) {
if (current.contains(child) || !isInstallArtifact(child)) {
continue;
}
try {
ZipArchives.deleteRecursively(child);
} catch (IOException error) {
IrisLogging.debug("Could not remove the old studio install %s: %s", child, error.getMessage());
}
}
} catch (IOException error) {
IrisLogging.debug("Could not list the studio folder %s: %s", root, error.getMessage());
}
}
private static boolean isInstallArtifact(Path child) {
String name = child.getFileName().toString();
return name.startsWith("electron-v") || BundledStudioApp.isAppFolder(child) || name.endsWith(STAGING_SUFFIX);
}
private static synchronized void ready(StudioAppInstall install, long elapsedMillis) {
installed = install;
unavailableReason = "";
state = StudioAppState.READY;
IrisLogging.info("Studio app ready in %d ms", elapsedMillis);
}
private static synchronized void unavailable(String reason) {
installed = null;
unavailableReason = reason;
state = StudioAppState.UNAVAILABLE;
IrisLogging.warn("Studio app unavailable: %s", reason);
}
private static boolean isSet(String value) {
return value != null && !value.isBlank();
}
}
@@ -1,6 +1,6 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,11 +16,14 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
package art.arcane.iris.studio.app;
import art.arcane.iris.generation.runtime.Engine;
import java.util.UUID;
public record PaletteExplorerStart(Engine engine, UUID worldId, UUID playerId, String biomeKey, double centerX, double centerZ) {
/** Where the downloaded studio app stands on this server. */
public enum StudioAppState {
NOT_STARTED,
DOWNLOAD_OFF,
NO_DISPLAY,
DOWNLOADING,
READY,
UNAVAILABLE
}
@@ -0,0 +1,247 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.app;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Unpacks archives into a folder that only appears once it is complete: everything lands in a staging folder first,
* which is then moved into place, so a crash halfway never leaves a folder that looks installed.
*/
final class ZipArchives {
private static final long DITTO_TIMEOUT_MINUTES = 5;
private static final int FILE_TYPE_MASK = 0170000;
private static final int SYMLINK_TYPE = 0120000;
private static final int PERMISSION_MASK = 0777;
private static final List<PosixFilePermission> PERMISSION_BITS = List.of(
PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_WRITE, PosixFilePermission.OTHERS_READ,
PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.GROUP_WRITE, PosixFilePermission.GROUP_READ,
PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_READ);
private ZipArchives() {
}
/** Keeps each entry's Unix mode and symlinks, so executables stay executable. */
static void extract(Path archive, Path folder) throws IOException {
Path staging = staging(folder);
boolean posix = staging.getFileSystem().supportedFileAttributeViews().contains("posix");
Map<String, Integer> modes = posix ? unixModes(archive) : Map.of();
try (ZipFile zip = new ZipFile(archive.toFile())) {
for (ZipEntry entry : Collections.list(zip.entries())) {
extractEntry(zip, entry, staging, modes.getOrDefault(entry.getName(), 0), posix);
}
}
moveIntoPlace(staging, folder);
}
/** Unpacks with macOS's ditto, which keeps everything an app bundle relies on. */
static void extractWithDitto(Path archive, Path folder) throws IOException {
Path staging = staging(folder);
Process ditto = new ProcessBuilder("ditto", "-x", "-k", archive.toString(), staging.toString())
.redirectErrorStream(true)
.start();
try {
if (!ditto.waitFor(DITTO_TIMEOUT_MINUTES, TimeUnit.MINUTES)) {
ditto.destroyForcibly();
throw new IOException("ditto did not finish unpacking " + archive);
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new IOException("unpacking " + archive + " was interrupted", interrupted);
}
if (ditto.exitValue() != 0) {
throw new IOException("ditto could not unpack " + archive + ": "
+ new String(ditto.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim());
}
moveIntoPlace(staging, folder);
}
static void deleteRecursively(Path path) throws IOException {
if (!Files.exists(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
return;
}
try (Stream<Path> walk = Files.walk(path)) {
for (Path entry : walk.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(entry);
}
}
}
private static void extractEntry(ZipFile zip, ZipEntry entry, Path staging, int mode, boolean posix) throws IOException {
Path target = insideStaging(staging, staging.resolve(entry.getName()));
if (entry.isDirectory()) {
Files.createDirectories(target);
return;
}
Files.createDirectories(target.getParent());
try (InputStream input = zip.getInputStream(entry)) {
if (posix && (mode & FILE_TYPE_MASK) == SYMLINK_TYPE) {
Path linkTarget = Path.of(new String(input.readAllBytes(), StandardCharsets.UTF_8));
insideStaging(staging, target.getParent().resolve(linkTarget));
Files.createSymbolicLink(target, linkTarget);
return;
}
Files.copy(input, target);
}
if (posix && mode != 0) {
Files.setPosixFilePermissions(target, permissions(mode));
}
}
private static Path insideStaging(Path staging, Path path) throws IOException {
Path normalized = path.normalize();
if (!normalized.startsWith(staging)) {
throw new IOException("archive entry " + path + " points outside its folder");
}
return normalized;
}
private static Set<PosixFilePermission> permissions(int mode) {
Set<PosixFilePermission> permissions = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE);
int bits = mode & PERMISSION_MASK;
for (int bit = 0; bit < PERMISSION_BITS.size(); bit++) {
if ((bits & (1 << bit)) != 0) {
permissions.add(PERMISSION_BITS.get(bit));
}
}
return permissions;
}
/**
* Each entry's Unix mode, read from the archive's central directory, where zip tools made on Unix keep it in the
* high half of the external attributes. {@link ZipFile} reads the entries but not this field.
*/
static Map<String, Integer> unixModes(Path archive) throws IOException {
try (FileChannel channel = FileChannel.open(archive)) {
CentralDirectory directory = CentralDirectory.locate(channel);
ByteBuffer records = read(channel, directory.offset(), directory.size());
Map<String, Integer> modes = new HashMap<>();
int position = 0;
for (long index = 0; index < directory.entries(); index++) {
if (records.getInt(position) != CentralDirectory.ENTRY_SIGNATURE) {
throw new IOException(archive + " has a damaged central directory");
}
int madeBySystem = (records.getShort(position + 4) >> 8) & 0xFF;
int nameLength = records.getShort(position + 28) & 0xFFFF;
int extraLength = records.getShort(position + 30) & 0xFFFF;
int commentLength = records.getShort(position + 32) & 0xFFFF;
int externalAttributes = records.getInt(position + 38);
byte[] name = new byte[nameLength];
records.get(position + 46, name);
if (madeBySystem == CentralDirectory.MADE_ON_UNIX) {
modes.put(new String(name, StandardCharsets.UTF_8), externalAttributes >>> 16);
}
position += 46 + nameLength + extraLength + commentLength;
}
return modes;
}
}
private static ByteBuffer read(FileChannel channel, long offset, long length) throws IOException {
if (length > Integer.MAX_VALUE - 8 || offset < 0 || offset + length > channel.size()) {
throw new IOException("zip structure points outside the archive");
}
ByteBuffer buffer = ByteBuffer.allocate((int) length).order(ByteOrder.LITTLE_ENDIAN);
while (buffer.hasRemaining()) {
if (channel.read(buffer, offset + buffer.position()) < 0) {
throw new IOException("archive ended early");
}
}
return buffer.flip();
}
private record CentralDirectory(long offset, long size, long entries) {
static final int ENTRY_SIGNATURE = 0x02014b50;
static final int MADE_ON_UNIX = 3;
private static final int END_SIGNATURE = 0x06054b50;
private static final int ZIP64_LOCATOR_SIGNATURE = 0x07064b50;
private static final int ZIP64_END_SIGNATURE = 0x06064b50;
private static final int END_RECORD_LENGTH = 22;
private static final int ZIP64_LOCATOR_LENGTH = 20;
private static final int MAX_COMMENT_LENGTH = 0xFFFF;
static CentralDirectory locate(FileChannel channel) throws IOException {
long size = channel.size();
int tailLength = (int) Math.min(size, END_RECORD_LENGTH + MAX_COMMENT_LENGTH);
long tailOffset = size - tailLength;
ByteBuffer tail = read(channel, tailOffset, tailLength);
for (int end = tailLength - END_RECORD_LENGTH; end >= 0; end--) {
if (tail.getInt(end) == END_SIGNATURE) {
return fromEndRecord(channel, tail, end, tailOffset + end);
}
}
throw new IOException("not a zip archive");
}
private static CentralDirectory fromEndRecord(FileChannel channel, ByteBuffer tail, int end, long endOffset) throws IOException {
long entries = tail.getShort(end + 10) & 0xFFFFL;
long size = tail.getInt(end + 12) & 0xFFFFFFFFL;
long offset = tail.getInt(end + 16) & 0xFFFFFFFFL;
if (entries != 0xFFFFL && size != 0xFFFFFFFFL && offset != 0xFFFFFFFFL) {
return new CentralDirectory(offset, size, entries);
}
ByteBuffer locator = read(channel, endOffset - ZIP64_LOCATOR_LENGTH, ZIP64_LOCATOR_LENGTH);
if (locator.getInt(0) != ZIP64_LOCATOR_SIGNATURE) {
throw new IOException("zip64 archive without its locator");
}
ByteBuffer zip64End = read(channel, locator.getLong(8), 56);
if (zip64End.getInt(0) != ZIP64_END_SIGNATURE) {
throw new IOException("zip64 archive without its end record");
}
return new CentralDirectory(zip64End.getLong(48), zip64End.getLong(40), zip64End.getLong(32));
}
}
private static Path staging(Path folder) throws IOException {
Path staging = folder.resolveSibling(folder.getFileName() + ".part");
deleteRecursively(staging);
Files.createDirectories(staging);
return staging;
}
private static void moveIntoPlace(Path staging, Path folder) throws IOException {
deleteRecursively(folder);
try {
Files.move(staging, folder, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException unsupported) {
Files.move(staging, folder);
}
}
}
@@ -0,0 +1,184 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.studio.bridge.JsonSplicer.Splice;
import art.arcane.iris.studio.scene.JsonPath;
import java.util.List;
import java.util.Objects;
/** One change the studio's node editor makes to an entry's file, as the splices of its text that make it. */
sealed interface GraphEdit {
/**
* The splices that make the change in {@code file}.
*
* @throws IllegalArgumentException naming why, when the file has nothing there to change
*/
List<Splice> splices(JsonSplicer file);
/** Sets member {@code key} of the object at {@code object} to {@code literal}, writing the object when it is missing. */
record Set(JsonPath object, String key, String literal) implements GraphEdit {
public Set {
Objects.requireNonNull(object, "object");
Objects.requireNonNull(key, "key");
requireValue(literal);
}
@Override
public List<Splice> splices(JsonSplicer file) {
if (file.at(object).orElse(null) instanceof JsonText.Obj settings) {
return List.of(file.put(settings, key, literal));
}
if (object.isRoot() || !(object.last() instanceof JsonPath.Key(String member))) {
throw new IllegalArgumentException("Nothing to set " + key + " on at " + object);
}
return new Set(object.parent(), member, "{" + JsonSplicer.quote(key) + ": " + literal + "}").splices(file);
}
}
/** Removes member {@code key} of the object at {@code object}, leaving it at its default. */
record Unset(JsonPath object, String key) implements GraphEdit {
@Override
public List<Splice> splices(JsonSplicer file) {
if (!(file.at(object).orElse(null) instanceof JsonText.Obj settings) || settings.member(key).isEmpty()) {
return List.of();
}
return List.of(file.remove(settings, key));
}
}
/** Appends {@code literal} to the array at {@code list}, writing the array when it is missing. */
record Append(JsonPath list, String literal) implements GraphEdit {
public Append {
Objects.requireNonNull(list, "list");
requireValue(literal);
}
@Override
public List<Splice> splices(JsonSplicer file) {
return List.of(appendTo(file, list, literal));
}
}
/** Appends a copy of the last element of the array at {@code list}, so a new item starts out filled in. */
record AddItem(JsonPath list) implements GraphEdit {
private static final String EMPTY_ITEM = "{}";
@Override
public List<Splice> splices(JsonSplicer file) {
if (!(file.at(list).orElse(null) instanceof JsonText.Arr array)) {
throw new IllegalArgumentException("No list at " + list);
}
String copy = array.elements().isEmpty() ? EMPTY_ITEM : file.detachedTextOf(array.elements().getLast());
return List.of(file.append(array, copy));
}
}
/** Deletes the value at {@code path}, and the member holding the array it was in when it was the only element. */
record Delete(JsonPath path) implements GraphEdit {
public Delete {
if (path.isRoot()) {
throw new IllegalArgumentException("The file itself can't be deleted");
}
}
@Override
public List<Splice> splices(JsonSplicer file) {
return List.of(removal(file, path));
}
}
/** Appends a copy of the element at {@code path}, with all it holds, to the array holding it. */
record Duplicate(JsonPath path) implements GraphEdit {
public Duplicate {
if (!path.isElement()) {
throw new IllegalArgumentException("Only an element of a list can be duplicated, not " + path);
}
}
@Override
public List<Splice> splices(JsonSplicer file) {
JsonText.Value element = valueAt(file, path);
if (!(file.at(path.parent()).orElse(null) instanceof JsonText.Arr array)) {
throw new IllegalArgumentException("No list holds " + path);
}
return List.of(file.append(array, file.detachedTextOf(element)));
}
}
/** Moves the element at {@code path}, with all it holds, to the end of the array at {@code toList}. */
record Move(JsonPath path, JsonPath toList) implements GraphEdit {
public Move {
if (!path.isElement()) {
throw new IllegalArgumentException("Only an element of a list can move, not " + path);
}
if (toList.startsWith(path)) {
throw new IllegalArgumentException("A node can't move into itself or into what it holds");
}
if (toList.equals(path.parent())) {
throw new IllegalArgumentException("It is there already");
}
}
@Override
public List<Splice> splices(JsonSplicer file) {
String moved = file.detachedTextOf(valueAt(file, path));
return List.of(removal(file, path), appendTo(file, toList, moved));
}
}
private static void requireValue(String literal) {
if (literal == null || !JsonText.isValue(literal)) {
throw new IllegalArgumentException(literal + " is not a JSON value");
}
}
private static JsonText.Value valueAt(JsonSplicer file, JsonPath path) {
return file.at(path).orElseThrow(() -> new IllegalArgumentException("Nothing at " + path));
}
private static Splice appendTo(JsonSplicer file, JsonPath list, String literal) {
if (file.at(list).orElse(null) instanceof JsonText.Arr array) {
return file.append(array, literal);
}
if (list.isRoot() || !(list.last() instanceof JsonPath.Key(String member))
|| !(file.at(list.parent()).orElse(null) instanceof JsonText.Obj owner)) {
throw new IllegalArgumentException("Nothing can be added at " + list);
}
return file.put(owner, member, "[" + literal + "]");
}
private static Splice removal(JsonSplicer file, JsonPath path) {
JsonPath holderPath = path.parent();
JsonText.Value holder = valueAt(file, holderPath);
if (path.last() instanceof JsonPath.Key(String key) && holder instanceof JsonText.Obj object) {
return file.remove(object, key);
}
if (!(path.last() instanceof JsonPath.Index(int index)) || !(holder instanceof JsonText.Arr array) || index >= array.elements().size()) {
throw new IllegalArgumentException("Nothing at " + path);
}
boolean onlyElement = array.elements().size() == 1;
if (onlyElement && !holderPath.isRoot() && holderPath.last() instanceof JsonPath.Key(String key)
&& file.at(holderPath.parent()).orElse(null) instanceof JsonText.Obj owner) {
return file.remove(owner, key);
}
return file.removeElement(array, index);
}
}
@@ -0,0 +1,92 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.studio.scene.JsonPath;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
/** An edit as the studio sends it: {@code {"revision": "…", "edit": {"op": "set", …}}}, paths as arrays of names and indices. */
record GraphEditRequest(String revision, GraphEdit edit) {
/** @throws IllegalArgumentException naming what is missing or wrong */
static GraphEditRequest parse(String body) {
JsonObject root = object(bodyOf(body), "The body");
JsonObject edit = object(root.get("edit"), "edit");
GraphEdit parsed = switch (text(edit, "op")) {
case "set" -> new GraphEdit.Set(path(edit, "object"), text(edit, "key"), text(edit, "literal"));
case "unset" -> new GraphEdit.Unset(path(edit, "object"), text(edit, "key"));
case "append" -> new GraphEdit.Append(path(edit, "list"), text(edit, "literal"));
case "addItem" -> new GraphEdit.AddItem(path(edit, "list"));
case "delete" -> new GraphEdit.Delete(path(edit, "path"));
case "duplicate" -> new GraphEdit.Duplicate(path(edit, "path"));
case "move" -> new GraphEdit.Move(path(edit, "path"), path(edit, "toList"));
default -> throw new IllegalArgumentException("Unknown edit: " + text(edit, "op"));
};
return new GraphEditRequest(text(root, "revision"), parsed);
}
/** A whole-file write, as undoing and redoing send it: {@code {"revision": "…", "text": "…"}}. */
record FileWrite(String revision, String text) {
static FileWrite parse(String body) {
JsonObject root = object(bodyOf(body), "The body");
return new FileWrite(GraphEditRequest.text(root, "revision"), GraphEditRequest.text(root, "text"));
}
}
private static JsonElement bodyOf(String body) {
try {
return JsonParser.parseString(body);
} catch (JsonParseException notJson) {
throw new IllegalArgumentException("The body is not JSON");
}
}
private static JsonObject object(JsonElement element, String name) {
if (element == null || !element.isJsonObject()) {
throw new IllegalArgumentException(name + " must be a JSON object");
}
return element.getAsJsonObject();
}
private static String text(JsonObject object, String key) {
JsonElement value = object.get(key);
if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) {
throw new IllegalArgumentException(key + " must be a string");
}
return value.getAsString();
}
private static JsonPath path(JsonObject object, String key) {
if (!(object.get(key) instanceof JsonArray steps)) {
throw new IllegalArgumentException(key + " must be an array of member names and indices");
}
JsonPath path = JsonPath.ROOT;
for (JsonElement step : steps) {
if (!(step instanceof JsonPrimitive primitive)) {
throw new IllegalArgumentException(key + " holds " + step + ", not a name or an index");
}
path = primitive.isNumber() ? path.element(primitive.getAsInt()) : path.member(primitive.getAsString());
}
return path;
}
}
@@ -0,0 +1,178 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.studio.scene.JsonPath;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* Changes to a JSON file's text as splices of the text, each replacing what one value or member is written as. All
* else stays as it was written: the layout, the order of the members and the comments. New members and elements are
* written in the style of their neighbours, on lines of their own where those are.
*/
final class JsonSplicer {
private static final String MEMBER_SEPARATOR = ", ";
private static final String LINE_SEPARATOR = ",\n";
private final JsonText source;
JsonSplicer(JsonText source) {
this.source = Objects.requireNonNull(source, "source");
}
/** {@code plain} as a JSON string literal. */
static String quote(String plain) {
StringBuilder quoted = new StringBuilder("\"");
for (char character : plain.toCharArray()) {
switch (character) {
case '"' -> quoted.append("\\\"");
case '\\' -> quoted.append("\\\\");
case '\n' -> quoted.append("\\n");
case '\r' -> quoted.append("\\r");
case '\t' -> quoted.append("\\t");
default -> quoted.append(character < 0x20 ? String.format("\\u%04x", (int) character) : String.valueOf(character));
}
}
return quoted.append('"').toString();
}
/** The value at {@code path}; empty when the file has none there. */
Optional<JsonText.Value> at(JsonPath path) {
return source.at(path);
}
/** The text of {@code value}, its later lines indented as if it started a line with no indent. */
String detachedTextOf(JsonText.Value value) {
return reindented(source.textOf(value), indentOfLine(value.start()), "");
}
Splice replace(JsonText.Value value, String literal) {
return new Splice(value.start(), value.end(), literal);
}
/** Sets the member, written after the last one in the object's own style when it is new. */
Splice put(JsonText.Obj object, String key, String literal) {
Optional<JsonText.Member> existing = object.member(key);
if (existing.isPresent()) {
return replace(existing.get().value(), literal);
}
if (object.members().isEmpty()) {
return replace(object, "{" + quote(key) + ": " + reindented(literal, "", indentOfLine(object.start())) + "}");
}
JsonText.Member last = object.members().getLast();
String indent = indentOfLine(last.keyStart());
String entry = quote(key) + ": " + reindented(literal, "", indent);
return new Splice(last.value().end(), last.value().end(), separatorIn(object, indent) + entry);
}
/** @throws IllegalArgumentException when the object has no member {@code key} */
Splice remove(JsonText.Obj object, String key) {
List<JsonText.Member> members = object.members();
int index = members.indexOf(object.member(key).orElseThrow(() -> new IllegalArgumentException("No " + key + " to remove")));
if (members.size() == 1) {
return replace(object, "{}");
}
if (index > 0) {
return new Splice(members.get(index - 1).value().end(), members.get(index).value().end(), "");
}
return new Splice(members.getFirst().keyStart(), members.get(1).keyStart(), "");
}
/** Adds an element after the last one, a multi-line one indented to match the array. */
Splice append(JsonText.Arr array, String literal) {
if (array.elements().isEmpty()) {
return replace(array, "[" + reindented(literal, "", indentOfLine(array.start())) + "]");
}
JsonText.Value last = array.elements().getLast();
String indent = indentOfLine(last.start());
return new Splice(last.end(), last.end(), separatorIn(array, indent) + reindented(literal, "", indent));
}
Splice removeElement(JsonText.Arr array, int index) {
List<JsonText.Value> elements = array.elements();
Objects.checkIndex(index, elements.size());
if (elements.size() == 1) {
return replace(array, "[]");
}
if (index > 0) {
return new Splice(elements.get(index - 1).end(), elements.get(index).end(), "");
}
return new Splice(elements.getFirst().start(), elements.get(1).start(), "");
}
/**
* The text with {@code splices} made, each placed by where it was in the source text.
*
* @throws IllegalArgumentException when two splices overlap
*/
String apply(List<Splice> splices) {
List<Splice> fromLast = new ArrayList<>(splices);
fromLast.sort(Comparator.comparingInt(Splice::start).reversed());
StringBuilder edited = new StringBuilder(source.text());
int earliestStart = Integer.MAX_VALUE;
for (Splice splice : fromLast) {
if (splice.end() > earliestStart) {
throw new IllegalArgumentException("Overlapping edits");
}
edited.replace(splice.start(), splice.end(), splice.replacement());
earliestStart = splice.start();
}
return edited.toString();
}
private String separatorIn(JsonText.Value holder, String indent) {
return source.textOf(holder).indexOf('\n') >= 0 ? LINE_SEPARATOR + indent : MEMBER_SEPARATOR;
}
// The blanks before the first character on the line holding position.
private String indentOfLine(int position) {
String text = source.text();
int lineStart = text.lastIndexOf('\n', position - 1) + 1;
int indentEnd = lineStart;
while (indentEnd < position && (text.charAt(indentEnd) == ' ' || text.charAt(indentEnd) == '\t')) {
indentEnd++;
}
return text.substring(lineStart, indentEnd);
}
private static String reindented(String literal, String fromIndent, String toIndent) {
String[] lines = literal.split("\n", -1);
StringBuilder result = new StringBuilder(lines[0]);
for (int index = 1; index < lines.length; index++) {
String line = lines[index].startsWith(fromIndent) ? lines[index].substring(fromIndent.length()) : lines[index].stripLeading();
result.append('\n').append(toIndent).append(line);
}
return result.toString();
}
/** Replaces the text from {@code start} up to {@code end} with {@code replacement}. */
record Splice(int start, int end, String replacement) {
Splice {
Objects.requireNonNull(replacement, "replacement");
if (start < 0 || end < start) {
throw new IllegalArgumentException("A splice runs forwards from 0, not " + start + " to " + end);
}
}
}
}
@@ -0,0 +1,358 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.studio.scene.JsonPath;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.internal.LazilyParsedNumber;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
/**
* A JSON file's text read into values that know where they are written, so an edit can change one value and leave the
* rest of the text, its layout and its comments as they were. Line and block comments are read as blanks.
*/
final class JsonText {
private static final Pattern NUMBER = Pattern.compile("-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?");
private static final String TRUE = "true";
private static final String FALSE = "false";
private static final String NULL = "null";
private final String text;
private final Value root;
private JsonText(String text, Value root) {
this.text = text;
this.root = root;
}
/** @throws IllegalArgumentException naming the line, when {@code text} is not one JSON value */
static JsonText parse(String text) {
Objects.requireNonNull(text, "text");
Parser parser = new Parser(text);
Value root = parser.value();
parser.skipBlank();
if (!parser.atEnd()) {
throw parser.error("Unexpected text after the end");
}
return new JsonText(text, root);
}
/** Whether {@code literal} is one JSON value. */
static boolean isValue(String literal) {
try {
parse(literal);
return true;
} catch (IllegalArgumentException notJson) {
return false;
}
}
String text() {
return text;
}
Value root() {
return root;
}
/** The value at {@code path}; empty when the file has none there. */
Optional<Value> at(JsonPath path) {
Value value = root;
for (JsonPath.Step step : path.steps()) {
Optional<Value> inside = stepInto(value, step);
if (inside.isEmpty()) {
return Optional.empty();
}
value = inside.get();
}
return Optional.of(value);
}
/** The value as it is written. */
String textOf(Value value) {
return text.substring(value.start(), value.end());
}
/** The whole file as Gson reads it, so what the pack reads and what is edited come from one reading of the text. */
JsonElement toGson() {
return gsonOf(root);
}
private JsonElement gsonOf(Value value) {
return switch (value) {
case Obj object -> {
JsonObject members = new JsonObject();
object.members().forEach(member -> members.add(member.key(), gsonOf(member.value())));
yield members;
}
case Arr array -> {
JsonArray elements = new JsonArray();
array.elements().forEach(element -> elements.add(gsonOf(element)));
yield elements;
}
case Literal literal -> gsonOf(literal);
};
}
private JsonElement gsonOf(Literal literal) {
if (literal.string().isPresent()) {
return new JsonPrimitive(literal.string().get());
}
String written = textOf(literal);
return switch (written) {
case TRUE -> new JsonPrimitive(true);
case FALSE -> new JsonPrimitive(false);
case NULL -> JsonNull.INSTANCE;
default -> new JsonPrimitive(new LazilyParsedNumber(written));
};
}
private static Optional<Value> stepInto(Value value, JsonPath.Step step) {
if (step instanceof JsonPath.Key(String name) && value instanceof Obj object) {
return object.get(name);
}
if (step instanceof JsonPath.Index(int position) && value instanceof Arr array && position < array.elements().size()) {
return Optional.of(array.elements().get(position));
}
return Optional.empty();
}
/** A value of the file, from {@code start} up to {@code end} in its text. */
sealed interface Value permits Obj, Arr, Literal {
int start();
int end();
}
/** One member of an object; {@code keyStart} is where its quoted name begins. */
record Member(String key, int keyStart, Value value) {
}
record Obj(int start, int end, List<Member> members) implements Value {
Obj {
members = List.copyOf(members);
}
Optional<Member> member(String key) {
return members.stream().filter(member -> member.key().equals(key)).findFirst();
}
Optional<Value> get(String key) {
return member(key).map(Member::value);
}
}
record Arr(int start, int end, List<Value> elements) implements Value {
Arr {
elements = List.copyOf(elements);
}
}
/** A string, number, true, false or null; {@code string} holds a string's decoded text, and is empty for the rest. */
record Literal(int start, int end, Optional<String> string) implements Value {
Literal {
Objects.requireNonNull(string, "string");
}
}
private static final class Parser {
private static final String STRUCTURE = "{}[],:\"";
private static final int UNICODE_ESCAPE_DIGITS = 4;
private static final int HEX = 16;
private final String text;
private int position;
Parser(String text) {
this.text = text;
}
boolean atEnd() {
return position >= text.length();
}
Value value() {
skipBlank();
if (atEnd()) {
throw error("Expected a value");
}
return switch (text.charAt(position)) {
case '{' -> object();
case '[' -> array();
case '"' -> {
int start = position;
String string = string();
yield new Literal(start, position, Optional.of(string));
}
default -> bareLiteral();
};
}
private Obj object() {
int start = position++;
List<Member> members = new ArrayList<>();
skipBlank();
if (peek() == '}') {
position++;
return new Obj(start, position, List.of());
}
while (true) {
skipBlank();
if (peek() != '"') {
throw error("Expected a quoted name");
}
int keyStart = position;
String key = string();
skipBlank();
expect(':');
members.add(new Member(key, keyStart, value()));
skipBlank();
if (peek() != ',') {
expect('}');
return new Obj(start, position, members);
}
position++;
}
}
private Arr array() {
int start = position++;
List<Value> elements = new ArrayList<>();
skipBlank();
if (peek() == ']') {
position++;
return new Arr(start, position, List.of());
}
while (true) {
elements.add(value());
skipBlank();
if (peek() != ',') {
expect(']');
return new Arr(start, position, elements);
}
position++;
}
}
private String string() {
position++;
StringBuilder decoded = new StringBuilder();
while (!atEnd()) {
char character = text.charAt(position++);
if (character == '"') {
return decoded.toString();
}
if (character != '\\') {
decoded.append(character);
continue;
}
if (atEnd()) {
break;
}
decoded.append(escaped(text.charAt(position++)));
}
throw error("Unclosed string");
}
private char escaped(char escape) {
return switch (escape) {
case 'n' -> '\n';
case 't' -> '\t';
case 'r' -> '\r';
case 'b' -> '\b';
case 'f' -> '\f';
case 'u' -> unicodeEscape();
default -> escape;
};
}
private char unicodeEscape() {
if (position + UNICODE_ESCAPE_DIGITS > text.length()) {
throw error("Unfinished \\u escape");
}
try {
char decoded = (char) Integer.parseInt(text.substring(position, position + UNICODE_ESCAPE_DIGITS), HEX);
position += UNICODE_ESCAPE_DIGITS;
return decoded;
} catch (NumberFormatException notHex) {
throw error("Malformed \\u escape");
}
}
private Literal bareLiteral() {
int start = position;
while (!atEnd() && STRUCTURE.indexOf(text.charAt(position)) < 0 && !Character.isWhitespace(text.charAt(position))) {
position++;
}
String word = text.substring(start, position);
if (!word.equals(TRUE) && !word.equals(FALSE) && !word.equals(NULL) && !NUMBER.matcher(word).matches()) {
position = start;
throw error(word.isEmpty() ? "Expected a value" : "Not a value: " + word);
}
return new Literal(start, position, Optional.empty());
}
void skipBlank() {
while (!atEnd()) {
char character = text.charAt(position);
if (Character.isWhitespace(character)) {
position++;
} else if (text.startsWith("//", position)) {
int lineEnd = text.indexOf('\n', position);
position = lineEnd < 0 ? text.length() : lineEnd;
} else if (text.startsWith("/*", position)) {
int commentEnd = text.indexOf("*/", position + 2);
position = commentEnd < 0 ? text.length() : commentEnd + 2;
} else {
return;
}
}
}
private char peek() {
return atEnd() ? '\0' : text.charAt(position);
}
private void expect(char wanted) {
if (peek() != wanted) {
throw error("Expected " + wanted);
}
position++;
}
IllegalArgumentException error(String problem) {
int line = 1;
for (int index = 0; index < Math.min(position, text.length()); index++) {
if (text.charAt(index) == '\n') {
line++;
}
}
return new IllegalArgumentException(problem + " on line " + line);
}
}
}
@@ -0,0 +1,76 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.iris.studio.scene.SceneBlocks;
import art.arcane.iris.studio.scene.SceneEntry;
import art.arcane.iris.studio.scene.SceneRequest;
import art.arcane.iris.studio.scene.SceneView;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
/** The pack's object files in 3D, filed by their folders. */
final class PackObjectsSceneView implements SceneView {
static final String ID = "iris:objects";
private static final char FOLDER_SEPARATOR = '/';
private static final int VARIANTS_OF_A_FILE = 1;
@Override
public String id() {
return ID;
}
@Override
public String label() {
return "Objects";
}
@Override
public String description() {
return "Every object file in the pack, in 3D";
}
@Override
public List<SceneEntry> entries(Engine engine) {
return Arrays.stream(engine.getData().getObjectLoader().getPossibleKeys())
.sorted()
.map(PackObjectsSceneView::entryOf)
.toList();
}
@Override
public SceneBlocks scene(Engine engine, SceneRequest request) {
String key = request.key();
IrisObject object = engine.getData().getObjectLoader().load(key);
if (object == null) {
throw new NoSuchElementException("No object file " + key);
}
return SceneBlocks.of(object);
}
private static SceneEntry entryOf(String key) {
int lastSeparator = key.lastIndexOf(FOLDER_SEPARATOR);
String folder = lastSeparator < 0 ? "" : key.substring(0, lastSeparator);
return new SceneEntry(key, key.substring(lastSeparator + 1), folder, VARIANTS_OF_A_FILE);
}
}
@@ -0,0 +1,59 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.studio.map.PalettePatterns;
import com.google.gson.Gson;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
/**
* A palette's pattern as the studio reads it, little endian:
* <pre>
* u32 header length | header, UTF-8 JSON | padding to 4 bytes | i16 picks[columns²]
* </pre>
* The header holds the columns across, the blocks between columns, the block states the picks index, and the pick
* ({@code noBlock}) of a column the palette places nothing at.
*/
final class PatternEncoding {
private static final int ALIGNMENT_BYTES = 4;
private PatternEncoding() {
}
static byte[] encode(PalettePatterns.Pattern pattern, int blocksPerColumn, Gson gson) {
byte[] header = gson.toJson(new Header(pattern.columns(), blocksPerColumn, pattern.blocks(), pattern.blocks(), PalettePatterns.NO_BLOCK))
.getBytes(StandardCharsets.UTF_8);
ByteBuffer buffer = ByteBuffer.allocate(aligned(Integer.BYTES + header.length) + pattern.picks().length * Short.BYTES)
.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(header.length).put(header);
buffer.position(aligned(buffer.position()));
buffer.asShortBuffer().put(pattern.picks());
return buffer.array();
}
private static int aligned(int bytes) {
return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES;
}
private record Header(int columns, int blocksPerColumn, java.util.List<String> blocks, java.util.List<String> drawnAs, int noBlock) {
}
}
@@ -0,0 +1,102 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.iris.studio.map.BakeRun;
import art.arcane.iris.studio.map.ObjectSource;
import art.arcane.iris.studio.map.ProceduralObjectSource;
import art.arcane.iris.studio.scene.SceneBakeTiming;
import art.arcane.iris.studio.scene.SceneBlocks;
import art.arcane.iris.studio.scene.SceneEntry;
import art.arcane.iris.studio.scene.SceneRequest;
import art.arcane.iris.studio.scene.SceneView;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.OptionalLong;
/** The trees, rock formations and more that the pack generates from settings, every variant in 3D. */
final class ProceduralObjectsSceneView implements SceneView {
static final String ID = "iris:objects/procedural";
private static final String BAKE_STAGE = "Bake";
private static final char FOLDER_SEPARATOR = '/';
private final ObjectSource source = new ProceduralObjectSource();
@Override
public String id() {
return ID;
}
@Override
public String label() {
return "Procedural";
}
@Override
public String description() {
return "Trees, rock formations and more that Iris generates from settings, every variant in 3D";
}
@Override
public boolean isBaked() {
return true;
}
@Override
public List<SceneEntry> entries(Engine engine) {
IrisData data = engine.getData();
return source.keys(data).stream()
.sorted()
.map(key -> entryOf(key, source.variants(data, key).size()))
.toList();
}
@Override
public SceneBlocks scene(Engine engine, SceneRequest request) {
IrisData data = engine.getData();
source.keys(data);
List<IrisObject> variants = source.variants(data, request.key());
if (variants.isEmpty()) {
throw new NoSuchElementException("No procedural object " + request.key());
}
return SceneBlocks.of(variants.get(Math.floorMod(request.variant(), variants.size())));
}
@Override
public SceneBakeTiming timeBake(Engine engine, String key) {
IrisData data = engine.getData();
source.keys(data);
OptionalLong seed = source.seed(key);
BakeRun run = seed.isEmpty() ? null : source.timeBake(data, key, seed.getAsLong());
if (run == null) {
throw new NoSuchElementException("No procedural object " + key);
}
return new SceneBakeTiming(run.variantCount(), List.of(new SceneBakeTiming.Stage(BAKE_STAGE, run.totalNanos())));
}
private static SceneEntry entryOf(String key, int variantCount) {
int lastSeparator = key.lastIndexOf(FOLDER_SEPARATOR);
String folder = lastSeparator < 0 ? "" : key.substring(0, lastSeparator);
return new SceneEntry(key, key.substring(lastSeparator + 1), folder, Math.max(1, variantCount));
}
}
@@ -0,0 +1,154 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.studio.scene.EditableSceneView.Creation;
import java.awt.Desktop;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.regex.Pattern;
/** The files of one creatable view's entries in a pack: written from the view's starter, looked up where used, and trashed. */
final class SceneFiles {
private static final Pattern KEY = Pattern.compile("[a-z0-9_-]+(/[a-z0-9_-]+)*");
private static final String FILE_EXTENSION = ".json";
// The pack watcher only reloads for .json, .iob and .png files, so a file being written is not read half done.
static final String WRITING_SUFFIX = ".tmp";
private static final String GENERATED_FOLDER_PREFIX = ".";
// The pack watcher ignores the .iris folder, so trashing a file there reloads the pack once, for the removal.
private static final String PACK_TRASH = ".iris/trash";
private static final String DESKTOP_TRASH = "the trash";
/** Where the desktop moves a file to its trash; absent a desktop it moves nothing. */
@FunctionalInterface
interface DesktopTrash {
/** @return whether the desktop took {@code file} to its trash */
boolean take(Path file);
}
private final Path packFolder;
private final Creation creation;
private final DesktopTrash desktopTrash;
SceneFiles(Path packFolder, Creation creation, DesktopTrash desktopTrash) {
this.packFolder = packFolder;
this.creation = creation;
this.desktopTrash = desktopTrash;
}
static DesktopTrash systemTrash() {
return file -> Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.MOVE_TO_TRASH)
&& Desktop.getDesktop().moveToTrash(file.toFile());
}
/** @return why {@code key} can't name an entry, or null when it can */
static String refusalOfKey(String key) {
if (key.isBlank()) {
return "Give it a name";
}
return KEY.matcher(key).matches() ? null : "Use lower case letters, digits, - and _, with / between folders";
}
/**
* Writes a new entry from the starter text at {@code key}.
*
* @throws IllegalArgumentException naming why, when {@code key} can't name a new entry or the starter is not JSON
*/
Path create(String key) throws IOException {
Path file = fileOf(key);
if (Files.exists(file)) {
throw new IllegalArgumentException(key + " already exists");
}
JsonText.parse(creation.starter());
Files.createDirectories(file.getParent());
Path written = file.resolveSibling(file.getFileName() + WRITING_SUFFIX);
Files.writeString(written, creation.starter(), StandardCharsets.UTF_8);
Files.move(written, file, StandardCopyOption.ATOMIC_MOVE);
return file;
}
/**
* The pack's files that name the entry at {@code key}, such as the biomes that place it, below the pack. Folders
* starting with a dot hold what the studio generates, like the schema, and are left out.
*/
List<String> usesOf(String key) throws IOException {
String reference = "\"" + creation.referencePrefix() + key + "\"";
Path own = fileOf(key);
List<String> using = new ArrayList<>();
Files.walkFileTree(packFolder, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path folder, BasicFileAttributes attributes) {
boolean generated = !folder.equals(packFolder) && folder.getFileName().toString().startsWith(GENERATED_FOLDER_PREFIX);
return generated ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
if (!file.equals(own) && file.getFileName().toString().endsWith(FILE_EXTENSION) && namesIn(file, reference)) {
using.add(packFolder.relativize(file).toString().replace('\\', '/'));
}
return FileVisitResult.CONTINUE;
}
});
using.sort(null);
return using;
}
/**
* Moves the entry at {@code key} to the desktop's trash, or where the desktop has none, to the pack's
* {@code .iris/trash}; returns where it went, to tell.
*
* @throws NoSuchElementException when the entry has no file
*/
String moveToTrash(String key) throws IOException {
Path file = fileOf(key);
if (!Files.isRegularFile(file)) {
throw new NoSuchElementException("Entry " + key + " has no file at " + packFolder.relativize(file));
}
if (desktopTrash.take(file)) {
return DESKTOP_TRASH;
}
Path trashed = packFolder.resolve(PACK_TRASH).resolve(key.replace('/', '_') + "-" + System.currentTimeMillis() + FILE_EXTENSION);
Files.createDirectories(trashed.getParent());
Files.move(file, trashed);
return PACK_TRASH;
}
private Path fileOf(String key) {
String refusal = refusalOfKey(key);
if (refusal != null) {
throw new IllegalArgumentException(refusal);
}
return packFolder.resolve(creation.folder()).resolve(key + FILE_EXTENSION);
}
private static boolean namesIn(Path file, String reference) throws IOException {
return new String(Files.readAllBytes(file), StandardCharsets.UTF_8).contains(reference);
}
}
@@ -0,0 +1,51 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
/**
* What the server asks of its machine: CPU counted like {@code top}, where 100 is one thread kept busy, and the Java
* heap in use.
*
* @param cpuPercent the process's CPU use with 100 per busy thread, or null when the JVM cannot tell
* @param threads the threads the server's CPU has, so the studio can show the most {@code cpuPercent} can reach
* @param heapUsedBytes the Java heap in use
* @param heapMaxBytes the most the Java heap can grow to
*/
record ServerUsage(Double cpuPercent, int threads, long heapUsedBytes, long heapMaxBytes) {
private static final double PERCENT_PER_THREAD = 100D;
static ServerUsage sample() {
Runtime runtime = Runtime.getRuntime();
OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean();
return of(processCpuLoad(system), runtime.availableProcessors(), runtime.totalMemory() - runtime.freeMemory(), runtime.maxMemory());
}
/** @param processCpuLoad the share of every core the process uses, or below zero when unknown */
static ServerUsage of(double processCpuLoad, int threads, long heapUsedBytes, long heapMaxBytes) {
Double cpuPercent = processCpuLoad < 0D ? null : processCpuLoad * threads * PERCENT_PER_THREAD;
return new ServerUsage(cpuPercent, threads, heapUsedBytes, heapMaxBytes);
}
private static double processCpuLoad(OperatingSystemMXBean system) {
return system instanceof com.sun.management.OperatingSystemMXBean hotspot ? hotspot.getProcessCpuLoad() : -1D;
}
}
@@ -0,0 +1,245 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
import art.arcane.iris.pack.schema.annotation.MinNumber;
import art.arcane.iris.pack.schema.annotation.RegistryListBlockType;
import art.arcane.iris.pack.schema.annotation.RegistryListResource;
import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.iris.platform.reflect.KeyedType;
import art.arcane.volmlib.util.documentation.Description;
import com.google.gson.Gson;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* The settings types of the pack as the node editor shows them, read from the pack's classes and the same annotations
* the pack's schema is written from: each setting's kind, limits, default and description.
*/
final class SettingsTypes {
/** The reference a block setting names, which the studio asks {@link StudioSuggestions} the blocks of. */
static final String BLOCK_REFERENCE = "BLOCK_TYPE";
private static final String IRIS_PACKAGE = "art.arcane.iris.";
private static final String PLAIN_FORMAT = "PLAIN";
private static final String KIND = "kind";
private static final Gson GSON = new Gson();
private SettingsTypes() {
}
/** {@code roots} and the types inside them, by class name. */
static Map<String, TypeWire> reachableFrom(Collection<Class<?>> roots) {
Map<String, TypeWire> described = new LinkedHashMap<>();
Deque<Class<?>> pending = new ArrayDeque<>(roots);
while (!pending.isEmpty()) {
Class<?> type = pending.pop();
if (described.containsKey(type.getName())) {
continue;
}
Object defaults = newInstanceOrNull(type);
List<OptionWire> options = settingsOf(type).stream().map(field -> optionOf(field, defaults, pending)).toList();
described.put(type.getName(), new TypeWire(descriptionOf(type.getAnnotation(Description.class)), options));
}
return described;
}
/** Whether a setting of {@code type} is an object of settings of its own, such as a palette, rather than a plain value. */
private static boolean isSettingsObject(Class<?> type) {
return type.getName().startsWith(IRIS_PACKAGE) && !type.isEnum() && !type.isArray()
&& !KeyedType.isKeyed(type) && !Collection.class.isAssignableFrom(type) && !Map.class.isAssignableFrom(type);
}
// The fields a file can set, a parent class's first, as the pack reads them.
private static List<Field> settingsOf(Class<?> type) {
List<Field> settings = new ArrayList<>();
Class<?> parent = type.getSuperclass();
if (parent != null && parent.getName().startsWith(IRIS_PACKAGE)) {
settings.addAll(settingsOf(parent));
}
Arrays.stream(type.getDeclaredFields())
.filter(field -> !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())
&& !Modifier.isTransient(field.getModifiers()))
.forEach(settings::add);
return settings;
}
private static OptionWire optionOf(Field field, Object defaults, Deque<Class<?>> pending) {
MinNumber minimum = field.getAnnotation(MinNumber.class);
MaxNumber maximum = field.getAnnotation(MaxNumber.class);
ArrayType arrayType = field.getAnnotation(ArrayType.class);
Integer minItems = arrayType == null || arrayType.min() <= 0 ? null : arrayType.min();
return new OptionWire(field.getName(), descriptionOf(field.getAnnotation(Description.class)), field.isAnnotationPresent(Required.class),
minimum == null ? null : minimum.value(), maximum == null ? null : maximum.value(), minItems,
defaultOf(field, defaults), kindOf(field, pending));
}
private static Map<String, Object> kindOf(Field field, Deque<Class<?>> pending) {
Class<?> type = field.getType();
if (Collection.class.isAssignableFrom(type)) {
return listOf(kindOfValue(elementTypeOf(field), field, pending));
}
if (Map.class.isAssignableFrom(type)) {
return wire("map", "value", kindOfValue(typeArgument(field, 1), field, pending));
}
return kindOfValue(type, field, pending);
}
// A list's or map's elements take the registry the field names, as a list of blocks does.
private static Map<String, Object> kindOfValue(Class<?> type, Field field, Deque<Class<?>> pending) {
if (type == null) {
return wire("any");
}
if (type == boolean.class || type == Boolean.class) {
return wire("boolean");
}
if (type == int.class || type == long.class || type == short.class || type == byte.class || type == Integer.class || type == Long.class) {
return wire("integer");
}
if (type == double.class || type == float.class || type == Double.class || type == Float.class) {
return wire("decimal");
}
if (type == String.class) {
return textKindOf(field);
}
if (type.isEnum()) {
return wire("enum", "constants", Arrays.stream(type.getEnumConstants()).map(constant -> constantOf((Enum<?>) constant)).toList());
}
if (KeyedType.isKeyed(type)) {
return wire("enum", "constants", Arrays.stream(KeyedType.values(type)).map(name -> Map.of("name", name, "description", "")).toList());
}
if (isSettingsObject(type)) {
pending.add(type);
return wire("object", "type", type.getName());
}
return wire("any");
}
private static Map<String, Object> textKindOf(Field field) {
if (field.isAnnotationPresent(RegistryListBlockType.class)) {
return wire("reference", "reference", BLOCK_REFERENCE, "format", PLAIN_FORMAT);
}
RegistryListResource resource = field.getAnnotation(RegistryListResource.class);
String folder = resource == null ? null : folderOf(resource.value());
if (folder != null) {
return wire("resource", "resource", folder);
}
return wire("text", "format", PLAIN_FORMAT);
}
private static String folderOf(Class<? extends IrisRegistrant> registrant) {
Object instance = newInstanceOrNull(registrant);
return instance instanceof IrisRegistrant resource ? resource.getFolderName() : null;
}
private static Map<String, Object> listOf(Map<String, Object> element) {
Map<String, Object> list = wire("list", "element", element);
list.put("unique", false);
return list;
}
private static Class<?> elementTypeOf(Field field) {
ArrayType arrayType = field.getAnnotation(ArrayType.class);
return arrayType != null ? arrayType.type() : typeArgument(field, 0);
}
private static Class<?> typeArgument(Field field, int index) {
if (!(field.getGenericType() instanceof ParameterizedType parameterized) || parameterized.getActualTypeArguments().length <= index) {
return null;
}
Type argument = parameterized.getActualTypeArguments()[index];
return argument instanceof Class<?> type ? type : null;
}
private static Map<String, String> constantOf(Enum<?> constant) {
try {
Description description = constant.getDeclaringClass().getField(constant.name()).getAnnotation(Description.class);
return Map.of("name", constant.name(), "description", descriptionOf(description));
} catch (NoSuchFieldException undocumented) {
return Map.of("name", constant.name(), "description", "");
}
}
// Only plain values are shown as defaults; an object or list is described by its own settings.
private static Object defaultOf(Field field, Object defaults) {
if (defaults == null) {
return null;
}
Object value;
try {
field.setAccessible(true);
value = field.get(defaults);
} catch (ReflectiveOperationException | RuntimeException unreadable) {
return null;
}
return switch (value) {
case null -> null;
case Boolean plain -> plain;
case Number plain -> plain;
case String plain -> plain;
case Enum<?> constant -> constant.name();
default -> null;
};
}
private static Object newInstanceOrNull(Class<?> type) {
try {
var constructor = type.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
} catch (ReflectiveOperationException | RuntimeException | LinkageError noPlainConstructor) {
return null;
}
}
private static String descriptionOf(Description description) {
return description == null ? "" : description.value();
}
private static Map<String, Object> wire(String kind, Object... members) {
Map<String, Object> wire = new LinkedHashMap<>();
wire.put(KIND, kind);
for (int index = 0; index + 1 < members.length; index += 2) {
wire.put((String) members[index], members[index + 1]);
}
return wire;
}
/** A settings type: what it is for, and the settings a file of it may write. */
record TypeWire(String description, List<OptionWire> options) {
}
/** One setting; a limit or default the pack does not give is null. */
record OptionWire(String name, String description, boolean required, Double minimum, Double maximum, Integer minItems,
Object defaultValue, Map<String, Object> kind) {
}
}
@@ -0,0 +1,828 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.studio.map.StudioAssets;
import art.arcane.iris.studio.map.StudioHover;
import art.arcane.iris.studio.imagemap.ImageMapPreviews;
import art.arcane.iris.studio.map.PalettePatterns;
import art.arcane.iris.studio.noise.NoiseSources;
import art.arcane.iris.studio.noise.NoiseTile;
import art.arcane.iris.studio.scene.SceneBakeTiming;
import art.arcane.iris.studio.scene.SceneBlocks;
import art.arcane.iris.studio.scene.SceneEntry;
import art.arcane.iris.studio.scene.SceneForm;
import art.arcane.iris.studio.scene.SceneRequest;
import art.arcane.iris.studio.scene.SceneSizes;
import art.arcane.iris.studio.scene.SceneView;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.studio.view.GuiMarker;
import art.arcane.iris.studio.view.PregenRenderSnapshot;
import art.arcane.iris.studio.view.PregeneratorJob;
import art.arcane.volmlib.util.function.NoiseProvider;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
/**
* An Iris Studio app's connection to one world: HTTP on the loopback interface, on a free port, each request carrying
* the bridge's token as {@code Authorization: Bearer <token>}. JSON for the world, hovers and players; tiles in
* {@link StudioTile}; {@code /v1/events} streams {@link StudioEvents}. Requests run on a small pool of daemon threads,
* so a busy studio cannot hold up the server.
*/
public final class StudioBridge implements AutoCloseable {
private static final String API = "/v1/";
private static final int TOKEN_BYTES = 24;
private static final int DEFAULT_TILE_SIZE = 128;
private static final int LARGEST_TILE_SIZE = 512;
private static final double SMALLEST_BLOCKS_PER_PIXEL = 1D / 16D;
private static final double LARGEST_BLOCKS_PER_PIXEL = 4_096D;
private static final double SMALLEST_NOISE_BLOCKS_PER_PIXEL = 1D / 64D;
private static final int LARGEST_PATTERN_BLOCKS_PER_COLUMN = 64;
private static final int DEFAULT_IMAGE_MAP_PREVIEW_PIXELS = 768;
private static final ModuleViewInfo PALETTES_VIEW = new ModuleViewInfo("iris:terrain/palettes", "Palettes",
"The blocks each biome's palette layers place");
private static final long DROPPED_TILE_KEPT_MINUTES = 10;
private static final long ENTITY_WAIT_MILLIS = 3_000L;
private static final String ASSETS_ENDPOINT = "assets/";
private static final String ASSET_RETRY_SECONDS = "2";
private static final long ASSET_CACHE_SECONDS = 86_400L;
private static final String OVERRIDE_PREFIX = "set.";
private static final int LARGEST_BODY_BYTES = 4 * 1024 * 1024;
private static final String VIEW_BIOMES = "biomes";
private static final String VIEW_REGIONS = "regions";
private static final String VIEW_RIVERS = "rivers";
static final int STATUS_OK = 200;
static final int STATUS_NO_CONTENT = 204;
static final int STATUS_BAD_REQUEST = 400;
static final int STATUS_UNAUTHORIZED = 401;
static final int STATUS_FORBIDDEN = 403;
static final int STATUS_NOT_FOUND = 404;
static final int STATUS_METHOD_NOT_ALLOWED = 405;
static final int STATUS_CONFLICT = 409;
static final int STATUS_UNPROCESSABLE = 422;
static final int STATUS_SERVER_ERROR = 500;
static final int STATUS_UNAVAILABLE = 503;
private static final String VIEW_HEIGHT = "height";
private static final String GROUP_WORLD = "WORLD";
private static final String GROUP_BIOME_LAYERS = "BIOME_LAYERS";
private static final String GROUP_DIAGNOSTICS = "DIAGNOSTICS";
private static final List<ViewInfo> VIEWS = List.of(
new ViewInfo(VIEW_BIOMES, "Biomes", "The biome at each spot, in the biome's colour", GROUP_WORLD, "World"),
new ViewInfo(VIEW_REGIONS, "Regions", "The region each spot belongs to", GROUP_WORLD, "World"),
new ViewInfo(VIEW_HEIGHT, "Height", "Terrain height, from deep water to snowy peaks", GROUP_WORLD, "World"),
new ViewInfo(VIEW_RIVERS, "Rivers", "Streams, rivers, falls, ponds, lakes, sea inlets, grottos and cave pools from the hydrology",
GROUP_WORLD, "World"),
new ViewInfo("land-biomes", "Land biomes", "The land biome each spot would get, also where the sea is", GROUP_BIOME_LAYERS, "Biome layers"),
new ViewInfo("sea-biomes", "Sea biomes", "The sea biome each spot would get, also where the land is", GROUP_BIOME_LAYERS, "Biome layers"),
new ViewInfo("cave-biomes", "Cave biomes", "The cave biome under each spot", GROUP_BIOME_LAYERS, "Biome layers"),
new ViewInfo("object-load", "Object load", "Configuration estimate of object density and chance, not measured performance",
GROUP_DIAGNOSTICS, "Diagnostics"),
new ViewInfo("decorator-load", "Decorator load", "Configuration estimate of decorator chance and stacks, not measured performance",
GROUP_DIAGNOSTICS, "Diagnostics"),
new ViewInfo("layer-load", "Layer load", "Configuration estimate of biome layer count, not measured performance",
GROUP_DIAGNOSTICS, "Diagnostics"),
new ViewInfo("noise", "Noise", "The pack's generators and the built-in noise styles, from above or as terrain",
"GENERATORS", "Generators"),
new ViewInfo("pregen", "Pregeneration", "The chunks of the running pregeneration as they are generated, with its progress", GROUP_WORLD, "World"),
new ViewInfo("imageMaps","Image maps", "Terrain height, biomes or masks painted from a PNG, previewed over the world area they cover",
"GENERATORS", "Generators"));
private final StudioWorld world;
private final String token;
private final Gson gson = new GsonBuilder().serializeNulls().create();
private final HttpServer server;
private final int port;
private final ExecutorService workers;
private final ScheduledExecutorService ticker;
private final StudioEvents events;
private final StudioScenes scenes = new StudioScenes();
private final Runnable hotloadHook;
private final Cache<String, AtomicBoolean> droppedTiles = Caffeine.newBuilder().expireAfterWrite(DROPPED_TILE_KEPT_MINUTES, TimeUnit.MINUTES).build();
private volatile boolean closed;
private StudioBridge(StudioWorld world) throws IOException {
this.world = world;
this.token = newToken();
this.events = new StudioEvents(world, gson);
this.server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
this.port = server.getAddress().getPort();
this.workers = Executors.newFixedThreadPool(workerCount(), daemonThreads("Iris Studio Bridge"));
this.ticker = Executors.newSingleThreadScheduledExecutor(daemonThreads("Iris Studio Events"));
this.hotloadHook = events::hotloaded;
server.setExecutor(workers);
server.createContext(API, this::handle);
}
static StudioBridge start(StudioWorld world) throws IOException {
StudioBridge bridge = new StudioBridge(world);
bridge.server.start();
bridge.ticker.scheduleWithFixedDelay(bridge::pollEvents, 0L, StudioEvents.POLL_INTERVAL_MILLIS, TimeUnit.MILLISECONDS);
GuiHost.get().registerHotloadHook(bridge.hotloadHook);
return bridge;
}
public String worldName() {
return world.name();
}
public int port() {
return port;
}
public String token() {
return token;
}
/** What the studio app opens to connect. */
public String link() {
return "iris-studio://127.0.0.1:" + port() + "/?token=" + token;
}
@Override
public void close() {
if (closed) {
return;
}
closed = true;
GuiHost.get().unregisterHotloadHook(hotloadHook);
ticker.shutdownNow();
events.closeAll();
server.stop(0);
workers.shutdownNow();
}
private void pollEvents() {
try {
events.poll();
} catch (Throwable error) {
IrisLogging.debug("Studio events failed: " + error);
}
}
private void handle(HttpExchange exchange) throws IOException {
try {
allowAnyOrigin(exchange.getResponseHeaders());
if ("OPTIONS".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(STATUS_NO_CONTENT, -1);
exchange.close();
return;
}
if (!isAuthorized(exchange)) {
throw new RequestError(STATUS_UNAUTHORIZED, "Missing or wrong token");
}
route(exchange);
} catch (RequestError error) {
sendJson(exchange, error.status, new ErrorBody(error.getMessage()));
} catch (CancellationException stopped) {
sendJson(exchange, STATUS_UNAVAILABLE, new ErrorBody("The world stopped"));
} catch (IOException clientHungUp) {
exchange.close();
} catch (Throwable error) {
IrisLogging.reportError("Studio bridge request " + exchange.getRequestURI().getPath(), error);
sendJson(exchange, STATUS_SERVER_ERROR, new ErrorBody(String.valueOf(error.getMessage())));
}
}
private void route(HttpExchange exchange) throws IOException {
String endpoint = exchange.getRequestURI().getPath().substring(API.length());
Query query = Query.of(exchange.getRequestURI());
if (endpoint.startsWith(ASSETS_ENDPOINT)) {
sendAsset(exchange, endpoint);
return;
}
switch (endpoint) {
case "world" -> sendJson(exchange, STATUS_OK, worldInfo(get(exchange)));
case "tile" -> sendBytes(exchange, "application/octet-stream", tile(get(exchange), query));
case "tile-cancel" -> cancelTile(exchange, query);
case "hover" -> sendJson(exchange, STATUS_OK, hover(get(exchange).engine(), query));
case "picks" -> sendJson(exchange, STATUS_OK, new PickInspection("", List.of()));
case "regions" -> sendJson(exchange, STATUS_OK, StudioHover.previewableRegions(get(exchange).engine()));
case "entities" -> sendJson(exchange, STATUS_OK, entities(get(exchange)));
case "scenes" -> sendJson(exchange, STATUS_OK, scenes.infos());
case "scene-entries" -> sendJson(exchange, STATUS_OK, sceneEntries(get(exchange).engine(), query));
case "scene" -> sendBytes(exchange, "application/octet-stream", scene(get(exchange).engine(), query).encode(gson));
case "scene-parts" -> sendBytes(exchange, "application/octet-stream", StudioScenes.encodeParts(scene(get(exchange).engine(), query)));
case "profile-form" -> sendJson(exchange, STATUS_OK, sceneForm(get(exchange).engine(), query));
case "scene-bake" -> sendJson(exchange, STATUS_OK, sceneBake(get(exchange).engine(), query));
case "scene-file" -> sendJson(exchange, STATUS_OK, sceneFile(get(exchange).engine(), query));
case "scene-edit" -> sendJson(exchange, STATUS_OK, sceneEdit(exchange, query));
case "scene-write" -> sendJson(exchange, STATUS_OK, sceneWrite(exchange, query));
case "scene-create" -> sendJson(exchange, STATUS_OK, sceneCreate(exchange, query));
case "scene-uses" -> sendJson(exchange, STATUS_OK, sceneUses(get(exchange).engine(), query));
case "scene-delete" -> sendJson(exchange, STATUS_OK, sceneDelete(exchange, query));
case "suggestions" -> sendJson(exchange, STATUS_OK, suggestions(get(exchange).engine(), query));
case "noise-sources" -> sendJson(exchange, STATUS_OK, NoiseSources.of(get(exchange).engine()).list());
case "noise-tile" -> sendBytes(exchange, "application/octet-stream", noiseTile(get(exchange).engine(), query));
case "patterns" -> sendJson(exchange, STATUS_OK, List.of(PALETTES_VIEW));
case "pattern-entries" -> sendJson(exchange, STATUS_OK, patternEntries(get(exchange).engine(), query));
case "pattern" -> sendBytes(exchange, "application/octet-stream", pattern(get(exchange).engine(), query));
case "pregen" -> sendJson(exchange, STATUS_OK, pregenStatus(exchange));
case "pregen-map" -> sendBytes(exchange, "image/png", pregenMap(exchange));
case "pregen-pause" -> sendJson(exchange, STATUS_OK, pregenPause(exchange));
case "image-maps" -> sendJson(exchange, STATUS_OK, ImageMapPreviews.entries(get(exchange).engine()));
case "image-map" -> sendJson(exchange, STATUS_OK, answering(() -> ImageMapPreviews.details(get(exchange).engine(), query.text("key"))));
case "image-map-preview" -> sendBytes(exchange, "image/png", imageMapPreview(get(exchange).engine(), query));
case "saved-worlds" -> sendJson(exchange, STATUS_OK, List.of());
case "events" -> streamEvents(exchange);
case "teleport" -> teleport(exchange, query);
case "open" -> throw new RequestError(STATUS_NOT_FOUND, "Opening a pack file from the studio is not available in Iris v4");
default -> throw new RequestError(STATUS_NOT_FOUND, "No such endpoint: " + endpoint);
}
}
private StudioWorld.Session get(HttpExchange exchange) {
requireMethod(exchange, "GET");
return runningSession();
}
private StudioWorld.Session post(HttpExchange exchange) {
requireMethod(exchange, "POST");
return runningSession();
}
private StudioWorld.Session runningSession() {
StudioWorld.Session session = world.session();
if (session == null) {
throw new RequestError(STATUS_UNAVAILABLE, "The world " + world.name() + " has no running engine");
}
return session;
}
private static void requireMethod(HttpExchange exchange, String method) {
if (!method.equals(exchange.getRequestMethod())) {
throw new RequestError(STATUS_METHOD_NOT_ALLOWED, "Use " + method);
}
}
private WorldInfo worldInfo(StudioWorld.Session session) {
Engine engine = session.engine();
return new WorldInfo(
world.name(),
engine.getDimension().getLoadKey(),
engine.getDimension().getName(),
Long.toString(engine.getWorld().getRawWorldSeed()),
engine.getMinHeight(),
engine.getHeight(),
engine.getDimension().getFluidHeight(),
DEFAULT_TILE_SIZE,
session.overlay() != null,
session.tiles().hydrologyEnabled(),
VIEWS
);
}
private static String viewOf(Query query) {
String view = query.text("view");
if (VIEWS.stream().noneMatch(known -> known.id().equals(view))) {
throw new RequestError(STATUS_BAD_REQUEST, "Unknown view: " + view);
}
return view;
}
private static String previewOf(Query query) {
if (!query.has("preview")) {
return null;
}
if (!VIEW_REGIONS.equals(viewOf(query))) {
throw new RequestError(STATUS_BAD_REQUEST, "Only the region view previews a region");
}
return query.text("preview");
}
private static StudioHover.Hover hover(Engine engine, Query query) {
String view = viewOf(query);
String preview = previewOf(query);
if (preview != null && engine.getData().getRegionLoader().load(preview) == null) {
throw new RequestError(STATUS_BAD_REQUEST, "This world has no region " + preview);
}
return StudioHover.sample(engine, query.number("x"), query.number("z"), preview, !VIEW_REGIONS.equals(view) || preview != null);
}
private byte[] tile(StudioWorld.Session session, Query query) {
Engine engine = session.engine();
String view = viewOf(query);
String preview = previewOf(query);
int size = query.whole("size", DEFAULT_TILE_SIZE);
double blocksPerPixel = query.number("scale");
if (size < 1 || size > LARGEST_TILE_SIZE) {
throw new RequestError(STATUS_BAD_REQUEST, "A tile is 1 to " + LARGEST_TILE_SIZE + " pixels");
}
if (!(blocksPerPixel >= SMALLEST_BLOCKS_PER_PIXEL && blocksPerPixel <= LARGEST_BLOCKS_PER_PIXEL)) {
throw new RequestError(STATUS_BAD_REQUEST, "The scale is " + SMALLEST_BLOCKS_PER_PIXEL + " to " + LARGEST_BLOCKS_PER_PIXEL + " blocks per pixel");
}
double tileBlocks = size * blocksPerPixel;
double startX = query.whole("x", 0) * tileBlocks;
double startZ = query.whole("z", 0) * tileBlocks;
AtomicBoolean dropped = query.has("request") ? droppedFlagOf(query.text("request")) : new AtomicBoolean();
BooleanSupplier cancelled = () -> dropped.get() || closed || engine.isClosing() || engine.isClosed();
StudioTile tile = VIEW_RIVERS.equals(view)
? session.tiles().rivers(startX, startZ, blocksPerPixel, size, cancelled)
: session.tiles().biomesOrRegions(view, preview, startX, startZ, blocksPerPixel, size, query.flag("heights"), cancelled);
return tile.encode(gson);
}
private static PregenStatus pregenStatus(HttpExchange exchange) {
requireMethod(exchange, "GET");
PregeneratorJob job = PregeneratorJob.getInstance();
if (job == null) {
return new PregenStatus(false, null);
}
return new PregenStatus(true, job.renderSnapshot());
}
private static byte[] pregenMap(HttpExchange exchange) {
requireMethod(exchange, "GET");
PregeneratorJob job = PregeneratorJob.getInstance();
if (job == null) {
throw new RequestError(STATUS_NOT_FOUND, "No pregeneration is running");
}
return job.renderMapState().png();
}
private static MessageBody pregenPause(HttpExchange exchange) {
requireMethod(exchange, "POST");
if (!PregeneratorJob.pauseResume()) {
throw new RequestError(STATUS_NOT_FOUND, "No pregeneration to pause or resume");
}
return new MessageBody(PregeneratorJob.isPaused() ? "Paused" : "Running");
}
private static byte[] imageMapPreview(Engine engine, Query query) {
try {
return answering(() -> ImageMapPreviews.preview(engine, query.text("key"), query.whole("size", DEFAULT_IMAGE_MAP_PREVIEW_PIXELS)));
} catch (IllegalArgumentException refused) {
throw new RequestError(STATUS_BAD_REQUEST, refused.getMessage());
}
}
private static List<PalettePatterns.Entry> patternEntries(Engine engine, Query query) {
requirePalettesView(query);
return PalettePatterns.entries(engine);
}
private byte[] pattern(Engine engine, Query query) {
requirePalettesView(query);
int columns = query.whole("size", DEFAULT_TILE_SIZE);
int blocksPerColumn = query.whole("scale", 1);
if (columns < 1 || columns > LARGEST_TILE_SIZE) {
throw new RequestError(STATUS_BAD_REQUEST, "A pattern is 1 to " + LARGEST_TILE_SIZE + " columns across");
}
if (blocksPerColumn < 1 || blocksPerColumn > LARGEST_PATTERN_BLOCKS_PER_COLUMN) {
throw new RequestError(STATUS_BAD_REQUEST, "The scale is 1 to " + LARGEST_PATTERN_BLOCKS_PER_COLUMN + " whole blocks per column");
}
String key = query.text("key");
int tileBlocks = columns * blocksPerColumn;
PalettePatterns.Pattern pattern = PalettePatterns.pattern(engine, key, query.whole("depth", 0),
query.whole("x", 0) * tileBlocks, query.whole("z", 0) * tileBlocks, columns, blocksPerColumn)
.orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No palette " + key));
return PatternEncoding.encode(pattern, blocksPerColumn, gson);
}
private static void requirePalettesView(Query query) {
if (!PALETTES_VIEW.id().equals(query.text("view"))) {
throw new RequestError(STATUS_NOT_FOUND, "No pattern view " + query.text("view"));
}
}
private byte[] noiseTile(Engine engine, Query query) {
int size = query.whole("size", DEFAULT_TILE_SIZE);
double blocksPerPixel = query.number("scale");
if (size < 1 || size > LARGEST_TILE_SIZE) {
throw new RequestError(STATUS_BAD_REQUEST, "A tile is 1 to " + LARGEST_TILE_SIZE + " pixels");
}
if (!(blocksPerPixel >= SMALLEST_NOISE_BLOCKS_PER_PIXEL && blocksPerPixel <= LARGEST_BLOCKS_PER_PIXEL)) {
throw new RequestError(STATUS_BAD_REQUEST, "The scale is " + SMALLEST_NOISE_BLOCKS_PER_PIXEL + " to " + LARGEST_BLOCKS_PER_PIXEL + " blocks per pixel");
}
NoiseSources sources = NoiseSources.of(engine);
String source = query.text("source");
NoiseProvider noise = noiseSampler(sources, source, query.longNumber("seed"));
return NoiseTile.sample(noise, query.whole("x", 0), query.whole("z", 0), blocksPerPixel, size, sources.isSmooth(source),
() -> closed || engine.isClosing() || engine.isClosed()).encode();
}
// A source that cannot be sampled fails every tile alike, so it is told once to the studio rather than logged per tile.
private static NoiseProvider noiseSampler(NoiseSources sources, String source, long seed) {
try {
return sources.sampler(source, seed);
} catch (NoSuchElementException unknown) {
throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
} catch (IllegalStateException unsampleable) {
throw new RequestError(STATUS_UNPROCESSABLE, unsampleable.getMessage());
}
}
// Asset paths name one file of one Minecraft version, so a studio may keep what it fetched for as long as it runs.
private static void sendAsset(HttpExchange exchange, String endpoint) throws IOException {
requireMethod(exchange, "GET");
byte[] asset;
try {
asset = StudioAssets.read(endpoint).orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No asset " + endpoint));
} catch (StudioAssets.NotReadyException notReady) {
exchange.getResponseHeaders().set("Retry-After", ASSET_RETRY_SECONDS);
throw new RequestError(STATUS_UNAVAILABLE, notReady.getMessage());
}
exchange.getResponseHeaders().set("Cache-Control", "max-age=" + ASSET_CACHE_SECONDS + ", immutable");
sendBytes(exchange, endpoint.endsWith(".png") ? "image/png" : "application/json", asset);
}
private List<SceneEntry> sceneEntries(Engine engine, Query query) {
return answering(() -> sceneView(query).entries(engine));
}
private SceneForm sceneForm(Engine engine, Query query) {
SceneView view = sceneView(query);
if (!view.hasForm()) {
throw new RequestError(STATUS_NOT_FOUND, "The entries of " + view.id() + " have no settings form");
}
return answering(() -> view.form(engine, query.text("key"), query.prefixed(OVERRIDE_PREFIX)));
}
private SceneBakeTiming sceneBake(Engine engine, Query query) {
SceneView view = sceneView(query);
if (!view.isBaked()) {
throw new RequestError(STATUS_NOT_FOUND, "The entries of " + view.id() + " are not baked");
}
return answering(() -> view.timeBake(engine, query.text("key")));
}
private SceneBlocks scene(Engine engine, Query query) {
SceneView view = sceneView(query);
SceneRequest request = new SceneRequest(query.text("key"), query.whole("variant", 0), sizeOf(view, query), query.prefixed(OVERRIDE_PREFIX));
return answering(() -> view.scene(engine, request));
}
// A view with sizes is asked at one of them, the one it opens with when the studio names none.
private static int sizeOf(SceneView view, Query query) {
SceneSizes sizes = view.sizes();
if (sizes == null) {
return 0;
}
int size = query.whole("size", sizes.opening());
if (!sizes.blocksAcross().contains(size)) {
throw new RequestError(STATUS_BAD_REQUEST, "View " + view.id() + " builds scenes " + sizes.blocksAcross() + " blocks across, not " + size);
}
return size;
}
private SceneView sceneView(Query query) {
return answering(() -> scenes.view(query.text("view")));
}
// An entry the pack does not have is the studio's to be told about, not a failure of the bridge.
private static <T> T answering(SceneTask<T> task) {
try {
return task.run();
} catch (NoSuchElementException unknown) {
throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
} catch (IOException failed) {
throw new IllegalStateException(failed);
}
}
@FunctionalInterface
private interface SceneTask<T> {
T run() throws IOException;
}
private StudioEditors.EditorState sceneFile(Engine engine, Query query) {
return editing(() -> editorsOf(engine).read(query.text("view"), query.text("key")));
}
private StudioEditors.EditorState sceneEdit(HttpExchange exchange, Query query) throws IOException {
Engine engine = post(exchange).engine();
String body = readBody(exchange);
return editing(() -> {
GraphEditRequest request = GraphEditRequest.parse(body);
return editorsOf(engine).edit(query.text("view"), query.text("key"), request.revision(), request.edit());
});
}
private StudioEditors.EditorState sceneWrite(HttpExchange exchange, Query query) throws IOException {
Engine engine = post(exchange).engine();
String body = readBody(exchange);
return editing(() -> {
GraphEditRequest.FileWrite write = GraphEditRequest.FileWrite.parse(body);
return editorsOf(engine).write(query.text("view"), query.text("key"), write.revision(), write.text());
});
}
private MessageBody sceneCreate(HttpExchange exchange, Query query) {
Engine engine = post(exchange).engine();
return editing(() -> {
editorsOf(engine).create(query.text("view"), query.text("key"));
return new MessageBody("Created " + query.text("key"));
});
}
private UsesBody sceneUses(Engine engine, Query query) {
return editing(() -> new UsesBody(editorsOf(engine).usesOf(query.text("view"), query.text("key"))));
}
private TrashedBody sceneDelete(HttpExchange exchange, Query query) {
Engine engine = post(exchange).engine();
return editing(() -> new TrashedBody(editorsOf(engine).delete(query.text("view"), query.text("key"))));
}
// What a setting naming a block (reference) or a pack resource (resource) may be typed as.
private static List<String> suggestions(Engine engine, Query query) {
return answering(() -> query.has("reference")
? StudioSuggestions.ofReference(engine.getData(), query.text("reference"))
: StudioSuggestions.ofResource(engine.getData(), query.text("resource")));
}
private StudioEditors editorsOf(Engine engine) {
return new StudioEditors(scenes, engine, SceneFiles.systemTrash());
}
// A refused edit is the user's to fix, so it answers with why rather than as a failure of the bridge.
private static <T> T editing(SceneTask<T> task) {
try {
return answering(task);
} catch (StudioEditors.StaleEditException stale) {
throw new RequestError(STATUS_CONFLICT, stale.getMessage());
} catch (StudioEditors.EditsLockedException locked) {
throw new RequestError(STATUS_FORBIDDEN, locked.getMessage());
} catch (IllegalArgumentException refused) {
throw new RequestError(STATUS_UNPROCESSABLE, refused.getMessage());
}
}
private static String readBody(HttpExchange exchange) throws IOException {
byte[] body = exchange.getRequestBody().readNBytes(LARGEST_BODY_BYTES + 1);
if (body.length > LARGEST_BODY_BYTES) {
throw new RequestError(STATUS_BAD_REQUEST, "The body is over " + LARGEST_BODY_BYTES + " bytes");
}
return new String(body, StandardCharsets.UTF_8);
}
private void cancelTile(HttpExchange exchange, Query query) throws IOException {
requireMethod(exchange, "POST");
droppedFlagOf(query.text("request")).set(true);
sendJson(exchange, STATUS_OK, new MessageBody(null));
}
private AtomicBoolean droppedFlagOf(String requestId) {
return droppedTiles.get(requestId, id -> new AtomicBoolean());
}
private List<GuiMarker> entities(StudioWorld.Session session) {
if (session.overlay() == null) {
return List.of();
}
CompletableFuture<List<GuiMarker>> found = new CompletableFuture<>();
session.overlay().requestEntities(found::complete);
try {
return found.get(ENTITY_WAIT_MILLIS, TimeUnit.MILLISECONDS);
} catch (TimeoutException slow) {
throw new RequestError(STATUS_UNAVAILABLE, "The server did not list its entities in time");
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new CancellationException("Bridge closing");
} catch (ExecutionException failed) {
throw new IllegalStateException(failed.getCause());
}
}
private void teleport(HttpExchange exchange, Query query) throws IOException {
StudioWorld.Session session = post(exchange);
if (session.overlay() == null) {
throw new RequestError(STATUS_NOT_FOUND, "This server cannot do that from the studio");
}
session.overlay().teleport(query.number("x"), query.number("z"));
sendJson(exchange, STATUS_OK, new MessageBody(null));
}
private void streamEvents(HttpExchange exchange) throws IOException {
requireMethod(exchange, "GET");
Headers headers = exchange.getResponseHeaders();
headers.set("Content-Type", "text/event-stream; charset=utf-8");
headers.set("Cache-Control", "no-cache");
exchange.sendResponseHeaders(STATUS_OK, 0);
OutputStream body = exchange.getResponseBody();
body.flush();
events.listen(body);
}
private boolean isAuthorized(HttpExchange exchange) {
String header = exchange.getRequestHeaders().getFirst("Authorization");
String expected = "Bearer " + token;
return header != null && MessageDigest.isEqual(
header.getBytes(StandardCharsets.UTF_8), expected.getBytes(StandardCharsets.UTF_8));
}
private static void allowAnyOrigin(Headers headers) {
headers.set("Access-Control-Allow-Origin", "*");
headers.set("Access-Control-Allow-Headers", "Authorization");
headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
}
private void sendJson(HttpExchange exchange, int status, Object body) throws IOException {
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
send(exchange, status, gson.toJson(body).getBytes(StandardCharsets.UTF_8));
}
private static void sendBytes(HttpExchange exchange, String contentType, byte[] body) throws IOException {
exchange.getResponseHeaders().set("Content-Type", contentType);
send(exchange, STATUS_OK, body);
}
private static void send(HttpExchange exchange, int status, byte[] body) throws IOException {
try (exchange) {
exchange.sendResponseHeaders(status, body.length);
exchange.getResponseBody().write(body);
}
}
private static String newToken() {
byte[] bytes = new byte[TOKEN_BYTES];
new SecureRandom().nextBytes(bytes);
return HexFormat.of().formatHex(bytes);
}
private static int workerCount() {
return Math.max(2, Runtime.getRuntime().availableProcessors() / 2);
}
private static ThreadFactory daemonThreads(String name) {
AtomicInteger count = new AtomicInteger();
return task -> {
Thread thread = new Thread(task, name + " " + count.incrementAndGet());
thread.setDaemon(true);
return thread;
};
}
static final class RequestError extends RuntimeException {
final int status;
RequestError(int status, String message) {
super(message);
this.status = status;
}
}
/** A request's query parameters; a missing or malformed one is a bad request. */
record Query(Map<String, String> values) {
static Query of(URI uri) {
Map<String, String> values = new HashMap<>();
String raw = uri.getRawQuery();
if (raw != null) {
for (String pair : raw.split("&")) {
int equals = pair.indexOf('=');
String name = equals < 0 ? pair : pair.substring(0, equals);
String value = equals < 0 ? "" : pair.substring(equals + 1);
values.put(decode(name), decode(value));
}
}
return new Query(values);
}
private static String decode(String text) {
return URLDecoder.decode(text, StandardCharsets.UTF_8);
}
String text(String name) {
String value = values.get(name);
if (value == null) {
throw new RequestError(STATUS_BAD_REQUEST, "Missing " + name);
}
return value;
}
double number(String name) {
try {
double value = Double.parseDouble(text(name));
if (!Double.isFinite(value)) {
throw new NumberFormatException();
}
return value;
} catch (NumberFormatException malformed) {
throw new RequestError(STATUS_BAD_REQUEST, name + " must be a number");
}
}
int whole(String name, int fallback) {
if (!values.containsKey(name)) {
return fallback;
}
try {
return Integer.parseInt(values.get(name));
} catch (NumberFormatException malformed) {
throw new RequestError(STATUS_BAD_REQUEST, name + " must be a whole number");
}
}
/** The parameters that start with {@code prefix}, by the rest of their names. */
Map<String, String> prefixed(String prefix) {
Map<String, String> found = new HashMap<>();
values.forEach((name, value) -> {
if (name.startsWith(prefix)) {
found.put(name.substring(prefix.length()), value);
}
});
return found;
}
long longNumber(String name) {
try {
return Long.parseLong(text(name));
} catch (NumberFormatException malformed) {
throw new RequestError(STATUS_BAD_REQUEST, name + " must be a whole number");
}
}
boolean has(String name) {
return values.containsKey(name);
}
boolean flag(String name) {
String value = values.get(name);
return "1".equals(value) || "true".equals(value);
}
}
private record ErrorBody(String error) {
}
private record MessageBody(String message) {
}
/** @param snapshot null while no pregeneration runs */
private record PregenStatus(boolean active, PregenRenderSnapshot snapshot) {
}
/** A view the studio lists beside the scene and pattern views. */
private record ModuleViewInfo(String id, String label, String description) {
}
/** The pack files that still name an entry. */
private record UsesBody(List<String> files) {
}
/** Where a deleted entry's file went. */
private record TrashedBody(String to) {
}
private record PickInspection(String detail, List<Object> sections) {
}
/** @param seed as text, as JavaScript numbers cannot hold every long */
private record WorldInfo(String world, String dimension, String dimensionName, String seed, int minY, int height,
int fluidHeight, int tileSize, boolean hasPlayers, boolean hydrology, List<ViewInfo> views) {
}
private record ViewInfo(String id, String label, String description, String group, String groupLabel) {
}
}
@@ -0,0 +1,111 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.spi.IrisLogging;
import com.google.gson.Gson;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
/**
* The open bridges, one per world. Each is announced in a connection file under {@code ~/.iris/studio/bridges}, which
* a studio app on the same machine lists to connect without a pasted link; the file goes when the bridge closes.
*/
public final class StudioBridges {
private static final Path CONNECTION_FOLDER = Path.of(System.getProperty("user.home"), ".iris", "studio", "bridges");
private static final String OWNER_ONLY = "rw-------";
private static final Map<String, StudioBridge> OPEN = new ConcurrentHashMap<>();
private StudioBridges() {
}
/**
* The bridge to {@code worldName}, started when it has none yet.
*
* @param engines the world's engine now, or null while it has none
* @param openerId the player the studio's teleports move, or null for the console
*/
public static synchronized StudioBridge open(String worldName, Supplier<Engine> engines, UUID openerId) throws IOException {
StudioBridge open = OPEN.get(worldName);
if (open != null) {
return open;
}
StudioBridge bridge = StudioBridge.start(new StudioWorld(worldName, engines, openerId));
OPEN.put(worldName, bridge);
announce(bridge);
return bridge;
}
public static synchronized void closeAll() {
StudioWindow.closeAll();
for (StudioBridge bridge : OPEN.values()) {
bridge.close();
withdraw(bridge);
}
OPEN.clear();
}
private static void announce(StudioBridge bridge) {
try {
Files.createDirectories(CONNECTION_FOLDER);
Path file = connectionFile(bridge);
Connection connection = new Connection(bridge.worldName(), bridge.port(), bridge.token(), bridge.link(),
ProcessHandle.current().pid(), System.currentTimeMillis());
Files.deleteIfExists(file);
createReadableByOwnerOnly(file);
Files.writeString(file, new Gson().toJson(connection), StandardCharsets.UTF_8);
} catch (IOException error) {
IrisLogging.warn("Could not write the studio connection file: %s", error.getMessage());
}
}
// The file holds the token, so other users of the machine must not read it, not even before it is written.
private static void createReadableByOwnerOnly(Path file) throws IOException {
if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
Files.createFile(file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(OWNER_ONLY)));
return;
}
Files.createFile(file);
}
private static void withdraw(StudioBridge bridge) {
try {
Files.deleteIfExists(connectionFile(bridge));
} catch (IOException error) {
IrisLogging.debug("Could not remove the studio connection file: " + error.getMessage());
}
}
private static Path connectionFile(StudioBridge bridge) {
return CONNECTION_FOLDER.resolve(bridge.port() + ".json");
}
/** @param pid the server's process, so the studio can skip files a crashed server left */
private record Connection(String world, int port, String token, String link, long pid, long startedMillis) {
}
}
@@ -0,0 +1,280 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.studio.scene.EditableSceneView;
import art.arcane.iris.studio.scene.GraphNode;
import art.arcane.iris.studio.scene.JsonPath;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* Reads and edits the files of editable scene views' entries for the studio. Every edit is made on the text as it was
* read, named by its revision, and splices only the values it changes, so the rest of the file stays as written.
*/
final class StudioEditors {
// Only a studio world reloads its pack when a file changes; elsewhere an edit would show nothing until a restart.
private static final String LOCKED_OUTSIDE_STUDIO = "Open the pack in a studio world to edit it";
private static final String NOT_AN_OBJECT = "The file does not hold a JSON object";
private final StudioScenes scenes;
private final Engine engine;
// A studio world generates from a copy of the pack; edits go to the pack itself, which the world reloads from.
private final Path packFolder;
private final Path loadedFolder;
private final SceneFiles.DesktopTrash desktopTrash;
StudioEditors(StudioScenes scenes, Engine engine, SceneFiles.DesktopTrash desktopTrash) {
this.scenes = scenes;
this.engine = engine;
this.packFolder = engine.getPackSource().toAbsolutePath().normalize();
this.loadedFolder = engine.getData().getDataFolder().toPath().toAbsolutePath().normalize();
this.desktopTrash = desktopTrash;
}
/**
* The entry's file as it is now.
*
* @throws NoSuchElementException when there is no such view, or the entry has no file of its own
*/
EditorState read(String viewId, String key) throws IOException {
Path file = fileOf(viewId, key);
return stateOf(viewId, key, file, Files.readString(file, StandardCharsets.UTF_8));
}
/**
* Makes {@code edit} and saves the file.
*
* @param revision the {@link EditorState#revision()} the edit was made on
* @throws StaleEditException when the file changed since {@code revision}
* @throws EditsLockedException when the world is not a studio world
* @throws IllegalArgumentException naming why, when the edit does not fit the file
*/
EditorState edit(String viewId, String key, String revision, GraphEdit edit) throws IOException {
requireStudioWorld();
Path file = fileOf(viewId, key);
JsonSplicer splicer = new JsonSplicer(JsonText.parse(currentText(file, revision)));
String edited = splicer.apply(edit.splices(splicer));
JsonText.parse(edited);
return save(viewId, key, file, edited);
}
/**
* Replaces the whole file, as undoing and redoing do.
*
* @throws StaleEditException when the file changed since {@code revision}
* @throws EditsLockedException when the world is not a studio world
* @throws IllegalArgumentException when {@code text} is not JSON
*/
EditorState write(String viewId, String key, String revision, String text) throws IOException {
requireStudioWorld();
Path file = fileOf(viewId, key);
currentText(file, revision);
JsonText.parse(text);
return save(viewId, key, file, text);
}
/**
* Writes a new entry {@code key} of the view from its starter text. The entry shows once the pack has reloaded.
*
* @throws EditsLockedException when the world is not a studio world
* @throws IllegalArgumentException naming why, when {@code key} can't name a new entry
* @throws NoSuchElementException when there is no such view, or its entries can't be created
*/
void create(String viewId, String key) throws IOException {
requireStudioWorld();
files(viewId).create(key);
}
/**
* The files of the pack that still name entry {@code key}, which a removal would leave without it.
*
* @throws NoSuchElementException when there is no such view, or its entries can't be removed
*/
List<String> usesOf(String viewId, String key) throws IOException {
return files(viewId).usesOf(key);
}
/**
* Moves entry {@code key} to the trash and tells where it went.
*
* @throws EditsLockedException when the world is not a studio world
* @throws NoSuchElementException when there is no such view, or the entry has no file
*/
String delete(String viewId, String key) throws IOException {
requireStudioWorld();
return files(viewId).moveToTrash(key);
}
private SceneFiles files(String viewId) {
EditableSceneView.Creation creation = scenes.editableView(viewId).creation()
.orElseThrow(() -> new NoSuchElementException("The entries of " + viewId + " can't be created or removed"));
return new SceneFiles(packFolder, creation, desktopTrash);
}
private void requireStudioWorld() {
if (!engine.isStudio()) {
throw new EditsLockedException(LOCKED_OUTSIDE_STUDIO);
}
}
private String lockedReason() {
return engine.isStudio() ? null : LOCKED_OUTSIDE_STUDIO;
}
private static String currentText(Path file, String revision) throws IOException {
String text = Files.readString(file, StandardCharsets.UTF_8);
if (!revisionOf(text).equals(revision)) {
throw new StaleEditException();
}
return text;
}
// Written beside the file and moved over it, so the pack watcher never reads it half written.
private EditorState save(String viewId, String key, Path file, String text) throws IOException {
Path written = file.resolveSibling(file.getFileName() + SceneFiles.WRITING_SUFFIX);
Files.writeString(written, text, StandardCharsets.UTF_8);
Files.move(written, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
return stateOf(viewId, key, file, text);
}
private Path fileOf(String viewId, String key) {
Path loaded = scenes.editableView(viewId).fileOf(engine, key)
.orElseThrow(() -> new NoSuchElementException("Entry " + key + " has no file to edit"))
.toPath().toAbsolutePath().normalize();
if (!loaded.startsWith(loadedFolder)) {
throw new NoSuchElementException("Entry " + key + " has no file in the pack");
}
Path file = packFolder.resolve(loadedFolder.relativize(loaded));
if (!Files.isRegularFile(file)) {
throw new NoSuchElementException("Entry " + key + " has no file in the pack");
}
return file;
}
// A file that is no longer JSON, or that the view can't read as nodes, is still shown, with why.
private EditorState stateOf(String viewId, String key, Path file, String text) {
String fileName = packFolder.relativize(file).toString().replace('\\', '/');
String revision = revisionOf(text);
JsonText source;
try {
source = JsonText.parse(text);
} catch (IllegalArgumentException notJson) {
return EditorState.unreadable(fileName, revision, text, notJson.getMessage(), lockedReason());
}
if (!(source.toGson() instanceof JsonObject root)) {
return EditorState.unreadable(fileName, revision, text, NOT_AN_OBJECT, lockedReason());
}
List<GraphNode> graph;
try {
graph = scenes.editableView(viewId).graph(engine, key, root);
} catch (IllegalArgumentException refused) {
return EditorState.unreadable(fileName, revision, text, String.valueOf(refused.getMessage()), lockedReason());
}
Set<Class<?>> types = new LinkedHashSet<>();
List<NodeWire> roots = graph.stream().map(node -> NodeWire.of(node, types)).toList();
return new EditorState(fileName, revision, text, roots, null, lockedReason(), SettingsTypes.reachableFrom(types));
}
static String revisionOf(String text) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException missing) {
throw new IllegalStateException("The JVM has no SHA-256", missing);
}
}
/**
* An entry's file as the studio shows it.
*
* @param file where it is below the pack folder
* @param revision tells this text from any other, so an edit made on an older one is refused
* @param roots the file as nodes; null when it can't be read as nodes, and {@code problem} says why
* @param locked why the file can't be edited here; null when it can
* @param types the settings types the nodes show, by class name
*/
record EditorState(String file, String revision, String text, List<NodeWire> roots, String problem, String locked,
Map<String, SettingsTypes.TypeWire> types) {
static EditorState unreadable(String file, String revision, String text, String problem, String locked) {
return new EditorState(file, revision, text, null, problem, locked, Map.of());
}
}
/** A {@link GraphNode} as the studio reads it: paths as arrays of member names and indices, settings types by class name. */
record NodeWire(String kind, String title, List<Object> path, int partId, List<String> roles, List<SettingsWire> settings,
List<LinkWire> children, List<Object> childList, boolean movable, boolean duplicable, List<AdditionWire> additions) {
static NodeWire of(GraphNode node, Set<Class<?>> types) {
List<SettingsWire> settings = node.settings().stream().map(section -> {
types.add(section.type());
return new SettingsWire(section.title(), stepsOf(section.path()), section.type().getName(), List.copyOf(section.shownAsNodes()));
}).toList();
List<LinkWire> children = node.children().stream().map(link -> new LinkWire(link.wire(), of(link.node(), types))).toList();
GraphNode.Edits edits = node.edits();
List<AdditionWire> additions = edits.additions().stream()
.map(addition -> new AdditionWire(addition.label(), stepsOf(addition.list()), addition.literal()))
.toList();
return new NodeWire(node.kind(), node.title(), stepsOf(node.path()), node.part(), node.roles(), settings, children,
edits.childList().map(NodeWire::stepsOf).orElse(null), edits.movable(), node.path().isElement(), additions);
}
static List<Object> stepsOf(JsonPath path) {
return path.steps().stream().<Object>map(step -> switch (step) {
case JsonPath.Key(String name) -> name;
case JsonPath.Index(int position) -> position;
}).toList();
}
}
record SettingsWire(String title, List<Object> path, String type, List<String> shownAsNodes) {
}
record LinkWire(String wire, NodeWire node) {
}
record AdditionWire(String label, List<Object> list, String literal) {
}
/** The file changed since the text an edit was made on, such as in a text editor. */
static final class StaleEditException extends RuntimeException {
StaleEditException() {
super("The file changed elsewhere; it was read again");
}
}
/** Edits are refused where the world would not show them, naming why. */
static final class EditsLockedException extends RuntimeException {
EditsLockedException(String reason) {
super(reason);
}
}
}
@@ -0,0 +1,163 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.studio.view.GuiMarker;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Server-sent events to every connected studio: {@code players} when a player moves, {@code world} when the world's
* engine changes (a hotload), {@code usage} with the server's CPU and heap every second, and a comment now and then so
* a dead connection is noticed. A studio that stops
* reading is dropped.
*/
final class StudioEvents {
private static final byte[] KEEP_ALIVE = ": alive\n\n".getBytes(StandardCharsets.UTF_8);
static final long POLL_INTERVAL_MILLIS = 250L;
private static final long KEEP_ALIVE_INTERVAL_MILLIS = 10_000L;
private static final long USAGE_INTERVAL_MILLIS = 1_000L;
private final StudioWorld world;
private final Gson gson;
private final List<OutputStream> listeners = new CopyOnWriteArrayList<>();
/** Listeners not yet told the world's state. */
private final List<OutputStream> joining = new CopyOnWriteArrayList<>();
private final AtomicBoolean listenerJoined = new AtomicBoolean();
private final AtomicBoolean usageWanted = new AtomicBoolean();
private final AtomicBoolean hotloaded = new AtomicBoolean();
private List<GuiMarker> lastPlayers;
private Engine lastEngine;
private long lastSentMillis;
private long lastUsageMillis;
StudioEvents(StudioWorld world, Gson gson) {
this.world = world;
this.gson = gson;
}
void listen(OutputStream stream) {
listeners.add(stream);
joining.add(stream);
listenerJoined.set(true);
usageWanted.set(true);
}
/** The pack was hotloaded; the engine may be the same, its streams are not. */
void hotloaded() {
hotloaded.set(true);
}
/** Sends what changed since the last poll; called every {@link #POLL_INTERVAL_MILLIS} from one thread. */
void poll() {
if (listeners.isEmpty()) {
return;
}
StudioWorld.Session session = world.session();
Engine engine = session == null ? null : session.engine();
List<OutputStream> joined = List.copyOf(joining);
if (engine != lastEngine || hotloaded.getAndSet(false)) {
lastEngine = engine;
send("world", new WorldChange(engine != null));
} else {
greet(joined, engine != null);
}
joining.removeAll(joined);
List<GuiMarker> players = session == null || session.overlay() == null ? List.of() : session.overlay().players();
if (listenerJoined.getAndSet(false) || !Objects.equals(players, lastPlayers)) {
lastPlayers = players;
send("players", players);
}
long now = System.currentTimeMillis();
if (usageWanted.getAndSet(false) || now - lastUsageMillis >= USAGE_INTERVAL_MILLIS) {
lastUsageMillis = now;
send("usage", ServerUsage.sample());
}
if (now - lastSentMillis > KEEP_ALIVE_INTERVAL_MILLIS) {
sendToAll(KEEP_ALIVE);
}
}
void closeAll() {
for (OutputStream listener : listeners) {
closeQuietly(listener);
}
listeners.clear();
joining.clear();
}
/**
* Tells studios that just connected what state the world is in, them alone. A studio takes its first world event as
* the state it connected to, so without one of its own it would take the next hotload for it and not redraw.
*/
private void greet(List<OutputStream> joined, boolean running) {
if (joined.isEmpty()) {
return;
}
byte[] message = eventOf("world", new WorldChange(running));
for (OutputStream listener : joined) {
sendTo(listener, message);
}
}
private void send(String event, Object data) {
sendToAll(eventOf(event, data));
}
private byte[] eventOf(String event, Object data) {
return ("event: " + event + "\ndata: " + gson.toJson(data) + "\n\n").getBytes(StandardCharsets.UTF_8);
}
private void sendToAll(byte[] message) {
lastSentMillis = System.currentTimeMillis();
for (OutputStream listener : listeners) {
sendTo(listener, message);
}
}
private void sendTo(OutputStream listener, byte[] message) {
try {
listener.write(message);
listener.flush();
} catch (IOException gone) {
listeners.remove(listener);
joining.remove(listener);
closeQuietly(listener);
}
}
private static void closeQuietly(OutputStream stream) {
try {
stream.close();
} catch (IOException ignored) {
}
}
/** @param running whether the world has an engine again; the studio redraws either way */
private record WorldChange(boolean running) {
}
}
@@ -0,0 +1,47 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.localization.RuntimeUiMessages;
import art.arcane.volmlib.util.localization.TextKey;
/** How a request to show the studio window ended; every outcome but {@link #OPENED} leaves the bridge link as the only way in. */
public enum StudioLaunch {
OPENED(null),
DOWNLOAD_OFF(RuntimeUiMessages.STUDIO_APP_DOWNLOAD_OFF),
NO_DISPLAY(RuntimeUiMessages.STUDIO_APP_NO_DISPLAY),
DOWNLOADING(RuntimeUiMessages.STUDIO_APP_DOWNLOADING),
UNAVAILABLE(RuntimeUiMessages.STUDIO_APP_UNAVAILABLE),
NOT_BUILT(RuntimeUiMessages.STUDIO_APP_NOT_BUILT),
FAILED_TO_START(RuntimeUiMessages.STUDIO_APP_FAILED_TO_START);
private final TextKey failureMessage;
StudioLaunch(TextKey failureMessage) {
this.failureMessage = failureMessage;
}
public boolean opened() {
return this == OPENED;
}
public TextKey failureMessage() {
return failureMessage;
}
}
@@ -0,0 +1,78 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.studio.scene.EditableSceneView;
import art.arcane.iris.studio.scene.SceneBlocks;
import art.arcane.iris.studio.scene.SceneSizes;
import art.arcane.iris.studio.scene.SceneView;
import art.arcane.iris.studio.scene.SceneViews;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.List;
import java.util.NoSuchElementException;
/** The scene views the studio lists: every feature's, then the studio's own. */
final class StudioScenes {
private static final List<SceneView> STUDIO_VIEWS = List.of(new PackObjectsSceneView(), new ProceduralObjectsSceneView());
private final List<SceneView> views = SceneViews.withStudioViews(STUDIO_VIEWS);
List<SceneViewInfo> infos() {
return views.stream().map(SceneViewInfo::of).toList();
}
/** @throws NoSuchElementException when no view has {@code id} */
SceneView view(String id) {
return views.stream().filter(view -> view.id().equals(id)).findFirst()
.orElseThrow(() -> new NoSuchElementException("No scene view " + id));
}
/** @throws NoSuchElementException when no view has {@code id}, or its entries can't be edited */
EditableSceneView editableView(String id) {
if (view(id) instanceof EditableSceneView editable) {
return editable;
}
throw new NoSuchElementException("The entries of " + id + " can't be edited");
}
/** The part of each block of {@code scene}, in the order it encodes them, as little endian 32-bit integers. */
static byte[] encodeParts(SceneBlocks scene) {
int[] parts = scene.parts();
ByteBuffer buffer = ByteBuffer.allocate(parts.length * Integer.BYTES).order(ByteOrder.LITTLE_ENDIAN);
buffer.asIntBuffer().put(parts);
return buffer.array();
}
/**
* A view as the studio lists it: {@code editable} when its entries are edited as nodes, {@code creatable} when they
* can also be created and deleted, {@code baked} when their bake can be timed, {@code parts} when a block can be
* traced to the part that placed it, and {@code form} when each entry has a settings form.
*/
record SceneViewInfo(String id, String label, String description, boolean editable, boolean creatable, boolean baked,
boolean parts, SceneSizes sizes, boolean form) {
static SceneViewInfo of(SceneView view) {
boolean editable = view instanceof EditableSceneView;
boolean creatable = view instanceof EditableSceneView editableView && editableView.creation().isPresent();
return new SceneViewInfo(view.id(), view.label(), view.description(), editable, creatable, view.isBaked(),
view.tracesParts(), view.sizes(), view.hasForm());
}
}
}
@@ -0,0 +1,61 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.ResourceLoader;
import art.arcane.iris.spi.IrisPlatforms;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.TreeSet;
/** What a setting naming a block or a resource of the pack may be typed as, for the studio to suggest while it is typed. */
final class StudioSuggestions {
private StudioSuggestions() {
}
/**
* The entries of the registry {@code referenceName} names, sorted; blocks are the pack's own and the platform's.
*
* @throws NoSuchElementException when there is no such reference
*/
static List<String> ofReference(IrisData data, String referenceName) {
if (!SettingsTypes.BLOCK_REFERENCE.equals(referenceName)) {
throw new NoSuchElementException("No reference named " + referenceName);
}
TreeSet<String> blocks = new TreeSet<>(Arrays.asList(data.getBlockLoader().getPossibleKeys()));
blocks.addAll(IrisPlatforms.get().registries().blockTypeKeys());
return List.copyOf(blocks);
}
/**
* The keys of the pack's resources in the folder {@code folder}, sorted.
*
* @throws NoSuchElementException when the pack has no resources of that folder
*/
static List<String> ofResource(IrisData data, String folder) {
ResourceLoader<?> loader = data.getLoaders().values().stream()
.filter(candidate -> folder.equals(candidate.getFolderName()))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("The pack has no " + folder));
return Arrays.stream(loader.getPossibleKeys()).sorted().distinct().toList();
}
}
@@ -0,0 +1,78 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import com.google.gson.Gson;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* A square of the map as the Iris Studio app reads it, little endian:
* <pre>
* u32 header length | header, UTF-8 JSON | padding to 4 bytes
* i16 subjects[grid²] | padding to 4 | i16 regions[grid²] | padding to 4 | f32 heights[grid²], when the header says so
* </pre>
* The grids hold {@code (size + 2)²} cells row by row: the tile's pixels inside a ring of the neighbouring tiles' edge
* pixels, so edges and slopes continue across tiles. Subjects and regions index the header's labels.
*
* @param subjectKind BIOME, REGION or WATER: what the subjects are
* @param heights null when the tile carries none
*/
record StudioTile(int size, double blocksPerPixel, String subjectKind, List<Label> labels, short[] subjects, short[] regions,
float[] heights) {
static final short NO_LABEL = -1;
private static final int ALIGNMENT_BYTES = 4;
/** @param color 0xRRGGBB */
record Label(String kind, String key, String name, int color) {
}
byte[] encode(Gson gson) {
byte[] header = gson.toJson(new Header(size, blocksPerPixel, subjectKind, labels, heights != null, false))
.getBytes(StandardCharsets.UTF_8);
int cells = (size + 2) * (size + 2);
int length = aligned(Integer.BYTES + header.length) + aligned(cells * Short.BYTES) * 2
+ (heights == null ? 0 : cells * Float.BYTES);
ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(header.length).put(header);
buffer.position(aligned(buffer.position()));
putShorts(buffer, subjects);
putShorts(buffer, regions);
if (heights != null) {
buffer.asFloatBuffer().put(heights);
}
return buffer.array();
}
private static void putShorts(ByteBuffer buffer, short[] grid) {
buffer.asShortBuffer().put(grid);
buffer.position(aligned(buffer.position() + grid.length * Short.BYTES));
}
private static int aligned(int bytes) {
return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES;
}
private record Header(int size, double blocksPerPixel, String subjectKind, List<Label> labels, boolean heights,
boolean pickNoise) {
}
}
@@ -0,0 +1,177 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.studio.map.RiverKey;
import art.arcane.iris.studio.map.components.MapLabels;
import art.arcane.iris.studio.map.components.MapLayer;
import art.arcane.iris.studio.map.components.MapTile;
import art.arcane.iris.studio.map.components.MapTileRenderer;
import art.arcane.iris.studio.map.components.PickDisplay;
import art.arcane.iris.studio.map.components.TileType;
import art.arcane.iris.studio.render.IrisRenderer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.function.BooleanSupplier;
/** Draws the studio app's map views with the renderer the Swing map uses, one tile at a time. */
final class StudioTiles {
private static final int RGB = 0xFFFFFF;
private static final short DRY = 0;
private static final String DRY_KEY = "dry";
private static final int DRY_COLOR = 0x1C1F26;
private static final int MAX_FINISH_ATTEMPTS = 200;
private static final long FINISH_WAIT_MILLIS = 50L;
private final Engine engine;
private final MapTileRenderer renderer;
private final IrisRenderer waterRenderer;
private final List<StudioTile.Label> waterLabels;
private final Map<Integer, Short> waterLabelByColor;
StudioTiles(Engine engine, MapTileRenderer renderer) {
this.engine = engine;
this.renderer = renderer;
this.waterRenderer = new IrisRenderer(engine);
List<StudioTile.Label> labels = new ArrayList<>();
labels.add(new StudioTile.Label("WATER", DRY_KEY, "No water", DRY_COLOR));
Map<Integer, Short> byColor = new HashMap<>();
for (RiverKey.Row row : RiverKey.rows()) {
byColor.put(row.color() & RGB, (short) labels.size());
labels.add(new StudioTile.Label("WATER", row.label(), row.label(), row.color() & RGB));
}
this.waterLabels = List.copyOf(labels);
this.waterLabelByColor = Map.copyOf(byColor);
}
boolean hydrologyEnabled() {
var runtime = engine.getComplex().getHydrologyRuntime();
return runtime != null && runtime.enabled();
}
StudioTile biomesOrRegions(String view, String previewRegion, double startX, double startZ, double blocksPerPixel, int size,
boolean withHeights, BooleanSupplier cancelled) {
MapLayer layer = layerOf(view, previewRegion);
boolean heightsWanted = withHeights || layer.type() == TileType.HEIGHT;
MapTileRenderer.TileRender render = renderer.prepareTile(startX, startZ, blocksPerPixel, size, layer, heightsWanted);
MapTile tile = render.render(cancelled);
for (int attempt = 0; !render.complete() && attempt < MAX_FINISH_ATTEMPTS; attempt++) {
pause(cancelled);
tile = render.render(cancelled);
}
return wire(tile, blocksPerPixel, heightsWanted && tile.hasHeights(), layer.type());
}
StudioTile rivers(double startX, double startZ, double blocksPerPixel, int size, BooleanSupplier cancelled) {
int grid = size + 2;
short[] subjects = new short[grid * grid];
Arrays.fill(subjects, DRY);
if (hydrologyEnabled()) {
IrisRenderer.WaterTile water = waterRenderer.prepareStudioWater(startX - blocksPerPixel, startZ - blocksPerPixel, blocksPerPixel, grid);
int[] colors = water.render(null, false, cancelled);
for (int attempt = 0; !water.complete() && attempt < MAX_FINISH_ATTEMPTS; attempt++) {
pause(cancelled);
colors = water.render(null, false, cancelled);
}
for (int cell = 0; cell < colors.length; cell++) {
subjects[cell] = waterLabelByColor.getOrDefault(colors[cell] & RGB, DRY);
}
}
return new StudioTile(size, blocksPerPixel, "WATER", waterLabels, subjects, subjects, null);
}
private static MapLayer layerOf(String view, String previewRegion) {
return switch (view) {
case "regions" -> previewRegion == null ? MapLayer.regions(PickDisplay.PICKS) : MapLayer.regionPreview(previewRegion, PickDisplay.PICKS);
case "height" -> MapLayer.of(TileType.HEIGHT);
case "land-biomes" -> MapLayer.of(TileType.BIOME_LAND);
case "sea-biomes" -> MapLayer.of(TileType.BIOME_SEA);
case "cave-biomes" -> MapLayer.of(TileType.CAVE_LAND);
case "object-load" -> MapLayer.of(TileType.OBJECT_LOAD);
case "decorator-load" -> MapLayer.of(TileType.DECORATOR_LOAD);
case "layer-load" -> MapLayer.of(TileType.LAYER_LOAD);
default -> MapLayer.biomes(PickDisplay.PICKS, false);
};
}
private StudioTile wire(MapTile tile, double blocksPerPixel, boolean withHeights, TileType legendType) {
int size = tile.size();
int grid = size + 2;
Labelling labelling = new Labelling();
short[] subjects = new short[grid * grid];
short[] regions = new short[grid * grid];
float[] heights = withHeights ? new float[grid * grid] : null;
for (int z = -1; z <= size; z++) {
for (int x = -1; x <= size; x++) {
int cell = (z + 1) * grid + x + 1;
subjects[cell] = labelling.indexOf(tile.labels(), tile.subjectAt(x, z));
regions[cell] = labelling.indexOf(tile.labels(), tile.regionAt(x, z));
if (heights != null) {
heights[cell] = (float) tile.heightAt(x, z);
}
}
}
List<StudioTile.Label> labels = labelling.labels(renderer, legendType);
return new StudioTile(size, blocksPerPixel, tile.subjectKind().name(), labels, subjects, regions, heights);
}
private static void pause(BooleanSupplier cancelled) {
if (cancelled.getAsBoolean()) {
throw new CancellationException("Tile dropped");
}
try {
Thread.sleep(FINISH_WAIT_MILLIS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new CancellationException("Tile interrupted");
}
}
/** Renumbers the labels a tile uses from 0, so its header lists only those. */
private static final class Labelling {
private final Map<Short, Short> indexByLabelId = new HashMap<>();
private final List<Short> usedLabelIds = new ArrayList<>();
short indexOf(MapLabels labels, short labelId) {
if (labelId == MapLabels.NONE || labels.label(labelId) == null) {
return StudioTile.NO_LABEL;
}
return indexByLabelId.computeIfAbsent(labelId, id -> {
usedLabelIds.add(id);
return (short) (usedLabelIds.size() - 1);
});
}
List<StudioTile.Label> labels(MapTileRenderer renderer, TileType legendType) {
List<StudioTile.Label> labels = new ArrayList<>();
for (short id : usedLabelIds) {
MapLabels.Label label = renderer.labels().label(id);
labels.add(new StudioTile.Label(label.kind().name(), label.key(), label.name(),
renderer.legendColor(label, legendType) & RGB));
}
return labels;
}
}
}
@@ -0,0 +1,111 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.studio.app.StudioAppInstall;
import art.arcane.iris.studio.app.StudioAppInstaller;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* Opens the Iris Studio window on a bridge, from the studio checkout the settings name or else from the app the
* server downloaded at startup. The app keeps one window:
* a second start hands its link to the open window and exits. Windows the server started close when it stops, as
* their bridges go with it.
*/
public final class StudioWindow {
private static final Path LOG_FILE = Path.of(System.getProperty("user.home"), ".iris", "studio", "window.log");
private static final String DEFAULT_ELECTRON = "electron";
private static final String BUILT_MAIN = "out/main/index.js";
/** Set by terminals that are Electron apps themselves; left in, Electron would start as plain Node with no window. */
private static final String RUN_AS_PLAIN_NODE = "ELECTRON_RUN_AS_NODE";
private static final List<Process> STARTED = new ArrayList<>();
private StudioWindow() {
}
public static synchronized StudioLaunch show(StudioBridge bridge) {
IrisSettings.IrisSettingsStudio settings = IrisSettings.get().getStudio();
String checkout = settings.getStudioApp();
if (checkout != null && !checkout.isBlank()) {
return showCheckout(Path.of(checkout), electronBinary(settings), bridge.link());
}
return showDownloaded(bridge.link());
}
private static StudioLaunch showCheckout(Path app, String electron, String link) {
if (!Files.isRegularFile(app.resolve(BUILT_MAIN))) {
IrisLogging.warn("Iris Studio is not built in %s; run npm run build there.", app);
return StudioLaunch.NOT_BUILT;
}
return launch(electron, app, link);
}
private static StudioLaunch showDownloaded(String link) {
return switch (StudioAppInstaller.installInBackground()) {
case READY -> {
StudioAppInstall install = StudioAppInstaller.installed();
yield launch(install.electron().toString(), install.app(), link);
}
case NOT_STARTED, DOWNLOADING -> StudioLaunch.DOWNLOADING;
case DOWNLOAD_OFF -> StudioLaunch.DOWNLOAD_OFF;
case NO_DISPLAY -> StudioLaunch.NO_DISPLAY;
case UNAVAILABLE -> {
IrisLogging.warn("Studio app unavailable: %s", StudioAppInstaller.unavailableReason());
yield StudioLaunch.UNAVAILABLE;
}
};
}
private static StudioLaunch launch(String electron, Path app, String link) {
try {
STARTED.removeIf(process -> !process.isAlive());
STARTED.add(start(electron, app, link));
return StudioLaunch.OPENED;
} catch (IOException error) {
IrisLogging.warn("Could not open Iris Studio: %s", error.getMessage());
return StudioLaunch.FAILED_TO_START;
}
}
public static synchronized void closeAll() {
STARTED.forEach(Process::destroy);
STARTED.clear();
}
private static Process start(String electron, Path app, String link) throws IOException {
Files.createDirectories(LOG_FILE.getParent());
ProcessBuilder builder = new ProcessBuilder(electron, app.toString(), link)
.redirectErrorStream(true)
.redirectOutput(ProcessBuilder.Redirect.to(LOG_FILE.toFile()));
builder.environment().remove(RUN_AS_PLAIN_NODE);
return builder.start();
}
private static String electronBinary(IrisSettings.IrisSettingsStudio settings) {
String electron = settings.getElectron();
return electron == null || electron.isBlank() ? DEFAULT_ELECTRON : electron;
}
}
@@ -0,0 +1,73 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.bridge;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.studio.map.components.MapTileRenderer;
import art.arcane.iris.studio.view.GuiHost;
import art.arcane.iris.studio.view.GuiOverlay;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Supplier;
/**
* The world a bridge shows. Its engine is asked for again whenever the one in use closes, as a hotload or a restart of
* the world does, so a bridge outlives them.
*/
final class StudioWorld {
private final String name;
private final Supplier<Engine> engines;
private final UUID openerId;
private Session session;
/**
* @param engines the world's engine now; null while it has none
* @param openerId the player the studio teleports, or null when the console opened it
*/
StudioWorld(String name, Supplier<Engine> engines, UUID openerId) {
this.name = Objects.requireNonNull(name, "name");
this.engines = Objects.requireNonNull(engines, "engines");
this.openerId = openerId;
}
String name() {
return name;
}
/** The world's engine and what the bridge draws it with; null while the world has no running engine. */
synchronized Session session() {
if (session != null && isRunning(session.engine())) {
return session;
}
Engine engine = engines.get();
session = isRunning(engine)
? new Session(engine, new StudioTiles(engine, new MapTileRenderer(engine)), GuiHost.get().overlayFor(engine, openerId))
: null;
return session;
}
private static boolean isRunning(Engine engine) {
return engine != null && !engine.isClosed() && !engine.isClosing() && engine.getComplex() != null;
}
/** @param overlay the server's players and teleports; null on a platform without one */
record Session(Engine engine, StudioTiles tiles, GuiOverlay overlay) {
}
}
@@ -0,0 +1,229 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.imagemap;
import art.arcane.iris.generation.image.CompiledIrisImageMap;
import art.arcane.iris.generation.image.IrisImageMap;
import art.arcane.iris.generation.image.IrisImageMapOrigin;
import art.arcane.iris.generation.image.IrisImageMapRotation;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.studio.workspace.ImageMapStudioExporter;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
/** The pack's image-map presets as the studio lists, describes and previews them over the world area they cover. */
public final class ImageMapPreviews {
private static final int BACKGROUND_COLOR = 0x252936;
private static final int MAP_ERROR_COLOR = 0xFF3DA8;
private static final int SMALLEST_PREVIEW_PIXELS = 64;
private static final int LARGEST_PREVIEW_PIXELS = 2048;
private ImageMapPreviews() {
}
public record Entry(String key, String name, String group, int variants) {
}
/** @param bounds the world area the map covers: minimum X, minimum Z, maximum X, maximum Z */
public record Details(String key, String type, String source, int width, int height, double blocksPerPixel, double[] bounds,
List<String> facts) {
}
public static List<Entry> entries(Engine engine) {
String[] keys = engine.getData().getImageMapLoader().getPossibleKeys();
if (keys == null) {
return List.of();
}
return Arrays.stream(keys).sorted().map(key -> new Entry(key, key.substring(key.lastIndexOf('/') + 1), folderOf(key), 1)).toList();
}
public static Details details(Engine engine, String key) throws IOException {
Loaded loaded = load(engine, key);
IrisImageMap definition = loaded.definition();
List<String> facts = new ArrayList<>();
facts.add("Source " + definition.getSource() + ".png, " + loaded.compiled().getSourceWidth() + " × " + loaded.compiled().getSourceHeight() + " pixels");
facts.add(definition.getBlocksPerPixel() + " blocks per pixel");
if (definition.getType().name().endsWith("HEIGHT")) {
facts.add("Heights " + definition.getMinimumHeight() + " to " + definition.getMaximumHeight());
}
if (loaded.compiled().getClippedPixelCount() > 0) {
facts.add(loaded.compiled().getClippedPixelCount() + " pixels clipped to the height range");
}
if (loaded.compiled().getUnknownColorPixelCount() > 0) {
facts.add(loaded.compiled().getUnknownColorPixelCount() + " pixels of a colour the legend does not name");
}
return new Details(key, readable(definition.getType().name()), definition.getSource(), loaded.compiled().getSourceWidth(),
loaded.compiled().getSourceHeight(), definition.getBlocksPerPixel(), worldBounds(loaded), List.copyOf(facts));
}
/** A PNG of the world area the map covers, {@code pixels} across its longer side. */
public static byte[] preview(Engine engine, String key, int pixels) throws IOException {
if (pixels < SMALLEST_PREVIEW_PIXELS || pixels > LARGEST_PREVIEW_PIXELS) {
throw new IllegalArgumentException("A preview is " + SMALLEST_PREVIEW_PIXELS + " to " + LARGEST_PREVIEW_PIXELS + " pixels");
}
Loaded loaded = load(engine, key);
double[] bounds = worldBounds(loaded);
double spanX = bounds[2] - bounds[0];
double spanZ = bounds[3] - bounds[1];
double blocksPerPixel = Math.max(spanX, spanZ) / pixels;
int width = Math.max(1, (int) Math.round(spanX / blocksPerPixel));
int height = Math.max(1, (int) Math.round(spanZ / blocksPerPixel));
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int row = 0; row < height; row++) {
for (int column = 0; column < width; column++) {
image.setRGB(column, row, colorAt(loaded, bounds[0] + column * blocksPerPixel, bounds[1] + row * blocksPerPixel));
}
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ImageIO.write(image, "png", bytes);
return bytes.toByteArray();
}
private static int colorAt(Loaded loaded, double worldX, double worldZ) {
CompiledIrisImageMap compiled = loaded.compiled();
if (!compiled.containsWorld(worldX, worldZ)) {
return BACKGROUND_COLOR;
}
try {
return switch (loaded.definition().getType()) {
case GRAYSCALE_HEIGHT, RGB_HEIGHT -> heightColor(compiled.sampleHeight(worldX, worldZ),
loaded.definition().getMinimumHeight(), loaded.definition().getMaximumHeight());
case COLOR_MAP -> targetColor(compiled.sampleTarget(worldX, worldZ));
case BINARY_MASK, GRAYSCALE_MASK, ALPHA_MASK -> grayscale(compiled.sampleNormalized(worldX, worldZ));
};
} catch (RuntimeException unsampleable) {
return MAP_ERROR_COLOR;
}
}
private static Loaded load(Engine engine, String key) throws IOException {
IrisData data = engine.getData();
IrisImageMap loaded = data.getImageMapLoader().load(key);
if (loaded == null) {
throw new NoSuchElementException("No image map " + key);
}
IrisImageMap definition = data.getGson().fromJson(data.getGson().toJson(loaded), IrisImageMap.class);
File source = data.getImageLoader().findFile(definition.getSource());
if (source == null || !source.isFile()) {
throw new NoSuchElementException("The source PNG " + definition.getSource() + " is missing");
}
CompiledIrisImageMap compiled = ImageMapStudioExporter.preview(source.toPath(), definition).compiled();
return new Loaded(definition, compiled);
}
private static double[] worldBounds(Loaded loaded) {
double[][] corners = {
sourceToWorld(loaded.definition(), 0, 0),
sourceToWorld(loaded.definition(), loaded.compiled().getSourceWidth(), 0),
sourceToWorld(loaded.definition(), loaded.compiled().getSourceWidth(), loaded.compiled().getSourceHeight()),
sourceToWorld(loaded.definition(), 0, loaded.compiled().getSourceHeight())
};
double[] bounds = {Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE};
for (double[] corner : corners) {
bounds[0] = Math.min(bounds[0], corner[0]);
bounds[1] = Math.min(bounds[1], corner[1]);
bounds[2] = Math.max(bounds[2], corner[0]);
bounds[3] = Math.max(bounds[3], corner[1]);
}
return bounds;
}
private static double[] sourceToWorld(IrisImageMap definition, double sourceX, double sourceZ) {
IrisImageMapOrigin origin = definition.getOrigin();
IrisImageMapOrigin sourceOrigin = definition.getSourceOrigin();
double x = sourceX - sourceOrigin.getX();
double z = sourceZ - sourceOrigin.getZ();
if (definition.isMirrorX()) {
x = -x;
}
if (definition.isMirrorZ()) {
z = -z;
}
double[] rotated = rotated(x, z, definition.getRotation());
return new double[]{origin.getX() + rotated[0] * definition.getBlocksPerPixel(), origin.getZ() + rotated[1] * definition.getBlocksPerPixel()};
}
private static double[] rotated(double x, double z, IrisImageMapRotation rotation) {
return switch (rotation) {
case DEG_0 -> new double[]{x, z};
case DEG_90 -> new double[]{-z, x};
case DEG_180 -> new double[]{-x, -z};
case DEG_270 -> new double[]{z, -x};
};
}
private static int targetColor(String target) {
if (target == null) {
return BACKGROUND_COLOR;
}
int hash = target.hashCode();
int red = 72 + Math.floorMod(hash, 152);
int green = 72 + Math.floorMod(hash >>> 8, 152);
int blue = 72 + Math.floorMod(hash >>> 16, 152);
return (red << 16) | (green << 8) | blue;
}
private static int heightColor(double height, double minimum, double maximum) {
double range = maximum - minimum;
double normalized = range == 0D ? 0.5D : Math.max(0D, Math.min(1D, (height - minimum) / range));
double red;
double green;
double blue;
if (normalized < 0.5D) {
double factor = normalized * 2D;
red = 38D + (45D * factor);
green = 77D + (111D * factor);
blue = 132D - (42D * factor);
} else {
double factor = (normalized - 0.5D) * 2D;
red = 83D + (169D * factor);
green = 188D + (58D * factor);
blue = 90D + (150D * factor);
}
return ((int) red << 16) | ((int) green << 8) | (int) blue;
}
private static int grayscale(double normalized) {
int level = (int) Math.round(Math.max(0D, Math.min(1D, normalized)) * 255D);
return (level << 16) | (level << 8) | level;
}
private static String folderOf(String key) {
int slash = key.lastIndexOf('/');
return slash < 0 ? "" : key.substring(0, slash);
}
private static String readable(String constantName) {
String lower = constantName.toLowerCase(Locale.ROOT).replace('_', ' ');
return Character.toUpperCase(lower.charAt(0)) + lower.substring(1);
}
private record Loaded(IrisImageMap definition, CompiledIrisImageMap compiled) {
}
}
@@ -1,154 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import com.formdev.flatlaf.extras.FlatSVGIcon;
import javax.swing.JComponent;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
/**
* IntelliJ's profiler gauge, how heavy the measured bake is, a meter and the time it took, all in the weight's colour.
*/
final class BakeMeter extends JComponent {
private static final long serialVersionUID = 4120925066373218716L;
private static final String PROFILER_ICON = "iris/icons/profiler.svg";
private static final String TIMING_LABEL = "Timing";
private static final String WIDEST_TIME = "999 ms";
private static final int ICON_SIZE = 16;
private static final int GAP = 6;
private static final int BAR_HEIGHT = 4;
private static final int HEIGHT = 20;
private final FlatSVGIcon icon = new FlatSVGIcon(PROFILER_ICON, ICON_SIZE, ICON_SIZE, BakeMeter.class.getClassLoader());
private BakeTiming timing;
private boolean timingUnderWay;
BakeMeter() {
icon.setColorFilter(new FlatSVGIcon.ColorFilter(drawn -> color()));
}
void showTiming() {
timing = null;
timingUnderWay = true;
setToolTipText("Baking every variant five times over");
repaint();
}
void show(BakeTiming measured) {
timing = measured;
timingUnderWay = false;
setToolTipText(measured.explain());
repaint();
}
void clear() {
timing = null;
timingUnderWay = false;
setToolTipText(null);
repaint();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(0, StudioTheme.scale(HEIGHT));
}
@Override
protected void paintComponent(Graphics graphics) {
Graphics2D canvas = (Graphics2D) graphics.create();
try {
canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
icon.paintIcon(this, canvas, 0, (getHeight() - icon.getIconHeight()) / 2);
int labelX = icon.getIconWidth() + StudioTheme.scale(GAP);
int barX = drawLabel(canvas, labelX) + StudioTheme.scale(GAP);
int timeX = getWidth() - timeWidth(canvas);
drawBar(canvas, barX, timeX - StudioTheme.scale(GAP) - barX);
drawTime(canvas, timeX);
} finally {
canvas.dispose();
}
}
private Color color() {
return timing == null ? StudioTheme.MUTED_TEXT : weight().color();
}
private BakeWeight weight() {
return BakeWeight.of(timing.totalMillis());
}
// Returns where the label ends.
private int drawLabel(Graphics2D canvas, int x) {
canvas.setFont(StudioTheme.boldFont());
FontMetrics metrics = canvas.getFontMetrics();
canvas.setColor(color());
canvas.drawString(labelText(), x, baseline(metrics));
int widestLabelWidth = metrics.stringWidth(TIMING_LABEL);
for (BakeWeight each : BakeWeight.values()) {
widestLabelWidth = Math.max(widestLabelWidth, metrics.stringWidth(each.label()));
}
return x + widestLabelWidth;
}
private String labelText() {
if (timing != null) {
return weight().label();
}
return timingUnderWay ? TIMING_LABEL : "—";
}
private void drawBar(Graphics2D canvas, int x, int width) {
int barHeight = StudioTheme.scale(BAR_HEIGHT);
int y = (getHeight() - barHeight) / 2;
canvas.setColor(StudioTheme.HOVER_BACKGROUND);
canvas.fillRoundRect(x, y, width, barHeight, barHeight, barHeight);
if (timing == null) {
return;
}
int filledWidth = (int) Math.round(width * BakeWeight.meterFill(timing.totalMillis()));
canvas.setColor(color());
canvas.fillRoundRect(x, y, Math.max(barHeight, filledWidth), barHeight, barHeight, barHeight);
}
private int timeWidth(Graphics2D canvas) {
return canvas.getFontMetrics(StudioTheme.smallFont()).stringWidth(WIDEST_TIME);
}
private void drawTime(Graphics2D canvas, int x) {
if (timing == null) {
return;
}
canvas.setFont(StudioTheme.smallFont());
FontMetrics metrics = canvas.getFontMetrics();
String time = BakeTiming.formatMillis(timing.totalMillis());
canvas.setColor(StudioTheme.SECONDARY_TEXT);
canvas.drawString(time, x + timeWidth(canvas) - metrics.stringWidth(time), baseline(metrics));
}
private int baseline(FontMetrics metrics) {
return (getHeight() + metrics.getAscent() - metrics.getDescent()) / 2;
}
}
@@ -21,5 +21,5 @@ package art.arcane.iris.studio.map;
/**
* How long one bake of a procedural object's variants took.
*/
record BakeRun(long totalNanos, int variantCount) {
public record BakeRun(long totalNanos, int variantCount) {
}
@@ -1,71 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
/**
* A procedural object's variants baked five times over, keeping the median run. The first run is slow while the JIT
* compiles the baker, and the garbage collector or chunk generation can slow any other, so neither ends up in the middle.
*/
record BakeTiming(BakeRun median) {
private static final int RUN_COUNT = 5;
private static final double NANOS_PER_MILLI = 1_000_000D;
/** Null when {@code bake} finds nothing to bake, or once the timing is no longer wanted. */
static BakeTiming measure(Supplier<BakeRun> bake, BooleanSupplier stillWanted) {
List<BakeRun> runs = new ArrayList<>();
for (int run = 0; run < RUN_COUNT; run++) {
if (!stillWanted.getAsBoolean()) {
return null;
}
BakeRun measured = bake.get();
if (measured == null) {
return null;
}
runs.add(measured);
}
runs.sort(Comparator.comparingLong(BakeRun::totalNanos));
return new BakeTiming(runs.get(runs.size() / 2));
}
double totalMillis() {
return median.totalNanos() / NANOS_PER_MILLI;
}
/** How long the bake took and when world generation pays for it. */
String explain() {
String variants = median.variantCount() == 1 ? "1 variant" : median.variantCount() + " variants";
return "<html>" + variants + " in " + formatMillis(totalMillis()) + " · median of " + RUN_COUNT + " runs<br>"
+ "Paid once per pack load, by the first chunk placing it<br>"
+ BakeWeight.scale() + "</html>";
}
static String formatMillis(double millis) {
if (millis >= 1000D) {
return String.format(Locale.ROOT, "%.1f s", millis / 1000D);
}
return String.format(Locale.ROOT, millis < 10D ? "%.1f ms" : "%.0f ms", millis);
}
}
@@ -1,74 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import java.awt.Color;
/**
* How long a procedural object's bake stalls the chunk that first places it, against a server tick of 50 ms.
*/
enum BakeWeight {
LIGHT("Light", 1D, 50D, StudioTheme.SUCCESS),
MODERATE("Moderate", 50D, 500D, StudioTheme.WARNING),
HEAVY("Heavy", 500D, 5_000D, StudioTheme.ERROR);
private final String label;
private final double fromMillis;
private final double meterFullAtMillis;
private final Color color;
BakeWeight(String label, double fromMillis, double meterFullAtMillis, Color color) {
this.label = label;
this.fromMillis = fromMillis;
this.meterFullAtMillis = meterFullAtMillis;
this.color = color;
}
static BakeWeight of(double millis) {
for (BakeWeight weight : values()) {
if (millis < weight.meterFullAtMillis) {
return weight;
}
}
return HEAVY;
}
/**
* How full the meter is for a bake of {@code millis}: each weight takes an equal share of the meter, filled on a
* logarithmic scale, since bakes span thousands of times.
*/
static double meterFill(double millis) {
BakeWeight weight = of(millis);
double clamped = Math.clamp(millis, weight.fromMillis, weight.meterFullAtMillis);
double withinWeight = Math.log(clamped / weight.fromMillis) / Math.log(weight.meterFullAtMillis / weight.fromMillis);
return (weight.ordinal() + withinWeight) / values().length;
}
static String scale() {
return "Light under " + BakeTiming.formatMillis(MODERATE.fromMillis) + ", heavy from " + BakeTiming.formatMillis(HEAVY.fromMillis);
}
String label() {
return label;
}
Color color() {
return color;
}
}
@@ -1,177 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import art.arcane.iris.studio.map.PickMeasuring.TypedSpread;
import art.arcane.iris.studio.map.components.PickDisplay;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.volmlib.util.stream.ProceduralStream;
import javax.swing.JComponent;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* The biome view's explorer: every region picks the biomes on its ground from its own biome lists, so for each region
* in view it shows how its noise picks them.
*/
final class BiomeExplorer {
private final Supplier<Engine> engineSource;
private final PickInspectorPanel inspector;
private final LatestMeasurement<Measurement> measurer = new LatestMeasurement<>("Iris Biome Explorer");
private MapCensus.ViewArea latestArea;
private MapCensus.ViewArea measuredArea;
/**
* @param onDisplayChosen receives how the map should draw the picks
*/
BiomeExplorer(Supplier<Engine> engineSource, Consumer<PickDisplay> onDisplayChosen) {
this.engineSource = engineSource;
this.inspector = new PickInspectorPanel("Biomes", onDisplayChosen);
}
PickInspectorPanel inspector() {
return inspector;
}
/**
* Measures the regions in this area and how they pick their biomes, unless that was already done.
*/
void measure(MapCensus.ViewArea area) {
latestArea = area;
if (area == null || area.equals(measuredArea)) {
return;
}
measuredArea = area;
measurer.measure(() -> measurePicks(area), this::show);
}
/**
* The pack changed, so the regions and their biomes are read again.
*/
void refresh() {
measuredArea = null;
measure(latestArea);
}
void close() {
measurer.close();
}
private void show(Measurement measurement) {
List<PickInspectorPanel.Section> sections = new ArrayList<>();
for (RegionPicks region : measurement.regions()) {
List<JComponent> charts = region.spreads().stream()
.map(spread -> (JComponent) inspector.noiseChart(spread, "Biomes", region.key() + "/" + spread.title()))
.toList();
sections.add(new PickInspectorPanel.Section(region.key(), region.name(), region.color(), region.share(),
biomeCountText(region.biomeCount()), charts));
}
inspector.showRegionSections("Each region splits its own biome noise by rarity", sections);
}
private static String biomeCountText(int count) {
return count == 1 ? "1 biome" : count + " biomes";
}
private Measurement measurePicks(MapCensus.ViewArea area) {
Engine engine = engineSource.get();
IrisComplex complex = engine == null ? null : engine.getComplex();
if (complex == null) {
return null;
}
Map<IrisRegion, RegionSamples> samplesByRegion = new IdentityHashMap<>();
int[] total = {0};
PickMeasuring.forEachSample(area, (x, z) -> {
IrisRegion region = complex.getRegionStream().get(x, z);
if (region == null) {
return;
}
total[0]++;
samplesByRegion.computeIfAbsent(region, subject -> new RegionSamples(engine, complex, subject)).add(x, z);
});
List<RegionPicks> regions = samplesByRegion.values().stream()
.sorted(Comparator.comparingInt(RegionSamples::count).reversed())
.map(samples -> samples.picks(engine, total[0]))
.toList();
return new Measurement(regions);
}
/**
* The spots in view one region owns. The biome view shows each spot's base biome, which the region picks from the
* biome list of the spot's continent type.
*/
private static final class RegionSamples {
private final IrisComplex complex;
private final IrisRegion region;
private final List<TypedSpread> spreads;
private final Map<InferredType, ProceduralStream<Double>> noiseByType = new EnumMap<>(InferredType.class);
private int count;
private RegionSamples(Engine engine, IrisComplex complex, IrisRegion region) {
this.complex = complex;
this.region = region;
this.spreads = PickMeasuring.biomeSpreads(engine, complex, region);
}
private void add(double x, double z) {
count++;
InferredType type = complex.getBridgeStream().get(x, z);
for (TypedSpread typed : spreads) {
if (typed.type() == type) {
typed.spread().add(noiseByType.computeIfAbsent(type, shown -> complex.biomePickNoiseStream(region, shown)).get(x, z));
}
}
}
private int count() {
return count;
}
private RegionPicks picks(Engine engine, int totalCount) {
double share = totalCount == 0 ? 0D : count / (double) totalCount;
String key = region.getLoadKey();
String name = region.getName();
int color = PickMeasuring.regionColor(engine, region);
List<TypedSpread> inView = spreads.stream().filter(typed -> typed.spread().sampleCount() > 0).toList();
int biomeCount = (int) inView.stream()
.flatMap(typed -> typed.spread().rows().stream())
.map(row -> row.option().key())
.distinct()
.count();
return new RegionPicks(key, name, color, share, biomeCount, inView.stream().map(TypedSpread::spread).toList());
}
}
private record RegionPicks(String key, String name, int color, double share, int biomeCount,
List<NoisePickSpread> spreads) {
}
private record Measurement(List<RegionPicks> regions) {
}
}
@@ -1,320 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import java.util.Arrays;
import java.util.function.IntUnaryOperator;
/**
* The visible faces of noise terrain as columns, with neighbouring columns merged into one face where they show the
* same stretch: tops of one height along X, and sides of one height range along the side. A face runs {@code columns}
* columns from its first one and reaches {@code height} across: one column along Z for tops, blocks up for sides.
* <p>
* Hole walls follow the surface: a side from the floor up for each column next to where a {@link TerrainHole} may end,
* shown in place of the usual side while the column beside it is left out. No face crosses a hole's cell edge, so one
* set of faces serves every hole.
* <p>
* Faces depend on neither the camera nor the hole, so they are found once per terrain rather than every frame.
*/
final class BlockFaces {
private static final int INITIAL_CAPACITY = 1024;
private static final Facing[] FACINGS = Facing.values();
private static final Kind[] KINDS = Kind.values();
private final NoiseTerrain terrain;
private final int floorY;
// Faces are kept kind by kind, and facing by facing within a kind.
private final int[] firstOfGroup = new int[KINDS.length * FACINGS.length + 1];
private int count;
private int[] firstColumn = new int[INITIAL_CAPACITY];
private int[] firstRow = new int[INITIAL_CAPACITY];
private int[] bottomY = new int[INITIAL_CAPACITY];
private int[] columns = new int[INITIAL_CAPACITY];
private int[] height = new int[INITIAL_CAPACITY];
private byte[] facing = new byte[INITIAL_CAPACITY];
private BlockFaces(NoiseTerrain terrain, int floorY) {
this.terrain = terrain;
this.floorY = floorY;
}
/**
* @param floorY where sides on the edge, next to a gap or into a hole end
*/
static BlockFaces of(NoiseTerrain terrain, int floorY) {
BlockFaces faces = new BlockFaces(terrain, floorY);
for (Kind kind : KINDS) {
for (Facing facing : FACINGS) {
faces.firstOfGroup[group(kind, facing)] = faces.count;
faces.add(kind, facing);
}
}
faces.firstOfGroup[KINDS.length * FACINGS.length] = faces.count;
faces.trimToCount();
return faces;
}
private static int group(Kind kind, Facing facing) {
return kind.ordinal() * FACINGS.length + facing.ordinal();
}
private void add(Kind kind, Facing facing) {
if (kind == Kind.HOLE_WALL) {
addHoleWalls(facing);
} else if (facing == Facing.TOP) {
addTops();
} else {
addSides(facing);
}
}
// A height of 64 places blocks up to y 64, so the column's top face is at 65.
static int blockTop(double height) {
return (int) Math.floor(height) + 1;
}
int count() {
return count;
}
// All faces of one kind and facing follow on from the first.
int first(Kind kind, Facing facing) {
return firstOfGroup[group(kind, facing)];
}
int count(Kind kind, Facing facing) {
return firstOfGroup[group(kind, facing) + 1] - firstOfGroup[group(kind, facing)];
}
boolean isHoleWall(int face) {
return face >= first(Kind.HOLE_WALL, FACINGS[0]);
}
int bottomY(int face) {
return bottomY[face];
}
Facing facing(int face) {
return FACINGS[facing[face]];
}
int columns(int face) {
return columns[face];
}
int height(int face) {
return height[face];
}
// The column and row of the face's first column; the others follow along its run.
int firstColumn(int face) {
return firstColumn[face];
}
int firstRow(int face) {
return firstRow[face];
}
// The corner the face runs and reaches from; east and south sides lie on the far edge of their column.
double originX(int face) {
return terrain.worldX(firstColumn[face] + (facing(face).normalX > 0 ? 1 : 0));
}
double originY(int face) {
return bottomY[face];
}
double originZ(int face) {
return terrain.worldZ(firstRow[face] + (facing(face).normalZ > 0 ? 1 : 0));
}
double runX(int face) {
return facing(face).runsAlongX() ? (double) columns[face] * terrain.step() : 0D;
}
double runZ(int face) {
return facing(face).runsAlongX() ? 0D : (double) columns[face] * terrain.step();
}
double reachY(int face) {
return facing(face) == Facing.TOP ? 0D : height[face];
}
double reachZ(int face) {
return facing(face) == Facing.TOP ? (double) height[face] * terrain.step() : 0D;
}
private boolean hasColumn(int column, int row) {
return terrain.hasHeight(column, row);
}
private static boolean startsCell(int columnOrRow) {
return columnOrRow % TerrainHole.CELL_COLUMNS == 0;
}
private void addTops() {
for (int row = 0; row < terrain.rows(); row++) {
int column = 0;
while (column < terrain.columns()) {
if (!hasColumn(column, row)) {
column++;
continue;
}
int top = blockTop(terrain.height(column, row));
int runEnd = column + 1;
while (runEnd < terrain.columns() && !startsCell(runEnd) && hasColumn(runEnd, row)
&& blockTop(terrain.height(runEnd, row)) == top) {
runEnd++;
}
add(Facing.TOP, column, row, top, runEnd - column, 1);
column = runEnd;
}
}
}
private void addSides(Facing side) {
for (int lane = 0; lane < lanes(side); lane++) {
int sideLane = lane;
addSideRuns(side, lane, step -> sideBottom(side, sideLane, step));
}
}
// A hole only ends on the lines between cells, so walls only stand along those inside the terrain.
private void addHoleWalls(Facing side) {
if (side == Facing.TOP) {
return;
}
int towardNeighbour = side.runsAlongX() ? side.normalZ : side.normalX;
for (int lane = 0; lane < lanes(side); lane++) {
int neighbourLane = lane + towardNeighbour;
boolean facesNextCell = lane / TerrainHole.CELL_COLUMNS != neighbourLane / TerrainHole.CELL_COLUMNS;
if (neighbourLane >= 0 && neighbourLane < lanes(side) && facesNextCell) {
addSideRuns(side, lane, step -> floorY);
}
}
}
private int lanes(Facing side) {
return side.runsAlongX() ? terrain.rows() : terrain.columns();
}
private void addSideRuns(Facing side, int lane, IntUnaryOperator bottomAt) {
int steps = side.runsAlongX() ? terrain.columns() : terrain.rows();
int step = 0;
while (step < steps) {
int top = sideTop(side, lane, step);
int bottom = bottomAt.applyAsInt(step);
if (bottom >= top) {
step++;
continue;
}
int runEnd = step + 1;
while (runEnd < steps && !startsCell(runEnd) && sideTop(side, lane, runEnd) == top && bottomAt.applyAsInt(runEnd) == bottom) {
runEnd++;
}
add(side, side.column(lane, step), side.row(lane, step), bottom, runEnd - step, top - bottom);
step = runEnd;
}
}
// No column means no side, which the caller sees as a side with no height.
private int sideTop(Facing side, int lane, int step) {
int column = side.column(lane, step);
int row = side.row(lane, step);
return hasColumn(column, row) ? blockTop(terrain.height(column, row)) : Integer.MIN_VALUE;
}
// Columns on the edge, or next to a gap, show their side all the way down to the floor.
private int sideBottom(Facing side, int lane, int step) {
int column = side.column(lane, step) + side.normalX;
int row = side.row(lane, step) + side.normalZ;
return hasColumn(column, row) ? blockTop(terrain.height(column, row)) : floorY;
}
private void add(Facing faceFacing, int column, int row, int bottom, int runColumns, int reach) {
if (count == facing.length) {
grow();
}
firstColumn[count] = column;
firstRow[count] = row;
bottomY[count] = bottom;
columns[count] = runColumns;
height[count] = reach;
facing[count] = (byte) faceFacing.ordinal();
count++;
}
private void grow() {
resizeTo(facing.length * 2);
}
// Large terrain keeps millions of faces, so the room left over from growing would be a lot of memory.
private void trimToCount() {
resizeTo(count);
}
private void resizeTo(int capacity) {
firstColumn = Arrays.copyOf(firstColumn, capacity);
firstRow = Arrays.copyOf(firstRow, capacity);
bottomY = Arrays.copyOf(bottomY, capacity);
columns = Arrays.copyOf(columns, capacity);
height = Arrays.copyOf(height, capacity);
facing = Arrays.copyOf(facing, capacity);
}
/**
* Which way a face looks. Tops and north and south sides run along X; east and west sides run along Z.
*/
enum Facing {
TOP(0, 1, 0),
NORTH(0, 0, -1),
SOUTH(0, 0, 1),
WEST(-1, 0, 0),
EAST(1, 0, 0);
final int normalX;
final int normalY;
final int normalZ;
Facing(int normalX, int normalY, int normalZ) {
this.normalX = normalX;
this.normalY = normalY;
this.normalZ = normalZ;
}
boolean runsAlongX() {
return normalX == 0;
}
// A lane is a row for faces running along X and a column for the others; steps go along the lane.
int column(int lane, int step) {
return runsAlongX() ? step : lane;
}
int row(int lane, int step) {
return runsAlongX() ? lane : step;
}
}
// Surface faces show unless their column is in a hole; hole walls only beside one.
enum Kind {
SURFACE,
HOLE_WALL
}
}
@@ -1,47 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import java.awt.Color;
/**
* Colours noise that is already a height in blocks, spreading a palette over the heights it can reach.
*/
record BlockHeightColorScale(NoisePalette palette, double minimum, double maximum) implements NoiseColorScale {
@Override
public int colorFinite(double value) {
double span = maximum - minimum;
return palette.colorNormalized(span <= 0D ? 0.5D : (value - minimum) / span);
}
@Override
public int colorInvalid() {
return palette.colorInvalid();
}
@Override
public Color displayColorNormalized(double normalized) {
return palette.displayColorNormalized(normalized);
}
@Override
public String label() {
return "Blocks";
}
}
@@ -1,213 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import art.arcane.iris.studio.map.BlockTextures.BlockTexture;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.UnaryOperator;
/**
* A block as the object viewer draws it: the textured faces of its model, in block units, already turned the way the
* blockstate faces.
*
* @param faces every face of every box in the model
* @param coveredSides the block's sides that a solid face fills completely, which hide whatever touches them
* @param hidesSameBlockSides whether the model fills the whole block, so like glass it hides the sides between two of
* the same blocks
*/
record BlockModel(List<Face> faces, Set<CubeFace> coveredSides, boolean hidesSameBlockSides) {
static final BlockModel EMPTY = new BlockModel(List.of(), Set.of(), false);
private static final int SIDE_CELLS = 16;
private static final double ON_SIDE_TOLERANCE = 1e-4D;
static BlockModel of(List<Face> faces) {
Set<CubeFace> coveredSides = EnumSet.noneOf(CubeFace.class);
boolean fillsEverySide = true;
for (CubeFace side : CubeFace.values()) {
if (sideIsFilled(faces, side, true)) {
coveredSides.add(side);
}
fillsEverySide &= sideIsFilled(faces, side, false);
}
return new BlockModel(List.copyOf(faces), Set.copyOf(coveredSides), fillsEverySide);
}
static BlockModel solidColor(int color) {
BlockTexture texture = BlockTexture.solid(color);
List<Face> faces = new ArrayList<>();
for (CubeFace side : CubeFace.values()) {
faces.add(Face.boxSide(Vec3.ZERO, new Vec3(1D, 1D, 1D), side, texture, side));
}
return of(faces);
}
boolean isEmpty() {
return faces.isEmpty();
}
BlockModel withTextures(UnaryOperator<BlockTexture> change) {
Map<BlockTexture, BlockTexture> changed = new IdentityHashMap<>();
List<Face> changedFaces = new ArrayList<>(faces.size());
for (Face face : faces) {
changedFaces.add(face.withTexture(changed.computeIfAbsent(face.texture(), change)));
}
return new BlockModel(List.copyOf(changedFaces), coveredSides, hidesSameBlockSides);
}
// The side is split into a grid, and every cell has to lie under a face pressed flat against it.
private static boolean sideIsFilled(List<Face> faces, CubeFace side, boolean onlySolidFaces) {
boolean[] filled = new boolean[SIDE_CELLS * SIDE_CELLS];
for (Face face : faces) {
if (face.liesOn(side) && (!onlySolidFaces || face.texture().isFullyOpaque())) {
face.fillCells(side, filled, SIDE_CELLS);
}
}
for (boolean cell : filled) {
if (!cell) {
return false;
}
}
return true;
}
/**
* A parallelogram from {@code origin} along {@code edgeU} and {@code edgeV}. The texture point at the origin and
* how it moves along each edge are given as fractions of the texture.
*
* @param normal the way the face looks out; it is hidden when seen from behind
* @param cullFace the block side whose neighbour hides this face when it covers that side, or null
*/
record Face(Vec3 origin, Vec3 edgeU, Vec3 edgeV, Vec3 normal, BlockTexture texture, TextureMapping mapping,
double shade, CubeFace cullFace) {
// Laid out as seen from outside: u to the right and v downwards, matching Minecraft's UVs for a whole texture.
static Face boxSide(Vec3 from, Vec3 to, CubeFace side, BlockTexture texture, CubeFace cullFace) {
Vec3[] corners = BoxCorners.of(from, to, side);
return new Face(corners[0], corners[3].minus(corners[0]), corners[1].minus(corners[0]), side.direction(),
texture, TextureMapping.WHOLE, side.shade(), cullFace);
}
Face withTexture(BlockTexture changedTexture) {
return new Face(origin, edgeU, edgeV, normal, changedTexture, mapping, shade, cullFace);
}
Face transformed(Transform transform) {
Vec3 turnedNormal = transform.direction(normal);
double length = Math.sqrt(turnedNormal.x() * turnedNormal.x() + turnedNormal.y() * turnedNormal.y() + turnedNormal.z() * turnedNormal.z());
return new Face(transform.point(origin), transform.direction(edgeU), transform.direction(edgeV),
length == 0D ? turnedNormal : turnedNormal.times(1D / length), texture, mapping, shade,
cullFace == null ? null : CubeFace.nearest(transform.direction(cullFace.direction())));
}
Face withCullFace(CubeFace side) {
return new Face(origin, edgeU, edgeV, normal, texture, mapping, shade, side);
}
Face withShade(double changedShade) {
return new Face(origin, edgeU, edgeV, normal, texture, mapping, changedShade, cullFace);
}
private boolean liesOn(CubeFace side) {
int axis = side.axis();
double plane = side.pointsPositive() ? 1D : 0D;
return CubeFace.nearest(normal) == side
&& Math.abs(normal.component(axis)) > 1D - ON_SIDE_TOLERANCE
&& Math.abs(origin.component(axis) - plane) < ON_SIDE_TOLERANCE
&& Math.abs(edgeU.component(axis)) < ON_SIDE_TOLERANCE
&& Math.abs(edgeV.component(axis)) < ON_SIDE_TOLERANCE;
}
private void fillCells(CubeFace side, boolean[] filled, int cells) {
int firstAxis = side.axis() == 0 ? 1 : 0;
int secondAxis = side.axis() == 2 ? 1 : 2;
double[] firstRange = range(firstAxis);
double[] secondRange = range(secondAxis);
for (int first = 0; first < cells; first++) {
double firstCenter = (first + 0.5D) / cells;
if (firstCenter < firstRange[0] || firstCenter > firstRange[1]) {
continue;
}
for (int second = 0; second < cells; second++) {
double secondCenter = (second + 0.5D) / cells;
if (secondCenter >= secondRange[0] && secondCenter <= secondRange[1]) {
filled[first * cells + second] = true;
}
}
}
}
private double[] range(int axis) {
double start = origin.component(axis);
double alongU = edgeU.component(axis);
double alongV = edgeV.component(axis);
double low = start + Math.min(0D, alongU) + Math.min(0D, alongV);
double high = start + Math.max(0D, alongU) + Math.max(0D, alongV);
return new double[]{low, high};
}
}
/**
* Where a face's corner sits in its texture and how the texture point moves along the face's two edges, all as
* fractions of the texture's width and height.
*/
record TextureMapping(double u, double v, double uAlongU, double vAlongU, double uAlongV, double vAlongV) {
static final TextureMapping WHOLE = new TextureMapping(0D, 0D, 1D, 0D, 0D, 1D);
}
/**
* A box side's corners in Minecraft's order: top left, bottom left, bottom right and top right, as seen from
* outside the box.
*/
static final class BoxCorners {
private BoxCorners() {
}
static Vec3[] of(Vec3 from, Vec3 to, CubeFace side) {
double minX = from.x();
double minY = from.y();
double minZ = from.z();
double maxX = to.x();
double maxY = to.y();
double maxZ = to.z();
return switch (side) {
case DOWN -> corners(minX, minY, maxZ, minX, minY, minZ, maxX, minY, minZ, maxX, minY, maxZ);
case UP -> corners(minX, maxY, minZ, minX, maxY, maxZ, maxX, maxY, maxZ, maxX, maxY, minZ);
case NORTH -> corners(maxX, maxY, minZ, maxX, minY, minZ, minX, minY, minZ, minX, maxY, minZ);
case SOUTH -> corners(minX, maxY, maxZ, minX, minY, maxZ, maxX, minY, maxZ, maxX, maxY, maxZ);
case WEST -> corners(minX, maxY, minZ, minX, minY, minZ, minX, minY, maxZ, minX, maxY, maxZ);
case EAST -> corners(maxX, maxY, maxZ, maxX, minY, maxZ, maxX, minY, minZ, maxX, maxY, minZ);
};
}
private static Vec3[] corners(double... coordinates) {
Vec3[] corners = new Vec3[4];
for (int corner = 0; corner < 4; corner++) {
corners[corner] = new Vec3(coordinates[corner * 3], coordinates[corner * 3 + 1], coordinates[corner * 3 + 2]);
}
return corners;
}
}
}
@@ -1,351 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import art.arcane.iris.studio.map.BlockModel.BoxCorners;
import art.arcane.iris.studio.map.BlockModel.Face;
import art.arcane.iris.studio.map.BlockModel.TextureMapping;
import art.arcane.iris.studio.map.BlockTextures.BlockStateId;
import art.arcane.iris.studio.map.BlockTextures.BlockTexture;
import art.arcane.iris.studio.map.BlockTextures.ModelDefinition;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Reads a block's look the way Minecraft does: every model part the blockstate picks, every box with its own texture
* and UVs, tilted boxes, the blockstate's turn with or without locked textures, and which faces a neighbour hides.
*/
final class BlockModelBuilder {
private static final double MODEL_UNITS = 16D;
private static final double BLOCK_CENTER = 0.5D;
private static final int QUARTER_TURN = 90;
private final BlockTextures textures;
private final EntityBlockShapes entityShapes;
BlockModelBuilder(BlockTextures textures) {
this.textures = textures;
this.entityShapes = new EntityBlockShapes(textures);
}
Optional<BlockModel> build(String blockState) {
try {
BlockStateId state = BlockStateId.parse(blockState);
List<JsonObject> placements = placementsOf(state);
if (placements == null) {
return Optional.empty();
}
List<Face> faces = new ArrayList<>();
for (JsonObject placement : placements) {
faces.addAll(placedFaces(state, placement));
}
faces.addAll(entityShapes.facesAddedTo(state));
return Optional.of(BlockModel.of(faces));
} catch (IOException | RuntimeException error) {
return Optional.empty();
}
}
/**
* A box with Minecraft's default UVs on each side, for shapes the game draws in code.
*/
static List<Face> box(Vec3 fromPixels, Vec3 toPixels, BlockTexture texture, boolean culledBySides) {
List<Face> faces = new ArrayList<>();
for (CubeFace side : CubeFace.values()) {
FaceUv uv = FaceUv.byDefault(side, fromPixels, toPixels);
Face face = boxFace(fromPixels, toPixels, side, texture, uv).withShade(side.shade());
faces.add(culledBySides ? face.withCullFace(side) : face);
}
return faces;
}
// A variant names one model; a multipart blockstate, like a fence's, adds a part for every condition that holds.
private List<JsonObject> placementsOf(BlockStateId state) throws IOException {
JsonObject definition = textures.readJson(BlockTextures.assetPath(state.namespace() + ":" + state.name(), "blockstates", ".json"));
if (definition == null) {
return null;
}
List<JsonObject> placements = new ArrayList<>();
if (definition.has("variants")) {
for (Map.Entry<String, JsonElement> variant : definition.getAsJsonObject("variants").entrySet()) {
if (BlockTextures.variantMatches(variant.getKey(), state.properties())) {
addPlacement(placements, variant.getValue());
break;
}
}
}
if (definition.has("multipart")) {
for (JsonElement part : definition.getAsJsonArray("multipart")) {
JsonObject rule = part.getAsJsonObject();
if (!rule.has("when") || BlockTextures.conditionMatches(rule.getAsJsonObject("when"), state.properties())) {
addPlacement(placements, rule.get("apply"));
}
}
}
return placements;
}
private static void addPlacement(List<JsonObject> placements, JsonElement models) {
JsonObject first = BlockTextures.firstModel(models);
if (first != null && first.has("model")) {
placements.add(first);
}
}
private List<Face> placedFaces(BlockStateId state, JsonObject placement) throws IOException {
ModelDefinition model = textures.readModel(placement.get("model").getAsString());
if (model.elements() == null) {
return entityShapes.facesOf(state, model);
}
BlockRotation rotation = BlockRotation.of(placement);
List<Face> faces = new ArrayList<>();
for (JsonElement element : model.elements()) {
addElementFaces(faces, state, model, element.getAsJsonObject(), rotation);
}
return faces;
}
private void addElementFaces(List<Face> faces, BlockStateId state, ModelDefinition model, JsonObject element, BlockRotation rotation) {
JsonObject elementFaces = element.getAsJsonObject("faces");
if (elementFaces == null) {
return;
}
Vec3 from = vector(element.getAsJsonArray("from"));
Vec3 to = vector(element.getAsJsonArray("to"));
Transform tilt = tiltOf(element);
boolean shaded = !element.has("shade") || element.get("shade").getAsBoolean();
CubeFace shadeSide = element.has("shade_direction_override")
? CubeFace.named(element.get("shade_direction_override").getAsString()) : null;
for (Map.Entry<String, JsonElement> entry : elementFaces.entrySet()) {
CubeFace side = CubeFace.named(entry.getKey());
JsonObject faceJson = entry.getValue().getAsJsonObject();
if (side == null || !faceJson.has("texture")) {
continue;
}
String textureName = BlockTextures.dereference(faceJson.get("texture").getAsString(), model.textures());
if (textureName == null) {
continue;
}
Optional<BlockTexture> texture = textures.faceTexture(state, textureName, BlockTextures.tintIndexOf(faceJson));
if (texture.isEmpty()) {
continue;
}
FaceUv uv = FaceUv.of(faceJson, side, from, to);
if (rotation.locksTextures()) {
uv = uv.lockedTo(side, rotation);
}
Face face = boxFace(from, to, side, texture.get(), uv).transformed(tilt);
if (faceJson.has("cullface")) {
face = face.withCullFace(CubeFace.named(faceJson.get("cullface").getAsString()));
}
face = face.transformed(rotation.transform());
faces.add(face.withShade(shadeOf(face, shaded, shadeSide, rotation)));
}
}
private static Face boxFace(Vec3 fromPixels, Vec3 toPixels, CubeFace side, BlockTexture texture, FaceUv uv) {
Vec3[] corners = BoxCorners.of(fromPixels.times(1D / MODEL_UNITS), toPixels.times(1D / MODEL_UNITS), side);
return new Face(corners[0], corners[3].minus(corners[0]), corners[1].minus(corners[0]), side.direction(),
texture, uv.mapping(), side.shade(), null);
}
private static double shadeOf(Face face, boolean shaded, CubeFace shadeSide, BlockRotation rotation) {
if (!shaded) {
return CubeFace.UP.shade();
}
if (shadeSide != null) {
return CubeFace.nearest(rotation.transform().direction(shadeSide.direction())).shade();
}
return CubeFace.nearest(face.normal()).shade();
}
// A box can be tilted around a point, on one axis or, since 1.21.?, on all three; rescaling stretches a tilted
// plant back to the full block width.
private static Transform tiltOf(JsonObject element) {
if (!element.has("rotation")) {
return Transform.IDENTITY;
}
JsonObject rotation = element.getAsJsonObject("rotation");
Vec3 origin = rotation.has("origin") ? vector(rotation.getAsJsonArray("origin")).times(1D / MODEL_UNITS) : new Vec3(BLOCK_CENTER, BLOCK_CENTER, BLOCK_CENTER);
Transform around = Transform.IDENTITY.translate(origin.x(), origin.y(), origin.z());
Transform back = Transform.IDENTITY.translate(-origin.x(), -origin.y(), -origin.z());
if (!rotation.has("axis")) {
return around
.rotateX(numberOr(rotation, "x", 0D))
.rotateY(numberOr(rotation, "y", 0D))
.rotateZ(numberOr(rotation, "z", 0D))
.then(back);
}
String axis = rotation.get("axis").getAsString();
double angle = numberOr(rotation, "angle", 0D);
boolean rescale = rotation.has("rescale") && rotation.get("rescale").getAsBoolean();
double stretch = rescale ? 1D / Math.cos(Math.toRadians(angle)) : 1D;
Transform stretched = around.scale(axis.equals("x") ? 1D : stretch, axis.equals("y") ? 1D : stretch, axis.equals("z") ? 1D : stretch);
Transform tilted = switch (axis) {
case "x" -> stretched.rotateX(angle);
case "y" -> stretched.rotateY(angle);
default -> stretched.rotateZ(angle);
};
return tilted.then(back);
}
private static double numberOr(JsonObject object, String key, double fallback) {
return object.has(key) ? object.get(key).getAsDouble() : fallback;
}
private static Vec3 vector(JsonArray values) {
return new Vec3(values.get(0).getAsDouble(), values.get(1).getAsDouble(), values.get(2).getAsDouble());
}
/**
* How a blockstate turns its model: around the x axis first, then the y axis, both in quarter turns against the
* right-hand rule. With uvlock the textures stay put while the shape turns.
*/
private record BlockRotation(int x, int y, boolean uvlock) {
static BlockRotation of(JsonObject placement) {
int x = placement.has("x") ? Math.floorMod(placement.get("x").getAsInt(), 360) : 0;
int y = placement.has("y") ? Math.floorMod(placement.get("y").getAsInt(), 360) : 0;
return new BlockRotation(x, y, placement.has("uvlock") && placement.get("uvlock").getAsBoolean());
}
boolean locksTextures() {
return uvlock && (x != 0 || y != 0);
}
Transform transform() {
return Transform.IDENTITY
.translate(BLOCK_CENTER, BLOCK_CENTER, BLOCK_CENTER)
.then(turn())
.translate(-BLOCK_CENTER, -BLOCK_CENTER, -BLOCK_CENTER);
}
Transform turn() {
return Transform.IDENTITY.rotateY(-y).rotateX(-x);
}
Transform inverseTurn() {
return Transform.IDENTITY.rotateX(x).rotateY(y);
}
}
/**
* A face's corner UVs in model pixels and the quarter turn of the texture on it.
*/
private record FaceUv(double u1, double v1, double u2, double v2, int rotation) {
static FaceUv of(JsonObject face, CubeFace side, Vec3 from, Vec3 to) {
int rotation = face.has("rotation") ? Math.floorMod(face.get("rotation").getAsInt(), 360) : 0;
if (!face.has("uv")) {
return byDefault(side, from, to).withRotation(rotation);
}
JsonArray uv = face.getAsJsonArray("uv");
return new FaceUv(uv.get(0).getAsDouble(), uv.get(1).getAsDouble(), uv.get(2).getAsDouble(), uv.get(3).getAsDouble(), rotation);
}
// The part of the texture the face would cover if the texture were laid over the whole block side.
static FaceUv byDefault(CubeFace side, Vec3 from, Vec3 to) {
double full = MODEL_UNITS;
return switch (side) {
case DOWN -> new FaceUv(from.x(), full - to.z(), to.x(), full - from.z(), 0);
case UP -> new FaceUv(from.x(), from.z(), to.x(), to.z(), 0);
case NORTH -> new FaceUv(full - to.x(), full - to.y(), full - from.x(), full - from.y(), 0);
case SOUTH -> new FaceUv(from.x(), full - to.y(), to.x(), full - from.y(), 0);
case WEST -> new FaceUv(from.z(), full - to.y(), to.z(), full - from.y(), 0);
case EAST -> new FaceUv(full - to.z(), full - to.y(), full - from.z(), full - from.y(), 0);
};
}
FaceUv withRotation(int changedRotation) {
return new FaceUv(u1, v1, u2, v2, changedRotation);
}
// Each corner takes the UV a quarter turn further along for every quarter turn of the texture.
TextureMapping mapping() {
double[] origin = cornerUv(0);
double[] alongU = cornerUv(3);
double[] alongV = cornerUv(1);
return new TextureMapping(origin[0] / MODEL_UNITS, origin[1] / MODEL_UNITS,
(alongU[0] - origin[0]) / MODEL_UNITS, (alongU[1] - origin[1]) / MODEL_UNITS,
(alongV[0] - origin[0]) / MODEL_UNITS, (alongV[1] - origin[1]) / MODEL_UNITS);
}
private double[] cornerUv(int corner) {
return switch ((corner + rotation / QUARTER_TURN) % 4) {
case 0 -> new double[]{u1, v1};
case 1 -> new double[]{u1, v2};
case 2 -> new double[]{u2, v2};
default -> new double[]{u2, v1};
};
}
/**
* Minecraft's uvlock: the UVs are carried through the reverse of the blockstate's turn, so the texture keeps
* its place in the world while the face moves to another side.
*/
FaceUv lockedTo(CubeFace side, BlockRotation blockRotation) {
CubeFace turnedSide = CubeFace.nearest(blockRotation.turn().direction(side.direction()));
Transform uvTurn = Transform.IDENTITY
.translate(BLOCK_CENTER, BLOCK_CENTER, BLOCK_CENTER)
.then(faceFromWorld(side))
.then(blockRotation.inverseTurn())
.then(worldFromFace(turnedSide))
.translate(-BLOCK_CENTER, -BLOCK_CENTER, -BLOCK_CENTER);
Vec3 first = uvTurn.point(new Vec3(u1 / MODEL_UNITS, v1 / MODEL_UNITS, 0D)).times(MODEL_UNITS);
Vec3 second = uvTurn.point(new Vec3(u2 / MODEL_UNITS, v2 / MODEL_UNITS, 0D)).times(MODEL_UNITS);
boolean keepsUOrder = Math.signum(u2 - u1) == Math.signum(second.x() - first.x());
boolean keepsVOrder = Math.signum(v2 - v1) == Math.signum(second.y() - first.y());
Vec3 textureRight = uvTurn.direction(new Vec3(Math.cos(Math.toRadians(rotation)), Math.sin(Math.toRadians(rotation)), 0D));
long quarterTurns = Math.round(Math.toDegrees(Math.atan2(textureRight.y(), textureRight.x())) / QUARTER_TURN);
return new FaceUv(
keepsUOrder ? first.x() : second.x(), keepsVOrder ? first.y() : second.y(),
keepsUOrder ? second.x() : first.x(), keepsVOrder ? second.y() : first.y(),
(int) Math.floorMod(-quarterTurns * QUARTER_TURN, 360L));
}
// Minecraft lays every side's texture out as if it were the south side, turned into place.
private static Transform worldFromFace(CubeFace side) {
return switch (side) {
case SOUTH -> Transform.IDENTITY;
case EAST -> Transform.IDENTITY.rotateY(90D);
case WEST -> Transform.IDENTITY.rotateY(-90D);
case NORTH -> Transform.IDENTITY.rotateY(180D);
case UP -> Transform.IDENTITY.rotateX(-90D);
case DOWN -> Transform.IDENTITY.rotateX(90D);
};
}
private static Transform faceFromWorld(CubeFace side) {
return switch (side) {
case SOUTH -> Transform.IDENTITY;
case EAST -> Transform.IDENTITY.rotateY(-90D);
case WEST -> Transform.IDENTITY.rotateY(90D);
case NORTH -> Transform.IDENTITY.rotateY(180D);
case UP -> Transform.IDENTITY.rotateX(90D);
case DOWN -> Transform.IDENTITY.rotateX(-90D);
};
}
}
}
@@ -49,10 +49,8 @@ final class BlockTextures {
private final ZipFile clientJar;
private final MinecraftBiomeColors biomeColors;
private final Map<String, Optional<ResolvedTexture>> resolvedTextures = new ConcurrentHashMap<>();
private final Map<String, Optional<BlockModel>> resolvedModels = new ConcurrentHashMap<>();
private final Map<String, Optional<BlockTexture>> faceTextures = new ConcurrentHashMap<>();
private final Map<String, Optional<BlockTexture>> icons = new ConcurrentHashMap<>();
private final BlockModelBuilder modelBuilder = new BlockModelBuilder(this);
private BlockTextures(ZipFile clientJar, MinecraftBiomeColors biomeColors) {
this.clientJar = clientJar;
@@ -134,13 +132,6 @@ final class BlockTextures {
.filter(ResolvedTexture::isSideOnSprite).map(ResolvedTexture::texture);
}
/**
* What the block looks like from every side, for drawing it in 3D.
*/
Optional<BlockModel> model(NativeBlockState block) {
return resolvedModels.computeIfAbsent(block.key(), modelBuilder::build);
}
private static Optional<NativeBlockState> withHalf(NativeBlockState block, BlockHalf half) {
String current = IrisProceduralBlocks.propertyValue(block, BlockHalf.PROPERTY);
if (current == null) {
@@ -1,102 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import javax.swing.Icon;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
/**
* What an empty view says, drawn in the middle of it the way IntelliJ fills an empty tool window: a large icon, what
* is missing, and where to add it.
*
* @param location the pack folder or file the hint points to, drawn as code
*/
record EmptyState(Icon icon, String title, String hint, String location, String footer) {
private static final int ICON_GAP = 18;
private static final int TITLE_GAP = 8;
private static final int LOCATION_GAP = 10;
private static final int FOOTER_GAP = 14;
private static final int CHIP_PADDING_X = 8;
private static final int CHIP_PADDING_Y = 4;
private static final int CHIP_ARC = 8;
/**
* Draws the empty state centred on the given point.
*/
void paint(Graphics2D graphics, Component owner, int centerX, int centerY) {
Graphics2D canvas = (Graphics2D) graphics.create();
try {
canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int top = centerY - height(canvas) / 2;
icon.paintIcon(owner, canvas, centerX - icon.getIconWidth() / 2, top);
top += icon.getIconHeight() + StudioTheme.scale(ICON_GAP);
top = drawCentered(canvas, title, StudioTheme.titleFont(), StudioTheme.TEXT, centerX, top);
top = drawCentered(canvas, hint, StudioTheme.font(), StudioTheme.SECONDARY_TEXT, centerX,
top + StudioTheme.scale(TITLE_GAP));
top = drawLocationChip(canvas, centerX, top + StudioTheme.scale(LOCATION_GAP));
drawCentered(canvas, footer, StudioTheme.smallFont(), StudioTheme.MUTED_TEXT, centerX, top + StudioTheme.scale(FOOTER_GAP));
} finally {
canvas.dispose();
}
}
private int height(Graphics2D canvas) {
return icon.getIconHeight() + StudioTheme.scale(ICON_GAP)
+ canvas.getFontMetrics(StudioTheme.titleFont()).getHeight()
+ StudioTheme.scale(TITLE_GAP) + canvas.getFontMetrics(StudioTheme.font()).getHeight()
+ StudioTheme.scale(LOCATION_GAP) + chipHeight(canvas)
+ StudioTheme.scale(FOOTER_GAP) + canvas.getFontMetrics(StudioTheme.smallFont()).getHeight();
}
private int chipHeight(Graphics2D canvas) {
return canvas.getFontMetrics(StudioTheme.monospacedFont()).getHeight() + StudioTheme.scale(CHIP_PADDING_Y) * 2;
}
private int drawLocationChip(Graphics2D canvas, int centerX, int top) {
canvas.setFont(StudioTheme.monospacedFont());
FontMetrics metrics = canvas.getFontMetrics();
int width = metrics.stringWidth(location) + StudioTheme.scale(CHIP_PADDING_X) * 2;
int height = chipHeight(canvas);
int left = centerX - width / 2;
RoundRectangle2D chip = new RoundRectangle2D.Double(left + 0.5D, top + 0.5D, width - 1D, height - 1D,
StudioTheme.scale(CHIP_ARC), StudioTheme.scale(CHIP_ARC));
canvas.setColor(StudioTheme.PANEL_BACKGROUND);
canvas.fill(chip);
canvas.setColor(StudioTheme.CONTROL_BORDER);
canvas.draw(chip);
canvas.setColor(StudioTheme.TEXT);
canvas.drawString(location, left + StudioTheme.scale(CHIP_PADDING_X), top + StudioTheme.scale(CHIP_PADDING_Y) + metrics.getAscent());
return top + height;
}
private static int drawCentered(Graphics2D canvas, String text, Font font, Color color, int centerX, int top) {
canvas.setFont(font);
canvas.setColor(color);
FontMetrics metrics = canvas.getFontMetrics();
canvas.drawString(text, centerX - metrics.stringWidth(text) / 2, top + metrics.getAscent());
return top + metrics.getHeight();
}
}
@@ -1,298 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import art.arcane.iris.studio.map.BlockModel.Face;
import art.arcane.iris.studio.map.BlockModel.TextureMapping;
import art.arcane.iris.studio.map.BlockTextures.BlockStateId;
import art.arcane.iris.studio.map.BlockTextures.BlockTexture;
import art.arcane.iris.studio.map.BlockTextures.ModelDefinition;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* Shapes for the blocks Minecraft draws in code instead of from a model file, like chests, heads, banners and
* fluids, which fill their block. Chests, heads, banners and the bell use their entity textures laid out the way Minecraft's model parts are;
* rarer ones are a simple box in their particle texture.
*/
final class EntityBlockShapes {
private static final Set<String> INVISIBLE = Set.of("air", "cave_air", "void_air", "barrier", "light",
"structure_void", "moving_piston", "pitcher_crop");
private static final int END_PORTAL_COLOR = 0x0E1219;
private static final double SKULL_WALL_OFFSET = 0.25D;
private static final double ROTATION_SEGMENT_DEGREES = 22.5D;
private static final double BANNER_SCALE = 2D / 3D;
private static final double MODEL_UNITS = 16D;
private static final Map<String, Integer> DYE_COLORS = Map.ofEntries(
Map.entry("white", 0xF9FFFE), Map.entry("orange", 0xF9801D), Map.entry("magenta", 0xC74EBD),
Map.entry("light_blue", 0x3AB3DA), Map.entry("yellow", 0xFED83D), Map.entry("lime", 0x80C71F),
Map.entry("pink", 0xF38BAA), Map.entry("gray", 0x474F52), Map.entry("light_gray", 0x9D9D97),
Map.entry("cyan", 0x169C9C), Map.entry("purple", 0x8932B8), Map.entry("blue", 0x3C44AA),
Map.entry("brown", 0x835432), Map.entry("green", 0x5E7C16), Map.entry("red", 0xB02E26),
Map.entry("black", 0x1D1D21));
private final BlockTextures textures;
EntityBlockShapes(BlockTextures textures) {
this.textures = textures;
}
/**
* The faces of a block whose model has no boxes of its own.
*/
List<Face> facesOf(BlockStateId state, ModelDefinition model) {
String name = state.name();
if (INVISIBLE.contains(name)) {
return List.of();
}
if (name.endsWith("chest")) {
return chest(state);
}
if (name.endsWith("_skull") || name.endsWith("_head")) {
return head(state, model);
}
if (name.endsWith("banner")) {
return banner(state);
}
return switch (name) {
case "conduit" -> particleBox(state, model, new Vec3(5, 5, 5), new Vec3(11, 11, 11), false);
case "decorated_pot" -> decoratedPot(state, model);
case "end_portal" -> BlockModelBuilder.box(new Vec3(0, 0, 0), new Vec3(16, 12, 16), BlockTexture.solid(END_PORTAL_COLOR), true);
case "end_gateway" -> BlockModelBuilder.box(new Vec3(0, 0, 0), new Vec3(16, 16, 16), BlockTexture.solid(END_PORTAL_COLOR), true);
default -> name.endsWith("copper_golem_statue")
? particleBox(state, model, new Vec3(4, 0, 4), new Vec3(12, 14, 12), false)
: particleBox(state, model, new Vec3(0, 0, 0), new Vec3(16, 16, 16), true);
};
}
/**
* Parts a block draws in code on top of its model, like the bell hanging in its frame.
*/
List<Face> facesAddedTo(BlockStateId state) {
if (!state.name().equals("bell")) {
return List.of();
}
Optional<BlockTexture> texture = textures.entityTexture("entity/bell/bell_body", MinecraftBlockTints.NO_TINT);
if (texture.isEmpty()) {
return List.of();
}
List<Face> faces = new ArrayList<>();
faces.addAll(modelPartBox(texture.get(), 0, 0, new Vec3(5, 6, 5), new Vec3(6, 7, 6), Transform.IDENTITY));
faces.addAll(modelPartBox(texture.get(), 0, 13, new Vec3(4, 4, 4), new Vec3(8, 2, 8), Transform.IDENTITY));
return faces;
}
private List<Face> particleBox(BlockStateId state, ModelDefinition model, Vec3 from, Vec3 to, boolean culledBySides) {
String particle = BlockTextures.dereference("#particle", model.textures());
if (particle == null) {
return List.of();
}
return textures.faceTexture(state, particle, BlockTextures.NO_TINT_INDEX)
.map(texture -> BlockModelBuilder.box(from, to, texture, culledBySides))
.orElse(List.of());
}
private List<Face> decoratedPot(BlockStateId state, ModelDefinition model) {
List<Face> faces = new ArrayList<>(particleBox(state, model, new Vec3(1, 0, 1), new Vec3(15, 16, 15), false));
faces.addAll(particleBox(state, model, new Vec3(4, 16, 4), new Vec3(12, 20, 12), false));
return faces;
}
// Single chests are 14 pixels wide; each half of a double chest is 15, reaching over to its partner.
private List<Face> chest(BlockStateId state) {
String type = state.properties().getOrDefault("type", "single");
String suffix = type.equals("single") ? "" : "_" + type;
Optional<BlockTexture> texture = textures.entityTexture("entity/chest/" + chestTextureName(state.name()) + suffix, MinecraftBlockTints.NO_TINT);
if (texture.isEmpty()) {
return List.of();
}
Transform place = Transform.IDENTITY
.translate(0.5D, 0.5D, 0.5D)
.rotateY(-yRotationOf(state.properties().getOrDefault("facing", "north")))
.translate(-0.5D, -0.5D, -0.5D);
double left = type.equals("left") ? 0D : 1D;
double width = type.equals("single") ? 14D : 15D;
double lockX = switch (type) {
case "left" -> 0D;
case "right" -> 15D;
default -> 7D;
};
double lockWidth = type.equals("single") ? 2D : 1D;
List<Face> faces = new ArrayList<>();
faces.addAll(modelPartBox(texture.get(), 0, 19, new Vec3(left, 0, 1), new Vec3(width, 10, 14), place));
faces.addAll(modelPartBox(texture.get(), 0, 0, new Vec3(left, 9, 1), new Vec3(width, 5, 14), place));
faces.addAll(modelPartBox(texture.get(), 0, 0, new Vec3(lockX, 7, 15), new Vec3(lockWidth, 4, 1), place));
return faces;
}
private static String chestTextureName(String blockName) {
String name = blockName.startsWith("waxed_") ? blockName.substring("waxed_".length()) : blockName;
return switch (name) {
case "trapped_chest" -> "trapped";
case "ender_chest" -> "ender";
case "copper_chest" -> "copper";
case "exposed_copper_chest" -> "copper_exposed";
case "weathered_copper_chest" -> "copper_weathered";
case "oxidized_copper_chest" -> "copper_oxidized";
default -> "normal";
};
}
// Heads are drawn upside down and mirrored in their model, and turn in sixteenths like signs.
private List<Face> head(BlockStateId state, ModelDefinition model) {
boolean onWall = state.name().contains("_wall_");
String kind = state.name().replace("_wall_", "_");
Optional<HeadLook> look = HeadLook.of(kind);
Optional<BlockTexture> texture = look.flatMap(found -> textures.entityTexture(found.texture(), MinecraftBlockTints.NO_TINT));
if (texture.isEmpty()) {
return onWall
? particleBox(state, model, new Vec3(4, 4, 8), new Vec3(12, 12, 16), false)
: particleBox(state, model, new Vec3(4, 0, 4), new Vec3(12, 8, 12), false);
}
Transform place;
if (onWall) {
CubeFace facing = CubeFace.named(state.properties().getOrDefault("facing", "north"));
place = Transform.IDENTITY
.translate(0.5D - facing.stepX() * SKULL_WALL_OFFSET, SKULL_WALL_OFFSET, 0.5D - facing.stepZ() * SKULL_WALL_OFFSET)
.scale(-1D, -1D, 1D)
.rotateY(yRotationOf(facing.opposite().modelName()));
} else {
int rotation = Integer.parseInt(state.properties().getOrDefault("rotation", "0"));
place = Transform.IDENTITY
.translate(0.5D, 0D, 0.5D)
.scale(-1D, -1D, 1D)
.rotateY(rotation * ROTATION_SEGMENT_DEGREES);
}
HeadLook found = look.get();
return modelPartBox(texture.get(), 0, 0, new Vec3(-found.width() / 2D, -8, -4), new Vec3(found.width(), 8, 8), place);
}
private List<Face> banner(BlockStateId state) {
boolean onWall = state.name().endsWith("_wall_banner");
String color = state.name().substring(0, state.name().length() - (onWall ? "_wall_banner" : "_banner").length());
Optional<BlockTexture> frame = textures.entityTexture("entity/banner/banner_base", MinecraftBlockTints.NO_TINT);
Optional<BlockTexture> cloth = textures.entityTexture("entity/banner/base", DYE_COLORS.getOrDefault(color, MinecraftBlockTints.NO_TINT));
if (frame.isEmpty() || cloth.isEmpty()) {
return List.of();
}
Transform place;
if (onWall) {
CubeFace facing = CubeFace.named(state.properties().getOrDefault("facing", "north"));
place = Transform.IDENTITY
.translate(0.5D, -1D / 6D, 0.5D)
.rotateY(-yRotationOf(facing.modelName()))
.translate(0D, -0.3125D, -0.4375D)
.scale(BANNER_SCALE, -BANNER_SCALE, -BANNER_SCALE);
} else {
int rotation = Integer.parseInt(state.properties().getOrDefault("rotation", "0"));
place = Transform.IDENTITY
.translate(0.5D, 0.5D, 0.5D)
.rotateY(-rotation * ROTATION_SEGMENT_DEGREES)
.scale(BANNER_SCALE, -BANNER_SCALE, -BANNER_SCALE);
}
List<Face> faces = new ArrayList<>();
if (!onWall) {
faces.addAll(modelPartBox(frame.get(), 44, 0, new Vec3(-1, -30, -1), new Vec3(2, 42, 2), place));
}
faces.addAll(modelPartBox(frame.get(), 0, 42, new Vec3(-10, -32, -1), new Vec3(20, 2, 2), place));
faces.addAll(modelPartBox(cloth.get(), 0, 0, new Vec3(-10, -32, -2), new Vec3(20, 40, 1), place));
return faces;
}
// Minecraft's facing angle: south is 0 and each quarter turn clockwise seen from above adds 90 degrees.
private static double yRotationOf(String facing) {
return switch (facing) {
case "west" -> 90D;
case "north" -> 180D;
case "east" -> 270D;
default -> 0D;
};
}
/**
* A box of a block entity's model, in model pixels, with its sides laid out on the texture the way Minecraft's
* model parts are: the top and bottom in a row above the four sides.
*/
static List<Face> modelPartBox(BlockTexture texture, int textureU, int textureV, Vec3 from, Vec3 size, Transform place) {
double minX = from.x() / MODEL_UNITS;
double minY = from.y() / MODEL_UNITS;
double minZ = from.z() / MODEL_UNITS;
double maxX = (from.x() + size.x()) / MODEL_UNITS;
double maxY = (from.y() + size.y()) / MODEL_UNITS;
double maxZ = (from.z() + size.z()) / MODEL_UNITS;
Vec3 v0 = new Vec3(minX, minY, minZ);
Vec3 v1 = new Vec3(maxX, minY, minZ);
Vec3 v2 = new Vec3(maxX, maxY, minZ);
Vec3 v3 = new Vec3(minX, maxY, minZ);
Vec3 v4 = new Vec3(minX, minY, maxZ);
Vec3 v5 = new Vec3(maxX, minY, maxZ);
Vec3 v6 = new Vec3(maxX, maxY, maxZ);
Vec3 v7 = new Vec3(minX, maxY, maxZ);
double u = textureU;
double v = textureV;
double width = size.x();
double height = size.y();
double depth = size.z();
List<Face> faces = new ArrayList<>(6);
faces.add(polygon(texture, place, CubeFace.DOWN, v5, v4, v0, u + depth, v, u + depth + width, v + depth));
faces.add(polygon(texture, place, CubeFace.UP, v2, v3, v7, u + depth + width, v + depth, u + depth + width + width, v));
faces.add(polygon(texture, place, CubeFace.WEST, v0, v4, v7, u, v + depth, u + depth, v + depth + height));
faces.add(polygon(texture, place, CubeFace.NORTH, v1, v0, v3, u + depth, v + depth, u + depth + width, v + depth + height));
faces.add(polygon(texture, place, CubeFace.EAST, v5, v1, v2, u + depth + width, v + depth, u + depth + width + depth, v + depth + height));
faces.add(polygon(texture, place, CubeFace.SOUTH, v4, v5, v6, u + depth + width + depth, v + depth, u + depth + width + depth + width, v + depth + height));
return faces;
}
// A model part's polygon gives its first corner (u2, v1), its second (u1, v1) and its third (u1, v2).
private static Face polygon(BlockTexture texture, Transform place, CubeFace side, Vec3 first, Vec3 second, Vec3 third,
double u1, double v1, double u2, double v2) {
double textureWidth = texture.width();
double textureHeight = texture.height();
TextureMapping mapping = new TextureMapping(u1 / textureWidth, v1 / textureHeight,
(u2 - u1) / textureWidth, 0D, 0D, (v2 - v1) / textureHeight);
Face face = new Face(second, first.minus(second), third.minus(second), side.direction(), texture, mapping, side.shade(), null)
.transformed(place);
return face.withShade(CubeFace.nearest(face.normal()).shade());
}
/**
* The entity texture of a mob head and how wide its head is.
*/
private record HeadLook(String texture, double width) {
private static final double HEAD_WIDTH = 8D;
private static final double PIGLIN_HEAD_WIDTH = 10D;
static Optional<HeadLook> of(String kind) {
return Optional.ofNullable(switch (kind) {
case "skeleton_skull" -> new HeadLook("entity/skeleton/skeleton", HEAD_WIDTH);
case "wither_skeleton_skull" -> new HeadLook("entity/skeleton/wither_skeleton", HEAD_WIDTH);
case "zombie_head" -> new HeadLook("entity/zombie/zombie", HEAD_WIDTH);
case "creeper_head" -> new HeadLook("entity/creeper/creeper", HEAD_WIDTH);
case "player_head" -> new HeadLook("entity/player/wide/steve", HEAD_WIDTH);
case "piglin_head" -> new HeadLook("entity/piglin/piglin", PIGLIN_HEAD_WIDTH);
default -> null;
});
}
}
}
@@ -1,81 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.awt.Container;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
/**
* Finds the Swing panels floating over a native window, the way AWT does when it cuts them out of that window. Only
* for the Swing thread.
*/
final class FloatingPanels {
private FloatingPanels() {
}
/**
* A floating panel that hides what lies behind most of it, and only lets it show through some parts.
*/
interface PartlySeeThrough {
/**
* @return where what lies behind shows through, in the panel's own coordinates
*/
List<Rectangle> seeThroughParts();
}
/**
* @return where what the window shows has to show through the panels over it, in the window's coordinates
*/
static List<Rectangle> seeThroughOver(Component window) {
List<Rectangle> parts = new ArrayList<>();
Rectangle windowBounds = new Rectangle(0, 0, window.getWidth(), window.getHeight());
Component child = window;
Container parent = child.getParent();
while (parent != null) {
for (int index = parent.getComponentZOrder(child) - 1; index >= 0; index--) {
Component above = parent.getComponent(index);
if (above.isLightweight() && above.isShowing()) {
addSeeThroughParts(above, window, windowBounds, parts);
}
}
if (!parent.isLightweight()) {
break;
}
child = parent;
parent = parent.getParent();
}
return parts;
}
private static void addSeeThroughParts(Component panel, Component window, Rectangle windowBounds, List<Rectangle> parts) {
List<Rectangle> panelParts = panel instanceof PartlySeeThrough partly
? partly.seeThroughParts()
: List.of(new Rectangle(0, 0, panel.getWidth(), panel.getHeight()));
for (Rectangle part : panelParts) {
Rectangle inWindow = SwingUtilities.convertRectangle(panel, part, window).intersection(windowBounds);
if (!inWindow.isEmpty()) {
parts.add(inWindow);
}
}
}
}
@@ -1,175 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.function.IntConsumer;
/**
* A slim vertical slider floating over the right edge of a 3D view, halfway down, with a short label above it. It
* stays faint so it hides little of the view, until the mouse comes near or it is told to stand out.
*/
final class FloatingSlider extends JPanel {
private static final long serialVersionUID = 4473820211915526120L;
private static final int PANEL_WIDTH = 30;
private static final int MAX_HEIGHT = 320;
private static final double HEIGHT_SHARE_OF_VIEW = 0.5D;
private static final int EDGE_MARGIN = 8;
private static final float FAINT_OPACITY = 0.28F;
private static final String BLANK_LABEL = " ";
private final JSlider slider = new JSlider(SwingConstants.VERTICAL, 0, 1, 1);
private final JLabel label = new JLabel(BLANK_LABEL, SwingConstants.CENTER);
private boolean movingQuietly;
private boolean hovered;
private boolean standingOut;
/**
* @param onMoved told the slider's value whenever the user moves it
*/
FloatingSlider(String tooltip, IntConsumer onMoved) {
super(new BorderLayout(0, StudioTheme.scale(4)));
setOpaque(false);
setToolTipText(tooltip);
label.setFont(StudioTheme.smallFont());
label.setForeground(StudioTheme.SECONDARY_TEXT);
slider.setOpaque(false);
slider.setFocusable(false);
slider.setToolTipText(tooltip);
slider.addChangeListener(event -> {
if (!movingQuietly) {
onMoved.accept(slider.getValue());
}
});
MouseAdapter hover = new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent event) {
setHovered(true);
}
@Override
public void mouseExited(MouseEvent event) {
setHovered(slider.getValueIsAdjusting());
}
@Override
public void mouseReleased(MouseEvent event) {
setHovered(slider.contains(event.getPoint()));
}
};
slider.addMouseListener(hover);
addMouseListener(hover);
add(label, BorderLayout.NORTH);
add(slider, BorderLayout.CENTER);
}
/**
* The view with this slider floating over its right edge, halfway down.
*/
JComponent floatingOver(JComponent view) {
FloatingSlider floating = this;
JPanel stack = new JPanel(null) {
private static final long serialVersionUID = -1950381405658102347L;
// The slider overlaps the view, so the view may not repaint without the slider on top of it.
@Override
public boolean isOptimizedDrawingEnabled() {
return false;
}
@Override
public void doLayout() {
view.setBounds(0, 0, getWidth(), getHeight());
int width = StudioTheme.scale(PANEL_WIDTH);
int height = Math.min(StudioTheme.scale(MAX_HEIGHT), (int) (getHeight() * HEIGHT_SHARE_OF_VIEW));
floating.setBounds(getWidth() - width - StudioTheme.scale(EDGE_MARGIN), (getHeight() - height) / 2, width, height);
}
};
stack.add(floating);
stack.add(view);
return stack;
}
/**
* Shows a range and value the user didn't choose, without telling anyone the slider moved.
*/
void showQuietly(int minimum, int maximum, int value) {
movingQuietly = true;
try {
slider.getModel().setRangeProperties(value, 0, minimum, maximum, false);
} finally {
movingQuietly = false;
}
}
// Moves the slider as if the user had.
void moveBy(int steps) {
slider.setValue(slider.getValue() + steps);
}
int value() {
return slider.getValue();
}
int maximum() {
return slider.getMaximum();
}
void showLabel(String text) {
label.setText(text.isEmpty() ? BLANK_LABEL : text);
repaint();
}
void setStandingOut(boolean nowStandingOut) {
if (standingOut != nowStandingOut) {
standingOut = nowStandingOut;
repaint();
}
}
@Override
protected void paintChildren(Graphics graphics) {
Graphics2D canvas = (Graphics2D) graphics.create();
try {
if (!hovered && !standingOut) {
canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, FAINT_OPACITY));
}
super.paintChildren(canvas);
} finally {
canvas.dispose();
}
}
private void setHovered(boolean nowHovered) {
if (hovered != nowHovered) {
hovered = nowHovered;
repaint();
}
}
}
@@ -1,103 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import javax.swing.Timer;
import java.util.concurrent.TimeUnit;
/**
* Keeps the last frame of what the explorer showed before on screen while the next thing loads, then fades it out over
* the first frame of the new one, so switching never shows an empty view in between.
*/
final class FrameCrossfade {
private static final long FADE_NANOS = TimeUnit.MILLISECONDS.toNanos(70L);
private static final int REPAINT_INTERVAL_MILLIS = 16;
private final Timer repaintTimer;
private Phase phase = Phase.NONE;
private NoiseRenderCoordinator.Result outgoing;
private long fadeStartedNanos;
FrameCrossfade(Runnable repaint) {
this.repaintTimer = new Timer(REPAINT_INTERVAL_MILLIS, event -> {
outgoing();
repaint.run();
});
}
/**
* Keeps showing the frame until the next one arrives. Without a frame, as when the switch before hasn't drawn yet,
* the frame already held stays.
*/
void hold(NoiseRenderCoordinator.Result frame) {
if (frame == null && outgoing != null) {
enter(Phase.HOLDING, outgoing);
return;
}
enter(frame == null ? Phase.NONE : Phase.HOLDING, frame);
}
/**
* The new frame is in, so the held one starts fading out over it.
*/
void reveal() {
if (phase != Phase.HOLDING) {
return;
}
fadeStartedNanos = System.nanoTime();
phase = Phase.FADING;
repaintTimer.start();
}
void clear() {
enter(Phase.NONE, null);
}
/**
* @return the frame to draw over the current one, or null when there is none
*/
NoiseRenderCoordinator.Result outgoing() {
if (phase == Phase.FADING && fadedShare() >= 1F) {
clear();
}
return outgoing;
}
float outgoingOpacity() {
return phase == Phase.FADING ? 1F - fadedShare() : 1F;
}
private float fadedShare() {
return Math.min(1F, (System.nanoTime() - fadeStartedNanos) / (float) FADE_NANOS);
}
private void enter(Phase nextPhase, NoiseRenderCoordinator.Result frame) {
phase = nextPhase;
outgoing = frame;
if (nextPhase != Phase.FADING) {
repaintTimer.stop();
}
}
private enum Phase {
NONE,
HOLDING,
FADING
}
}
@@ -1,64 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import javax.swing.JComponent;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
/**
* How many frames a second a 3D view keeps up, right-aligned, floating over the view.
*/
final class FrameRateLabel extends JComponent {
private static final long serialVersionUID = -6402187316475095871L;
private static final String WIDEST_TEXT = "8888 fps";
private String text = "";
FrameRateLabel() {
setOpaque(false);
}
void showRate(double framesPerSecond) {
String next = Math.round(framesPerSecond) + " fps";
if (!next.equals(text)) {
text = next;
repaint();
}
}
@Override
public Dimension getPreferredSize() {
FontMetrics metrics = getFontMetrics(StudioTheme.smallFont());
return new Dimension(metrics.stringWidth(WIDEST_TEXT), metrics.getHeight());
}
@Override
protected void paintComponent(Graphics graphics) {
Graphics2D canvas = (Graphics2D) graphics;
canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
canvas.setFont(StudioTheme.smallFont());
canvas.setColor(StudioTheme.MUTED_TEXT);
FontMetrics metrics = canvas.getFontMetrics();
canvas.drawString(text, getWidth() - metrics.stringWidth(text), metrics.getAscent());
}
}
@@ -1,381 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import art.arcane.iris.spi.IrisLogging;
import org.lwjgl.PointerBuffer;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GLXCapabilities;
import org.lwjgl.system.Callback;
import org.lwjgl.system.CallbackI;
import org.lwjgl.system.Configuration;
import org.lwjgl.system.JNI;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.linux.DynamicLinkLoader;
import org.lwjgl.system.linux.X11;
import org.lwjgl.system.linux.XErrorEvent;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.lang.invoke.MethodHandles;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import static org.lwjgl.opengl.GL11.GL_RENDERER;
import static org.lwjgl.opengl.GL11.glGetString;
import static org.lwjgl.opengl.GLX.glXDestroyContext;
import static org.lwjgl.opengl.GLX.glXMakeCurrent;
import static org.lwjgl.opengl.GLX.glXSwapBuffers;
import static org.lwjgl.opengl.GLX13.GLX_BLUE_SIZE;
import static org.lwjgl.opengl.GLX13.GLX_DEPTH_SIZE;
import static org.lwjgl.opengl.GLX13.GLX_DOUBLEBUFFER;
import static org.lwjgl.opengl.GLX13.GLX_DRAWABLE_TYPE;
import static org.lwjgl.opengl.GLX13.GLX_GREEN_SIZE;
import static org.lwjgl.opengl.GLX13.GLX_RED_SIZE;
import static org.lwjgl.opengl.GLX13.GLX_RENDER_TYPE;
import static org.lwjgl.opengl.GLX13.GLX_RGBA_BIT;
import static org.lwjgl.opengl.GLX13.GLX_VISUAL_ID;
import static org.lwjgl.opengl.GLX13.GLX_WINDOW_BIT;
import static org.lwjgl.opengl.GLX13.GLX_X_RENDERABLE;
import static org.lwjgl.opengl.GLX13.glXChooseFBConfig;
import static org.lwjgl.opengl.GLX13.glXGetFBConfigAttrib;
import static org.lwjgl.opengl.GLX13.glXMakeContextCurrent;
import static org.lwjgl.opengl.GLXARBCreateContext.GLX_CONTEXT_MAJOR_VERSION_ARB;
import static org.lwjgl.opengl.GLXARBCreateContext.GLX_CONTEXT_MINOR_VERSION_ARB;
import static org.lwjgl.opengl.GLXARBCreateContext.glXCreateContextAttribsARB;
import static org.lwjgl.opengl.GLXARBCreateContextProfile.GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
import static org.lwjgl.opengl.GLXARBCreateContextProfile.GLX_CONTEXT_PROFILE_MASK_ARB;
import static org.lwjgl.opengl.GLXEXTSwapControl.glXSwapIntervalEXT;
import static org.lwjgl.system.APIUtil.apiClosureRet;
import static org.lwjgl.system.APIUtil.apiCreateCIF;
import static org.lwjgl.system.MemoryUtil.NULL;
import static org.lwjgl.system.MemoryUtil.memAddress;
import static org.lwjgl.system.MemoryUtil.memGetAddress;
import static org.lwjgl.system.libffi.LibFFI.ffi_type_pointer;
import static org.lwjgl.system.libffi.LibFFI.ffi_type_sint32;
/**
* A connection of our own to the X server Swing's windows are on, with one OpenGL context that draws straight into
* those windows, so a frame never has to be copied back and painted by Swing. Only for the GPU thread.
*/
final class GlxDisplay {
private static final String X11_TOOLKIT = "sun.awt.X11.XToolkit";
private static final String NATIVE_CONTEXT_API = "native";
private static final String NVIDIA_DRIVER_VERSION_FILE = "/proc/driver/nvidia/version";
private static final Set<String> SOFTWARE_RENDERERS = Set.of("llvmpipe", "softpipe", "software rasterizer");
private static final int OPENGL_MAJOR_VERSION = 3;
private static final int OPENGL_MINOR_VERSION = 3;
private static final int COLOR_CHANNEL_BITS = 8;
private static final int DEPTH_BITS = 24;
// Frames are only drawn when something moves, and the compositor keeps them from tearing.
private static final int SWAP_EVERY_FRAME = 0;
private final long display;
private final long context;
private final long visualId;
private final boolean canSetSwapInterval;
private final Set<Long> windowsWithSwapIntervalSet = new HashSet<>();
private final String renderer;
private long currentWindow;
private GlxDisplay(long display, long context, long visualId, boolean canSetSwapInterval, String renderer) {
this.display = display;
this.context = context;
this.visualId = visualId;
this.canSetSwapInterval = canSetSwapInterval;
this.renderer = renderer;
}
/**
* Opens the connection and makes its context current on this thread, without any window yet.
*
* @throws IllegalStateException when Swing doesn't draw on X or no card there draws OpenGL 3.3 in hardware
*/
static GlxDisplay open() {
if (!isSwingOnX()) {
throw new IllegalStateException("Swing doesn't draw on X");
}
preferNvidiaCard();
// LWJGL would take EGL in a Wayland session, even though Swing's windows are on X.
Configuration.OPENGL_CONTEXT_API.set(NATIVE_CONTEXT_API);
GL.create();
long display = X11.nXOpenDisplay(NULL);
if (display == NULL) {
GL.destroy();
throw new IllegalStateException("Can't connect to the X server");
}
XErrors.watch(display);
try {
return openOn(display);
} catch (RuntimeException failure) {
XErrors.forget(display);
X11.XCloseDisplay(display);
GL.destroy();
throw failure;
}
}
static boolean isSwingOnX() {
return !GraphicsEnvironment.isHeadless() && X11_TOOLKIT.equals(Toolkit.getDefaultToolkit().getClass().getName());
}
private static GlxDisplay openOn(long display) {
int screen = X11.XDefaultScreen(display);
GLXCapabilities glx = GL.createCapabilitiesGLX(display, screen);
if (!glx.GLX13 || !glx.GLX_ARB_create_context || !glx.GLX_ARB_create_context_profile) {
throw new IllegalStateException("GLX can't make an OpenGL " + OPENGL_MAJOR_VERSION + "." + OPENGL_MINOR_VERSION + " context");
}
long visualId = Xlib.defaultVisualId(display, screen);
long config = configFor(display, screen, visualId);
long context = glXCreateContextAttribsARB(display, config, NULL, true, new int[]{
GLX_CONTEXT_MAJOR_VERSION_ARB, OPENGL_MAJOR_VERSION,
GLX_CONTEXT_MINOR_VERSION_ARB, OPENGL_MINOR_VERSION,
GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
0});
Xlib.sync(display);
if (context == NULL || XErrors.takeFailed(display)) {
throw new IllegalStateException("GLX can't make an OpenGL " + OPENGL_MAJOR_VERSION + "." + OPENGL_MINOR_VERSION + " context");
}
if (!glXMakeContextCurrent(display, NULL, NULL, context)) {
glXDestroyContext(display, context);
throw new IllegalStateException("GLX can't use a context without a window");
}
GL.createCapabilities();
String renderer = glGetString(GL_RENDERER);
if (isDrawnInSoftware(renderer)) {
glXMakeContextCurrent(display, NULL, NULL, NULL);
glXDestroyContext(display, context);
throw new IllegalStateException("GLX only draws in software, on " + renderer);
}
return new GlxDisplay(display, context, visualId, glx.GLX_EXT_swap_control, renderer);
}
/**
* Laptops show X on the built-in card and only lend the faster one out when asked to. Asked the way NVIDIA's own
* prime-run does, unless whoever started the server asked for something else already.
*/
private static void preferNvidiaCard() {
if (!Files.exists(Path.of(NVIDIA_DRIVER_VERSION_FILE))) {
return;
}
LibC.setenvUnlessSet("__NV_PRIME_RENDER_OFFLOAD", "1");
LibC.setenvUnlessSet("__GLX_VENDOR_LIBRARY_NAME", "nvidia");
}
// Windows are only drawn into with the visual they were made with; Swing makes them with the screen's default one.
private static long configFor(long display, int screen, long visualId) {
PointerBuffer configs = glXChooseFBConfig(display, screen, new int[]{
GLX_X_RENDERABLE, 1,
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DOUBLEBUFFER, 1,
GLX_RED_SIZE, COLOR_CHANNEL_BITS,
GLX_GREEN_SIZE, COLOR_CHANNEL_BITS,
GLX_BLUE_SIZE, COLOR_CHANNEL_BITS,
GLX_DEPTH_SIZE, DEPTH_BITS,
0});
if (configs == null) {
throw new IllegalStateException("GLX has no double-buffered config with a depth buffer");
}
try {
int[] configVisual = new int[1];
for (int index = 0; index < configs.remaining(); index++) {
long config = configs.get(index);
glXGetFBConfigAttrib(display, config, GLX_VISUAL_ID, configVisual);
if (configVisual[0] == visualId) {
return config;
}
}
} finally {
X11.XFree(configs);
}
throw new IllegalStateException("GLX can't draw into windows of the default visual 0x" + Long.toHexString(visualId));
}
private static boolean isDrawnInSoftware(String renderer) {
String lowerCase = renderer == null ? "" : renderer.toLowerCase(Locale.ROOT);
return SOFTWARE_RENDERERS.stream().anyMatch(lowerCase::contains);
}
String renderer() {
return renderer;
}
boolean canDrawInto(long windowVisualId) {
return windowVisualId == visualId;
}
/**
* Makes the window what the default framebuffer draws into.
*
* @return false when the window can't be drawn into
*/
boolean drawInto(long window) {
if (window == currentWindow) {
return true;
}
boolean madeCurrent = glXMakeCurrent(display, window, context);
Xlib.sync(display);
if (!madeCurrent || XErrors.takeFailed(display)) {
currentWindow = NULL;
return false;
}
currentWindow = window;
if (canSetSwapInterval && windowsWithSwapIntervalSet.add(window)) {
glXSwapIntervalEXT(display, window, SWAP_EVERY_FRAME);
}
return true;
}
/**
* Puts what was drawn into the window on screen.
*
* @return false when the window couldn't take it, or something drawn into it before failed
*/
boolean show(long window) {
glXSwapBuffers(display, window);
return !XErrors.takeFailed(display);
}
/**
* Stops drawing into a window before it goes away, keeping the context for the rest.
*/
void forget(long window) {
windowsWithSwapIntervalSet.remove(window);
if (window != currentWindow) {
return;
}
glXMakeContextCurrent(display, NULL, NULL, context);
currentWindow = NULL;
Xlib.sync(display);
XErrors.takeFailed(display);
}
/**
* Destroys the context and the connection. Nothing is drawn through this display afterwards.
*/
void close() {
glXMakeContextCurrent(display, NULL, NULL, NULL);
glXDestroyContext(display, context);
currentWindow = NULL;
windowsWithSwapIntervalSet.clear();
Xlib.sync(display);
XErrors.forget(display);
X11.XCloseDisplay(display);
}
/**
* Notes X errors on our own connection instead of letting Xlib end the process over them, which is what it does
* for any connection but Swing's. Errors on other connections go wherever they went before.
*/
private static final class XErrors {
private static final Set<Long> watchedDisplays = ConcurrentHashMap.newKeySet();
private static final Set<Long> failedDisplays = ConcurrentHashMap.newKeySet();
private static long previousHandler;
private static ErrorHandler handler;
static synchronized void watch(long display) {
if (handler == null) {
handler = XErrors::handle;
previousHandler = Xlib.setErrorHandler(handler.address());
}
watchedDisplays.add(display);
}
static void forget(long display) {
watchedDisplays.remove(display);
failedDisplays.remove(display);
}
static boolean takeFailed(long display) {
return failedDisplays.remove(display);
}
private static int handle(long display, long errorEvent) {
if (watchedDisplays.contains(display)) {
failedDisplays.add(display);
IrisLogging.debug("X error " + Byte.toUnsignedInt(XErrorEvent.create(errorEvent).error_code()) + " drawing a 3D view");
return 0;
}
return previousHandler == NULL ? 0 : JNI.callPPI(display, errorEvent, previousHandler);
}
}
@FunctionalInterface
private interface ErrorHandler extends CallbackI {
Callback.Descriptor DESCRIPTOR = new Callback.Descriptor(ErrorHandler.class, MethodHandles.lookup(),
apiCreateCIF(ffi_type_sint32, ffi_type_pointer, ffi_type_pointer));
@Override
default Callback.Descriptor getDescriptor() {
return DESCRIPTOR;
}
@Override
default void callback(long ret, long args) {
apiClosureRet(ret, invoke(memGetAddress(memGetAddress(args)), memGetAddress(memGetAddress(args + Long.BYTES))));
}
int invoke(long display, long errorEvent);
}
// The few Xlib calls LWJGL has no binding for.
private static final class Xlib {
static long defaultVisualId(long display, int screen) {
long visual = JNI.callPP(display, screen, function("XDefaultVisual"));
return JNI.callPP(visual, function("XVisualIDFromVisual"));
}
static void sync(long display) {
JNI.callPI(display, 0, function("XSync"));
}
static long setErrorHandler(long handler) {
return JNI.callPP(handler, function("XSetErrorHandler"));
}
private static long function(String name) {
long address = X11.getLibrary().getFunctionAddress(name);
if (address == NULL) {
throw new IllegalStateException("Xlib has no " + name);
}
return address;
}
}
private static final class LibC {
private static final int KEEP_EXISTING = 0;
private static final long EVERYTHING_LOADED = NULL;
// Looked up among everything the process loaded, which LWJGL's own dlsym won't do.
static void setenvUnlessSet(String name, String value) {
try (MemoryStack stack = MemoryStack.stackPush()) {
long setenv = DynamicLinkLoader.ndlsym(EVERYTHING_LOADED, memAddress(stack.ASCII("setenv")));
if (setenv == NULL) {
return;
}
JNI.callPPI(memAddress(stack.ASCII(name)), memAddress(stack.ASCII(value)), KEEP_EXISTING, setenv);
}
}
}
}
@@ -1,106 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* What was put on the graphics card, by what it was made from. The sources are held weakly: once nothing else keeps
* one, its upload can never be asked for again and is deleted. Only for the GPU thread.
*/
final class GpuCache<U extends GpuCache.Upload> {
private final LinkedHashMap<Source, U> leastRecentlyUsedFirst = new LinkedHashMap<>(16, 0.75F, true);
private final ReferenceQueue<Object> collectedSources = new ReferenceQueue<>();
U get(Object source) {
return leastRecentlyUsedFirst.get(Source.lookingFor(source));
}
void put(Object source, U upload) {
leastRecentlyUsedFirst.put(new Source(source, collectedSources), upload);
}
void forgetCollected() {
for (Reference<?> collected = collectedSources.poll(); collected != null; collected = collectedSources.poll()) {
U upload = leastRecentlyUsedFirst.remove(collected);
if (upload != null) {
upload.delete();
}
}
}
/**
* Deletes the least recently used uploads until the cache fits, sparing those made from what is kept.
*/
void forgetBeyond(long mostBytes, Set<Object> kept) {
long bytes = 0L;
for (U upload : leastRecentlyUsedFirst.values()) {
bytes += upload.bytes();
}
Iterator<Map.Entry<Source, U>> oldestFirst = leastRecentlyUsedFirst.entrySet().iterator();
while (bytes > mostBytes && oldestFirst.hasNext()) {
Map.Entry<Source, U> entry = oldestFirst.next();
if (!kept.contains(entry.getKey().get())) {
bytes -= entry.getValue().bytes();
entry.getValue().delete();
oldestFirst.remove();
}
}
}
interface Upload {
long bytes();
void delete();
}
// Equal only to a source of the same object, so a collected one is equal to nothing but itself.
private static final class Source extends WeakReference<Object> {
private final int identityHash;
private Source(Object source, ReferenceQueue<Object> collected) {
super(source, collected);
identityHash = System.identityHashCode(source);
}
static Source lookingFor(Object source) {
return new Source(source, null);
}
@Override
public int hashCode() {
return identityHash;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
Object source = get();
return source != null && other instanceof Source otherSource && source == otherSource.get();
}
}
}
@@ -1,187 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.jawt.JAWT;
import org.lwjgl.system.jawt.JAWTDrawingSurface;
import org.lwjgl.system.jawt.JAWTDrawingSurfaceInfo;
import org.lwjgl.system.jawt.JAWTX11DrawingSurfaceInfo;
import javax.swing.SwingUtilities;
import java.awt.Canvas;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_DrawingSurface_FreeDrawingSurfaceInfo;
import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_DrawingSurface_GetDrawingSurfaceInfo;
import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_DrawingSurface_Lock;
import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_DrawingSurface_Unlock;
import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_FreeDrawingSurface;
import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_GetAWT;
import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_GetDrawingSurface;
import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_LOCK_ERROR;
import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_VERSION_1_4;
/**
* A native window inside a 3D view that the graphics card draws frames straight into. Swing can't paint over it, so
* panels floating over the view are cut out of it, and the view paints what lies behind them itself. The mouse belongs
* to the view behind it, as if this window weren't there.
*/
final class GpuCanvas extends Canvas {
private static final long serialVersionUID = 2874650379461920137L;
private final transient Component view;
private final transient Runnable onExposed;
private volatile long window;
private volatile long visualId;
/**
* @param onExposed runs on the Swing thread when what the window showed was lost and has to be drawn again
*/
GpuCanvas(Component view, Runnable onExposed) {
this.view = view;
this.onExposed = onExposed;
setFocusable(false);
setBackground(StudioTheme.EDITOR_BACKGROUND);
handMouseToView();
}
/**
* @return the X window frames go into, or 0 while there is none
*/
long window() {
return window;
}
long visualId() {
return visualId;
}
@Override
public void addNotify() {
super.addNotify();
readNativeWindow();
}
// A frame on its way into the window would otherwise draw into one that no longer exists.
@Override
public void removeNotify() {
long goingWindow = window;
window = 0L;
if (goingWindow != 0L) {
GpuContext.forgetWindow(goingWindow);
}
super.removeNotify();
}
// Erasing to the background first would flash it between frames.
@Override
public void update(Graphics graphics) {
onExposed.run();
}
@Override
public void paint(Graphics graphics) {
onExposed.run();
}
private void readNativeWindow() {
try (MemoryStack stack = MemoryStack.stackPush()) {
JAWT awt = JAWT.calloc(stack).version(JAWT_VERSION_1_4);
if (!JAWT_GetAWT(awt)) {
return;
}
JAWTDrawingSurface surface = JAWT_GetDrawingSurface(this, awt.GetDrawingSurface());
if (surface == null) {
return;
}
try {
readLocked(surface);
} finally {
JAWT_FreeDrawingSurface(surface, awt.FreeDrawingSurface());
}
}
}
private void readLocked(JAWTDrawingSurface surface) {
if ((JAWT_DrawingSurface_Lock(surface, surface.Lock()) & JAWT_LOCK_ERROR) != 0) {
return;
}
try {
JAWTDrawingSurfaceInfo info = JAWT_DrawingSurface_GetDrawingSurfaceInfo(surface, surface.GetDrawingSurfaceInfo());
if (info == null) {
return;
}
try {
JAWTX11DrawingSurfaceInfo x11 = JAWTX11DrawingSurfaceInfo.create(info.platformInfo());
visualId = x11.visualID();
window = x11.drawable();
} finally {
JAWT_DrawingSurface_FreeDrawingSurfaceInfo(info, surface.FreeDrawingSurfaceInfo());
}
} finally {
JAWT_DrawingSurface_Unlock(surface, surface.Unlock());
}
}
private void handMouseToView() {
MouseAdapter handOver = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent event) {
handOver(event);
}
@Override
public void mouseReleased(MouseEvent event) {
handOver(event);
}
@Override
public void mouseClicked(MouseEvent event) {
handOver(event);
}
@Override
public void mouseDragged(MouseEvent event) {
handOver(event);
}
@Override
public void mouseMoved(MouseEvent event) {
handOver(event);
}
@Override
public void mouseWheelMoved(MouseWheelEvent event) {
handOver(event);
}
};
addMouseListener(handOver);
addMouseMotionListener(handOver);
addMouseWheelListener(handOver);
}
private void handOver(MouseEvent event) {
view.dispatchEvent(SwingUtilities.convertMouseEvent(this, event, view));
}
}
@@ -1,75 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import static org.lwjgl.opengl.GL12.GL_BGRA;
import static org.lwjgl.opengl.GL12.GL_NEAREST;
import static org.lwjgl.opengl.GL12.GL_RGBA8;
import static org.lwjgl.opengl.GL12.GL_TEXTURE_2D;
import static org.lwjgl.opengl.GL12.GL_TEXTURE_MAG_FILTER;
import static org.lwjgl.opengl.GL12.GL_TEXTURE_MIN_FILTER;
import static org.lwjgl.opengl.GL12.GL_UNSIGNED_INT_8_8_8_8_REV;
import static org.lwjgl.opengl.GL12.glBindTexture;
import static org.lwjgl.opengl.GL12.glDeleteTextures;
import static org.lwjgl.opengl.GL12.glGenTextures;
import static org.lwjgl.opengl.GL12.glTexImage2D;
import static org.lwjgl.opengl.GL12.glTexParameteri;
/**
* Terrain's column colours on the graphics card, one texel per column, so faces running over many columns still colour
* each one. Only for the GPU thread.
*/
final class GpuColors {
private static final int BYTES_PER_COLUMN = 4;
private final int texture = glGenTextures();
private final long bytes;
private GpuColors(NoiseTerrain terrain) {
this.bytes = (long) terrain.columns() * terrain.rows() * BYTES_PER_COLUMN;
}
/**
* @param largestSide the card's GL_MAX_TEXTURE_SIZE
* @return the colours, or null when the terrain has more columns or rows than the card's textures can hold
*/
static GpuColors upload(NoiseTerrain terrain, int largestSide) {
if (terrain.columns() > largestSide || terrain.rows() > largestSide) {
return null;
}
GpuColors uploaded = new GpuColors(terrain);
glBindTexture(GL_TEXTURE_2D, uploaded.texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, terrain.columns(), terrain.rows(), 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, terrain.colors());
return uploaded;
}
long bytes() {
return bytes;
}
void bind() {
glBindTexture(GL_TEXTURE_2D, texture);
}
void delete() {
glDeleteTextures(texture);
}
}
@@ -1,301 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.studio.view.GuiHost;
import org.lwjgl.PointerBuffer;
import org.lwjgl.egl.EGL;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.Configuration;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.lwjgl.egl.EGL15.EGL_CONTEXT_MAJOR_VERSION;
import static org.lwjgl.egl.EGL15.EGL_CONTEXT_MINOR_VERSION;
import static org.lwjgl.egl.EGL15.EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT;
import static org.lwjgl.egl.EGL15.EGL_CONTEXT_OPENGL_PROFILE_MASK;
import static org.lwjgl.egl.EGL15.EGL_EXTENSIONS;
import static org.lwjgl.egl.EGL15.EGL_NONE;
import static org.lwjgl.egl.EGL15.EGL_NO_CONTEXT;
import static org.lwjgl.egl.EGL15.EGL_NO_DISPLAY;
import static org.lwjgl.egl.EGL15.EGL_NO_SURFACE;
import static org.lwjgl.egl.EGL15.EGL_OPENGL_API;
import static org.lwjgl.egl.EGL15.EGL_OPENGL_BIT;
import static org.lwjgl.egl.EGL15.EGL_PBUFFER_BIT;
import static org.lwjgl.egl.EGL15.EGL_RENDERABLE_TYPE;
import static org.lwjgl.egl.EGL15.EGL_SURFACE_TYPE;
import static org.lwjgl.egl.EGL15.eglBindAPI;
import static org.lwjgl.egl.EGL15.eglChooseConfig;
import static org.lwjgl.egl.EGL15.eglCreateContext;
import static org.lwjgl.egl.EGL15.eglDestroyContext;
import static org.lwjgl.egl.EGL15.eglInitialize;
import static org.lwjgl.egl.EGL15.eglMakeCurrent;
import static org.lwjgl.egl.EGL15.eglQueryString;
import static org.lwjgl.egl.EGL15.eglReleaseThread;
import static org.lwjgl.egl.EGL15.eglTerminate;
import static org.lwjgl.egl.EXTDeviceEnumeration.eglQueryDevicesEXT;
import static org.lwjgl.egl.EXTDeviceQuery.eglQueryDeviceStringEXT;
import static org.lwjgl.egl.EXTPlatformBase.eglGetPlatformDisplayEXT;
import static org.lwjgl.egl.EXTPlatformDevice.EGL_PLATFORM_DEVICE_EXT;
import static org.lwjgl.opengl.GL11.GL_RENDERER;
import static org.lwjgl.opengl.GL11.glGetString;
/**
* An OpenGL context on a graphics card, and the one thread allowed to use it. Where Swing draws on X, the context draws
* straight into Swing's windows through GLX. Anywhere else, or when GLX only draws in software, it is made through
* EGL without any window: EGL lists the cards and the first one that isn't drawn in software is taken.
*/
final class GpuContext {
private static final String THREAD_NAME = "Iris GPU";
private static final long RELEASE_WAIT_SECONDS = 5L;
private static final int OPENGL_MAJOR_VERSION = 3;
private static final int OPENGL_MINOR_VERSION = 3;
private static final String SOFTWARE_DEVICE_EXTENSION = "EGL_MESA_device_software";
private static final Set<String> REQUIRED_CLIENT_EXTENSIONS = Set.of("EGL_EXT_device_enumeration", "EGL_EXT_device_query",
"EGL_EXT_platform_base", "EGL_EXT_platform_device");
private static volatile GpuContext shared;
private static boolean unavailable;
private final ExecutorService thread = Executors.newSingleThreadExecutor(runnable -> {
Thread gpuThread = new Thread(runnable, THREAD_NAME);
gpuThread.setDaemon(true);
return gpuThread;
});
private String renderer;
private GlxDisplay windows;
private volatile boolean drawsIntoWindows;
private long eglDisplay = EGL_NO_DISPLAY;
private long eglContext = EGL_NO_CONTEXT;
private GpuContext() {
}
/**
* Whether frames can go straight into windows, as far as is known without opening the context.
*/
static boolean drawsIntoWindows() {
GpuContext context = shared;
return context != null && context.drawsIntoWindows;
}
/**
* Only for the context's thread.
*
* @return the connection drawing into windows, or nothing when frames are only drawn off screen
*/
Optional<GlxDisplay> windows() {
return drawsIntoWindows ? Optional.of(windows) : Optional.empty();
}
/**
* Stops drawing into a window about to be destroyed, waiting for a frame going into it to finish first.
*/
static void forgetWindow(long window) {
GpuContext context = shared;
if (context == null || context.windows == null) {
return;
}
try {
context.call(() -> {
context.windows.forget(window);
return null;
});
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
} catch (RuntimeException failure) {
IrisLogging.reportError(failure);
}
}
// Off-screen frames still work in the same context, read back like on a machine without GLX.
void stopDrawingIntoWindows(RuntimeException failure) {
if (!drawsIntoWindows) {
return;
}
drawsIntoWindows = false;
IrisLogging.reportError(failure);
IrisLogging.warn("3D views stop drawing straight into windows: %s", failure.getMessage());
}
/**
* @return the context every view shares, opened on first use, or nothing when this machine has no usable card
*/
static synchronized Optional<GpuContext> shared() {
if (shared == null && !unavailable) {
shared = open();
unavailable = shared == null;
}
return Optional.ofNullable(shared);
}
private static GpuContext open() {
GpuContext context = new GpuContext();
try {
context.thread.submit(context::openOnCard).get();
IrisLogging.info(context.drawsIntoWindows ? "3D views draw on %s, straight into their windows" : "3D views draw on %s",
context.renderer);
releaseOnShutdown();
return context;
} catch (ExecutionException failure) {
IrisLogging.warn("3D views draw without a graphics card: %s", failure.getCause());
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
}
context.thread.shutdownNow();
return null;
}
// NVIDIA's driver crashes the JVM on its way out when a context is still current on some thread.
private static void releaseOnShutdown() {
GuiHost.runAtShutdown(GpuContext::releaseShared);
}
/**
* Lets go of the card once frames already asked for are drawn. Frames asked for later are drawn without it.
*/
static synchronized void releaseShared() {
GpuContext context = shared;
if (context == null) {
return;
}
context.thread.execute(context::release);
context.thread.shutdown();
try {
if (!context.thread.awaitTermination(RELEASE_WAIT_SECONDS, TimeUnit.SECONDS)) {
IrisLogging.warn("3D views didn't let go of the graphics card in time");
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
}
}
private void release() {
drawsIntoWindows = false;
if (windows != null) {
windows.close();
return;
}
eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroyContext(eglDisplay, eglContext);
eglTerminate(eglDisplay);
eglReleaseThread();
}
/**
* Runs {@code work} on the context's thread and waits for it.
*/
<T> T call(Callable<T> work) throws InterruptedException {
try {
return thread.submit(work).get();
} catch (ExecutionException failure) {
throw new IllegalStateException("Drawing on the graphics card failed", failure.getCause());
}
}
// GL would otherwise look for a GLX library as soon as it loads, which a context from EGL doesn't use.
private Void openOnCard() {
Configuration.OPENGL_EXPLICIT_INIT.set(true);
try {
windows = GlxDisplay.open();
renderer = windows.renderer();
drawsIntoWindows = true;
return null;
} catch (RuntimeException | LinkageError noWindows) {
IrisLogging.info("3D views can't draw straight into windows: %s", noWindows);
}
openWithoutWindows();
return null;
}
private void openWithoutWindows() {
if (!canListDevices()) {
throw new IllegalStateException("EGL can't list graphics cards");
}
GL.create(EGL.getFunctionProvider());
for (long device : devices()) {
if (!isDrawnInSoftware(device) && makeCurrentOn(device)) {
GL.createCapabilities();
renderer = glGetString(GL_RENDERER);
return;
}
}
throw new IllegalStateException("No graphics card supports OpenGL " + OPENGL_MAJOR_VERSION + "." + OPENGL_MINOR_VERSION);
}
// LWJGL's own capability flags read false for these even where the library has them, so the list is asked for.
private static boolean canListDevices() {
String extensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
return extensions != null && Arrays.asList(extensions.split(" ")).containsAll(REQUIRED_CLIENT_EXTENSIONS);
}
private static long[] devices() {
int[] count = new int[1];
eglQueryDevicesEXT(null, count);
PointerBuffer found = PointerBuffer.allocateDirect(count[0]);
eglQueryDevicesEXT(found, count);
long[] devices = new long[count[0]];
for (int device = 0; device < devices.length; device++) {
devices[device] = found.get(device);
}
return devices;
}
private static boolean isDrawnInSoftware(long device) {
String extensions = eglQueryDeviceStringEXT(device, EGL_EXTENSIONS);
return extensions != null && extensions.contains(SOFTWARE_DEVICE_EXTENSION);
}
// Nothing is drawn to a surface, only to framebuffers of the context's own, so the context needs none. Configs
// default to window surfaces, which a card without a display has none of.
private boolean makeCurrentOn(long device) {
long display = eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, device, (int[]) null);
if (display == EGL_NO_DISPLAY || !eglInitialize(display, new int[1], new int[1])) {
return false;
}
PointerBuffer config = PointerBuffer.allocateDirect(1);
int[] configCount = new int[1];
int[] wanted = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_NONE};
if (!eglChooseConfig(display, wanted, config, configCount) || configCount[0] == 0
|| !eglBindAPI(EGL_OPENGL_API)) {
eglTerminate(display);
return false;
}
long context = eglCreateContext(display, config.get(0), EGL_NO_CONTEXT, new int[]{
EGL_CONTEXT_MAJOR_VERSION, OPENGL_MAJOR_VERSION,
EGL_CONTEXT_MINOR_VERSION, OPENGL_MINOR_VERSION,
EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
EGL_NONE});
if (context == EGL_NO_CONTEXT || !eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, context)) {
eglTerminate(display);
return false;
}
eglDisplay = display;
eglContext = context;
return true;
}
}
@@ -1,139 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import org.lwjgl.system.MemoryUtil;
import java.nio.IntBuffer;
import static org.lwjgl.opengl.GL33.GL_RGBA32I;
import static org.lwjgl.opengl.GL33.GL_STATIC_DRAW;
import static org.lwjgl.opengl.GL33.GL_TEXTURE_BUFFER;
import static org.lwjgl.opengl.GL33.glBindBuffer;
import static org.lwjgl.opengl.GL33.glBindTexture;
import static org.lwjgl.opengl.GL33.glBufferData;
import static org.lwjgl.opengl.GL33.glBufferSubData;
import static org.lwjgl.opengl.GL33.glDeleteBuffers;
import static org.lwjgl.opengl.GL33.glDeleteTextures;
import static org.lwjgl.opengl.GL33.glGenBuffers;
import static org.lwjgl.opengl.GL33.glGenTextures;
import static org.lwjgl.opengl.GL33.glTexBuffer;
/**
* A layer's block faces on the graphics card, four ints each: first column, first row, bottom, and run with height.
* The vertex shader reads them from a buffer texture and works out each face's two triangles itself, which cards draw
* far faster than millions of tiny instances. Only for the GPU thread.
*/
final class GpuFaces {
static final int CORNERS_PER_FACE = 6;
private static final int INTS_PER_FACE = 4;
private static final int BYTES_PER_FACE = INTS_PER_FACE * Integer.BYTES;
private static final int FACES_PER_UPLOAD = 1 << 20;
private static final int LARGEST_PACKED = 0xFFFF;
private static final BlockFaces.Facing[] FACINGS = BlockFaces.Facing.values();
private static final BlockFaces.Kind[] KINDS = BlockFaces.Kind.values();
// Copied rather than kept, so the faces left in memory can be dropped once nothing else uses them.
private final int[][] firstOf = new int[KINDS.length][FACINGS.length];
private final int[][] countOf = new int[KINDS.length][FACINGS.length];
private final long bytes;
private final int buffer = glGenBuffers();
private final int texture = glGenTextures();
private GpuFaces(BlockFaces faces) {
for (BlockFaces.Kind kind : KINDS) {
for (BlockFaces.Facing facing : FACINGS) {
firstOf[kind.ordinal()][facing.ordinal()] = faces.first(kind, facing);
countOf[kind.ordinal()][facing.ordinal()] = faces.count(kind, facing);
}
}
bytes = (long) faces.count() * BYTES_PER_FACE;
}
/**
* @throws IllegalArgumentException when there are more faces than the card's buffer textures hold, or a face runs
* or reaches further than four ints can hold
* @param mostFaces the card's GL_MAX_TEXTURE_BUFFER_SIZE
*/
static GpuFaces upload(BlockFaces faces, int mostFaces) {
if (faces.count() > mostFaces || (long) faces.count() * CORNERS_PER_FACE > Integer.MAX_VALUE) {
throw new IllegalArgumentException(faces.count() + " faces are more than the graphics card can hold");
}
GpuFaces uploaded = new GpuFaces(faces);
try {
uploaded.fill(faces);
} catch (RuntimeException failure) {
uploaded.delete();
throw failure;
}
return uploaded;
}
// Packed a slice at a time, so large terrain doesn't need all of it twice in memory.
private void fill(BlockFaces faces) {
glBindBuffer(GL_TEXTURE_BUFFER, buffer);
glBufferData(GL_TEXTURE_BUFFER, (long) Math.max(1, faces.count()) * BYTES_PER_FACE, GL_STATIC_DRAW);
IntBuffer packed = MemoryUtil.memAllocInt(Math.max(1, Math.min(faces.count(), FACES_PER_UPLOAD)) * INTS_PER_FACE);
try {
for (int from = 0; from < faces.count(); from += FACES_PER_UPLOAD) {
int to = Math.min(faces.count(), from + FACES_PER_UPLOAD);
pack(faces, packed, from, to);
glBufferSubData(GL_TEXTURE_BUFFER, (long) from * BYTES_PER_FACE, packed);
}
} finally {
MemoryUtil.memFree(packed);
}
glBindTexture(GL_TEXTURE_BUFFER, texture);
glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32I, buffer);
}
private static void pack(BlockFaces faces, IntBuffer packed, int fromFace, int toFace) {
packed.clear();
for (int face = fromFace; face < toFace; face++) {
int run = faces.columns(face);
int reach = faces.height(face);
if (run > LARGEST_PACKED || reach > LARGEST_PACKED) {
throw new IllegalArgumentException("A face of " + run + " by " + reach + " is too large to draw on the graphics card");
}
packed.put(faces.firstColumn(face)).put(faces.firstRow(face)).put(faces.bottomY(face)).put(run | reach << 16);
}
packed.flip();
}
void bind() {
glBindTexture(GL_TEXTURE_BUFFER, texture);
}
int first(BlockFaces.Kind kind, BlockFaces.Facing facing) {
return firstOf[kind.ordinal()][facing.ordinal()];
}
int count(BlockFaces.Kind kind, BlockFaces.Facing facing) {
return countOf[kind.ordinal()][facing.ordinal()];
}
long bytes() {
return bytes;
}
void delete() {
glDeleteTextures(texture);
glDeleteBuffers(buffer);
}
}
@@ -1,67 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import java.util.OptionalDouble;
import static org.lwjgl.opengl.GL11.GL_DEPTH_COMPONENT;
import static org.lwjgl.opengl.GL11.GL_FLOAT;
import static org.lwjgl.opengl.GL11.glReadPixels;
/**
* Where the graphics card draws a frame: a picture read back for Swing, or straight into a window. Only for the GPU
* thread.
*/
interface GpuFrameTarget {
double FARTHEST_DEPTH = 1D;
/**
* Makes the target the one drawn into, at the given size.
*/
void bindSized(int width, int height);
/**
* Ends the frame drawn since {@link #bindSized}.
*
* @param depthRange the range the clip matrix was made for
*/
OrbitPicture finish(OrbitProjection projection, double depthRange);
/**
* Reads the one depth a picture keeps, the middle's, from what is bound.
*/
static OptionalDouble depthInMiddle(OrbitProjection projection, double depthRange, int width, int height) {
int middleX = (int) projection.screenCenterX();
int middleY = (int) projection.screenCenterY();
if (middleX < 0 || middleY < 0 || middleX >= width || middleY >= height) {
return OptionalDouble.empty();
}
float[] middleDepth = new float[1];
glReadPixels(middleX, height - 1 - middleY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, middleDepth);
return OrbitPicture.finite(blockDepth(middleDepth[0], depthRange));
}
// The depth buffer holds 0 at the near plane and 1 at the far one, nearer being smaller.
private static double blockDepth(float bufferDepth, double depthRange) {
if (bufferDepth >= FARTHEST_DEPTH) {
return Double.NEGATIVE_INFINITY;
}
return -(2D * bufferDepth - 1D) * depthRange;
}
}
@@ -1,90 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import static org.lwjgl.opengl.GL30.GL_BGRA;
import static org.lwjgl.opengl.GL30.GL_COLOR_ATTACHMENT0;
import static org.lwjgl.opengl.GL30.GL_DEPTH_ATTACHMENT;
import static org.lwjgl.opengl.GL30.GL_DEPTH_COMPONENT24;
import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER;
import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER_COMPLETE;
import static org.lwjgl.opengl.GL30.GL_RENDERBUFFER;
import static org.lwjgl.opengl.GL30.GL_RGBA8;
import static org.lwjgl.opengl.GL30.GL_UNSIGNED_INT_8_8_8_8_REV;
import static org.lwjgl.opengl.GL30.glBindFramebuffer;
import static org.lwjgl.opengl.GL30.glBindRenderbuffer;
import static org.lwjgl.opengl.GL30.glCheckFramebufferStatus;
import static org.lwjgl.opengl.GL30.glFramebufferRenderbuffer;
import static org.lwjgl.opengl.GL30.glGenFramebuffers;
import static org.lwjgl.opengl.GL30.glGenRenderbuffers;
import static org.lwjgl.opengl.GL30.glReadPixels;
import static org.lwjgl.opengl.GL30.glRenderbufferStorage;
import static org.lwjgl.opengl.GL30.glViewport;
/**
* A picture the graphics card draws into instead of a window, read back as an {@link OrbitPicture} so Swing shows it
* like any other. Only for the GPU thread.
*/
final class GpuFramebuffer implements GpuFrameTarget {
private final int framebuffer = glGenFramebuffers();
private final int colorBuffer = glGenRenderbuffers();
private final int depthBuffer = glGenRenderbuffers();
private int width;
private int height;
private int[] colorRows = new int[0];
@Override
public void bindSized(int nextWidth, int nextHeight) {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
if (nextWidth != width || nextHeight != height) {
resizeTo(nextWidth, nextHeight);
}
glViewport(0, 0, width, height);
}
private void resizeTo(int nextWidth, int nextHeight) {
width = nextWidth;
height = nextHeight;
glBindRenderbuffer(GL_RENDERBUFFER, colorBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
throw new IllegalStateException("The graphics card can't draw a " + width + "x" + height + " picture");
}
colorRows = new int[width * height];
}
// Reads what was drawn. Only the middle's depth is read back, the one depth a picture keeps.
@Override
public OrbitPicture finish(OrbitProjection projection, double depthRange) {
glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, colorRows);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
for (int row = 0; row < height; row++) {
System.arraycopy(colorRows, (height - 1 - row) * width, pixels, row * width, width);
}
return OrbitPicture.whole(image, GpuFrameTarget.depthInMiddle(projection, depthRange, width, height));
}
}
@@ -1,191 +0,0 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.studio.map;
import art.arcane.iris.spi.IrisLogging;
import java.util.Optional;
import static org.lwjgl.opengl.GL33.GL_BLEND;
import static org.lwjgl.opengl.GL33.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL33.GL_CULL_FACE;
import static org.lwjgl.opengl.GL33.GL_DEPTH_BUFFER_BIT;
import static org.lwjgl.opengl.GL33.GL_DEPTH_TEST;
import static org.lwjgl.opengl.GL33.GL_LESS;
import static org.lwjgl.opengl.GL33.GL_NO_ERROR;
import static org.lwjgl.opengl.GL33.GL_POLYGON_OFFSET_FILL;
import static org.lwjgl.opengl.GL33.glClear;
import static org.lwjgl.opengl.GL33.glClearColor;
import static org.lwjgl.opengl.GL33.glClearDepth;
import static org.lwjgl.opengl.GL33.glDepthFunc;
import static org.lwjgl.opengl.GL33.glDepthMask;
import static org.lwjgl.opengl.GL33.glDisable;
import static org.lwjgl.opengl.GL33.glEnable;
import static org.lwjgl.opengl.GL33.glGetError;
/**
* Runs a 3D view's frame on the graphics card, straight into the view's window where frames can go there, or else into
* a picture read back for Swing. A card that fails once isn't used again, as it would most likely fail every frame,
* each time only after costing the frame its time.
*/
final class GpuFrames {
private static final double COLOR_CHANNEL_MAX = 255D;
private static GpuFramebuffer offScreen;
private static volatile boolean failed;
private GpuFrames() {
}
/**
* A frame drawn on the card's thread.
*/
@FunctionalInterface
interface Drawing {
/**
* @return the frame, or nothing when the card can't draw this scene and it should be drawn without one
*/
Optional<OrbitPicture> drawInto(GpuFrameTarget target);
}
/**
* @return the picture, or nothing when the caller should draw it without a card
*/
static Optional<OrbitPicture> drawPicture(Drawing drawing) {
return onCard(gpu -> drawing.drawInto(offScreenFramebuffer()));
}
static boolean canDrawOnScreen() {
return !failed && GpuContext.drawsIntoWindows();
}
/**
* @return the frame, or nothing when it can't go straight into the window and the caller should draw a picture
*/
static Optional<OrbitPicture> drawOnScreen(ScreenTarget screen, Drawing drawing) {
return onCard(gpu -> {
Optional<GlxDisplay> windows = gpu.windows();
long window = screen.canvas().window();
if (windows.isEmpty() || window == 0L) {
return Optional.empty();
}
try {
if (!windows.get().canDrawInto(screen.canvas().visualId())) {
throw new IllegalStateException("The view's window has another visual than the one GLX draws with");
}
if (!windows.get().drawInto(window)) {
throw new IllegalStateException("GLX can't draw into the view's window");
}
return drawing.drawInto(new GpuWindowFrame(screen.seeThrough()));
} catch (RuntimeException failure) {
gpu.stopDrawingIntoWindows(failure);
return Optional.empty();
}
});
}
/**
* Puts the last frame drawn into the view's window on screen. Another view may have drawn into its own window
* since, so the view's window is made current again first.
*
* @return false when the window didn't take it, and the caller should draw a picture instead
*/
static boolean showOnScreen(ScreenTarget screen) {
return onCard(gpu -> {
Optional<GlxDisplay> windows = gpu.windows();
long window = screen.canvas().window();
if (windows.isEmpty() || window == 0L) {
return Optional.<Boolean>empty();
}
try {
if (!windows.get().drawInto(window) || !windows.get().show(window)) {
throw new IllegalStateException("The window didn't take the frame");
}
return Optional.of(true);
} catch (RuntimeException failure) {
gpu.stopDrawingIntoWindows(failure);
return Optional.<Boolean>empty();
}
}).isPresent();
}
static void failOnError() {
int error = glGetError();
if (error != GL_NO_ERROR) {
throw new IllegalStateException("OpenGL error 0x" + Integer.toHexString(error));
}
}
/**
* Clears to the views' background, and sets up for opaque drawing with depth.
*/
static void clearToBackground() {
int background = StudioTheme.EDITOR_BACKGROUND.getRGB();
glClearColor(channel(background, 16), channel(background, 8), channel(background, 0), 1F);
glClearDepth(1D);
glDepthMask(true);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glDisable(GL_BLEND);
glDisable(GL_CULL_FACE);
glDisable(GL_POLYGON_OFFSET_FILL);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
static float channel(int color, int shift) {
return (float) (((color >>> shift) & 0xFF) / COLOR_CHANNEL_MAX);
}
private static GpuFramebuffer offScreenFramebuffer() {
if (offScreen == null) {
offScreen = new GpuFramebuffer();
}
return offScreen;
}
private static <T> Optional<T> onCard(CardWork<T> work) {
if (failed) {
return Optional.empty();
}
Optional<GpuContext> gpu = GpuContext.shared();
if (gpu.isEmpty()) {
return Optional.empty();
}
try {
return gpu.get().call(() -> work.drawOn(gpu.get()));
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
return Optional.empty();
} catch (RuntimeException failure) {
stopUsingCard(failure);
return Optional.empty();
}
}
private static void stopUsingCard(RuntimeException failure) {
failed = true;
IrisLogging.reportError(failure);
IrisLogging.warn("3D views draw without a graphics card from now on: %s", failure.getCause() == null ? failure : failure.getCause());
}
@FunctionalInterface
private interface CardWork<T> {
Optional<T> drawOn(GpuContext gpu);
}
}
Loaded 100 of 491 files, more files were not shown because too many files have changed in this diff. Show more