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 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 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
742 changed files with 38759 additions and 40099 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:
```
@@ -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);
@@ -19,7 +19,6 @@
package art.arcane.iris.modded;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.BiomeEnvironment;
@@ -224,18 +223,17 @@ public final class ModdedEngineEffects extends EngineAssignedComponent implement
}
private void applyEffects(NativeWorld level, NativeProtocolPlayer player, Iterable<IrisEffect> effects) {
PackRuntime runtime = PackRuntime.of(getEngine());
for (IrisEffect effect : effects) {
try {
applyEffect(level, player, effect, runtime);
applyEffect(level, player, effect);
} catch (Throwable error) {
IrisLogging.reportError(error);
}
}
}
private void applyEffect(NativeWorld level, NativeProtocolPlayer player, IrisEffect effect, PackRuntime runtime) {
if (!effect.shouldApplyNow(runtime)) {
private void applyEffect(NativeWorld level, NativeProtocolPlayer player, IrisEffect effect) {
if (!effect.shouldApplyNow()) {
return;
}
@@ -18,7 +18,6 @@
package art.arcane.iris.modded;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.decoration.IrisSurface;
import art.arcane.iris.generation.runtime.Engine;
@@ -128,7 +127,7 @@ public final class ModdedEntitySpawner {
entity.configureAnimal(irisEntity);
applySpawnEffect(irisEntity.getSpawnEffect(), entity, level, PackRuntime.of(engine));
applySpawnEffect(irisEntity.getSpawnEffect(), entity, level);
ModdedEntityCommandRunner.run(irisEntity.getRawCommands(), level.world(), blockX, blockY, blockZ);
if (riseEffectActive && entity.living()) {
startRiseEffect(engine, level, entity);
@@ -201,9 +200,8 @@ public final class ModdedEntitySpawner {
return level.chunksSafe(chunkX, chunkZ);
}
private static void applySpawnEffect(IrisEffect effect, NativeSpawnedEntity entity, NativeEntityRuntime level,
PackRuntime runtime) {
if (effect == null || !effect.shouldApplyNow(runtime)) {
private static void applySpawnEffect(IrisEffect effect, NativeSpawnedEntity entity, NativeEntityRuntime level) {
if (effect == null || !effect.shouldApplyNow()) {
return;
}
@@ -30,7 +30,6 @@ import art.arcane.iris.world.loot.IrisLootTable;
import art.arcane.iris.structure.object.IrisObjectLoot;
import art.arcane.iris.structure.object.IrisObjectPlacement;
import art.arcane.iris.structure.object.IrisObjectVanillaLoot;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
@@ -41,9 +40,6 @@ import java.util.ArrayList;
import java.util.List;
public final class ModdedLootApplier {
private static final String LOOT_TABLE_KEY_KIND = "missing-loot-table";
private static final String VANILLA_LOOT_TABLE_KEY_KIND = "missing-vanilla-loot-table";
private ModdedLootApplier() {
}
@@ -121,8 +117,7 @@ public final class ModdedLootApplier {
}
IrisLootTable table = engine.getData().getLootLoader().load(loot.getName());
if (table == null) {
IrisLogging.warnOnce(IrisData.onceKey(engine.getData(), LOOT_TABLE_KEY_KIND, loot.getName()),
"Couldn't find loot table " + loot.getName());
IrisLogging.warn("Couldn't find loot table " + loot.getName());
continue;
}
bucket(engine, loot, new Candidate(new IrisLootSource(table), loot.getWeight()), access, exact, basic, global);
@@ -134,8 +129,7 @@ public final class ModdedLootApplier {
}
NativeContainerLoot.Table table = access.table(loot.getName());
if (table == null) {
IrisLogging.warnOnce(IrisData.onceKey(engine.getData(), VANILLA_LOOT_TABLE_KEY_KIND, loot.getName()),
"Couldn't find vanilla loot table " + loot.getName());
IrisLogging.warn("Couldn't find vanilla loot table " + loot.getName());
continue;
}
bucket(engine, loot, new Candidate(new NativeLootSource(table), loot.getWeight()), access, exact, basic, global);
@@ -1,6 +1,5 @@
package art.arcane.iris.modded;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.nativelib.terrain.structure.StructureStagePolicy;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.mantle.DeferredPlacementRecords;
@@ -152,7 +151,7 @@ final class ModdedNativeStructurePolicy implements NativeModdedStructureStage.Po
@Override
public NativeBlockState paletteBlock(StructurePalette source, RNG rng, int x, int y, int z) {
return ((IrisMaterialPalette) source).get(rng, x, y, z, PackRuntime.of(generator.engine()));
return ((IrisMaterialPalette) source).get(rng, x, y, z, generator.engine().getData());
}
@Override
@@ -20,18 +20,22 @@ package art.arcane.iris.modded;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.ResourceLoader;
import art.arcane.iris.pack.loading.SnippetFolder;
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;
import art.arcane.volmlib.util.json.JSONArray;
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));
}
}
@@ -100,23 +119,17 @@ public final class ModdedWorkspaceGenerator {
try {
String snipType = snippetClass.getDeclaredAnnotation(Snippet.class).value();
JSONObject entry = new JSONObject();
List<String> fileMatch = new SnippetFolder(snipType).workspaceFileMatches();
KList<String> fileMatch = new KList<>();
for (int depth = 1; depth < 8; depth++) {
fileMatch.add("/snippet/" + snipType + Form.repeat("/*", depth) + ".json");
}
entry.put("fileMatch", new JSONArray(fileMatch.toArray()));
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',
+1 -1
View File
@@ -482,7 +482,7 @@ List<String> dependencyBuildMetadata = [
'META-INF/versions/*/OSGI-INF/**'
]
String languageTomlSupportClassPattern = 'art/arcane/volmlib/util/config/(?:TomlCodec|TomlSegments|ConfigComments|ConfigJson|ConfigExposePolicy|ConfigDoc|ConfigDescription|ConfigDocumentation)(?:\\$[^/]+)?\\.class'
String languageTomlSupportClassPattern = 'art/arcane/volmlib/util/config/(?:TomlCodec|ConfigJson|ConfigExposePolicy|ConfigDoc|ConfigDescription|ConfigDocumentation)(?:\\$[^/]+)?\\.class'
tasks.named('shadowJar', ShadowJar).configure {
inputs.property('languageTomlSupportClassPattern', languageTomlSupportClassPattern)
@@ -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
@@ -1,6 +1,5 @@
package art.arcane.iris.generation.bake;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.cache.ConcurrentClockCache;
import art.arcane.iris.generation.stream.ProvisionalSampling;
@@ -17,7 +16,7 @@ public final class ChunkBakeCache {
private final PlaneSource source;
private final ConcurrentClockCache<ChunkPlanes> entries;
private final ThreadSlots<Recent> recent = new ThreadSlots<>(Recent::new);
private final ThreadLocal<Recent> recent = ThreadLocal.withInitial(Recent::new);
private volatile int generation;
public ChunkBakeCache(PlaneSource source, int capacityChunks) {
@@ -3,7 +3,6 @@ package art.arcane.iris.generation.bake;
import art.arcane.iris.generation.noise.GeneratorProgram;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.TerrainBatchScratch;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.math.M;
import java.util.Arrays;
@@ -13,28 +12,26 @@ public final class TerrainProgram {
private static final int CONSTANT = 1;
private static final int ACTIVE = 2;
private final PackRuntime runtime;
private final IrisGenerator[][] generators;
private final GeneratorProgram[][] programs;
private final long heightSeed;
private TerrainProgram(PackRuntime runtime, IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) {
this.runtime = runtime;
private TerrainProgram(IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) {
this.generators = generators;
this.programs = programs;
this.heightSeed = heightSeed;
}
public static TerrainProgram compile(PackRuntime runtime, IrisGenerator[][] generators, long heightSeed) {
public static TerrainProgram compile(IrisGenerator[][] generators, long heightSeed) {
GeneratorProgram[][] programs = new GeneratorProgram[generators.length][];
for (int group = 0; group < generators.length; group++) {
programs[group] = new GeneratorProgram[generators[group].length];
for (int index = 0; index < generators[group].length; index++) {
IrisGenerator generator = generators[group][index];
programs[group][index] = generator.supportsBatch() ? generator.compileProgram(runtime, heightSeed) : null;
programs[group][index] = generator.supportsBatch() ? generator.compileProgram(heightSeed) : null;
}
}
return new TerrainProgram(runtime, generators, programs, heightSeed);
return new TerrainProgram(generators, programs, heightSeed);
}
public long heightSeed() {
@@ -61,7 +58,7 @@ public final class TerrainProgram {
GeneratorProgram[] compiled = programs[group];
for (int member = 0; member < members.length; member++) {
GeneratorProgram program = compiled[member];
double noise = program != null ? program.height(scratch, x, z) : members[member].getHeight(runtime, x, z, heightSeed);
double noise = program != null ? program.height(scratch, x, z) : members[member].getHeight(x, z, heightSeed);
if (!Double.isFinite(noise)) {
throw new IllegalStateException("Terrain generator noise was not finite at " + x + "," + z
+ " (generator=" + members[member].getLoadKey() + ", noise=" + noise
@@ -151,7 +148,7 @@ public final class TerrainProgram {
program.heights(scratch, activeX, activeZ, activeCount, noise);
} else {
for (int index = 0; index < activeCount; index++) {
noise[index] = members[member].getHeight(runtime, activeX[index], activeZ[index], heightSeed);
noise[index] = members[member].getHeight(activeX[index], activeZ[index], heightSeed);
}
}
for (int index = 0; index < activeCount; index++) {
@@ -1,155 +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.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.iris.generation.decoration.DecoratorRuntime;
import art.arcane.iris.generation.decoration.IrisDecorationPart;
import art.arcane.iris.generation.decoration.IrisDecorator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.Supplier;
/**
* What one engine derives from an {@link IrisBiome}: its scatter generators, the children generators per shrink
* scale, the height generators of its layer palettes and the runtimes of those palettes, linked by layer index so
* painting a column reads them without looking each layer up.
*/
public final class BiomeRuntime {
private static final int BIOME_SEED_CAPACITY = 8;
private static final int CHILD_SEED_CAPACITY = 8;
private static final int LAYER_HEIGHT_SEED_CAPACITY = 32;
private static final int SURFACE_LAYER_SEED_OFFSET = 7235;
private static final int SEA_LAYER_SEED_OFFSET = 7735;
private static final int CEILING_LAYER_SEED_OFFSET = 7235;
private final IrisBiome biome;
private final PackRuntime runtime;
private final SeedTable<CNG> biomeGenerators;
private final ConcurrentHashMap<Long, SeedTable<CNG>> childGeneratorsByScale = new ConcurrentHashMap<>();
private final SeedTable<KList<CNG>> layerHeights;
private final SeedTable<KList<CNG>> seaLayerHeights;
private final SeedTable<KList<CNG>> ceilingLayerHeights;
private final LinkedLayers surfaceLayers;
private final LinkedLayers seaLayers;
private final LinkedLayers ceilingLayers;
private final AtomicReferenceArray<LinkedDecorators> decoratorBuckets =
new AtomicReferenceArray<>(IrisDecorationPart.values().length);
public BiomeRuntime(IrisBiome biome, PackRuntime runtime) {
this.biome = biome;
this.runtime = runtime;
this.biomeGenerators = new SeedTable<>(BIOME_SEED_CAPACITY, seed -> biome.createBiomeGenerator(seed, runtime));
this.layerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed ->
IrisBiomeLayerGenerator.createHeightGenerators(biome.getLayers(), SURFACE_LAYER_SEED_OFFSET, seed, runtime));
this.seaLayerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed ->
IrisBiomeLayerGenerator.createHeightGenerators(biome.getSeaLayers(), SEA_LAYER_SEED_OFFSET, seed, runtime));
this.ceilingLayerHeights = new SeedTable<>(LAYER_HEIGHT_SEED_CAPACITY, seed ->
IrisBiomeLayerGenerator.createHeightGenerators(biome.getCaveCeilingLayers(), CEILING_LAYER_SEED_OFFSET, seed, runtime));
this.surfaceLayers = new LinkedLayers(biome::getLayers);
this.seaLayers = new LinkedLayers(biome::getSeaLayers);
this.ceilingLayers = new LinkedLayers(biome::getCaveCeilingLayers);
}
public CNG biomeGenerator(long seed) {
return biomeGenerators.get(seed);
}
public CNG childrenGenerator(long seed, double scale) {
return childGeneratorsByScale.computeIfAbsent(Double.doubleToLongBits(scale), ignored ->
new SeedTable<>(CHILD_SEED_CAPACITY, childSeed -> biome.createChildrenGenerator(childSeed, scale, runtime)))
.get(seed);
}
public KList<CNG> layerHeights(long seed) {
return layerHeights.get(seed);
}
public KList<CNG> seaLayerHeights(long seed) {
return seaLayerHeights.get(seed);
}
public KList<CNG> ceilingLayerHeights(long seed) {
return ceilingLayerHeights.get(seed);
}
/** The runtime of the surface layer at this index of {@link IrisBiome#getLayers()}. */
public PaletteLayerRuntime surfaceLayer(int index) {
return surfaceLayers.get(index);
}
/** The runtime of the sea layer at this index of {@link IrisBiome#getSeaLayers()}. */
public PaletteLayerRuntime seaLayer(int index) {
return seaLayers.get(index);
}
/** The runtime of the cave ceiling layer at this index of {@link IrisBiome#getCaveCeilingLayers()}. */
public PaletteLayerRuntime ceilingLayer(int index) {
return ceilingLayers.get(index);
}
/** The runtimes of this part's {@link IrisBiome#getDecoratorBucket} decorators, in bucket order. */
public DecoratorRuntime[] decorators(IrisDecorationPart part) {
IrisDecorator[] bucket = biome.getDecoratorBucket(part);
LinkedDecorators linked = decoratorBuckets.getAcquire(part.ordinal());
if (linked != null && linked.bucket() == bucket) {
return linked.runtimes();
}
DecoratorRuntime[] runtimes = new DecoratorRuntime[bucket.length];
for (int index = 0; index < bucket.length; index++) {
runtimes[index] = runtime.decorator(bucket[index]);
}
decoratorBuckets.setRelease(part.ordinal(), new LinkedDecorators(bucket, runtimes));
return runtimes;
}
private record LinkedDecorators(IrisDecorator[] bucket, DecoratorRuntime[] runtimes) {
}
private final class LinkedLayers {
private final Supplier<KList<IrisBiomePaletteLayer>> layers;
private volatile PaletteLayerRuntime[] linked;
private LinkedLayers(Supplier<KList<IrisBiomePaletteLayer>> layers) {
this.layers = layers;
}
private PaletteLayerRuntime get(int index) {
PaletteLayerRuntime[] current = linked;
if (current == null) {
current = link(layers.get());
linked = current;
}
return current[index];
}
private PaletteLayerRuntime[] link(KList<IrisBiomePaletteLayer> source) {
PaletteLayerRuntime[] result = new PaletteLayerRuntime[source.size()];
for (int index = 0; index < result.length; index++) {
result[index] = runtime.paletteLayer(source.get(index));
}
return result;
}
}
}
@@ -1,57 +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.generation.biome;
import art.arcane.iris.generation.cave.IrisCaveProfileSampler;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import java.util.Optional;
/**
* What one engine derives from an {@link IrisFloatingChildBiomes} entry: its edge taper profile per base seed and the
* cave profile sampler of the biome it carves with.
*/
public final class FloatingChildRuntime {
private static final int EDGE_PROFILE_SEED_CAPACITY = 8;
private final IrisFloatingChildBiomes entry;
private final PackRuntime runtime;
private final SeedTable<FloatingIslandEdgeProfile> edgeProfiles;
private volatile Optional<IrisCaveProfileSampler> carvingProfileSampler;
public FloatingChildRuntime(IrisFloatingChildBiomes entry, PackRuntime runtime) {
this.entry = entry;
this.runtime = runtime;
this.edgeProfiles = new SeedTable<>(EDGE_PROFILE_SEED_CAPACITY, seed -> entry.createEdgeTaperProfile(seed, runtime));
}
public FloatingIslandEdgeProfile edgeTaperProfile(long baseSeed) {
return edgeProfiles.get(baseSeed);
}
public IrisCaveProfileSampler carvingProfileSampler() {
Optional<IrisCaveProfileSampler> resolved = carvingProfileSampler;
if (resolved == null) {
resolved = Optional.ofNullable(entry.createCarvingProfileSampler(runtime));
carvingProfileSampler = resolved;
}
return resolved.orElse(null);
}
}
@@ -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.generation.biome;
import java.util.HashMap;
/**
* One worker's floating island samples for the chunk it is generating. A runtime scope keeps one per worker thread,
* so the memo never outlives the engine that produced its samples.
*/
public final class FloatingIslandMemo {
private static final int CHUNK_COLUMN_COUNT = 256;
private final HashMap<Long, MemoizedSample> samples = new HashMap<>(CHUNK_COLUMN_COUNT);
private MemoContext context;
public void clear() {
samples.clear();
context = null;
}
/** The memoized sample for this column and parent, which may itself be null; null when not sampled yet. */
MemoizedSample find(IrisBiome parent, long column) {
MemoizedSample cached = samples.get(column);
return cached != null && cached.parent == parent ? cached : null;
}
void remember(IrisBiome parent, long column, FloatingIslandSample sample) {
samples.put(column, new MemoizedSample(parent, sample));
}
void enterChunk(int chunkX, int chunkZ, int height, long seed, FloatingIslandBoundarySampler boundarySampler) {
if (context != null && context.matches(chunkX, chunkZ, height, seed, boundarySampler)) {
return;
}
samples.clear();
context = new MemoContext(chunkX, chunkZ, height, seed, boundarySampler);
}
private record MemoContext(int chunkX, int chunkZ, int height, long seed,
FloatingIslandBoundarySampler boundarySampler) {
private boolean matches(int chunkX, int chunkZ, int height, long seed,
FloatingIslandBoundarySampler boundarySampler) {
return this.chunkX == chunkX && this.chunkZ == chunkZ && this.height == height && this.seed == seed
&& this.boundarySampler == boundarySampler;
}
}
record MemoizedSample(IrisBiome parent, FloatingIslandSample sample) {
}
}
@@ -20,12 +20,16 @@ package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.cave.IrisCaveProfileSampler;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.collection.KList;
import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap;
import java.util.Arrays;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
public final class FloatingIslandSample {
@@ -47,6 +51,8 @@ public final class FloatingIslandSample {
private static final double CARVE_MAX_VERTICAL_RUN_FRACTION = 0.18D;
private static final ThreadLocal<int[]> LAST_REJECT = ThreadLocal.withInitial(() -> new int[1]);
private static final ThreadLocal<double[]> LAST_DENSITY = ThreadLocal.withInitial(() -> new double[2]);
private static final ThreadLocal<ChunkMemo> CHUNK_MEMO = ThreadLocal.withInitial(ChunkMemo::new);
private static final ThreadLocal<IdentityHashMap<CNG, Long2DoubleOpenHashMap>> FOOTPRINT_MEMO = ThreadLocal.withInitial(IdentityHashMap::new);
private static final AtomicBoolean NULL_CNG_WARNED = new AtomicBoolean(false);
public static int getLastReject() {
@@ -61,20 +67,33 @@ public final class FloatingIslandSample {
return LAST_DENSITY.get()[1];
}
public static void clearChunkMemo(PackRuntime runtime) {
runtime.floatingIslandMemo().clear();
public static void clearThreadCaches() {
CHUNK_MEMO.remove();
FOOTPRINT_MEMO.remove();
LAST_REJECT.remove();
LAST_DENSITY.remove();
}
public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime, FloatingIslandBoundarySampler boundarySampler) {
long column = (((long) wx) << 32) ^ (wz & 0xFFFFFFFFL);
FloatingIslandMemo memo = runtime.floatingIslandMemo();
memo.enterChunk(wx >> 4, wz >> 4, chunkHeight, baseSeed, boundarySampler);
FloatingIslandMemo.MemoizedSample cached = memo.find(parent, column);
if (cached != null) {
return cached.sample();
public static void clearChunkMemo() {
CHUNK_MEMO.get().samples.clear();
FOOTPRINT_MEMO.get().clear();
}
public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) {
long key = (((long) wx) << 32) ^ (wz & 0xFFFFFFFFL);
ChunkMemo memo = CHUNK_MEMO.get();
if (memo.context == null || !memo.context.matches(wx >> 4, wz >> 4, chunkHeight, baseSeed,
data, engine, boundarySampler)) {
memo.samples.clear();
FOOTPRINT_MEMO.get().clear();
memo.context = new MemoContext(wx >> 4, wz >> 4, chunkHeight, baseSeed, data, engine, boundarySampler);
}
FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler);
memo.remember(parent, column, result);
MemoizedSample cached = memo.samples.get(key);
if (cached != null && cached.parent == parent) {
return cached.sample;
}
FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler);
memo.samples.put(key, new MemoizedSample(parent, result));
return result;
}
@@ -165,18 +184,18 @@ public final class FloatingIslandSample {
}
private static int maximumEdgeFieldWidth(KList<IrisFloatingChildBiomes> entries, long baseSeed,
PackRuntime runtime, IrisBiome parent) {
IrisData data, IrisBiome parent) {
int maximumWidth = FloatingIslandEdgeProfile.MIN_WIDTH;
for (IrisFloatingChildBiomes entry : entries) {
FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, runtime, parent);
FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, data, parent);
maximumWidth = Math.max(maximumWidth, profile.fieldWidth());
}
return maximumWidth;
}
private static FloatingIslandEdgeProfile resolveEdgeProfile(IrisFloatingChildBiomes entry, long baseSeed,
PackRuntime runtime, IrisBiome parent) {
FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, runtime);
IrisData data, IrisBiome parent) {
FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, data);
if (profile != null) {
return profile;
}
@@ -184,17 +203,17 @@ public final class FloatingIslandSample {
return FloatingIslandEdgeProfile.DEFAULT;
}
public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime, FloatingIslandBoundarySampler boundarySampler) {
public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) {
KList<IrisFloatingChildBiomes> entries = parent.getFloatingChildBiomes();
if (entries == null || entries.isEmpty()) {
return reject(REJECT_NO_ENTRIES);
}
int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, runtime, parent);
int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, data, parent);
int parentBoundaryDistance = boundarySampler.edgeDistance(parent, wx, wz, boundaryFieldWidth);
if (parent.isMergeFloatingChildBiomes()) {
return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler,
return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler,
parentBoundaryDistance, boundaryFieldWidth);
}
@@ -204,7 +223,7 @@ public final class FloatingIslandSample {
entry = entries.getFirst();
} else {
IrisFloatingChildBiomes reference = entries.getFirst();
CNG picker = reference.getPickerCng(baseSeed, runtime);
CNG picker = reference.getPickerCng(baseSeed, data);
if (picker == null) {
warnNullCng("pickerStyle", parent);
return reject(REJECT_NO_PICK);
@@ -218,20 +237,20 @@ public final class FloatingIslandSample {
ownershipBoundaryDistance = ownership.boundaryDistance();
}
return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler,
return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler,
parentBoundaryDistance, ownershipBoundaryDistance);
}
private static FloatingIslandSample sampleMerged(IrisBiome parent, KList<IrisFloatingChildBiomes> entries,
int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime,
FloatingIslandBoundarySampler boundarySampler,
int wx, int wz, int chunkHeight, long baseSeed, IrisData data,
Engine engine, FloatingIslandBoundarySampler boundarySampler,
int parentBoundaryDistance, int boundaryFieldWidth) {
KList<FloatingIslandSample> samples = new KList<>();
int minY = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
for (IrisFloatingChildBiomes entry : entries) {
FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, runtime,
FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine,
boundarySampler, parentBoundaryDistance, boundaryFieldWidth + 1);
if (sample == null) {
continue;
@@ -294,11 +313,11 @@ public final class FloatingIslandSample {
}
private static FloatingIslandSample sampleEntry(IrisBiome parent, IrisFloatingChildBiomes entry, int wx, int wz,
int chunkHeight, long baseSeed, PackRuntime runtime,
int chunkHeight, long baseSeed, IrisData data, Engine engine,
FloatingIslandBoundarySampler boundarySampler,
int parentBoundaryDistance, int ownershipBoundaryDistance) {
FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, runtime, parent);
CNG footprintCng = entry.getFootprintCng(baseSeed, runtime);
FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, data, parent);
CNG footprintCng = entry.getFootprintCng(baseSeed, data);
if (footprintCng == null) {
warnNullCng("footprintStyle", parent);
return reject(REJECT_NO_SEED);
@@ -324,23 +343,23 @@ public final class FloatingIslandSample {
return reject(REJECT_NO_THICKNESS);
}
CNG altitudeCng = entry.getAltitudeCng(baseSeed, runtime);
CNG altitudeCng = entry.getAltitudeCng(baseSeed, data);
if (altitudeCng == null) {
warnNullCng("altitudeStyle", parent);
return reject(REJECT_NO_SEED);
}
double altNoise = altitudeCng.noise(wx, wz);
double altClamped = Math.max(0, Math.min(1, altNoise));
int worldMin = runtime.engine().getWorld().minHeight();
int worldMin = engine.getWorld().minHeight();
int minAlt = Math.max(0, entry.getMinHeightAboveSurface() - worldMin);
int maxAlt = Math.max(minAlt, entry.getMaxHeightAboveSurface() - worldMin);
int baseY = minAlt + (int) Math.round(altClamped * (maxAlt - minAlt));
IrisBiome target = entry.getRealBiome(parent, runtime.data());
int fullTopHeight = computeTopHeight(entry, target, runtime, baseSeed, wx, wz);
IrisBiome target = entry.getRealBiome(parent, data);
int fullTopHeight = computeTopHeight(entry, target, engine, baseSeed, wx, wz, data);
int topH = roundedEdgeHeight(fullTopHeight, edgeFade);
CNG bottomCng = entry.getBottomCng(baseSeed, runtime);
CNG bottomCng = entry.getBottomCng(baseSeed, data);
if (bottomCng == null) {
warnNullCng("bottomStyle", parent);
return reject(REJECT_NO_SEED);
@@ -397,11 +416,11 @@ public final class FloatingIslandSample {
}
boolean[] solidMask = new boolean[thickness];
CNG wallWarp = entry.getWallWarpCng(baseSeed, runtime);
CNG wallWarp = entry.getWallWarpCng(baseSeed, data);
double warpAmp = Math.max(0, entry.getWallWarpAmplitude());
double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade);
IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(runtime);
CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, runtime) : null;
IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data);
CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null;
double carveThreshold = entry.getCarveThreshold();
boolean useWarp = wallWarp != null && effectiveWarpAmp > 0;
boolean useProfileCarve = carvingProfileSampler != null;
@@ -664,7 +683,27 @@ public final class FloatingIslandSample {
}
private static double footprintSigned(CNG footprintCng, int wx, int wz) {
return signedFromUnit(footprintCng.noise(wx, wz));
IdentityHashMap<CNG, Long2DoubleOpenHashMap> memoByCng = FOOTPRINT_MEMO.get();
Long2DoubleOpenHashMap memo = memoByCng.get(footprintCng);
if (memo == null) {
memo = new Long2DoubleOpenHashMap(512);
memo.defaultReturnValue(Double.NaN);
memoByCng.put(footprintCng, memo);
}
long key = columnKey(wx, wz);
double cached = memo.get(key);
if (!Double.isNaN(cached)) {
return cached;
}
double signed = signedFromUnit(footprintCng.noise(wx, wz));
memo.put(key, signed);
return signed;
}
private static long columnKey(int wx, int wz) {
return ((long) wx << 32) ^ (wz & 0xFFFFFFFFL);
}
private static double signedFromUnit(double value) {
@@ -740,7 +779,7 @@ public final class FloatingIslandSample {
}
}
private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, PackRuntime runtime, long baseSeed, int wx, int wz) {
private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, Engine engine, long baseSeed, int wx, int wz, IrisData data) {
int maxTopHeight = Math.max(0, entry.getMaxTopHeight());
if (maxTopHeight == 0) {
return 0;
@@ -748,7 +787,7 @@ public final class FloatingIslandSample {
return switch (entry.getTopShapeMode()) {
case FLAT -> maxTopHeight;
case NOISE -> {
CNG topCng = entry.getTopShapeCng(baseSeed, runtime);
CNG topCng = entry.getTopShapeCng(baseSeed, data);
if (topCng == null) {
warnNullCng("topShapeStyle", null);
yield maxTopHeight / 2;
@@ -762,7 +801,7 @@ public final class FloatingIslandSample {
if (target == null) {
yield maxTopHeight / 2;
}
double h = target.getHeight(runtime, wx, wz, baseSeed);
double h = target.getHeight(engine, wx, wz, baseSeed);
int rounded = (int) Math.round(h);
if (rounded < 0) {
yield 0;
@@ -771,4 +810,21 @@ public final class FloatingIslandSample {
}
};
}
private static final class ChunkMemo {
private final HashMap<Long, MemoizedSample> samples = new HashMap<>(256);
private MemoContext context;
}
private record MemoContext(int chunkX, int chunkZ, int height, long seed, IrisData data, Engine engine,
FloatingIslandBoundarySampler boundarySampler) {
private boolean matches(int chunkX, int chunkZ, int height, long seed, IrisData data, Engine engine,
FloatingIslandBoundarySampler boundarySampler) {
return this.chunkX == chunkX && this.chunkZ == chunkZ && this.height == height && this.seed == seed
&& this.data == data && this.engine == engine && this.boundarySampler == boundarySampler;
}
}
private record MemoizedSample(IrisBiome parent, FloatingIslandSample sample) {
}
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.decoration.IrisDecorationPart;
import art.arcane.iris.generation.decoration.IrisDecorator;
@@ -48,6 +47,7 @@ import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.iris.pack.schema.annotation.DependsOn;
@@ -63,6 +63,7 @@ import art.arcane.volmlib.util.collection.KSet;
import art.arcane.iris.generation.block.DataProvider;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.iris.generation.context.IrisContext;
import art.arcane.volmlib.util.stream.ProceduralStream;
import lombok.AccessLevel;
import lombok.Data;
@@ -92,6 +93,7 @@ import java.util.Objects;
@EqualsAndHashCode(callSuper = false)
public class IrisBiome extends IrisRegistrant implements Rarity {
public static final int CHILD_HOPS = 4;
private static final int BIOME_GENERATOR_CACHE_SIZE = 8;
private static final int CHILDREN_SEED_SALT = 2137;
private final transient AtomicCache<KMap<String, IrisBiomeGeneratorLink>> genCache = new AtomicCache<>();
@@ -102,10 +104,25 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
private final transient AtomicCache<Color> cacheColorDecoratorLoad = new AtomicCache<>();
private final transient AtomicCache<Color> cacheColorLayerLoad = new AtomicCache<>();
private final transient AtomicCache<Color> cacheColorDepositLoad = new AtomicCache<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<ChildGeneratorKey, CNG> childrenGenerators = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedChildGenerator recentChildGenerator;
@Getter(AccessLevel.NONE)
private final transient LazyBoundedCache<Long, CNG> biomeGenerators =
new LazyBoundedCache<>(BIOME_GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile SeededBiomeGenerator recentBiomeGenerator;
private final transient AtomicCache<Integer> maxHeight = new AtomicCache<>();
private final transient AtomicCache<Integer> maxWithObjectHeight = new AtomicCache<>();
private final transient AtomicCache<IrisBiome> realCarveBiome = new AtomicCache<>();
private final transient AtomicCache<KList<IrisBiome>> realChildren = new AtomicCache<>();
private final transient IrisBiomeLayerHeightCache layerHeightGenerators = new IrisBiomeLayerHeightCache();
private final transient IrisBiomeLayerHeightCache layerCeilingHeightGenerators = new IrisBiomeLayerHeightCache();
private final transient IrisBiomeLayerHeightCache layerSeaHeightGenerators = new IrisBiomeLayerHeightCache();
private final transient AtomicCache<KList<IrisOreGenerator>> surfaceOreCache = new AtomicCache<>();
private final transient AtomicCache<KList<IrisOreGenerator>> undergroundOreCache = new AtomicCache<>();
private final transient AtomicCache<IrisOreBands> surfaceOreBandsCache = new AtomicCache<>();
@@ -257,16 +274,16 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return IrisBiomeOres.canReplaceSurfaceOre(this, state);
}
public NativeBlockState generateOres(int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) {
return IrisBiomeOres.generateOres(this, x, y, z, rng, runtime, surface);
public NativeBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) {
return IrisBiomeOres.generateOres(this, x, y, z, rng, data, surface);
}
public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
return IrisBiomeOres.generateSurfaceOres(this, x, y, z, rng, runtime);
public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) {
return IrisBiomeOres.generateSurfaceOres(this, x, y, z, rng, data);
}
public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
return IrisBiomeOres.generateUndergroundOres(this, x, y, z, rng, runtime);
public NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) {
return IrisBiomeOres.generateUndergroundOres(this, x, y, z, rng, data);
}
public boolean hasSurfaceOres() {
@@ -452,38 +469,68 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
});
}
public double getHeight(PackRuntime runtime, double x, double z, long seed) {
public double getHeight(Engine xg, double x, double z, long seed) {
double height = 0;
for (IrisBiomeGeneratorLink i : generators) {
height += i.getHeight(runtime, x, z, seed);
height += i.getHeight(xg, x, z, seed);
}
return Math.max(0, Math.min(height, runtime.engine().getHeight()));
return Math.max(0, Math.min(height, xg.getHeight()));
}
public CNG getBiomeGenerator(RNG random) {
IrisData loader = getLoader();
Engine engine = resolveBiomeGeneratorEngine(loader);
return getBiomeGenerator(random, engine);
}
/** Engines seed the scatter generator from their own biome seed; engine-less tools use the caller's seed. */
public CNG getBiomeGenerator(RNG random, Engine engine) {
IrisData loader = getLoader();
long seed = engine == null ? random.getSeed() : engine.getSeedManager().getBiome();
return PackRuntime.of(engine, getLoader()).biome(this).biomeGenerator(seed);
SeededBiomeGenerator recent = recentBiomeGenerator;
if (recent != null && recent.seed == seed) {
return recent.generator;
}
CNG generator = biomeGenerators.computeIfAbsent(seed, ignored -> createBiomeGenerator(seed, loader));
recentBiomeGenerator = new SeededBiomeGenerator(seed, generator);
return generator;
}
CNG createBiomeGenerator(long seed, PackRuntime runtime) {
private Engine resolveBiomeGeneratorEngine(IrisData loader) {
IrisContext context = IrisContext.get();
if (context != null) {
Engine contextEngine = context.getEngine();
if (!contextEngine.isClosed() && (loader == null || contextEngine.getData() == loader)) {
return contextEngine;
}
}
return loader == null ? null : loader.getEngine();
}
private CNG createBiomeGenerator(long seed, IrisData loader) {
int signature = 213949 + 228888 + getRarity() + getName().length();
return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), runtime);
return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), loader);
}
public CNG getChildrenGenerator(PackRuntime runtime, RNG random, int sig, double scale) {
return getChildrenGenerator(runtime, deriveChildStyleSeed(random, sig).getSeed(), scale);
public CNG getChildrenGenerator(RNG random, int sig, double scale) {
return getChildrenGenerator(deriveChildStyleSeed(random, sig).getSeed(), scale);
}
public CNG getChildrenGenerator(PackRuntime runtime, long seed, double scale) {
double childScale = getChildStyle().isSeeded() ? 1 : scale;
return runtime.biome(this).childrenGenerator(seed, childScale);
}
CNG createChildrenGenerator(long seed, double scale, PackRuntime runtime) {
return getChildStyle().createScaledGenerator(new RNG(seed), runtime, scale);
public CNG getChildrenGenerator(long seed, double scale) {
IrisData data = getLoader();
Engine engine = data == null ? null : data.getEngine();
CachedChildGenerator recent = recentChildGenerator;
if (recent != null && recent.key.matches(seed, scale, data, engine)) {
return recent.generator;
}
ChildGeneratorKey key = new ChildGeneratorKey(seed, scale, data, engine);
CNG generator = childrenGenerators.computeIfAbsent(key,
ignored -> getChildStyle().createScaledGenerator(new RNG(seed), data, scale));
recentChildGenerator = new CachedChildGenerator(key, generator);
return generator;
}
static RNG deriveChildStyleSeed(RNG random, int signature) {
@@ -494,24 +541,24 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return deriveChildStyleSeed(random, signature).getSeed();
}
public KList<NativeBlockState> generateLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, runtime, complex);
public KList<NativeBlockState> generateLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex);
}
public KList<NativeBlockState> generateLayersWithSlope(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, ProceduralStream<Double> slopeStream) {
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, runtime, slopeStream);
public KList<NativeBlockState> generateLayersWithSlope(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, ProceduralStream<Double> slopeStream) {
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, rdata, slopeStream);
}
public KList<NativeBlockState> generateCeilingLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateCeilingLayers(this, dim, wx, wz, random, maxDepth, height, runtime, complex);
public KList<NativeBlockState> generateCeilingLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateCeilingLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex);
}
public KList<NativeBlockState> generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateLockedLayers(this, wx, wz, random, maxDepthf, height, runtime, complex);
public KList<NativeBlockState> generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateLockedLayers(this, wx, wz, random, maxDepthf, height, rdata, complex);
}
public KList<NativeBlockState> generateSeaLayers(double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, runtime);
public KList<NativeBlockState> generateSeaLayers(double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, rdata);
}
/**
@@ -526,20 +573,20 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return IrisBiomeLayerGenerator.getMaxWithObjectHeight(this, data, engine);
}
public KList<CNG> getLayerHeightGenerators(RNG rng, PackRuntime runtime) {
return runtime.biome(this).layerHeights(rng.getSeed());
public KList<CNG> getLayerHeightGenerators(RNG rng, IrisData rdata) {
return IrisBiomeLayerGenerator.getLayerHeightGenerators(this, rng, rdata);
}
public KList<CNG> getLayerSeaHeightGenerators(RNG rng, PackRuntime runtime) {
return runtime.biome(this).seaLayerHeights(rng.getSeed());
public KList<CNG> getLayerSeaHeightGenerators(RNG rng, IrisData data) {
return IrisBiomeLayerGenerator.getLayerSeaHeightGenerators(this, rng, data);
}
public KList<CNG> getCaveCeilingLayerHeightGenerators(RNG rng, PackRuntime runtime) {
return runtime.biome(this).ceilingLayerHeights(rng.getSeed());
public KList<CNG> getCaveCeilingLayerHeightGenerators(RNG rng, IrisData data) {
return IrisBiomeLayerGenerator.getCaveCeilingLayerHeightGenerators(this, rng, data);
}
public NativeBlockState getSurfaceBlock(int x, int z, RNG rng, PackRuntime runtime) {
return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, runtime);
public NativeBlockState getSurfaceBlock(int x, int z, RNG rng, IrisData idm) {
return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, idm);
}
public boolean isLand() {
@@ -569,10 +616,18 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return inferredType.equals(InferredType.SHORE);
}
public Biome getSkyBiome(RNG rng, double x, double y, double z) {
return IrisBiomeDerivatives.getSkyBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
}
public Biome getSkyBiome(RNG rng, Engine engine, double x, double y, double z) {
return IrisBiomeDerivatives.getSkyBiome(this, rng, engine, x, y, z);
}
public IrisBiomeCustom getCustomBiome(RNG rng, double x, double y, double z) {
return IrisBiomeDerivatives.getCustomBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
}
public IrisBiomeCustom getCustomBiome(RNG rng, Engine engine, double x, double y, double z) {
return IrisBiomeDerivatives.getCustomBiome(this, rng, engine, x, y, z);
}
@@ -601,14 +656,27 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return new KList<>(m);
}
//TODO: Test
public Biome getGroundBiome(RNG rng, double x, double y, double z) {
return IrisBiomeDerivatives.getGroundBiome(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
}
public Biome getGroundBiome(RNG rng, Engine engine, double x, double y, double z) {
return IrisBiomeDerivatives.getGroundBiome(this, rng, engine, x, y, z);
}
public String getSkyBiomeKey(RNG rng, double x, double y, double z) {
return IrisBiomeDerivatives.getSkyBiomeKey(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
}
public String getSkyBiomeKey(RNG rng, Engine engine, double x, double y, double z) {
return IrisBiomeDerivatives.getSkyBiomeKey(this, rng, engine, x, y, z);
}
public String getGroundBiomeKey(RNG rng, double x, double y, double z) {
return IrisBiomeDerivatives.getGroundBiomeKey(this, rng, resolveBiomeGeneratorEngine(getLoader()), x, y, z);
}
public String getGroundBiomeKey(RNG rng, Engine engine, double x, double y, double z) {
return IrisBiomeDerivatives.getGroundBiomeKey(this, rng, engine, x, y, z);
}
@@ -646,4 +714,37 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
public String getTypeName() {
return "Biome";
}
private static final class SeededBiomeGenerator {
private final long seed;
private final CNG generator;
private SeededBiomeGenerator(long seed, CNG generator) {
this.seed = seed;
this.generator = generator;
}
}
private record ChildGeneratorKey(long seed, double scale, IrisData data, Engine engine) {
private boolean matches(long seed, double scale, IrisData data, Engine engine) {
return this.seed == seed && Double.doubleToLongBits(this.scale) == Double.doubleToLongBits(scale)
&& this.data == data && this.engine == engine;
}
@Override
public boolean equals(Object object) {
return object instanceof ChildGeneratorKey other && matches(other.seed, other.scale, other.data, other.engine);
}
@Override
public int hashCode() {
int hash = Long.hashCode(seed);
hash = 31 * hash + Double.hashCode(scale);
hash = 31 * hash + System.identityHashCode(data);
return 31 * hash + System.identityHashCode(engine);
}
}
private record CachedChildGenerator(ChildGeneratorKey key, CNG generator) {
}
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.volmlib.util.cache.AtomicCache;
@@ -82,8 +81,8 @@ public class IrisBiomeGeneratorLink {
});
}
public double getHeight(PackRuntime runtime, double x, double z, long seed) {
double g = getCachedGenerator(runtime::data).getHeight(runtime, x, z, seed);
public double getHeight(DataProvider xg, double x, double z, long seed) {
double g = getCachedGenerator(xg).getHeight(x, z, seed);
g = g < 0 ? 0 : g;
g = g > 1 ? 1 : g;
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisSlopeClip;
import art.arcane.iris.structure.object.IrisObject;
@@ -46,18 +45,18 @@ final class IrisBiomeLayerGenerator {
private IrisBiomeLayerGenerator() {
}
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, runtime, complex, null);
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, rdata, complex, null);
}
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, ProceduralStream<Double> slopeStream) {
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, runtime, null, slopeStream);
static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, ProceduralStream<Double> slopeStream) {
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, rdata, null, slopeStream);
}
private static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex, ProceduralStream<Double> slopeStream) {
private static KList<NativeBlockState> generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex, ProceduralStream<Double> slopeStream) {
if (biome.isLockLayers()) {
KList<NativeBlockState> data = generateLockedLayers(biome, wx, wz, random, maxDepth, height, runtime, complex, slopeStream);
appendSurfaceFallback(data, biome, dim, wx, wz, random, Math.min(maxDepth, biome.getLockLayersMax()), runtime);
KList<NativeBlockState> data = generateLockedLayers(biome, wx, wz, random, maxDepth, height, rdata, complex, slopeStream);
appendSurfaceFallback(data, biome, dim, wx, wz, random, Math.min(maxDepth, biome.getLockLayersMax()), rdata);
return data;
}
@@ -74,8 +73,7 @@ final class IrisBiomeLayerGenerator {
return data;
}
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.layerHeights(random.getSeed());
KList<CNG> heightGenerators = getLayerHeightGenerators(biome, random, rdata);
double surfaceSlope = 0D;
boolean sampledSlope = false;
@@ -100,7 +98,7 @@ final class IrisBiomeLayerGenerator {
continue;
}
appendLayer(data, layer, biomeRuntime.surfaceLayer(i), i, d, wx, wz, random, maxDepth);
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
if (data.size() >= maxDepth) {
break;
@@ -117,12 +115,12 @@ final class IrisBiomeLayerGenerator {
}
}
appendSurfaceFallback(data, biome, dim, wx, wz, random, maxDepth, runtime);
appendSurfaceFallback(data, biome, dim, wx, wz, random, maxDepth, rdata);
return data;
}
private static void appendSurfaceFallback(KList<NativeBlockState> data, IrisBiome biome, IrisDimension dim,
double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
if (!data.isEmpty() || maxDepth <= 0 || biome.getLayers().isEmpty()) {
return;
}
@@ -131,11 +129,11 @@ final class IrisBiomeLayerGenerator {
fallback = dim.getSurfaceLayerFallback();
}
if (fallback == IrisSurfaceLayerFallback.TOP_LAYER) {
appendLayer(data, biome.getLayers().get(0), runtime.biome(biome).surfaceLayer(0), 0, 1, wx, wz, random, maxDepth);
appendLayer(data, biome.getLayers().get(0), 0, 1, wx, wz, random, maxDepth, rdata);
}
}
static KList<NativeBlockState> generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
static KList<NativeBlockState> generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
KList<NativeBlockState> data = new KList<>();
if (maxDepth <= 0) {
@@ -149,8 +147,7 @@ final class IrisBiomeLayerGenerator {
return data;
}
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.ceilingLayerHeights(random.getSeed());
KList<CNG> heightGenerators = getCaveCeilingLayerHeightGenerators(biome, random, rdata);
for (int i = 0; i < layerCount; i++) {
IrisBiomePaletteLayer layer = ceilingLayers.get(i);
@@ -162,7 +159,7 @@ final class IrisBiomeLayerGenerator {
continue;
}
appendLayer(data, layer, biomeRuntime.ceilingLayer(i), i, d, wx, wz, random, maxDepth);
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
if (data.size() >= maxDepth) {
break;
@@ -182,11 +179,11 @@ final class IrisBiomeLayerGenerator {
return data;
}
static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex) {
return generateLockedLayers(biome, wx, wz, random, maxDepthf, height, runtime, complex, null);
static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) {
return generateLockedLayers(biome, wx, wz, random, maxDepthf, height, rdata, complex, null);
}
private static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex, ProceduralStream<Double> slopeStream) {
private static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex, ProceduralStream<Double> slopeStream) {
KList<NativeBlockState> data = new KList<>();
int maxDepth = Math.min(maxDepthf, biome.getLockLayersMax());
KList<IrisBiomePaletteLayer> layers = biome.getLayers();
@@ -195,8 +192,7 @@ final class IrisBiomeLayerGenerator {
return data;
}
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.layerHeights(random.getSeed());
KList<CNG> heightGenerators = getLayerHeightGenerators(biome, random, rdata);
int[] boundaries = new int[layerCount + 1];
double surfaceSlope = 0D;
boolean sampledSlope = false;
@@ -231,10 +227,10 @@ final class IrisBiomeLayerGenerator {
int layerIndex = findLayer(boundaries, position);
IrisBiomePaletteLayer layer = layers.get(layerIndex);
int offset = position - boundaries[layerIndex];
double blocksPerSample = layer.blocksPerSample();
double zoom = layer.getZoom();
try {
data.add(layer.get(random, layerIndex + offset,
(wx + offset) / blocksPerSample, offset, (wz - offset) / blocksPerSample, biomeRuntime.surfaceLayer(layerIndex)));
(wx + offset) / zoom, offset, (wz - offset) / zoom, rdata));
} catch (Throwable error) {
GenerationFailures.skipPlacement(error, "surface layer", "block", (int) wx, height - depth, (int) wz, biome.getLoadKey());
}
@@ -278,7 +274,7 @@ final class IrisBiomeLayerGenerator {
: complex.getSlopeStream().getDouble(x, z);
}
static KList<NativeBlockState> generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
static KList<NativeBlockState> generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
KList<NativeBlockState> data = new KList<>();
KList<IrisBiomePaletteLayer> seaLayers = biome.getSeaLayers();
@@ -288,8 +284,7 @@ final class IrisBiomeLayerGenerator {
return data;
}
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.seaLayerHeights(random.getSeed());
KList<CNG> heightGenerators = getLayerSeaHeightGenerators(biome, random, rdata);
for (int i = 0; i < layerCount; i++) {
IrisBiomePaletteLayer layer = seaLayers.get(i);
@@ -301,7 +296,7 @@ final class IrisBiomeLayerGenerator {
continue;
}
appendLayer(data, layer, biomeRuntime.seaLayer(i), i, d, wx, wz, random, maxDepth);
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
if (data.size() >= maxDepth) {
break;
@@ -311,51 +306,46 @@ final class IrisBiomeLayerGenerator {
return data;
}
static KList<CNG> getLayerHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
return runtime.biome(biome).layerHeights(rng.getSeed());
static KList<CNG> getLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData rdata) {
return getHeightGenerators(biome.getLayerHeightGenerators(), biome.getLayers(), 7235, rng, rdata);
}
static KList<CNG> getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
return runtime.biome(biome).seaLayerHeights(rng.getSeed());
static KList<CNG> getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, IrisData data) {
return getHeightGenerators(biome.getLayerSeaHeightGenerators(), biome.getSeaLayers(), 7735, rng, data);
}
static KList<CNG> getCaveCeilingLayerHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
return runtime.biome(biome).ceilingLayerHeights(rng.getSeed());
static KList<CNG> getCaveCeilingLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData data) {
return getHeightGenerators(biome.getLayerCeilingHeightGenerators(), biome.getCaveCeilingLayers(), 7235, rng, data);
}
static KList<CNG> createHeightGenerators(KList<IrisBiomePaletteLayer> layers, int seedOffset, long seed,
PackRuntime runtime) {
RNG rng = new RNG(seed);
KList<CNG> result = new KList<>();
int offset = seedOffset;
for (IrisBiomePaletteLayer layer : layers) {
result.add(layer.getHeightGenerator(rng.nextParallelRNG((offset++) * offset * offset * offset), runtime));
}
return result;
private static KList<CNG> getHeightGenerators(IrisBiomeLayerHeightCache cache,
KList<IrisBiomePaletteLayer> layers,
int seedOffset, RNG rng, IrisData data) {
return cache.get(layers, seedOffset, rng, data);
}
private static void appendLayer(KList<NativeBlockState> blocks, IrisBiomePaletteLayer layer,
PaletteLayerRuntime layerRuntime, int layerIndex, int thickness, double x, double z,
RNG random, int maxDepth) {
double blocksPerSample = layer.blocksPerSample();
int layerIndex, int thickness, double x, double z,
RNG random, int maxDepth, IrisData data) {
double zoom = layer.getZoom();
for (int offset = 0; offset < thickness && blocks.size() < maxDepth; offset++) {
try {
blocks.add(layer.get(random, layerIndex + offset,
(x + offset) / blocksPerSample, offset, (z - offset) / blocksPerSample, layerRuntime));
(x + offset) / zoom, offset, (z - offset) / zoom, data));
} catch (Throwable error) {
GenerationFailures.skipPlacement(error, "surface layer", "block", (int) x, -1, (int) z, "none");
}
}
}
static NativeBlockState getSurfaceBlock(IrisBiome biome, int x, int z, RNG rng, PackRuntime runtime) {
static NativeBlockState getSurfaceBlock(IrisBiome biome, int x, int z, RNG rng, IrisData idm) {
KList<IrisBiomePaletteLayer> layers = biome.getLayers();
if (layers.isEmpty()) {
return B.getState("AIR");
}
return layers.get(0).get(rng, x, 0, z, runtime);
return layers.get(0).get(rng, x, 0, z, idm);
}
static int getMaxHeight(IrisBiome biome, Engine engine) {
@@ -0,0 +1,68 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
final class IrisBiomeLayerHeightCache {
private final LazyBoundedCache<GeneratorKey, KList<CNG>> generators = new LazyBoundedCache<>(32);
private volatile CachedGenerators recent;
KList<CNG> get(KList<IrisBiomePaletteLayer> layers, int seedOffset, RNG rng, IrisData data) {
Engine engine = data == null ? null : data.getEngine();
long seed = rng.getSeed();
CachedGenerators cached = recent;
if (cached != null && cached.key.matches(data, engine, seed)) {
return cached.generators;
}
GeneratorKey key = new GeneratorKey(data, engine, seed);
KList<CNG> result = generators.computeIfAbsent(key, ignored -> create(layers, seedOffset, rng, data));
recent = new CachedGenerators(key, result);
return result;
}
private static KList<CNG> create(KList<IrisBiomePaletteLayer> layers, int seedOffset, RNG rng, IrisData data) {
KList<CNG> result = new KList<>();
int offset = seedOffset;
for (IrisBiomePaletteLayer layer : layers) {
result.add(layer.getHeightGenerator(rng.nextParallelRNG((offset++) * offset * offset * offset), data));
}
return result;
}
private record CachedGenerators(GeneratorKey key, KList<CNG> generators) {
}
private static final class GeneratorKey {
private final IrisData data;
private final Engine engine;
private final long seed;
private GeneratorKey(IrisData data, Engine engine, long seed) {
this.data = data;
this.engine = engine;
this.seed = seed;
}
private boolean matches(IrisData data, Engine engine, long seed) {
return this.data == data && this.engine == engine && this.seed == seed;
}
@Override
public boolean equals(Object object) {
return this == object || object instanceof GeneratorKey other
&& matches(other.data, other.engine, other.seed);
}
@Override
public int hashCode() {
int result = System.identityHashCode(data);
result = 31 * result + System.identityHashCode(engine);
return 31 * result + Long.hashCode(seed);
}
}
}
@@ -22,7 +22,7 @@ import art.arcane.iris.generation.decoration.IrisOreGenerator;
import art.arcane.iris.generation.decoration.IrisOreBands;
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.iris.generation.block.B;
@@ -39,17 +39,17 @@ final class IrisBiomeOres {
private IrisBiomeOres() {
}
static NativeBlockState generateOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) {
static NativeBlockState generateOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data, boolean surface) {
KList<IrisOreGenerator> localOres = surface ? getSurfaceOres(biome) : getUndergroundOres(biome);
return generateOres(localOres, x, y, z, rng, runtime);
return generateOres(localOres, x, y, z, rng, data);
}
static NativeBlockState generateSurfaceOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime) {
return generateOres(getSurfaceOres(biome), x, y, z, rng, runtime);
static NativeBlockState generateSurfaceOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) {
return generateOres(getSurfaceOres(biome), x, y, z, rng, data);
}
static NativeBlockState generateUndergroundOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime) {
return generateOres(getUndergroundOres(biome), x, y, z, rng, runtime);
static NativeBlockState generateUndergroundOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) {
return generateOres(getUndergroundOres(biome), x, y, z, rng, data);
}
static boolean hasSurfaceOres(IrisBiome biome) {
@@ -122,7 +122,7 @@ final class IrisBiomeOres {
});
}
private static NativeBlockState generateOres(KList<IrisOreGenerator> localOres, int x, int y, int z, RNG rng, PackRuntime runtime) {
private static NativeBlockState generateOres(KList<IrisOreGenerator> localOres, int x, int y, int z, RNG rng, IrisData data) {
if (localOres.isEmpty()) {
return null;
}
@@ -130,7 +130,7 @@ final class IrisBiomeOres {
int oreCount = localOres.size();
for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) {
IrisOreGenerator oreGenerator = localOres.get(oreIndex);
NativeBlockState ore = oreGenerator.generate(x, y, z, rng, runtime);
NativeBlockState ore = oreGenerator.generate(x, y, z, rng, data);
if (ore != null) {
return ore;
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
@@ -26,6 +25,8 @@ import art.arcane.iris.generation.terrain.IrisSlopeClip;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.iris.pack.schema.annotation.DependsOn;
import art.arcane.volmlib.util.documentation.Description;
@@ -36,12 +37,17 @@ import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
@Snippet("biome-palette")
@Accessors(chain = true)
@@ -50,7 +56,24 @@ import lombok.experimental.Accessors;
@Description("A layer of surface / subsurface material in biomes")
@Data
public class IrisBiomePaletteLayer {
private static final int LAYER_GENERATOR_CACHE_SIZE = 32;
private final transient AtomicCache<KList<NativeBlockState>> blockData = new AtomicCache<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<LayerGeneratorKey, CNG> layerGenerators =
new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient AtomicReferenceArray<CachedLayerGenerator> recentLayerGenerators =
new AtomicReferenceArray<>(LAYER_GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<LayerGeneratorKey, CNG> heightGenerators =
new LazyBoundedCache<>(LAYER_GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient AtomicReference<CachedLayerGenerator> recentHeightGenerator = new AtomicReference<>();
@Description("The style of noise")
private IrisGeneratorStyle style = NoiseStyle.STATIC.style();
@DependsOn({"minHeight", "maxHeight"})
@@ -75,17 +98,23 @@ public class IrisBiomePaletteLayer {
@Description("The palette of blocks to be used in this layer")
private KList<IrisBlockData> palette = new KList<IrisBlockData>().qadd(new IrisBlockData("GRASS_BLOCK"));
public CNG getHeightGenerator(RNG rng, PackRuntime runtime) {
long generatorSeed = rng.getSeed() + minHeight * maxHeight + getBlockData(runtime.data()).size();
return runtime.paletteLayer(this).heightGenerator(generatorSeed);
public CNG getHeightGenerator(RNG rng, IrisData data) {
Engine engine = data == null ? null : data.getEngine();
long generatorSeed = rng.getSeed() + minHeight * maxHeight + getBlockData(data).size();
CachedLayerGenerator recent = recentHeightGenerator.get();
if (recent != null && recent.key.matches(data, engine, generatorSeed)) {
return recent.generator;
}
LayerGeneratorKey key = new LayerGeneratorKey(data, engine, generatorSeed);
CNG generator = heightGenerators.computeIfAbsent(key,
ignored -> CNG.signature(new RNG(generatorSeed)));
recentHeightGenerator.set(new CachedLayerGenerator(key, generator));
return generator;
}
static CNG createHeightGenerator(long generatorSeed) {
return CNG.signature(new RNG(generatorSeed));
}
public NativeBlockState get(RNG rng, double x, double y, double z, PackRuntime runtime) {
return get(rng, 0, x, y, z, runtime);
public NativeBlockState get(RNG rng, double x, double y, double z, IrisData data) {
return get(rng, 0, x, y, z, data);
}
/**
@@ -93,53 +122,44 @@ public class IrisBiomePaletteLayer {
* only built inside the lazy layer generator initializer, using the exact same seed derivation
* as {@code parent.nextParallelRNG(signature)} followed by the generator signature.
*/
public NativeBlockState get(RNG parent, int signature, double x, double y, double z, PackRuntime runtime) {
KList<NativeBlockState> localBlockData = getBlockData(runtime.data());
if (localBlockData.size() <= 1) {
return localBlockData.isEmpty() ? null : localBlockData.get(0);
}
return fit(localBlockData, runtime.paletteLayer(this), parent, signature, x, y, z);
}
public NativeBlockState get(RNG parent, int signature, double x, double y, double z, IrisData data) {
KList<NativeBlockState> localBlockData = getBlockData(data);
/** {@link #get(RNG, int, double, double, double, PackRuntime)} for a caller that already holds this layer's runtime. */
public NativeBlockState get(RNG parent, int signature, double x, double y, double z, PaletteLayerRuntime layerRuntime) {
KList<NativeBlockState> localBlockData = getBlockData(layerRuntime.packRuntime().data());
if (localBlockData.size() <= 1) {
return localBlockData.isEmpty() ? null : localBlockData.get(0);
if (localBlockData.isEmpty()) {
return null;
}
return fit(localBlockData, layerRuntime, parent, signature, x, y, z);
}
private NativeBlockState fit(KList<NativeBlockState> localBlockData, PaletteLayerRuntime layerRuntime,
RNG parent, int signature, double x, double y, double z) {
CNG generator = layerRuntime.layerGenerator(layerGeneratorSeed(parent, signature, localBlockData.size()));
if (style.isSeeded()) {
return generator.fit(localBlockData, x, z);
if (localBlockData.size() == 1) {
return localBlockData.get(0);
}
double localZoom = zoom;
return generator.fit(localBlockData, x / localZoom, y / localZoom, z / localZoom);
double scaledX = x / localZoom;
double scaledY = y / localZoom;
double scaledZ = z / localZoom;
return getLayerGenerator(parent, signature, data).fit(localBlockData, scaledX, scaledY, scaledZ);
}
/** How many blocks one step of the layer's block noise spans: its zoom, or 1 for a seeded style, which is read flat. */
public double blocksPerSample() {
return style.isSeeded() ? 1 : zoom;
public CNG getLayerGenerator(RNG rng, IrisData data) {
return getLayerGenerator(rng, 0, data);
}
public CNG getLayerGenerator(RNG rng, PackRuntime runtime) {
return getLayerGenerator(rng, 0, runtime);
}
public CNG getLayerGenerator(RNG parent, int signature, IrisData data) {
Engine engine = data == null ? null : data.getEngine();
long generatorSeed = parent.getSeed() + signature + minHeight + maxHeight + getBlockData(data).size();
int slot = (int) generatorSeed & (LAYER_GENERATOR_CACHE_SIZE - 1);
CachedLayerGenerator recent = recentLayerGenerators.getAcquire(slot);
if (recent != null && recent.key.matches(data, engine, generatorSeed)) {
return recent.generator;
}
public CNG getLayerGenerator(RNG parent, int signature, PackRuntime runtime) {
long generatorSeed = layerGeneratorSeed(parent, signature, getBlockData(runtime.data()).size());
return runtime.paletteLayer(this).layerGenerator(generatorSeed);
}
private long layerGeneratorSeed(RNG parent, int signature, int blockCount) {
return parent.getSeed() + signature + minHeight + maxHeight + blockCount;
}
CNG createLayerGenerator(long generatorSeed, PackRuntime runtime) {
return style.createNoCache(new RNG(generatorSeed), runtime);
LayerGeneratorKey key = new LayerGeneratorKey(data, engine, generatorSeed);
CNG generator = layerGenerators.computeIfAbsent(key,
ignored -> style.create(new RNG(generatorSeed), data, engine));
if (generator != null) {
recentLayerGenerators.setRelease(slot, new CachedLayerGenerator(key, generator));
}
return generator;
}
public KList<IrisBlockData> add(String b) {
@@ -175,4 +195,49 @@ public class IrisBiomePaletteLayer {
palette.clear();
return this;
}
private static final class LayerGeneratorKey {
private final IrisData data;
private final Engine engine;
private final long seed;
private LayerGeneratorKey(IrisData data, Engine engine, long seed) {
this.data = data;
this.engine = engine;
this.seed = seed;
}
private boolean matches(IrisData data, Engine engine, long seed) {
return this.data == data && this.engine == engine && this.seed == seed;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof LayerGeneratorKey other)) {
return false;
}
return data == other.data && engine == other.engine && seed == other.seed;
}
@Override
public int hashCode() {
int result = System.identityHashCode(data);
result = 31 * result + System.identityHashCode(engine);
result = 31 * result + Long.hashCode(seed);
return result;
}
}
private static final class CachedLayerGenerator {
private final LayerGeneratorKey key;
private final CNG generator;
private CachedLayerGenerator(LayerGeneratorKey key, CNG generator) {
this.key = key;
this.generator = generator;
}
}
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cave.IrisCaveProfileSampler;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
@@ -34,6 +33,10 @@ import art.arcane.volmlib.util.math.Rarity;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description;
@@ -59,72 +62,97 @@ import lombok.experimental.Accessors;
@Data
public class IrisFloatingChildBiomes implements Rarity {
private final transient AtomicCache<IrisBiome> resolvedBiome = new AtomicCache<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<RuntimeKey, FloatingIslandEdgeProfile> edgeTaperProfiles = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedEdgeProfile recentEdgeProfile;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<RuntimeKey, IrisCaveProfileSampler> carvingProfileSamplers = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedCarvingProfile recentCarvingProfile;
private final transient AtomicCache<IrisObjectScale> shrinkScaleCache = new AtomicCache<>();
public CNG getFootprintCng(long baseSeed, PackRuntime runtime) {
return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, runtime);
public CNG getFootprintCng(long baseSeed, IrisData data) {
return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, data);
}
public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, PackRuntime runtime) {
return runtime.floatingChild(this).edgeTaperProfile(baseSeed);
public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, IrisData data) {
Engine engine = data == null ? null : data.getEngine();
CachedEdgeProfile recent = recentEdgeProfile;
if (recent != null && recent.key.matches(baseSeed, data, engine)) {
return recent.profile;
}
RuntimeKey key = new RuntimeKey(baseSeed, data, engine);
FloatingIslandEdgeProfile profile = edgeTaperProfiles.computeIfAbsent(key, ignored -> {
int width = FloatingIslandEdgeProfile.clampWidth(getEdgeTaperWidth());
double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude(
getEdgeTaperVariationAmplitude(), width);
IrisGeneratorStyle style = getEdgeTaperVariationStyle();
CNG variation = amplitude > 0.0D && style != null
? style.create(baseSeed ^ 0xED6E7A9E5L, data)
: null;
return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation);
});
recentEdgeProfile = new CachedEdgeProfile(key, profile);
return profile;
}
FloatingIslandEdgeProfile createEdgeTaperProfile(long baseSeed, PackRuntime runtime) {
int width = FloatingIslandEdgeProfile.clampWidth(getEdgeTaperWidth());
double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude(getEdgeTaperVariationAmplitude(), width);
IrisGeneratorStyle style = getEdgeTaperVariationStyle();
CNG variation = amplitude > 0.0D && style != null
? style.create(baseSeed ^ 0xED6E7A9E5L, runtime)
: null;
return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation);
public CNG getPickerCng(long baseSeed, IrisData data) {
return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, data);
}
public CNG getPickerCng(long baseSeed, PackRuntime runtime) {
return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, runtime);
public CNG getAltitudeCng(long baseSeed, IrisData data) {
return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, data);
}
public CNG getAltitudeCng(long baseSeed, PackRuntime runtime) {
return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, runtime);
public CNG getTopShapeCng(long baseSeed, IrisData data) {
return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, data);
}
public CNG getTopShapeCng(long baseSeed, PackRuntime runtime) {
return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, runtime);
public CNG getBottomCng(long baseSeed, IrisData data) {
return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, data);
}
public CNG getBottomCng(long baseSeed, PackRuntime runtime) {
return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, runtime);
}
public CNG getWallWarpCng(long baseSeed, PackRuntime runtime) {
public CNG getWallWarpCng(long baseSeed, IrisData data) {
IrisGeneratorStyle style = getWallWarpStyle();
if (style == null) {
return null;
}
return style.create(baseSeed ^ 0xA117BA17E0FL, runtime);
return style.create(baseSeed ^ 0xA117BA17E0FL, data);
}
public CNG getCarveCng(long baseSeed, PackRuntime runtime) {
public CNG getCarveCng(long baseSeed, IrisData data) {
IrisGeneratorStyle style = getCarveStyle();
if (style == null) {
return null;
}
return style.create(baseSeed ^ 0xCA5EC1EE5EL, runtime);
return style.create(baseSeed ^ 0xCA5EC1EE5EL, data);
}
public IrisCaveProfileSampler getCarvingProfileSampler(PackRuntime runtime) {
public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) {
if (!hasCarvingReference()) {
return null;
}
return runtime.floatingChild(this).carvingProfileSampler();
}
IrisCaveProfileSampler createCarvingProfileSampler(PackRuntime runtime) {
Engine engine = runtime.engine();
IrisBiome resolved = resolveCarvingBiome(carving, engine, runtime.data());
if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().isEnabled()) {
return null;
CachedCarvingProfile recent = recentCarvingProfile;
if (recent != null && recent.key.matches(0L, data, engine)) {
return recent.sampler;
}
return new IrisCaveProfileSampler(engine, resolved.getCaveProfile());
RuntimeKey key = new RuntimeKey(0L, data, engine);
IrisCaveProfileSampler sampler = carvingProfileSamplers.computeIfAbsent(key, ignored -> {
IrisBiome resolved = resolveCarvingBiome(carving, engine, data);
if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().isEnabled()) {
return null;
}
return new IrisCaveProfileSampler(engine, resolved.getCaveProfile());
});
recentCarvingProfile = new CachedCarvingProfile(key, sampler);
return sampler;
}
public boolean hasCarvingReference() {
@@ -372,4 +400,28 @@ public class IrisFloatingChildBiomes implements Rarity {
return loaded;
});
}
private record RuntimeKey(long seed, IrisData data, Engine engine) {
private boolean matches(long seed, IrisData data, Engine engine) {
return this.seed == seed && this.data == data && this.engine == engine;
}
@Override
public boolean equals(Object object) {
return object instanceof RuntimeKey other && matches(other.seed, other.data, other.engine);
}
@Override
public int hashCode() {
int hash = Long.hashCode(seed);
hash = 31 * hash + System.identityHashCode(data);
return 31 * hash + System.identityHashCode(engine);
}
}
private record CachedEdgeProfile(RuntimeKey key, FloatingIslandEdgeProfile profile) {
}
private record CachedCarvingProfile(RuntimeKey key, IrisCaveProfileSampler sampler) {
}
}
@@ -1,57 +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.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.noise.CNG;
/**
* What one engine derives from an {@link IrisBiomePaletteLayer}: the block selection and depth generators of the
* seeds that sample it.
*/
public final class PaletteLayerRuntime {
private static final int LAYER_SEED_CAPACITY = 32;
private static final int LAYER_RECENT_SLOTS = 32;
private static final int HEIGHT_SEED_CAPACITY = 32;
private final PackRuntime runtime;
private final SeedTable<CNG> layerGenerators;
private final SeedTable<CNG> heightGenerators;
public PaletteLayerRuntime(IrisBiomePaletteLayer layer, PackRuntime runtime) {
this.runtime = runtime;
this.layerGenerators = new SeedTable<>(LAYER_SEED_CAPACITY, LAYER_RECENT_SLOTS,
seed -> layer.createLayerGenerator(seed, runtime));
this.heightGenerators = new SeedTable<>(HEIGHT_SEED_CAPACITY, IrisBiomePaletteLayer::createHeightGenerator);
}
/** The scope this runtime was built in, whose pack data resolves the layer's palette. */
public PackRuntime packRuntime() {
return runtime;
}
public CNG layerGenerator(long seed) {
return layerGenerators.get(seed);
}
public CNG heightGenerator(long seed) {
return heightGenerators.get(seed);
}
}
@@ -0,0 +1,49 @@
package art.arcane.iris.generation.cache;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.function.Function;
public final class LazyBoundedCache<K, V> {
private final int maximumSize;
private transient LinkedHashMap<K, V> entries;
public LazyBoundedCache(int maximumSize) {
if (maximumSize <= 0) {
throw new IllegalArgumentException("Maximum cache size must be positive");
}
this.maximumSize = maximumSize;
}
public synchronized V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
K requiredKey = Objects.requireNonNull(key, "Cache key");
Function<? super K, ? extends V> requiredMapping = Objects.requireNonNull(mappingFunction, "Cache mapping function");
if (entries != null) {
V cached = entries.get(requiredKey);
if (cached != null) {
return cached;
}
}
V computed = requiredMapping.apply(requiredKey);
if (computed == null) {
return null;
}
if (entries == null) {
entries = new LinkedHashMap<>(maximumSize, 1F, true);
}
entries.put(requiredKey, computed);
if (entries.size() > maximumSize) {
entries.sequencedKeySet().removeFirst();
}
return computed;
}
synchronized boolean isInitialized() {
return entries != null;
}
synchronized int size() {
return entries == null ? 0 : entries.size();
}
}
@@ -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;
}
}
@@ -22,7 +22,7 @@ import art.arcane.iris.pack.value.IrisRange;
import art.arcane.iris.generation.noise.IrisStyledRange;
import art.arcane.volmlib.util.math.M;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.math.RNG;
@@ -52,18 +52,18 @@ public final class IrisCaveProfileSampler {
private final boolean hasModules;
public IrisCaveProfileSampler(Engine engine, IrisCaveProfile profile) {
PackRuntime runtime = PackRuntime.of(engine, engine.getData());
IrisData data = engine.getData();
this.profile = profile;
List<ModuleState> moduleStates = new ArrayList<>();
RNG baseRng = new RNG(engine.getSeedManager().getCarve());
this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), runtime);
this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), runtime);
this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), runtime);
this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data);
this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data);
this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data);
IrisStyledRange threshold = profile.getDensityThreshold();
thresholdMin = threshold.getMin();
thresholdMax = threshold.getMax();
thresholdHasNoise = thresholdMin != thresholdMax && !threshold.getStyle().isFlat();
thresholdDensity = thresholdHasNoise ? threshold.getStyle().create(baseRng.nextParallelRNG(489_112), runtime) : null;
thresholdDensity = thresholdHasNoise ? threshold.getStyle().create(baseRng.nextParallelRNG(489_112), data) : null;
constantThreshold = thresholdMin == thresholdMax ? thresholdMin : M.lerp(thresholdMin, thresholdMax, 0.5D);
this.baseWeight = profile.getBaseWeight();
this.detailWeight = profile.getDetailWeight();
@@ -73,7 +73,7 @@ public final class IrisCaveProfileSampler {
double weight = Math.abs(baseWeight) + Math.abs(detailWeight);
int index = 0;
for (IrisCaveFieldModule module : profile.getModules()) {
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), runtime);
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data);
ModuleState state = new ModuleState(module, moduleDensity);
moduleStates.add(state);
weight += Math.abs(state.weight);
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.GenerationFailures;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.mantle.EngineMantle;
@@ -47,7 +46,6 @@ final class DecoratorCore {
private static volatile NativeBlockState twistingVines;
private static volatile NativeBlockState twistingVinesPlant;
/** Per-thread placement options; callers clear the mantle reference once a placement returns. */
static final ThreadLocal<PlaceOpts> SCRATCH_OPTS = ThreadLocal.withInitial(PlaceOpts::new);
@@ -94,27 +92,25 @@ final class DecoratorCore {
}
static IrisDecorator pickDecorator(IrisBiome biome, IrisDecorationPart part, RNG gRNG,
RNG colRng, PackRuntime runtime, double realX, double realZ) {
RNG colRng, IrisData data, double realX, double realZ) {
IrisDecorator[] bucket = biome.getDecoratorBucket(part);
if (bucket.length == 0) {
return null;
}
DecoratorRuntime[] decoratorRuntimes = runtime.biome(biome).decorators(part);
IrisDecorator picked = null;
int count = 0;
for (int index = 0; index < bucket.length; index++) {
IrisDecorator d = bucket[index];
for (IrisDecorator d : bucket) {
try {
if (d.passesChanceGate(gRNG, realX, realZ, decoratorRuntimes[index])) {
if (d.passesChanceGate(gRNG, realX, realZ, data)) {
count++;
if (count == 1 || colRng.nextInt(count) == 0) {
picked = d;
}
}
} catch (Throwable e) {
skip(e, d, runtime.data(), (int) realX, -1, (int) realZ, biome);
skip(e, d, data, (int) realX, -1, (int) realZ, biome);
}
}
@@ -123,14 +119,14 @@ final class DecoratorCore {
static void placeSurfaceSingle(IrisDecorator decorator,
int x, int z, int realX, int height, int realZ,
Hunk<NativeBlockState> data, RNG rng, PackRuntime runtime,
Hunk<NativeBlockState> data, RNG rng, IrisData irisData,
boolean underwater, boolean caveSkipFluid, EngineMantle mantle) {
if (height < 0 || height >= data.getHeight()) {
return;
}
NativeBlockState bdx = data.get(x, height, z);
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
if (!IrisSpeleothems.isSpike(bd) && !underwater && !canGoOn(bd, bdx)
&& !decorator.isForcePlace() && decorator.getForceBlock() == null) {
@@ -142,14 +138,14 @@ final class DecoratorCore {
return;
}
data.set(x, height, z, fixFacesForHunk(
decorator.getForceBlock().getBlockData(runtime.data()), data, x, z, realX, height, realZ, mantle));
decorator.getForceBlock().getBlockData(irisData), data, x, z, realX, height, realZ, mantle));
}
if (!decorator.isForcePlace()) {
if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(runtime.data()), bdx)) {
if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(irisData), bdx)) {
return;
}
if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(runtime.data()), bdx)) {
if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(irisData), bdx)) {
return;
}
}
@@ -180,7 +176,7 @@ final class DecoratorCore {
data.set(x, lowerY, z, lower);
data.set(x, upperY, z, IrisProceduralBlocks.normalizeWaterlogging(upper, data.get(x, upperY, z), true));
} catch (Throwable e) {
skip(e, decorator, runtime.data(), realX, lowerY, realZ, null);
skip(e, decorator, irisData, realX, lowerY, realZ, null);
}
return;
}
@@ -206,8 +202,8 @@ final class DecoratorCore {
static void placeSingleAt(IrisDecorator decorator, int x, int z,
int realX, int height, int realZ, Hunk<NativeBlockState> data,
RNG rng, PackRuntime runtime, boolean applyFixFaces, EngineMantle mantle) {
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
RNG rng, IrisData irisData, boolean applyFixFaces, EngineMantle mantle) {
NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
if (bd == null) {
return;
}
@@ -216,7 +212,7 @@ final class DecoratorCore {
return;
}
if (IrisSpeleothems.isSpike(bd)) {
if (height + 1 < data.getHeight() && allowsSurface(decorator, data.get(x, height + 1, z), runtime.data())) {
if (height + 1 < data.getHeight() && allowsSurface(decorator, data.get(x, height + 1, z), irisData)) {
placeSingleSpike(bd, data, x, z, height, false, false);
}
return;
@@ -229,17 +225,17 @@ final class DecoratorCore {
static void placeStackUp(IrisDecorator decorator, int x, int z, int realX, int realZ,
int height, int max, Hunk<NativeBlockState> data,
RNG rng, PackRuntime runtime, PlaceOpts opts) {
RNG rng, IrisData irisData, PlaceOpts opts) {
if (height < 0 || height >= data.getHeight()) {
return;
}
NativeBlockState support = data.get(x, height, z);
if (!allowsSurface(decorator, support, runtime.data())) {
if (!allowsSurface(decorator, support, irisData)) {
return;
}
int effectiveMax = opts.underwater ? Math.min(max, opts.fluidHeight - height) : max;
int stack = computeStack(decorator, rng, realX, realZ, runtime, effectiveMax);
int stack = computeStack(decorator, rng, realX, realZ, irisData, effectiveMax);
int placed = 0;
boolean hasSpikes = false;
NativeBlockState sampledBlock = null;
@@ -258,8 +254,8 @@ final class DecoratorCore {
boolean top = threshold >= decorator.getTopThreshold();
if (sampledBlock == null || top != sampledTop) {
sampledBlock = top
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
: decorator.pickBlockData(rng, runtime, realX, realZ);
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
sampledTop = top;
}
NativeBlockState block = sampledBlock;
@@ -292,15 +288,15 @@ final class DecoratorCore {
static void placeStackDown(IrisDecorator decorator, int x, int z, int realX, int realZ,
int height, int minHeight, Hunk<NativeBlockState> data,
RNG rng, PackRuntime runtime, int max, PlaceOpts opts, EngineMantle mantle) {
RNG rng, IrisData irisData, int max, PlaceOpts opts, EngineMantle mantle) {
if (height < 0 || height >= data.getHeight()) {
return;
}
NativeBlockState support = height + 1 < data.getHeight() ? data.get(x, height + 1, z) : null;
if (!allowsSurface(decorator, support, runtime.data())) {
if (!allowsSurface(decorator, support, irisData)) {
return;
}
int stack = computeStack(decorator, rng, realX, realZ, runtime, max);
int stack = computeStack(decorator, rng, realX, realZ, irisData, max);
int placed = 0;
boolean hasSpikes = false;
NativeBlockState sampledBlock = null;
@@ -319,8 +315,8 @@ final class DecoratorCore {
boolean top = threshold >= decorator.getTopThreshold();
if (sampledBlock == null || top != sampledTop) {
sampledBlock = top
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
: decorator.pickBlockData(rng, runtime, realX, realZ);
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
sampledTop = top;
}
NativeBlockState block = sampledBlock;
@@ -353,11 +349,11 @@ final class DecoratorCore {
static void placeFloatingSimple(IrisDecorator decorator,
int xf, int zf, int realX, int realZ,
int height, int max, Hunk<NativeBlockState> data,
RNG rng, PackRuntime runtime, EngineMantle mantle) {
RNG rng, IrisData irisData, EngineMantle mantle) {
if (!hasFloatingSurface(data, xf, height, zf)) {
return;
}
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
if (bd == null) {
return;
}
@@ -367,7 +363,7 @@ final class DecoratorCore {
}
if (IrisSpeleothems.isSpike(bd)) {
if (max > 1 && allowsSurface(decorator, data.get(xf, height, zf), runtime.data())) {
if (max > 1 && allowsSurface(decorator, data.get(xf, height, zf), irisData)) {
placeSingleSpike(bd, data, xf, zf, height + 1, true, false);
}
return;
@@ -387,7 +383,7 @@ final class DecoratorCore {
data.set(xf, lowerY, zf, IrisProceduralBlocks.normalizeWaterlogging(lower, data.get(xf, lowerY, zf), true));
data.set(xf, upperY, zf, IrisProceduralBlocks.normalizeWaterlogging(upper, data.get(xf, upperY, zf), true));
} catch (Throwable e) {
skip(e, decorator, runtime.data(), realX, lowerY, realZ, null);
skip(e, decorator, irisData, realX, lowerY, realZ, null);
}
return;
}
@@ -400,11 +396,11 @@ final class DecoratorCore {
static int placeFloatingStacked(IrisDecorator decorator,
int xf, int zf, int realX, int realZ,
int height, int max, Hunk<NativeBlockState> data,
RNG rng, PackRuntime runtime, EngineMantle mantle) {
RNG rng, IrisData irisData, EngineMantle mantle) {
if (!hasFloatingSurface(data, xf, height, zf)) {
return 0;
}
int stack = decorator.getHeight(rng, realX, realZ, runtime);
int stack = decorator.getHeight(rng, realX, realZ, irisData);
if (decorator.isScaleStack()) {
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack());
} else {
@@ -424,8 +420,8 @@ final class DecoratorCore {
boolean top = threshold >= decorator.getTopThreshold();
if (sampledBlock == null || top != sampledTop) {
sampledBlock = top
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
: decorator.pickBlockData(rng, runtime, realX, realZ);
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
sampledTop = top;
}
NativeBlockState bd = sampledBlock;
@@ -437,7 +433,7 @@ final class DecoratorCore {
break;
}
if (IrisSpeleothems.isSpike(bd)) {
if (!allowsSurface(decorator, data.get(xf, height, zf), runtime.data())
if (!allowsSurface(decorator, data.get(xf, height, zf), irisData)
|| !IrisSpeleothems.canPlace(bd, data, xf, zf, h, true, false)) {
break;
}
@@ -585,8 +581,8 @@ final class DecoratorCore {
}
static int computeStack(IrisDecorator decorator, RNG rng, double realX, double realZ,
PackRuntime runtime, int max) {
int stack = decorator.getHeight(rng, realX, realZ, runtime);
IrisData irisData, int max) {
int stack = decorator.getHeight(rng, realX, realZ, irisData);
if (decorator.isScaleStack()) {
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack());
} else {
@@ -1,57 +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.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.noise.CNG;
/** What one engine derives from an {@link IrisDecorator}: the stack, placement and variance generators of each seed. */
public final class DecoratorRuntime {
private static final int SEED_CAPACITY = 32;
private final PackRuntime runtime;
private final SeedTable<CNG> heightGenerators;
private final SeedTable<CNG> layerGenerators;
private final SeedTable<CNG> varianceGenerators;
public DecoratorRuntime(IrisDecorator decorator, PackRuntime runtime) {
this.runtime = runtime;
this.heightGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createHeightGenerator(seed, runtime));
this.layerGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createLayerGenerator(seed, runtime));
this.varianceGenerators = new SeedTable<>(SEED_CAPACITY, seed -> decorator.createVarianceGenerator(seed, runtime));
}
/** The scope this runtime was built in, whose pack data resolves the decorator's palettes. */
public PackRuntime packRuntime() {
return runtime;
}
public CNG heightGenerator(long seed) {
return heightGenerators.get(seed);
}
public CNG layerGenerator(long seed) {
return layerGenerators.get(seed);
}
public CNG varianceGenerator(long seed) {
return varianceGenerators.get(seed);
}
}
@@ -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.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.volmlib.util.collection.KList;
/**
* What one engine derives from an {@link IrisDepositGenerator}: the clump variants of the engine's deposit seed, at
* the configured size and at each scaled size the deposit modifier asks for.
*/
public final class DepositRuntime {
private static final int SCALED_SIZE_CAPACITY = 64;
private final IrisDepositGenerator deposit;
private final PackRuntime runtime;
private final long depositSeed;
private final SeedTable<KList<IrisObject>> scaledClumps;
private volatile KList<IrisObject> clumps;
public DepositRuntime(IrisDepositGenerator deposit, PackRuntime runtime) {
this.deposit = deposit;
this.runtime = runtime;
this.depositSeed = runtime.engine().getSeedManager().getDeposit();
this.scaledClumps = new SeedTable<>(SCALED_SIZE_CAPACITY, sizes -> deposit.createScaledClumps(
depositSeed, minSize(sizes), maxSize(sizes), runtime.data()));
}
public KList<IrisObject> clumps() {
KList<IrisObject> built = clumps;
if (built != null) {
return built;
}
synchronized (this) {
if (clumps == null) {
clumps = deposit.createClumps(depositSeed, runtime.data());
}
return clumps;
}
}
public KList<IrisObject> scaledClumps(int minSize, int maxSize) {
return scaledClumps.get(sizeKey(minSize, maxSize));
}
private static long sizeKey(int minSize, int maxSize) {
return ((long) minSize << 32) | (maxSize & 0xffffffffL);
}
private static int minSize(long sizeKey) {
return (int) (sizeKey >>> 32);
}
private static int maxSize(long sizeKey) {
return (int) sizeKey;
}
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -37,8 +36,7 @@ public class FloatingDecorator {
int height, int max, Hunk<NativeBlockState> data, RNG rng,
Runnable candidatesNullCallback) {
RNG gRNG = new RNG(DecoratorCore.partSeed(engine.getSeedManager().getComponent(), part));
PackRuntime runtime = PackRuntime.of(engine);
IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, runtime, realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, engine.getData(), realX, realZ);
if (decorator == null) {
candidatesNullCallback.run();
@@ -47,11 +45,11 @@ public class FloatingDecorator {
if (!decorator.isStacking()) {
DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data,
gRNG, runtime, engine.getMantle());
gRNG, engine.getData(), engine.getMantle());
return max > 1 ? 1 : 0;
}
return DecoratorCore.placeFloatingStacked(decorator, xf, zf, realX, realZ, height, max, data,
gRNG, runtime, engine.getMantle());
gRNG, engine.getData(), engine.getMantle());
}
}
@@ -1,6 +1,5 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.block.B;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
@@ -33,7 +32,7 @@ public final class HydrologyVegetation {
this.shoreRng = new RNG(DecoratorCore.partSeed(this.seed, IrisDecorationPart.SHORE_LINE));
}
public void decorate(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, WaterRole role, Water water, PackRuntime runtime) {
public void decorate(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, WaterRole role, Water water, IrisData data) {
Placement placement = placement(role);
if (placement == Placement.NONE) {
return;
@@ -46,7 +45,7 @@ public final class HydrologyVegetation {
if (ground < 0 || ground + 1 >= output.getHeight()) {
return;
}
Column column = new Column(output, localX, localZ, x, z, ground, water, runtime);
Column column = new Column(output, localX, localZ, x, z, ground, water, data);
if (placement == Placement.SHORE) {
decorateShore(column, decorators.shore);
return;
@@ -113,7 +112,7 @@ public final class HydrologyVegetation {
int count = 0;
for (IrisDecorator decorator : bucket) {
try {
if (!decorator.passesChanceGate(partRng, column.x, column.z, column.runtime)) {
if (!decorator.passesChanceGate(partRng, column.x, column.z, column.data)) {
continue;
}
} catch (Throwable e) {
@@ -214,10 +213,9 @@ public final class HydrologyVegetation {
private final int z;
private final int ground;
private final Water water;
private final PackRuntime runtime;
private final IrisData data;
private Column(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, int ground, Water water, PackRuntime runtime) {
private Column(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, int ground, Water water, IrisData data) {
this.output = output;
this.localX = localX;
this.localZ = localZ;
@@ -225,8 +223,7 @@ public final class HydrologyVegetation {
this.z = z;
this.ground = ground;
this.water = water;
this.runtime = runtime;
this.data = runtime.data();
this.data = data;
}
private boolean accepts(IrisDecorator decorator, NativeBlockState support) {
@@ -234,7 +231,7 @@ public final class HydrologyVegetation {
}
private int stack(IrisDecorator decorator, RNG rng, int room) {
return decorator.isStacking() ? Math.min(room, DecoratorCore.computeStack(decorator, rng, x, z, runtime, room)) : 1;
return decorator.isStacking() ? Math.min(room, DecoratorCore.computeStack(decorator, rng, x, z, data, room)) : 1;
}
private void place(IrisDecorator decorator, RNG rng, int baseY, int room, Slot slot, NativeBlockState support) {
@@ -246,7 +243,7 @@ public final class HydrologyVegetation {
}
private void placePicked(IrisDecorator decorator, RNG rng, int baseY, int room, Slot slot, NativeBlockState support) {
NativeBlockState first = decorator.pickBlockData(rng, runtime, x, z);
NativeBlockState first = decorator.pickBlockData(rng, data, x, z);
if (first == null) {
return;
}
@@ -263,7 +260,7 @@ public final class HydrologyVegetation {
int y = baseY + index;
boolean top = (stack == 1 ? 1D : (double) index / (stack - 1)) >= decorator.getTopThreshold();
if (top != sampledTop) {
sampled = top ? decorator.pickBlockDataTop(rng, runtime, x, z) : decorator.pickBlockData(rng, runtime, x, z);
sampled = top ? decorator.pickBlockDataTop(rng, data, x, z) : decorator.pickBlockData(rng, data, x, z);
sampledTop = top;
}
NativeBlockState block = sampled == null ? null : fit(sampled, y, slot, decorator, index == 0 ? support : null);
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.biome.IrisBiome;
@@ -48,22 +47,21 @@ public class IrisCeilingDecorator extends IrisEngineDecorator {
Hunk<NativeBlockState> data, IrisBiome biome, InferredType inferredType, int height, int max) {
boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(inferredType);
RNG rng = getRNG(realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
if (decorator == null) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, height, max, caveSkipFluid, runtime);
place(decorator, x, z, realX, realZ, data, height, max, caveSkipFluid);
} catch (Throwable e) {
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
}
}
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
int height, int max, boolean caveSkipFluid, PackRuntime runtime) {
int height, int max, boolean caveSkipFluid) {
if (!decorator.isStacking()) {
if (caveSkipFluid) {
NativeBlockState state = data.get(x, height, z);
@@ -71,13 +69,13 @@ public class IrisCeilingDecorator extends IrisEngineDecorator {
return;
}
}
DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, partRNG, runtime, true, getEngine().getMantle());
DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, partRNG, getData(), true, getEngine().getMantle());
return;
}
DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get();
opts.reset();
opts.caveSkipFluid = caveSkipFluid;
DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, partRNG, runtime, max, opts, getEngine().getMantle());
DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, partRNG, getData(), max, opts, getEngine().getMantle());
}
}
@@ -18,9 +18,9 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
@@ -52,6 +52,8 @@ import lombok.experimental.Accessors;
@Description("A biome decorator is used for placing flowers, grass, cacti and so on")
@Data
public class IrisDecorator {
private final transient LazyBoundedCache<GeneratorKey, Generators> generators = new LazyBoundedCache<>(32);
private transient volatile Generators recentGenerators;
private final transient AtomicCache<KList<NativeBlockState>> blockData = new AtomicCache<>();
private final transient AtomicCache<KList<NativeBlockState>> blockDataTops = new AtomicCache<>();
private final transient AtomicCache<NativeBlockState[]> blockDataArray = new AtomicCache<>();
@@ -116,39 +118,50 @@ public class IrisDecorator {
@Description("When the stack passes the top threshold, the top palette will start being used instead of the normal palette.")
private double topThreshold = 1.0;
public int getHeight(RNG rng, double x, double z, PackRuntime runtime) {
public int getHeight(RNG rng, double x, double z, IrisData data) {
if (stackMin == stackMax) {
return stackMin;
}
return getHeightGenerator(rng, runtime)
return getHeightGenerator(rng, data)
.fit(stackMin, stackMax,
x / heightVariance.getZoom(),
z / heightVariance.getZoom());
}
public CNG getHeightGenerator(RNG rng, PackRuntime runtime) {
return runtime.decorator(this).heightGenerator(rng.getSeed());
public CNG getHeightGenerator(RNG rng, IrisData data) {
AtomicCache<CNG> cache = generators(rng, data).height;
CNG cached = cache.getIfPresent();
return cached != null ? cached : cache.aquire(() ->
heightVariance.create(rng.nextParallelRNG(getBlockData(data).size() + stackMax + stackMin), data));
}
public CNG getGenerator(RNG rng, PackRuntime runtime) {
return runtime.decorator(this).layerGenerator(rng.getSeed());
public CNG getGenerator(RNG rng, IrisData data) {
AtomicCache<CNG> cache = generators(rng, data).layer;
CNG cached = cache.getIfPresent();
return cached != null ? cached : cache.aquire(() -> style.create(rng.nextParallelRNG(getBlockData(data).size()), data));
}
public CNG getVarianceGenerator(RNG rng, PackRuntime runtime) {
return runtime.decorator(this).varianceGenerator(rng.getSeed());
public CNG getVarianceGenerator(RNG rng, IrisData data) {
AtomicCache<CNG> cache = generators(rng, data).variance;
CNG cached = cache.getIfPresent();
return cached != null ? cached : cache.aquire(() -> createVarianceGenerator(rng, data));
}
public CNG createHeightGenerator(long seed, PackRuntime runtime) {
return heightVariance.create(new RNG(seed).nextParallelRNG(getBlockData(runtime.data()).size() + stackMax + stackMin), runtime);
private Generators generators(RNG rng, IrisData data) {
long seed = rng.getSeed();
Engine engine = data == null ? null : data.getEngine();
Generators recent = recentGenerators;
if (recent != null && recent.key.seed == seed && recent.key.data == data && recent.key.engine == engine) {
return recent;
}
Generators selected = generators.computeIfAbsent(new GeneratorKey(seed, data, engine), Generators::new);
recentGenerators = selected;
return selected;
}
public CNG createLayerGenerator(long seed, PackRuntime runtime) {
return style.create(new RNG(seed).nextParallelRNG(getBlockData(runtime.data()).size()), runtime);
}
public CNG createVarianceGenerator(long seed, PackRuntime runtime) {
return variance.createNoCache(deriveVarianceSeed(new RNG(seed), runtime.data()), runtime).scale(1D / variance.getZoom());
private CNG createVarianceGenerator(RNG rng, IrisData data) {
return variance.createNoCache(deriveVarianceSeed(rng, data), data).scale(1D / variance.getZoom());
}
RNG deriveVarianceSeed(RNG rng, IrisData data) {
@@ -160,38 +173,27 @@ public class IrisDecorator {
return palette;
}
public boolean passesChanceGate(RNG rng, double x, double z, PackRuntime runtime) {
return passesChanceGate(rng, x, z, runtime.decorator(this));
}
/** {@link #passesChanceGate(RNG, double, double, PackRuntime)} for a caller that already holds this decorator's runtime. */
public boolean passesChanceGate(RNG rng, double x, double z, DecoratorRuntime decoratorRuntime) {
if (getBlockData(decoratorRuntime.packRuntime().data()).isEmpty()) {
public boolean passesChanceGate(RNG rng, double x, double z, IrisData data) {
if (getBlockData(data).isEmpty()) {
return false;
}
double blocksPerSample = chanceBlocksPerSample();
double xx = x / blocksPerSample;
double zz = z / blocksPerSample;
return decoratorRuntime.layerGenerator(rng.getSeed()).fitDouble(0D, 1D, xx, zz) <= chance;
double xx = x / style.getZoom();
double zz = z / style.getZoom();
return getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance;
}
/** A style without a seed divides by its zoom here on top of its own scale; a seeded one is read in plain blocks. */
private double chanceBlocksPerSample() {
return style.isSeeded() ? 1 : style.getZoom();
}
public NativeBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, PackRuntime runtime) {
if (!passesChanceGate(rng, x, z, runtime)) {
public NativeBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, IrisData data) {
if (!passesChanceGate(rng, x, z, data)) {
return null;
}
if (getBlockData(runtime.data()).size() == 1) {
return getBlockData(runtime.data()).get(0);
if (getBlockData(data).size() == 1) {
return getBlockData(data).get(0);
}
return getVarianceGenerator(rng, runtime).fit(getBlockData(runtime.data()), z, x);
return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x);
}
public NativeBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, PackRuntime runtime) {
KList<NativeBlockState> palette = getBlockData(runtime.data());
public NativeBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) {
KList<NativeBlockState> palette = getBlockData(data);
if (palette.isEmpty()) {
IrisLogging.warnOnce("decorator-empty:" + b.getName(), "Empty Block Data for " + b.getName());
return null;
@@ -201,25 +203,24 @@ public class IrisDecorator {
return palette.get(0);
}
return getVarianceGenerator(rng, runtime).fit(palette, z, y, x); //X and Z must be switched
return getVarianceGenerator(rng, data).fit(palette, z, y, x); //X and Z must be switched
}
public NativeBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, PackRuntime runtime) {
KList<NativeBlockState> topPalette = getBlockDataTops(runtime.data());
public NativeBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) {
KList<NativeBlockState> topPalette = getBlockDataTops(data);
if (topPalette.isEmpty()) {
return getBlockData100(b, rng, x, y, z, runtime);
return getBlockData100(b, rng, x, y, z, data);
}
double blocksPerSample = chanceBlocksPerSample();
double xx = x / blocksPerSample;
double zz = z / blocksPerSample;
double xx = x / style.getZoom();
double zz = z / style.getZoom();
if (getGenerator(rng, runtime).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here
if (getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here
if (topPalette.size() == 1) {
return topPalette.get(0);
}
return getVarianceGenerator(rng, runtime).fit(topPalette, z, y, x); //X and Z must be switched
return getVarianceGenerator(rng, data).fit(topPalette, z, y, x); //X and Z must be switched
}
return null;
@@ -335,30 +336,55 @@ public class IrisDecorator {
return resolved;
}
public NativeBlockState pickBlockData(RNG rng, PackRuntime runtime, double x, double z) {
NativeBlockState[] arr = getBlockDataArray(runtime.data());
public NativeBlockState pickBlockData(RNG rng, IrisData data, double x, double z) {
NativeBlockState[] arr = getBlockDataArray(data);
if (arr.length == 0) {
return null;
}
if (arr.length == 1) {
return arr[0];
}
return arr[Math.abs((int) getVarianceGenerator(rng, runtime).fit(0, arr.length - 1, z, x))];
return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))];
}
public NativeBlockState pickBlockDataTop(RNG rng, PackRuntime runtime, double x, double z) {
NativeBlockState[] arr = getBlockDataTopsArray(runtime.data());
public NativeBlockState pickBlockDataTop(RNG rng, IrisData data, double x, double z) {
NativeBlockState[] arr = getBlockDataTopsArray(data);
if (arr.length == 0) {
return pickBlockData(rng, runtime, x, z);
return pickBlockData(rng, data, x, z);
}
if (arr.length == 1) {
return arr[0];
}
return arr[Math.abs((int) getVarianceGenerator(rng, runtime).fit(0, arr.length - 1, z, x))];
return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))];
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isStacking() {
return getStackMax() > 1;
}
private static final class Generators {
private final GeneratorKey key;
private final AtomicCache<CNG> layer = new AtomicCache<>();
private final AtomicCache<CNG> variance = new AtomicCache<>();
private final AtomicCache<CNG> height = new AtomicCache<>();
private Generators(GeneratorKey key) {
this.key = key;
}
}
private record GeneratorKey(long seed, IrisData data, Engine engine) {
@Override
public boolean equals(Object other) {
return other instanceof GeneratorKey key
&& seed == key.seed && data == key.data && engine == key.engine;
}
@Override
public int hashCode() {
return 31 * (31 * Long.hashCode(seed) + System.identityHashCode(data))
+ System.identityHashCode(engine);
}
}
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.structure.object.IrisObject;
@@ -63,10 +62,12 @@ public class IrisDepositGenerator {
private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L;
private static final long FNV_PRIME = 0x100000001b3L;
private final transient ConcurrentMap<ClumpCacheKey, KList<IrisObject>> objects = new ConcurrentHashMap<>();
private final transient AtomicCache<KList<NativeBlockState>> blockData = new AtomicCache<>();
private final transient AtomicCache<Boolean> ore = new AtomicCache<>();
private final transient AtomicCache<KSet<String>> replaceableBlockData = new AtomicCache<>();
private final transient AtomicCache<KSet<String>> surfaceReplaceableBlockData = new AtomicCache<>();
private final transient ConcurrentMap<ClumpCacheKey, KList<IrisObject>> scaledObjects = new ConcurrentHashMap<>();
@Required
@MinNumber(-8192)
@MaxNumber(8192)
@@ -144,47 +145,54 @@ public class IrisDepositGenerator {
@Description("If set to true, this deposit will replace bedrock")
private boolean replaceBedrock = false;
public IrisObject getClump(PackRuntime runtime, RNG rng) {
public IrisObject getClump(Engine engine, RNG rng, IrisData rdata) {
if (shape != IrisDepositShape.IRIS) {
return generateConfiguredClumpObject(rng, runtime.data(), minSize, maxSize);
return generateConfiguredClumpObject(rng, rdata, minSize, maxSize);
}
KList<IrisObject> objects = runtime.deposit(this).clumps();
ClumpCacheKey cacheKey = new ClumpCacheKey(engine.getSeedManager().getDeposit(), minSize, maxSize);
KList<IrisObject> objects = this.objects.computeIfAbsent(cacheKey, key -> {
RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata));
KList<IrisObject> objectsf = new KList<>();
for (int i = 0; i < varience; i++) {
objectsf.add(generateClumpObject(
rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize()));
}
return objectsf;
});
return objects.get(rng.i(0, objects.size()));
}
public IrisObject getClump(PackRuntime runtime, RNG rng, double sizeMultiplier) {
public IrisObject getClump(Engine engine, RNG rng, IrisData rdata, double sizeMultiplier) {
if (sizeMultiplier == 1D) {
return getClump(runtime, rng);
return getClump(engine, rng, rdata);
}
int scaledMinSize = scaledDepositSize(minSize, sizeMultiplier);
int scaledMaxSize = scaledDepositSize(maxSize, sizeMultiplier);
if (shape != IrisDepositShape.IRIS) {
return generateConfiguredClumpObject(rng, runtime.data(), scaledMinSize, scaledMaxSize);
return generateConfiguredClumpObject(rng, rdata, scaledMinSize, scaledMaxSize);
}
KList<IrisObject> objects = runtime.deposit(this).scaledClumps(scaledMinSize, scaledMaxSize);
ClumpCacheKey cacheKey = new ClumpCacheKey(
engine.getSeedManager().getDeposit(), scaledMinSize, scaledMaxSize);
KList<IrisObject> objects = scaledObjects.computeIfAbsent(cacheKey, key -> {
long sizeSeed = ((long) key.minSize() << 32) ^ (key.maxSize() & 0xffffffffL);
RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata) + sizeSeed);
KList<IrisObject> generated = new KList<>();
for (int i = 0; i < varience; i++) {
generated.add(generateClumpObject(
rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize()));
}
return generated;
});
return objects.get(rng.i(0, objects.size()));
}
public KList<IrisObject> createClumps(long depositSeed, IrisData rdata) {
return createClumpVariants(new RNG(depositSeed + stableClumpSalt(rdata)), rdata, minSize, maxSize);
}
public KList<IrisObject> createScaledClumps(long depositSeed, int scaledMinSize, int scaledMaxSize, IrisData rdata) {
long sizeSeed = ((long) scaledMinSize << 32) ^ (scaledMaxSize & 0xffffffffL);
return createClumpVariants(new RNG(depositSeed + stableClumpSalt(rdata) + sizeSeed), rdata, scaledMinSize, scaledMaxSize);
}
private KList<IrisObject> createClumpVariants(RNG rngv, IrisData rdata, int clumpMinSize, int clumpMaxSize) {
KList<IrisObject> variants = new KList<>();
for (int i = 0; i < varience; i++) {
variants.add(generateClumpObject(rngv.nextParallelRNG(2349 * i + 3598), rdata, clumpMinSize, clumpMaxSize));
}
return variants;
}
public int getMaxDimension() {
return Math.min(11, (int) Math.ceil(Math.cbrt(maxSize)));
}
@@ -271,7 +279,7 @@ public class IrisDepositGenerator {
}
/**
* Advances {@code rng} exactly as {@link #getClump(PackRuntime, RNG)} would and reports the clump's width
* Advances {@code rng} exactly as {@link #getClump(Engine, RNG, IrisData)} would and reports the clump's width
* and lowest block offset without building it, so a caller can reject the clump first and replay the build
* only for clumps it keeps. Returns null without drawing when the shape has no footprint path.
*/
@@ -674,6 +682,9 @@ public class IrisDepositGenerator {
return false;
}
record ClumpCacheKey(long depositSeed, int minSize, int maxSize) {
}
@FunctionalInterface
interface CellSink {
void add(int x, int y, int z);
@@ -1,6 +1,7 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.value.IrisRange;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.collection.KList;
@@ -10,24 +11,20 @@ import java.util.Arrays;
/**
* One ore list (a biome's, region's or dimension's surface or underground ores) indexed by Y. Each Y
* holds the indices of the generators whose range contains it, in list order, so resolving a block tries exactly
* the generators that could place there and still returns the first one that does. The seeded chance fields live in
* an {@link OreBandsRuntime}, aligned with {@link #generators()}.
* holds the generators whose range contains it, in list order, so resolving a block tries exactly
* the generators that could place there and still returns the first one that does.
*/
public final class IrisOreBands {
public static final IrisOreBands EMPTY = new IrisOreBands(new IrisOreGenerator[0], 0, -1, null);
private static final int MAXIMUM_INDEXED_HEIGHT = 8192;
private final IrisOreGenerator[] generators;
private final int[] everyGenerator;
private final int minY;
private final int maxY;
private final int[][] byY;
private final IrisOreGenerator[][] byY;
private IrisOreBands(IrisOreGenerator[] generators, int minY, int maxY, int[][] byY) {
private IrisOreBands(IrisOreGenerator[] generators, int minY, int maxY, IrisOreGenerator[][] byY) {
this.generators = generators;
this.everyGenerator = new int[generators.length];
Arrays.setAll(everyGenerator, index -> index);
this.minY = minY;
this.maxY = maxY;
this.byY = byY;
@@ -60,19 +57,19 @@ public final class IrisOreBands {
height > MAXIMUM_INDEXED_HEIGHT ? null : index(generators, minY, (int) height));
}
private static int[][] index(IrisOreGenerator[] generators, int minY, int height) {
int[][] byY = new int[height][];
int[] scratch = new int[generators.length];
int[] previous = null;
private static IrisOreGenerator[][] index(IrisOreGenerator[] generators, int minY, int height) {
IrisOreGenerator[][] byY = new IrisOreGenerator[height][];
IrisOreGenerator[] scratch = new IrisOreGenerator[generators.length];
IrisOreGenerator[] previous = null;
for (int offset = 0; offset < height; offset++) {
int y = minY + offset;
int count = 0;
for (int index = 0; index < generators.length; index++) {
if (generators[index].getRange().contains(y)) {
scratch[count++] = index;
for (IrisOreGenerator generator : generators) {
if (generator.getRange().contains(y)) {
scratch[count++] = generator;
}
}
int[] candidates = Arrays.copyOf(scratch, count);
IrisOreGenerator[] candidates = Arrays.copyOf(scratch, count);
byY[offset] = previous != null && Arrays.equals(previous, candidates) ? previous : candidates;
previous = byY[offset];
}
@@ -95,18 +92,13 @@ public final class IrisOreBands {
return y >= minY && y <= maxY;
}
/** The banded generators in list order; chance fields built for them must keep this order. */
public IrisOreGenerator[] generators() {
return generators.clone();
}
/**
* The ore placed at a Y inside {@link #contains(int)}, or null when no generator places one.
*/
NativeBlockState generate(int x, int y, int z, RNG rng, IrisOreGenerator.OreChance[] chances, PackRuntime runtime) {
int[] candidates = byY == null ? everyGenerator : byY[y - minY];
for (int index : candidates) {
NativeBlockState ore = generators[index].generate(x, y, z, rng, chances[index], runtime);
public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data, Engine engine) {
IrisOreGenerator[] candidates = byY == null ? generators : byY[y - minY];
for (IrisOreGenerator candidate : candidates) {
NativeBlockState ore = candidate.generate(x, y, z, rng, data, engine);
if (ore != null) {
return ore;
}
@@ -18,13 +18,13 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.pack.value.IrisRange;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
@@ -56,46 +56,72 @@ public class IrisOreGenerator {
@Description("Vertical band (min, max) this ore can generate in, in engine-local Y where 0 is the bottom of the dimension, not world Y.")
private IrisRange range = new IrisRange(30, 80);
public void warm(RNG rng, PackRuntime runtime) {
runtime.oreChance(this, rng.getSeed());
palette.getLayerGenerator(rng, runtime);
private final transient LazyBoundedCache<ChanceKey, OreChance> chanceCache = new LazyBoundedCache<>(32);
private transient volatile CachedChance recentChance;
public void warm(RNG rng, IrisData data) {
chance(rng, data);
palette.getLayerGenerator(rng, data);
}
public NativeBlockState generate(int x, int y, int z, RNG rng, PackRuntime runtime) {
if (!canPlaceAt(y)) {
public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data) {
return generate(x, y, z, rng, data, data == null ? null : data.getEngine());
}
public NativeBlockState generate(int x, int y, int z, RNG rng, IrisData data, Engine engine) {
if (threshold <= 0 || !range.contains(y)) {
return null;
}
return placeByChance(x, y, z, rng, runtime.oreChance(this, rng.getSeed()), runtime);
}
/** Places with a chance field already resolved for {@code rng}'s seed, as {@link OreBandsRuntime} holds them. */
public NativeBlockState generate(int x, int y, int z, RNG rng, OreChance chance, PackRuntime runtime) {
if (!canPlaceAt(y)) {
if (palette.getPalette().isEmpty()) {
return null;
}
return placeByChance(x, y, z, rng, chance, runtime);
}
private boolean canPlaceAt(int y) {
return threshold > 0 && range.contains(y) && !palette.getPalette().isEmpty();
}
private NativeBlockState placeByChance(int x, int y, int z, RNG rng, OreChance chance, PackRuntime runtime) {
if (chance.sample(x, y, z) > threshold) {
if (chance(rng, data, engine).sample(x, y, z) > threshold) {
return null;
}
return palette.get(rng, x, y, z, runtime);
return palette.get(rng, x, y, z, data);
}
public OreChance createChance(long seed, PackRuntime runtime) {
return OreChance.of(chanceStyle.create(new RNG(seed), runtime));
private OreChance chance(RNG rng, IrisData data) {
return chance(rng, data, data == null ? null : data.getEngine());
}
private OreChance chance(RNG rng, IrisData data, Engine engine) {
long seed = rng.getSeed();
CachedChance recent = recentChance;
if (recent != null && recent.key.seed == seed && recent.key.data == data && recent.key.engine == engine) {
return recent.chance;
}
ChanceKey key = new ChanceKey(seed, data, engine);
OreChance selected = chanceCache.computeIfAbsent(key, ignored -> OreChance.of(chanceStyle.create(rng, data)));
recentChance = new CachedChance(key, selected);
return selected;
}
private record ChanceKey(long seed, IrisData data, Engine engine) {
@Override
public boolean equals(Object other) {
return other instanceof ChanceKey key
&& seed == key.seed && data == key.data && engine == key.engine;
}
@Override
public int hashCode() {
return 31 * (31 * Long.hashCode(seed) + System.identityHashCode(data))
+ System.identityHashCode(engine);
}
}
private record CachedChance(ChanceKey key, OreChance chance) {
}
/**
* The chance field, with its single value resolved once when it is constant (a FLAT style),
* which bands such as a full deepslate layer sample at every block.
*/
public record OreChance(CNG noise, boolean constant, double value) {
private record OreChance(CNG noise, boolean constant, double value) {
private static OreChance of(CNG noise) {
boolean constant = noise.isConstant();
return new OreChance(noise, constant, constant ? noise.noise(0D, 0D, 0D) : 0D);
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.structure.object.IrisObject;
@@ -60,7 +59,7 @@ public final class IrisProceduralBlocks {
public static NativeBlockState resolve(String block, IrisMaterialPalette palette, IrisData data, int x, int y, int z, RNG paletteRng) {
if (paletteSet(palette)) {
return palette.get(paletteRng, x, y, z, PackRuntime.forPack(data));
return palette.get(paletteRng, x, y, z, data);
}
if (block != null && !block.isEmpty()) {
return B.getStateOrNull(block, false);
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -43,28 +42,27 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator {
return;
}
RNG rng = getRNG(realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
if (decorator == null) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, biome, height, max, limit, runtime);
place(decorator, x, z, realX, realZ, data, biome, height, max, limit);
} catch (Throwable e) {
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
}
}
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
IrisBiome biome, int height, int max, int limit, PackRuntime runtime) {
IrisBiome biome, int height, int max, int limit) {
if (!decorator.isStacking()) {
if (!decorator.isForcePlace() && !decorator.getSlopeCondition().isDefault()
&& !decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ))) {
return;
}
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData());
if (block != null) {
data.set(x, height, z, block);
}
@@ -72,13 +70,13 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator {
}
int stack = Math.min(limit - height,
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height));
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height));
for (int i = 0; i < stack; i++) {
int h = height + i;
double threshold = stack == 1 ? 1.0 : ((double) i) / (stack - 1);
NativeBlockState block = threshold >= decorator.getTopThreshold()
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData())
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
if (block == null) {
break;
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -43,26 +42,25 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
return;
}
RNG rng = getRNG(realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
if (decorator == null) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, biome, height, max, maxBaseY, runtime);
place(decorator, x, z, realX, realZ, data, biome, height, max, maxBaseY);
} catch (Throwable e) {
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
}
}
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
IrisBiome biome, int height, int max, int maxBaseY, PackRuntime runtime) {
IrisBiome biome, int height, int max, int maxBaseY) {
if (!decorator.isStacking()) {
int targetY = height + 1;
if (DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData());
if (block != null) {
data.set(x, targetY, z, block);
}
@@ -71,7 +69,7 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
}
int stack = Math.min(maxBaseY - height,
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height));
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height));
for (int i = 0; i < stack; i++) {
int h = height + i;
int targetY = h + 1;
@@ -80,8 +78,8 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
}
double threshold = stack == 1 ? 1.0 : ((double) i) / (stack - 1);
NativeBlockState block = threshold >= decorator.getTopThreshold()
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData())
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
if (block == null) {
break;
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -79,8 +78,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
int max
) {
RNG rng = getRNG(realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
if (decorator == null) {
return;
@@ -92,14 +90,14 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
}
try {
placePicked(decorator, x, z, realX, realZ, data, biome, height, max, runtime);
placePicked(decorator, x, z, realX, realZ, data, biome, height, max);
} catch (Throwable e) {
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
}
}
private void placePicked(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
IrisBiome biome, int height, int max, PackRuntime runtime) {
IrisBiome biome, int height, int max) {
NativeBlockState support = data.get(x, height, z);
if (support == null || !support.isSolid()) {
return;
@@ -113,7 +111,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
|| !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
return;
}
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData());
if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)
&& IrisSugarCane.canPlace(block, data, x, targetY, z, realX, realZ, getEngine())) {
data.set(x, targetY, z, block);
@@ -122,7 +120,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
return;
}
int stack = DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height);
int stack = DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height);
if (stack == 1) {
int targetY = height + 1;
@@ -130,7 +128,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
return;
}
NativeBlockState block = decorator.getBlockDataForTop(biome, partRNG, realX, height, realZ, runtime);
NativeBlockState block = decorator.getBlockDataForTop(biome, partRNG, realX, height, realZ, getData());
if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)
&& IrisSugarCane.canPlace(block, data, x, targetY, z, realX, realZ, getEngine())) {
data.set(x, targetY, z, block);
@@ -148,8 +146,8 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
}
double threshold = ((double) i) / (stack - 1);
NativeBlockState block = threshold >= decorator.getTopThreshold()
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData())
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
if (block == null) {
break;
}
@@ -1,6 +1,5 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.biome.IrisBiome;
@@ -80,7 +79,7 @@ final class IrisSugarCane {
}
IrisBiome biome = complex.getTrueBiomeStream().get(x, z);
KList<NativeBlockState> layers = biome.generateSeaLayers(x, z,
new RNG(engine.getSeedManager().getTerrain()), fluidHeight - terrainHeight, PackRuntime.of(engine));
new RNG(engine.getSeedManager().getTerrain()), fluidHeight - terrainHeight, engine.getData());
int depth = fluidHeight - y;
return supportsAdjacent(layers.hasIndex(depth) ? layers.get(depth) : complex.resolveSeaFluid(x, z));
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.context.ChunkContext;
@@ -74,22 +73,21 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator {
}
boolean caveSkipFluid = skipsFluid(inferredType);
RNG rng = getRNG(realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
if (decorator == null || !isSlopeValid(decorator, realX, height, realZ)) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, height, max, underwater, fluidHeight, caveSkipFluid, runtime);
place(decorator, x, z, realX, realZ, data, height, max, underwater, fluidHeight, caveSkipFluid);
} catch (Throwable e) {
DecoratorCore.skip(e, decorator, getData(), realX, height, realZ, biome);
}
}
private void place(IrisDecorator decorator, int x, int z, int realX, int realZ, Hunk<NativeBlockState> data,
int height, int max, boolean underwater, int fluidHeight, boolean caveSkipFluid, PackRuntime runtime) {
int height, int max, boolean underwater, int fluidHeight, boolean caveSkipFluid) {
AquaticPlacementSnapshot aquaticSnapshot = captureAquaticPlacement(
decorator, getData(), data, x, z, height, max);
if (decorator.isStacking()) {
@@ -99,17 +97,13 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator {
opts.fluidHeight = fluidHeight;
opts.caveSkipFluid = caveSkipFluid;
opts.mantle = getEngine().getMantle();
try {
DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, partRNG, runtime, opts);
} finally {
opts.mantle = null;
}
DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, partRNG, getData(), opts);
aquaticSnapshot.restoreIfUnsupported(data, x, z);
return;
}
DecoratorCore.placeSurfaceSingle(decorator, x, z, realX, height, realZ,
data, partRNG, runtime, underwater, caveSkipFluid, getEngine().getMantle());
data, partRNG, getData(), underwater, caveSkipFluid, getEngine().getMantle());
aquaticSnapshot.restoreIfUnsupported(data, x, z);
}
@@ -1,68 +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.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.math.RNG;
/**
* What one engine derives from an {@link IrisOreBands} for one seed: the chance field of every banded generator,
* resolved once so placing ores block by block reads plain fields instead of looking each generator up.
*/
public final class OreBandsRuntime {
private final IrisOreBands bands;
private final PackRuntime runtime;
private final IrisOreGenerator.OreChance[] chances;
public OreBandsRuntime(IrisOreBands bands, long seed, PackRuntime runtime) {
this.bands = bands;
this.runtime = runtime;
IrisOreGenerator[] generators = bands.generators();
this.chances = new IrisOreGenerator.OreChance[generators.length];
for (int index = 0; index < generators.length; index++) {
chances[index] = runtime.oreChance(generators[index], seed);
}
}
public IrisOreBands bands() {
return bands;
}
public boolean hasOres() {
return bands.hasOres();
}
public int lowestY() {
return bands.lowestY();
}
public int highestY() {
return bands.highestY();
}
public boolean contains(int y) {
return bands.contains(y);
}
/** The ore placed at a Y inside {@link #contains(int)}, or null when no generator places one. */
public NativeBlockState generate(int x, int y, int z, RNG rng) {
return bands.generate(x, y, z, rng, chances, runtime);
}
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.decoration.formation;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
@@ -60,7 +59,7 @@ public final class FormationBlockResolver {
strataRng = new RNG(formation.getSeed() + band * 31L);
strataRngs.put(band, strataRng);
}
NativeBlockState strataState = strata.get(strataRng, x, band, z, PackRuntime.forPack(data));
NativeBlockState strataState = strata.get(strataRng, x, band, z, data);
if (strataState != null) {
return strataState;
}
@@ -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);
}
}
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.decoration.tree;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
@@ -85,7 +84,7 @@ public final class TreeBlockResolver {
private static NativeBlockState resolveSecondaryLeaf(IrisProceduralTree tree, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) {
if (IrisProceduralBlocks.paletteSet(tree.getSecondaryLeavesPalette())) {
return tree.getSecondaryLeavesPalette().get(paletteRng, pos.x(), pos.y(), pos.z(), PackRuntime.forPack(data));
return tree.getSecondaryLeavesPalette().get(paletteRng, pos.x(), pos.y(), pos.z(), data);
}
if (tree.getWeightedSecondaryLeaves() != null && !tree.getWeightedSecondaryLeaves().isEmpty()) {
String picked = pickWeighted(tree, new RNG(tree.getSeed() ^ positionHash(pos)));
@@ -118,7 +117,7 @@ public final class TreeBlockResolver {
private static NativeBlockState resolveBlock(String block, IrisMaterialPalette palette, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) {
if (IrisProceduralBlocks.paletteSet(palette)) {
return palette.get(paletteRng, pos.x(), pos.y(), pos.z(), PackRuntime.forPack(data));
return palette.get(paletteRng, pos.x(), pos.y(), pos.z(), data);
}
if (block != null && !block.isEmpty()) {
return B.getStateOrNull(block, false);
@@ -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));
}
}
@@ -1,6 +1,5 @@
package art.arcane.iris.generation.hydrology.engine;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.runtime.HydrologyPlanException;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.concurrent.MultiBurst;
@@ -79,7 +78,7 @@ public final class HydrologyRuntime {
private final NaturalHeights naturalHeight;
private final BooleanSupplier mainThread;
private final RasterLru rasters;
private final ThreadSlots<LastRaster> last;
private final ThreadLocal<LastRaster> last;
private final Set<Long> queued;
private final ConcurrentHashMap<Long, CompletableFuture<ChunkWaterRaster>> building;
private final RasterFailures failures;
@@ -133,7 +132,7 @@ public final class HydrologyRuntime {
this.naturalHeight = Objects.requireNonNull(naturalHeight, "naturalHeight");
this.mainThread = Objects.requireNonNull(mainThread, "mainThread");
this.rasters = new RasterLru();
this.last = new ThreadSlots<>(LastRaster::new);
this.last = ThreadLocal.withInitial(LastRaster::new);
this.queued = ConcurrentHashMap.newKeySet();
this.building = new ConcurrentHashMap<>();
this.failures = new RasterFailures(ticker);
@@ -60,7 +60,7 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource,
this.focus = complex.getFocusBiome();
this.binding = Objects.requireNonNull(binding, "binding");
this.climate = settings.climate();
this.wetness = climate.enabled() ? climate.style().create(settings.seed() ^ SALT_CLIMATE, complex.getPackRuntime()) : null;
this.wetness = climate.enabled() ? climate.style().create(settings.seed() ^ SALT_CLIMATE, complex.getData()) : null;
}
@Override
@@ -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) {
}
}
}
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.cache.Cache;
import art.arcane.iris.generation.runtime.Engine;
@@ -33,7 +32,6 @@ import org.jetbrains.annotations.Nullable;
final class FloatingIslandSampleResolver implements IslandObjectPlacer.SampleProvider {
private final IrisData data;
private final Engine engine;
private final PackRuntime runtime;
private final int chunkHeight;
private final long baseSeed;
private final FloatingIslandBoundarySampler boundarySampler;
@@ -43,7 +41,6 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro
FloatingIslandSampleResolver(EngineMantle engineMantle, FloatingIslandBoundarySampler boundarySampler) {
this.data = engineMantle.getData();
this.engine = engineMantle.getEngine();
this.runtime = PackRuntime.of(engine, data);
this.chunkHeight = engine.getHeight();
this.baseSeed = engine.getSeedManager().getTerrain() ^ IrisFloatingChildBiomeModifier.FLOATING_BASE_SEED_SALT;
this.boundarySampler = boundarySampler;
@@ -51,10 +48,6 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro
this.resolvedSamples = new LongOpenHashSet();
}
PackRuntime runtime() {
return runtime;
}
@Override
public @Nullable FloatingIslandSample sample(int x, int z) {
long key = Cache.key(x, z);
@@ -66,7 +59,7 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro
resolvedSamples.add(key);
return null;
}
FloatingIslandSample sample = FloatingIslandSample.sample(parent, x, z, chunkHeight, baseSeed, runtime, boundarySampler);
FloatingIslandSample sample = FloatingIslandSample.sample(parent, x, z, chunkHeight, baseSeed, data, engine, boundarySampler);
resolvedSamples.add(key);
if (sample != null) {
sampleCache.put(key, sample);
@@ -18,8 +18,6 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.GenerationCounter;
@@ -80,7 +78,6 @@ public class IrisCaveCarver3D {
private final Engine engine;
private final IrisData data;
private final PackRuntime runtime;
private final IrisCaveProfile profile;
private final NoiseProgram baseDensity;
private final NoiseProgram detailDensity;
@@ -111,8 +108,8 @@ public class IrisCaveCarver3D {
private final int verticalDensityStep;
private final int worldMinimumY;
private final int densityMaximumY;
private final ThreadSlots<Boolean> carving = new ThreadSlots<>(() -> false);
private final ThreadSlots<CaveCarveScratch> scratchCache = new ThreadSlots<>(CaveCarveScratch::new);
private final ThreadLocal<Boolean> carving = ThreadLocal.withInitial(() -> false);
private final ThreadLocal<CaveCarveScratch> scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new);
private final CaveDensityGrid densityGrid;
private final CaveDensityGrid.Owner densityOwner;
private final CaveDensityGrid.Owner warpOwner;
@@ -125,7 +122,6 @@ public class IrisCaveCarver3D {
this.engine = engine;
this.densityGrid = densityGrid;
this.data = engine.getData();
this.runtime = PackRuntime.of(engine, data);
this.profile = profile;
this.carveAir = new MatterCavern(true, "", LIQUID_AIR);
this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID);
@@ -134,10 +130,10 @@ public class IrisCaveCarver3D {
List<CaveFieldModuleState> moduleStates = new ArrayList<>();
RNG baseRng = new RNG(engine.getSeedManager().getCarve());
this.baseDensity = NoiseProgram.compileSigned3D(profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), runtime));
this.detailDensity = NoiseProgram.compileSigned3D(profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), runtime));
this.warpDensity = NoiseProgram.compileSigned3D(profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), runtime));
this.surfaceBreakDensity = profile.getSurfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), runtime);
this.baseDensity = NoiseProgram.compileSigned3D(profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data));
this.detailDensity = NoiseProgram.compileSigned3D(profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data));
this.warpDensity = NoiseProgram.compileSigned3D(profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data));
this.surfaceBreakDensity = profile.getSurfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), data);
this.thresholdRng = baseRng.nextParallelRNG(489_112);
this.baseWeight = profile.getBaseWeight();
this.detailWeight = profile.getDetailWeight();
@@ -153,7 +149,7 @@ public class IrisCaveCarver3D {
double weight = Math.abs(baseWeight) + Math.abs(detailWeight);
int index = 0;
for (IrisCaveFieldModule module : profile.getModules()) {
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), runtime);
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data);
CaveFieldModuleState state = new CaveFieldModuleState(module, NoiseProgram.compileSigned3D(moduleDensity));
moduleStates.add(state);
weight += Math.abs(state.weight);
@@ -346,7 +342,7 @@ public class IrisCaveCarver3D {
} else if (densityThreshold.getStyle().isFlat()) {
constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5);
} else {
thresholdDensity = densityThreshold.getStyle().create(thresholdRng, runtime);
thresholdDensity = densityThreshold.getStyle().create(thresholdRng, data);
}
for (int lx = 0; lx < 16; lx++) {
@@ -26,7 +26,7 @@ import art.arcane.volmlib.util.structure.StructureCarveEnvelope;
import art.arcane.volmlib.nativelib.terrain.structure.StructureWaterRules;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.cache.Cache;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.GenerationFailures;
@@ -197,7 +197,6 @@ public class IrisStructureComponent extends IrisMantleComponent {
settings.getPalette(), "Structure stilt palette must not be null");
int mantleOffset = getEngineMantle().getEngine().getMinHeight();
int maxDepth = Math.max(1, settings.getMaxDepth());
PackRuntime runtime = PackRuntime.of(getEngineMantle().getEngine(), getData());
for (Long2IntMap.Entry column : columns.long2IntEntrySet()) {
int worldX = StructureFoundationPlanner.unpackX(column.getLongKey());
int worldZ = StructureFoundationPlanner.unpackZ(column.getLongKey());
@@ -226,16 +225,16 @@ public class IrisStructureComponent extends IrisMantleComponent {
}
StructureFoundationPlanner.fillSupportColumn(foundationY, groundY, y -> {
writeFoundationSupport(
writer, palette, rng, runtime, worldX, y, worldZ, mantleOffset);
writer, palette, rng, getData(), worldX, y, worldZ, mantleOffset);
});
}
}
static void writeFoundationSupport(MantleWriter writer, IrisMaterialPalette palette, RNG rng,
PackRuntime runtime, int worldX, int mantleY, int worldZ,
IrisData data, int worldX, int mantleY, int worldZ,
int mantleOffset) {
int worldY = mantleY + mantleOffset;
NativeBlockState support = palette.get(rng, worldX, worldY, worldZ, runtime);
NativeBlockState support = palette.get(rng, worldX, worldY, worldZ, data);
if (support == null) {
throw new IllegalStateException("Structure stilt palette resolved no block at "
+ worldX + "," + worldY + "," + worldZ);
@@ -152,7 +152,7 @@ public class MantleCarvingComponent extends IrisMantleComponent {
private void generateLayer(MantleWriter writer, int x, int z, ChunkContext context, BlendScratch blendScratch) {
IrisComplex complex = context.getComplex();
IrisDimensionCarvingResolver.State resolverState = IrisDimensionCarvingResolver.threadState(getEngineMantle().getEngine());
IrisDimensionCarvingResolver.State resolverState = blendScratch.resolverState;
int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, blendScratch.chunkSurfaceHeights);
PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start();
List<WeightedProfile> weightedProfiles = resolveWeightedProfiles(x, z, complex, resolverState);
@@ -766,6 +766,7 @@ public class MantleCarvingComponent extends IrisMantleComponent {
private final double[][] neighbourHeights = new double[NEIGHBOURS][CHUNK_AREA];
private final Object[][] neighbourObjects = new Object[NEIGHBOURS][CHUNK_AREA];
private final long[][] neighbourSubmerged = new long[NEIGHBOURS][4];
private final IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State();
private int nextWeightBuffer;
private boolean inUse;
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.PackRuntime;
import java.io.UncheckedIOException;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.GenerationFailures;
@@ -77,7 +76,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent {
RNG chunkRng = new RNG(Cache.key(x, z) + seed() + 0x0FA710BEL);
FloatingIslandSampleResolver sampleResolver = new FloatingIslandSampleResolver(getEngineMantle(), context.getFloatingIslandBoundarySampler());
FloatingIslandSample.clearChunkMemo(sampleResolver.runtime());
FloatingIslandSample.clearChunkMemo();
FloatingIslandSample[] samples = new FloatingIslandSample[256];
for (int xf = 0; xf < 16; xf++) {
@@ -181,7 +180,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent {
if (placement.isCompatExcluded(data)) {
return;
}
int density = placement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), data));
int density = placement.getDensity(rng, minX, minZ, data);
double perAttempt = placement.getChance();
for (int i = 0; i < density; i++) {
if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) {
@@ -250,7 +249,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent {
if (placement.isCompatExcluded(data)) {
return;
}
int density = placement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), data));
int density = placement.getDensity(rng, minX, minZ, data);
double perAttempt = placement.getChance();
for (int i = 0; i < density; i++) {
@@ -346,7 +345,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent {
if (placement.isCompatExcluded(data)) {
return;
}
int density = placement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), data));
int density = placement.getDensity(rng, minX, minZ, data);
double perAttempt = placement.getChance();
for (int i = 0; i < density; i++) {
@@ -19,7 +19,6 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.block.B;
import art.arcane.iris.generation.cache.Cache;
@@ -35,7 +34,6 @@ import art.arcane.iris.structure.object.IrisAxisRotationClamp;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.cave.IrisCaveAnchorMode;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.iris.structure.object.IrisObjectPlacement;
@@ -71,11 +69,8 @@ import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.iris.generation.block.DataProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.EnumSet;
import java.util.HashMap;
@@ -89,10 +84,9 @@ import java.util.function.BiConsumer;
public class MantleObjectComponent extends IrisMantleComponent {
private static final long CAVE_REJECT_LOG_THROTTLE_MS = 5000L;
private static final int BEDROCK_CLEARANCE = 6;
private static final long OBJECT_SEPARATION_SEED_SALT = 0x5E9A2A7E0B1EC75L;
static final byte LIQUID_FORCED_AIR = 3;
private static final Map<String, CaveRejectLogState> CAVE_REJECT_LOG_STATE = new ConcurrentHashMap<>();
private static final String MISSING_LOAD_KEY_KIND = "marker-missing-load-key";
private static final Set<String> MISSING_LOAD_KEY_WARNED = ConcurrentHashMap.newKeySet();
private static final long SOURCE_PLAN_STATS_INTERVAL_MS = 30_000L;
private static final int MAXIMUM_TREE_MATERIALS = 8192;
private static final Map<NativeBlockState, TreeBlockMaterial> TREE_MATERIALS = new ConcurrentHashMap<>();
@@ -110,29 +104,21 @@ public class MantleObjectComponent extends IrisMantleComponent {
this.collisionRuleState = -1;
}
static String placementMarker(IrisObject object, int id, String context) {
private static String placementMarker(IrisObject object, int id, String context) {
String key = object == null ? null : object.getLoadKey();
if (key == null || key.isEmpty() || key.equals("null")) {
warnMissingLoadKeyOnce(object, context);
String fingerprint = context + "|" + (object == null ? "<null>" : object.getClass().getSimpleName());
if (MISSING_LOAD_KEY_WARNED.add(fingerprint)) {
java.io.File file = object == null ? null : object.getLoadFile();
IrisLogging.warn("Skipping placement marker write: IrisObject has no loadKey (context=" + context
+ ", file=" + (file == null ? "<unknown>" : file.getPath()) + "). "
+ "This would previously produce 'Couldn't find Object: null' warnings on chunk reload.");
}
return null;
}
return key + "@" + id;
}
/**
* Keyed by call-site context and object class only: the file path and coordinates stay in the message,
* never in the key, so the key space is bounded.
*/
private static void warnMissingLoadKeyOnce(IrisObject object, String context) {
String fingerprint = context + "|" + (object == null ? "<null>" : object.getClass().getSimpleName());
IrisData pack = object == null ? null : object.getLoader();
java.io.File file = object == null ? null : object.getLoadFile();
IrisLogging.warnOnce(IrisData.onceKey(pack, MISSING_LOAD_KEY_KIND, fingerprint),
"Skipping placement marker write: IrisObject has no loadKey (context=" + context
+ ", file=" + (file == null ? "<unknown>" : file.getPath()) + "). "
+ "This would previously produce 'Couldn't find Object: null' warnings on chunk reload.");
}
private static boolean isTreePlacement(IrisObject object, IrisObjectPlacement placement) {
String key = object == null ? null : object.getLoadKey();
return (key != null && key.startsWith("trees/"))
@@ -493,17 +479,29 @@ public class MantleObjectComponent extends IrisMantleComponent {
for (IrisObjectPlacement i : surfaceBiome.getSurfaceObjects()) {
biomeSurfaceChecked++;
Optional<ObjectPlacementResult> triggered = placeSurfacePlacement(writer, rng, x, z, i, complex, traceRegen, "biome-surface", surfaceBiome.getLoadKey());
if (triggered.isEmpty()) {
continue;
boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && !i.isCompatExcluded(getData());
if (traceRegen) {
IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z
+ " scope=biome-surface"
+ " chanceResult=" + chance
+ " chanceBase=" + i.getChance()
+ " densityMid=" + i.getDensity()
+ " objects=" + i.getPlace().size());
}
if (chance) {
biomeSurfaceTriggered++;
try {
ObjectPlacementResult result = placeObject(writer, rng, x << 4, z << 4, i, complex, traceRegen, x, z, "biome-surface");
attempts += result.attempts();
placed += result.placed();
rejected += result.rejected();
nullObjects += result.nullObjects();
errors += result.errors();
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "object", i.getPlace().toString(", "), x << 4, -1, z << 4, surfaceBiome.getLoadKey());
errors++;
}
}
biomeSurfaceTriggered++;
ObjectPlacementResult result = triggered.get();
attempts += result.attempts();
placed += result.placed();
rejected += result.rejected();
nullObjects += result.nullObjects();
errors += result.errors();
}
for (IrisObjectPlacement i : caveBiome.getCarvingObjects()) {
@@ -538,17 +536,29 @@ public class MantleObjectComponent extends IrisMantleComponent {
for (IrisObjectPlacement i : region.getSurfaceObjects()) {
regionSurfaceChecked++;
Optional<ObjectPlacementResult> triggered = placeSurfacePlacement(writer, rng, x, z, i, complex, traceRegen, "region-surface", region.getLoadKey());
if (triggered.isEmpty()) {
continue;
boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && !i.isCompatExcluded(getData());
if (traceRegen) {
IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z
+ " scope=region-surface"
+ " chanceResult=" + chance
+ " chanceBase=" + i.getChance()
+ " densityMid=" + i.getDensity()
+ " objects=" + i.getPlace().size());
}
if (chance) {
regionSurfaceTriggered++;
try {
ObjectPlacementResult result = placeObject(writer, rng, x << 4, z << 4, i, complex, traceRegen, x, z, "region-surface");
attempts += result.attempts();
placed += result.placed();
rejected += result.rejected();
nullObjects += result.nullObjects();
errors += result.errors();
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "object", i.getPlace().toString(", "), x << 4, -1, z << 4, region.getLoadKey());
errors++;
}
}
regionSurfaceTriggered++;
ObjectPlacementResult result = triggered.get();
attempts += result.attempts();
placed += result.placed();
rejected += result.rejected();
nullObjects += result.nullObjects();
errors += result.errors();
}
for (IrisObjectPlacement i : region.getCarvingObjects()) {
@@ -949,7 +959,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
int rejected = 0;
int nullObjects = 0;
int errors = 0;
int density = objectPlacement.getDensity(rng, x, z, PackRuntime.of(getEngineMantle().getEngine(), getData()));
int density = objectPlacement.getDensity(rng, x, z, getData());
boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(chunkX, chunkZ);
for (int i = 0; i < density; i++) {
@@ -957,194 +967,86 @@ public class MantleObjectComponent extends IrisMantleComponent {
IrisObject v = objectPlacement.scaleObject(rng, objectPlacement.getObject(complex, rng), getDimension());
if (v == null) {
nullObjects++;
traceNullObject(traceRegen, chunkX, chunkZ, scope, i, density, objectPlacement);
if (traceRegen) {
IrisLogging.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " densityIndex=" + i
+ " density=" + density
+ " placementKeys=" + objectPlacement.getPlace().toString(","));
}
continue;
}
int xx = rng.i(x, x + 16);
int zz = rng.i(z, z + 16);
ObjectPlacementResult result = placeObjectAt(writer, rng, v, xx, zz, objectPlacement, complex, traceRegen, chunkX, chunkZ, scope, i, density);
placed += result.placed();
rejected += result.rejected();
errors += result.errors();
IrisObjectPlacement effectivePlacement = resolveEffectivePlacement(objectPlacement, v);
if (!allowsObjectPlacement(complex, v, effectivePlacement, xx, zz)) {
rejected++;
continue;
}
boolean treePlacement = isTreePlacement(v, effectivePlacement);
int id = rng.i(0, Integer.MAX_VALUE);
IObjectPlacer placePlacer = golden ? new GoldenDebugObjectPlacer(writer, scope + "/" + v.getLoadKey()) : writer;
if (golden) {
IrisLogging.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " densityIndex=" + i
+ " xx=" + xx
+ " zz=" + zz
+ " mode=" + effectivePlacement.getMode());
}
try {
String marker = placementMarker(v, id, "surface");
int continuation = writer.beginObjectPlacement(effectivePlacement.waterRule());
int result = v.place(xx, zz, placePlacer, effectivePlacement, rng, (b, data) -> {
if (marker != null) {
writer.setData(b.getX(), b.getY(), b.getZ(), marker);
}
if (treePlacement && marker != null) {
writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data);
}
if (effectivePlacement.isDolphinTarget() && effectivePlacement.isUnderwater() && B.isStorageChest(data)) {
writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE);
}
}, null, getData());
if (result >= 0) {
writer.recordObjectPlacement(continuation);
placed++;
} else {
rejected++;
}
if (golden) {
IrisLogging.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " resultY=" + result
+ " fallback=surface");
}
if (traceRegen) {
IrisLogging.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " resultY=" + result
+ " px=" + xx
+ " pz=" + zz
+ " fallback=surface"
+ " densityIndex=" + i
+ " density=" + density);
}
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "object", v.getLoadKey(), chunkX << 4, -1, chunkZ << 4, scope);
errors++;
} finally {
writer.endObjectPlacement();
}
}
return new ObjectPlacementResult(attempts, placed, rejected, nullObjects, errors);
}
private void traceNullObject(boolean traceRegen, int chunkX, int chunkZ, String scope, int densityIndex, int density, IrisObjectPlacement objectPlacement) {
if (!traceRegen) {
return;
}
IrisLogging.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " densityIndex=" + densityIndex
+ " density=" + density
+ " placementKeys=" + objectPlacement.getPlace().toString(","));
}
@BlockCoordinates
private ObjectPlacementResult placeObjectAt(
ObjectPassPlacer writer,
RNG rng,
IrisObject v,
int xx,
int zz,
IrisObjectPlacement objectPlacement,
IrisComplex complex,
boolean traceRegen,
int chunkX,
int chunkZ,
String scope,
int densityIndex,
int density
) {
IrisObjectPlacement effectivePlacement = resolveEffectivePlacement(objectPlacement, v);
if (!allowsObjectPlacement(complex, v, effectivePlacement, xx, zz)) {
return new ObjectPlacementResult(0, 0, 1, 0, 0);
}
boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(chunkX, chunkZ);
boolean treePlacement = isTreePlacement(v, effectivePlacement);
int id = rng.i(0, Integer.MAX_VALUE);
IObjectPlacer placePlacer = golden ? new GoldenDebugObjectPlacer(writer, scope + "/" + v.getLoadKey()) : writer;
if (golden) {
IrisLogging.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " densityIndex=" + densityIndex
+ " xx=" + xx
+ " zz=" + zz
+ " mode=" + effectivePlacement.getMode());
}
try {
String marker = placementMarker(v, id, "surface");
int continuation = writer.beginObjectPlacement(effectivePlacement.waterRule());
int result = v.place(xx, zz, placePlacer, effectivePlacement, rng, (b, data) -> {
if (marker != null) {
writer.setData(b.getX(), b.getY(), b.getZ(), marker);
}
if (treePlacement && marker != null) {
writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data);
}
if (effectivePlacement.isDolphinTarget() && effectivePlacement.isUnderwater() && B.isStorageChest(data)) {
writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE);
}
}, null, getData());
if (result >= 0) {
writer.recordObjectPlacement(continuation);
}
if (golden) {
IrisLogging.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " resultY=" + result
+ " fallback=surface");
}
if (traceRegen) {
IrisLogging.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " object=" + v.getLoadKey()
+ " resultY=" + result
+ " px=" + xx
+ " pz=" + zz
+ " fallback=surface"
+ " densityIndex=" + densityIndex
+ " density=" + density);
}
return result >= 0 ? new ObjectPlacementResult(0, 1, 0, 0, 0) : new ObjectPlacementResult(0, 0, 1, 0, 0);
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "object", v.getLoadKey(), chunkX << 4, -1, chunkZ << 4, scope);
return new ObjectPlacementResult(0, 0, 0, 0, 1);
} finally {
writer.endObjectPlacement();
}
}
private Optional<ObjectPlacementResult> placeSurfacePlacement(
ObjectPassPlacer writer,
RNG rng,
int chunkX,
int chunkZ,
IrisObjectPlacement placement,
IrisComplex complex,
boolean traceRegen,
String scope,
String ownerKey
) {
try {
if (placement.isSeparated()) {
return placeSeparatedObject(writer, chunkX, chunkZ, placement, complex, traceRegen, scope);
}
double chance = objectSeparation().chanceAt(placement, (chunkX << 4) + 8, (chunkZ << 4) + 8);
boolean passes = rng.chance(chance + rng.d(-0.005, 0.005)) && !placement.isCompatExcluded(getData());
traceSurfaceChance(traceRegen, chunkX, chunkZ, scope, passes, placement);
if (!passes) {
return Optional.empty();
}
return Optional.of(placeObject(writer, rng, chunkX << 4, chunkZ << 4, placement, complex, traceRegen, chunkX, chunkZ, scope));
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "object", placement.getPlace().toString(", "), chunkX << 4, -1, chunkZ << 4, ownerKey);
return Optional.of(new ObjectPlacementResult(0, 0, 0, 0, 1));
}
}
private void traceSurfaceChance(boolean traceRegen, int chunkX, int chunkZ, String scope, boolean passes, IrisObjectPlacement placement) {
if (!traceRegen) {
return;
}
IrisLogging.debug("Regen object placer chance: chunk=" + chunkX + "," + chunkZ
+ " scope=" + scope
+ " chanceResult=" + passes
+ " chanceBase=" + placement.getChance()
+ " densityMid=" + placement.getDensity()
+ " objects=" + placement.getPlace().size());
}
private Optional<ObjectPlacementResult> placeSeparatedObject(
ObjectPassPlacer writer,
int chunkX,
int chunkZ,
IrisObjectPlacement placement,
IrisComplex complex,
boolean traceRegen,
String scope
) {
Optional<ObjectSeparation.Candidate> kept = placement.isCompatExcluded(getData())
? Optional.empty()
: objectSeparation().keptCandidate(chunkX, chunkZ, placement);
traceSurfaceChance(traceRegen, chunkX, chunkZ, scope, kept.isPresent(), placement);
if (kept.isEmpty()) {
return Optional.empty();
}
ObjectSeparation.Candidate candidate = kept.get();
IrisObject object = placement.scaleObject(candidate.rng(), placement.getObject(complex, candidate.rng()), getDimension());
if (object == null) {
traceNullObject(traceRegen, chunkX, chunkZ, scope, 0, 1, placement);
return Optional.of(new ObjectPlacementResult(1, 0, 0, 1, 0));
}
ObjectPlacementResult result = placeObjectAt(writer, candidate.rng(), object, candidate.x(), candidate.z(), placement, complex, traceRegen, chunkX, chunkZ, scope, 0, 1);
return Optional.of(new ObjectPlacementResult(1, result.placed(), result.rejected(), 0, result.errors()));
}
private ObjectSeparation objectSeparation() {
return new ObjectSeparation(seed() + OBJECT_SEPARATION_SEED_SALT, PackRuntime.of(getEngineMantle().getEngine(), getData()), this::surfacePlacementsAt);
}
private List<IrisObjectPlacement> surfacePlacementsAt(int chunkX, int chunkZ) {
IrisComplex complex = getComplex();
if (!complex.allowsNewGenerationChunk(chunkX, chunkZ)) {
return List.of();
}
int blockX = (chunkX << 4) + 8;
int blockZ = (chunkZ << 4) + 8;
List<IrisObjectPlacement> placements = new ArrayList<>(complex.getTrueBiomeStream().get(blockX, blockZ).getSurfaceObjects());
placements.addAll(complex.getRegionStream().get(blockX, blockZ).getSurfaceObjects());
placements.removeIf(placement -> placement.isCompatExcluded(getData()));
return placements;
}
@ChunkCoordinates
private boolean caveAnchorBiomeConflicts(int x, int y, int z, String expectedCaveBiomeKey) {
if (expectedCaveBiomeKey == null) {
@@ -1192,7 +1094,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
int errors = 0;
int minX = chunkX << 4;
int minZ = chunkZ << 4;
int density = objectPlacement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), getData()));
int density = objectPlacement.getDensity(rng, minX, minZ, getData());
IrisCaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement, caveProfile);
if (objectPlacement.getMode() == ObjectPlaceMode.CEILING_HANG) {
anchorMode = IrisCaveAnchorMode.CEILING;
@@ -1426,7 +1328,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
int chunkHeight = getEngineMantle().getEngine().getHeight();
int minX = chunkX << 4;
int minZ = chunkZ << 4;
int density = objectPlacement.getDensity(rng, minX, minZ, PackRuntime.of(getEngineMantle().getEngine(), getData()));
int density = objectPlacement.getDensity(rng, minX, minZ, getData());
for (int i = 0; i < density; i++) {
IrisObject v = objectPlacement.scaleObject(rng, objectPlacement.getObject(upperCtx, rng), upperCtx.getDimension());
@@ -1832,7 +1734,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
@BlockCoordinates
private Set<String> guessPlacedKeys(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) {
Set<String> f = new KSet<>();
for (int i = 0; i < objectPlacement.getDensity(rng, x, z, PackRuntime.of(getEngineMantle().getEngine(), getData())); i++) {
for (int i = 0; i < objectPlacement.getDensity(rng, x, z, getData()); i++) {
IrisObject v = objectPlacement.scaleObject(rng, objectPlacement.getObject(getComplex(), rng), getDimension());
if (v == null) {
continue;
@@ -1852,34 +1754,21 @@ public class MantleObjectComponent extends IrisMantleComponent {
IrisBiome biome = getComplex().getTrueBiomeStream().get(blockX, blockZ);
IrisRegion region = getComplex().getRegionStream().get(blockX, blockZ);
Set<String> v = new KSet<>();
guessSurfaceKeys(rng, x, z, biome.getSurfaceObjects(), v);
guessSurfaceKeys(rng, x, z, region.getSurfaceObjects(), v);
for (IrisObjectPlacement i : biome.getSurfaceObjects()) {
if (rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && !i.isCompatExcluded(getData())) {
v.addAll(guessPlacedKeys(rng, x, z, i));
}
}
for (IrisObjectPlacement i : region.getSurfaceObjects()) {
if (rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && !i.isCompatExcluded(getData())) {
v.addAll(guessPlacedKeys(rng, x, z, i));
}
}
return v;
}
private void guessSurfaceKeys(RNG rng, int x, int z, List<IrisObjectPlacement> placements, Set<String> keys) {
ObjectSeparation separation = objectSeparation();
for (IrisObjectPlacement i : placements) {
if (i.isSeparated()) {
guessSeparatedKey(separation, x, z, i).ifPresent(keys::add);
continue;
}
double chance = separation.chanceAt(i, (x << 4) + 8, (z << 4) + 8);
if (rng.chance(chance + rng.d(-0.005, 0.005)) && !i.isCompatExcluded(getData())) {
keys.addAll(guessPlacedKeys(rng, x, z, i));
}
}
}
private Optional<String> guessSeparatedKey(ObjectSeparation separation, int x, int z, IrisObjectPlacement placement) {
if (placement.isCompatExcluded(getData())) {
return Optional.empty();
}
return separation.keptCandidate(x, z, placement)
.map(candidate -> placement.scaleObject(candidate.rng(), placement.getObject(getComplex(), candidate.rng()), getDimension()))
.map(IrisObject::getLoadKey);
}
protected int computeRadius() {
KSet<String> warnedLargeObjects = new KSet<>();
PlacementReach reach = new ReachScan(getDimension(), this::getData, warnedLargeObjects).dimension();
@@ -19,7 +19,6 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.iris.world.storage.matter.TileWrapper;
@@ -85,14 +84,14 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
@ToString.Exclude
private final ThreadSlots<Integer> activeComponentPriority = ThreadSlots.bindings();
private final ThreadLocal<Integer> activeComponentPriority = new ThreadLocal<>();
@Getter(AccessLevel.NONE)
private final ThreadSlots<ObjectPlacementCapture> objectPlacementCapture = ThreadSlots.bindings();
private final ThreadLocal<ObjectPlacementCapture> objectPlacementCapture = new ThreadLocal<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
@ToString.Exclude
private final ThreadSlots<ObjectWater> objectWater = ThreadSlots.bindings();
private final ThreadLocal<ObjectWater> objectWater = new ThreadLocal<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
@@ -8,14 +8,11 @@ import art.arcane.volmlib.util.io.CountingDataInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UncheckedIOException;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.world.storage.matter.IrisMatterSupport;
import art.arcane.iris.world.storage.matter.RetiredMatterSlices;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
@@ -150,7 +147,6 @@ public record ObjectContinuationBundle(List<Fragment> fragments) {
Matter matter = new IrisMatter(width, height, depth);
int sliceCount = input.readUnsignedByte();
matter.getHeader().read(input);
HashSet<String> skippedRetired = new HashSet<>();
for (int index = 0; index < sliceCount; index++) {
int size = input.readInt();
long end = input.count() + size;
@@ -158,24 +154,9 @@ public record ObjectContinuationBundle(List<Fragment> fragments) {
throw new IOException("Invalid object continuation slice size");
}
String identifier = input.readUTF();
if (input.count() > end) {
throw new IOException("Object continuation slice size mismatch: " + identifier);
}
Class<?> type = IrisMatter.getSliceType(identifier);
if (type == null) {
if (!RetiredMatterSlices.isRetired(identifier)) {
throw new IOException("Unknown object continuation slice type: " + identifier);
}
if (!skippedRetired.add(identifier)) {
throw new IOException("Duplicate object continuation slice type: " + identifier);
}
input.skipTo(end);
IrisLogging.warnOnce("object-continuation:retired-slice:" + identifier,
"Skipping retired object continuation slice %s written by an older Iris version", identifier);
continue;
}
if (matter.hasSlice(type)) {
throw new IOException("Duplicate object continuation slice type: " + identifier);
if (type == null || matter.hasSlice(type)) {
throw new IOException("Unavailable or duplicate object continuation slice: " + identifier);
}
MatterSlice<?> slice = matter.createSlice(type, matter);
if (slice == null) {
@@ -1,137 +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.generation.mantle;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.structure.object.IrisObjectPlacement;
import art.arcane.volmlib.util.math.RNG;
import java.util.List;
import java.util.Optional;
/**
* The chance and spacing of surface object placements.
*
* <p>A separated placement rolls one candidate spot per chunk. The candidate stands only when no candidate of a lower rank,
* from a placement with the same objects, lies closer than the separation. Spots and ranks come from the seed, the chunk
* and the objects alone, so every chunk agrees on them across chunk, biome and region borders, and objects never stand
* closer than the separation, whatever order chunks generate in.
*/
final class ObjectSeparation {
private static final int CHUNK_WIDTH_BLOCKS = 16;
private static final int CHUNK_SHIFT = 4;
private final long seed;
private final PackRuntime runtime;
private final SurfacePlacements surfacePlacements;
ObjectSeparation(long seed, PackRuntime runtime, SurfacePlacements surfacePlacements) {
this.seed = seed;
this.runtime = runtime;
this.surfacePlacements = surfacePlacements;
}
/** The placements a chunk places on the surface, in placing order. A chunk places the biome's before the region's. */
@FunctionalInterface
interface SurfacePlacements {
List<IrisObjectPlacement> at(int chunkX, int chunkZ);
}
/** Where a chunk would place, in block coordinates, with the random that picks and places the object there. */
record Candidate(int x, int z, long rank, RNG rng) {
boolean isCloserThan(Candidate other, int blocks) {
long dx = x - other.x;
long dz = z - other.z;
return dx * dx + dz * dz < (long) blocks * blocks;
}
}
/** The chance to place at the block column: the placement's chance, multiplied by its chance noise when it has one. */
double chanceAt(IrisObjectPlacement placement, double x, double z) {
IrisGeneratorStyle style = placement.getChanceStyle();
if (style == null) {
return placement.getChance();
}
return placement.getChance() * style.create(seed, runtime).fitDouble(0D, 1D, x, z);
}
/**
* The candidate the chunk places for the separated placement; empty when it rolled none or a lower ranked one is too
* close.
*/
Optional<Candidate> keptCandidate(int chunkX, int chunkZ, IrisObjectPlacement placement) {
Optional<Candidate> own = candidateOf(chunkX, chunkZ, placement);
if (own.isEmpty() || isOutranked(own.get(), chunkX, chunkZ, placement)) {
return Optional.empty();
}
return own;
}
private boolean isOutranked(Candidate own, int chunkX, int chunkZ, IrisObjectPlacement placement) {
int reach = placement.getSeparation();
int minimumChunkX = Math.floorDiv(own.x() - reach, CHUNK_WIDTH_BLOCKS);
int maximumChunkX = Math.floorDiv(own.x() + reach, CHUNK_WIDTH_BLOCKS);
int minimumChunkZ = Math.floorDiv(own.z() - reach, CHUNK_WIDTH_BLOCKS);
int maximumChunkZ = Math.floorDiv(own.z() + reach, CHUNK_WIDTH_BLOCKS);
for (int x = minimumChunkX; x <= maximumChunkX; x++) {
for (int z = minimumChunkZ; z <= maximumChunkZ; z++) {
if ((x != chunkX || z != chunkZ) && isOutrankedBy(x, z, own, placement)) {
return true;
}
}
}
return false;
}
private boolean isOutrankedBy(int rivalChunkX, int rivalChunkZ, Candidate own, IrisObjectPlacement placement) {
Optional<Candidate> rival = placementOfSameObjectsAt(rivalChunkX, rivalChunkZ, placement)
.flatMap(other -> candidateOf(rivalChunkX, rivalChunkZ, other));
return rival.isPresent() && rival.get().rank() < own.rank() && rival.get().isCloserThan(own, placement.getSeparation());
}
private Optional<IrisObjectPlacement> placementOfSameObjectsAt(int chunkX, int chunkZ, IrisObjectPlacement placement) {
return surfacePlacements.at(chunkX, chunkZ).stream()
.filter(other -> other.isSeparated() && other.getPlace().equals(placement.getPlace()))
.findFirst();
}
private Optional<Candidate> candidateOf(int chunkX, int chunkZ, IrisObjectPlacement placement) {
RNG rng = new RNG(chunkSeed(chunkX, chunkZ, placement.getPlace().hashCode()));
int x = (chunkX << CHUNK_SHIFT) + rng.nextInt(CHUNK_WIDTH_BLOCKS);
int z = (chunkZ << CHUNK_SHIFT) + rng.nextInt(CHUNK_WIDTH_BLOCKS);
if (!rng.chance(chanceAt(placement, x, z))) {
return Optional.empty();
}
return Optional.of(new Candidate(x, z, rng.nextLong(), rng));
}
// Each input is mixed in after the previous one: XORing scaled coordinates gave chunk x,z and -x,-z the same seed
// whenever both were odd.
private long chunkSeed(int chunkX, int chunkZ, int objectsHash) {
return splitMix(splitMix(splitMix(seed + objectsHash) + chunkX) + chunkZ);
}
private static long splitMix(long value) {
long mixed = value + 0x9E3779B97F4A7C15L;
mixed = (mixed ^ (mixed >>> 30)) * 0xBF58476D1CE4E5B9L;
mixed = (mixed ^ (mixed >>> 27)) * 0x94D049BB133111EBL;
return mixed ^ (mixed >>> 31);
}
}
@@ -24,9 +24,9 @@ import art.arcane.volmlib.util.math.RNG;
public class ExpressionNoise implements NoiseGenerator {
private final RNG rng;
private final ExpressionRuntime expression;
private final IrisExpression expression;
public ExpressionNoise(RNG rng, ExpressionRuntime expression) {
public ExpressionNoise(RNG rng, IrisExpression expression) {
this.rng = rng;
this.expression = expression;
}
@@ -1,258 +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.generation.noise;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import art.arcane.volmlib.util.stream.interpolation.Interpolated;
import com.dfsek.paralithic.Expression;
import com.dfsek.paralithic.functions.dynamic.Context;
import com.dfsek.paralithic.functions.dynamic.DynamicFunction;
import com.dfsek.paralithic.node.Statefulness;
import lombok.NonNull;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
/**
* An {@link IrisExpression} parsed for one runtime scope: its functions and variables read that scope's engine
* streams and seeded styles, so the parsed expression belongs to the scope and not to the pack object.
*/
public final class ExpressionRuntime {
private static final int SEED_CAPACITY = 8;
private static final int MAX_RETAINED_EVALUATION_DEPTH = 8;
private static final int MAX_RETAINED_ARGUMENTS = 256;
private static final ThreadLocal<EvaluationScratch> EVALUATION_SCRATCH =
ThreadLocal.withInitial(EvaluationScratch::new);
private final VariableRuntime[] variables;
private final Expression parsed;
private final SeedTable<ProceduralStream<Double>> streams;
public ExpressionRuntime(IrisExpression expression, PackRuntime runtime) {
this.variables = expression.getVariables().stream()
.map(variable -> new VariableRuntime(variable, runtime))
.toArray(VariableRuntime[]::new);
this.parsed = expression.parse(function -> new FunctionRuntime(function, runtime));
this.streams = new SeedTable<>(SEED_CAPACITY, seed -> {
RNG streamRng = new RNG(seed);
return ProceduralStream.of((x, z) -> evaluate(streamRng, x, z),
(x, y, z) -> evaluate(streamRng, x, y, z), Interpolated.DOUBLE);
});
}
public ProceduralStream<Double> stream(RNG rng) {
return streams.get(rng.getSeed());
}
public double evaluate(RNG rng, double x, double z) {
EvaluationScratch scratch = EVALUATION_SCRATCH.get();
double[] arguments = scratch.acquire(3 + variables.length);
try {
int index = 0;
for (VariableRuntime variable : variables) {
arguments[index++] = variable.value(rng, x, z);
}
arguments[index++] = x;
arguments[index++] = z;
arguments[index] = -1;
return parsed.evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
}
}
public double evaluate(RNG rng, double x, double y, double z) {
EvaluationScratch scratch = EVALUATION_SCRATCH.get();
double[] arguments = scratch.acquire(3 + variables.length);
try {
int index = 0;
for (VariableRuntime variable : variables) {
arguments[index++] = variable.value(rng, x, y, z);
}
arguments[index++] = x;
arguments[index++] = y;
arguments[index] = z;
return parsed.evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
}
}
public record FunctionContext(@NonNull RNG rng) implements Context {
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
FunctionContext that = (FunctionContext) o;
return rng.getSeed() == that.rng.getSeed();
}
@Override
public int hashCode() {
return Long.hashCode(rng.getSeed());
}
}
private static Engine requireEngine(PackRuntime runtime, String kind, String name) {
Engine engine = runtime.engine();
if (engine == null) {
throw new IllegalStateException("Expression " + kind + " '" + name + "' requires an active Iris engine.");
}
return engine;
}
private static final class FunctionRuntime implements DynamicFunction {
private final IrisExpressionFunction function;
private final PackRuntime runtime;
private final SeedTable<Provider> providers;
private FunctionRuntime(IrisExpressionFunction function, PackRuntime runtime) {
this.function = function;
this.runtime = runtime;
this.providers = new SeedTable<>(SEED_CAPACITY, this::createProvider);
}
@Override
public int getArgNumber() {
return function.argumentCount();
}
@NotNull
@Override
public Statefulness statefulness() {
return Statefulness.STATEFUL;
}
@Override
public double eval(double... doubles) {
return 0;
}
@Override
public double eval(@Nullable Context raw, double... args) {
FunctionContext context = Objects.requireNonNull((FunctionContext) raw, "Expression context");
return providers.get(context.rng().getSeed()).eval(args);
}
private Provider createProvider(long seed) {
if (function.getEngineStreamValue() != null) {
Engine engine = requireEngine(runtime, "function", function.getName());
ProceduralStream<Double> stream = function.getEngineStreamValue().get(engine);
return coordinates -> stream.get(coordinates[0], coordinates[1]);
}
if (function.getStyleValue() != null) {
return function.getStyleValue().create(seed, runtime)::noise;
}
return coordinates -> Double.NaN;
}
}
@FunctionalInterface
private interface Provider {
double eval(double... args);
}
private static final class VariableRuntime {
private final IrisExpressionLoad variable;
private final PackRuntime runtime;
private final SeedTable<CNG> styles;
private volatile ProceduralStream<Double> engineStream;
private volatile Double engineValue;
private VariableRuntime(IrisExpressionLoad variable, PackRuntime runtime) {
this.variable = variable;
this.runtime = runtime;
this.styles = new SeedTable<>(SEED_CAPACITY,
seed -> variable.getStyleValue().createNoCache(new RNG(seed), runtime));
}
private double value(RNG rng, double x, double z) {
if (variable.getEngineValue() != null) {
return engineValue();
}
if (variable.getEngineStreamValue() != null) {
return engineStream().get(x, z);
}
if (variable.getStyleValue() != null) {
return styles.get(rng.getSeed()).noise(x, z);
}
return variable.getStaticValue();
}
private double value(RNG rng, double x, double y, double z) {
if (variable.getEngineValue() != null) {
return engineValue();
}
if (variable.getEngineStreamValue() != null) {
return engineStream().get(x, z);
}
if (variable.getStyleValue() != null) {
return styles.get(rng.getSeed()).noise(x, y, z);
}
return variable.getStaticValue();
}
private double engineValue() {
Double value = engineValue;
if (value == null) {
value = variable.getEngineValue().get(requireEngine(runtime, "variable", variable.getName()));
engineValue = value;
}
return value;
}
private ProceduralStream<Double> engineStream() {
ProceduralStream<Double> stream = engineStream;
if (stream == null) {
stream = variable.getEngineStreamValue().get(requireEngine(runtime, "variable", variable.getName()));
engineStream = stream;
}
return stream;
}
}
private static final class EvaluationScratch {
private final double[][] retained = new double[MAX_RETAINED_EVALUATION_DEPTH][];
private int depth;
private double[] acquire(int length) {
double[] arguments;
if (depth >= retained.length || length > MAX_RETAINED_ARGUMENTS) {
arguments = new double[length];
} else {
arguments = retained[depth];
if (arguments == null || arguments.length != length) {
arguments = new double[length];
retained[depth] = arguments;
}
}
depth++;
return arguments;
}
private void release() {
depth--;
}
}
}
@@ -1,6 +1,5 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.interpolation.IrisInterpolation;
import java.util.Arrays;
@@ -15,7 +14,6 @@ public final class GeneratorProgram {
private final NoiseLayerProgram cliffs;
private final boolean multiplicitive;
private final double opacity;
private final double exponent;
private final double offsetX;
private final double offsetZ;
private final double zoom;
@@ -23,21 +21,15 @@ public final class GeneratorProgram {
private final double cliffHeightMin;
private final double cliffHeightMax;
private final boolean cellCracks;
private final PackRuntime runtime;
private final IrisGenerator.SurfaceCacheStripe[] surfaceStripes;
GeneratorProgram(IrisGenerator generator, long superSeed, NoiseLayerProgram[] layers, double totalOpacity,
NoiseLayerProgram cliffs, PackRuntime runtime) {
GeneratorProgram(IrisGenerator generator, long superSeed, NoiseLayerProgram[] layers, double totalOpacity, NoiseLayerProgram cliffs) {
this.generator = generator;
this.runtime = runtime;
this.surfaceStripes = runtime.generator(generator).surfaceStripes();
this.superSeed = superSeed;
this.layers = layers;
this.totalOpacity = totalOpacity;
this.cliffs = cliffs;
this.multiplicitive = generator.isMultiplicitive();
this.opacity = generator.getOpacity();
this.exponent = generator.getExponent();
this.offsetX = generator.getOffsetX();
this.offsetZ = generator.getOffsetZ();
this.zoom = generator.getZoom();
@@ -77,7 +69,7 @@ public final class GeneratorProgram {
double lowerZ = Math.floor(z / SURFACE_GRID) * SURFACE_GRID;
double dx = (x - lowerX) / SURFACE_GRID;
double dz = (z - lowerZ) / SURFACE_GRID;
IrisGenerator.SurfaceCacheStripe[] stripes = surfaceStripes;
IrisGenerator.SurfaceCacheStripe[] stripes = generator.surfaceStripes();
double northWest = lattice(scratch, stripes, lowerX, lowerZ);
if (dx == 0D && dz == 0D) {
return northWest;
@@ -124,8 +116,7 @@ public final class GeneratorProgram {
double noise = layer.sample(scratch, sampleX, sampleZ);
value = multiplicitive ? value * noise : value + noise;
}
double combined = multiplicitive ? value : value / totalOpacity;
value = IrisGenerator.applyExponent(combined, exponent) * opacity;
value = multiplicitive ? value * opacity : (value / totalOpacity) * opacity;
if (Double.isNaN(value)) {
value = 0D;
}
@@ -133,7 +124,7 @@ public final class GeneratorProgram {
double height = IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, cliffs.sample(scratch, sampleX, sampleZ));
value = (Math.round((value * 255D) / height) * height) / 255D;
}
return cellCracks ? generator.cell(runtime, x, z, value, 0D) : value;
return cellCracks ? generator.cell(x, z, value, 0D) : value;
}
private void surfaceHeights(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] out) {
@@ -235,7 +226,7 @@ public final class GeneratorProgram {
}
private void resolveLattice(TerrainBatchScratch scratch, int nodes, double[] lattice) {
IrisGenerator.SurfaceCacheStripe[] stripes = surfaceStripes;
IrisGenerator.SurfaceCacheStripe[] stripes = generator.surfaceStripes();
int indexMark = scratch.indexMark();
int mark = scratch.mark();
try {
@@ -305,8 +296,7 @@ public final class GeneratorProgram {
}
}
for (int index = 0; index < count; index++) {
double combined = multiplicitive ? out[index] : out[index] / totalOpacity;
double value = IrisGenerator.applyExponent(combined, exponent) * opacity;
double value = multiplicitive ? out[index] * opacity : (out[index] / totalOpacity) * opacity;
out[index] = Double.isNaN(value) ? 0D : value;
}
if (cliffs != null) {
@@ -318,7 +308,7 @@ public final class GeneratorProgram {
}
if (cellCracks) {
for (int index = 0; index < count; index++) {
out[index] = generator.cell(runtime, xs[index], zs[index], out[index], 0D);
out[index] = generator.cell(xs[index], zs[index], out[index], 0D);
}
}
}
@@ -1,45 +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.generation.noise;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.noise.CellGenerator;
/**
* What one engine derives from an {@link IrisGenerator}: the lattice of smoothed surface heights it has sampled and
* the cell generators of its crack seeds.
*/
public final class GeneratorRuntime {
private static final int CELL_SEED_CAPACITY = 8;
private final IrisGenerator.SurfaceCacheStripe[] surfaceStripes = IrisGenerator.createSurfaceStripes();
private final SeedTable<CellGenerator> cellGenerators;
public GeneratorRuntime(IrisGenerator generator) {
this.cellGenerators = new SeedTable<>(CELL_SEED_CAPACITY, generator::buildCellGenerator);
}
IrisGenerator.SurfaceCacheStripe[] surfaceStripes() {
return surfaceStripes;
}
public CellGenerator cellGenerator(long seed) {
return cellGenerators.get(seed);
}
}
@@ -20,22 +20,28 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.spi.IrisLogging;
import com.dfsek.paralithic.Expression;
import com.dfsek.paralithic.functions.dynamic.DynamicFunction;
import com.dfsek.paralithic.eval.parser.Parser;
import com.dfsek.paralithic.eval.parser.Scope;
import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import art.arcane.iris.generation.noise.IrisExpressionFunction.FunctionContext;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import art.arcane.volmlib.util.stream.interpolation.Interpolated;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.function.Function;
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@@ -43,6 +49,9 @@ import java.util.function.Function;
@Data
@EqualsAndHashCode(callSuper = false)
public class IrisExpression extends IrisRegistrant {
private static final int MAX_RETAINED_EVALUATION_DEPTH = 8;
private static final int MAX_RETAINED_ARGUMENTS = 256;
@ArrayType(type = IrisExpressionLoad.class, min = 1)
@Description("Variables to use in this expression")
private KList<IrisExpressionLoad> variables = new KList<>();
@@ -55,38 +64,88 @@ public class IrisExpression extends IrisRegistrant {
@Description("The expression. Inherited variables are x, y and z. Avoid using those variable names.")
private String expression;
/**
* Parses this expression with each valid function bound to the runtime object the caller built for it.
* Returns null when the expression does not parse; the failure is reported.
*/
public Expression parse(Function<IrisExpressionFunction, DynamicFunction> functionRuntime) {
Scope scope = new Scope(); // Create variable scope. This scope can hold both constants and invocation variables.
Parser parser = new Parser();
private transient AtomicCache<Expression> expressionCache = new AtomicCache<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<Long, ProceduralStream<Double>> streams = new LazyBoundedCache<>(8);
try {
for (IrisExpressionLoad i : variables) {
scope.addInvocationVariable(i.getName());
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient ThreadLocal<EvaluationScratch> evaluationScratch = ThreadLocal.withInitial(EvaluationScratch::new);
private Expression expression() {
return expressionCache.aquire(() -> {
Scope scope = new Scope(); // Create variable scope. This scope can hold both constants and invocation variables.
Parser parser = new Parser();
try {
for (IrisExpressionLoad i : variables) {
scope.addInvocationVariable(i.getName());
}
scope.addInvocationVariable("x");
scope.addInvocationVariable("y");
scope.addInvocationVariable("z");
} catch (Throwable e) {
IrisLogging.reportError("Script variable load failed in " + getLoadFile().getPath() + ".", e);
}
scope.addInvocationVariable("x");
scope.addInvocationVariable("y");
scope.addInvocationVariable("z");
} catch (Throwable e) {
IrisLogging.reportError("Script variable load failed in " + getLoadFile().getPath() + ".", e);
}
for (IrisExpressionFunction f : functions) {
if (!f.isValid()) continue;
f.setData(getLoader());
parser.registerFunction(f.getName(), f);
}
for (IrisExpressionFunction f : functions) {
if (!f.isValid()) continue;
parser.registerFunction(f.getName(), functionRuntime.apply(f));
}
try {
return parser.parse(getExpression(), scope);
} catch (Throwable e) {
IrisLogging.reportError("Script load failed in " + getLoadFile().getPath() + ".", e);
}
return null;
});
}
public ProceduralStream<Double> stream(RNG rng) {
return streams.computeIfAbsent(rng.getSeed(), seed -> {
RNG streamRng = new RNG(seed);
return ProceduralStream.of((x, z) -> evaluate(streamRng, x, z),
(x, y, z) -> evaluate(streamRng, x, y, z), Interpolated.DOUBLE);
});
}
public double evaluate(RNG rng, double x, double z) {
EvaluationScratch scratch = evaluationScratch.get();
double[] arguments = scratch.acquire(3 + getVariables().size());
try {
return parser.parse(getExpression(), scope);
} catch (Throwable e) {
IrisLogging.reportError("Script load failed in " + getLoadFile().getPath() + ".", e);
int index = 0;
for (IrisExpressionLoad variable : getVariables()) {
arguments[index++] = variable.getValue(rng, getLoader(), x, z);
}
arguments[index++] = x;
arguments[index++] = z;
arguments[index] = -1;
return expression().evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
}
}
return null;
public double evaluate(RNG rng, double x, double y, double z) {
EvaluationScratch scratch = evaluationScratch.get();
double[] arguments = scratch.acquire(3 + getVariables().size());
try {
int index = 0;
for (IrisExpressionLoad variable : getVariables()) {
arguments[index++] = variable.getValue(rng, getLoader(), x, y, z);
}
arguments[index++] = x;
arguments[index++] = y;
arguments[index] = z;
return expression().evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
}
}
@Override
@@ -98,4 +157,28 @@ public class IrisExpression extends IrisRegistrant {
public String getTypeName() {
return "Expression";
}
private static final class EvaluationScratch {
private final double[][] retained = new double[MAX_RETAINED_EVALUATION_DEPTH][];
private int depth;
private double[] acquire(int length) {
double[] arguments;
if (depth >= retained.length || length > MAX_RETAINED_ARGUMENTS) {
arguments = new double[length];
} else {
arguments = retained[depth];
if (arguments == null || arguments.length != length) {
arguments = new double[length];
retained[depth] = arguments;
}
}
depth++;
return arguments;
}
private void release() {
depth--;
}
}
}
@@ -2,15 +2,31 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.IrisEngineStreamType;
import com.dfsek.paralithic.functions.dynamic.Context;
import com.dfsek.paralithic.functions.dynamic.DynamicFunction;
import com.dfsek.paralithic.node.Statefulness;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MinNumber;
import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.stream.ProceduralStream;
import java.util.Objects;
import art.arcane.volmlib.util.math.RNG;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Snippet("expression-function")
@Accessors(chain = true)
@@ -19,7 +35,7 @@ import lombok.experimental.Accessors;
@Description("Represents a function to use in your expression. Do not set the name to x, y, or z, also don't duplicate names.")
@Data
@EqualsAndHashCode(callSuper = false)
public class IrisExpressionFunction {
public class IrisExpressionFunction implements DynamicFunction {
@Required
@Description("The function to assign this value to. Do not set the name to x, y, or z")
private String name;
@@ -34,12 +50,102 @@ public class IrisExpressionFunction {
@Description("Number of arguments for the function")
private int args = 2;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient final LazyBoundedCache<FunctionKey, Provider> providers = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedProvider recentProvider;
private transient IrisData data;
public boolean isValid() {
return styleValue != null || engineStreamValue != null;
}
public int argumentCount() {
@Override
public int getArgNumber() {
if (engineStreamValue != null) return 2;
return Math.max(args, 2);
}
@NotNull
@Override
public Statefulness statefulness() {
return Statefulness.STATEFUL;
}
@Override
public double eval(double... doubles) {
return 0;
}
@Override
public double eval(@Nullable Context raw, double... args) {
FunctionContext context = Objects.requireNonNull((FunctionContext) raw, "Expression context");
IrisData currentData = data;
Engine engine = currentData == null ? null : currentData.getEngine();
long seed = context.rng.getSeed();
CachedProvider recent = recentProvider;
if (recent != null && recent.key.matches(seed, currentData, engine)) {
return recent.provider.eval(args);
}
FunctionKey key = new FunctionKey(seed, currentData, engine);
Provider provider = providers.computeIfAbsent(key, ignored -> createProvider(key));
recentProvider = new CachedProvider(key, provider);
return provider.eval(args);
}
private Provider createProvider(FunctionKey key) {
if (engineStreamValue != null) {
if (key.engine == null) {
throw new IllegalStateException("Expression function '" + name + "' requires an active Iris engine.");
}
ProceduralStream<Double> stream = engineStreamValue.get(key.engine);
return coordinates -> stream.get(coordinates[0], coordinates[1]);
}
if (styleValue != null) {
return styleValue.create(new RNG(key.seed), key.data, key.engine)::noise;
}
return coordinates -> Double.NaN;
}
private record FunctionKey(long seed, IrisData data, Engine engine) {
private boolean matches(long seed, IrisData data, Engine engine) {
return this.seed == seed && this.data == data && this.engine == engine;
}
@Override
public boolean equals(Object object) {
return object instanceof FunctionKey other && matches(other.seed, other.data, other.engine);
}
@Override
public int hashCode() {
int hash = Long.hashCode(seed);
hash = 31 * hash + System.identityHashCode(data);
return 31 * hash + System.identityHashCode(engine);
}
}
private record CachedProvider(FunctionKey key, Provider provider) {
}
public record FunctionContext(@NonNull RNG rng) implements Context {
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
FunctionContext that = (FunctionContext) o;
return rng.getSeed() == that.rng.getSeed();
}
@Override
public int hashCode() {
return Long.hashCode(rng.getSeed());
}
}
@FunctionalInterface
private interface Provider {
double eval(double... args);
}
}
@@ -21,15 +21,30 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.IrisEngineStreamType;
import art.arcane.iris.generation.runtime.IrisEngineValueType;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
@Snippet("expression-load")
@Accessors(chain = true)
@NoArgsConstructor
@@ -38,6 +53,7 @@ import lombok.experimental.Accessors;
@Data
@EqualsAndHashCode(callSuper = false)
public class IrisExpressionLoad {
private static final int STYLE_CACHE_SIZE = 8;
@Required
@Description("The variable to assign this value to. Do not set the name to x, y, or z")
private String name = "";
@@ -53,4 +69,119 @@ public class IrisExpressionLoad {
@Description("If defined, iris will use an internal value from the engine as it's value")
private IrisEngineValueType engineValue = null;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient final Map<Engine, EngineCache> engineCaches =
Collections.synchronizedMap(new IdentityHashMap<>());
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient final LazyBoundedCache<StandaloneStyleKey, CNG> standaloneStyleCache =
new LazyBoundedCache<>(STYLE_CACHE_SIZE);
public double getValue(RNG rng, IrisData data, double x, double z) {
if (engineValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).value.aquire(() -> engineValue.get(engine));
}
if (engineStreamValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z);
}
if (styleValue != null) {
return style(data, rng).noise(x, z);
}
return staticValue;
}
public double getValue(RNG rng, IrisData data, double x, double y, double z) {
if (engineValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).value.aquire(() -> engineValue.get(engine));
}
if (engineStreamValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z);
}
if (styleValue != null) {
return style(data, rng).noise(x, y, z);
}
return staticValue;
}
private Engine requireEngine(IrisData data) {
Engine engine = data.getEngine();
if (engine == null) {
throw new IllegalStateException("Expression variable '" + name + "' requires an active Iris engine.");
}
return engine;
}
private EngineCache cacheFor(Engine engine) {
synchronized (engineCaches) {
Iterator<Map.Entry<Engine, EngineCache>> iterator = engineCaches.entrySet().iterator();
while (iterator.hasNext()) {
if (iterator.next().getKey().isClosed()) {
iterator.remove();
}
}
EngineCache cache = engineCaches.get(engine);
if (cache != null) {
return cache;
}
EngineCache created = new EngineCache();
engineCaches.put(engine, created);
return created;
}
}
private CNG style(IrisData data, RNG rng) {
Engine engine = data.getEngine();
long seed = rng.getSeed();
if (engine != null) {
return cacheFor(engine).styles.computeIfAbsent(seed,
ignored -> styleValue.createNoCache(new RNG(seed), data));
}
StandaloneStyleKey key = new StandaloneStyleKey(data, seed);
return standaloneStyleCache.computeIfAbsent(key,
ignored -> styleValue.createNoCache(new RNG(seed), data));
}
private static final class EngineCache {
private final AtomicCache<ProceduralStream<Double>> stream = new AtomicCache<>();
private final AtomicCache<Double> value = new AtomicCache<>();
private final LazyBoundedCache<Long, CNG> styles = new LazyBoundedCache<>(STYLE_CACHE_SIZE);
}
private static final class StandaloneStyleKey {
private final IrisData data;
private final long seed;
private StandaloneStyleKey(IrisData data, long seed) {
this.data = data;
this.seed = seed;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof StandaloneStyleKey key)) {
return false;
}
return data == key.data && seed == key.seed;
}
@Override
public int hashCode() {
return 31 * System.identityHashCode(data) + Long.hashCode(seed);
}
}
}
@@ -19,7 +19,9 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
@@ -30,10 +32,13 @@ import art.arcane.volmlib.util.interpolation.IrisInterpolation;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CellGenerator;
import java.util.concurrent.atomic.AtomicReferenceArray;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.List;
@@ -49,6 +54,15 @@ public class IrisGenerator extends IrisRegistrant {
private static final int SURFACE_CACHE_STRIPES = 16;
private static final int SURFACE_CACHE_STRIPE_SIZE = 1024;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<Long, CellGenerator> cellGenerators = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedCellGenerator recentCellGenerator;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile SurfaceCache surfaceSamples;
@MinNumber(0.001)
@Description("The zoom or frequency.")
private double zoom = 1;
@@ -62,9 +76,6 @@ public class IrisGenerator extends IrisRegistrant {
@Description("Multiply the compsites instead of adding them")
private boolean multiplicitive = false;
@MinNumber(0.001)
@Description("Curves the combined composite value (0-1) as value^exponent before opacity. Above 1 flattens lows and sharpens peaks, below 1 does the opposite. Unlike the exponent on a single noise generator, this acts on the combined result of all composites.")
private double exponent = 1;
@MinNumber(0.001)
@Description("The size of the cell fractures")
private double cellFractureZoom = 1D;
@MinNumber(0)
@@ -108,13 +119,21 @@ public class IrisGenerator extends IrisRegistrant {
return cliffHeightMax > 0;
}
CellGenerator buildCellGenerator(long seed) {
CellGenerator created = new CellGenerator(new RNG(seed + 239466));
created.setShuffle(getCellFractureShuffle());
return created;
public CellGenerator getCellGenerator(long seed) {
CachedCellGenerator recent = recentCellGenerator;
if (recent != null && recent.seed == seed) {
return recent.generator;
}
CellGenerator generator = cellGenerators.computeIfAbsent(seed, ignored -> {
CellGenerator created = new CellGenerator(new RNG(seed + 239466));
created.setShuffle(getCellFractureShuffle());
return created;
});
recentCellGenerator = new CachedCellGenerator(seed, generator);
return generator;
}
public <T> T fit(PackRuntime runtime, T[] v, long superSeed, double rx, double rz) {
public <T> T fit(T[] v, long superSeed, double rx, double rz) {
if (v.length == 0) {
return null;
}
@@ -123,10 +142,10 @@ public class IrisGenerator extends IrisRegistrant {
return v[0];
}
return v[fit(runtime, 0, v.length - 1, superSeed, rx, rz)];
return v[fit(0, v.length - 1, superSeed, rx, rz)];
}
public <T> T fit(PackRuntime runtime, List<T> v, long superSeed, double rx, double rz) {
public <T> T fit(List<T> v, long superSeed, double rx, double rz) {
if (v.size() == 0) {
return null;
}
@@ -135,60 +154,61 @@ public class IrisGenerator extends IrisRegistrant {
return v.get(0);
}
return v.get(fit(runtime, 0, v.size() - 1, superSeed, rx, rz));
return v.get(fit(0, v.size() - 1, superSeed, rx, rz));
}
public int fit(PackRuntime runtime, int min, int max, long superSeed, double rx, double rz) {
public int fit(int min, int max, long superSeed, double rx, double rz) {
if (min == max) {
return min;
}
double noise = getHeight(runtime, rx, rz, superSeed);
double noise = getHeight(rx, rz, superSeed);
return (int) Math.round(IrisInterpolation.lerp(min, max, noise));
}
public int fit(PackRuntime runtime, double min, double max, long superSeed, double rx, double rz) {
public int fit(double min, double max, long superSeed, double rx, double rz) {
if (min == max) {
return (int) Math.round(min);
}
double noise = getHeight(runtime, rx, rz, superSeed);
double noise = getHeight(rx, rz, superSeed);
return (int) Math.round(IrisInterpolation.lerp(min, max, noise));
}
public double fitDouble(PackRuntime runtime, double min, double max, long superSeed, double rx, double rz) {
public double fitDouble(double min, double max, long superSeed, double rx, double rz) {
if (min == max) {
return min;
}
double noise = getHeight(runtime, rx, rz, superSeed);
double noise = getHeight(rx, rz, superSeed);
return IrisInterpolation.lerp(min, max, noise);
}
public double getHeight(PackRuntime runtime, double rx, double rz, long superSeed) {
return getHeight(runtime, rx, 0, rz, superSeed, true);
public double getHeight(double rx, double rz, long superSeed) {
return getHeight(rx, 0, rz, superSeed, true);
}
public double getHeight(PackRuntime runtime, double rx, double ry, double rz, long superSeed) {
return getHeight(runtime, rx, ry, rz, superSeed, false);
public double getHeight(double rx, double ry, double rz, long superSeed) {
return getHeight(rx, ry, rz, superSeed, false);
}
public double getHeight(PackRuntime runtime, double rx, double ry, double rz, long superSeed, boolean no3d) {
public double getHeight(double rx, double ry, double rz, long superSeed, boolean no3d) {
if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) {
throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1");
}
requireValidExponent();
if (composite.isEmpty()) {
return 0D;
}
IrisData data = getLoader();
Engine engine = data == null ? null : data.getEngine();
if (surfaceDetail == 1D) {
return sampleHeight(rx, rz, superSeed, runtime);
return sampleHeight(rx, rz, superSeed, data, engine);
}
return surfaceHeight(rx, rz, superSeed, runtime);
return surfaceHeight(rx, rz, superSeed, data, engine);
}
public boolean supportsBatch() {
@@ -204,29 +224,35 @@ public class IrisGenerator extends IrisRegistrant {
return !hasCliffs() || cliffHeightGenerator.supportsBatch();
}
public GeneratorProgram compileProgram(PackRuntime runtime, long superSeed) {
public GeneratorProgram compileProgram(long superSeed) {
if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) {
throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1");
}
requireValidExponent();
if (!supportsBatch()) {
throw new IllegalStateException("Generator " + getLoadKey() + " cannot be compiled into a batch program");
}
IrisData data = getLoader();
Engine engine = data == null ? null : data.getEngine();
int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ);
NoiseLayerProgram[] layers = new NoiseLayerProgram[composite.size()];
double totalOpacity = 0D;
for (int index = 0; index < layers.length; index++) {
IrisNoiseGenerator layer = composite.get(index);
layers[index] = layer.compileProgram(getSeed() + superSeed + hc, runtime);
layers[index] = layer.compileProgram(getSeed() + superSeed + hc, data, engine);
if (!multiplicitive) {
totalOpacity += layer.getOpacity();
}
}
double cliffSeed = (double) (superSeed + 294596 + hc) - 34857;
NoiseLayerProgram cliffs = hasCliffs()
? cliffHeightGenerator.compileProgram((long) (getSeed() + cliffSeed + hc), runtime)
? cliffHeightGenerator.compileProgram((long) (getSeed() + cliffSeed + hc), data, engine)
: null;
return new GeneratorProgram(this, superSeed, layers, totalOpacity, cliffs, runtime);
return new GeneratorProgram(this, superSeed, layers, totalOpacity, cliffs);
}
SurfaceCacheStripe[] surfaceStripes() {
IrisData data = getLoader();
return surfaceCache(data, data == null ? null : data.getEngine()).stripes();
}
static boolean cachedSurface(SurfaceCacheStripe[] stripes, double x, double z, long superSeed, double[] target, int index) {
@@ -255,30 +281,30 @@ public class IrisGenerator extends IrisRegistrant {
return mixed;
}
private double surfaceHeight(double rx, double rz, long superSeed, PackRuntime runtime) {
SurfaceCacheStripe[] stripes = runtime.generator(this).surfaceStripes();
private double surfaceHeight(double rx, double rz, long superSeed, IrisData data, Engine engine) {
SurfaceCacheStripe[] stripes = surfaceCache(data, engine).stripes();
double lowerX = Math.floor(rx / SURFACE_GRID) * SURFACE_GRID;
double lowerZ = Math.floor(rz / SURFACE_GRID) * SURFACE_GRID;
double dx = (rx - lowerX) / SURFACE_GRID;
double dz = (rz - lowerZ) / SURFACE_GRID;
double northWest = cachedSurfaceHeight(lowerX, lowerZ, superSeed, stripes, runtime);
double northWest = cachedSurfaceHeight(lowerX, lowerZ, superSeed, stripes, data, engine);
if (dx == 0D && dz == 0D) {
return northWest;
}
double north = dx == 0D ? northWest : IrisInterpolation.lerp(northWest,
cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ, superSeed, stripes, runtime), dx);
cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ, superSeed, stripes, data, engine), dx);
double smooth = north;
if (dz != 0D) {
double southWest = cachedSurfaceHeight(lowerX, lowerZ + SURFACE_GRID, superSeed, stripes, runtime);
double southWest = cachedSurfaceHeight(lowerX, lowerZ + SURFACE_GRID, superSeed, stripes, data, engine);
double south = dx == 0D ? southWest : IrisInterpolation.lerp(southWest,
cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ + SURFACE_GRID, superSeed, stripes, runtime), dx);
cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ + SURFACE_GRID, superSeed, stripes, data, engine), dx);
smooth = IrisInterpolation.lerp(north, south, dz);
}
return surfaceDetail == 0D ? smooth
: smooth + (sampleHeight(rx, rz, superSeed, runtime) - smooth) * surfaceDetail;
: smooth + (sampleHeight(rx, rz, superSeed, data, engine) - smooth) * surfaceDetail;
}
private double sampleHeight(double rx, double rz, long superSeed, PackRuntime runtime) {
private double sampleHeight(double rx, double rz, long superSeed, IrisData data, Engine engine) {
int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ);
double h = multiplicitive ? 1 : 0;
double tp = 0;
@@ -287,52 +313,37 @@ public class IrisGenerator extends IrisRegistrant {
if (composite.size() == 1) {
if (multiplicitive) {
h *= composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
h *= composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine);
} else {
tp += composite.get(0).getOpacity();
h += composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
h += composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine);
}
} else {
for (IrisNoiseGenerator i : composite) {
if (multiplicitive) {
h *= i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
h *= i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine);
} else {
tp += i.getOpacity();
h += i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
h += i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine);
}
}
}
double combined = multiplicitive ? h : h / tp;
double v = applyExponent(combined, exponent) * opacity;
double v = multiplicitive ? h * opacity : (h / tp) * opacity;
if (Double.isNaN(v)) {
v = 0;
}
v = hasCliffs() ? cliff(runtime, rx, rz, v, superSeed + 294596 + hc) : v;
v = hasCellCracks() ? cell(runtime, rx, rz, v, superSeed + 48622 + hc) : v;
v = hasCliffs() ? cliff(rx, rz, v, superSeed + 294596 + hc, data, engine) : v;
v = hasCellCracks() ? cell(rx, rz, v, superSeed + 48622 + hc) : v;
return v;
}
static double applyExponent(double value, double exponent) {
if (exponent == 1) {
return value;
}
return value < 0 ? -Math.pow(-value, exponent) : Math.pow(value, exponent);
}
private void requireValidExponent() {
if (!Double.isFinite(exponent) || exponent <= 0D) {
throw new IllegalArgumentException("Generator exponent must be finite and above 0");
}
}
private double cachedSurfaceHeight(double x, double z, long superSeed, SurfaceCacheStripe[] stripes, PackRuntime runtime) {
private double cachedSurfaceHeight(double x, double z, long superSeed, SurfaceCacheStripe[] stripes, IrisData data, Engine engine) {
if (x != (int) x || z != (int) z) {
return sampleHeight(x, z, superSeed, runtime);
return sampleHeight(x, z, superSeed, data, engine);
}
long key = ((long) (int) x << 32) | ((int) z & 0xffffffffL);
long mixed = surfaceMix(key);
@@ -342,12 +353,27 @@ public class IrisGenerator extends IrisRegistrant {
if (cached != null) {
return cached.height();
}
double height = sampleHeight(x, z, superSeed, runtime);
double height = sampleHeight(x, z, superSeed, data, engine);
stripe.put(slot, new SurfaceSample(key, superSeed, height));
return height;
}
static SurfaceCacheStripe[] createSurfaceStripes() {
private SurfaceCache surfaceCache(IrisData data, Engine engine) {
SurfaceCache cached = surfaceSamples;
if (cached != null && cached.data() == data && cached.engine() == engine) {
return cached;
}
synchronized (this) {
cached = surfaceSamples;
if (cached == null || cached.data() != data || cached.engine() != engine) {
cached = new SurfaceCache(data, engine, createSurfaceCache());
surfaceSamples = cached;
}
return cached;
}
}
private static SurfaceCacheStripe[] createSurfaceCache() {
SurfaceCacheStripe[] stripes = new SurfaceCacheStripe[SURFACE_CACHE_STRIPES];
for (int i = 0; i < stripes.length; i++) {
stripes[i] = new SurfaceCacheStripe();
@@ -355,29 +381,45 @@ public class IrisGenerator extends IrisRegistrant {
return stripes;
}
public double cell(PackRuntime runtime, double rx, double rz, double v, double superSeed) {
public double cell(double rx, double rz, double v, double superSeed) {
double fractureX = rx / getCellFractureZoom();
double fractureZ = rz / getCellFractureZoom();
return runtime.generator(this).cellGenerator(getSeed() + 46222).getDistance(fractureX, fractureZ) > getCellPercentSize() ? (v * getCellFractureHeight()) : v;
return getCellGenerator(getSeed() + 46222).getDistance(fractureX, fractureZ) > getCellPercentSize() ? (v * getCellFractureHeight()) : v;
}
private boolean hasCellCracks() {
return getCellFractureHeight() != 0;
}
public double getCliffHeight(PackRuntime runtime, double rx, double rz, double superSeed) {
public double getCliffHeight(double rx, double rz, double superSeed) {
IrisData data = getLoader();
return getCliffHeight(rx, rz, superSeed, data, data == null ? null : data.getEngine());
}
private double getCliffHeight(double rx, double rz, double superSeed, IrisData data, Engine engine) {
int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ);
double sampleX = (rx + offsetX) / zoom;
double sampleZ = (rz + offsetZ) / zoom;
double h = cliffHeightGenerator.getNoise((long) (getSeed() + superSeed + hc), sampleX, sampleZ, runtime);
double h = cliffHeightGenerator.getNoise((long) (getSeed() + superSeed + hc), sampleX, sampleZ, data, engine);
return IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, h);
}
public double cliff(PackRuntime runtime, double rx, double rz, double v, double superSeed) {
double cliffHeight = getCliffHeight(runtime, rx, rz, superSeed - 34857);
public double cliff(double rx, double rz, double v, double superSeed) {
IrisData data = getLoader();
return cliff(rx, rz, v, superSeed, data, data == null ? null : data.getEngine());
}
private double cliff(double rx, double rz, double v, double superSeed, IrisData data, Engine engine) {
double cliffHeight = getCliffHeight(rx, rz, superSeed - 34857, data, engine);
return (Math.round((v * 255D) / cliffHeight) * cliffHeight) / 255D;
}
public IrisGenerator rescale(double scale) {
zoom /= scale;
surfaceSamples = null;
return this;
}
public KList<IrisNoiseGenerator> getAllComposites() {
KList<IrisNoiseGenerator> g = new KList<>();
@@ -398,6 +440,9 @@ public class IrisGenerator extends IrisRegistrant {
return "Generator";
}
private record SurfaceCache(IrisData data, Engine engine, SurfaceCacheStripe[] stripes) {
}
private record SurfaceSample(long key, long seed, double height) {
}
@@ -413,4 +458,7 @@ public class IrisGenerator extends IrisRegistrant {
entries.set(slot, sample);
}
}
private record CachedCellGenerator(long seed, CellGenerator generator) {
}
}
@@ -21,8 +21,8 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.image.IrisImageMap;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.world.history.GenerationKernelRegistry;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
@@ -52,7 +52,15 @@ import java.util.concurrent.ConcurrentHashMap;
@Description("A gen style")
@Data
public class IrisGeneratorStyle {
private static final int GENERATOR_CACHE_SIZE = 8;
private static final ConcurrentHashMap<String, String> ACTIVE_CACHE_KEYS = new ConcurrentHashMap<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<GeneratorCacheKey, CNG> generatorCache =
new LazyBoundedCache<>(GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedGenerator recentGenerator;
@Description("The base noise style. Used when neither expression nor imageMap is set; a failed expression also falls back to this style, except one that names an unknown engine stream, which fails the pack load.")
private NoiseStyle style = NoiseStyle.FLAT;
@@ -83,8 +91,6 @@ public class IrisGeneratorStyle {
@MaxNumber(8192)
@Description("If the cache size is set above 0, this generator will be cached")
private int cacheSize = 0;
@Description("Rolls this noise from the world seed and this number, so every style with the same seed shares one noise. Child biomes, palettes and decorator placement read a seeded style flat in blocks: zoom is its only scale, so a layer's zoom, childShrinkFactor and the decorator's extra zoom don't apply.")
private Long seed = null;
public IrisGeneratorStyle(NoiseStyle s) {
this.style = s;
@@ -95,20 +101,24 @@ public class IrisGeneratorStyle {
return this;
}
public CNG createNoCache(RNG rng, PackRuntime runtime) {
return createNoCache(rng, runtime, 1, 0, false);
public CNG createNoCache(RNG rng, IrisData data) {
return createNoCache(rng, data, 1, 0, false, resolveEngine(data));
}
public CNG createScaledGenerator(RNG rng, PackRuntime runtime, double scaleFactor) {
return createNoCache(rng, runtime).bake().scale(scaleFactor).bake();
public CNG createScaledGenerator(RNG rng, IrisData data, double scaleFactor) {
return createNoCache(rng, data).bake().scale(scaleFactor).bake();
}
public CNG createForLayer(RNG rng, PackRuntime runtime, int octaveMultiplier) {
return createNoCache(rng, runtime, Math.clamp(octaveMultiplier, 1, 16), 0, false);
public CNG createForLayer(RNG rng, IrisData data, int octaveMultiplier) {
return createForLayer(rng, data, octaveMultiplier, resolveEngine(data));
}
public CNG createForPrebake(RNG rng, PackRuntime runtime, int fallbackCacheSize) {
return createNoCache(rng, runtime, 1, Math.max(0, fallbackCacheSize), true);
CNG createForLayer(RNG rng, IrisData data, int octaveMultiplier, Engine engine) {
return createNoCache(rng, data, Math.clamp(octaveMultiplier, 1, 16), 0, false, engine);
}
public CNG createForPrebake(RNG rng, IrisData data, int fallbackCacheSize) {
return createNoCache(rng, data, 1, Math.max(0, fallbackCacheSize), true, resolveEngine(data));
}
@@ -121,34 +131,7 @@ public class IrisGeneratorStyle {
}
private int hash() {
int unseededHash = Objects.hash(expression, imageMapHash(), multiplier, fracture != null ? fracture.hash() : 0, exponent, cacheSize, zoom, cellularZoom, cellularFrequency, style == null ? null : style.name());
return isSeeded() ? Objects.hash(unseededHash, seed) : unseededHash;
}
public boolean isSeeded() {
return seed != null;
}
/** The random a style is built from: the caller's, or for a seeded style one rolled from its seed and the world seed. */
public RNG rollFor(RNG callerRandom, Engine engine) {
if (!isSeeded()) {
return callerRandom;
}
return new RNG(rolledSeed(engine));
}
private long rolledSeed(Engine engine) {
long worldSeed = engine == null ? 0L : engine.getSeedManager().getSeed();
return splitMix(worldSeed ^ splitMix(seed));
}
// Spreads nearby seed numbers far apart; Iris's own seed forking only adds.
private static long splitMix(long value) {
long mixed = value + 0x9E3779B97F4A7C15L;
mixed = (mixed ^ (mixed >>> 30)) * 0xBF58476D1CE4E5B9L;
mixed = (mixed ^ (mixed >>> 27)) * 0x94D049BB133111EBL;
return mixed ^ (mixed >>> 31);
return Objects.hash(expression, imageMapHash(), multiplier, fracture != null ? fracture.hash() : 0, exponent, cacheSize, zoom, cellularZoom, cellularFrequency, style == null ? null : style.name());
}
public int prebakeSignature() {
@@ -192,11 +175,8 @@ public class IrisGeneratorStyle {
}
}
private CNG createNoCache(RNG callerRandom, PackRuntime runtime, int octaveMultiplier, int fallbackCacheSize,
boolean quietCacheLog) {
IrisData data = runtime.data();
Engine engine = runtime.engine();
RNG rng = rollFor(callerRandom, engine);
private CNG createNoCache(RNG rng, IrisData data, int octaveMultiplier, int fallbackCacheSize,
boolean quietCacheLog, Engine engine) {
requirePositiveFinite("zoom", zoom);
requirePositiveFinite("exponent", exponent);
if (!Double.isFinite(cellularFrequency) || cellularFrequency < 0D) {
@@ -213,7 +193,7 @@ public class IrisGeneratorStyle {
if (getExpression() != null) {
IrisExpression e = data.getExpressionLoader().load(getExpression());
if (e != null) {
cng = new CNG(rng, new ExpressionNoise(rng, runtime.expression(e)), 1D, 1).bake();
cng = new CNG(rng, new ExpressionNoise(rng, e), 1D, 1).bake();
sourceStamp = Integer.toUnsignedLong(Objects.hash(getExpression(),
e.getLoadFile() == null ? 0L : e.getLoadFile().lastModified()));
}
@@ -231,8 +211,8 @@ public class IrisGeneratorStyle {
.pow(cng.getPower() * exponent);
if (fracture != null) {
cng.fractureWith(fracture.createNoCache(rng.nextParallelRNG(2934), runtime, 1,
fallbackCacheSize, quietCacheLog), fracture.getMultiplier());
cng.fractureWith(fracture.createNoCache(rng.nextParallelRNG(2934), data, 1,
fallbackCacheSize, quietCacheLog, engine), fracture.getMultiplier());
}
if (cellularFrequency > 0) {
@@ -252,17 +232,32 @@ public class IrisGeneratorStyle {
return cng;
}
public double warp(RNG rng, PackRuntime runtime, double value, double... coords) {
return create(rng, runtime).noise(coords) + value;
public double warp(RNG rng, IrisData data, double value, double... coords) {
return create(rng, data).noise(coords) + value;
}
/** The generator this runtime shares for this style and seed. */
public CNG create(RNG rng, PackRuntime runtime) {
return create(rng.getSeed(), runtime);
public CNG create(RNG rng, IrisData data) {
return create(rng, data, resolveEngine(data));
}
public CNG create(long callerSeed, PackRuntime runtime) {
return runtime.styleGenerator(this, isSeeded() ? rolledSeed(runtime.engine()) : callerSeed);
public CNG create(long seed, IrisData data) {
return cachedGenerator(seed, data, resolveEngine(data));
}
public CNG create(RNG rng, IrisData data, Engine engine) {
return cachedGenerator(rng.getSeed(), data, engine);
}
private CNG cachedGenerator(long seed, IrisData data, Engine engine) {
CachedGenerator recent = recentGenerator;
if (recent != null && recent.key.matches(data, engine, seed)) {
return recent.generator;
}
GeneratorCacheKey key = new GeneratorCacheKey(data, engine, seed);
CNG generator = generatorCache.computeIfAbsent(key,
ignored -> createNoCache(new RNG(seed), data, 1, 0, false, engine));
recentGenerator = new CachedGenerator(key, generator);
return generator;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
@@ -287,6 +282,10 @@ public class IrisGeneratorStyle {
));
}
private Engine resolveEngine(IrisData data) {
return data == null ? null : data.getEngine();
}
private static void requirePositiveFinite(String field, double value) {
if (!Double.isFinite(value) || value <= 0D || !Double.isFinite(1D / value)) {
throw new IllegalArgumentException(field + " must be finite and positive");
@@ -305,4 +304,41 @@ public class IrisGeneratorStyle {
}
}
}
private static final class GeneratorCacheKey {
private final IrisData data;
private final Engine engine;
private final long seed;
private GeneratorCacheKey(IrisData data, Engine engine, long seed) {
this.data = data;
this.engine = engine;
this.seed = seed;
}
private boolean matches(IrisData data, Engine engine, long seed) {
return this.data == data && this.engine == engine && this.seed == seed;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof GeneratorCacheKey key)) {
return false;
}
return data == key.data && engine == key.engine && seed == key.seed;
}
@Override
public int hashCode() {
int result = System.identityHashCode(data);
result = 31 * result + System.identityHashCode(engine);
return 31 * result + Long.hashCode(seed);
}
}
private record CachedGenerator(GeneratorCacheKey key, CNG generator) {
}
}
@@ -18,7 +18,9 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
@@ -38,12 +40,16 @@ import art.arcane.volmlib.util.noise.OffsetNoiseGenerator;
import art.arcane.volmlib.util.noise.PerlinNoise;
import art.arcane.volmlib.util.noise.SimplexNoise;
import art.arcane.volmlib.util.noise.program.NoiseProgram;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
@Snippet("generator")
@Accessors(chain = true)
@@ -52,6 +58,7 @@ import java.util.Objects;
@Description("A noise generator")
@Data
public class IrisNoiseGenerator {
private static final int GENERATOR_CACHE_SIZE = 32;
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;
@@ -60,6 +67,13 @@ public class IrisNoiseGenerator {
static final int Z_AXIS = 1;
private static final ThreadLocal<FractureSamples> FRACTURE_SAMPLES = ThreadLocal.withInitial(FractureSamples::new);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<GeneratorKey, CNG> generators =
new LazyBoundedCache<>(GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient AtomicReference<CachedGenerator> recentGenerator = new AtomicReference<>();
@MinNumber(0.0001)
@Description("The coordinate input zoom")
private double zoom = 1;
@@ -104,28 +118,43 @@ public class IrisNoiseGenerator {
this.enabled = enabled;
}
CNG getGenerator(long superSeed, PackRuntime runtime) {
return runtime.noiseLayerGenerator(this, superSeed + GENERATOR_SEED_SALT - seed);
}
CNG getGenerator(long superSeed, IrisData data, Engine engine) {
long generatorSeed = superSeed + GENERATOR_SEED_SALT - seed;
CachedGenerator recent = recentGenerator.get();
if (recent != null && recent.key.matches(data, engine, generatorSeed)) {
return recent.generator;
}
/** Builds this layer's generator for one derived seed; {@link PackRuntime} shares the result. */
public CNG buildGenerator(long generatorSeed, PackRuntime runtime) {
return style.createForLayer(new RNG(generatorSeed), runtime, octaves);
GeneratorKey key = new GeneratorKey(data, engine, generatorSeed);
CNG generator = generators.computeIfAbsent(key,
ignored -> style.createForLayer(new RNG(generatorSeed), data, octaves, engine));
if (generator != null) {
recentGenerator.set(new CachedGenerator(key, generator));
}
return generator;
}
public double getMax() {
return getOffsetY() + opacity;
}
public double getNoise(long superSeed, double xv, double zv, PackRuntime runtime) {
return getNoiseForAxis(superSeed, xv, zv, runtime, X_AXIS);
public double getNoise(long superSeed, double xv, double zv, IrisData data) {
if (!enabled) {
return offsetY;
}
return getNoise(superSeed, xv, zv, data, data == null ? null : data.getEngine());
}
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, PackRuntime runtime, int axis) {
private double getNoiseForAxis(long superSeed, double xv, double zv, IrisData data, Engine engine, int axis) {
if (!enabled) {
return offsetY;
}
@@ -135,7 +164,7 @@ public class IrisNoiseGenerator {
if (!samples.active) {
samples.active = true;
try {
if (samples.prepare(this, superSeed, runtime)) {
if (samples.prepare(this, superSeed, data, engine)) {
return samples.sample(xv, zv, axis);
}
} finally {
@@ -151,13 +180,13 @@ public class IrisNoiseGenerator {
for (IrisNoiseGenerator i : fracture) {
if (i.isEnabled()) {
double fractureOffset = i.getOpacity() / 2D;
x += i.getNoiseForAxis(superSeed + seed + g, xv, zv, runtime, X_AXIS) - fractureOffset;
z += i.getNoiseForAxis(superSeed + seed + g, xv, zv, runtime, Z_AXIS) - 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, runtime).reseededForAxis(axis), x, z);
return sample(getGenerator(superSeed, data, engine).reseededForAxis(axis), x, z);
}
boolean supportsBatch() {
@@ -181,11 +210,11 @@ public class IrisNoiseGenerator {
return true;
}
NoiseLayerProgram compileProgram(long superSeed, PackRuntime runtime) {
return compileProgram(superSeed, runtime, false);
NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine) {
return compileProgram(superSeed, data, engine, false);
}
private NoiseLayerProgram compileProgram(long superSeed, PackRuntime runtime, boolean readAsFracture) {
private NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine, boolean readAsFracture) {
if (!enabled) {
return NoiseLayerProgram.disabled(this);
}
@@ -201,12 +230,12 @@ public class IrisNoiseGenerator {
int compiled = 0;
for (IrisNoiseGenerator child : fracture) {
if (child.isEnabled()) {
children[compiled] = child.compileProgram(superSeed + seed + salt, runtime, true);
children[compiled] = child.compileProgram(superSeed + seed + salt, data, engine, true);
offsets[compiled++] = child.getOpacity() / 2D;
}
salt += 819;
}
CNG generator = Objects.requireNonNull(getGenerator(superSeed, runtime), "Noise layer generator");
CNG generator = Objects.requireNonNull(getGenerator(superSeed, data, engine), "Noise layer generator");
NoiseProgram zAxisProgram = readAsFracture ? NoiseProgram.compile2D(generator.reseededForAxis(Z_AXIS)) : null;
return NoiseLayerProgram.of(this, NoiseProgram.compile2D(generator), zAxisProgram, children, offsets);
}
@@ -282,19 +311,54 @@ public class IrisNoiseGenerator {
return false;
}
private static final class GeneratorKey {
private final IrisData data;
private final Engine engine;
private final long seed;
private GeneratorKey(IrisData data, Engine engine, long seed) {
this.data = data;
this.engine = engine;
this.seed = seed;
}
private boolean matches(IrisData data, Engine engine, long seed) {
return this.data == data && this.engine == engine && this.seed == seed;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof GeneratorKey other)) {
return false;
}
return data == other.data && engine == other.engine && seed == other.seed;
}
@Override
public int hashCode() {
int result = System.identityHashCode(data);
result = 31 * result + System.identityHashCode(engine);
result = 31 * result + Long.hashCode(seed);
return result;
}
}
private static final class FractureSamples {
private final IrisNoiseGenerator[] nodes = new IrisNoiseGenerator[MAXIMUM_FRACTURE_NODES];
private final CNG[] generators = new CNG[MAXIMUM_FRACTURE_NODES];
private int size;
private boolean active;
private boolean prepare(IrisNoiseGenerator node, long superSeed, PackRuntime runtime) {
private boolean prepare(IrisNoiseGenerator node, long superSeed, IrisData data, Engine engine) {
while (size < MAXIMUM_FRACTURE_NODES) {
if (node.getClass() != IrisNoiseGenerator.class || !node.enabled || !node.hasPureStyle()
|| node.fracture.size() > 1) {
return false;
}
CNG generator = node.getGenerator(superSeed, runtime);
CNG generator = node.getGenerator(superSeed, data, engine);
if (!isPureGenerator(generator)) {
return false;
}
@@ -340,4 +404,14 @@ public class IrisNoiseGenerator {
active = false;
}
}
private static final class CachedGenerator {
private final GeneratorKey key;
private final CNG generator;
private CachedGenerator(GeneratorKey key, CNG generator) {
this.key = key;
this.generator = generator;
}
}
}
@@ -18,7 +18,7 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
import art.arcane.iris.pack.schema.annotation.MinNumber;
@@ -63,16 +63,16 @@ public class IrisShapedGeneratorStyle {
this.generator = new IrisGeneratorStyle(style);
}
public double get(RNG rng, PackRuntime runtime, double... dim) {
return generator.create(rng, runtime).fitDouble(min, max, dim);
public double get(RNG rng, IrisData data, double... dim) {
return generator.create(rng, data).fitDouble(min, max, dim);
}
public double get(RNG rng, PackRuntime runtime, double x, double z) {
return generator.create(rng, runtime).fitDouble(min, max, x, z);
public double get(RNG rng, IrisData data, double x, double z) {
return generator.create(rng, data).fitDouble(min, max, x, z);
}
public double get(RNG rng, PackRuntime runtime, double x, double y, double z) {
return generator.create(rng, runtime).fitDouble(min, max, x, y, z);
public double get(RNG rng, IrisData data, double x, double y, double z) {
return generator.create(rng, data).fitDouble(min, max, x, y, z);
}
public boolean isFlat() {
@@ -18,7 +18,7 @@
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.volmlib.util.math.M;
@@ -46,7 +46,7 @@ public class IrisStyledRange {
@Description("The style to pick the range")
private IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.STATIC);
public double get(RNG rng, double x, double z, PackRuntime runtime) {
public double get(RNG rng, double x, double z, IrisData data) {
if (min == max) {
return min;
}
@@ -55,11 +55,11 @@ public class IrisStyledRange {
return M.lerp(min, max, 0.5);
}
return style.create(rng, runtime).fitDouble(min, max, x, z);
return style.create(rng, data).fitDouble(min, max, x, z);
}
public ProceduralStream<Double> stream(RNG rng, PackRuntime runtime) {
return ProceduralStream.of((x, z) -> get(rng, x, z, runtime), Interpolated.DOUBLE);
public ProceduralStream<Double> stream(RNG rng, IrisData data) {
return ProceduralStream.of((x, z) -> get(rng, x, z, data), Interpolated.DOUBLE);
}
public boolean isFlat() {
@@ -133,7 +133,7 @@ public final class DimensionStackContext {
upper.getDimension().getLoadKey()
);
RNG seamRng = new RNG(engine.getSeedManager().getTerrain() ^ salt);
CNG seamNoise = style.create(seamRng, PackRuntime.of(engine, engine.getData()));
CNG seamNoise = style.create(seamRng, engine.getData(), engine);
int amplitude = blend.getAmplitude();
samplers.add((x, z) -> clampSeamOffset(
seamNoise.fitDouble(-amplitude, amplitude, x, z), amplitude));
@@ -154,7 +154,6 @@ public final class DimensionTerrainContext implements DataProvider {
resolvedData = engine.getData();
}
IrisData dimensionData = resolvedData;
PackRuntime dimensionRuntime = PackRuntime.of(engine, dimensionData);
IrisImageMapRuntime imageMapRuntime = IrisImageMapRuntime.compile(
dimensionData,
dimension,
@@ -220,7 +219,7 @@ public final class DimensionTerrainContext implements DataProvider {
}
ProceduralStream<Double> regionStyleStream = dimension.getRegionStyle()
.create(rng.nextParallelRNG(883), dimensionRuntime).stream()
.create(rng.nextParallelRNG(883), dimensionData).stream()
.zoom(dimension.getRegionZoom());
KList<IrisRegion> regionPool = new KList<>();
for (IrisRegion region : dimensionData.getRegionLoader().loadAll(dimension.getRegions())) {
@@ -239,7 +238,7 @@ public final class DimensionTerrainContext implements DataProvider {
.convertAware2D((region, x, z) -> mappedRegion(imageMapRuntime, region, x, z)), cachePrefix + "ImageMappedRegionStream", engine, cacheSize)
: proceduralRegionStream;
Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> preparedBiomeStreams =
compileInferredBiomeStreams(dimension, dimensionRuntime, rng, preparedRegions);
compileInferredBiomeStreams(dimension, dimensionData, rng, preparedRegions);
ProceduralStream<IrisBiome> landBiomeStream = regionStream
.convert(region -> IrisComplex.preparedInferredBiomeStream(
@@ -260,7 +259,7 @@ public final class DimensionTerrainContext implements DataProvider {
inferredStreams.put(InferredType.SHORE, shoreBiomeStream);
ProceduralStream<InferredType> bridgeStream = focusBiome == null
? ContinentGenerator.create(dimension, rng, dimensionRuntime).stream()
? ContinentGenerator.create(dimension, rng, dimensionData).stream()
.convert(value -> value >= dimension.getLandChance()
? InferredType.SEA
: InferredType.LAND)
@@ -269,20 +268,16 @@ public final class DimensionTerrainContext implements DataProvider {
Interpolated.of(value -> 0D, value -> focusBiome.getInferredType())
);
boolean sealessRegions = IrisComplex.lacks(preparedBiomeStreams, InferredType.SEA);
ProceduralStream<IrisBiome> proceduralBaseBiomeStream = focusBiome == null
? bridgeStream
.convertAware2D((continent, x, z) -> {
InferredType type = sealessRegions
? IrisComplex.baseType(preparedBiomeStreams, regionStream.get(x, z), continent)
: continent;
.convertAware2D((type, x, z) -> {
ProceduralStream<IrisBiome> stream = inferredStreams.get(type);
return stream != null
? stream.get(x, z)
: inferredStreams.get(InferredType.LAND).get(x, z);
})
.convertAware2D((biome, x, z) -> implode(
biome, x, z, rng, dimensionRuntime, dataProvider, childSelectionPlans, 3))
biome, x, z, rng, dataProvider, childSelectionPlans, 3))
: ProceduralStream.of(
(x, z) -> focusBiome,
Interpolated.of(value -> 0D, value -> focusBiome)
@@ -298,7 +293,7 @@ public final class DimensionTerrainContext implements DataProvider {
: ProceduralStream.ofDouble((x, z) -> {
double value = 0D;
for (IrisShapedGeneratorStyle style : overlayNoise) {
value += style.get(rng, dimensionRuntime, x, z);
value += style.get(rng, dimensionData, x, z);
}
return value;
});
@@ -345,7 +340,6 @@ public final class DimensionTerrainContext implements DataProvider {
}
});
interpolatedHeight += IrisComplex.averageGeneratorHeights(
dimensionRuntime,
groupGenerators,
sampledBounds.min(),
sampledBounds.max(),
@@ -383,7 +377,7 @@ public final class DimensionTerrainContext implements DataProvider {
);
return resolvedBiome == baseBiome
? baseBiome
: implode(resolvedBiome, x, z, rng, dimensionRuntime, dataProvider, childSelectionPlans, 3);
: implode(resolvedBiome, x, z, rng, dataProvider, childSelectionPlans, 3);
}), cachePrefix + "ImageMappedFinalBiomeStream", engine, cacheSize)
: GenerationStreams.cache2D(ProceduralStream.of(
(x, z) -> focusBiome,
@@ -400,19 +394,19 @@ public final class DimensionTerrainContext implements DataProvider {
Terrain3DRuntime terrain3D = !terrain3DEnabled ? null : new Terrain3DRuntime(
new Terrain3DRuntime.Sources(heightStream::getDouble, finalBiomeStream::get),
new Terrain3DRuntime.Options(engine.getSeedManager().getTerrain() ^ seedOffset,
localHeight, fluidHeight, dimensionRuntime, true, Math.max(4096, cacheSize))
localHeight, fluidHeight, dimensionData, true, Math.max(4096, cacheSize))
);
ProceduralStream<Double> shapedHeightStream = terrain3D == null ? heightStream
: GenerationStreams.cache2DDouble(ProceduralStream.ofDouble((x, z) -> shapedHeight(terrain3D, x, z)), cachePrefix + "Terrain3DHeightStream", engine, cacheSize);
ProceduralStream<Double> slopeStream = GenerationStreams.cache2DDouble(shapedHeightStream.slope(3), cachePrefix + "SlopeStream", engine, cacheSize);
ProceduralStream<NativeBlockState> rockStream = dimension.getRockPalette()
.getLayerGenerator(rng.nextParallelRNG(45), dimensionRuntime).stream()
.getLayerGenerator(rng.nextParallelRNG(45), dimensionData).stream()
.select(dimension.getRockPalette().getBlockData(dimensionData));
FluidBlockSampler fluidBlockSampler;
if (includeFluid) {
ProceduralStream<NativeBlockState> fluidStream = dimension.getFluidPalette()
.getLayerGenerator(rng.nextParallelRNG(78), dimensionRuntime).stream()
.getLayerGenerator(rng.nextParallelRNG(78), dimensionData).stream()
.select(dimension.getFluidPalette().getBlockData(dimensionData));
fluidBlockSampler = fluidStream::get;
} else {
@@ -511,7 +505,7 @@ public final class DimensionTerrainContext implements DataProvider {
private static Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> compileInferredBiomeStreams(
IrisDimension dimension,
PackRuntime runtime,
IrisData data,
RNG rng,
Iterable<IrisRegion> regions
) {
@@ -523,11 +517,11 @@ public final class DimensionTerrainContext implements DataProvider {
}
EnumMap<InferredType, ProceduralStream<IrisBiome>> streams = new EnumMap<>(InferredType.class);
streams.put(InferredType.LAND, createInferredBiomeStream(
dimension, runtime, rng, region, InferredType.LAND));
dimension, data, rng, region, InferredType.LAND));
streams.put(InferredType.SEA, createInferredBiomeStream(
dimension, runtime, rng, region, InferredType.SEA));
dimension, data, rng, region, InferredType.SEA));
streams.put(InferredType.SHORE, createInferredBiomeStream(
dimension, runtime, rng, region, InferredType.SHORE));
dimension, data, rng, region, InferredType.SHORE));
compiled.put(region, Collections.unmodifiableMap(streams));
}
return Collections.unmodifiableMap(compiled);
@@ -535,41 +529,33 @@ public final class DimensionTerrainContext implements DataProvider {
private static ProceduralStream<IrisBiome> createInferredBiomeStream(
IrisDimension dimension,
PackRuntime runtime,
IrisData data,
RNG rng,
IrisRegion region,
InferredType type
) {
if ((type == InferredType.SEA || type == InferredType.SHORE) && loadInferredBiomes(runtime.data(), biomeKeys(region, type), type).isEmpty()) {
return IrisComplex.NO_BIOMES;
}
return switch (type) {
case LAND -> dimension.getLandBiomeStyle()
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), runtime).stream()
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), data).stream()
.zoom(dimension.getBiomeZoom())
.zoom(dimension.getLandZoom())
.zoom(region.getLandBiomeZoom())
.selectRarity(IrisComplex.requireLandBiomes(region,
loadInferredBiomes(runtime.data(), region.getLandBiomes(), InferredType.LAND)));
.selectRarity(loadInferredBiomes(data, region.getLandBiomes(), InferredType.LAND));
case SEA -> dimension.getSeaBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), runtime).stream()
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), data).stream()
.zoom(dimension.getBiomeZoom())
.zoom(dimension.getSeaZoom())
.zoom(region.getSeaBiomeZoom())
.selectRarity(loadInferredBiomes(runtime.data(), region.getSeaBiomes(), InferredType.SEA));
.selectRarity(loadInferredBiomes(data, region.getSeaBiomes(), InferredType.SEA));
case SHORE -> dimension.getShoreBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), runtime).stream()
.create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), data).stream()
.zoom(dimension.getBiomeZoom())
.zoom(region.getShoreBiomeZoom())
.selectRarity(loadInferredBiomes(runtime.data(), region.getShoreBiomes(), InferredType.SHORE));
.selectRarity(loadInferredBiomes(data, region.getShoreBiomes(), InferredType.SHORE));
default -> throw new IllegalArgumentException("Unsupported stacked terrain biome type: " + type);
};
}
private static KList<String> biomeKeys(IrisRegion region, InferredType type) {
return type == InferredType.SEA ? region.getSeaBiomes() : region.getShoreBiomes();
}
private static KList<IrisBiome> loadInferredBiomes(
IrisData data,
KList<String> keys,
@@ -608,7 +594,6 @@ public final class DimensionTerrainContext implements DataProvider {
double x,
double z,
RNG rng,
PackRuntime runtime,
DataProvider dataProvider,
Map<IrisBiome, IrisComplex.ChildSelectionPlan> childSelectionPlans,
int remainingDepth
@@ -636,7 +621,7 @@ public final class DimensionTerrainContext implements DataProvider {
}
IrisBiome selected = selectionPlan.select(
biome.getChildrenGenerator(runtime, rng, 123, biome.getChildShrinkFactor()), x, z);
biome.getChildrenGenerator(rng, 123, biome.getChildShrinkFactor()), x, z);
if (selected == null) {
return biome;
}
@@ -645,7 +630,6 @@ public final class DimensionTerrainContext implements DataProvider {
x,
z,
rng,
runtime,
dataProvider,
childSelectionPlans,
remainingDepth - 1
@@ -85,9 +85,6 @@ import java.util.stream.Collectors;
public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, Hotloadable {
IrisComplex getComplex();
/** The runtime objects this engine derived from its pack, or null while no runtime is active. */
PackRuntime getPackRuntime();
default BiomeEnvironment getBiomeEnvironment(int x, int y, int z) {
return new BiomeEnvironment(0L, getBiome(x, y, z), getRegion(x, y, z), getDimension(), getData());
}
@@ -76,7 +76,6 @@ final class EngineHotloader {
engine.sealForTransition("complex hotload", false);
engine.prepareRuntimeHotload();
assembly = new RuntimeAssembly(
engine,
RuntimeAssembly.nextRuntimeId(),
previousGeneration.target(),
previousGeneration.mantleStorageDirectory(),
@@ -95,7 +94,6 @@ final class EngineHotloader {
GenerationRuntime nextGeneration = previousGeneration.withComplex(
assembly.cacheId,
assembly.complex,
assembly.packRuntime,
assembly.upperContext,
assembly.dimensionStackContext,
biomeMaxes);
@@ -88,7 +88,6 @@ final class EngineRuntimeBuilder {
PreparedHydrologyCacheIdentity cacheIdentity
) {
RuntimeAssembly assembly = new RuntimeAssembly(
engine,
RuntimeAssembly.nextRuntimeId(),
runtimeTarget,
mantleStorageDirectory,
@@ -168,7 +167,6 @@ final class EngineRuntimeBuilder {
TransitionGenerationPlan transitionPlan
) {
RuntimeAssembly assembly = new RuntimeAssembly(
engine,
RuntimeAssembly.nextRuntimeId(),
runtimeTarget,
mantleStorageDirectory,
@@ -423,7 +421,6 @@ final class EngineRuntimeBuilder {
final GenerationKernelRegistry.RuntimeKernel runtimeKernel;
final SeedManager seedManager;
final TransitionGenerationPlan transitionPlan;
final PackRuntime packRuntime;
static int nextRuntimeId() {
return RUNTIME_IDS.incrementAndGet();
@@ -438,9 +435,8 @@ final class EngineRuntimeBuilder {
CompletableFuture<Long> hash32;
boolean ownsMantle;
RuntimeAssembly(Engine engine, int cacheId, EngineTarget target) {
RuntimeAssembly(int cacheId, EngineTarget target) {
this(
engine,
cacheId,
target,
null,
@@ -448,9 +444,8 @@ final class EngineRuntimeBuilder {
null);
}
RuntimeAssembly(Engine engine, int cacheId, EngineTarget target, Path mantleStorageDirectory) {
RuntimeAssembly(int cacheId, EngineTarget target, Path mantleStorageDirectory) {
this(
engine,
cacheId,
target,
mantleStorageDirectory,
@@ -459,7 +454,6 @@ final class EngineRuntimeBuilder {
}
RuntimeAssembly(
Engine engine,
int cacheId,
EngineTarget target,
Path mantleStorageDirectory,
@@ -475,7 +469,6 @@ final class EngineRuntimeBuilder {
this.seedManager = this.runtimeKernel.createSeedManager(target.getWorld().getRawWorldSeed());
this.kernelVersion = this.runtimeKernel.version();
this.transitionPlan = transitionPlan;
this.packRuntime = PackRuntime.forEngine(engine, target.getData());
}
GenerationRuntime freezeGeneration(BiomeMaxes biomeMaxes) {
@@ -492,7 +485,6 @@ final class EngineRuntimeBuilder {
seedManager,
transitionPlan,
complex,
packRuntime,
upperContext,
dimensionStackContext,
mode,
@@ -18,10 +18,6 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.structure.nativegen.NativeStructureVolumeIndex;
import art.arcane.iris.structure.placement.StructureReachability;
import art.arcane.iris.structure.placement.StructurePlacementScope;
import art.arcane.iris.structure.placement.IrisStructureLocator;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.EngineBackgroundTasks.BackgroundTaskDrain;
import art.arcane.iris.generation.runtime.EngineRuntimeBuilder.RuntimeAssembly;
@@ -184,7 +180,6 @@ final class EngineShutdownSequence {
engine.closed = true;
engine.lifecycleState = LifecycleState.CLOSED;
}
failure = appendFailure(failure, runCleanup(null, this::releaseStructureRegistries));
IrisLogging.debug("Engine Fully Shutdown!");
}
}
@@ -212,15 +207,6 @@ final class EngineShutdownSequence {
throw new IllegalStateException("Iris engine shutdown remains incomplete after cleanup failures.", failure);
}
/** Engine-keyed structure registries hold only live engines, so a closed engine removes itself from each one. */
private void releaseStructureRegistries() {
NativeStructureOwnershipStore.release(engine);
IrisStructureLocator.invalidate(engine);
StructurePlacementScope.invalidate(engine);
StructureReachability.invalidate(engine);
NativeStructureVolumeIndex.uninstall(engine);
}
void cleanupFailedConstruction(Throwable original) {
engine.getClosing().set(true);
engine.backgroundTasks.closeBackgroundTaskAdmission();
@@ -265,7 +251,6 @@ final class EngineShutdownSequence {
cleanupFailure = releaseGenerationAdmissions(cleanupFailure);
if (generationAdmissions.isEmpty()) {
engine.closed = true;
cleanupFailure = appendFailure(cleanupFailure, runCleanup(null, this::releaseStructureRegistries));
}
}
}
@@ -23,17 +23,29 @@ import art.arcane.iris.generation.runtime.IrisEngine.BiomeEnvironmentBinding;
import art.arcane.iris.generation.runtime.IrisEngine.GenerationRuntimeBinding;
import art.arcane.iris.generation.runtime.IrisEngine.GenerationRuntimeScope;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
/**
* Every per-thread engine binding (runtime assembly, biome environment, generation runtime scope) in one frame.
* The engine getters run on generation hot paths, where a ThreadLocal lookup probes long collision chains in the
* workers' crowded thread-local maps. Frames therefore live in thread slots the engine owns, so a closed engine
* leaves nothing behind on its pooled workers.
* workers' crowded thread-local maps. Frames therefore live in a table indexed by thread id and owned by their
* thread; a frame whose slot is taken by another thread falls back to a ThreadLocal.
*/
final class EngineThreadState {
private final ThreadSlots<Frame> frames = ThreadSlots.bindings();
private static final int SLOTS = 256;
private final AtomicReferenceArray<Frame> slots = new AtomicReferenceArray<>(SLOTS);
private final ThreadLocal<Frame> overflow = new ThreadLocal<>();
private final AtomicInteger overflowFrames = new AtomicInteger();
Frame current() {
return frames.get();
Thread thread = Thread.currentThread();
Frame frame = slots.getPlain(slot(thread));
if (frame != null && frame.owner == thread) {
return frame;
}
return overflowFrames.get() == 0 ? null : overflow.get();
}
GenerationRuntimeBinding binding() {
@@ -110,8 +122,13 @@ final class EngineThreadState {
if (frame != null) {
return frame;
}
frame = new Frame();
frames.set(frame);
Thread thread = Thread.currentThread();
frame = new Frame(thread);
if (!slots.compareAndSet(slot(thread), null, frame)) {
frame.overflow = true;
overflow.set(frame);
overflowFrames.incrementAndGet();
}
return frame;
}
@@ -119,12 +136,27 @@ final class EngineThreadState {
if (frame.assembly != null || frame.environment != null || frame.binding != null) {
return;
}
frames.remove();
if (frame.overflow) {
overflow.remove();
overflowFrames.decrementAndGet();
return;
}
slots.compareAndSet(slot(frame.owner), frame, null);
}
private static int slot(Thread thread) {
return (int) thread.threadId() & (SLOTS - 1);
}
static final class Frame {
private final Thread owner;
private boolean overflow;
RuntimeAssembly assembly;
BiomeEnvironmentBinding environment;
GenerationRuntimeBinding binding;
private Frame(Thread owner) {
this.owner = owner;
}
}
}
@@ -48,7 +48,6 @@ public final class GenerationCacheWarmer {
public static void warm(Engine engine) {
long start = M.ms();
IrisData data = engine.getData();
PackRuntime runtime = PackRuntime.of(engine, data);
RNG root = new RNG(engine.getSeedManager().getComponent() + 7777L);
int[] counter = {0};
List<ProceduralWarmTask> proceduralTasks = new ArrayList<>();
@@ -56,28 +55,28 @@ public final class GenerationCacheWarmer {
KList<IrisBiome> biomes = engine.getAllBiomes();
biomes.sort(Comparator.comparing(IrisBiome::getLoadKey));
for (IrisBiome biome : biomes) {
warmPlacements(biome.getObjects(), root, counter, runtime);
warmDecorators(biome.getDecorators(), engine.getSeedManager().getComponent(), counter, runtime);
warmOres(biome.getOres(), engine.getSeedManager().getTerrain(), counter, runtime);
warmPlacements(biome.getObjects(), root, counter, data, engine);
warmDecorators(biome.getDecorators(), engine.getSeedManager().getComponent(), counter, data);
warmOres(biome.getOres(), engine.getSeedManager().getTerrain(), counter, data);
collectProcedural(biome.getProceduralObjects(), root, counter, proceduralTasks);
}
KList<IrisRegion> regions = engine.getDimension().getAllRegions(engine);
regions.sort(Comparator.comparing(IrisRegion::getLoadKey));
for (IrisRegion region : regions) {
warmPlacements(region.getObjects(), root, counter, runtime);
warmOres(region.getOres(), engine.getSeedManager().getTerrain(), counter, runtime);
warmPlacements(region.getObjects(), root, counter, data, engine);
warmOres(region.getOres(), engine.getSeedManager().getTerrain(), counter, data);
collectProcedural(region.getProceduralObjects(), root, counter, proceduralTasks);
}
warmOres(engine.getDimension().getOres(), engine.getSeedManager().getTerrain(), counter, runtime);
warmOres(engine.getDimension().getOres(), engine.getSeedManager().getTerrain(), counter, data);
warmProcedural(proceduralTasks, data);
IrisLogging.debug("[IrisEngine timing] cache warm " + counter[0] + " configs=" + (M.ms() - start) + "ms");
}
private static void warmPlacements(KList<IrisObjectPlacement> placements, RNG root, int[] counter,
PackRuntime runtime) {
IrisData data, Engine engine) {
if (placements == null) {
return;
}
@@ -86,12 +85,12 @@ public final class GenerationCacheWarmer {
continue;
}
RNG rng = root.nextParallelRNG(counter[0]++);
placement.getSurfaceWarp(rng, runtime);
placement.getDensity(rng, 0, 0, runtime);
placement.getSurfaceWarp(rng, data, engine);
placement.getDensity(rng, 0, 0, data);
}
}
private static void warmDecorators(KList<IrisDecorator> decorators, long componentSeed, int[] counter, PackRuntime runtime) {
private static void warmDecorators(KList<IrisDecorator> decorators, long componentSeed, int[] counter, IrisData data) {
if (decorators == null) {
return;
}
@@ -101,13 +100,13 @@ public final class GenerationCacheWarmer {
}
counter[0]++;
RNG rng = new RNG(IrisEngineDecorator.seedForPart(componentSeed, decorator.getPartOf()));
decorator.getHeightGenerator(rng, runtime);
decorator.getGenerator(rng, runtime);
decorator.getVarianceGenerator(rng, runtime);
decorator.getHeightGenerator(rng, data);
decorator.getGenerator(rng, data);
decorator.getVarianceGenerator(rng, data);
}
}
private static void warmOres(KList<IrisOreGenerator> ores, long terrainSeed, int[] counter, PackRuntime runtime) {
private static void warmOres(KList<IrisOreGenerator> ores, long terrainSeed, int[] counter, IrisData data) {
if (ores == null) {
return;
}
@@ -116,7 +115,7 @@ public final class GenerationCacheWarmer {
continue;
}
counter[0]++;
ore.warm(new RNG(terrainSeed), runtime);
ore.warm(new RNG(terrainSeed), data);
}
}
@@ -38,7 +38,6 @@ record GenerationRuntime(
SeedManager seedManager,
TransitionGenerationPlan transitionPlan,
IrisComplex complex,
PackRuntime packRuntime,
UpperDimensionContext upperContext,
DimensionStackContext dimensionStackContext,
EngineMode mode,
@@ -58,7 +57,6 @@ record GenerationRuntime(
throw new IllegalArgumentException("Generation kernel version does not match its executable runtime.");
}
Objects.requireNonNull(complex, "generation complex");
Objects.requireNonNull(packRuntime, "generation pack runtime");
Objects.requireNonNull(mode, "generation mode");
Objects.requireNonNull(mantle, "generation mantle");
mantleStorageDirectory = IrisEngineMantle.normalizeStorageDirectory(mantleStorageDirectory);
@@ -72,7 +70,6 @@ record GenerationRuntime(
GenerationRuntime withComplex(
int nextCacheId,
IrisComplex nextComplex,
PackRuntime nextPackRuntime,
UpperDimensionContext nextUpperContext,
DimensionStackContext nextDimensionStackContext,
BiomeMaxes nextBiomeMaxes
@@ -87,7 +84,6 @@ record GenerationRuntime(
seedManager,
transitionPlan,
nextComplex,
nextPackRuntime,
nextUpperContext,
nextDimensionStackContext,
mode,
@@ -154,16 +154,10 @@ public class IrisComplex implements DataProvider {
InferredType.SEA,
InferredType.SHORE
};
/**
* The biome stream of a sea or shore list a region leaves empty. It answers null everywhere, which tells the
* surface resolution to keep the column's own biome instead of converting it.
*/
static final ProceduralStream<IrisBiome> NO_BIOMES = ProceduralStream.of((x, z) -> null,
Interpolated.of(value -> 0D, value -> null));
@Getter(AccessLevel.NONE)
private final transient ThreadSlots<GridBoundsCache> gridBoundsCache = new ThreadSlots<>(GridBoundsCache::new);
private final transient ThreadLocal<GridBoundsCache> gridBoundsCache = ThreadLocal.withInitial(GridBoundsCache::new);
@Getter(AccessLevel.NONE)
private final transient ThreadSlots<EffectiveWater.Chunks> effectiveChunks = new ThreadSlots<>(EffectiveWater.Chunks::new);
private final transient ThreadLocal<EffectiveWater.Chunks> effectiveChunks = ThreadLocal.withInitial(EffectiveWater.Chunks::new);
@Getter(AccessLevel.NONE)
private final int biomeBoundsSamplingStep;
private transient volatile SharedCornerBounds sharedCornerBounds;
@@ -206,14 +200,11 @@ public class IrisComplex implements DataProvider {
private RNG rng;
private double fluidHeight;
private IrisData data;
private final transient PackRuntime packRuntime;
private Map<IrisInterpolator, Set<IrisGenerator>> generators;
private ProceduralStream<IrisRegion> regionStream;
private ProceduralStream<Double> regionStyleStream;
private ProceduralStream<Double> regionIdentityStream;
private ProceduralStream<InferredType> bridgeStream;
@Getter(AccessLevel.NONE)
private ProceduralStream<InferredType> baseTypeStream;
private ProceduralStream<IrisBiome> landBiomeStream;
private ProceduralStream<IrisBiome> caveBiomeStream;
private ProceduralStream<IrisBiome> seaBiomeStream;
@@ -334,7 +325,6 @@ public class IrisComplex implements DataProvider {
this.rng = new RNG(engine.getSeedManager().getComplex());
childStyleSeed = IrisBiome.childStyleSeed(rng, 123);
this.data = engine.getData();
this.packRuntime = PackRuntime.of(engine, data);
imageMapRuntime = IrisImageMapRuntime.compile(engine);
double height = engine.getMaxHeight();
fluidHeight = engine.getDimension().getFluidHeight();
@@ -422,20 +412,20 @@ public class IrisComplex implements DataProvider {
double value = 0D;
for (IrisShapedGeneratorStyle style : overlayNoise) {
value += style.get(rng, packRuntime, x, z);
value += style.get(rng, getData(), x, z);
}
return value;
});
bakeCache = new ChunkBakeCache(new BakeSource(), detached ? ChunkBakeCache.MINIMUM_CAPACITY
: ChunkBakeCache.capacityFor(Runtime.getRuntime().maxMemory()));
rockSource = engine.getDimension().getRockPalette().getLayerGenerator(rng.nextParallelRNG(45), packRuntime).stream()
rockSource = engine.getDimension().getRockPalette().getLayerGenerator(rng.nextParallelRNG(45), data).stream()
.select(engine.getDimension().getRockPalette().getBlockData(data));
rockStream = new BakedStream<>(bakeCache, BakePlane.ROCK, rockSource);
fluidSource = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), packRuntime).stream()
fluidSource = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), data).stream()
.select(engine.getDimension().getFluidPalette().getBlockData(data));
fluidStream = new BakedStream<>(bakeCache, BakePlane.FLUID, fluidSource);
regionStyleStream = engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883), packRuntime).stream()
regionStyleStream = engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883), getData()).stream()
.zoom(engine.getDimension().getRegionZoom());
regionIdentityStream = regionStyleStream.fit(Integer.MIN_VALUE, Integer.MAX_VALUE);
regionSource = focusedRegions != null ? focusedRegions
@@ -461,17 +451,11 @@ public class IrisComplex implements DataProvider {
.convertAware2D(ProceduralStream::get);
inferredStreams.put(InferredType.SHORE, shoreBiomeStream);
bridgeStream = focusedBiomes != null ? focusedBiomes.convert(IrisBiome::getInferredType) :
ContinentGenerator.create(engine.getDimension(), rng, packRuntime).stream()
ContinentGenerator.create(engine.getDimension(), rng, getData()).stream()
.convert((v) -> v >= engine.getDimension().getLandChance() ? InferredType.SEA : InferredType.LAND);
// A region without sea biomes picks its continental sea from its land biomes.
baseTypeStream = focusedBiomes != null || !lacks(inferredBiomeStreams, InferredType.SEA) ? bridgeStream
: ProceduralStream.of(
(x, z) -> baseType(inferredBiomeStreams, contextRegionStream.get(x, z), bridgeStream.get(x, z)),
(x, y, z) -> baseType(inferredBiomeStreams, contextRegionStream.get(x, z), bridgeStream.get(x, y, z)),
Interpolated.of(value -> 0D, value -> null));
ProceduralStream<IrisBiome> proceduralBaseBiomeStream = focusedBiomes != null ? focusedBiomes
: ProceduralStream.of(this::proceduralBaseBiome,
(x, y, z) -> implode(inferredByType.get(baseTypeStream.get(x, y, z)).get(x, z), x, z),
(x, y, z) -> implode(inferredByType.get(bridgeStream.get(x, y, z)).get(x, z), x, z),
Interpolated.of(value -> 0D, value -> null));
baseBiomeSource = focusedBiomes != null || !imageMapRuntime.has(IrisImageMapApplication.BIOME)
? proceduralBaseBiomeStream : ProceduralStream.of((x, z) -> {
@@ -499,7 +483,7 @@ public class IrisComplex implements DataProvider {
(x, z) -> baseTerrainHeightStream.getDouble(x, z),
this::sampleTerrain3DBiome),
new Terrain3DRuntime.Options(engine.getSeedManager().getTerrain(), engine.getHeight(),
fluidHeight, packRuntime, terrain3DEnabled, TERRAIN_COLUMN_CACHE_SIZE));
fluidHeight, data, terrain3DEnabled, TERRAIN_COLUMN_CACHE_SIZE));
unblendedNaturalHeightStream = terrain3DEnabled
? ProceduralStream.ofDouble(this::sampleTerrain3DHeight)
: baseTerrainHeightStream;
@@ -1072,7 +1056,7 @@ public class IrisComplex implements DataProvider {
synchronized (this) {
program = terrainProgram;
if (program == null) {
program = TerrainProgram.compile(packRuntime, frozenGenerators, terrainEngine.getSeedManager().getHeight() + 239945);
program = TerrainProgram.compile(frozenGenerators, terrainEngine.getSeedManager().getHeight() + 239945);
terrainProgram = program;
}
}
@@ -1081,7 +1065,7 @@ public class IrisComplex implements DataProvider {
}
private IrisBiome proceduralBaseBiome(double x, double z) {
return implode(inferredByType.get(baseTypeStream.get(x, z)).get(x, z), x, z);
return implode(inferredByType.get(bridgeStream.get(x, z)).get(x, z), x, z);
}
private final class BakeSource implements PlaneSource {
@@ -1182,73 +1166,29 @@ public class IrisComplex implements DataProvider {
InferredType inferredType,
IrisBiome emptyBiome
) {
ProceduralStream<Double> noise = biomePickNoiseStream(engine.getDimension(), region, inferredType);
KList<IrisBiome> biomes = loadInferredBiomes(biomeKeys(region, inferredType), inferredType);
return switch (inferredType) {
case CAVE -> new RarityStream<>(noise, biomes).onNull(emptyBiome);
case LAND -> new RarityStream<>(noise, requireLandBiomes(region, biomes));
case SEA, SHORE -> biomes.isEmpty() ? NO_BIOMES : new RarityStream<>(noise, biomes);
};
}
/**
* Every region needs a land biome: the surface falls back to land wherever it leaves sea or shore, and a region
* without sea biomes picks its continental sea from land too.
*/
static KList<IrisBiome> requireLandBiomes(IrisRegion region, KList<IrisBiome> landBiomes) {
if (!landBiomes.isEmpty()) {
return landBiomes;
}
String regionKey = region.getLoadKey() == null || region.getLoadKey().isBlank() ? "<unkeyed>" : region.getLoadKey();
throw new IllegalStateException(region.getLandBiomes().isEmpty()
? "Region '" + regionKey + "' has no landBiomes; every region needs at least one land biome."
: "Region '" + regionKey + "' has no landBiomes this Minecraft version can generate; every listed land biome is excluded.");
}
/** Whether any prepared region left the given biome list empty. */
static boolean lacks(Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> streams, InferredType inferredType) {
for (Map<InferredType, ProceduralStream<IrisBiome>> regionStreams : streams.values()) {
if (regionStreams.get(inferredType) == NO_BIOMES) {
return true;
}
}
return false;
}
/** The biome list a spot's base biome comes from: the continent's choice, or land where the region has no sea. */
static InferredType baseType(
Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> streams,
IrisRegion region,
InferredType continent
) {
return continent == InferredType.SEA && preparedInferredBiomeStream(streams, region, InferredType.SEA) == NO_BIOMES
? InferredType.LAND
: continent;
}
/** The biome list the given region picks this spot's base biome from. */
public InferredType baseTypeIn(IrisRegion region, double x, double z) {
return baseTypeStream == bridgeStream ? bridgeStream.get(x, z) : baseType(inferredBiomeStreams, region, bridgeStream.get(x, z));
ProceduralStream<IrisBiome> picked = new RarityStream<>(biomePickNoiseStream(engine.getDimension(), region, inferredType),
loadInferredBiomes(biomeKeys(region, inferredType), inferredType));
return inferredType == InferredType.CAVE ? picked.onNull(emptyBiome) : picked;
}
private ProceduralStream<Double> biomePickNoiseStream(IrisDimension dimension, IrisRegion region, InferredType inferredType) {
return switch (inferredType) {
case CAVE -> dimension.getCaveBiomeStyle()
.create(rng.nextParallelRNG(InferredType.CAVE.ordinal()), packRuntime).stream()
.create(rng.nextParallelRNG(InferredType.CAVE.ordinal()), getData()).stream()
.zoom(dimension.getBiomeZoom())
.zoom(region.getCaveBiomeZoom());
case LAND -> dimension.getLandBiomeStyle()
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), packRuntime).stream()
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), getData()).stream()
.zoom(dimension.getBiomeZoom())
.zoom(dimension.getLandZoom())
.zoom(region.getLandBiomeZoom());
case SEA -> dimension.getSeaBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), packRuntime).stream()
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), getData()).stream()
.zoom(dimension.getBiomeZoom())
.zoom(dimension.getSeaZoom())
.zoom(region.getSeaBiomeZoom());
case SHORE -> dimension.getShoreBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), packRuntime).stream()
.create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), getData()).stream()
.zoom(dimension.getBiomeZoom())
.zoom(region.getShoreBiomeZoom());
};
@@ -1310,7 +1250,7 @@ public class IrisComplex implements DataProvider {
if (focusBiome != null) {
return new BiomePick(focusBiome, focusBiome.getInferredType());
}
InferredType type = baseTypeIn(region, x, z);
InferredType type = bridgeStream.get(x, z);
return new BiomePick(implode(createInferredBiomeStream(region, type).get(x, z), x, z), type);
}
@@ -1368,7 +1308,7 @@ public class IrisComplex implements DataProvider {
configurationName + " fluidPalette may contain only fluid blocks");
}
}
return palette.getLayerGenerator(fluidRng, packRuntime).stream().select(blocks);
return palette.getLayerGenerator(fluidRng, data).stream().select(blocks);
}
public NativeBlockState resolveSeaFluid(double x, double z) {
@@ -1982,7 +1922,7 @@ public class IrisComplex implements DataProvider {
if (height >= fluidHeight - 1 && !biome.isShore()) {
if (!aboveShoreBand(height, region, x, z, fluidHeight, shoreSlopes)) {
return convertedOrKept(shoreBiomes.get(x, z), biome);
return shoreBiomes.get(x, z);
}
if (!biome.isLand()) {
return landBiomes.get(x, z);
@@ -1992,21 +1932,16 @@ public class IrisComplex implements DataProvider {
}
if (height < fluidHeight && !biome.isAquatic()) {
return convertedOrKept(seaBiomes.get(x, z), biome);
return seaBiomes.get(x, z);
}
if (height == fluidHeight && !biome.isShore()) {
return convertedOrKept(shoreBiomes.get(x, z), biome);
return shoreBiomes.get(x, z);
}
return biome;
}
// A null conversion comes from NO_BIOMES: the region lists no biomes of that type, so the column keeps its own.
private static IrisBiome convertedOrKept(IrisBiome converted, IrisBiome biome) {
return converted == null ? biome : converted;
}
private double interpolateGenerators(Engine engine, IrisInterpolator interpolator, int interpolatorIndex, IrisGenerator[] generators, double x, double z, long seed) {
if (generators.length == 0) {
return 0;
@@ -2026,7 +1961,7 @@ public class IrisComplex implements DataProvider {
}
if (program == null || program.heightSeed() != heightSeed || group >= program.groups()
|| program.groupSize(group) != generators.length || generators != frozenGenerators[group]) {
return averageGeneratorHeights(packRuntime, generators, low, high, x, z, heightSeed);
return averageGeneratorHeights(generators, low, high, x, z, heightSeed);
}
return program.average(group, BATCH_SCRATCH.get(), low, high, x, z);
}
@@ -2193,7 +2128,7 @@ public class IrisComplex implements DataProvider {
IrisBiome biome = focusedBiomeAt(x, z);
for (GeneratorGroup group : biomeBuffetGenerators.get(biome)) {
NoiseBounds bounds = generatorBounds.get(group.interpolator()).get(biome).noiseBounds;
h += averageGeneratorHeights(packRuntime, group.generators(), bounds.min(), bounds.max(), x, z, seed + 239945);
h += averageGeneratorHeights(group.generators(), bounds.min(), bounds.max(), x, z, seed + 239945);
}
return h;
}
@@ -2472,7 +2407,6 @@ public class IrisComplex implements DataProvider {
}
static double averageGeneratorHeights(
PackRuntime runtime,
IrisGenerator[] generators,
double low,
double high,
@@ -2499,7 +2433,7 @@ public class IrisComplex implements DataProvider {
GenerationCounter.GENERATOR_EVALUATIONS.add(generators.length);
}
for (IrisGenerator generator : generators) {
double noise = generator.getHeight(runtime, x, z, seed);
double noise = generator.getHeight(x, z, seed);
if (!Double.isFinite(noise)) {
throw new IllegalStateException("Terrain generator noise was not finite at " + x + "," + z
+ " (generator=" + generator.getLoadKey() + ", noise=" + noise
@@ -2593,13 +2527,13 @@ public class IrisComplex implements DataProvider {
}
private IrisBiome pickChild(IrisBiome parent, double x, double z) {
CNG childCell = parent.getChildrenGenerator(packRuntime, childStyleSeed, parent.getChildShrinkFactor());
CNG childCell = parent.getChildrenGenerator(childStyleSeed, parent.getChildShrinkFactor());
return resolveChildSelectionPlan(parent).select(childCell, x, z).withInferredType(parent.getInferredType());
}
private List<IrisBiome> childLineage(IrisBiome biome, int x, int z) {
IrisBiome[] rootFirst = new IrisBiome[IrisBiome.CHILD_HOPS + 1];
IrisBiome current = inferredByType.get(baseTypeStream.get(x, z)).get(x, z);
IrisBiome current = inferredByType.get(bridgeStream.get(x, z)).get(x, z);
rootFirst[0] = current;
int size = 1;
for (int hop = 0; hop < IrisBiome.CHILD_HOPS && !current.getChildren().isEmpty(); hop++) {
@@ -2948,7 +2882,7 @@ public class IrisComplex implements DataProvider {
if (constant != null) {
return constant;
}
InferredType type = pick != null ? pick.type() : complex.baseTypeIn(region, x, z);
InferredType type = pick != null ? pick.type() : complex.bridgeStream.get(x, z);
constant = constants == null ? null : constants.typed(type, group);
if (constant != null) {
return constant;
@@ -1424,17 +1424,6 @@ public class IrisEngine implements Engine {
return complexIn(threadState.current());
}
@Override
public PackRuntime getPackRuntime() {
EngineThreadState.Frame frame = threadState.current();
RuntimeAssembly assembly = frame == null ? null : frame.assembly;
if (assembly != null) {
return assembly.packRuntime;
}
GenerationRuntime current = selectedGenerationRuntime(frame);
return current == null ? null : current.packRuntime();
}
private IrisComplex complexIn(EngineThreadState.Frame frame) {
RuntimeAssembly assembly = frame == null ? null : frame.assembly;
if (assembly != null && assembly.complex != null) {
@@ -1,258 +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.generation.runtime;
import art.arcane.iris.generation.biome.BiomeRuntime;
import art.arcane.iris.generation.biome.FloatingChildRuntime;
import art.arcane.iris.generation.biome.FloatingIslandMemo;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.biome.IrisBiomePaletteLayer;
import art.arcane.iris.generation.biome.IrisFloatingChildBiomes;
import art.arcane.iris.generation.biome.PaletteLayerRuntime;
import art.arcane.iris.generation.decoration.DecoratorRuntime;
import art.arcane.iris.generation.decoration.DepositRuntime;
import art.arcane.iris.generation.decoration.IrisDecorator;
import art.arcane.iris.generation.decoration.IrisDepositGenerator;
import art.arcane.iris.generation.decoration.IrisOreBands;
import art.arcane.iris.generation.decoration.IrisOreGenerator;
import art.arcane.iris.generation.decoration.OreBandsRuntime;
import art.arcane.iris.generation.noise.ExpressionRuntime;
import art.arcane.iris.generation.noise.GeneratorRuntime;
import art.arcane.iris.generation.noise.IrisExpression;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.structure.graph.StructureGraphCompilation;
import art.arcane.iris.structure.object.IrisObjectPlacement;
import art.arcane.iris.world.entity.IrisEffect;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.scheduling.ChronoLatch;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* The runtime objects one owner derives from pack objects: seeded generators, samplers and profiles. Pack objects are
* read-only configuration, so everything built for a seed, an engine or a world lives here and dies with the owner.
* An engine owns one per generation runtime; engine-less tools use the scope their {@link IrisData} owns.
*/
public final class PackRuntime {
private static final int STYLE_SEED_CAPACITY = 8;
private static final int NOISE_LAYER_SEED_CAPACITY = 32;
private static final int MATERIAL_PALETTE_SEED_CAPACITY = 32;
private static final int CARVING_CHILD_SEED_CAPACITY = 8;
private static final int ORE_CHANCE_SEED_CAPACITY = 32;
private static final int ORE_BANDS_SEED_CAPACITY = 8;
private static final int SURFACE_WARP_SEED_CAPACITY = 8;
private final Engine engine;
private final IrisData data;
private final RuntimeTable<IrisData, PackRuntime> foreignDataScopes;
private final RuntimeTable<IrisGeneratorStyle, SeedTable<CNG>> styleGenerators = new RuntimeTable<>(
style -> new SeedTable<>(STYLE_SEED_CAPACITY, seed -> style.createNoCache(new RNG(seed), this)));
private final RuntimeTable<IrisNoiseGenerator, SeedTable<CNG>> noiseLayerGenerators = new RuntimeTable<>(
layer -> new SeedTable<>(NOISE_LAYER_SEED_CAPACITY, seed -> layer.buildGenerator(seed, this)));
private final RuntimeTable<IrisMaterialPalette, SeedTable<CNG>> materialPaletteGenerators = new RuntimeTable<>(
palette -> new SeedTable<>(MATERIAL_PALETTE_SEED_CAPACITY, seed -> palette.createLayerGenerator(seed, this)));
private final RuntimeTable<IrisDimensionCarvingEntry, SeedTable<CNG>> carvingChildGenerators = new RuntimeTable<>(
entry -> new SeedTable<>(CARVING_CHILD_SEED_CAPACITY, seed -> entry.createChildrenGenerator(seed, this)));
private final RuntimeTable<IrisOreGenerator, SeedTable<IrisOreGenerator.OreChance>> oreChances = new RuntimeTable<>(
ore -> new SeedTable<>(ORE_CHANCE_SEED_CAPACITY, seed -> ore.createChance(seed, this)));
private final RuntimeTable<IrisOreBands, SeedTable<OreBandsRuntime>> oreBands = new RuntimeTable<>(
bands -> new SeedTable<>(ORE_BANDS_SEED_CAPACITY, seed -> new OreBandsRuntime(bands, seed, this)));
private final RuntimeTable<IrisObjectPlacement, SeedTable<CNG>> surfaceWarps = new RuntimeTable<>(
placement -> new SeedTable<>(SURFACE_WARP_SEED_CAPACITY, seed -> placement.createSurfaceWarp(seed, this)));
private final ConcurrentMap<String, StructureGraphCompilation> structureGraphs = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Boolean> structureRuntimeOutputs = new ConcurrentHashMap<>();
private final ThreadSlots<IrisDimensionCarvingResolver.State> carvingResolverStates =
new ThreadSlots<>(IrisDimensionCarvingResolver.State::new);
private final RuntimeTable<IrisEffect, ChronoLatch> effectLatches =
new RuntimeTable<>(effect -> new ChronoLatch(effect.getInterval()));
private final RuntimeTable<IrisDecorator, DecoratorRuntime> decorators =
new RuntimeTable<>(decorator -> new DecoratorRuntime(decorator, this));
private final RuntimeTable<IrisDepositGenerator, DepositRuntime> deposits =
new RuntimeTable<>(deposit -> new DepositRuntime(deposit, this));
private final RuntimeTable<IrisGenerator, GeneratorRuntime> generators = new RuntimeTable<>(GeneratorRuntime::new);
private final RuntimeTable<IrisExpression, ExpressionRuntime> expressions =
new RuntimeTable<>(expression -> new ExpressionRuntime(expression, this));
private final RuntimeTable<IrisBiome, BiomeRuntime> biomes = new RuntimeTable<>(biome -> new BiomeRuntime(biome, this));
private final RuntimeTable<IrisBiomePaletteLayer, PaletteLayerRuntime> paletteLayers =
new RuntimeTable<>(layer -> new PaletteLayerRuntime(layer, this));
private final RuntimeTable<IrisFloatingChildBiomes, FloatingChildRuntime> floatingChildren =
new RuntimeTable<>(entry -> new FloatingChildRuntime(entry, this));
private final ThreadSlots<FloatingIslandMemo> floatingIslandMemos = new ThreadSlots<>(FloatingIslandMemo::new);
private PackRuntime(Engine engine, IrisData data) {
this.engine = engine;
this.data = data;
this.foreignDataScopes = engine == null ? null : new RuntimeTable<>(foreign -> new PackRuntime(engine, foreign));
}
/** The scope an engine owns for its pack; the engine creates it with each generation runtime. */
public static PackRuntime forEngine(Engine engine, IrisData data) {
return new PackRuntime(Objects.requireNonNull(engine, "engine"), data);
}
/** A scope for tools without an engine. A null pack is allowed for content that never loads other files. */
public static PackRuntime standalone(IrisData data) {
return new PackRuntime(null, data);
}
/**
* The runtime scope for work on this pack: the engine's while one is generating, otherwise the scope the pack
* data owns. Resolve it once per chunk or column and pass it down.
*/
public static PackRuntime of(Engine engine, IrisData data) {
PackRuntime engineRuntime = engine == null ? null : engine.getPackRuntime();
if (engineRuntime == null) {
return forPack(data);
}
return engineRuntime.scopeFor(data);
}
/** The scope a pack keeps for content baked from its own files alone, such as procedural object variants. */
public static PackRuntime forPack(IrisData data) {
return data == null ? standalone(null) : data.standalonePackRuntime();
}
/** The engine's scope for its own pack. */
public static PackRuntime of(Engine engine) {
return of(engine, engine.getData());
}
/** The owning engine, or null for an engine-less scope. */
public Engine engine() {
return engine;
}
public IrisData data() {
return data;
}
/**
* The scope this owner keeps for another pack, such as a stacked dimension's. Pack objects resolve expressions
* and images through their own data, so runtime objects of a foreign pack must be built against it.
*/
public PackRuntime scopeFor(IrisData packData) {
if (packData == null || packData == data || foreignDataScopes == null) {
return this;
}
return foreignDataScopes.get(packData);
}
/** Styles are shared configuration that each caller seeds itself, so a style keeps one generator per seed. */
public CNG styleGenerator(IrisGeneratorStyle style, long seed) {
return styleGenerators.get(style).get(seed);
}
/** Noise layers are seeded from the generator that reads them, so a layer keeps one generator per seed. */
public CNG noiseLayerGenerator(IrisNoiseGenerator layer, long seed) {
return noiseLayerGenerators.get(layer).get(seed);
}
/** Material palettes are seeded by the stream or decorator that reads them, so a palette keeps one generator per seed. */
public CNG materialPaletteGenerator(IrisMaterialPalette palette, long seed) {
return materialPaletteGenerators.get(palette).get(seed);
}
/** Carving entries pick their children from the carve seed, so an entry keeps one child generator per seed. */
public CNG carvingChildGenerator(IrisDimensionCarvingEntry entry, long seed) {
return carvingChildGenerators.get(entry).get(seed);
}
/** Ores are seeded by the stage that places them, so an ore keeps one chance field per seed. */
public IrisOreGenerator.OreChance oreChance(IrisOreGenerator ore, long seed) {
return oreChances.get(ore).get(seed);
}
/** An ore list's chance fields for one seed, resolved together so painting a column holds them directly. */
public OreBandsRuntime oreBands(IrisOreBands bands, long seed) {
return oreBands.get(bands).get(seed);
}
/** Object placements warp by the engine's component seed, so a placement keeps one warp generator per seed. */
public CNG surfaceWarp(IrisObjectPlacement placement, long seed) {
return surfaceWarps.get(placement).get(seed);
}
/** Structure graphs compile from the pack's own files, so the pack scope keeps one compilation per structure key. */
public ConcurrentMap<String, StructureGraphCompilation> structureGraphs() {
return structureGraphs;
}
/** Whether each structure's sampled assemblies always place output, keyed like {@link #structureGraphs()}. */
public ConcurrentMap<String, Boolean> structureRuntimeOutputs() {
return structureRuntimeOutputs;
}
/** Hotload drops the compiled structure graphs of a pack whose files changed. */
public void forgetStructureGraphs() {
structureGraphs.clear();
structureRuntimeOutputs.clear();
}
/** Carving lookups that are not handed a resolver state memoize their roots in the calling thread's state. */
public IrisDimensionCarvingResolver.State carvingResolverState() {
return carvingResolverStates.get();
}
/** Every player and entity of this owner shares one interval latch per effect. */
public ChronoLatch effectLatch(IrisEffect effect) {
return effectLatches.get(effect);
}
public DecoratorRuntime decorator(IrisDecorator decorator) {
return decorators.get(decorator);
}
public DepositRuntime deposit(IrisDepositGenerator deposit) {
return deposits.get(deposit);
}
public GeneratorRuntime generator(IrisGenerator generator) {
return generators.get(generator);
}
public ExpressionRuntime expression(IrisExpression expression) {
return expressions.get(expression);
}
public BiomeRuntime biome(IrisBiome biome) {
return biomes.get(biome);
}
public PaletteLayerRuntime paletteLayer(IrisBiomePaletteLayer layer) {
return paletteLayers.get(layer);
}
public FloatingChildRuntime floatingChild(IrisFloatingChildBiomes entry) {
return floatingChildren.get(entry);
}
/** The calling worker's floating island samples for its current chunk. */
public FloatingIslandMemo floatingIslandMemo() {
return floatingIslandMemos.get();
}
}
@@ -1,68 +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.generation.runtime;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* Runtime objects of one kind keyed by the identity of the pack object they were built from. Pack types compare by
* value, so two equal configurations still get their own runtime object. A builder may resolve other runtime objects
* from the same table, so entries are built outside the map and the first one published wins.
*/
public final class RuntimeTable<C, R> {
private final ConcurrentHashMap<Identity, R> entries = new ConcurrentHashMap<>();
private final Function<C, R> builder;
public RuntimeTable(Function<C, R> builder) {
this.builder = Objects.requireNonNull(builder, "runtime builder");
}
public R get(C config) {
Identity key = new Identity(Objects.requireNonNull(config, "pack object"));
R existing = entries.get(key);
if (existing != null) {
return existing;
}
R built = Objects.requireNonNull(builder.apply(config), "runtime object");
R raced = entries.putIfAbsent(key, built);
return raced == null ? built : raced;
}
private static final class Identity {
private final Object referent;
private final int hash;
private Identity(Object referent) {
this.referent = referent;
this.hash = System.identityHashCode(referent);
}
@Override
public boolean equals(Object other) {
return other instanceof Identity identity && identity.referent == referent;
}
@Override
public int hashCode() {
return hash;
}
}
}
@@ -1,99 +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.generation.runtime;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.LongFunction;
/**
* The values one runtime object builds per seed, for pack objects that callers sample with seeds they derive
* themselves. Bounded by least-recent use; an evicted value is rebuilt from the same seed, so eviction never changes
* output. Recently used values are kept aside in seed-indexed slots because callers usually ask for the same few
* seeds many times in a row.
*/
public final class SeedTable<T> {
private static final int SINGLE_RECENT_SLOT = 1;
private final int capacity;
private final LongFunction<T> builder;
private final LinkedHashMap<Long, T> entries;
private final AtomicReferenceArray<Recent<T>> recent;
private final int recentMask;
public SeedTable(int capacity, LongFunction<T> builder) {
this(capacity, SINGLE_RECENT_SLOT, builder);
}
/** @param recentSlots a power of two: how many seeds stay on the lock-free path at once */
public SeedTable(int capacity, int recentSlots, LongFunction<T> builder) {
if (capacity < 1) {
throw new IllegalArgumentException("Seed table capacity must be positive.");
}
if (recentSlots < 1 || Integer.bitCount(recentSlots) != 1) {
throw new IllegalArgumentException("Recent seed slots must be a positive power of two.");
}
this.capacity = capacity;
this.builder = Objects.requireNonNull(builder, "seed builder");
this.entries = new LinkedHashMap<>(capacity * 2, 0.75F, true);
this.recent = new AtomicReferenceArray<>(recentSlots);
this.recentMask = recentSlots - 1;
}
public T get(long seed) {
int slot = (int) seed & recentMask;
Recent<T> last = recent.getAcquire(slot);
if (last != null && last.seed == seed) {
return last.value;
}
T value = stored(seed);
if (value == null) {
value = publish(seed, Objects.requireNonNull(builder.apply(seed), "seeded runtime value"));
}
recent.setRelease(slot, new Recent<>(seed, value));
return value;
}
private T stored(long seed) {
synchronized (entries) {
return entries.get(seed);
}
}
private T publish(long seed, T built) {
synchronized (entries) {
T raced = entries.putIfAbsent(seed, built);
if (raced != null) {
return raced;
}
evictBeyondCapacity();
return built;
}
}
private void evictBeyondCapacity() {
while (entries.size() > capacity) {
entries.sequencedKeySet().removeFirst();
}
}
private record Recent<T>(long seed, T value) {
}
}
@@ -1,150 +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.generation.runtime;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.Supplier;
/**
* Per-thread values owned by the object that holds this table, typically an engine-owned runtime. Unlike a
* ThreadLocal, the values live here and not in the worker threads, so they become unreachable with their owner even
* while the pooled workers that filled them stay alive. A live thread never loses its value: a thread whose probed
* slots all belong to other live threads keeps its value in an overflow map, which drops dead threads whenever it
* takes a new one. The size therefore follows the live threads and not the worker churn.
* <p>
* Owners and values sit in parallel arrays so the common lookup, a thread in its home slot, is one owner compare and
* one value read that do not depend on each other. Only the owning thread writes a slot's value, and a slot changes
* owner only once its previous owner removed its value or died, so an owner match always pairs with that owner's
* value. Until some thread has had to store away from its home slot, a thread missing from its home slot has no
* value at all, so unbound threads skip the probe too.
*/
public final class ThreadSlots<T> {
private static final int SLOT_COUNT = 256;
private static final int SLOT_MASK = SLOT_COUNT - 1;
private static final int PROBE_LIMIT = 8;
private static final int NOT_FOUND = -1;
private final AtomicReferenceArray<Thread> owners = new AtomicReferenceArray<>(SLOT_COUNT);
private final AtomicReferenceArray<T> values = new AtomicReferenceArray<>(SLOT_COUNT);
private final ConcurrentHashMap<Thread, T> overflow = new ConcurrentHashMap<>();
private final Supplier<T> factory;
private volatile boolean storedAwayFromHome;
/** A table whose threads each get a value from the factory on first use. */
public ThreadSlots(Supplier<T> factory) {
this.factory = Objects.requireNonNull(factory, "thread value factory");
}
private ThreadSlots() {
this.factory = null;
}
/** A table of values each thread binds with {@link #set} and clears with {@link #remove}. */
public static <T> ThreadSlots<T> bindings() {
return new ThreadSlots<>();
}
/** This thread's value, created by the factory on first use; null for an unbound thread of a bindings table. */
public T get() {
Thread thread = Thread.currentThread();
int home = home(thread);
if (owners.getPlain(home) == thread) {
return values.getPlain(home);
}
T awayFromHome = storedAwayFromHome ? getAwayFromHome(thread) : null;
if (awayFromHome != null || factory == null) {
return awayFromHome;
}
T created = factory.get();
store(thread, created);
return created;
}
public void set(T value) {
if (value == null) {
remove();
return;
}
Thread thread = Thread.currentThread();
int index = find(thread);
if (index != NOT_FOUND) {
values.set(index, value);
return;
}
if (overflow.replace(thread, value) == null) {
store(thread, value);
}
}
public void remove() {
Thread thread = Thread.currentThread();
int index = find(thread);
if (index != NOT_FOUND) {
values.set(index, null);
owners.set(index, null);
return;
}
if (!overflow.isEmpty()) {
overflow.remove(thread);
}
}
private T getAwayFromHome(Thread thread) {
int index = find(thread);
if (index != NOT_FOUND) {
return values.getPlain(index);
}
return overflow.isEmpty() ? null : overflow.get(thread);
}
private int find(Thread thread) {
int home = home(thread);
for (int probe = 0; probe < PROBE_LIMIT; probe++) {
int index = (home + probe) & SLOT_MASK;
if (owners.getPlain(index) == thread) {
return index;
}
}
return NOT_FOUND;
}
private void store(Thread thread, T value) {
int home = home(thread);
for (int probe = 0; probe < PROBE_LIMIT; probe++) {
int index = (home + probe) & SLOT_MASK;
Thread current = owners.get(index);
if ((current == null || !current.isAlive()) && owners.compareAndSet(index, current, thread)) {
values.set(index, value);
if (probe > 0) {
storedAwayFromHome = true;
}
return;
}
}
storedAwayFromHome = true;
overflow.keySet().removeIf(owner -> !owner.isAlive());
overflow.put(thread, value);
}
private static int home(Thread thread) {
return (int) thread.threadId() & SLOT_MASK;
}
}
@@ -61,7 +61,6 @@ public class IrisBiomeActuator extends EngineAssignedActuator<NativeBiome> {
ChunkedDataCache<IrisBiome> biomeCache = context.getBiome();
IrisComplex complex = context.getComplex();
DimensionStackContext dimensionStackContext = engine.getDimensionStackContext();
IrisDimension dimension = getDimension();
for (int xf = 0; xf < width; xf++) {
for (int zf = 0; zf < depth; zf++) {
@@ -70,7 +69,7 @@ public class IrisBiomeActuator extends EngineAssignedActuator<NativeBiome> {
IrisBiome biome = biomeCache.get(xf, zf);
NativeBiome platformBiome = resolve(biomeKey(
biome,
dimension,
getDimension(),
engine,
worldX,
0,
@@ -18,7 +18,6 @@
package art.arcane.iris.generation.stage;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.subterrain.SubterrainCell;
import art.arcane.iris.generation.subterrain.SubterrainPlanner;
@@ -43,7 +42,6 @@ import art.arcane.iris.generation.mantle.TerrainMatterView;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.biome.IrisBiomePaletteLayer;
import art.arcane.iris.generation.biome.PaletteLayerRuntime;
import art.arcane.iris.generation.decoration.IrisDecorationPart;
import art.arcane.iris.generation.decoration.IrisDecorator;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver;
@@ -232,7 +230,6 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
} finally {
getEngine().getMetrics().getCave().put(caveStopwatch.getMilliseconds());
mantleChunk.release();
scratch.releaseReferences();
}
}
@@ -343,7 +340,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
int blockZ = chunkZ << 4;
return new SubterrainSurfaceMaterials(planner,
planner.plansForBounds(blockX - 1, blockZ - 1, blockX + 16, blockZ + 16),
getEngine().getDimension(), getComplex(), PackRuntime.of(getEngine()), rng, getEngine().getWorld().minHeight());
getEngine().getDimension(), getComplex(), getData(), rng, getEngine().getWorld().minHeight());
}
static boolean hasExplicitCarveIntent(MatterCavern cavern) {
@@ -609,9 +606,6 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
private final IrisData data;
private final int chunkBlockX;
private final int chunkBlockZ;
private final PackRuntime wallRuntime;
private IrisBiomePaletteLayer lastWall;
private PaletteLayerRuntime lastWallRuntime;
private WallPainter(Hunk<NativeBlockState> output, CaveTerrainSnapshot terrain, CaveInputs inputs,
Long2ObjectOpenHashMap<IrisBiome> caveBiomeCache, Map<String, IrisBiome> customBiomeCache,
@@ -625,7 +619,6 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
this.data = data;
this.chunkBlockX = chunkBlockX;
this.chunkBlockZ = chunkBlockZ;
this.wallRuntime = inputs.runtime.scopeFor(data);
}
@Override
@@ -644,20 +637,11 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
if (biome == null) {
return;
}
IrisBiomePaletteLayer wallLayer = biome.getWall();
NativeBlockState wall = wallLayer.get(rng, 0, worldX, yy, worldZ, wallLayerRuntime(wallLayer));
NativeBlockState wall = biome.getWall().get(rng, worldX, yy, worldZ, data);
if (wall != null) {
output.setRaw(rx, yy, rz, wall);
}
}
private PaletteLayerRuntime wallLayerRuntime(IrisBiomePaletteLayer wallLayer) {
if (wallLayer != lastWall) {
lastWall = wallLayer;
lastWallRuntime = wallRuntime.paletteLayer(wallLayer);
}
return lastWallRuntime;
}
}
private void addInternalWallsFromMantle(CaveTerrainSnapshot terrain, CarveWallBuffer walls, CarveColumnMask[] columnMasks) {
@@ -1032,13 +1016,13 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
private KList<NativeBlockState> floorLayers(CaveLayerMemo layers, IrisBiome biome, int worldX, int worldZ, int floorY,
CaveInputs inputs) {
if (!hasHeightFreeFloorLayers(biome)) {
return biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.runtime, inputs.complex);
return biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.data, inputs.complex);
}
KList<NativeBlockState> remembered = layers.floor(biome);
if (remembered != null) {
return remembered;
}
KList<NativeBlockState> blocks = biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.runtime, inputs.complex);
KList<NativeBlockState> blocks = biome.generateLayers(inputs.dimension, worldX, worldZ, rng, 3, floorY, inputs.data, inputs.complex);
layers.rememberFloor(biome, blocks);
return blocks;
}
@@ -1049,7 +1033,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
if (remembered != null) {
return remembered;
}
KList<NativeBlockState> blocks = biome.generateCeilingLayers(inputs.dimension, worldX, worldZ, rng, 3, ceilingY, inputs.runtime, inputs.complex);
KList<NativeBlockState> blocks = biome.generateCeilingLayers(inputs.dimension, worldX, worldZ, rng, 3, ceilingY, inputs.data, inputs.complex);
layers.rememberCeiling(biome, blocks);
return blocks;
}
@@ -1372,7 +1356,6 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
private final IrisComplex complex;
private final IrisDimension dimension;
private final IrisData data;
private final PackRuntime runtime;
private final int height;
private final IrisDimensionCarvingResolver.State state = new IrisDimensionCarvingResolver.State();
private final IrisDimensionCarvingResolver.Snapshot snapshot;
@@ -1410,7 +1393,6 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
complex = engine.getComplex();
dimension = engine.getDimension();
data = engine.getData();
runtime = PackRuntime.of(engine, data);
height = engine.getHeight();
cells = SubterrainChunkCells.of(engine, chunkX, chunkZ);
IrisContext context = IrisContext.get();
@@ -67,12 +67,6 @@ final class IrisCarveScratch {
caveBiomeCache.clear();
customCaveBiomePresent = false;
}
/** Drops every biome, block and cavern reference so the thread's scratch pins no pack once a chunk is carved. */
void releaseReferences() {
reset();
layers.reset();
}
}
final class CaveLayerMemo {
@@ -84,8 +78,6 @@ final class CaveLayerMemo {
private int ceilingCount;
void reset() {
Arrays.fill(floor, 0, floorCount, null);
Arrays.fill(ceiling, 0, ceilingCount, null);
floorCount = 0;
ceilingCount = 0;
}
Loaded 100 of 742 files, more files were not shown because too many files have changed in this diff. Show more