Compare commits

..
Author SHA1 Message Date
piexel 9413e2ff5f Report build and system facts on development builds
Printed at startup, by /iris debug info and in the debug dump
2026-11-30 22:50:40 +01:00
piexel 8893432b6f Mark development builds in the console
Purple fins, DEV tag, branch and build age
2026-11-30 17:08:32 +01:00
piexel df31f1e2e3 Edit the biome, region or dimension you stand in 2026-11-30 14:37:11 +01:00
piexel 0fa1e01cd3 Merge master 2026-11-28 18:08:39 +01:00
Brian Fopiano 512ea0b0d7 Allow empty sea and shore lists
- Keep the column biome when a region lists no shore biomes
- Keep the column biome when a region lists no sea biomes
- Pick continental sea from land in regions without sea biomes
- Fail complex compile when a region has no usable land biome
- Report regions without landBiomes as blocking validation errors
- Report regions whose land biomes are all version-excluded
- Use the region-aware base type in studio map noise views
- Handle missing sea biomes in studio sea layer views
2026-11-28 09:58:37 -05:00
Brian Fopiano 9425e802dc Skip retired continuation slices
- Add retired slice id list with TreeCanopy
- Skip unregistered retired slices by size prefix and warn once
- Split unknown and duplicate slice type errors
- Reject slice ids that overrun their size prefix
- Test retired skip, unknown id and duplicate failures
2026-11-28 09:58:22 -05:00
Brian Fopiano 95395cbc87 Cache saved terrain status
- Add per-slot terrain status cache under the iris folder
- Reuse a bit only when header location and timestamp match
- Decode again when timestamps fall near the previous scan time
- Never reuse bits for chunks stored in external mcc files
- Skip reading region files when every pending chunk is cached
- Use the cache only for the startup recovery scan
- Ignore unreadable or mismatched cache files and rescan fully
- Cover warm hits, invalidation and corrupt cache in tests
2026-11-28 09:58:21 -05:00
Brian Fopiano c71feb62e0 Fix bed rule for no-sleep dimensions
- Write destroy_on_use instead of the unknown explodes key
- Test bed rules for overworld, nether and end bases
2026-11-28 08:18:44 -05:00
Brian Fopiano 77969617d8 Fix Bukkit jar build
- Keep TomlSegments and ConfigComments in the shaded config classes
- Update the Mac noise hash after the fracture fix
2026-11-27 20:36:20 -05:00
Piexel ac5788ef02 Warn once for repeated pack warnings (#1262)
- Scope resource, loot and placement warnings to the pack
- Forget a pack's warn-once keys on reload and hotload
- Show read failure stack traces only the first time
- Drop least recently seen once-key past the cap
- Walk the caller stack only for stated warnings
2026-11-27 15:52:26 -05:00
Piexel d7c5526eab Add style seed and generator exponent (#1268)
- Add seed to noise styles, rolled from the world seed
- Read seeded styles flat in child, palette and decorator lookups
- Add exponent curve to generators on scalar and batch paths
- Reject generator exponents at or below zero
- Warn in datapack export when seed or exponent is dropped
2026-11-27 13:44:03 -05:00
Piexel 4c90095361 Warn on imported feature height (#1274)
- Warn when importedFeatures runs outside -64..320
- Point at disabled and disabledSteps to remove ores
- Stay silent when imported features are off
2026-11-27 12:58:04 -05:00
Piexel 25c612b3c3 Add requireAllContent (#1281)
- Add requireAllContent dimension setting, off by default
- Fail pack validation when flagged dimension loses reached content
- Skip content the dimension never references
- Keep declared fallbacks from failing the pack
- Name missing keys with up to three uses each
2026-11-27 11:58:38 -05:00
Piexel 6e078ad4a0 Add list snippets (#1271)
- Expand JSON array snippet files into list entries
- Read snippet values as JSON trees and skip malformed ones once
- Route snippet references through one SnippetFolder lookup
- Reject references that leave snippet/<type>/, including symlinks
2026-11-27 11:40:19 -05:00
Piexel fc5db87514 Skip unused broken packs (#1265)
- Skip unloadable packs no world uses and name them
- Fail compilation naming the pack and worlds that use it
- Exclude skipped packs from registry requirements
- Always create the dimension type folder
2026-11-27 11:40:08 -05:00
Piexel d720e9afab Fix studio world leak (#1276)
- Move seeded generator caches into engine-owned PackRuntime
- Replace per-thread ThreadLocal memos with engine-owned ThreadSlots
- Release engine-keyed structure entries when an engine closes
- Keep pack objects as read-only configuration
2026-11-27 11:39:53 -05:00
piexel 1e04f61957 Keep custom leaves from decaying and from cutting logs
- Implement the log and leaves checks added in https://github.com/VolmitSoftware/VolmLib/pull/4 so master compiles against the current VolmLib again
- Let external providers make a block persistent and report block tags
- Make CraftEngine leaves with a persistent property keep their leaves when decay is prevented
- Count CraftEngine blocks with the logs and leaves tags as logs and leaves
- Skip leaf placements that would replace a log another object placed
- Make object placement persist leaves by their persistent property, not their distance property
2026-11-23 23:31:03 +01:00
Brian Fopiano 435ed10648 Merge pull request #1264 from VolmitSoftware/fix/fracture-mirror
Stop fractured noise from mirroring across x = z
2026-11-23 13:42:18 -05:00
piexel 53376816d7 Brighten the splash info labels 2026-11-19 22:45:27 +01:00
piexel aa78a380fd Make version, server and packs stand out in the splash info 2026-11-19 22:40:20 +01:00
piexel 3048f6e2bf Dim the splash info so the title leads 2026-11-19 22:36:18 +01:00
piexel 73b3d4a899 Keep teal for the Iris tag and even out the splash info
Green success marks, one label style, info aligned to the logo, lowercase web link
2026-11-19 22:32:03 +01:00
piexel 1c9f62a84c Bring back the console report tree and highlights
Rails sit in the gutter, so rows stay aligned
2026-11-19 21:33:00 +01:00
piexel 46b5c33cf1 Lay out console output on a status gutter
Aligned label rows and next-step commands, per CLI guidelines
2026-11-19 21:07:13 +01:00
piexel 6fb25fb53e Keep custom leaves from decaying and from cutting logs
- Let external providers make a block persistent and report block tags
- Make CraftEngine leaves with a persistent property keep their leaves when decay is prevented
- Count CraftEngine blocks with the logs and leaves tags as logs and leaves
- Skip leaf placements that would replace a log another object placed
- Make object placement persist leaves by their persistent property, not their distance property
2026-11-19 19:56:49 +01:00
piexel 3b9cb4ce91 Drop debug lines before the platform binds 2026-11-18 22:07:57 +01:00
piexel 7c31231a77 Fit console command output to the console charset
- Route VolmitSender console text through ConsoleGlyphs
2026-11-18 21:09:42 +01:00
piexel 5f70643446 Dim secondary splash facts 2026-11-18 20:32:17 +01:00
piexel 415aee9f4d Use the Iris color in the splash 2026-11-18 20:27:14 +01:00
piexel 5a9abb2756 Draw console reports as a tree 2026-11-18 20:22:43 +01:00
piexel 01874b1e6f Fall back to ASCII bullets on non-Unicode consoles 2026-11-18 19:38:15 +01:00
piexel b545500abe Shade console log lines like chat 2026-11-18 19:21:24 +01:00
piexel 673dda2860 Declutter the boot log 2026-11-18 18:25:51 +01:00
piexel 2f82ad34a3 Color boot reports in the console
- Keep legacy colors on Bukkit warning and error lines
- Stop stripping colors from ChatReport console output
- Render unknown pack fields as a themed report once logging is bound
- Label epoch snapshots by their dimension key
- Show clean pack validation with the success tone
2026-11-18 17:59:34 +01:00
piexel 7b2e28d439 Kebab-case remaining command names
- Rename loadWorld and unloadWorld to load-world and unload-world
- Kebab-case camelCase jigsaw params
2026-11-18 17:45:10 +01:00
piexel 38ec1752c1 Group unknown pack field warnings
- Report each field once per pack, keyed by pack-relative path
- Print one block per pack after loading goes quiet
- Drop the snippet and Gson note
2026-11-18 17:45:10 +01:00
piexel 10463d58cc Drop * from pack suggestions
- Stop suggesting the internal all-packs sentinel
- Say omit for every pack in validate, status and compat help
2026-11-18 17:24:48 +01:00
piexel a1bf501c30 Autocomplete more command parameters
- Suggest pack folders for pack validate, cleanup, restore, status and compat
- Suggest preview and apply for pack restore mode
- Suggest versions and installed datapack ids for datapack export and remove
- Suggest structure keys for structure info, place, jigsaw convert and adopt inspect
- Suggest workcell ids for jigsaw save and goto
- Suggest formats for jigsaw export
- Suggest subterrain families, marker keys and world slots
2026-11-18 17:17:09 +01:00
piexel cdb4e68708 Autocomplete export and cleanup modes
- Suggest mode and format values for datapack export
- Suggest preview and apply for pack cleanup mode
2026-11-18 16:59:02 +01:00
piexel 8531fcf103 Fix metrics details and theme command errors
- Stop iris metrics crashing once a world has generation timings
- Tag and color director parse and execution errors
2026-11-18 15:41:58 +01:00
piexel 1144032d62 Lowercase developer command names
- Rename Developer, EngineStatus and packBenchmark to developer, engine-status and pack-benchmark
- Key genhash centers as center-x and center-z like goldenhash
2026-11-18 15:31:31 +01:00
piexel 561ec4e0db Space chat reports
- Add a blank line before each report and before its hint in chat
- Keep console and log output compact
2026-11-18 15:24:30 +01:00
piexel 6dd22fa34e Lighter report weight
- Keep bold only on the Iris tag
- Show the short regen-stop command; the click still targets the world
2026-11-18 13:58:01 +01:00
piexel 496bdab2c3 Clearer structure verify and pack status
- Show verify counts on one line, zeros omitted
- List unreachable structures last with short biome lists
- Keep pack status colors and sort broken packs first
2026-11-18 13:32:56 +01:00
piexel b5072e4266 Stoppable regen with one run per world
- Add /iris std regen-stop
- Refuse a second regen in the same world
- Show the stop command when a regen starts
- Report stopped regens with their own outcome
2026-11-18 13:32:56 +01:00
piexel 36e7e6a337 Sample regions from the generator
- Read region chances from the generator instead of saved world history
- Stop the scan at its first error and report it once
2026-11-18 13:32:44 +01:00
piexel 8c9f3bd73d Readable report layout
- Group reasons that differ only in their subject
- Highlight names, keys and paths; dim the explanation
- Bold report titles and tone-colored bullets
- Render bold and reset codes through the gradient
- Fix bold codes flagged as colors
- Make the tag brackets actually bold
2026-11-18 13:32:44 +01:00
piexel ac4bc6b96a Hide boot validate hint when nothing is cut
- Show the pack validate hint only when the boot list is truncated
2026-11-18 13:32:44 +01:00
piexel ebf3ca85cc Themed command and progress output
- Restyle structure verify, regions, metrics, worlds and engine status
- Fold datapack export diagnostics into one report
- Share one progress bar and slow per-tick action bar updates
- Tag permission, jigsaw and auto-studio messages
2026-11-18 13:32:44 +01:00
piexel 6b1e1e55cb Quiet bulk importer chat
- Show per-item import results on the action bar
- Collect failures into one summary report
2026-11-18 13:32:44 +01:00
piexel 4d0063dd7d Themed boot validation output
- Share pack boot reporting between Bukkit and modded
- Cap boot warnings and errors with a pointer to pack validate
- Merge refused-world join notices into one report
2026-11-18 13:32:44 +01:00
piexel 8b98e2a61c Themed chat reports for pack and studio
- Add ChatReport renderer with capped bullets and clickable hints
- Group unknown content keys per registry and namespace
- Drop unknown-key findings the compat gate already names
2026-11-18 13:32:44 +01:00
piexel e0aeabd520 Keep regen off the server thread and move it to std
- Load regen chunks asynchronously and skip chunks that were never generated
- Hold a generation stage per regen chunk so a hotload waits for it
- Count skipped chunks apart in the regen progress and summary
- Log each studio hotload with its pack and duration
- Move regen from /iris dev to /iris std on Bukkit and modded
2026-11-14 18:42:23 +01:00
piexel ed44db5497 Stop fractured noise from mirroring across x = z
- Read each composite fracture axis from its own reseeded generator at unswapped coordinates in IrisNoiseGenerator and the batched NoiseLayerProgram
- Read the datapack exporter's z warps at unswapped coordinates
- Add a mirror test for the composite fracture and move the fracture test reference to per-axis seeds
- Retake NoiseSeedCohesionTest (Linux/Windows digest), IrisCaveCarver3DCellKernelTest PACK_SHARED and three IrisMathNoiseHotPathParityTest values
2026-11-14 17:32:08 +01:00
Brian Fopiano 832070cd69 Fix foundation cell lookup
- Call lowestFoundationCells in NMS surface terrain tests
- Match the renamed VolmLib occupancy method
2026-11-11 01:08:33 -05:00
431 changed files with 13984 additions and 4350 deletions

No files matched your search

@@ -570,7 +570,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertTrue(state(blocks, 4, 96, 0).isAir());
assertEquals(1, pathGround.size());
@@ -619,7 +619,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -675,7 +675,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -570,7 +570,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertTrue(state(blocks, 4, 96, 0).isAir());
assertEquals(1, pathGround.size());
@@ -619,7 +619,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -675,7 +675,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
area::isInside, cells -> {});
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
assertEquals(2, pathGround.size());
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
@@ -40,12 +40,20 @@ final class IrisBootstrapSequence {
requireUsableWorldStorage(startupPaths);
ProvisionResult provisioned = provision(context, startupPaths);
Path datapackRoot = provisioned.datapackRoot();
context.getLogger().info("Iris startup datapack is {} at {}", provisioned.status(), datapackRoot);
context.getLogger().info("{} {}", provisionOutcome(provisioned.status()), datapackRoot);
} catch (Throwable failure) {
armStartupFailure(context, failure);
}
}
private static String provisionOutcome(DefaultPackBootstrapProvisioner.ProvisionStatus status) {
return switch (status) {
case INSTALLED -> "Installed the startup datapack at";
case UPDATED -> "Updated the startup datapack at";
case UNCHANGED -> "The startup datapack is already up to date at";
};
}
private static void loadRuntimeLibraries(BootstrapContext context) {
SlimJar.loadBootstrap(
context.getDataDirectory().resolve("cache").resolve("libraries"),
@@ -22,8 +22,12 @@ import art.arcane.iris.api.terrain.IrisTerrainService;
import art.arcane.iris.command.CommandSVC;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.configuration.SettingsHotloadWatch;
import art.arcane.iris.diagnostics.BuildChannel;
import art.arcane.iris.diagnostics.DiagnosticsReport;
import art.arcane.iris.diagnostics.LogFilterSVC;
import art.arcane.iris.diagnostics.splash.IrisSplashComposer;
import art.arcane.iris.diagnostics.splash.IrisSplashPackScanner;
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.iris.generation.decoration.tree.TreeBlockMaterial;
import art.arcane.iris.generation.runtime.BlockEditAccess;
@@ -47,6 +51,9 @@ import art.arcane.iris.integration.IrisPapiState;
import art.arcane.iris.integration.MultiverseCoreLink;
import art.arcane.iris.integration.MultiverseSVC;
import art.arcane.iris.localization.C;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.localization.ConsoleGlyphs;
import art.arcane.iris.localization.ConsoleLayout;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.pack.datapack.DatapackIngestService;
import art.arcane.iris.pack.datapack.DatapackIngestService.StartupValidationOutcome;
@@ -141,9 +148,11 @@ import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@@ -259,7 +268,7 @@ public final class IrisRuntime implements IrisPluginRuntime {
if (current == null) {
Iris plugin = Iris.instance;
current = new VolmitSender(Bukkit.getConsoleSender());
current.setTag(plugin == null ? IrisSafeguard.mode().tag("") : plugin.getTag());
current.setTag(logPrefix());
sender = current;
}
return current;
@@ -306,17 +315,22 @@ public final class IrisRuntime implements IrisPluginRuntime {
static void msg(String string) {
try {
Iris plugin = Iris.instance;
String markup = ConsoleGlyphs.console().fit(ConsoleLayout.onGutter(ChatReport.Tone.INFO, string));
if (shadesConsole()) {
logShaded(Level.INFO, logPrefix() + markup);
return;
}
ComponentLog.logMarkup(
plugin,
Logger.getLogger("Iris"),
logPrefix(plugin),
logPrefix(),
Level.INFO,
string,
markup,
null);
} catch (Throwable e) {
try {
Iris plugin = Iris.instance;
String plainPrefix = ComponentText.legacy(logPrefix(plugin)).plain();
String plainPrefix = ComponentText.legacy(logPrefix()).plain();
Logger.getLogger("Iris").log(Level.INFO, plainPrefix + IrisLogging.clean(string));
} catch (Throwable inner) {
System.err.println("[Iris] Failed to emit log message: " + inner.getMessage());
@@ -399,11 +413,11 @@ public final class IrisRuntime implements IrisPluginRuntime {
}
static void success(String string) {
Iris.msg(C.IRIS + string);
Iris.msg(ChatReport.Tone.SUCCESS.marked(ChatReport.Tone.SUCCESS.consolePaint(string)));
}
static void info(String format, Object... args) {
Iris.msg(C.WHITE + safeFormat(format, args));
Iris.msg(safeFormat(format, args));
}
private static String safeFormat(String format, Object... args) {
@@ -597,20 +611,41 @@ public final class IrisRuntime implements IrisPluginRuntime {
};
}
private static void diagnostic(Level level, String message) {
String line = IrisLogging.clean(message);
private static void diagnostic(Level level, String rawMessage) {
String message = ConsoleGlyphs.console().fit(ConsoleLayout.onGutter(diagnosticTone(level), rawMessage));
if (shadesConsole()) {
logShaded(level, logPrefix() + C.escapeTags(message));
return;
}
Iris plugin = Iris.instance;
ComponentLog.log(
ComponentLog.logLegacy(
plugin,
Logger.getLogger("Iris"),
logPrefix(plugin),
logPrefix(),
level,
ComponentText.literal(line),
message,
null);
}
private static String logPrefix(Iris plugin) {
return plugin == null ? ComponentLog.discriminator("Iris", "&a") : plugin.getTag();
private static ChatReport.Tone diagnosticTone(Level level) {
if (level == Level.SEVERE) {
return ChatReport.Tone.ERROR;
}
return level == Level.WARNING ? ChatReport.Tone.WARNING : ChatReport.Tone.INFO;
}
private static boolean shadesConsole() {
return IrisSettings.get().getGeneral().isUseConsoleCustomColors();
}
private static void logShaded(Level level, String prefixedLine) {
IrisSettings.IrisSettingsGeneral general = IrisSettings.get().getGeneral();
String shaded = C.aura(prefixedLine, general.getSpinh(), general.getSpins(), general.getSpinb());
ComponentLog.logMarkup(Iris.instance, Logger.getLogger("Iris"), "", level, shaded, null);
}
private static String logPrefix() {
return ConsoleGlyphs.console().fit(IrisSafeguard.mode().logTag());
}
static int irisVersion(String input) {
@@ -716,7 +751,7 @@ public final class IrisRuntime implements IrisPluginRuntime {
timings.mark("datapacks");
IrisSafeguard.execute();
timings.mark("safeguard");
getSender().setTag(plugin.getTag());
getSender().setTag(logPrefix());
// A cosmetic banner must never abort the bootstrap.
J.attempt(this::splash);
IrisSafeguard.printReports();
@@ -807,27 +842,34 @@ public final class IrisRuntime implements IrisPluginRuntime {
timings.mark("startupTasks");
IrisLanguage.checkUpstream();
timings.report();
if (BuildChannel.current().isDevelopment()) {
J.attempt(IrisRuntime::printDiagnostics);
}
}
private static void printDiagnostics() {
DiagnosticsReport.sections(IrisWorldGeneratorResolver::awaitsExternalContent)
.forEach(section -> section.report().consoleLines().forEach(IrisLogging::notice));
}
private static DebugDumpContributor.Report captureDebugReport() {
String language = IrisLanguage.debugReport();
return () -> IrisSafeguard.debugReport() + "\n" + language;
String diagnostics = DiagnosticsReport.plainText(IrisWorldGeneratorResolver::awaitsExternalContent);
return () -> IrisSafeguard.debugReport() + "\n" + language + "\n" + diagnostics;
}
private static final class EnableTimings {
private static final int REPORTED_SERVICES = 3;
private static final long REPORTED_PHASE_MIN_MS = 100;
private static final long SLOW_SERVICE_MIN_MS = 1000;
private final long startedAt = System.nanoTime();
private final StringBuilder phases = new StringBuilder();
private final Map<String, Long> phaseMillis = new LinkedHashMap<>();
private final Map<String, Long> serviceMillis = new LinkedHashMap<>();
private long lastMark = startedAt;
private void mark(String phase) {
long now = System.nanoTime();
if (!phases.isEmpty()) {
phases.append(' ');
}
phases.append(phase).append('=').append(TimeUnit.NANOSECONDS.toMillis(now - lastMark)).append("ms");
phaseMillis.put(phase, TimeUnit.NANOSECONDS.toMillis(now - lastMark));
lastMark = now;
}
@@ -836,16 +878,35 @@ public final class IrisRuntime implements IrisPluginRuntime {
}
private void report() {
IrisLogging.notice("Enabled in %dms (%s)",
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt), phases);
String slowest = serviceMillis.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.limit(REPORTED_SERVICES)
.map(entry -> entry.getKey() + "=" + entry.getValue() + "ms")
.collect(Collectors.joining(" "));
if (!slowest.isBlank()) {
IrisLogging.notice("Slowest services: %s", slowest);
String total = seconds(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt));
ChatReport.Builder report = ChatReport.of(ChatReport.Tone.SUCCESS, "Enabled in " + total).unlimited();
slowestFirst(phaseMillis, REPORTED_PHASE_MIN_MS)
.forEach(phase -> report.entry(titleCase(phase.getKey()), seconds(phase.getValue())));
String slowServices = slowestFirst(serviceMillis, SLOW_SERVICE_MIN_MS).stream()
.map(service -> service.getKey() + " " + seconds(service.getValue()))
.collect(Collectors.joining(", "));
if (!slowServices.isEmpty()) {
report.entry("Slow Services", slowServices);
}
report.build().consoleLines().forEach(IrisLogging::notice);
}
private static List<Map.Entry<String, Long>> slowestFirst(Map<String, Long> millisByName, long minimumMillis) {
return millisByName.entrySet().stream()
.filter(entry -> entry.getValue() >= minimumMillis)
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.toList();
}
private static String titleCase(String camelCaseName) {
String spaced = camelCaseName.replaceAll("(?<=[a-z])(?=[A-Z])", " ");
return Arrays.stream(spaced.split(" "))
.map(word -> word.isEmpty() ? word : Character.toUpperCase(word.charAt(0)) + word.substring(1))
.collect(Collectors.joining(" "));
}
private static String seconds(long millis) {
return String.format(Locale.ROOT, "%.1fs", millis / 1000.0);
}
}
@@ -930,7 +991,7 @@ public final class IrisRuntime implements IrisPluginRuntime {
Iris.debug("Starting up auto Studio!");
try {
Player r = new KList<>(plugin.getServer().getOnlinePlayers()).getRandom();
Iris.service(StudioSVC.class).open(r != null ? new VolmitSender(r) : getSender(), 1337, IrisSettings.get().getGenerator().getDefaultWorldType(), (w) -> {
Iris.service(StudioSVC.class).open(r != null ? new VolmitSender(r, plugin.getTag()) : getSender(), 1337, IrisSettings.get().getGenerator().getDefaultWorldType(), (w) -> {
J.s(() -> {
final Location spawn = w.getSpawnLocation();
for (Player i : plugin.getServer().getOnlinePlayers()) {
@@ -1490,15 +1551,38 @@ public final class IrisRuntime implements IrisPluginRuntime {
}
private void splash() {
Iris.info("Custom Biomes: " + INMS.get().countCustomBiomes());
printPacks();
IrisSafeguard.mode().trySplash();
File packFolder = Iris.service(StudioSVC.class).getWorkspaceFolder();
List<IrisSplashPackScanner.SplashPackMetadata> packs = IrisSplashPackScanner.collect(packFolder, Iris::reportError);
List<List<IrisSplashComposer.Detail>> startupFacts = startupFacts(packs);
if (IrisSettings.get().getGeneral().isSplashLogoStartup()) {
printWithoutLogPrefix(IrisSafeguard.mode().composeSplash(startupFacts));
} else {
startupFacts.forEach(row -> Iris.info(IrisSplashComposer.plainRow(row)));
}
announcePackUpdates(packs);
}
private void printPacks() {
File packFolder = Iris.service(StudioSVC.class).getWorkspaceFolder();
IrisSplashComposer.composePackLines(packFolder, Iris::reportError).thenAccept(lines -> {
private void printWithoutLogPrefix(String text) {
if (shadesConsole()) {
ComponentLog.logMarkup(plugin, Logger.getLogger("Iris"), "", Level.INFO, C.mini(C.escapeTags(text)), null);
return;
}
ComponentLog.logLegacy(plugin, Logger.getLogger("Iris"), "", Level.INFO, text, null);
}
private static List<List<IrisSplashComposer.Detail>> startupFacts(List<IrisSplashPackScanner.SplashPackMetadata> packs) {
boolean eagerInjection = IrisSettings.get().getGeneral().isEagerRuntimeInjection();
boolean datapackFromBootstrap = DefaultPackBootstrapProvisioner.wasProvisionedThisStartup();
return List.of(
List.of(IrisSplashComposer.Detail.headline("Packs", IrisSplashComposer.packSummary(packs))),
List.of(new IrisSplashComposer.Detail("Custom biomes", String.valueOf(INMS.get().countCustomBiomes()))),
List.of(new IrisSplashComposer.Detail("SIMD", SimdSupport.shortStatus()),
new IrisSplashComposer.Detail("Datapack", datapackFromBootstrap ? "bootstrap" : "startup install"),
new IrisSplashComposer.Detail("Injection", eagerInjection ? "eager" : "deferred")));
}
private void announcePackUpdates(List<IrisSplashPackScanner.SplashPackMetadata> packs) {
IrisSplashComposer.composeUpdateLines(packs).thenAccept(lines -> {
if (plugin.isEnabled()) {
lines.forEach(Iris::info);
}
@@ -18,11 +18,16 @@
package art.arcane.iris.command;
import art.arcane.iris.command.specialhandlers.ExportVersionHandler;
import art.arcane.iris.command.specialhandlers.InstalledDatapackHandler;
import art.arcane.iris.Iris;
import art.arcane.iris.command.handlers.DimensionHandler;
import art.arcane.iris.command.specialhandlers.ExportFormatHandler;
import art.arcane.iris.command.specialhandlers.ExportModeHandler;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.localization.BukkitCommandMessages;
import art.arcane.iris.localization.C;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.localization.DirectorCommandMessages;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.pack.datapack.DataVersion;
@@ -46,12 +51,14 @@ import art.arcane.volmlib.util.localization.LanguageAudience;
import art.arcane.volmlib.util.localization.MessageArgument;
import art.arcane.volmlib.util.localization.TextKey;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
@Director(name = "datapack", aliases = {"datapacks", "dp"}, description = "Download & manage external datapack imports", descriptionKey = "iris.director.commanddatapack.director.download_manage_external_datapack_imports_modrinth")
public class CommandDatapack implements DirectorExecutor {
private static final int RESOURCE_REPORTS = 4;
private static final int EXPORT_DIAGNOSTIC_LIMIT = 10;
@Director(description = "Download/update every datapack listed in a pack dimension's 'datapackImports' and install it into the world so its structures register like vanilla", descriptionKey = "iris.director.commanddatapack.director.download_update_every_datapack_listed_pack_dimension_s_datapackimports_install_it_into", aliases = {"pull"})
public void ingest(
@@ -69,24 +76,27 @@ public class CommandDatapack implements DirectorExecutor {
KList<String> configured = DatapackIngestService.collectConfiguredImports();
List<DatapackIngestService.Entry> installed = DatapackIngestService.installed();
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_DATAPACK_CONFIGURED_DATAPACK_IMPORTS, MessageArgument.untrusted("value", configured.size())));
for (String url : configured) {
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_DATAPACK_MESSAGE, MessageArgument.untrusted("url", url)));
}
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_DATAPACK_INSTALLED_DATAPACKS, MessageArgument.untrusted("value", installed.size())));
for (DatapackIngestService.Entry entry : installed) {
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_DATAPACK_MESSAGE_2, MessageArgument.untrusted("value", entry.id), MessageArgument.untrusted("value2", (entry.versionNumber == null ? "?" : entry.versionNumber))));
}
ChatReport.Builder imports = ChatReport.of(ChatReport.Tone.INFO,
IrisLanguage.text(BukkitCommandMessages.COMMAND_DATAPACK_CONFIGURED_DATAPACK_IMPORTS, MessageArgument.untrusted("value", configured.size())))
.unlimited()
.items(configured);
if (configured.isEmpty()) {
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_DATAPACK_ADD_MODRINTH_URLS_DIMENSION_S_DATAPACKIMPORTS_LIST_THEN_RUN_IRIS));
imports.hint(IrisLanguage.text(BukkitCommandMessages.COMMAND_DATAPACK_ADD_MODRINTH_URLS_DIMENSION_S_DATAPACKIMPORTS_LIST_THEN_RUN_IRIS), null);
}
sender.sendReport(imports.build());
ChatReport.Builder installedReport = ChatReport.of(ChatReport.Tone.INFO,
IrisLanguage.text(BukkitCommandMessages.COMMAND_DATAPACK_INSTALLED_DATAPACKS, MessageArgument.untrusted("value", installed.size())))
.unlimited();
for (DatapackIngestService.Entry entry : installed) {
installedReport.entry(entry.id, entry.versionNumber == null ? "?" : entry.versionNumber);
}
sender.sendReport(installedReport.build());
}
@Director(description = "Remove an installed datapack by id (also delete its URL from datapackImports to keep it gone)", descriptionKey = "iris.director.commanddatapack.director.remove_installed_datapack_by_id_also_delete_its_url_from_datapackimports_keep", aliases = {"rm"})
public void remove(
@Param(description = "The datapack id (folder name) shown by /iris datapack list", descriptionKey = "iris.director.commanddatapack.param.datapack_id_folder_name_shown_by_iris_datapack_list")
@Param(description = "The datapack id (folder name) shown by /iris datapack list", descriptionKey = "iris.director.commanddatapack.param.datapack_id_folder_name_shown_by_iris_datapack_list", customHandler = InstalledDatapackHandler.class)
String id
) {
DatapackIngestService.remove(sender(), id);
@@ -96,15 +106,15 @@ public class CommandDatapack implements DirectorExecutor {
public void export(
@Param(name = "dimension", description = "The dimension to export", descriptionKey = "iris.director.commanddatapack.param.export_dimension", customHandler = DimensionHandler.class)
IrisDimension dimension,
@Param(name = "version", description = "Target Minecraft version, 26.3 or later (blank uses the latest)", descriptionKey = "iris.director.commanddatapack.param.export_version", defaultValue = "")
@Param(name = "version", description = "Target Minecraft version, 26.3 or later (blank uses the latest)", descriptionKey = "iris.director.commanddatapack.param.export_version", defaultValue = "", customHandler = ExportVersionHandler.class)
String version,
@Param(name = "mode", description = "Output mode: preset, dimension, or overworld", descriptionKey = "iris.director.commanddatapack.param.export_mode", defaultValue = WorldgenExportRequest.DEFAULT_MODE)
@Param(name = "mode", description = "Output mode: preset, dimension, or overworld", descriptionKey = "iris.director.commanddatapack.param.export_mode", defaultValue = WorldgenExportRequest.DEFAULT_MODE, customHandler = ExportModeHandler.class)
String mode,
@Param(name = "namespace", description = "Namespace for the exported resources", descriptionKey = "iris.director.commanddatapack.param.export_namespace", defaultValue = WorldgenExportRequest.DEFAULT_NAMESPACE)
String namespace,
@Param(name = "output", description = "Output name in the datapack exports folder (blank uses the dimension and version)", descriptionKey = "iris.director.commanddatapack.param.export_output", defaultValue = "")
String output,
@Param(name = "format", description = "zip or directory", descriptionKey = "iris.director.commanddatapack.param.export_format", defaultValue = WorldgenExportRequest.DEFAULT_FORMAT)
@Param(name = "format", description = "zip or directory", descriptionKey = "iris.director.commanddatapack.param.export_format", defaultValue = WorldgenExportRequest.DEFAULT_FORMAT, customHandler = ExportFormatHandler.class)
String format,
@Param(name = "objects", description = "Include objects as structure templates", descriptionKey = "iris.director.commanddatapack.param.export_objects", defaultValue = "true")
boolean objects,
@@ -158,17 +168,33 @@ public class CommandDatapack implements DirectorExecutor {
}
private static void reportExport(ExportFeedback feedback, WorldgenExportResult result) {
for (ExportDiagnostic diagnostic : result.diagnostics()) {
feedback.send(diagnosticColor(diagnostic.severity()), IrisLanguage.text(DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_DIAGNOSTIC, MessageArgument.untrusted("key", diagnosticLabel(diagnostic)), MessageArgument.untrusted("message", diagnostic.message())));
ChatReport.Builder report = ChatReport.of(exportTone(result), exportTitle(result)).limit(EXPORT_DIAGNOSTIC_LIMIT);
result.diagnostics().stream()
.sorted(Comparator.comparingInt((ExportDiagnostic diagnostic) -> diagnostic.severity().ordinal()).reversed())
.forEach(diagnostic -> report.styledItem(diagnosticColor(diagnostic.severity())
+ ChatReport.clean(IrisLanguage.text(DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_DIAGNOSTIC,
MessageArgument.untrusted("key", diagnosticLabel(diagnostic)),
MessageArgument.untrusted("message", diagnostic.message())))));
feedback.report(report.build());
}
private static ChatReport.Tone exportTone(WorldgenExportResult result) {
if (!result.isSuccess()) {
return ChatReport.Tone.ERROR;
}
boolean warned = result.diagnostics().stream()
.anyMatch(diagnostic -> diagnostic.severity() != ExportDiagnostic.Severity.INFO);
return warned ? ChatReport.Tone.WARNING : ChatReport.Tone.SUCCESS;
}
private static String exportTitle(WorldgenExportResult result) {
if (result.isSuccess()) {
feedback.send(C.GREEN, IrisLanguage.text(DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_EXPORTED, MessageArgument.untrusted("path", result.output())));
return;
return IrisLanguage.text(DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_EXPORTED, MessageArgument.untrusted("path", result.output()));
}
TextKey outcome = result.status() == WorldgenExportResult.Status.REJECTED
? DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_REJECTED
: DirectorCommandMessages.COMMAND_DATAPACK_EXPORT_FAILED;
feedback.send(C.RED, IrisLanguage.text(outcome, MessageArgument.untrusted("reason", result.message())));
return IrisLanguage.text(outcome, MessageArgument.untrusted("reason", result.message()));
}
private static C diagnosticColor(ExportDiagnostic.Severity severity) {
@@ -208,11 +234,19 @@ public class CommandDatapack implements DirectorExecutor {
private void send(C color, String message) {
String line = color + message;
deliver(() -> sender.sendMessage(line));
}
private void report(ChatReport report) {
deliver(() -> sender.sendReport(report));
}
private void deliver(Runnable delivery) {
if (sender.isPlayer()) {
J.runEntity(sender.player(), () -> sender.sendMessage(line));
J.runEntity(sender.player(), delivery);
return;
}
sender.sendMessage(line);
delivery.run();
}
}
}
@@ -3,9 +3,12 @@ package art.arcane.iris.command;
import art.arcane.iris.Iris;
import art.arcane.iris.IrisRuntime;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.diagnostics.DiagnosticsReport;
import art.arcane.iris.localization.BukkitCommandMessagesExtended;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.command.DirectorExecutor;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import art.arcane.iris.world.IrisWorldGeneratorResolver;
import art.arcane.volmlib.util.director.annotations.Director;
import art.arcane.volmlib.util.director.annotations.Param;
import art.arcane.volmlib.util.director.help.DirectorMiniMenu;
@@ -29,6 +32,13 @@ public final class CommandDebug implements DirectorExecutor {
"Iris", Iris.instance.getDescription().getVersion(), DirectorMiniMenu.Theme.irisGreen()));
}
@Director(sync = true, description = "Print build and system facts", descriptionKey = "iris.director.commanddebug.director.info")
public void info() {
VolmitSender sender = sender();
DiagnosticsReport.sections(IrisWorldGeneratorResolver::awaitsExternalContent)
.forEach(section -> sender.sendReport(section.report()));
}
@Director(description = "Toggle debug", descriptionKey = "iris.director.commandiris.director.toggle_debug")
public void toggle() {
boolean enabled = !IrisSettings.get().getGeneral().isDebug();
@@ -24,7 +24,6 @@ import art.arcane.iris.pack.datapack.ServerConfigurator;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.world.runtime.ChunkClearer;
import art.arcane.iris.generation.validation.GoldenHashScanner;
import art.arcane.iris.world.runtime.InPlaceChunkRegenerator;
import art.arcane.iris.generation.runtime.IrisEngineSVC;
import art.arcane.iris.pack.IrisPackBenchmarking;
import art.arcane.iris.world.IrisToolbelt;
@@ -66,10 +65,10 @@ import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.BukkitCommandMessages;
import art.arcane.volmlib.util.localization.MessageArgument;
import art.arcane.iris.localization.BukkitCommandMessagesExtended;
@Director(name = "Developer", origin = DirectorOrigin.BOTH, description = "Iris World Manager", descriptionKey = "iris.director.commanddeveloper.director.iris_world_manager", aliases = {"dev"})
@Director(name = "developer",origin = DirectorOrigin.BOTH, description = "Iris World Manager", descriptionKey = "iris.director.commanddeveloper.director.iris_world_manager", aliases = {"dev"})
public class CommandDeveloper implements DirectorExecutor {
@Director(description = "Get Loaded TectonicPlates Count", descriptionKey = "iris.director.commanddeveloper.director.get_loaded_tectonicplates_count", origin = DirectorOrigin.BOTH, sync = true)
public void EngineStatus() {
@Director(name = "engine-status", description = "Get Loaded TectonicPlates Count",descriptionKey = "iris.director.commanddeveloper.director.get_loaded_tectonicplates_count", origin = DirectorOrigin.BOTH, sync = true)
public void engineStatus() {
Iris.service(IrisEngineSVC.class)
.engineStatus(sender());
}
@@ -80,9 +79,9 @@ public class CommandDeveloper implements DirectorExecutor {
World world,
@Param(description = "Radius in chunks around the center", descriptionKey = "iris.director.commanddeveloper.param.radius_chunks_around_center", defaultValue = "4")
int radius,
@Param(description = "Center chunk X", descriptionKey = "iris.director.commanddeveloper.param.center_chunk_x", defaultValue = "0")
@Param(name = "center-x", description = "Center chunk X", descriptionKey = "iris.director.commanddeveloper.param.center_chunk_x", defaultValue = "0")
int centerX,
@Param(description = "Center chunk Z", descriptionKey = "iris.director.commanddeveloper.param.center_chunk_z", defaultValue = "0")
@Param(name = "center-z", description = "Center chunk Z", descriptionKey = "iris.director.commanddeveloper.param.center_chunk_z", defaultValue = "0")
int centerZ) {
if (world == null) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_WORLD_IS_NULL));
@@ -215,7 +214,7 @@ public class CommandDeveloper implements DirectorExecutor {
}
}
@Director(description = "Test", descriptionKey = "iris.director.commanddeveloper.director.test_2")
@Director(name = "pack-benchmark", description = "Test", descriptionKey = "iris.director.commanddeveloper.director.test_2")
public void packBenchmark(
@Param(description = "The pack to bench", descriptionKey = "iris.director.commanddeveloper.param.pack_bench", aliases = {"pack"}, defaultValue = "overworld")
IrisDimension dimension,
@@ -305,51 +304,6 @@ public class CommandDeveloper implements DirectorExecutor {
}
}
// --- Regen ---
@Director(name = "regen", aliases = {"rg"}, description = "Delete and regenerate nearby chunks in place using Iris generation", descriptionKey = "iris.director.commanddeveloper.director.delete_regenerate_nearby_chunks_place_using_iris_generation", origin = DirectorOrigin.PLAYER)
public void regen(
@Param(name = "radius", description = "The radius of nearby chunks", descriptionKey = "iris.director.commanddeveloper.param.radius_nearby_chunks", defaultValue = "5")
int radius
) {
if (radius < 0) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_RADIUS_MUST_BE_0_GREATER_2));
return;
}
Player player = player();
VolmitSender commandSender = sender();
World world = player.getWorld();
if (!IrisToolbelt.isIrisWorld(world)) {
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_YOU_MUST_BE_IRIS_WORLD_USE_REGEN));
return;
}
Engine engine = IrisToolbelt.access(world).getEngine();
if (engine == null) {
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_ENGINE_ACCESS_THIS_WORLD_IS_NULL_GENERATE_NEARBY_CHUNKS_FIRST));
return;
}
int chunks = (radius * 2 + 1) * (radius * 2 + 1);
// The player position must be read on the thread owning the player; the regenerator hops per chunk itself.
if (!J.runEntity(player, () -> {
int centerX = player.getLocation().getBlockX() >> 4;
int centerZ = player.getLocation().getBlockZ() >> 4;
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_REGEN_STARTED_CHUNK_S_AROUND_DELETING_REGENERATING_PLACE, MessageArgument.untrusted("chunks", chunks), MessageArgument.untrusted("centerX", centerX), MessageArgument.untrusted("centerZ", centerZ)));
Iris.info("Regen run start: world=" + world.getName()
+ " center=" + centerX + "," + centerZ
+ " radius=" + radius
+ " chunks=" + chunks);
new InPlaceChunkRegenerator(world, engine, commandSender, centerX, centerZ, radius).start();
})) {
Iris.warn("Could not schedule regen on the thread owning " + player.getName() + ".");
}
}
@Director(name = "goldenhash", aliases = {"gold"}, description = "Generate chunks into buffers (no world writes) and hash blocks+biomes; captures a golden file or verifies against an existing one. Deletes the world's entire mantle - use on disposable test worlds.", descriptionKey = "iris.director.commanddeveloper.director.generate_chunks_into_buffers_no_world_writes_hash_blocks_biomes_captures_golden", origin = DirectorOrigin.BOTH)
public void goldenhash(
@Param(description = "The world to scan", descriptionKey = "iris.director.commanddeveloper.param.world_scan", contextual = true, contextualOverride = true)
@@ -65,7 +65,7 @@ public class CommandEdit implements DirectorExecutor {
@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) {
public void biome(@Param(contextual = true, contextualOverride = true, description = "The biome to edit", descriptionKey = "iris.director.commandedit.param.biome_edit") IrisBiome biome) {
if (noStudio()) {
return;
}
@@ -83,7 +83,7 @@ public class CommandEdit implements DirectorExecutor {
}
@Director(description = "Edit the region you specified", descriptionKey = "iris.director.commandedit.director.edit_region_you_specified", aliases = {"r"}, origin = DirectorOrigin.PLAYER)
public void region(@Param(contextual = false, description = "The region to edit", descriptionKey = "iris.director.commandedit.param.region_edit") IrisRegion region) {
public void region(@Param(contextual = true, contextualOverride = true, description = "The region to edit", descriptionKey = "iris.director.commandedit.param.region_edit") IrisRegion region) {
if (noStudio()) {
return;
}
@@ -101,7 +101,7 @@ public class CommandEdit implements DirectorExecutor {
}
@Director(description = "Edit the dimension you specified", descriptionKey = "iris.director.commandedit.director.edit_dimension_you_specified", aliases = {"d"}, origin = DirectorOrigin.PLAYER)
public void dimension(@Param(contextual = false, description = "The dimension to edit", descriptionKey = "iris.director.commandedit.param.dimension_edit") IrisDimension dimension) {
public void dimension(@Param(contextual = true, contextualOverride = true, description = "The dimension to edit", descriptionKey = "iris.director.commandedit.param.dimension_edit") IrisDimension dimension) {
if (noStudio()) {
return;
}
@@ -18,6 +18,7 @@
package art.arcane.iris.command;
import art.arcane.iris.command.specialhandlers.SubterrainFeatureHandler;
import art.arcane.iris.Iris;
import art.arcane.iris.localization.BukkitCommandMessages;
import art.arcane.iris.localization.BukkitCommandMessagesExtended;
@@ -93,7 +94,7 @@ public class CommandFind implements DirectorExecutor {
@Director(description = "Find an authored underground feature by id or geometry family", sync = true)
public void subterrain(
@Param(description = "Feature definition id or family: tectonic_fault, cenote, lava_tube, travertine_terraces")
@Param(description = "Feature definition id or family: tectonic_fault, cenote, lava_tube, travertine_terraces", customHandler = SubterrainFeatureHandler.class)
String feature,
@Param(description = "Search radius in blocks", defaultValue = "8192")
int radius,
@@ -18,6 +18,7 @@
package art.arcane.iris.command;
import art.arcane.iris.command.specialhandlers.OpenSuggestionHandler;
import art.arcane.iris.Iris;
import art.arcane.iris.IrisRuntime;
import art.arcane.iris.world.BukkitWorldReconciler;
@@ -47,6 +48,8 @@ import art.arcane.volmlib.util.director.annotations.Param;
import art.arcane.volmlib.util.director.exceptions.DirectorParsingException;
import art.arcane.iris.command.specialhandlers.NullablePlayerHandler;
import art.arcane.iris.localization.C;
import art.arcane.iris.localization.BukkitRuntimeMessages;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import art.arcane.iris.world.task.J;
import org.bukkit.Bukkit;
@@ -58,6 +61,8 @@ import org.bukkit.entity.Player;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
@@ -82,6 +87,7 @@ public class CommandIris implements DirectorExecutor {
private static final String NO_DOWNLOAD_SOURCE = "__none__";
private static final String PRESERVE_REPLACEMENT_SEED = "preserve";
private static final long WORLD_UNLOAD_TIMEOUT_SECONDS = 150L;
private static final int METRICS_DETAIL_LIMIT = 12;
private CommandStudio studio;
private CommandPregen pregen;
@@ -196,7 +202,8 @@ public class CommandIris implements DirectorExecutor {
name = "target",
aliases = "world-name",
description = "The exact existing world slot to replace",
descriptionKey = "iris.director.commandiris.param.replace_exact_existing_world_slot_next_restart"
descriptionKey = "iris.director.commandiris.param.replace_exact_existing_world_slot_next_restart",
customHandler = WorldSlotHandler.class
)
String target,
@Param(
@@ -340,26 +347,18 @@ public class CommandIris implements DirectorExecutor {
}
}
if (sender().isPlayer()) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_IRIS_WORLDS));
for (World IrisWorld : IrisWorlds.copy()) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_MESSAGE, MessageArgument.untrusted("value", IrisWorld.getName())));
}
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_BUKKIT_WORLDS));
for (World BukkitWorld : BukkitWorlds.copy()) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_MESSAGE_2, MessageArgument.untrusted("value", BukkitWorld.getName())));
}
} else {
Iris.info(C.BLUE + "Iris Worlds: ");
for (World IrisWorld : IrisWorlds.copy()) {
Iris.info(C.IRIS + "- " +IrisWorld.getName());
}
Iris.info(C.GOLD + "Bukkit Worlds: ");
for (World BukkitWorld : BukkitWorlds.copy()) {
Iris.info(C.GRAY + "- " +BukkitWorld.getName());
}
sender().sendReport(worldListReport(ChatReport.Tone.SUCCESS,
IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_IRIS_WORLDS), IrisWorlds));
sender().sendReport(worldListReport(ChatReport.Tone.INFO,
IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_BUKKIT_WORLDS), BukkitWorlds));
}
private static ChatReport worldListReport(ChatReport.Tone tone, String title, List<World> worlds) {
ChatReport.Builder report = ChatReport.of(tone, title).unlimited();
for (World world : worlds) {
report.item(world.getName());
}
return report.build();
}
@Director(description = "Remove an Iris world", descriptionKey = "iris.director.commandiris.director.remove_iris_world", aliases = {"rm"}, sync = true)
@@ -465,8 +464,22 @@ public class CommandIris implements DirectorExecutor {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_YOU_MUST_BE_IRIS_WORLD));
return;
}
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_SENDING_METRICS));
engine().printMetrics(sender()::sendMessage);
List<String> lines = new ArrayList<>();
engine().printMetrics(lines::add);
String detailsHeader = IrisLanguage.text(BukkitRuntimeMessages.IRIS_ENGINE_DETAILS);
int detailsIndex = lines.indexOf(detailsHeader);
List<String> totals = detailsIndex < 0 ? lines : lines.subList(0, detailsIndex);
sender().sendReport(ChatReport.of(ChatReport.Tone.SUCCESS,
IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_SENDING_METRICS))
.items(totals)
.unlimited()
.build());
if (detailsIndex >= 0) {
sender().sendReport(ChatReport.of(ChatReport.Tone.INFO, detailsHeader)
.items(lines.subList(detailsIndex + 1, lines.size()))
.limit(METRICS_DETAIL_LIMIT)
.build());
}
}
@Director(description = "Reload configuration file (this is also done automatically)", descriptionKey = "iris.director.commandiris.director.reload_configuration_file_this_is_also_done_automatically")
@@ -489,7 +502,7 @@ public class CommandIris implements DirectorExecutor {
}
@Director(description = "Unload an Iris World", descriptionKey = "iris.director.commandiris.director.unload_iris_world", origin = DirectorOrigin.PLAYER, sync = true)
@Director(name = "unload-world", description = "Unload an Iris World", descriptionKey = "iris.director.commandiris.director.unload_iris_world", origin = DirectorOrigin.PLAYER, sync = true)
public void unloadWorld(
@Param(description = "The world to unload", descriptionKey = "iris.director.commandiris.param.world_unload")
World world
@@ -609,7 +622,7 @@ public class CommandIris implements DirectorExecutor {
}
}
@Director(description = "Load an Iris World", descriptionKey = "iris.director.commandiris.director.load_iris_world", origin = DirectorOrigin.PLAYER, sync = true, aliases = {"import"})
@Director(name = "load-world", description = "Load an Iris World", descriptionKey = "iris.director.commandiris.director.load_iris_world", origin = DirectorOrigin.PLAYER, sync = true, aliases = {"import"})
public void loadWorld(
@Param(
description = "The name of the world to load",
@@ -711,6 +724,13 @@ public class CommandIris implements DirectorExecutor {
).isPresent();
}
public static final class WorldSlotHandler extends OpenSuggestionHandler {
@Override
protected Collection<String> suggestions() {
return Bukkit.getWorlds().stream().map(world -> world.getKey().toString()).toList();
}
}
public static class ManagedWorldNameHandler implements DirectorParameterHandler<String> {
@Override
public KList<String> getPossibilities() {
@@ -1,5 +1,8 @@
package art.arcane.iris.command;
import art.arcane.iris.command.specialhandlers.OpenSuggestionHandler;
import art.arcane.iris.command.specialhandlers.RegisteredStructureKeyHandler;
import art.arcane.iris.command.specialhandlers.ExportFormatHandler;
import art.arcane.iris.Iris;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.studio.object.StudioOpenCoordinator;
@@ -52,7 +55,10 @@ import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
@@ -145,7 +151,7 @@ public class CommandJigsaw implements DirectorExecutor {
aliases = {"import", "import-vanilla"}, sync = true, origin = DirectorOrigin.PLAYER)
public void convert(
@Param(description = "Pack dimension") IrisDimension dimension,
@Param(description = "Registered structure key such as minecraft:village_plains") String source,
@Param(description = "Registered structure key such as minecraft:village_plains", customHandler = RegisteredStructureKeyHandler.class) String source,
@Param(description = "New Iris structure key, or auto", defaultValue = "auto") String target,
@Param(description = "Studio world seed", defaultValue = "1337") long seed
) {
@@ -366,7 +372,7 @@ public class CommandJigsaw implements DirectorExecutor {
@Director(description = "Flush the automatic save for a workcell now", sync = true,
origin = DirectorOrigin.PLAYER)
public void save(
@Param(description = "Workcell ID or selected", defaultValue = "selected") String bay
@Param(description = "Workcell ID or selected", defaultValue = "selected", customHandler = JigsawWorkcellOrSelectedHandler.class) String bay
) {
ActiveContext context = requireActive();
if (context == null) {
@@ -387,7 +393,7 @@ public class CommandJigsaw implements DirectorExecutor {
@Director(name = "goto", aliases = "teleport", description = "Select and teleport to a Studio workcell",
sync = true, origin = DirectorOrigin.PLAYER)
public void gotoBay(
@Param(description = "Workcell ID") String bay
@Param(description = "Workcell ID", customHandler = JigsawWorkcellHandler.class) String bay
) {
if (requireActive() != null) {
JigsawStudioService.get().teleportTo(player(), bay);
@@ -410,7 +416,7 @@ public class CommandJigsaw implements DirectorExecutor {
@Param(description = "Datapack namespace", defaultValue = "iris") String namespace,
@Param(description = "Output name under the Studio exports folder", defaultValue = "jigsaw-export")
String output,
@Param(description = "directory or zip", defaultValue = "zip") String format,
@Param(description = "directory or zip", defaultValue = "zip", customHandler = ExportFormatHandler.class) String format,
@Param(description = "Replace an existing export", defaultValue = "false") boolean replace
) {
ActiveContext context = requireActive();
@@ -815,4 +821,27 @@ public class CommandJigsaw implements DirectorExecutor {
}
}
public static class JigsawWorkcellHandler extends OpenSuggestionHandler {
@Override
protected Collection<String> suggestions() {
ActiveContext context = active(player());
if (context == null) {
return List.of();
}
return context.session().layout().bays().stream().map(JigsawStudioBay::stableId).toList();
}
}
public static final class JigsawWorkcellOrSelectedHandler extends JigsawWorkcellHandler {
private static final String SELECTED_WORKCELL = "selected";
@Override
protected Collection<String> suggestions() {
List<String> options = new ArrayList<>();
options.add(SELECTED_WORKCELL);
options.addAll(super.suggestions());
return options;
}
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.command;
import art.arcane.iris.command.specialhandlers.IrisStructureHandler;
import art.arcane.iris.Iris;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.structure.authoring.StructureKey;
@@ -45,7 +46,7 @@ public class CommandJigsawAdopt implements DirectorExecutor {
origin = DirectorOrigin.PLAYER)
public void inspect(
@Param(description = "Pack dimension") IrisDimension dimension,
@Param(description = "Existing Iris structure key") String source,
@Param(description = "Existing Iris structure key", customHandler = IrisStructureHandler.class) String source,
@Param(description = "New owned Iris key, or auto", defaultValue = "auto") String target,
@Param(description = "auto, in-place, or clone", defaultValue = "auto",
customHandler = JigsawAdoptionStrategyHandler.class) String strategy
@@ -94,7 +95,7 @@ public class CommandJigsawAdopt implements DirectorExecutor {
@Director(description = "Apply one inspected adoption plan without overwriting", sync = true,
origin = DirectorOrigin.PLAYER)
public void apply(
@Param(description = "Plan UUID returned by adopt inspect",
@Param(name = "plan-id", description = "Plan UUID returned by adopt inspect",
customHandler = JigsawAdoptionPlanHandler.class) String planId
) {
VolmitSender commandSender = sender();
@@ -25,8 +25,8 @@ public class CommandJigsawPiece implements DirectorExecutor {
@Director(description = "Create an owned piece from the selected Studio topology", sync = true,
origin = DirectorOrigin.PLAYER)
public void create(
@Param(description = "Owned pool resource key") String poolKey,
@Param(description = "New owned piece and object key") String pieceKey,
@Param(name = "pool-key", description = "Owned pool resource key") String poolKey,
@Param(name = "piece-key", description = "New owned piece and object key") String pieceKey,
@Param(description = "Positive selection weight", defaultValue = "1") int weight
) {
CommandJigsaw.ActiveContext context = CommandJigsaw.active(player());
@@ -81,8 +81,8 @@ public class CommandJigsawPiece implements DirectorExecutor {
@Director(description = "Add an existing jigsaw piece to an owned pool transactionally", sync = true,
origin = DirectorOrigin.PLAYER)
public void add(
@Param(description = "Owned pool resource key") String poolKey,
@Param(description = "Existing jigsaw piece key") String pieceKey,
@Param(name = "pool-key", description = "Owned pool resource key") String poolKey,
@Param(name = "piece-key", description = "Existing jigsaw piece key") String pieceKey,
@Param(description = "Positive selection weight", defaultValue = "1") int weight
) {
CommandJigsaw.ActiveContext context = CommandJigsaw.active(player());
@@ -153,7 +153,7 @@ public class CommandJigsawPiece implements DirectorExecutor {
@Director(description = "Remove the selected piece from an owned pool transactionally", sync = true,
origin = DirectorOrigin.PLAYER)
public void remove(
@Param(description = "Owned pool resource key") String poolKey
@Param(name = "pool-key", description = "Owned pool resource key") String poolKey
) {
CommandJigsaw.ActiveContext context = CommandJigsaw.active(player());
if (context == null) {
@@ -10,8 +10,8 @@ public class CommandJigsawPool implements DirectorExecutor {
@Director(description = "Create an empty owned jigsaw pool", sync = true,
origin = DirectorOrigin.PLAYER)
public void create(
@Param(description = "New owned pool resource key") String poolKey,
@Param(description = "Owned fallback pool key, or none", defaultValue = "none")
@Param(name = "pool-key", description = "New owned pool resource key") String poolKey,
@Param(name = "fallback-pool-key", description = "Owned fallback pool key, or none", defaultValue = "none")
String fallbackPoolKey
) {
CommandJigsaw.ActiveContext context = CommandJigsaw.active(player());
@@ -13,8 +13,8 @@ public class CommandJigsawRules implements DirectorExecutor {
@Director(description = "Set maximum expansion depth and horizontal radius", sync = true,
origin = DirectorOrigin.PLAYER)
public void limits(
@Param(description = "Maximum expansion depth") int maxDepth,
@Param(description = "Maximum radius in chunks") int maxSizeChunks
@Param(name = "max-depth", description = "Maximum expansion depth") int maxDepth,
@Param(name = "max-size-chunks", description = "Maximum radius in chunks") int maxSizeChunks
) {
CommandJigsaw.ActiveContext context = CommandJigsaw.active(player());
if (context == null) {
@@ -36,16 +36,16 @@ public class CommandJigsawRules implements DirectorExecutor {
context,
"",
"",
"Persisted jigsaw limits: maxDepth=" + maxDepth
+ ", maxSizeChunks=" + maxSizeChunks + ".");
"Persisted jigsaw limits: max-depth=" + maxDepth
+ ", max-size-chunks=" + maxSizeChunks + ".");
});
}
@Director(description = "Set or clear one owned pool's direct fallback", sync = true,
origin = DirectorOrigin.PLAYER)
public void fallback(
@Param(description = "Owned pool resource key") String poolKey,
@Param(description = "Owned fallback pool key, or none") String fallbackPoolKey
@Param(name = "pool-key", description = "Owned pool resource key") String poolKey,
@Param(name = "fallback-pool-key", description = "Owned fallback pool key, or none") String fallbackPoolKey
) {
CommandJigsaw.ActiveContext context = CommandJigsaw.active(player());
if (context == null) {
@@ -16,7 +16,7 @@ public class CommandJigsawVariant implements DirectorExecutor {
@Director(description = "Set the selected piece weight in a pool", sync = true,
origin = DirectorOrigin.PLAYER)
public void weight(
@Param(description = "Pool resource key") String poolKey,
@Param(name = "pool-key", description = "Pool resource key") String poolKey,
@Param(description = "Positive selection weight") int weight
) {
CommandJigsaw.ActiveContext context = CommandJigsaw.active(player());
@@ -85,7 +85,7 @@ public class CommandJigsawVariant implements DirectorExecutor {
@Director(description = "Set the active variant's author-facing label", sync = true,
origin = DirectorOrigin.PLAYER)
public void label(
@Param(description = "Display label; quote labels containing spaces") String displayName
@Param(name = "display-name", description = "Display label; quote labels containing spaces") String displayName
) {
CommandJigsaw.ActiveContext context = CommandJigsaw.active(player());
if (context == null) {
@@ -147,7 +147,7 @@ public class CommandJigsawVariant implements DirectorExecutor {
description = "Duplicate every enabled workcell's active variant as one coherent family",
sync = true, origin = DirectorOrigin.PLAYER)
public void duplicateFamily(
@Param(description = "Family key or next", defaultValue = "next") String themeKey
@Param(name = "theme-key", description = "Family key or next", defaultValue = "next") String themeKey
) {
CommandJigsaw.ActiveContext context = CommandJigsaw.active(player());
if (context == null) {
@@ -43,7 +43,7 @@ public class CommandJigsawWorkcell implements DirectorExecutor {
@Director(description = "Set the selected workcell's author-facing label", sync = true,
origin = DirectorOrigin.PLAYER)
public void label(
@Param(description = "Display label; quote labels containing spaces") String displayName
@Param(name = "display-name", description = "Display label; quote labels containing spaces") String displayName
) {
CommandJigsaw.ActiveContext context = CommandJigsaw.active(player());
if (context == null) {
@@ -18,6 +18,7 @@
package art.arcane.iris.command;
import art.arcane.iris.command.specialhandlers.PackFolderHandler;
import art.arcane.iris.pack.PackFingerprints;
import art.arcane.iris.Iris;
@@ -32,8 +33,10 @@ import art.arcane.iris.studio.StudioSVC;
import art.arcane.iris.world.IrisToolbelt;
import art.arcane.iris.world.lifecycle.LifecycleOperationCoordinator;
import art.arcane.iris.localization.C;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.command.handlers.DimensionHandler;
import art.arcane.iris.command.specialhandlers.PreviewApplyModeHandler;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import art.arcane.volmlib.util.director.annotations.Director;
import art.arcane.volmlib.util.director.annotations.Param;
@@ -45,8 +48,10 @@ import org.bukkit.World;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.BukkitCommandMessages;
@@ -54,6 +59,9 @@ import art.arcane.volmlib.util.localization.MessageArgument;
import art.arcane.iris.localization.BukkitRuntimeMessages;
@Director(name = "pack", aliases = {"pk"}, description = "Pack validation and maintenance", descriptionKey = "iris.director.commandpack.director.pack_validation_maintenance")
public class CommandPack implements DirectorExecutor {
private static final int PATH_REPORT_LIMIT = 10;
private static final Pattern LEADING_COLOR = Pattern.compile("^§[0-9a-fk-or]");
@Director(name = "update-world", description = "Stage an installed pack for a world and request a clean restart", descriptionKey = "iris.director.commanddeveloper.director.stage_world_generation_update")
public void updateWorld(
@Param(description = "The world to update", descriptionKey = "iris.director.commanddeveloper.param.world_update", contextual = true, contextualOverride = true)
@@ -101,7 +109,7 @@ public class CommandPack implements DirectorExecutor {
@Director(description = "Validate a pack (or all packs) and re-publish results", descriptionKey = "iris.director.commandpack.director.validate_pack_all_packs_re_publish_results", aliases = {"v"})
public void validate(
@Param(description = "The pack folder name to validate, or * for every pack", descriptionKey = "iris.director.commandpack.param.pack_folder_name_validate_leave_empty_all", defaultValue = "*")
@Param(description = "The pack folder name to validate; omit for every pack", descriptionKey = "iris.director.commandpack.param.pack_folder_name_validate_leave_empty_all", defaultValue = "*", customHandler = PackFolderHandler.class)
String pack
) {
VolmitSender s = sender();
@@ -119,13 +127,15 @@ public class CommandPack implements DirectorExecutor {
}
int broken = 0;
for (File dir : dirs) {
PackValidationResult result = runValidate(s, dir);
if (result != null && !result.isLoadable()) {
PackValidationResult result = runValidate(dir);
if (!result.isLoadable()) {
broken++;
reportResult(s, result);
}
}
persistValidationCache(packsRoot);
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_VALIDATION_COMPLETE_BROKEN_PACKS, MessageArgument.untrusted("broken", String.valueOf(broken)), MessageArgument.untrusted("value", String.valueOf(dirs.size()))));
ChatReport.Tone summaryTone = broken == 0 ? ChatReport.Tone.SUCCESS : ChatReport.Tone.ERROR;
s.sendMessage(summaryTone.paint(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_VALIDATION_COMPLETE_BROKEN_PACKS, MessageArgument.untrusted("broken", String.valueOf(broken)), MessageArgument.untrusted("value", String.valueOf(dirs.size())))));
return;
}
@@ -134,7 +144,7 @@ public class CommandPack implements DirectorExecutor {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_PACK_NOT_FOUND_UNDER_PACKS, MessageArgument.untrusted("pack", String.valueOf(pack))));
return;
}
runValidate(s, target);
reportResult(s, runValidate(target));
persistValidationCache(packsRoot);
}
@@ -152,9 +162,9 @@ public class CommandPack implements DirectorExecutor {
@Director(description = "Preview or apply unused-resource cleanup", descriptionKey = "iris.director.commandpack.director.preview_apply_unused_resource_cleanup", aliases = {"c"})
public void cleanup(
@Param(description = "The pack folder name to clean", descriptionKey = "iris.director.commandpack.param.pack_folder_name_clean")
@Param(description = "The pack folder name to clean", descriptionKey = "iris.director.commandpack.param.pack_folder_name_clean", customHandler = PackFolderHandler.class)
String pack,
@Param(description = "preview or apply", descriptionKey = "iris.director.commandpack.param.preview_apply", defaultValue = "preview")
@Param(description = "preview or apply", descriptionKey = "iris.director.commandpack.param.preview_apply", defaultValue = "preview", customHandler = PreviewApplyModeHandler.class)
String mode
) {
VolmitSender s = sender();
@@ -165,19 +175,18 @@ public class CommandPack implements DirectorExecutor {
if ("apply".equalsIgnoreCase(mode)) {
PackResourceCleanup.ApplyResult result = PackResourceCleanup.apply(packFolder);
if (!result.success()) {
s.sendMessage(IrisLanguage.text(
reportPaths(s, ChatReport.Tone.ERROR, IrisLanguage.text(
BukkitRuntimeMessages.COMMAND_PACK_CLEANUP_FAILED,
MessageArgument.untrusted("error", String.valueOf(result.error()))
));
reportPaths(s, result.quarantinedPaths(), BukkitRuntimeMessages.COMMAND_PACK_PATH_STILL_QUARANTINED);
), result.quarantinedPaths(), BukkitRuntimeMessages.COMMAND_PACK_PATH_STILL_QUARANTINED);
return;
}
if (!result.changed()) {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_NO_CLEANUP_CANDIDATES_FOUND_PACK, MessageArgument.untrusted("pack", String.valueOf(pack))));
return;
}
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_QUARANTINED_CLEANUP_CANDIDATE_S_UNDER, MessageArgument.untrusted("size", String.valueOf(result.quarantinedPaths().size())), MessageArgument.untrusted("quarantinePath", String.valueOf(result.quarantinePath()))));
reportPaths(s, result.quarantinedPaths(), BukkitRuntimeMessages.COMMAND_PACK_PATH_QUARANTINED);
reportPaths(s, ChatReport.Tone.SUCCESS, IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_QUARANTINED_CLEANUP_CANDIDATE_S_UNDER, MessageArgument.untrusted("size", String.valueOf(result.quarantinedPaths().size())), MessageArgument.untrusted("quarantinePath", String.valueOf(result.quarantinePath()))),
result.quarantinedPaths(), BukkitRuntimeMessages.COMMAND_PACK_PATH_QUARANTINED);
return;
}
if (!"preview".equalsIgnoreCase(mode)) {
@@ -196,16 +205,16 @@ public class CommandPack implements DirectorExecutor {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_NO_CLEANUP_CANDIDATES_FOUND_PACK_2, MessageArgument.untrusted("pack", String.valueOf(pack))));
return;
}
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_CLEANUP_PREVIEW_PACK_CANDIDATE_S_NO_FILES_WERE_CHANGED, MessageArgument.untrusted("pack", String.valueOf(pack)), MessageArgument.untrusted("size", String.valueOf(preview.candidatePaths().size()))));
reportPaths(s, preview.candidatePaths(), BukkitRuntimeMessages.COMMAND_PACK_PATH_CANDIDATE);
reportPaths(s, ChatReport.Tone.INFO, IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_CLEANUP_PREVIEW_PACK_CANDIDATE_S_NO_FILES_WERE_CHANGED, MessageArgument.untrusted("pack", String.valueOf(pack)), MessageArgument.untrusted("size", String.valueOf(preview.candidatePaths().size()))),
preview.candidatePaths(), BukkitRuntimeMessages.COMMAND_PACK_PATH_CANDIDATE);
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_RUN_IRIS_PACK_CLEANUP_MODE_APPLY_QUARANTINE_THESE_CANDIDATES_AFTER_FRESH_SCAN, MessageArgument.untrusted("pack", String.valueOf(pack))));
}
@Director(description = "Preview or apply restoration of the latest quarantine", descriptionKey = "iris.director.commandpack.director.preview_apply_restoration_latest_quarantine", aliases = {"r"})
public void restore(
@Param(description = "The pack folder name to restore", descriptionKey = "iris.director.commandpack.param.pack_folder_name_restore")
@Param(description = "The pack folder name to restore", descriptionKey = "iris.director.commandpack.param.pack_folder_name_restore", customHandler = PackFolderHandler.class)
String pack,
@Param(description = "preview or apply", descriptionKey = "iris.director.commandpack.param.preview_apply_2", defaultValue = "preview")
@Param(description = "preview or apply", descriptionKey = "iris.director.commandpack.param.preview_apply_2", defaultValue = "preview", customHandler = PreviewApplyModeHandler.class)
String mode
) {
VolmitSender s = sender();
@@ -216,8 +225,8 @@ public class CommandPack implements DirectorExecutor {
if ("apply".equalsIgnoreCase(mode)) {
PackResourceCleanup.RestoreResult result = PackResourceCleanup.restoreLatest(packFolder);
if (!result.conflicts().isEmpty()) {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_RESTORE_REFUSED_BECAUSE_DESTINATION_S_ALREADY_EXIST, MessageArgument.untrusted("size", String.valueOf(result.conflicts().size()))));
reportPaths(s, result.conflicts(), BukkitRuntimeMessages.COMMAND_PACK_PATH_CONFLICT);
reportPaths(s, ChatReport.Tone.ERROR, IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_RESTORE_REFUSED_BECAUSE_DESTINATION_S_ALREADY_EXIST, MessageArgument.untrusted("size", String.valueOf(result.conflicts().size()))),
result.conflicts(), BukkitRuntimeMessages.COMMAND_PACK_PATH_CONFLICT);
return;
}
if (!result.success()) {
@@ -231,8 +240,8 @@ public class CommandPack implements DirectorExecutor {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_NOTHING_RESTORE_PACK, MessageArgument.untrusted("pack", String.valueOf(pack))));
return;
}
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_RESTORED_FILE_S_FROM, MessageArgument.untrusted("size", String.valueOf(result.restoredPaths().size())), MessageArgument.untrusted("dumpPath", String.valueOf(result.dumpPath()))));
reportPaths(s, result.restoredPaths(), BukkitRuntimeMessages.COMMAND_PACK_PATH_RESTORED);
reportPaths(s, ChatReport.Tone.SUCCESS, IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_RESTORED_FILE_S_FROM, MessageArgument.untrusted("size", String.valueOf(result.restoredPaths().size())), MessageArgument.untrusted("dumpPath", String.valueOf(result.dumpPath()))),
result.restoredPaths(), BukkitRuntimeMessages.COMMAND_PACK_PATH_RESTORED);
return;
}
if (!"preview".equalsIgnoreCase(mode)) {
@@ -251,11 +260,11 @@ public class CommandPack implements DirectorExecutor {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_NOTHING_RESTORE_PACK_2, MessageArgument.untrusted("pack", String.valueOf(pack))));
return;
}
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_RESTORE_PREVIEW_FILE_S_NO_FILES_WERE_CHANGED, MessageArgument.untrusted("dumpPath", String.valueOf(preview.dumpPath())), MessageArgument.untrusted("size", String.valueOf(preview.filePaths().size()))));
reportPaths(s, preview.filePaths(), BukkitRuntimeMessages.COMMAND_PACK_PATH_FILE);
reportPaths(s, ChatReport.Tone.INFO, IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_RESTORE_PREVIEW_FILE_S_NO_FILES_WERE_CHANGED, MessageArgument.untrusted("dumpPath", String.valueOf(preview.dumpPath())), MessageArgument.untrusted("size", String.valueOf(preview.filePaths().size()))),
preview.filePaths(), BukkitRuntimeMessages.COMMAND_PACK_PATH_FILE);
if (!preview.conflicts().isEmpty()) {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_RESTORE_IS_BLOCKED_BY_EXISTING_DESTINATION_S, MessageArgument.untrusted("size", String.valueOf(preview.conflicts().size()))));
reportPaths(s, preview.conflicts(), BukkitRuntimeMessages.COMMAND_PACK_PATH_CONFLICT);
reportPaths(s, ChatReport.Tone.ERROR, IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_RESTORE_IS_BLOCKED_BY_EXISTING_DESTINATION_S, MessageArgument.untrusted("size", String.valueOf(preview.conflicts().size()))),
preview.conflicts(), BukkitRuntimeMessages.COMMAND_PACK_PATH_CONFLICT);
return;
}
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_RUN_IRIS_PACK_RESTORE_MODE_APPLY_RESTORE_AFTER_FRESH_CONFLICT_CHECK, MessageArgument.untrusted("pack", String.valueOf(pack))));
@@ -263,7 +272,7 @@ public class CommandPack implements DirectorExecutor {
@Director(description = "Show cached validation status for a pack", descriptionKey = "iris.director.commandpack.director.show_cached_validation_status_pack", aliases = {"s"})
public void status(
@Param(description = "The pack folder name, or * for every pack", descriptionKey = "iris.director.commandpack.param.pack_folder_name", defaultValue = "*")
@Param(description = "The pack folder name; omit for every pack", descriptionKey = "iris.director.commandpack.param.pack_folder_name", defaultValue = "*", customHandler = PackFolderHandler.class)
String pack
) {
VolmitSender s = sender();
@@ -272,17 +281,13 @@ public class CommandPack implements DirectorExecutor {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_NO_VALIDATION_RESULTS_RECORDED_RUN_IRIS_PACK_VALIDATE_FIRST));
return;
}
PackValidationRegistry.snapshot().forEach((name, result) -> {
TextKey key = result.isLoadable()
? BukkitRuntimeMessages.COMMAND_PACK_STATUS_OK
: BukkitRuntimeMessages.COMMAND_PACK_STATUS_BROKEN;
s.sendMessage(IrisLanguage.text(
key,
MessageArgument.untrusted("pack", name),
MessageArgument.trusted("blocking", result.getBlockingErrors().size()),
MessageArgument.trusted("warnings", result.getWarnings().size())
));
});
ChatReport.Builder report = ChatReport.of(ChatReport.Tone.INFO, "Pack validation status").unlimited();
PackValidationRegistry.snapshot().entrySet().stream()
.sorted(Comparator.comparing((Map.Entry<String, PackValidationResult> entry) -> statusTone(entry.getValue()).ordinal())
.reversed()
.thenComparing(Map.Entry::getKey))
.forEach(entry -> report.styledItem(statusLine(entry.getKey(), entry.getValue())));
s.sendReport(report.build());
return;
}
PackValidationResult result = PackValidationRegistry.get(pack);
@@ -295,7 +300,7 @@ public class CommandPack implements DirectorExecutor {
@Director(description = "Show pack content that cannot generate on this Minecraft version", descriptionKey = "iris.director.commandpack.director.show_content_cannot_generate_this_minecraft_version", aliases = {"cp"})
public void compat(
@Param(description = "The pack folder name to report on, or * for every pack", descriptionKey = "iris.director.commandpack.param.pack_folder_name_compat", defaultValue = "*")
@Param(description = "The pack folder name to report on; omit for every pack", descriptionKey = "iris.director.commandpack.param.pack_folder_name_compat", defaultValue = "*", customHandler = PackFolderHandler.class)
String pack
) {
VolmitSender s = sender();
@@ -306,15 +311,11 @@ public class CommandPack implements DirectorExecutor {
return;
}
for (Map.Entry<String, PackValidationResult> entry : snapshot.entrySet()) {
for (String line : compatOutput(entry.getKey(), entry.getValue())) {
s.sendMessage(line);
}
s.sendReport(compatReport(entry.getKey(), entry.getValue()));
}
return;
}
for (String line : compatOutput(pack, PackValidationRegistry.get(pack))) {
s.sendMessage(line);
}
s.sendReport(compatReport(pack, PackValidationRegistry.get(pack)));
}
/**
@@ -322,33 +323,31 @@ public class CommandPack implements DirectorExecutor {
* printed with every subject; the boot listing is the capped form of the same data.
*/
static List<String> compatOutput(String pack, PackValidationResult result) {
List<String> lines = new ArrayList<>();
return compatReport(pack, result).lines().stream().map(ChatReport.Line::text).toList();
}
static ChatReport compatReport(String pack, PackValidationResult result) {
if (result == null) {
lines.add(IrisLanguage.text(
return ChatReport.of(ChatReport.Tone.WARNING, IrisLanguage.text(
BukkitRuntimeMessages.COMMAND_PACK_NO_VALIDATION_RESULT_RUN_IRIS_PACK_VALIDATE,
MessageArgument.untrusted("pack", String.valueOf(pack)),
MessageArgument.untrusted("pack2", String.valueOf(pack))));
return lines;
MessageArgument.untrusted("pack2", String.valueOf(pack)))).build();
}
String version = compatVersion(result);
if (result.getCompatFindings().isEmpty()) {
lines.add(IrisLanguage.text(
return ChatReport.of(ChatReport.Tone.SUCCESS, IrisLanguage.text(
BukkitRuntimeMessages.COMMAND_PACK_COMPAT_NONE,
MessageArgument.untrusted("pack", pack),
MessageArgument.untrusted("version", version)));
return lines;
MessageArgument.untrusted("version", version))).build();
}
lines.add(IrisLanguage.text(
BukkitRuntimeMessages.COMMAND_PACK_COMPAT_HEADER,
MessageArgument.untrusted("pack", pack),
MessageArgument.untrusted("version", version)));
for (String line : PackCompatReport.of(result.getCompatFindings()).keyLines(0)) {
lines.add(IrisLanguage.text(
BukkitRuntimeMessages.COMMAND_PACK_MESSAGE_2,
MessageArgument.untrusted("value", line)));
}
lines.add(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_COMPAT_REMEDY));
return lines;
return ChatReport.of(ChatReport.Tone.WARNING, IrisLanguage.text(
BukkitRuntimeMessages.COMMAND_PACK_COMPAT_HEADER,
MessageArgument.untrusted("pack", pack),
MessageArgument.untrusted("version", version)))
.items(PackCompatReport.of(result.getCompatFindings()).keyLines(0))
.unlimited()
.hint(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_COMPAT_REMEDY), null)
.build();
}
/** The live Minecraft version, falling back to the one the validation ran against. */
@@ -363,7 +362,7 @@ public class CommandPack implements DirectorExecutor {
return persisted == null || persisted.isBlank() ? "unknown" : persisted;
}
PackValidationResult runValidate(VolmitSender s, File packFolder) {
PackValidationResult runValidate(File packFolder) {
PackValidationRegistry.ValidationTicket ticket =
PackValidationRegistry.tryBeginValidation(packFolder.toPath());
PackValidationResult result;
@@ -399,7 +398,6 @@ public class CommandPack implements DirectorExecutor {
result = new PackValidationResult(packFolder.getName(),
List.of("Pack content changed during validation."), List.of(), System.currentTimeMillis());
}
reportResult(s, result);
return result;
}
@@ -443,24 +441,46 @@ public class CommandPack implements DirectorExecutor {
}
private void reportResult(VolmitSender s, PackValidationResult result) {
if (result.isLoadable()) {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_PACK_IS_LOADABLE_WARNINGS, MessageArgument.untrusted("packName", String.valueOf(result.getPackName())), MessageArgument.untrusted("size", String.valueOf(result.getWarnings().size()))));
} else {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_PACK_IS_BROKEN, MessageArgument.untrusted("packName", String.valueOf(result.getPackName()))));
for (String reason : result.getBlockingErrors()) {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_MESSAGE, MessageArgument.untrusted("reason", String.valueOf(reason))));
}
}
int wMax = Math.min(10, result.getWarnings().size());
for (int i = 0; i < wMax; i++) {
s.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_MESSAGE_2, MessageArgument.untrusted("value", String.valueOf(result.getWarnings().get(i)))));
}
if (result.getWarnings().size() > wMax) {
s.sendMessage(IrisLanguage.text(
BukkitRuntimeMessages.COMMAND_PACK_MORE_WARNING_S,
MessageArgument.trusted("count", result.getWarnings().size() - wMax)
));
s.sendReport(validationReport(result));
}
private static String statusLine(String name, PackValidationResult result) {
TextKey key = result.isLoadable()
? BukkitRuntimeMessages.COMMAND_PACK_STATUS_OK
: BukkitRuntimeMessages.COMMAND_PACK_STATUS_BROKEN;
String line = IrisLanguage.text(
key,
MessageArgument.trusted("pack", C.WHITE + ChatReport.clean(name)),
MessageArgument.trusted("blocking", statusCount(result.getBlockingErrors().size(), C.RED)),
MessageArgument.trusted("warnings", statusCount(result.getWarnings().size(), C.GOLD)));
return LEADING_COLOR.matcher(line).replaceFirst(statusTone(result).color().toString());
}
private static ChatReport.Tone statusTone(PackValidationResult result) {
return !result.isLoadable() ? ChatReport.Tone.ERROR
: result.getWarnings().isEmpty() ? ChatReport.Tone.SUCCESS : ChatReport.Tone.WARNING;
}
private static String statusCount(int count, C color) {
return (count == 0 ? C.DARK_GRAY : color) + String.valueOf(count) + C.GRAY;
}
static ChatReport validationReport(PackValidationResult result) {
String packName = String.valueOf(result.getPackName());
if (!result.isLoadable()) {
String revalidate = "/iris pack validate " + packName;
return ChatReport.of(ChatReport.Tone.ERROR, IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_PACK_IS_BROKEN,
MessageArgument.untrusted("packName", packName)))
.items(result.getBlockingErrors())
.hint("Fix the pack, then run " + revalidate, revalidate)
.build();
}
ChatReport.Tone tone = result.getWarnings().isEmpty() ? ChatReport.Tone.SUCCESS : ChatReport.Tone.WARNING;
return ChatReport.of(tone, IrisLanguage.text(BukkitRuntimeMessages.COMMAND_PACK_PACK_IS_LOADABLE_WARNINGS,
MessageArgument.untrusted("packName", packName),
MessageArgument.untrusted("size", String.valueOf(result.getWarnings().size()))))
.items(result.getWarnings())
.build();
}
private File findPack(VolmitSender sender, String pack) {
@@ -476,17 +496,12 @@ public class CommandPack implements DirectorExecutor {
return packFolder;
}
private void reportPaths(VolmitSender sender, List<String> paths, TextKey label) {
int max = Math.min(10, paths.size());
for (int i = 0; i < max; i++) {
sender.sendMessage(IrisLanguage.text(
BukkitCommandMessages.COMMAND_PACK_MESSAGE,
MessageArgument.untrusted("label", IrisLanguage.text(label)),
MessageArgument.untrusted("value", paths.get(i))
));
}
if (paths.size() > max) {
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_PACK_MORE, MessageArgument.untrusted("value", (paths.size() - max))));
private void reportPaths(VolmitSender sender, ChatReport.Tone tone, String header, List<String> paths, TextKey label) {
ChatReport.Builder report = ChatReport.of(tone, header).limit(PATH_REPORT_LIMIT);
String labelText = IrisLanguage.plain(label);
for (String path : paths) {
report.entry(labelText, path);
}
sender.sendReport(report.build());
}
}
@@ -26,6 +26,7 @@ import art.arcane.iris.world.IrisToolbelt;
import art.arcane.volmlib.util.director.annotations.Director;
import art.arcane.volmlib.util.director.annotations.Param;
import art.arcane.iris.localization.C;
import art.arcane.iris.localization.ChatReport;
import art.arcane.volmlib.util.format.Form;
import art.arcane.volmlib.util.math.Position2;
import org.bukkit.World;
@@ -82,9 +83,13 @@ public class CommandPregen implements DirectorExecutor {
} else {
IrisToolbelt.pregenerate(task, world);
}
String msg = C.GREEN + "Pregen started in " + C.GOLD + world.getName() + C.GREEN + " of " + C.GOLD + (radius * 2) + C.GREEN + " by " + C.GOLD + (radius * 2) + C.GREEN + " blocks from " + C.GOLD + center.getX() + "," + center.getZ();
String msg = C.GRAY + "Pregen started in " + ChatReport.highlight(world.getName())
+ " over " + ChatReport.highlight((radius * 2) + "×" + (radius * 2)) + " blocks around "
+ ChatReport.highlight(center.getBlockX() + ", " + center.getBlockZ());
sender().sendMessage(msg);
Iris.info(msg);
if (sender().isPlayer()) {
Iris.info(msg);
}
} catch (Throwable e) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_PREGEN_FAILED_START_PREGENERATION_SEE_CONSOLE_DETAILS));
Iris.reportError(e);
@@ -94,9 +99,11 @@ public class CommandPregen implements DirectorExecutor {
@Director(description = "Stop the active pregeneration task", descriptionKey = "iris.director.commandpregen.director.stop_active_pregeneration_task", aliases = "x")
public void stop() {
if (PregeneratorJob.shutdownInstance()) {
String message = C.BLUE + "Pregen stop requested; finishing active work before cancellation.";
sender().sendMessage(message);
Iris.info(message);
String message = "Pregen stop requested; finishing active work before cancellation.";
sender().sendInfo(message);
if (sender().isPlayer()) {
Iris.info(message);
}
} else {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_PREGEN_NO_ACTIVE_PREGENERATION_TASKS_STOP));
}
@@ -120,8 +127,10 @@ public class CommandPregen implements DirectorExecutor {
}
String world = progress.worldName() == null ? "?" : progress.worldName();
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_PREGEN_PREGEN, MessageArgument.untrusted("world", world), MessageArgument.untrusted("value", Form.f(progress.generated())), MessageArgument.untrusted("value2", Form.f(progress.totalChunks())), MessageArgument.untrusted("value3", String.format("%.1f", progress.percent())), MessageArgument.untrusted("value4", (progress.paused() ? C.YELLOW + " PAUSED" : ""))));
sender().sendMessage(IrisLanguage.text(
ChatReport.Tone tone = progress.failed() > 0 ? ChatReport.Tone.WARNING
: progress.paused() ? ChatReport.Tone.INFO : ChatReport.Tone.SUCCESS;
String headline = IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_PREGEN_PREGEN, MessageArgument.untrusted("world", world), MessageArgument.untrusted("value", Form.f(progress.generated())), MessageArgument.untrusted("value2", Form.f(progress.totalChunks())), MessageArgument.untrusted("value3", String.format("%.1f", progress.percent())), MessageArgument.untrusted("value4", (progress.paused() ? " PAUSED" : "")));
sender().sendReport(ChatReport.of(tone, headline).item(IrisLanguage.text(
BukkitCommandMessagesExtended.COMMAND_PREGEN_SPEED_S_ETA_ELAPSED_METHOD,
MessageArgument.untrusted("overall", Form.f(progress.overallChunksPerSecond(), 1)),
MessageArgument.untrusted("tenSecond", Form.f(progress.chunksPerSecond(), 1)),
@@ -130,6 +139,6 @@ public class CommandPregen implements DirectorExecutor {
MessageArgument.untrusted("eta", Form.duration(progress.eta(), 2)),
MessageArgument.untrusted("elapsed", Form.duration(progress.elapsed(), 2)),
MessageArgument.untrusted("method", progress.method()),
MessageArgument.untrusted("failures", progress.failed() > 0 ? C.RED + " Failed: " + Form.f(progress.failed()) : "")));
MessageArgument.untrusted("failures", progress.failed() > 0 ? " Failed: " + Form.f(progress.failed()) : ""))).build());
}
}
@@ -22,6 +22,7 @@ import art.arcane.iris.Iris;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.localization.C;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.platform.bukkit.plugin.IrisService;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import art.arcane.iris.world.task.J;
@@ -190,7 +191,7 @@ public class CommandSVC implements IrisService, CommandExecutor, TabCompleter, D
}
if (!(args.length > 1 && args[0].equalsIgnoreCase("debug") && args[1].equalsIgnoreCase("dump"))
&& !sender.hasPermission(ROOT_PERMISSION)) {
ComponentMessenger.sendSection(sender, IrisLanguage.text(
sendTaggedError(sender, IrisLanguage.text(
IrisMessages.COMMAND_PERMISSION_DENIED,
MessageArgument.trusted("permission", ROOT_PERMISSION)
));
@@ -200,6 +201,11 @@ public class CommandSVC implements IrisService, CommandExecutor, TabCompleter, D
J.aBukkit(() -> executeCommand(sender, label, args));
}
private static void sendTaggedError(CommandSender sender, String message) {
String tag = Iris.instance == null ? "" : Iris.instance.getTag();
ComponentMessenger.sendSection(sender, tag + ChatReport.Tone.ERROR.paint(message));
}
public List<String> tabCompleteRoot(CommandSender sender, String alias, String[] args) {
List<String> suggestions = args.length > 0 && args[0].equalsIgnoreCase("language")
? Iris.instance.completeLanguage(sender, Arrays.copyOfRange(args, 1, args.length))
@@ -349,10 +355,11 @@ public class CommandSVC implements IrisService, CommandExecutor, TabCompleter, D
return sender instanceof Player;
}
/** The director only reports parse and execution failures here, so they get the error style. */
@Override
public void sendMessage(String message) {
if (message != null && !message.trim().isEmpty()) {
ComponentMessenger.sendLiteral(sender, message);
sendTaggedError(sender, message);
}
}
}
@@ -18,6 +18,7 @@
package art.arcane.iris.command;
import art.arcane.iris.command.specialhandlers.IrisStructureHandler;
import art.arcane.iris.Iris;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.structure.BulkStructureImporter;
@@ -42,6 +43,7 @@ import art.arcane.iris.structure.nativegen.NativeStructureGenerationStatus;
import art.arcane.iris.structure.object.ObjectPlaceMode;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.iris.localization.C;
import art.arcane.iris.localization.ChatReport;
import art.arcane.volmlib.util.director.DirectorOrigin;
import art.arcane.volmlib.util.director.annotations.Director;
import art.arcane.volmlib.util.director.annotations.Param;
@@ -61,11 +63,13 @@ import org.bukkit.entity.Player;
import org.bukkit.generator.structure.Structure;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.BukkitCommandMessages;
@@ -73,6 +77,9 @@ import art.arcane.volmlib.util.localization.MessageArgument;
import art.arcane.iris.localization.BukkitCommandMessagesExtended;
@Director(name = "structure", aliases = {"struct", "str"}, description = "Iris structure tools (index, import, info)", descriptionKey = "iris.director.commandstructure.director.iris_structure_tools_index_import_info")
public class CommandStructure implements DirectorExecutor {
private static final int VERIFY_ITEM_LIMIT = 15;
private static final int UNREACHABLE_BIOMES_SHOWN = 3;
private static final String VANILLA_NAMESPACE = "minecraft:";
@Director(description = "Regenerate structure-index.json listing all vanilla, datapack & iris structures", descriptionKey = "iris.director.commandstructure.director.regenerate_structure_index_json_listing_all_vanilla_datapack_iris_structures", aliases = {"ls"}, origin = DirectorOrigin.BOTH)
public void list(
@Param(description = "The dimension whose pack to index", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_index", aliases = "dim")
@@ -171,7 +178,6 @@ public class CommandStructure implements DirectorExecutor {
private void runVerification(Engine engine, KList<String> structureKeys, int centerX, int centerZ,
int searchRadius, VolmitSender commandSender, Player target) {
KList<String> messages = new KList<>();
Map<String, IrisNativeStructureDecision> decisions = new HashMap<>(structureKeys.size());
boolean requiresNativeReachability = false;
for (String keyName : structureKeys) {
@@ -185,8 +191,8 @@ public class CommandStructure implements DirectorExecutor {
try {
reachable = StructureReachability.reachableKeys(engine);
} catch (Throwable error) {
messages.add(C.RED + "Structure verification could not resolve native biome reachability.");
sendVerificationMessages(commandSender, target, messages);
sendVerificationReport(commandSender, target, ChatReport.of(ChatReport.Tone.ERROR,
"Structure verification could not resolve native biome reachability").build());
Iris.reportError("Could not resolve native structure biome reachability for verification.", error);
return;
}
@@ -197,6 +203,9 @@ public class CommandStructure implements DirectorExecutor {
int unreachable = 0;
int searchLimited = 0;
int errors = 0;
List<String> problems = new ArrayList<>();
List<String> planned = new ArrayList<>();
List<String> unreachableLines = new ArrayList<>();
for (String keyName : structureKeys) {
IrisNativeStructureDecision decision = decisions.get(keyName);
if (IrisStructureLocator.isPlaced(engine, keyName)) {
@@ -205,56 +214,81 @@ public class CommandStructure implements DirectorExecutor {
IrisStructureLocator.locate(engine, keyName, centerX, centerZ, searchRadius);
if (result.status() == IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED) {
searchLimited++;
messages.add(C.YELLOW + "[iris-search-limit] " + C.WHITE + keyName + C.YELLOW
+ ": unable to complete the density search before its safety limit was reached");
problems.add(verifyLine(C.GOLD, keyName, "density search hit its safety limit"));
continue;
}
if (!result.found()) {
messages.add(C.YELLOW + "[iris-not-found] " + C.WHITE + keyName);
problems.add(verifyLine(C.GOLD, keyName, "not found in range"));
continue;
}
located++;
messages.add(C.AQUA + "[iris-planned] " + C.WHITE + keyName + C.GREEN + " @ "
+ result.originX() + "," + result.baseY() + "," + result.originZ());
planned.add(verifyLine(C.IRIS, keyName,
result.originX() + ", " + result.baseY() + ", " + result.originZ()));
} catch (Throwable error) {
errors++;
messages.add(C.RED + "[error] " + C.WHITE + keyName + C.RED + ": "
+ error.getClass().getSimpleName());
problems.add(verifyLine(C.RED, keyName, error.getClass().getSimpleName()));
Iris.reportError("Could not verify Iris-placed structure '" + keyName + "'.", error);
}
continue;
}
if (!decision.generate()) {
disabled++;
messages.add(C.GRAY + "[disabled] " + C.WHITE + keyName);
continue;
}
if (!reachable.contains(keyName.toLowerCase(Locale.ROOT))) {
unreachable++;
KList<String> missing = StructureReachability.missingBiomeKeys(engine, keyName);
messages.add(C.YELLOW + "[unreachable] " + C.WHITE + keyName
+ (missing.isEmpty() ? "" : C.YELLOW + " needs " + String.join("/", missing)));
unreachableLines.add(unreachableLine(keyName, StructureReachability.missingBiomeKeys(engine, keyName)));
continue;
}
nativeEligible++;
messages.add(C.GREEN + "[native-eligible] " + C.WHITE + keyName);
}
messages.add(C.GREEN + "Structure verify: " + C.WHITE + located + C.GREEN + " Iris placement plans found, "
+ C.WHITE + nativeEligible + C.GREEN + " native structures eligible, "
+ C.WHITE + disabled + C.GREEN + " disabled by policy, "
+ C.WHITE + unreachable + C.GREEN + " biome-unreachable, "
+ C.WHITE + searchLimited + C.GREEN + " density searches safety-limited, "
+ C.WHITE + errors + C.GREEN + " errors. Native eligibility is checked without running blocking live locates.");
sendVerificationMessages(commandSender, target, messages);
ChatReport.Tone tone = errors > 0 ? ChatReport.Tone.ERROR
: problems.isEmpty() ? ChatReport.Tone.SUCCESS : ChatReport.Tone.WARNING;
ChatReport.Builder report = ChatReport.of(tone, "Structure verify").limit(VERIFY_ITEM_LIMIT);
report.styledItem(String.join(C.DARK_GRAY + " · ", List.of(
verifyCount(located, "planned", C.IRIS),
verifyCount(nativeEligible, "native", C.AQUA),
verifyCount(problems.size() - errors - searchLimited, "not found", C.GOLD),
verifyCount(searchLimited, "search-limited", C.GOLD),
verifyCount(errors, "errors", C.RED),
verifyCount(unreachable, "unreachable", C.GRAY),
verifyCount(disabled, "disabled", C.GRAY))
.stream().filter(count -> !count.isEmpty()).toList()));
problems.forEach(report::styledItem);
planned.forEach(report::styledItem);
unreachableLines.forEach(report::styledItem);
report.hint("Unreachable: no biome in this dimension can place it. Native eligibility is checked without blocking locates.", null);
sendVerificationReport(commandSender, target, report.build());
}
private void sendVerificationMessages(VolmitSender commandSender, Player target,
KList<String> messages) {
Runnable send = () -> {
for (String message : messages) {
commandSender.sendMessage(message);
}
};
private static String verifyLine(C accent, String keyName, String detail) {
return C.WHITE + structureName(keyName) + C.DARK_GRAY + " " + accent + ChatReport.clean(detail);
}
private static String verifyCount(int count, String label, C color) {
return count == 0 ? "" : color.toString() + count + C.GRAY + " " + label;
}
private static String unreachableLine(String keyName, List<String> missingBiomes) {
String name = C.GRAY + structureName(keyName) + C.DARK_GRAY + " ";
if (missingBiomes.isEmpty()) {
return name + "no biome can place it";
}
int shown = Math.min(UNREACHABLE_BIOMES_SHOWN, missingBiomes.size());
String biomes = missingBiomes.subList(0, shown).stream()
.map(CommandStructure::structureName)
.collect(Collectors.joining(C.DARK_GRAY + ", " + C.GRAY, C.GRAY.toString(), ""));
int hidden = missingBiomes.size() - shown;
return name + "needs " + biomes + (hidden > 0 ? C.DARK_GRAY + " +" + hidden + " more" : "");
}
private static String structureName(String key) {
String cleaned = ChatReport.clean(key);
return cleaned.startsWith(VANILLA_NAMESPACE) ? cleaned.substring(VANILLA_NAMESPACE.length()) : cleaned;
}
private void sendVerificationReport(VolmitSender commandSender, Player target, ChatReport report) {
Runnable send = () -> commandSender.sendReport(report);
if (target != null) {
J.runEntity(target, send);
} else {
@@ -293,7 +327,7 @@ public class CommandStructure implements DirectorExecutor {
public void info(
@Param(description = "The dimension whose pack holds the structure", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_holds_structure", aliases = "dim")
IrisDimension dimension,
@Param(description = "The iris structure key to inspect", descriptionKey = "iris.director.commandstructure.param.iris_structure_key_inspect")
@Param(description = "The iris structure key to inspect", descriptionKey = "iris.director.commandstructure.param.iris_structure_key_inspect", customHandler = IrisStructureHandler.class)
String structure
) {
IrisData data = dimension.getLoader();
@@ -331,7 +365,7 @@ public class CommandStructure implements DirectorExecutor {
public void place(
@Param(description = "The dimension whose pack holds the structure", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_holds_structure_2", aliases = "dim")
IrisDimension dimension,
@Param(description = "The iris structure key to place", descriptionKey = "iris.director.commandstructure.param.iris_structure_key_place")
@Param(description = "The iris structure key to place", descriptionKey = "iris.director.commandstructure.param.iris_structure_key_place", customHandler = IrisStructureHandler.class)
String structure
) {
IrisData data = dimension.getLoader();
@@ -28,12 +28,16 @@ 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.localization.RuntimeUiMessages;
import art.arcane.iris.localization.RuntimeProgressMessages;
import art.arcane.iris.platform.bukkit.BoardSVC;
import art.arcane.iris.studio.StudioSVC;
import art.arcane.iris.structure.BulkStructureImporter;
import art.arcane.iris.structure.FeatureImporter;
import art.arcane.iris.structure.StructureImporter;
import art.arcane.iris.world.IrisToolbelt;
import art.arcane.iris.world.runtime.InPlaceChunkRegenerator;
import art.arcane.iris.generation.runtime.DimensionStackContext;
import art.arcane.iris.generation.runtime.DimensionStackLayout;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.world.loot.InventorySlotType;
import art.arcane.iris.generation.biome.IrisBiome;
@@ -59,6 +63,7 @@ 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 art.arcane.iris.localization.ChatReport;
import art.arcane.volmlib.util.format.Form;
import art.arcane.volmlib.util.function.NoiseProvider;
import art.arcane.volmlib.util.interpolation.InterpolationMethod;
@@ -94,11 +99,13 @@ import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import art.arcane.iris.localization.IrisLanguage;
@@ -109,9 +116,15 @@ import art.arcane.iris.localization.BukkitCommandMessagesExtended;
@Director(name = "studio", aliases = {"std", "s"}, description = "Studio Commands", descriptionKey = "iris.director.commandstudio.director.studio_commands")
public class CommandStudio implements DirectorExecutor {
private static final long CHUNK_SCAN_TIMEOUT_MS = 3_000;
private static final String REGEN_STOP_COMMAND = "/iris std regen-stop";
private CommandEdit edit;
//private CommandDeepSearch deepSearch;
private static String regionShareLine(String region, int rarity, double share) {
return C.WHITE + ChatReport.clean(region) + C.DARK_GRAY + ": " + C.IRIS + Form.pc(share, 1)
+ C.DARK_GRAY + " · " + C.GRAY + "rarity " + rarity;
}
public static String hrf(Duration duration) {
return duration.toString().substring(2).replaceAll("(\\d[HMS])(?!$)", "$1 ").toLowerCase();
}
@@ -124,7 +137,6 @@ public class CommandStudio implements DirectorExecutor {
long seed,
@Param(defaultValue = "false", description = "Attempt to open Studio before a required registry restart", aliases = "f")
boolean force) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_STUDIO_PACK_SEED, MessageArgument.untrusted("value", dimension.getName()), MessageArgument.untrusted("seed", seed)));
Iris.service(StudioSVC.class).open(sender(), seed, dimension.getLoadKey(), force);
}
@@ -220,6 +232,88 @@ public class CommandStudio implements DirectorExecutor {
LanguageAudience.run(audience, () -> sendHotloadResult(commandSender, failure)));
}
@Director(name = "regen", aliases = {"rg"}, description = "Delete and regenerate nearby chunks in place using Iris generation", descriptionKey = "iris.director.commanddeveloper.director.delete_regenerate_nearby_chunks_place_using_iris_generation", origin = DirectorOrigin.PLAYER)
public void regen(
@Param(name = "radius", description = "The radius of nearby chunks", descriptionKey = "iris.director.commanddeveloper.param.radius_nearby_chunks", defaultValue = "5")
int radius
) {
if (radius < 0) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_RADIUS_MUST_BE_0_GREATER_2));
return;
}
Player player = player();
VolmitSender commandSender = sender();
World world = player.getWorld();
if (!IrisToolbelt.isIrisWorld(world)) {
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_YOU_MUST_BE_IRIS_WORLD_USE_REGEN));
return;
}
Engine engine = IrisToolbelt.access(world).getEngine();
if (engine == null) {
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_ENGINE_ACCESS_THIS_WORLD_IS_NULL_GENERATE_NEARBY_CHUNKS_FIRST));
return;
}
int chunks = (radius * 2 + 1) * (radius * 2 + 1);
// The player position must be read on the thread owning the player; the regenerator hops per chunk itself.
if (!J.runEntity(player, () -> {
int centerX = player.getLocation().getBlockX() >> 4;
int centerZ = player.getLocation().getBlockZ() >> 4;
InPlaceChunkRegenerator regenerator = new InPlaceChunkRegenerator(world, engine, commandSender, centerX, centerZ, radius);
if (!regenerator.start()) {
InPlaceChunkRegenerator.activeIn(world).ifPresent(running -> sendRegenAlreadyRunning(commandSender, world, running));
return;
}
String started = IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_DEVELOPER_REGEN_STARTED_CHUNK_S_AROUND_DELETING_REGENERATING_PLACE, MessageArgument.untrusted("chunks", chunks), MessageArgument.untrusted("centerX", centerX), MessageArgument.untrusted("centerZ", centerZ));
commandSender.sendReport(withRegenStopHint(ChatReport.of(ChatReport.Tone.INFO, started), world).build());
Iris.info("Regen run start: world=" + world.getName()
+ " center=" + centerX + "," + centerZ
+ " radius=" + radius
+ " chunks=" + chunks);
})) {
Iris.warn("Could not schedule regen on the thread owning " + player.getName() + ".");
}
}
@Director(name = "regen-stop", aliases = {"rgstop"}, description = "Stop the regen running in a world", descriptionKey = "iris.director.commanddeveloper.director.stop_regen_running_world", origin = DirectorOrigin.BOTH)
public void regenStop(
@Param(description = "The world whose regen to stop", descriptionKey = "iris.director.commanddeveloper.param.world_regen_stop", contextual = true, contextualOverride = true)
World world
) {
String regenTitle = IrisLanguage.text(RuntimeProgressMessages.CHUNK_TITLE_REGEN);
Optional<InPlaceChunkRegenerator> running = world == null ? Optional.empty() : InPlaceChunkRegenerator.activeIn(world);
if (running.isEmpty()) {
sender().sendInfo(IrisLanguage.text(RuntimeProgressMessages.CHUNK_NONE_RUNNING,
MessageArgument.trusted("title", regenTitle),
MessageArgument.untrusted("world", world == null ? "?" : world.getName())));
return;
}
running.get().requestStop();
sender().sendWarning(IrisLanguage.text(RuntimeProgressMessages.CHUNK_STOPPING,
MessageArgument.trusted("title", regenTitle),
MessageArgument.untrusted("world", world.getName())));
}
private static void sendRegenAlreadyRunning(VolmitSender sender, World world, InPlaceChunkRegenerator running) {
String alreadyRunning = IrisLanguage.text(RuntimeProgressMessages.CHUNK_ALREADY_RUNNING,
MessageArgument.trusted("title", IrisLanguage.text(RuntimeProgressMessages.CHUNK_TITLE_REGEN)),
MessageArgument.untrusted("world", world.getName()),
MessageArgument.trusted("applied", running.appliedChunks()),
MessageArgument.trusted("total", running.totalChunks() <= 0 ? "?" : running.totalChunks()));
sender.sendReport(withRegenStopHint(ChatReport.of(ChatReport.Tone.WARNING, alreadyRunning), world).build());
}
private static ChatReport.Builder withRegenStopHint(ChatReport.Builder report, World world) {
String hint = IrisLanguage.text(RuntimeProgressMessages.CHUNK_STOP_HINT, MessageArgument.untrusted("command", REGEN_STOP_COMMAND));
return report.hint(hint, REGEN_STOP_COMMAND, REGEN_STOP_COMMAND + " world=" + world.getName());
}
@Director(description = "Toggle your Studio debug scoreboard", descriptionKey = "iris.director.commandstudio.director.toggle_your_studio_debug_scoreboard", aliases = {"board", "sidebar", "sb"}, origin = DirectorOrigin.PLAYER)
public void scoreboard() {
Player target = player();
@@ -353,6 +447,21 @@ public class CommandStudio implements DirectorExecutor {
player().openInventory(inv);
}
/**
* Region chances describe the pack's generator, so sample it directly; the engine's getRegion answers from saved
* world history instead, which throws for every chunk whose history is not loaded.
*/
private static IrisRegion generatorRegion(Engine engine, int blockX, int blockZ) {
DimensionStackContext stack = engine.getDimensionStackContext();
if (stack != null) {
DimensionStackLayout.Layer layer = stack.getLayout(blockX, blockZ).surfaceLayer();
if (layer != null && layer.region() != null) {
return layer.region();
}
}
return engine.getComplex().getRegionStream().get(blockX, blockZ);
}
@Director(description = "Calculate the chance for each region to generate", descriptionKey = "iris.director.commandstudio.director.calculate_chance_each_region_generate", origin = DirectorOrigin.PLAYER)
public void regions(@Param(description = "The radius in chunks", descriptionKey = "iris.director.commandstudio.param.radius_chunks", defaultValue = "500") int radius) {
var engine = engine();
@@ -384,6 +493,7 @@ public class CommandStudio implements DirectorExecutor {
var loc = player.getLocation();
int totalTasks = d * d;
AtomicInteger completedTasks = new AtomicInteger(0);
AtomicReference<Throwable> firstFailure = new AtomicReference<>();
progressShown = true;
c = J.ar(() -> {
double jobProgress = (double) completedTasks.get() / totalTasks;
@@ -391,16 +501,32 @@ public class CommandStudio implements DirectorExecutor {
BukkitPlatform.showProgressLane(player, "iris:job", IrisLanguage.text(RuntimeUiMessages.FINDING_REGIONS) + " " + Form.pc(jobProgress, 0), jobProgress, 4000L);
}, 0);
new Spiraler(d, d, (x, z) -> executor.queue(() -> {
var region = engine.getRegion((x << 4) + 8, (z << 4) + 8);
data.computeIfAbsent(region.getLoadKey(), (k) -> new AtomicInteger(0))
.incrementAndGet();
completedTasks.incrementAndGet();
if (firstFailure.get() != null) {
return;
}
try {
var region = generatorRegion(engine, (x << 4) + 8, (z << 4) + 8);
data.computeIfAbsent(region.getLoadKey(), (k) -> new AtomicInteger(0))
.incrementAndGet();
completedTasks.incrementAndGet();
} catch (Throwable failure) {
firstFailure.compareAndSet(null, failure);
}
})).setOffset(loc.getBlockX(), loc.getBlockZ()).drain();
executor.complete();
if (firstFailure.get() != null) {
throw firstFailure.get();
}
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_DONE));
var loader = engine.getData().getRegionLoader();
data.forEach((k, v) -> sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_MESSAGE, MessageArgument.untrusted("k", k), MessageArgument.untrusted("value", loader.load(k).getRarity()), MessageArgument.untrusted("value2", Form.f((double) v.get() / totalTasks * 100, 2)))));
ChatReport.Builder report = ChatReport.of(ChatReport.Tone.SUCCESS,
IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_DONE)).unlimited();
data.entrySet().stream()
.sorted((a, b) -> Integer.compare(b.getValue().get(), a.getValue().get()))
.forEach(entry -> report.styledItem(regionShareLine(entry.getKey(),
loader.load(entry.getKey()).getRarity(),
(double) entry.getValue().get() / totalTasks)));
sender.sendReport(report.build());
} catch (Throwable e) {
Iris.reportError(e);
sender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_REGIONS_SCAN_FAILED,
@@ -18,6 +18,7 @@
package art.arcane.iris.command;
import art.arcane.iris.command.specialhandlers.MarkerHandler;
import art.arcane.iris.platform.bukkit.BukkitBlockResolution;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
@@ -203,7 +204,7 @@ public class CommandWhat implements DirectorExecutor {
private static final int MARKER_SIGNAL_BATCH = 128;
@Director(description = "Show markers in chunk", descriptionKey = "iris.director.commandwhat.director.show_markers_chunk", origin = DirectorOrigin.PLAYER)
public void markers(@Param(description = "Marker name such as cave_floor or cave_ceiling", descriptionKey = "iris.director.commandwhat.param.marker_name_such_as_cave_floor_cave_ceiling") String marker) {
public void markers(@Param(description = "Marker name such as cave_floor or cave_ceiling", descriptionKey = "iris.director.commandwhat.param.marker_name_such_as_cave_floor_cave_ceiling", customHandler = MarkerHandler.class) String marker) {
VolmitSender commandSender = sender();
Player player = player();
if (player == null) {
@@ -10,8 +10,10 @@ import art.arcane.volmlib.util.format.Form;
import java.util.List;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.localization.IrisLanguage;
import art.arcane.iris.localization.BukkitCommandMessages;
import art.arcane.volmlib.util.localization.TextKey;
import art.arcane.iris.localization.RuntimeUiMessages;
import art.arcane.volmlib.util.localization.MessageArgument;
final class IrisEngineStatus {
@@ -22,36 +24,53 @@ final class IrisEngineStatus {
CacheSummary caches = summarizeCaches();
MaintenanceMetrics metrics = snapshot.metrics();
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_MESSAGE));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_STATUS));
sender.sendMessage(IrisLanguage.text(
BukkitCommandMessages.IRIS_ENGINE_STATUS_SERVICE,
MessageArgument.trusted("value", status(snapshot.serviceRunning()))
));
sender.sendMessage(IrisLanguage.text(
BukkitCommandMessages.IRIS_ENGINE_STATUS_METRICS,
MessageArgument.trusted("value", status(snapshot.metricsRunning()))
));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_MAINTENANCE_PERIOD, MessageArgument.untrusted("value", Form.duration(snapshot.maintenancePeriodMillis()))));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_WORKER_PARALLELISM, MessageArgument.untrusted("value", snapshot.workerParallelism())));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_ACTIVE_WORLD_TASKS, MessageArgument.untrusted("value", metrics.activeTasks())));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_TECTONIC_PLATES));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_CONFIGURED_RETENTION, MessageArgument.untrusted("value", Form.duration(snapshot.retentionMillis()))));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_HEAP_USAGE, MessageArgument.untrusted("value", Form.pc(snapshot.heapUsage()))));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_RESIDENT, MessageArgument.untrusted("value", metrics.residentTectonicPlates())));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_QUEUED, MessageArgument.untrusted("value", metrics.queuedTectonicPlates())));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_AVERAGE_IDLE_DURATION, MessageArgument.untrusted("value", Form.duration(metrics.averageIdleDuration(), 2))));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_MAX_IDLE_DURATION, MessageArgument.untrusted("value", Form.duration(metrics.maxIdleDuration(), 2))));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_MIN_IDLE_DURATION, MessageArgument.untrusted("value", Form.duration(metrics.minIdleDuration(), 2))));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_CACHES));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_RESOURCE, MessageArgument.untrusted("value", caches.sizes()[0]), MessageArgument.untrusted("value2", caches.counts()[0])));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_2D_STREAM, MessageArgument.untrusted("value", caches.sizes()[1]), MessageArgument.untrusted("value2", caches.counts()[1])));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_3D_STREAM, MessageArgument.untrusted("value", caches.sizes()[2]), MessageArgument.untrusted("value2", caches.counts()[2])));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_OTHER, MessageArgument.untrusted("value", caches.sizes()[3]), MessageArgument.untrusted("value2", caches.counts()[3])));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_OTHER_2));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_IRIS_WORLDS, MessageArgument.untrusted("value", metrics.worlds())));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_LOADED_CHUNKS, MessageArgument.untrusted("value", metrics.loadedChunks())));
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_MESSAGE_2));
sender.sendReport(section(BukkitCommandMessages.IRIS_ENGINE_STATUS_STATUS,
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_SERVICE, MessageArgument.trusted("value", status(snapshot.serviceRunning()))),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_METRICS, MessageArgument.trusted("value", status(snapshot.metricsRunning()))),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_MAINTENANCE_PERIOD, MessageArgument.untrusted("value", Form.duration(snapshot.maintenancePeriodMillis()))),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_WORKER_PARALLELISM, MessageArgument.untrusted("value", snapshot.workerParallelism())),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_ACTIVE_WORLD_TASKS, MessageArgument.untrusted("value", metrics.activeTasks()))));
sender.sendReport(section(BukkitCommandMessages.IRIS_ENGINE_STATUS_TECTONIC_PLATES,
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_CONFIGURED_RETENTION, MessageArgument.untrusted("value", Form.duration(snapshot.retentionMillis()))),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_HEAP_USAGE, MessageArgument.untrusted("value", Form.pc(snapshot.heapUsage()))),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_RESIDENT, MessageArgument.untrusted("value", metrics.residentTectonicPlates())),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_QUEUED, MessageArgument.untrusted("value", metrics.queuedTectonicPlates())),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_AVERAGE_IDLE_DURATION, MessageArgument.untrusted("value", Form.duration(metrics.averageIdleDuration(), 2))),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_MAX_IDLE_DURATION, MessageArgument.untrusted("value", Form.duration(metrics.maxIdleDuration(), 2))),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_MIN_IDLE_DURATION, MessageArgument.untrusted("value", Form.duration(metrics.minIdleDuration(), 2)))));
sender.sendReport(section(BukkitCommandMessages.IRIS_ENGINE_STATUS_CACHES,
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_RESOURCE, MessageArgument.untrusted("value", caches.sizes()[0]), MessageArgument.untrusted("value2", caches.counts()[0])),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_2D_STREAM, MessageArgument.untrusted("value", caches.sizes()[1]), MessageArgument.untrusted("value2", caches.counts()[1])),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_3D_STREAM, MessageArgument.untrusted("value", caches.sizes()[2]), MessageArgument.untrusted("value2", caches.counts()[2])),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_OTHER, MessageArgument.untrusted("value", caches.sizes()[3]), MessageArgument.untrusted("value2", caches.counts()[3]))));
sender.sendReport(section(BukkitCommandMessages.IRIS_ENGINE_STATUS_OTHER_2,
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_IRIS_WORLDS, MessageArgument.untrusted("value", metrics.worlds())),
IrisLanguage.text(BukkitCommandMessages.IRIS_ENGINE_STATUS_LOADED_CHUNKS, MessageArgument.untrusted("value", metrics.loadedChunks()))));
}
private static ChatReport section(TextKey header, String... statLines) {
ChatReport.Builder report = ChatReport.of(ChatReport.Tone.INFO, stripTrailingColon(IrisLanguage.text(header))).unlimited();
for (String statLine : statLines) {
addStat(report, statLine);
}
return report.build();
}
/** Status keys render as {@code - Label: value}; a labelled stat becomes a report entry, anything else a plain item. */
private static void addStat(ChatReport.Builder report, String statLine) {
String cleaned = ChatReport.clean(statLine);
String withoutDash = cleaned.startsWith("-") ? cleaned.substring(1).strip() : cleaned;
int separator = withoutDash.indexOf(": ");
if (separator < 0) {
report.styledItem(withoutDash);
return;
}
report.entry(withoutDash.substring(0, separator), withoutDash.substring(separator + 2));
}
private static String stripTrailingColon(String header) {
String cleaned = ChatReport.clean(header);
return cleaned.endsWith(":") ? cleaned.substring(0, cleaned.length() - 1) : cleaned;
}
private static String status(boolean running) {
@@ -27,7 +27,9 @@ import art.arcane.iris.world.lifecycle.WorldLifecycleStaging;
import art.arcane.iris.pack.validation.CompatRegistry;
import art.arcane.iris.world.lifecycle.WorldReplacementSeed;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.pack.BrokenPackException;
import art.arcane.iris.pack.PackBootReporter;
import art.arcane.iris.pack.PackDownloader;
import art.arcane.iris.pack.PackDirectoryResolver;
import art.arcane.iris.pack.PackValidationCache;
@@ -82,7 +84,6 @@ import java.util.stream.Stream;
*/
public final class IrisWorldGeneratorResolver {
private static final int VALIDATION_STABILITY_ATTEMPTS = 2;
private static final int COMPAT_BOOT_KEY_CAP = 3;
private static final Object SNAPSHOT_VALIDATION_LOCK = new Object();
private static final String IRIS_DIMENSION_NAMESPACE = "iris";
private static final String PLOT_SQUARED_DISCOVERY_WORLD = "CheckingPlotSquaredGenerator";
@@ -235,38 +236,16 @@ public final class IrisWorldGeneratorResolver {
PackValidationRegistry.publish(packDirectory.toPath(), result, packFingerprint, contextFingerprint);
}
String minecraftVersion = IrisPlatforms.isBound() ? IrisPlatforms.get().minecraftVersion() : null;
String compatSummary = PackValidator.compatSummary(result, minecraftVersion);
String compatSuffix = compatSummary.isEmpty() ? "" : " " + compatSummary;
if (!result.isLoadable()) {
if (hasPendingExternalContent(result, IrisServices.getOrNull(ExternalDataSVC.class))
&& packDirectory != null
&& PackValidator.validateForDatapackBootstrap(packDirectory).isLoadable()) {
Iris.info("Pack '" + result.getPackName() + "' is waiting for external block providers to initialize.");
Iris.info("Waiting for external block providers before loading pack '" + result.getPackName() + "'…");
continue;
}
Iris.error("Pack '" + result.getPackName()
+ "' FAILED validation - world and Studio creation with this pack will be refused. Reasons:");
for (String reason : result.getBlockingErrors()) {
Iris.error(" - " + reason);
}
} else if (!result.getWarnings().isEmpty()) {
Iris.info("Pack '" + result.getPackName() + "' validated ("
+ result.getWarnings().size() + " warning(s))." + compatSuffix);
for (String warning : result.getWarnings()) {
Iris.warn(" [" + result.getPackName() + "] " + warning);
}
} else if (cached.isEmpty()) {
if (compatSummary.isEmpty()) {
Iris.success("Pack '" + result.getPackName() + "' validated.");
} else {
Iris.info("Pack '" + result.getPackName() + "' validated." + compatSuffix);
}
} else if (!compatSummary.isEmpty()) {
Iris.info("Pack '" + result.getPackName() + "' validated." + compatSuffix);
}
// Cache hits carry the persisted findings, so the listing prints on every boot, not only after a miss.
for (String line : PackValidator.compatBootLines(result, minecraftVersion, COMPAT_BOOT_KEY_CAP)) {
Iris.warn(line);
PackBootReporter.logBroken(result, minecraftVersion);
} else {
PackBootReporter.logValidated(result, minecraftVersion, false);
}
}
IrisStartupValidation.markPacksReady();
@@ -705,11 +684,11 @@ public final class IrisWorldGeneratorResolver {
try {
requireSnapshotLoadable(snapshotRoot);
} catch (BrokenPackException exception) {
Iris.error("Refusing to create world '" + worldName + "' using broken snapshot at '"
+ snapshotRoot + "':");
for (String reason : exception.getReasons()) {
Iris.error(" - " + reason);
}
ChatReport.of(ChatReport.Tone.ERROR, "Refusing to create world '" + worldName
+ "' using broken snapshot at '" + snapshotRoot + "'")
.items(exception.getReasons())
.build()
.log();
throw exception;
}
@@ -731,6 +710,11 @@ public final class IrisWorldGeneratorResolver {
return new BukkitChunkGenerator(world, false, snapshotRoot, dimension.getLoadKey(), history);
}
/** Whether a pack fails validation only because a block provider plugin has not registered its blocks yet. */
public static boolean awaitsExternalContent(PackValidationResult validation) {
return hasPendingExternalContent(validation, IrisServices.getOrNull(ExternalDataSVC.class));
}
static boolean hasPendingExternalContent(PackValidationResult validation, ExternalDataSVC external) {
return validation != null && external != null && validation.getCompatFindings().stream()
.anyMatch(finding -> finding.registry() == CompatRegistry.BLOCK
@@ -19,7 +19,7 @@
package art.arcane.iris.world;
import art.arcane.iris.Iris;
import art.arcane.iris.localization.C;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.world.safeguard.GenerationRefusalNotice;
import art.arcane.volmlib.util.bukkit.WorldIdentity;
import org.bukkit.Bukkit;
@@ -84,8 +84,17 @@ public final class WorldRefusalReporter implements Listener {
if (!player.isOp() && !player.hasPermission("iris.all")) {
return;
}
for (String notice : operatorNotices.values()) {
player.sendMessage(C.RED + notice);
ChatReport report = ChatReport.of(ChatReport.Tone.ERROR, operatorNotices.size() == 1
? "An Iris world did not load and refuses to generate"
: operatorNotices.size() + " Iris worlds did not load and refuse to generate")
.items(operatorNotices.values())
.hint("The console has the full refusal notice", null)
.build();
String tag = Iris.instance == null ? "" : Iris.instance.getTag();
player.sendMessage(ChatReport.SPACER.text());
player.sendMessage(tag + report.titleLine().text());
for (ChatReport.Line line : report.bodyLines(true)) {
player.sendMessage(line.text());
}
}
@@ -99,8 +108,8 @@ public final class WorldRefusalReporter implements Listener {
for (String line : notice(worldName, key, failure, startupWorldsCreated)) {
Iris.error(line);
}
operatorNotices.put(worldKey == null ? worldName : key, "Iris world '" + worldName + "' (" + key
+ ") did not load and refuses to generate: " + GenerationRefusalNotice.summary(failure));
operatorNotices.put(worldKey == null ? worldName : key, worldName + " (" + key + "): "
+ GenerationRefusalNotice.summary(failure));
} catch (Throwable reportingFailure) {
System.err.println("[Iris] Iris refused to generate world '" + worldName + "' (" + key
+ "); the refusal could not be reported: " + reportingFailure.getClass().getName());
@@ -27,7 +27,7 @@ export default {
await context.step('regeneration removes target furniture and preserves neighbor ownership', async () => {
const ready = await context.command('/iriscenative neighbor', /CE_NEIGHBOR_READY|CE_FAILED/, 30000)
context.expect(ready.includes('CE_NEIGHBOR_READY chunk=2,0 furniture=3 target=1'), ready)
const regenerated = await context.command('/iris developer regen radius=0', /Regen complete:|Regen failed:/, 90000)
const regenerated = await context.command('/iris studio regen radius=0', /Regen complete:|Regen failed:/, 90000)
context.expect(regenerated.includes('Regen complete:'), regenerated)
const response = await context.command('/iriscenative loaded', /CE_LOADED|CE_FAILED/, 30000)
context.expect(response.includes('CE_LOADED removed=1 untouched=1 replacement=1 wall=1 target=1'), response)
@@ -62,12 +62,12 @@ export default {
})
await context.step('unload while the player is inside and verify evacuation', async () => {
context.expect((await playerWorld()) === storageName, 'Player must be inside the world before unload')
await context.command(`/iris unloadWorld ${worldKey}`)
await context.command(`/iris unload-world ${worldKey}`)
await wait(async () => await settledStatus('loaded=false registered=true configured=true disk=true'), 'World unloaded with storage preserved')
await assertEvacuated('Unload evacuated the player to a loaded world')
})
await context.step('reload the saved world and enter it again', async () => {
await context.command(`/iris loadWorld ${worldName}`)
await context.command(`/iris load-world ${worldName}`)
await wait(async () => await settledStatus('loaded=true registered=true configured=true disk=true'), 'World reloaded')
await context.command(`/iris tp ${worldKey}`)
await assertSafeEntry()
@@ -1,5 +1,6 @@
package art.arcane.iris.command;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.pack.validation.CompatAction;
import art.arcane.iris.pack.validation.CompatFinding;
import art.arcane.iris.pack.validation.CompatRegistry;
@@ -30,9 +31,13 @@ public class CommandPackCompatTest {
return new PackValidationResult("overworld", List.of(), List.of(), 1L, findings, "26.1.2");
}
private static List<String> plainCompatOutput(String pack, PackValidationResult result) {
return CommandPack.compatOutput(pack, result).stream().map(ChatReport::clean).toList();
}
@Test
public void unknownPackIsReportedWithoutAnyCompatLines() {
List<String> lines = CommandPack.compatOutput("nope", null);
List<String> lines = plainCompatOutput("nope", null);
assertEquals(1, lines.size());
assertTrue(lines.getFirst(), lines.getFirst().contains("No validation result for 'nope'"));
@@ -40,7 +45,7 @@ public class CommandPackCompatTest {
@Test
public void packWithoutFindingsSaysSoAndNamesTheVersion() {
List<String> lines = CommandPack.compatOutput("overworld", result(List.of()));
List<String> lines = plainCompatOutput("overworld", result(List.of()));
assertEquals(1, lines.size());
assertTrue(lines.getFirst(), lines.getFirst().contains("Pack 'overworld' uses no content"));
@@ -49,7 +54,7 @@ public class CommandPackCompatTest {
@Test
public void findingsArePrintedUncappedWithTheFallbackRemedy() {
List<String> lines = CommandPack.compatOutput("overworld", result(List.of(
List<String> lines = plainCompatOutput("overworld", result(List.of(
block(CompatAction.EXCLUDED, "cave/a"),
block(CompatAction.EXCLUDED, "cave/b"),
block(CompatAction.EXCLUDED, "cave/c"),
@@ -7,7 +7,6 @@ import art.arcane.iris.pack.PackValidationRegistry;
import art.arcane.iris.pack.PackValidationCache;
import art.arcane.iris.pack.PackValidationResult;
import art.arcane.iris.pack.PackValidator;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
@@ -83,7 +82,7 @@ public class CommandPackValidationPublicationTest {
try (MockedStatic<PackValidator> validator = mockStatic(PackValidator.class)) {
validator.when(() -> PackValidator.validate(root)).thenReturn(valid);
assertSame(valid, new CommandPack().runValidate(mock(VolmitSender.class), root));
assertSame(valid, new CommandPack().runValidate(root));
assertSame(valid, PackValidationRegistry.get(root.toPath()));
assertSame(valid, PackValidationRegistry.get(root.getName()));
@@ -101,7 +100,7 @@ public class CommandPackValidationPublicationTest {
}
});
assertFalse(new CommandPack().runValidate(mock(VolmitSender.class), root).isLoadable());
assertFalse(new CommandPack().runValidate(root).isLoadable());
assertNull(PackValidationRegistry.get(root.toPath()));
assertNull(PackValidationRegistry.get(root.getName()));
}
@@ -119,7 +118,7 @@ public class CommandPackValidationPublicationTest {
return new PackValidationResult(root.getName(), List.of(), List.of(), 1L);
});
assertFalse(new CommandPack().runValidate(mock(VolmitSender.class), root).isLoadable());
assertFalse(new CommandPack().runValidate(root).isLoadable());
assertFalse(PackValidationRegistry.get(root.toPath()).isLoadable());
}
}
@@ -19,6 +19,7 @@
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;
@@ -223,17 +224,18 @@ 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);
applyEffect(level, player, effect, runtime);
} catch (Throwable error) {
IrisLogging.reportError(error);
}
}
}
private void applyEffect(NativeWorld level, NativeProtocolPlayer player, IrisEffect effect) {
if (!effect.shouldApplyNow()) {
private void applyEffect(NativeWorld level, NativeProtocolPlayer player, IrisEffect effect, PackRuntime runtime) {
if (!effect.shouldApplyNow(runtime)) {
return;
}
@@ -18,6 +18,7 @@
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;
@@ -127,7 +128,7 @@ public final class ModdedEntitySpawner {
entity.configureAnimal(irisEntity);
applySpawnEffect(irisEntity.getSpawnEffect(), entity, level);
applySpawnEffect(irisEntity.getSpawnEffect(), entity, level, PackRuntime.of(engine));
ModdedEntityCommandRunner.run(irisEntity.getRawCommands(), level.world(), blockX, blockY, blockZ);
if (riseEffectActive && entity.living()) {
startRiseEffect(engine, level, entity);
@@ -200,8 +201,9 @@ public final class ModdedEntitySpawner {
return level.chunksSafe(chunkX, chunkZ);
}
private static void applySpawnEffect(IrisEffect effect, NativeSpawnedEntity entity, NativeEntityRuntime level) {
if (effect == null || !effect.shouldApplyNow()) {
private static void applySpawnEffect(IrisEffect effect, NativeSpawnedEntity entity, NativeEntityRuntime level,
PackRuntime runtime) {
if (effect == null || !effect.shouldApplyNow(runtime)) {
return;
}
@@ -30,6 +30,7 @@ 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;
@@ -40,6 +41,9 @@ 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() {
}
@@ -117,7 +121,8 @@ public final class ModdedLootApplier {
}
IrisLootTable table = engine.getData().getLootLoader().load(loot.getName());
if (table == null) {
IrisLogging.warn("Couldn't find loot table " + loot.getName());
IrisLogging.warnOnce(IrisData.onceKey(engine.getData(), LOOT_TABLE_KEY_KIND, loot.getName()),
"Couldn't find loot table " + loot.getName());
continue;
}
bucket(engine, loot, new Candidate(new IrisLootSource(table), loot.getWeight()), access, exact, basic, global);
@@ -129,7 +134,8 @@ public final class ModdedLootApplier {
}
NativeContainerLoot.Table table = access.table(loot.getName());
if (table == null) {
IrisLogging.warn("Couldn't find vanilla loot table " + loot.getName());
IrisLogging.warnOnce(IrisData.onceKey(engine.getData(), VANILLA_LOOT_TABLE_KEY_KIND, loot.getName()),
"Couldn't find vanilla loot table " + loot.getName());
continue;
}
bucket(engine, loot, new Candidate(new NativeLootSource(table), loot.getWeight()), access, exact, basic, global);
@@ -1,5 +1,6 @@
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;
@@ -151,7 +152,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, generator.engine().getData());
return ((IrisMaterialPalette) source).get(rng, x, y, z, PackRuntime.of(generator.engine()));
}
@Override
@@ -21,6 +21,7 @@ package art.arcane.iris.modded;
import art.arcane.iris.pack.PackFingerprints;
import art.arcane.iris.pack.BrokenPackException;
import art.arcane.iris.pack.PackBootReporter;
import art.arcane.iris.pack.PackDirectoryResolver;
import art.arcane.iris.pack.PackDownloader;
import art.arcane.iris.pack.PackValidationRegistry;
@@ -43,7 +44,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public final class ModdedStartup {
private static final int COMPAT_BOOT_KEY_CAP = 3;
private static final AtomicBoolean PREPARED = new AtomicBoolean(false);
private static final AtomicBoolean STARTED = new AtomicBoolean(false);
private static final AtomicBoolean RESTORE_BEGUN = new AtomicBoolean(false);
@@ -142,22 +142,10 @@ public final class ModdedStartup {
try {
PackValidationResult result = validatePack(packDir);
String minecraftVersion = IrisPlatforms.isBound() ? IrisPlatforms.get().minecraftVersion() : null;
String compatSummary = PackValidator.compatSummary(result, minecraftVersion);
String compatSuffix = compatSummary.isEmpty() ? "" : " " + compatSummary;
if (!result.isLoadable()) {
ModdedIrisLog.error("Iris pack '{}' FAILED validation with {} blocking error(s); world/studio creation will be refused. First error: {}",
result.getPackName(), result.getBlockingErrors().size(),
result.getBlockingErrors().getFirst());
} else if (!result.getWarnings().isEmpty()) {
ModdedIrisLog.info("Iris pack '{}' validated ({} warning(s)).{}", result.getPackName(), result.getWarnings().size(), compatSuffix);
for (String warning : result.getWarnings()) {
ModdedIrisLog.warn(" [{}] {}", result.getPackName(), warning);
}
if (result.isLoadable()) {
PackBootReporter.logValidated(result, minecraftVersion, true);
} else {
ModdedIrisLog.info("Iris pack '{}' validated.{}", result.getPackName(), compatSuffix);
}
for (String line : PackValidator.compatBootLines(result, minecraftVersion, COMPAT_BOOT_KEY_CAP)) {
ModdedIrisLog.warn("{}", line);
PackBootReporter.logBroken(result, minecraftVersion);
}
} catch (Throwable e) {
ModdedIrisLog.error("Iris pack validation failed for '{}'", packDir.getName(), e);
@@ -20,18 +20,18 @@ 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.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.List;
public final class ModdedWorkspaceGenerator {
private ModdedWorkspaceGenerator() {
@@ -100,11 +100,7 @@ public final class ModdedWorkspaceGenerator {
try {
String snipType = snippetClass.getDeclaredAnnotation(Snippet.class).value();
JSONObject entry = new JSONObject();
KList<String> fileMatch = new KList<>();
for (int depth = 1; depth < 8; depth++) {
fileMatch.add("/snippet/" + snipType + Form.repeat("/*", depth) + ".json");
}
List<String> fileMatch = new SnippetFolder(snipType).workspaceFileMatches();
entry.put("fileMatch", new JSONArray(fileMatch.toArray()));
entry.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json");
@@ -73,7 +73,6 @@ final class ModdedCommandHelp {
Entry.command("catalog", "[namespace|refresh]", ModdedCatalogMessages.HELP_CATALOG),
Entry.group("ingest", ModdedCatalogMessages.HELP_INGEST),
Entry.command("metrics", "", ModdedHelpMessages.COMMAND_METRICS_PRINT_GENERATION_METRICS_FOR_YOUR_CURRENT_IRIS_DIMENSION, "measure"),
Entry.command("regen", "[radius]", ModdedHelpMessages.COMMAND_REGEN_DELETE_AND_REGENERATE_NEARBY_CHUNKS_IN_PLACE, "rg"),
Entry.group("pregen", ModdedHelpMessages.GROUP_PREGEN_PREGENERATE_AN_IRIS_DIMENSION, "pregenerate"),
Entry.command("wand", "", ModdedHelpMessages.COMMAND_WAND_GET_AN_IRIS_OBJECT_WAND),
Entry.command("dust", "", ModdedHelpMessages.COMMAND_DUST_GET_DUST_THAT_REVEALS_OBJECT_PLACEMENTS, "d"),
@@ -151,6 +150,7 @@ final class ModdedCommandHelp {
Entry.command("tpstudio", "", ModdedHelpMessages.COMMAND_TPSTUDIO_TELEPORT_INTO_THE_OPEN_STUDIO_DIMENSION, "stp"),
Entry.command("status", "", ModdedHelpMessages.COMMAND_STATUS_SHOW_THE_OPEN_STUDIO_DIMENSION_AND_ITS_PACK),
Entry.command("hotload", "", ModdedHelpMessages.COMMAND_HOTLOAD_REFRESH_THE_OPEN_STUDIO, "refresh"),
Entry.command("regen", "[radius]", ModdedHelpMessages.COMMAND_REGEN_DELETE_AND_REGENERATE_NEARBY_CHUNKS_IN_PLACE, "rg"),
Entry.command("noise", "[generator] [seed]", ModdedHelpMessages.COMMAND_NOISE_OPEN_THE_NOISE_EXPLORER_GUI_ON_THE_SERVER_DISPLAY, "nmap"),
Entry.command("map", "", ModdedHelpMessages.COMMAND_MAP_OPEN_THE_VISION_MAP_GUI_ON_THE_SERVER_DISPLAY, "render"),
Entry.command("vscode", "[pack]", ModdedHelpMessages.COMMAND_VSCODE_REGENERATE_THE_CODE_WORKSPACE_FOR_A_PACK_AND_OPEN_IT_IN_YOUR, "vsc"),
@@ -120,9 +120,6 @@ final class ModdedCommandTree {
root.then(metricsTree("metrics"));
root.then(metricsTree("measure"));
root.then(regenTree("regen"));
root.then(regenTree("rg"));
root.then(pregenTree("pregen"));
root.then(pregenTree("pregenerate"));
@@ -222,13 +219,6 @@ final class ModdedCommandTree {
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> IrisModdedCommands.metrics(context.getSource())));
}
private static LiteralArgumentBuilder<NativeCommandSource> regenTree(String name) {
return NativeCommandRegistration.literal(name).requires(GATE)
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> IrisModdedCommands.regen(context.getSource(), 0)))
.then(NativeCommandRegistration.argument("radius", IntegerArgumentType.integer(0, 64))
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> IrisModdedCommands.regen(context.getSource(), IntegerArgumentType.getInteger(context, "radius")))));
}
private static LiteralArgumentBuilder<NativeCommandSource> gotoTree(String name) {
return NativeCommandRegistration.literal(name).requires(GATE)
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> ModdedCommandHelp.send(context.getSource(), name)))
@@ -159,6 +159,8 @@ public final class ModdedStudioCommands {
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> hotload(context.getSource()))));
root.then(NativeCommandRegistration.literal("refresh")
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> hotload(context.getSource()))));
root.then(regenTree("regen"));
root.then(regenTree("rg"));
root.then(workspaceTree("vscode", true));
root.then(workspaceTree("vsc", true));
root.then(workspaceTree("update", false));
@@ -210,6 +212,13 @@ public final class ModdedStudioCommands {
STUDIOS.clear();
}
private static LiteralArgumentBuilder<NativeCommandSource> regenTree(String name) {
return NativeCommandRegistration.literal(name)
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> IrisModdedCommands.regen(context.getSource(), 0)))
.then(NativeCommandRegistration.argument("radius", IntegerArgumentType.integer(0, 64))
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> IrisModdedCommands.regen(context.getSource(), IntegerArgumentType.getInteger(context, "radius")))));
}
private static LiteralArgumentBuilder<NativeCommandSource> openTree(String name) {
return NativeCommandRegistration.literal(name)
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> openHelp(context.getSource())))
@@ -206,6 +206,23 @@ public class IrisModdedCommandParityTest {
assertNotNull("pack cp", child(child(iris, "pk"), "cp").getCommand());
}
@Test
public void regenLivesUnderStudio() {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher<>();
IrisModdedCommands.register(new NativeCommandRegistration(dispatcher));
CommandNode<CommandSourceStack> iris = child(dispatcher.getRoot(), "iris");
assertNotNull("std regen", child(child(iris, "std"), "regen").getCommand());
assertNotNull("studio rg radius", child(child(child(iris, "studio"), "rg"), "radius").getCommand());
assertNull("top-level regen", iris.getChild("regen"));
assertNull("top-level rg", iris.getChild("rg"));
assertTrue(ModdedCommandHelp.consoleLines("studio").stream().anyMatch((String line) ->
line.startsWith("/iris studio regen [radius] (rg) - ")));
}
@Test
public void consoleHelpListsEveryEntryWithInlineUsageAndDescription() {
List<String> root = ModdedCommandHelp.consoleLines("");
@@ -33,6 +33,14 @@ public final class GenerationRevisionScope {
"core/src/main/java/art/arcane/iris/diagnostics/splash/IrisSplashRenderer.java",
"core/src/main/java/art/arcane/iris/diagnostics/splash/IrisSplashComposer.java",
"core/src/main/java/art/arcane/iris/diagnostics/splash/IrisSplashPackScanner.java",
"core/src/main/java/art/arcane/iris/diagnostics/BuildChannel.java",
"core/src/main/java/art/arcane/iris/diagnostics/BuildIdentity.java",
"core/src/main/java/art/arcane/iris/diagnostics/BuildFacts.java",
"core/src/main/java/art/arcane/iris/diagnostics/SystemFacts.java",
"core/src/main/java/art/arcane/iris/diagnostics/DiagnosticFact.java",
"core/src/main/java/art/arcane/iris/diagnostics/DiagnosticSection.java",
"core/src/main/java/art/arcane/iris/diagnostics/DiagnosticsReport.java",
"core/src/main/java/art/arcane/iris/diagnostics/FactFormat.java",
"adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedIrisSplash.java",
"adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandDebug.java",
"adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandDeveloper.java",
+30 -1
View File
@@ -235,6 +235,18 @@ tasks.named('processResources').configure { Task resources ->
}
def templateSource = file('src/main/templates')
def templateDest = layout.buildDirectory.dir('generated/sources/templates')
def sourceHashesProvided = { -> providers.environmentVariable('MULTIPLEXOR_SOURCE_HASHES').isPresent() }
def gitOutput = { String... arguments ->
try {
Process process = new ProcessBuilder(['git', '-C', rootProject.projectDir.absolutePath] + arguments.toList())
.redirectError(ProcessBuilder.Redirect.DISCARD)
.start()
String output = new String(process.inputStream.readAllBytes(), StandardCharsets.UTF_8).trim()
return process.waitFor() == 0 ? output : null
} catch (Exception ignored) {
return null
}
}
def generateTemplates = tasks.register('generateTemplates', Copy) {
inputs.properties([
environment: providers.provider {
@@ -283,6 +295,23 @@ def generateTemplates = tasks.register('generateTemplates', Copy) {
logger.error('Git commit hash not found', failure)
return 'unknown'
},
branch: providers.provider {
if (sourceHashesProvided()) {
return ''
}
String branch = gitOutput('rev-parse', '--abbrev-ref', 'HEAD')
if (branch == null || branch == 'HEAD') {
return ''
}
return branch.replace('\\', '\\\\').replace('"', '\\"')
},
dirty: providers.provider {
if (sourceHashesProvided()) {
return false
}
String status = gitOutput('status', '--porcelain')
return status != null && !status.isEmpty()
},
minecraftVersion: providers.gradleProperty('minecraftVersion'),
])
@@ -482,7 +511,7 @@ List<String> dependencyBuildMetadata = [
'META-INF/versions/*/OSGI-INF/**'
]
String languageTomlSupportClassPattern = 'art/arcane/volmlib/util/config/(?:TomlCodec|ConfigJson|ConfigExposePolicy|ConfigDoc|ConfigDescription|ConfigDocumentation)(?:\\$[^/]+)?\\.class'
String languageTomlSupportClassPattern = 'art/arcane/volmlib/util/config/(?:TomlCodec|TomlSegments|ConfigComments|ConfigJson|ConfigExposePolicy|ConfigDoc|ConfigDescription|ConfigDocumentation)(?:\\$[^/]+)?\\.class'
tasks.named('shadowJar', ShadowJar).configure {
inputs.property('languageTomlSupportClassPattern', languageTomlSupportClassPattern)
@@ -28,6 +28,7 @@ import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Entity;
@@ -35,6 +36,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.junit.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import java.util.List;
import java.util.Map;
@@ -196,6 +198,68 @@ public class CraftEngineDataProviderTest {
}
}
@Test
public void decayingCustomLeavesAreMadePersistentAndKeepTheirCustomIdentity() {
BooleanProperty persistent = BooleanProperty.create("persistent", false);
BlockDefinition definition = mock(BlockDefinition.class);
ImmutableBlockState decaying = blockState(definition, "test:leaves[persistent=false]");
ImmutableBlockState kept = blockState(definition, "test:leaves[persistent=true]");
BlockData base = mock(BlockData.class);
BlockData keptBase = mock(BlockData.class);
doReturn(persistent).when(decaying).getProperty("persistent");
doReturn(false).when(decaying).get(persistent);
when(decaying.with(persistent, true)).thenReturn(kept);
try (MockedStatic<CraftEngineBlocks> blocks = mockStatic(CraftEngineBlocks.class)) {
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(base)).thenReturn(decaying);
blocks.when(() -> CraftEngineBlocks.getBukkitBlockData(kept)).thenReturn(keptBase);
IrisCustomData result = (IrisCustomData) new CraftEngineDataProvider()
.withoutDecay(IrisCustomData.of(base, new Identifier("craftengine", "test/leaves[persistent=false]")));
assertSame(keptBase, result.getBase());
assertEquals(new Identifier("test", "leaves[persistent=true]"), result.getCustom());
}
}
@Test
public void persistentOrDecaylessCustomBlocksAreKeptAsTheyAre() {
BooleanProperty persistent = BooleanProperty.create("persistent", false);
BlockDefinition definition = mock(BlockDefinition.class);
ImmutableBlockState alreadyPersistent = blockState(definition, "test:leaves[persistent=true]");
ImmutableBlockState withoutProperty = blockState(definition, "test:log");
BlockData persistentData = mock(BlockData.class);
BlockData logData = mock(BlockData.class);
BlockData vanilla = mock(BlockData.class);
doReturn(persistent).when(alreadyPersistent).getProperty("persistent");
doReturn(true).when(alreadyPersistent).get(persistent);
try (MockedStatic<CraftEngineBlocks> blocks = mockStatic(CraftEngineBlocks.class)) {
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(persistentData)).thenReturn(alreadyPersistent);
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(logData)).thenReturn(withoutProperty);
CraftEngineDataProvider provider = new CraftEngineDataProvider();
assertSame(persistentData, provider.withoutDecay(persistentData));
assertSame(logData, provider.withoutDecay(logData));
assertSame(vanilla, provider.withoutDecay(vanilla));
}
}
@Test
public void customBlocksCarryTheTagsTheirSettingsListEvenWhenWrapped() {
ImmutableBlockState state = mock(ImmutableBlockState.class, Mockito.RETURNS_DEEP_STUBS);
BlockData base = mock(BlockData.class);
BlockData vanilla = mock(BlockData.class);
when(state.settings().tags()).thenReturn(Set.of(Key.of("minecraft:logs")));
try (MockedStatic<CraftEngineBlocks> blocks = mockStatic(CraftEngineBlocks.class)) {
blocks.when(() -> CraftEngineBlocks.getCustomBlockState(base)).thenReturn(state);
CraftEngineDataProvider provider = new CraftEngineDataProvider();
BlockData wrapped = IrisCustomData.of(base, new Identifier("craftengine", "test/log"));
assertTrue(provider.hasBlockTag(wrapped, NamespacedKey.minecraft("logs")));
assertFalse(provider.hasBlockTag(wrapped, NamespacedKey.minecraft("leaves")));
assertFalse(provider.hasBlockTag(vanilla, NamespacedKey.minecraft("logs")));
}
}
@Test
public void unknownOrInvalidBlockPropertiesFailBeforeNativeConversion() {
Identifier id = new Identifier("test", "lamp");
@@ -0,0 +1,16 @@
package art.arcane.iris.command.specialhandlers;
import art.arcane.iris.pack.datapack.export.DatapackExportDestinations;
import java.util.Locale;
public final class ExportFormatHandler extends FixedChoiceHandler {
public ExportFormatHandler() {
super("zip", "directory");
}
@Override
protected String canonicalize(String input) {
return DatapackExportDestinations.parseFormat(input).name().toLowerCase(Locale.ROOT);
}
}
@@ -0,0 +1,16 @@
package art.arcane.iris.command.specialhandlers;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import java.util.Locale;
public final class ExportModeHandler extends FixedChoiceHandler {
public ExportModeHandler() {
super("preset", "dimension", "overworld");
}
@Override
protected String canonicalize(String input) {
return WorldgenExportMode.parse(input).name().toLowerCase(Locale.ROOT);
}
}
@@ -0,0 +1,18 @@
package art.arcane.iris.command.specialhandlers;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.WorldgenExportTargets;
public final class ExportVersionHandler extends FixedChoiceHandler {
public ExportVersionHandler() {
super(WorldgenExportTargets.SUPPORTED.stream().map(DataVersion::getVersion).toArray(String[]::new));
}
@Override
protected String canonicalize(String input) {
if (input == null || input.isBlank()) {
return "";
}
return WorldgenExportTargets.resolve(input).getVersion();
}
}
@@ -0,0 +1,41 @@
package art.arcane.iris.command.specialhandlers;
import art.arcane.iris.command.DirectorParameterHandler;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.director.exceptions.DirectorParsingException;
import java.util.List;
public abstract class FixedChoiceHandler implements DirectorParameterHandler<String> {
private final List<String> choices;
protected FixedChoiceHandler(String... choices) {
this.choices = List.of(choices);
}
protected abstract String canonicalize(String input);
@Override
public KList<String> getPossibilities() {
return new KList<>(choices);
}
@Override
public String toString(String value) {
return value == null ? "" : value;
}
@Override
public String parse(String input, boolean force) throws DirectorParsingException {
try {
return canonicalize(input);
} catch (IllegalArgumentException error) {
throw new DirectorParsingException(error.getMessage());
}
}
@Override
public boolean supports(Class<?> type) {
return type == String.class;
}
}
@@ -0,0 +1,12 @@
package art.arcane.iris.command.specialhandlers;
import art.arcane.iris.pack.datapack.DatapackIngestService;
import java.util.Collection;
public final class InstalledDatapackHandler extends OpenSuggestionHandler {
@Override
protected Collection<String> suggestions() {
return DatapackIngestService.installed().stream().map(entry -> entry.id).toList();
}
}
@@ -0,0 +1,18 @@
package art.arcane.iris.command.specialhandlers;
import art.arcane.iris.generation.runtime.Engine;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public final class MarkerHandler extends OpenSuggestionHandler {
@Override
protected Collection<String> suggestions() {
Engine activeEngine = engine();
if (activeEngine == null || activeEngine.getData() == null) {
return List.of();
}
return Arrays.stream(activeEngine.getData().getMarkerLoader().getPossibleKeys()).sorted().toList();
}
}
@@ -0,0 +1,30 @@
package art.arcane.iris.command.specialhandlers;
import art.arcane.iris.command.DirectorParameterHandler;
import art.arcane.volmlib.util.collection.KList;
import java.util.Collection;
public abstract class OpenSuggestionHandler implements DirectorParameterHandler<String> {
protected abstract Collection<String> suggestions();
@Override
public KList<String> getPossibilities() {
return new KList<>(suggestions());
}
@Override
public String toString(String value) {
return value == null ? "" : value;
}
@Override
public String parse(String input, boolean force) {
return input == null ? "" : input.trim();
}
@Override
public boolean supports(Class<?> type) {
return type == String.class;
}
}
@@ -0,0 +1,18 @@
package art.arcane.iris.command.specialhandlers;
import art.arcane.iris.pack.PackDirectoryResolver;
import art.arcane.iris.spi.IrisPlatforms;
import java.io.File;
import java.util.Collection;
public final class PackFolderHandler extends OpenSuggestionHandler {
@Override
protected Collection<String> suggestions() {
return PackDirectoryResolver.listVisiblePackDirectories(IrisPlatforms.get().packsFolder())
.stream()
.map(File::getName)
.sorted()
.toList();
}
}
@@ -0,0 +1,18 @@
package art.arcane.iris.command.specialhandlers;
import java.util.Locale;
public final class PreviewApplyModeHandler extends FixedChoiceHandler {
public PreviewApplyModeHandler() {
super("preview", "apply");
}
@Override
protected String canonicalize(String input) {
String mode = input.trim().toLowerCase(Locale.ROOT);
if (!mode.equals("preview") && !mode.equals("apply")) {
throw new IllegalArgumentException("Mode must be preview or apply.");
}
return mode;
}
}
@@ -0,0 +1,12 @@
package art.arcane.iris.command.specialhandlers;
import art.arcane.iris.spi.IrisPlatforms;
import java.util.Collection;
public final class RegisteredStructureKeyHandler extends OpenSuggestionHandler {
@Override
protected Collection<String> suggestions() {
return IrisPlatforms.get().structureHooks().structureKeys().stream().sorted().toList();
}
}
@@ -0,0 +1,16 @@
package art.arcane.iris.command.specialhandlers;
import art.arcane.iris.generation.subterrain.IrisSubterrainFamily;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
public final class SubterrainFeatureHandler extends OpenSuggestionHandler {
@Override
protected Collection<String> suggestions() {
return Arrays.stream(IrisSubterrainFamily.values())
.map(family -> family.name().toLowerCase(Locale.ROOT))
.toList();
}
}
@@ -0,0 +1,23 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.BuildConstants;
public enum BuildChannel {
RELEASE,
DEVELOPMENT;
private static final String RELEASE_ENVIRONMENT = "production";
private static final BuildChannel CURRENT = of(BuildConstants.ENVIRONMENT);
public static BuildChannel current() {
return CURRENT;
}
static BuildChannel of(String environment) {
return RELEASE_ENVIRONMENT.equals(environment) ? RELEASE : DEVELOPMENT;
}
public boolean isDevelopment() {
return this == DEVELOPMENT;
}
}
@@ -0,0 +1,318 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.simd.SimdSupport;
import art.arcane.iris.pack.PackValidationRegistry;
import art.arcane.iris.pack.PackValidationResult;
import art.arcane.iris.platform.bukkit.nms.INMS;
import art.arcane.iris.platform.bukkit.nms.v1X.NMSBinding1X;
import art.arcane.iris.world.safeguard.IrisSafeguard;
import art.arcane.iris.world.safeguard.Mode;
import art.arcane.volmlib.util.noise.FractalBillowSimplexNoise;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.CodeSource;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.TreeMap;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/** The build block: which jar runs, what it was built against, and what startup made of it. */
public final class BuildFacts {
private static final String VOLMLIB_STAMP = "META-INF/volmit/volmlib.properties";
private static final String LOCAL_VOLMLIB_SOURCE = "local";
private static final int SHORT_COMMIT_LENGTH = 7;
private static final String DIRTY_MARK = "+dirty";
private static final String NATIVE_NOISE_STATUS_PREFIX = "native";
private static final String SCALAR_SIMD = "scalar";
private static final Pattern IRIS_JAR_NAME = Pattern.compile("(?i)iris\\b.*\\.jar");
private static final int SETTINGS_SHOWN = 4;
private static final int PACKS_SHOWN = 6;
private BuildFacts() {
}
enum TerrainProvider {
NATIVE,
DISABLED,
UNBOUND
}
enum PackOutcome {
LOADABLE,
WAITING,
FAILED
}
record Jar(String path, Optional<Duration> age, List<String> otherIrisJars) {
}
record Natives(String noiseStatus, TerrainProvider terrain, String simd) {
}
record PackState(String name, PackOutcome outcome, int warnings) {
}
public static DiagnosticSection current(Predicate<PackValidationResult> awaitingExternalContent) {
return DiagnosticSection.gather(title(BuildIdentity.current()), List.of(
() -> currentJar().flatMap(BuildFacts::jar),
() -> volmLibStamp().flatMap(BuildFacts::volmLib),
() -> natives(currentNatives()),
() -> settings(currentSettingChanges()),
() -> checks(IrisSafeguard.asContext()),
() -> packs(packStates(PackValidationRegistry.snapshot(), awaitingExternalContent))));
}
static String title(BuildIdentity build) {
if (!build.channel().isDevelopment()) {
return "Build " + build.commitLabel();
}
String title = "Dev build " + build.commitLabel();
return build.hasBranch() ? title + " on " + build.branch() : title;
}
static Optional<DiagnosticFact> jar(Jar jar) {
DiagnosticFact.Items items = new DiagnosticFact.Items().plain(jar.path());
jar.age().ifPresent(age -> items.muted("deployed " + FactFormat.age(age) + " ago"));
if (!jar.otherIrisJars().isEmpty()) {
items.warning("also " + String.join(", ", jar.otherIrisJars()));
}
return items.fact("Jar");
}
static Optional<DiagnosticFact> volmLib(Properties stamp) {
String source = stamp.getProperty("source");
if (source == null || source.isBlank()) {
return Optional.empty();
}
if (!LOCAL_VOLMLIB_SOURCE.equals(source)) {
return new DiagnosticFact.Items().plain(source).fact("VolmLib");
}
String commit = stamp.getProperty("commit", "unknown");
String shortCommit = commit.length() > SHORT_COMMIT_LENGTH ? commit.substring(0, SHORT_COMMIT_LENGTH) : commit;
String dirtyMark = Boolean.parseBoolean(stamp.getProperty("dirty")) ? DIRTY_MARK : "";
return new DiagnosticFact.Items().plain(LOCAL_VOLMLIB_SOURCE + " @ " + shortCommit + dirtyMark).fact("VolmLib");
}
static Optional<DiagnosticFact> natives(Natives natives) {
boolean nativeNoise = natives.noiseStatus().startsWith(NATIVE_NOISE_STATUS_PREFIX);
return new DiagnosticFact.Items()
.flagged(nativeNoise ? "noise ok" : "noise " + natives.noiseStatus(), !nativeNoise)
.flagged(terrainLabel(natives.terrain()), natives.terrain() != TerrainProvider.NATIVE)
.flagged("SIMD " + natives.simd(), SCALAR_SIMD.equals(natives.simd()))
.fact("Natives");
}
private static String terrainLabel(TerrainProvider terrain) {
return switch (terrain) {
case NATIVE -> "terrain ok";
case DISABLED -> "terrain off";
case UNBOUND -> "terrain failed";
};
}
static Optional<DiagnosticFact> settings(Map<String, String> changes) {
DiagnosticFact.Items items = new DiagnosticFact.Items();
if (changes.isEmpty()) {
return items.muted("defaults").fact("Settings");
}
changes.entrySet().stream()
.limit(SETTINGS_SHOWN)
.forEach(change -> items.plain(change.getKey() + "=" + change.getValue()));
int hidden = changes.size() - SETTINGS_SHOWN;
if (hidden > 0) {
items.muted("+" + hidden + " more");
}
return items.fact("Settings");
}
/** Every leaf of {@code current} that differs from {@code defaults}, keyed by its dotted path, in settings order. */
static Map<String, String> settingChanges(JsonElement current, JsonElement defaults) {
Map<String, String> changes = new LinkedHashMap<>();
collectSettingChanges("", current, defaults, changes);
return changes;
}
private static void collectSettingChanges(String path, JsonElement current, JsonElement defaults,
Map<String, String> changes) {
if (current == null || !current.isJsonObject()) {
if (!Objects.equals(current, defaults)) {
changes.put(path, settingValue(current));
}
return;
}
JsonObject defaultSection = defaults != null && defaults.isJsonObject() ? defaults.getAsJsonObject() : new JsonObject();
for (Map.Entry<String, JsonElement> setting : current.getAsJsonObject().entrySet()) {
String settingPath = path.isEmpty() ? setting.getKey() : path + "." + setting.getKey();
collectSettingChanges(settingPath, setting.getValue(), defaultSection.get(setting.getKey()), changes);
}
}
private static String settingValue(JsonElement value) {
if (value == null || value.isJsonNull()) {
return "null";
}
return value.isJsonPrimitive() ? value.getAsString() : value.toString();
}
static Optional<DiagnosticFact> checks(Map<String, String> modeIdsByCheck) {
Map<Mode, List<String>> checksByMode = new EnumMap<>(Mode.class);
modeIdsByCheck.forEach((check, modeId) -> checksByMode
.computeIfAbsent(Mode.valueOf(modeId.toUpperCase(Locale.ROOT)), ignored -> new ArrayList<>())
.add(check));
DiagnosticFact.Items items = new DiagnosticFact.Items();
checksByMode.forEach((mode, checks) -> {
if (mode == Mode.STABLE) {
items.plain(checks.size() + " ok");
return;
}
String outcome = mode == Mode.WARNING ? " warn (" : " failed (";
items.warning(checks.size() + outcome + String.join(", ", checks) + ")");
});
return items.fact("Checks");
}
static Optional<DiagnosticFact> packs(List<PackState> packs) {
DiagnosticFact.Items items = new DiagnosticFact.Items();
if (packs.isEmpty()) {
return items.muted("none").fact("Packs");
}
packs.stream().limit(PACKS_SHOWN).forEach(pack -> addPack(items, pack));
int hidden = packs.size() - PACKS_SHOWN;
if (hidden > 0) {
items.muted("+" + hidden + " more");
}
return items.fact("Packs");
}
private static void addPack(DiagnosticFact.Items items, PackState pack) {
switch (pack.outcome()) {
case FAILED -> items.warning(pack.name() + " failed");
case WAITING -> items.muted(pack.name() + " waiting");
case LOADABLE -> {
if (pack.warnings() == 0) {
items.plain(pack.name() + " ok");
return;
}
items.warning(pack.name() + " " + pack.warnings() + (pack.warnings() == 1 ? " warning" : " warnings"));
}
}
}
static List<PackState> packStates(Map<String, PackValidationResult> resultsByPack,
Predicate<PackValidationResult> awaitingExternalContent) {
List<PackState> states = new ArrayList<>(resultsByPack.size());
new TreeMap<>(resultsByPack).forEach((pack, result) -> states.add(new PackState(pack,
packOutcome(result, awaitingExternalContent), result.getWarnings().size())));
return states;
}
private static PackOutcome packOutcome(PackValidationResult result, Predicate<PackValidationResult> awaitingExternalContent) {
if (result.isLoadable()) {
return PackOutcome.LOADABLE;
}
return awaitingExternalContent.test(result) ? PackOutcome.WAITING : PackOutcome.FAILED;
}
private static Optional<Jar> currentJar() {
Optional<Path> runningJar = runningJar();
if (runningJar.isEmpty()) {
return Optional.empty();
}
Path jar = runningJar.get();
return Optional.of(new Jar(serverRelative(jar), modificationAge(jar), otherIrisJars(jar)));
}
private static Optional<Path> runningJar() {
try {
CodeSource source = BuildFacts.class.getProtectionDomain().getCodeSource();
if (source == null || source.getLocation() == null) {
return Optional.empty();
}
Path jar = Path.of(source.getLocation().toURI()).toAbsolutePath().normalize();
return Files.isRegularFile(jar) ? Optional.of(jar) : Optional.empty();
} catch (URISyntaxException unresolvable) {
return Optional.empty();
}
}
/** The server runs from its root folder, so the working directory is what paths are relative to. */
private static String serverRelative(Path jar) {
Path serverRoot = Path.of("").toAbsolutePath().normalize();
Path shown = jar.startsWith(serverRoot) ? serverRoot.relativize(jar) : jar;
return shown.toString().replace('\\', '/');
}
/** A plain copy resets the modification time, so this is when the jar was deployed rather than built. */
private static Optional<Duration> modificationAge(Path jar) {
try {
Instant modified = Files.getLastModifiedTime(jar).toInstant();
return Optional.of(Duration.between(modified, Instant.now()));
} catch (IOException unreadable) {
return Optional.empty();
}
}
private static List<String> otherIrisJars(Path jar) {
Path folder = jar.getParent();
if (folder == null) {
return List.of();
}
try (Stream<Path> files = Files.list(folder)) {
return files.filter(file -> !file.equals(jar) && Files.isRegularFile(file))
.map(file -> file.getFileName().toString())
.filter(name -> IRIS_JAR_NAME.matcher(name).matches())
.sorted()
.toList();
} catch (IOException unreadable) {
return List.of();
}
}
private static Optional<Properties> volmLibStamp() {
try (InputStream input = BuildFacts.class.getClassLoader().getResourceAsStream(VOLMLIB_STAMP)) {
if (input == null) {
return Optional.empty();
}
Properties stamp = new Properties();
stamp.load(input);
return Optional.of(stamp);
} catch (IOException unreadable) {
return Optional.empty();
}
}
private static Natives currentNatives() {
return new Natives(FractalBillowSimplexNoise.nativeBackendStatus(), currentTerrainProvider(), SimdSupport.shortStatus());
}
private static TerrainProvider currentTerrainProvider() {
if (!INMS.isBound()) {
return TerrainProvider.UNBOUND;
}
return INMS.get() instanceof NMSBinding1X ? TerrainProvider.DISABLED : TerrainProvider.NATIVE;
}
private static Map<String, String> currentSettingChanges() {
Gson gson = new Gson();
return settingChanges(gson.toJsonTree(IrisSettings.get()), gson.toJsonTree(new IrisSettings()));
}
}
@@ -0,0 +1,27 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.BuildConstants;
/** Which source a jar was built from, as the splash and the build report name it. */
public record BuildIdentity(BuildChannel channel, String commit, String environment, String branch, boolean dirty) {
private static final int SHORT_COMMIT_LENGTH = 7;
private static final String DIRTY_MARK = "+dirty";
public static BuildIdentity current() {
return new BuildIdentity(BuildChannel.current(), BuildConstants.COMMIT, BuildConstants.ENVIRONMENT,
BuildConstants.BRANCH, BuildConstants.DIRTY);
}
/** "df31f1e/production" on a release; on a development build the environment gives way to the dirty mark. */
public String commitLabel() {
String shortCommit = commit.length() > SHORT_COMMIT_LENGTH ? commit.substring(0, SHORT_COMMIT_LENGTH) : commit;
if (!channel.isDevelopment()) {
return shortCommit + "/" + environment;
}
return dirty ? shortCommit + DIRTY_MARK : shortCommit;
}
public boolean hasBranch() {
return branch != null && !branch.isBlank();
}
}
@@ -0,0 +1,54 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.localization.ChatReport.ValuePart;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/** One labelled line of a diagnostics section, such as "Jar" or "Memory". */
public record DiagnosticFact(String label, List<ValuePart> value) {
public DiagnosticFact {
value = List.copyOf(value);
}
public String plainValue() {
return value.stream().map(ValuePart::text).collect(Collectors.joining());
}
/** A fact's value as a comma separated list; the separators stay muted so the items carry the color. */
static final class Items {
private static final String SEPARATOR = ", ";
private final List<ValuePart> parts = new ArrayList<>();
Items plain(String text) {
return add(ValuePart.plain(text));
}
Items muted(String text) {
return add(ValuePart.muted(text));
}
Items warning(String text) {
return add(ValuePart.warning(text));
}
Items flagged(String text, boolean needsLook) {
return needsLook ? warning(text) : plain(text);
}
Optional<DiagnosticFact> fact(String label) {
return parts.isEmpty() ? Optional.empty() : Optional.of(new DiagnosticFact(label, parts));
}
private Items add(ValuePart part) {
if (!parts.isEmpty()) {
parts.add(ValuePart.muted(SEPARATOR));
}
parts.add(part);
return this;
}
}
}
@@ -0,0 +1,45 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.spi.IrisLogging;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
/** A titled block of facts, printed as a console or chat report or written as plain text into the debug dump. */
public record DiagnosticSection(String title, List<DiagnosticFact> facts) {
private static final String PLAIN_INDENT = " ";
public DiagnosticSection {
facts = List.copyOf(facts);
}
/** Gathers each fact on its own, so a fact that cannot be determined is left out instead of failing the section. */
static DiagnosticSection gather(String title, List<Supplier<Optional<DiagnosticFact>>> gatherers) {
List<DiagnosticFact> facts = new ArrayList<>(gatherers.size());
for (Supplier<Optional<DiagnosticFact>> gatherer : gatherers) {
try {
gatherer.get().ifPresent(facts::add);
} catch (RuntimeException | LinkageError undeterminable) {
IrisLogging.debug("Diagnostics left out a fact of '" + title + "': " + undeterminable);
}
}
return new DiagnosticSection(title, facts);
}
public ChatReport report() {
ChatReport.Builder report = ChatReport.of(ChatReport.Tone.DIAGNOSTIC, title).unlimited();
facts.forEach(fact -> report.entry(fact.label(), fact.value()));
return report.build();
}
public String plainText() {
StringBuilder text = new StringBuilder(title);
for (DiagnosticFact fact : facts) {
text.append('\n').append(PLAIN_INDENT).append(fact.label()).append(": ").append(fact.plainValue());
}
return text.toString();
}
}
@@ -0,0 +1,23 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.pack.PackValidationResult;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/** The build and system blocks, gathered fresh for each reader: the startup print, the command and the debug dump. */
public final class DiagnosticsReport {
private DiagnosticsReport() {
}
public static List<DiagnosticSection> sections(Predicate<PackValidationResult> awaitingExternalContent) {
return List.of(BuildFacts.current(awaitingExternalContent), SystemFacts.current());
}
public static String plainText(Predicate<PackValidationResult> awaitingExternalContent) {
return sections(awaitingExternalContent).stream()
.map(DiagnosticSection::plainText)
.collect(Collectors.joining("\n"));
}
}
@@ -0,0 +1,36 @@
package art.arcane.iris.diagnostics;
import java.time.Duration;
/** The compact units diagnostics print: ages like "36s" or "3d", sizes like "6G" or "512M". */
final class FactFormat {
private static final long SECONDS_PER_MINUTE = 60;
private static final long SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE;
private static final long SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR;
private static final double BYTES_PER_GIB = 1L << 30;
private static final double BYTES_PER_MIB = 1L << 20;
private FactFormat() {
}
static String age(Duration age) {
long seconds = Math.max(0, age.toSeconds());
if (seconds < SECONDS_PER_MINUTE) {
return seconds + "s";
}
if (seconds < SECONDS_PER_HOUR) {
return seconds / SECONDS_PER_MINUTE + "m";
}
if (seconds < SECONDS_PER_DAY) {
return seconds / SECONDS_PER_HOUR + "h";
}
return seconds / SECONDS_PER_DAY + "d";
}
static String size(long bytes) {
if (bytes >= BYTES_PER_GIB) {
return Math.round(bytes / BYTES_PER_GIB) + "G";
}
return Math.round(Math.max(0, bytes) / BYTES_PER_MIB) + "M";
}
}
@@ -0,0 +1,219 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.iris.platform.agent.Agent;
import art.arcane.iris.world.IrisWorldStorage;
import art.arcane.iris.world.pregen.AsyncPregenMethod;
import java.io.IOException;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** The system block: what the host gives this JVM and what Iris made of it. */
public final class SystemFacts {
private static final String TITLE = "System";
private static final Path CPU_INFO = Path.of("/proc/cpuinfo");
private static final Path MEMORY_INFO = Path.of("/proc/meminfo");
private static final List<Path> CONTAINER_MARKERS = List.of(
Path.of("/.dockerenv"), Path.of("/run/.containerenv"), Path.of("/run/systemd/container"));
private static final String CPU_THREAD_ENTRY = "processor";
private static final String CPU_MODEL_ENTRY = "model name";
private static final String AVAILABLE_MEMORY_ENTRY = "MemAvailable:";
private static final long BYTES_PER_KIB = 1024;
private static final String PRE_TOUCH_FLAG = "-XX:+AlwaysPreTouch";
private static final Pattern MAJOR_MINOR_VERSION = Pattern.compile("^(\\d+\\.\\d+)");
private static final List<Pattern> CPU_MODEL_NOISE = List.of(
Pattern.compile("\\((?:R|TM|tm)\\)"),
Pattern.compile("\\s*@.*$"),
Pattern.compile("\\s+\\d+-Core Processor$"),
Pattern.compile("\\s+(?:CPU|Processor)\\b"),
Pattern.compile("^(?:AMD|Intel)\\s+"));
private SystemFacts() {
}
record Cpu(int availableThreads, OptionalInt hostThreads, Optional<String> model) {
}
record Pools(int generation, int io, int pregen) {
}
record Memory(long maxHeapBytes, OptionalLong hostBytes, OptionalLong hostAvailableBytes) {
}
record Jvm(int feature, Optional<String> collector, boolean preTouch, boolean agentAttached) {
}
record Os(String name, String version, String architecture, boolean container) {
}
public static DiagnosticSection current() {
return DiagnosticSection.gather(TITLE, List.of(
() -> cpu(currentCpu()),
() -> pools(currentPools()),
() -> memory(currentMemory()),
() -> jvm(currentJvm()),
() -> os(currentOs()),
() -> disk(IrisWorldStorage.levelRoot().getFreeSpace())));
}
static Optional<DiagnosticFact> cpu(Cpu cpu) {
DiagnosticFact.Items items = new DiagnosticFact.Items();
if (cpu.hostThreads().isEmpty()) {
items.plain(cpu.availableThreads() + " threads available");
cpu.model().ifPresent(items::muted);
return items.fact("CPU");
}
int hostThreads = cpu.hostThreads().getAsInt();
boolean limited = cpu.availableThreads() < hostThreads;
items.flagged(cpu.availableThreads() + " of " + hostThreads + " threads available", limited);
cpu.model().ifPresent(items::muted);
if (limited) {
items.warning("limited");
} else {
items.muted("no limit");
}
return items.fact("CPU");
}
static Optional<DiagnosticFact> pools(Pools pools) {
DiagnosticFact.Items items = new DiagnosticFact.Items();
addPool(items, "generation", pools.generation());
addPool(items, "io", pools.io());
addPool(items, "pregen", pools.pregen());
return items.fact("Iris pools");
}
private static void addPool(DiagnosticFact.Items items, String pool, int workers) {
if (workers > 0) {
items.plain(pool + " " + workers);
}
}
static Optional<DiagnosticFact> memory(Memory memory) {
String heap = "heap " + FactFormat.size(memory.maxHeapBytes());
DiagnosticFact.Items items = new DiagnosticFact.Items();
memory.hostBytes().ifPresentOrElse(
host -> items.plain(heap + " of " + FactFormat.size(host) + " host"),
() -> items.plain(heap));
memory.hostAvailableBytes().ifPresent(available -> items.muted(FactFormat.size(available) + " available"));
return items.fact("Memory");
}
static Optional<DiagnosticFact> jvm(Jvm jvm) {
DiagnosticFact.Items items = new DiagnosticFact.Items().plain("Java " + jvm.feature());
jvm.collector().ifPresent(items::plain);
if (jvm.preTouch()) {
items.muted("pretouch");
}
items.muted(jvm.agentAttached() ? "agent attached" : "no agent");
return items.fact("JVM");
}
static Optional<DiagnosticFact> os(Os os) {
Matcher majorMinor = MAJOR_MINOR_VERSION.matcher(os.version());
String version = majorMinor.find() ? majorMinor.group(1) : os.version();
DiagnosticFact.Items items = new DiagnosticFact.Items()
.plain(os.name() + " " + version)
.muted(os.architecture());
if (os.container()) {
items.muted("container");
}
return items.fact("OS");
}
static Optional<DiagnosticFact> disk(long worldFreeBytes) {
return new DiagnosticFact.Items().plain("world folder " + FactFormat.size(worldFreeBytes) + " free").fact("Disk");
}
/** Drops trademarks, vendor, clock and core count, so "AMD Ryzen 9 7950X 16-Core Processor" reads "Ryzen 9 7950X". */
static String compactCpuModel(String model) {
String compact = model.strip();
for (Pattern noise : CPU_MODEL_NOISE) {
compact = noise.matcher(compact).replaceAll("");
}
return compact.replaceAll("\\s+", " ").strip();
}
private static Cpu currentCpu() {
int availableThreads = Runtime.getRuntime().availableProcessors();
List<String> cpuInfo = readLines(CPU_INFO);
long hostThreads = cpuInfo.stream().filter(line -> line.startsWith(CPU_THREAD_ENTRY)).count();
Optional<String> model = cpuInfo.stream()
.filter(line -> line.startsWith(CPU_MODEL_ENTRY))
.findFirst()
.map(line -> compactCpuModel(line.substring(line.indexOf(':') + 1)));
return new Cpu(availableThreads, hostThreads > 0 ? OptionalInt.of((int) hostThreads) : OptionalInt.empty(), model);
}
private static Pools currentPools() {
return new Pools(MultiBurst.burst.parallelism(), MultiBurst.ioBurst.parallelism(),
AsyncPregenMethod.plannedWorkerThreads());
}
private static Memory currentMemory() {
long maxHeap = Runtime.getRuntime().maxMemory();
OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean();
if (!(system instanceof com.sun.management.OperatingSystemMXBean host)) {
return new Memory(maxHeap, OptionalLong.empty(), OptionalLong.empty());
}
OptionalLong available = availableMemory();
return new Memory(maxHeap, OptionalLong.of(host.getTotalMemorySize()),
available.isPresent() ? available : OptionalLong.of(host.getFreeMemorySize()));
}
/** Linux counts page cache as used in its free figure, so the reclaimable estimate says more about headroom. */
private static OptionalLong availableMemory() {
return readLines(MEMORY_INFO).stream()
.filter(line -> line.startsWith(AVAILABLE_MEMORY_ENTRY))
.findFirst()
.map(line -> line.substring(AVAILABLE_MEMORY_ENTRY.length()).replace("kB", "").strip())
.map(kibibytes -> OptionalLong.of(Long.parseLong(kibibytes) * BYTES_PER_KIB))
.orElse(OptionalLong.empty());
}
private static Jvm currentJvm() {
Optional<String> collector = ManagementFactory.getGarbageCollectorMXBeans().stream()
.findFirst()
.map(GarbageCollectorMXBean::getName)
.map(SystemFacts::collectorName);
boolean preTouch = ManagementFactory.getRuntimeMXBean().getInputArguments().contains(PRE_TOUCH_FLAG);
return new Jvm(Runtime.version().feature(), collector, preTouch, Agent.isInstalled());
}
/** Collector beans are named per generation, like "G1 Young Generation" or "PS Scavenge". */
static String collectorName(String beanName) {
String family = beanName.split(" ", 2)[0];
return switch (family) {
case "PS" -> "Parallel";
case "Copy", "MarkSweepCompact" -> "Serial";
default -> family;
};
}
private static Os currentOs() {
boolean container = CONTAINER_MARKERS.stream().anyMatch(Files::exists);
return new Os(System.getProperty("os.name", "unknown"), System.getProperty("os.version", ""),
System.getProperty("os.arch", "unknown"), container);
}
private static List<String> readLines(Path file) {
if (!Files.isReadable(file)) {
return List.of();
}
try {
return Files.readAllLines(file);
} catch (IOException unreadable) {
return List.of();
}
}
}
@@ -1,40 +1,108 @@
package art.arcane.iris.diagnostics.splash;
import art.arcane.iris.BuildConstants;
import art.arcane.iris.diagnostics.BuildIdentity;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.pack.BuiltInPackUpdates;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
public final class IrisSplashComposer {
private static final String SPLASH_PADDING = " ".repeat(4);
private static final int FIRST_SPARE_INFO_ROW = 7;
private static final int SPARE_INFO_ROWS = 3;
private static final int PACKS_SHOWN = 6;
private static final int LABEL_WIDTH = 14;
private static final String FACT_GAP = " ";
private static final String DEVELOPMENT_TAG_SUFFIX = " DEV";
private static final String DEVELOPMENT_VERSION_SUFFIX = " (dev)";
private IrisSplashComposer() {
}
public static String[] composeInfo(String version, String serverLine, InfoStyle style) {
String releaseTrain = releaseTrain(version);
return composeInfo(version, serverLine, style, List.of());
}
public static String[] composeInfo(String version, String serverLine, InfoStyle style, List<List<Detail>> detailRows) {
return composeInfo(version, serverLine, style, BuildIdentity.current(), detailRows);
}
public static String[] composeInfo(String version, String serverLine, InfoStyle style, BuildIdentity build,
List<List<Detail>> detailRows) {
String[] info = composeHeader(version, serverLine, style, build);
int rows = Math.min(detailRows.size(), SPARE_INFO_ROWS);
for (int row = 0; row < rows; row++) {
info[FIRST_SPARE_INFO_ROW + row] = style.linePrefix() + styledRow(detailRows.get(row), style);
}
return info;
}
public static String plainRow(List<Detail> row) {
return styledRow(row, InfoStyle.PLAIN).strip();
}
public static String packSummary(List<IrisSplashPackScanner.SplashPackMetadata> packs) {
if (packs.isEmpty()) {
return "none";
}
String shown = packs.stream()
.limit(PACKS_SHOWN)
.map(pack -> pack.name() + " v" + pack.version())
.collect(Collectors.joining(", "));
int hidden = packs.size() - PACKS_SHOWN;
return hidden > 0 ? shown + " +" + hidden + " more" : shown;
}
/** The first fact's value starts in the shared value column; further facts on the row follow after a gap. */
private static String styledRow(List<Detail> row, InfoStyle style) {
StringBuilder styled = new StringBuilder();
for (Detail detail : row) {
String label = styled.isEmpty()
? " " + padRight(detail.label(), LABEL_WIDTH)
: FACT_GAP + detail.label() + " ";
styled.append(style.label(label))
.append(detail.headline() ? style.headlineValue(detail.value()) : style.value(detail.value()));
}
return styled.toString();
}
private static String padRight(String text, int width) {
return text + " ".repeat(Math.max(1, width - text.length()));
}
private static String[] composeHeader(String version, String serverLine, InfoStyle style, BuildIdentity build) {
String prefix = style.linePrefix();
String java = javaVersion() < 0 ? "unknown" : String.valueOf(javaVersion());
return new String[]{
prefix + style.title(" Iris, ") + style.subtitle("Dimension Engine ") + style.tag("[" + titleTag(version, build) + "]"),
prefix + styledRow(List.of(Detail.headline("Version", versionLabel(version, build))), style),
prefix + styledRow(List.of(new Detail("By", "Volmit Software (Arcane Arts)")), style),
prefix + styledRow(List.of(new Detail("Web", "volmitsoftware.com")), style),
prefix + styledRow(List.of(Detail.headline("Server", serverLine)), style),
prefix + styledRow(List.of(new Detail("Java", java), new Detail("Date", startupDate())), style),
prefix + styledRow(List.of(new Detail("Commit", build.commitLabel())), style),
"",
prefix + style.title(" Iris, ") + style.subtitle("Dimension Engine ") + style.tag("[" + releaseTrain + "]"),
prefix + style.label(" Version: ") + style.value(version),
prefix + style.label(" By: ") + style.value("Volmit Software (Arcane Arts)"),
prefix + style.label(" Web: ") + style.value("VolmitSoftware.com"),
prefix + style.label(" Server: ") + style.value(serverLine),
prefix + style.label(" Java: ") + style.value(javaVersion() < 0 ? "unknown" : String.valueOf(javaVersion())) + style.label(" | Date: ") + style.value(startupDate()),
prefix + style.label(" Commit: ") + style.value(BuildConstants.COMMIT) + style.label("/") + style.value(BuildConstants.ENVIRONMENT),
"",
"",
""
};
}
private static String titleTag(String version, BuildIdentity build) {
String releaseTrain = releaseTrain(version);
return build.channel().isDevelopment() ? releaseTrain + DEVELOPMENT_TAG_SUFFIX : releaseTrain;
}
private static String versionLabel(String version, BuildIdentity build) {
return build.channel().isDevelopment() ? version + DEVELOPMENT_VERSION_SUFFIX : version;
}
public static String compose(String[] splash, String[] info) {
StringBuilder builder = new StringBuilder("\n\n");
for (int i = 0; i < splash.length; i++) {
@@ -43,29 +111,22 @@ public final class IrisSplashComposer {
return builder.toString();
}
public static CompletableFuture<List<String>> composePackLines(File packFolder, IrisSplashPackScanner.SplashPackErrorReporter reporter) {
List<IrisSplashPackScanner.SplashPackMetadata> packs = IrisSplashPackScanner.collect(packFolder, reporter);
public static CompletableFuture<List<String>> composeUpdateLines(List<IrisSplashPackScanner.SplashPackMetadata> packs) {
return BuiltInPackUpdates.check(packs.stream().map(IrisSplashPackScanner.SplashPackMetadata::name).toList())
.thenApply(updates -> composePackLines(packs, updates));
.thenApply(updates -> composeUpdateLines(packs, updates));
}
static List<String> composePackLines(List<IrisSplashPackScanner.SplashPackMetadata> packs,
Map<String, BuiltInPackUpdates.Update> updates) {
if (packs.isEmpty()) {
return List.of();
}
List<String> lines = new ArrayList<>(packs.size() + 1);
lines.add("Custom Dimensions: " + packs.size());
for (IrisSplashPackScanner.SplashPackMetadata pack : packs) {
BuiltInPackUpdates.Update update = updates.get(pack.name());
lines.add(" " + pack.name() + " v" + pack.version()
+ (update == null ? "" : update.suffix(pack.version())));
}
static List<String> composeUpdateLines(List<IrisSplashPackScanner.SplashPackMetadata> packs,
Map<String, BuiltInPackUpdates.Update> updates) {
List<String> lines = new ArrayList<>();
for (IrisSplashPackScanner.SplashPackMetadata pack : packs) {
BuiltInPackUpdates.Update update = updates.get(pack.name());
if (update != null && update.newerThan(pack.version())) {
lines.add("Update " + pack.name() + ": /iris download pack=" + pack.name() + " overwrite=true");
lines.addAll(ChatReport.of(ChatReport.Tone.INFO, "Pack " + pack.name() + " v" + update.version()
+ " is available. You have v" + pack.version() + ".")
.nextStep("Update it", "/iris download pack=" + pack.name() + " overwrite=true")
.build()
.consoleLines());
}
}
return lines;
@@ -106,6 +167,17 @@ public final class IrisSplashComposer {
return LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
}
/** A headline fact is what support asks for first, so its value stands out from the rest. */
public record Detail(String label, String value, boolean headline) {
public Detail(String label, String value) {
this(label, value, false);
}
public static Detail headline(String label, String value) {
return new Detail(label, value, true);
}
}
public interface InfoStyle {
InfoStyle PLAIN = new InfoStyle() {
};
@@ -133,5 +205,9 @@ public final class IrisSplashComposer {
default String value(String text) {
return text;
}
default String headlineValue(String text) {
return value(text);
}
}
}
@@ -1,5 +1,6 @@
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;
@@ -16,7 +17,7 @@ public final class ChunkBakeCache {
private final PlaneSource source;
private final ConcurrentClockCache<ChunkPlanes> entries;
private final ThreadLocal<Recent> recent = ThreadLocal.withInitial(Recent::new);
private final ThreadSlots<Recent> recent = new ThreadSlots<>(Recent::new);
private volatile int generation;
public ChunkBakeCache(PlaneSource source, int capacityChunks) {
@@ -3,6 +3,7 @@ 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;
@@ -12,26 +13,28 @@ 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(IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) {
private TerrainProgram(PackRuntime runtime, IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) {
this.runtime = runtime;
this.generators = generators;
this.programs = programs;
this.heightSeed = heightSeed;
}
public static TerrainProgram compile(IrisGenerator[][] generators, long heightSeed) {
public static TerrainProgram compile(PackRuntime runtime, 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(heightSeed) : null;
programs[group][index] = generator.supportsBatch() ? generator.compileProgram(runtime, heightSeed) : null;
}
}
return new TerrainProgram(generators, programs, heightSeed);
return new TerrainProgram(runtime, generators, programs, heightSeed);
}
public long heightSeed() {
@@ -58,7 +61,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(x, z, heightSeed);
double noise = program != null ? program.height(scratch, x, z) : members[member].getHeight(runtime, 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
@@ -148,7 +151,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(activeX[index], activeZ[index], heightSeed);
noise[index] = members[member].getHeight(runtime, activeX[index], activeZ[index], heightSeed);
}
}
for (int index = 0; index < activeCount; index++) {
@@ -0,0 +1,155 @@
/*
* 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;
}
}
}
@@ -0,0 +1,57 @@
/*
* 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);
}
}
@@ -0,0 +1,67 @@
/*
* 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,16 +20,12 @@ package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.cave.IrisCaveProfileSampler;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
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 {
@@ -51,8 +47,6 @@ 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() {
@@ -67,33 +61,20 @@ public final class FloatingIslandSample {
return LAST_DENSITY.get()[1];
}
public static void clearThreadCaches() {
CHUNK_MEMO.remove();
FOOTPRINT_MEMO.remove();
LAST_REJECT.remove();
LAST_DENSITY.remove();
public static void clearChunkMemo(PackRuntime runtime) {
runtime.floatingIslandMemo().clear();
}
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);
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();
}
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));
FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler);
memo.remember(parent, column, result);
return result;
}
@@ -184,18 +165,18 @@ public final class FloatingIslandSample {
}
private static int maximumEdgeFieldWidth(KList<IrisFloatingChildBiomes> entries, long baseSeed,
IrisData data, IrisBiome parent) {
PackRuntime runtime, IrisBiome parent) {
int maximumWidth = FloatingIslandEdgeProfile.MIN_WIDTH;
for (IrisFloatingChildBiomes entry : entries) {
FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, data, parent);
FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, runtime, parent);
maximumWidth = Math.max(maximumWidth, profile.fieldWidth());
}
return maximumWidth;
}
private static FloatingIslandEdgeProfile resolveEdgeProfile(IrisFloatingChildBiomes entry, long baseSeed,
IrisData data, IrisBiome parent) {
FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, data);
PackRuntime runtime, IrisBiome parent) {
FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, runtime);
if (profile != null) {
return profile;
}
@@ -203,17 +184,17 @@ public final class FloatingIslandSample {
return FloatingIslandEdgeProfile.DEFAULT;
}
public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) {
public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime, FloatingIslandBoundarySampler boundarySampler) {
KList<IrisFloatingChildBiomes> entries = parent.getFloatingChildBiomes();
if (entries == null || entries.isEmpty()) {
return reject(REJECT_NO_ENTRIES);
}
int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, data, parent);
int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, runtime, parent);
int parentBoundaryDistance = boundarySampler.edgeDistance(parent, wx, wz, boundaryFieldWidth);
if (parent.isMergeFloatingChildBiomes()) {
return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler,
return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler,
parentBoundaryDistance, boundaryFieldWidth);
}
@@ -223,7 +204,7 @@ public final class FloatingIslandSample {
entry = entries.getFirst();
} else {
IrisFloatingChildBiomes reference = entries.getFirst();
CNG picker = reference.getPickerCng(baseSeed, data);
CNG picker = reference.getPickerCng(baseSeed, runtime);
if (picker == null) {
warnNullCng("pickerStyle", parent);
return reject(REJECT_NO_PICK);
@@ -237,20 +218,20 @@ public final class FloatingIslandSample {
ownershipBoundaryDistance = ownership.boundaryDistance();
}
return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler,
return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, runtime, boundarySampler,
parentBoundaryDistance, ownershipBoundaryDistance);
}
private static FloatingIslandSample sampleMerged(IrisBiome parent, KList<IrisFloatingChildBiomes> entries,
int wx, int wz, int chunkHeight, long baseSeed, IrisData data,
Engine engine, FloatingIslandBoundarySampler boundarySampler,
int wx, int wz, int chunkHeight, long baseSeed, PackRuntime runtime,
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, data, engine,
FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, runtime,
boundarySampler, parentBoundaryDistance, boundaryFieldWidth + 1);
if (sample == null) {
continue;
@@ -313,11 +294,11 @@ public final class FloatingIslandSample {
}
private static FloatingIslandSample sampleEntry(IrisBiome parent, IrisFloatingChildBiomes entry, int wx, int wz,
int chunkHeight, long baseSeed, IrisData data, Engine engine,
int chunkHeight, long baseSeed, PackRuntime runtime,
FloatingIslandBoundarySampler boundarySampler,
int parentBoundaryDistance, int ownershipBoundaryDistance) {
FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, data, parent);
CNG footprintCng = entry.getFootprintCng(baseSeed, data);
FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, runtime, parent);
CNG footprintCng = entry.getFootprintCng(baseSeed, runtime);
if (footprintCng == null) {
warnNullCng("footprintStyle", parent);
return reject(REJECT_NO_SEED);
@@ -343,23 +324,23 @@ public final class FloatingIslandSample {
return reject(REJECT_NO_THICKNESS);
}
CNG altitudeCng = entry.getAltitudeCng(baseSeed, data);
CNG altitudeCng = entry.getAltitudeCng(baseSeed, runtime);
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 = engine.getWorld().minHeight();
int worldMin = runtime.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, data);
int fullTopHeight = computeTopHeight(entry, target, engine, baseSeed, wx, wz, data);
IrisBiome target = entry.getRealBiome(parent, runtime.data());
int fullTopHeight = computeTopHeight(entry, target, runtime, baseSeed, wx, wz);
int topH = roundedEdgeHeight(fullTopHeight, edgeFade);
CNG bottomCng = entry.getBottomCng(baseSeed, data);
CNG bottomCng = entry.getBottomCng(baseSeed, runtime);
if (bottomCng == null) {
warnNullCng("bottomStyle", parent);
return reject(REJECT_NO_SEED);
@@ -416,11 +397,11 @@ public final class FloatingIslandSample {
}
boolean[] solidMask = new boolean[thickness];
CNG wallWarp = entry.getWallWarpCng(baseSeed, data);
CNG wallWarp = entry.getWallWarpCng(baseSeed, runtime);
double warpAmp = Math.max(0, entry.getWallWarpAmplitude());
double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade);
IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data);
CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null;
IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(runtime);
CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, runtime) : null;
double carveThreshold = entry.getCarveThreshold();
boolean useWarp = wallWarp != null && effectiveWarpAmp > 0;
boolean useProfileCarve = carvingProfileSampler != null;
@@ -683,27 +664,7 @@ public final class FloatingIslandSample {
}
private static double footprintSigned(CNG footprintCng, int wx, int 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);
return signedFromUnit(footprintCng.noise(wx, wz));
}
private static double signedFromUnit(double value) {
@@ -779,7 +740,7 @@ public final class FloatingIslandSample {
}
}
private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, Engine engine, long baseSeed, int wx, int wz, IrisData data) {
private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, PackRuntime runtime, long baseSeed, int wx, int wz) {
int maxTopHeight = Math.max(0, entry.getMaxTopHeight());
if (maxTopHeight == 0) {
return 0;
@@ -787,7 +748,7 @@ public final class FloatingIslandSample {
return switch (entry.getTopShapeMode()) {
case FLAT -> maxTopHeight;
case NOISE -> {
CNG topCng = entry.getTopShapeCng(baseSeed, data);
CNG topCng = entry.getTopShapeCng(baseSeed, runtime);
if (topCng == null) {
warnNullCng("topShapeStyle", null);
yield maxTopHeight / 2;
@@ -801,7 +762,7 @@ public final class FloatingIslandSample {
if (target == null) {
yield maxTopHeight / 2;
}
double h = target.getHeight(engine, wx, wz, baseSeed);
double h = target.getHeight(runtime, wx, wz, baseSeed);
int rounded = (int) Math.round(h);
if (rounded < 0) {
yield 0;
@@ -810,21 +771,4 @@ 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,6 +18,7 @@
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;
@@ -47,7 +48,6 @@ 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,7 +63,6 @@ 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;
@@ -93,7 +92,6 @@ 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<>();
@@ -104,25 +102,10 @@ 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<>();
@@ -274,16 +257,16 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return IrisBiomeOres.canReplaceSurfaceOre(this, state);
}
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 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 generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) {
return IrisBiomeOres.generateSurfaceOres(this, x, y, z, rng, data);
public NativeBlockState generateSurfaceOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
return IrisBiomeOres.generateSurfaceOres(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 NativeBlockState generateUndergroundOres(int x, int y, int z, RNG rng, PackRuntime runtime) {
return IrisBiomeOres.generateUndergroundOres(this, x, y, z, rng, runtime);
}
public boolean hasSurfaceOres() {
@@ -469,68 +452,38 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
});
}
public double getHeight(Engine xg, double x, double z, long seed) {
public double getHeight(PackRuntime runtime, double x, double z, long seed) {
double height = 0;
for (IrisBiomeGeneratorLink i : generators) {
height += i.getHeight(xg, x, z, seed);
height += i.getHeight(runtime, x, z, seed);
}
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);
return Math.max(0, Math.min(height, runtime.engine().getHeight()));
}
/** 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();
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;
return PackRuntime.of(engine, getLoader()).biome(this).biomeGenerator(seed);
}
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) {
CNG createBiomeGenerator(long seed, PackRuntime runtime) {
int signature = 213949 + 228888 + getRarity() + getName().length();
return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), loader);
return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), runtime);
}
public CNG getChildrenGenerator(RNG random, int sig, double scale) {
return getChildrenGenerator(deriveChildStyleSeed(random, sig).getSeed(), scale);
public CNG getChildrenGenerator(PackRuntime runtime, RNG random, int sig, double scale) {
return getChildrenGenerator(runtime, deriveChildStyleSeed(random, sig).getSeed(), 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;
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);
}
static RNG deriveChildStyleSeed(RNG random, int signature) {
@@ -541,24 +494,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, IrisData rdata, IrisComplex complex) {
return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex);
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> 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> 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> 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> 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> 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> 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> generateSeaLayers(double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, rdata);
public KList<NativeBlockState> generateSeaLayers(double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, runtime);
}
/**
@@ -573,20 +526,20 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
return IrisBiomeLayerGenerator.getMaxWithObjectHeight(this, data, engine);
}
public KList<CNG> getLayerHeightGenerators(RNG rng, IrisData rdata) {
return IrisBiomeLayerGenerator.getLayerHeightGenerators(this, rng, rdata);
public KList<CNG> getLayerHeightGenerators(RNG rng, PackRuntime runtime) {
return runtime.biome(this).layerHeights(rng.getSeed());
}
public KList<CNG> getLayerSeaHeightGenerators(RNG rng, IrisData data) {
return IrisBiomeLayerGenerator.getLayerSeaHeightGenerators(this, rng, data);
public KList<CNG> getLayerSeaHeightGenerators(RNG rng, PackRuntime runtime) {
return runtime.biome(this).seaLayerHeights(rng.getSeed());
}
public KList<CNG> getCaveCeilingLayerHeightGenerators(RNG rng, IrisData data) {
return IrisBiomeLayerGenerator.getCaveCeilingLayerHeightGenerators(this, rng, data);
public KList<CNG> getCaveCeilingLayerHeightGenerators(RNG rng, PackRuntime runtime) {
return runtime.biome(this).ceilingLayerHeights(rng.getSeed());
}
public NativeBlockState getSurfaceBlock(int x, int z, RNG rng, IrisData idm) {
return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, idm);
public NativeBlockState getSurfaceBlock(int x, int z, RNG rng, PackRuntime runtime) {
return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, runtime);
}
public boolean isLand() {
@@ -616,18 +569,10 @@ 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);
}
@@ -656,27 +601,14 @@ 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);
}
@@ -714,37 +646,4 @@ 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,6 +18,7 @@
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;
@@ -81,8 +82,8 @@ public class IrisBiomeGeneratorLink {
});
}
public double getHeight(DataProvider xg, double x, double z, long seed) {
double g = getCachedGenerator(xg).getHeight(x, z, seed);
public double getHeight(PackRuntime runtime, double x, double z, long seed) {
double g = getCachedGenerator(runtime::data).getHeight(runtime, x, z, seed);
g = g < 0 ? 0 : g;
g = g > 1 ? 1 : g;
@@ -18,6 +18,7 @@
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;
@@ -45,18 +46,18 @@ final class IrisBiomeLayerGenerator {
private IrisBiomeLayerGenerator() {
}
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, 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, ProceduralStream<Double> slopeStream) {
return generateLayers(biome, dim, wx, wz, random, maxDepth, height, rdata, null, slopeStream);
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);
}
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) {
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) {
if (biome.isLockLayers()) {
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);
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);
return data;
}
@@ -73,7 +74,8 @@ final class IrisBiomeLayerGenerator {
return data;
}
KList<CNG> heightGenerators = getLayerHeightGenerators(biome, random, rdata);
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.layerHeights(random.getSeed());
double surfaceSlope = 0D;
boolean sampledSlope = false;
@@ -98,7 +100,7 @@ final class IrisBiomeLayerGenerator {
continue;
}
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
appendLayer(data, layer, biomeRuntime.surfaceLayer(i), i, d, wx, wz, random, maxDepth);
if (data.size() >= maxDepth) {
break;
@@ -115,12 +117,12 @@ final class IrisBiomeLayerGenerator {
}
}
appendSurfaceFallback(data, biome, dim, wx, wz, random, maxDepth, rdata);
appendSurfaceFallback(data, biome, dim, wx, wz, random, maxDepth, runtime);
return data;
}
private static void appendSurfaceFallback(KList<NativeBlockState> data, IrisBiome biome, IrisDimension dim,
double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
if (!data.isEmpty() || maxDepth <= 0 || biome.getLayers().isEmpty()) {
return;
}
@@ -129,11 +131,11 @@ final class IrisBiomeLayerGenerator {
fallback = dim.getSurfaceLayerFallback();
}
if (fallback == IrisSurfaceLayerFallback.TOP_LAYER) {
appendLayer(data, biome.getLayers().get(0), 0, 1, wx, wz, random, maxDepth, rdata);
appendLayer(data, biome.getLayers().get(0), runtime.biome(biome).surfaceLayer(0), 0, 1, wx, wz, random, maxDepth);
}
}
static KList<NativeBlockState> generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) {
static KList<NativeBlockState> generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, PackRuntime runtime, IrisComplex complex) {
KList<NativeBlockState> data = new KList<>();
if (maxDepth <= 0) {
@@ -147,7 +149,8 @@ final class IrisBiomeLayerGenerator {
return data;
}
KList<CNG> heightGenerators = getCaveCeilingLayerHeightGenerators(biome, random, rdata);
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.ceilingLayerHeights(random.getSeed());
for (int i = 0; i < layerCount; i++) {
IrisBiomePaletteLayer layer = ceilingLayers.get(i);
@@ -159,7 +162,7 @@ final class IrisBiomeLayerGenerator {
continue;
}
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
appendLayer(data, layer, biomeRuntime.ceilingLayer(i), i, d, wx, wz, random, maxDepth);
if (data.size() >= maxDepth) {
break;
@@ -179,11 +182,11 @@ final class IrisBiomeLayerGenerator {
return data;
}
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);
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);
}
private static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex, ProceduralStream<Double> slopeStream) {
private static KList<NativeBlockState> generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, PackRuntime runtime, IrisComplex complex, ProceduralStream<Double> slopeStream) {
KList<NativeBlockState> data = new KList<>();
int maxDepth = Math.min(maxDepthf, biome.getLockLayersMax());
KList<IrisBiomePaletteLayer> layers = biome.getLayers();
@@ -192,7 +195,8 @@ final class IrisBiomeLayerGenerator {
return data;
}
KList<CNG> heightGenerators = getLayerHeightGenerators(biome, random, rdata);
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.layerHeights(random.getSeed());
int[] boundaries = new int[layerCount + 1];
double surfaceSlope = 0D;
boolean sampledSlope = false;
@@ -227,10 +231,10 @@ final class IrisBiomeLayerGenerator {
int layerIndex = findLayer(boundaries, position);
IrisBiomePaletteLayer layer = layers.get(layerIndex);
int offset = position - boundaries[layerIndex];
double zoom = layer.getZoom();
double blocksPerSample = layer.blocksPerSample();
try {
data.add(layer.get(random, layerIndex + offset,
(wx + offset) / zoom, offset, (wz - offset) / zoom, rdata));
(wx + offset) / blocksPerSample, offset, (wz - offset) / blocksPerSample, biomeRuntime.surfaceLayer(layerIndex)));
} catch (Throwable error) {
GenerationFailures.skipPlacement(error, "surface layer", "block", (int) wx, height - depth, (int) wz, biome.getLoadKey());
}
@@ -274,7 +278,7 @@ final class IrisBiomeLayerGenerator {
: complex.getSlopeStream().getDouble(x, z);
}
static KList<NativeBlockState> generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, IrisData rdata) {
static KList<NativeBlockState> generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, PackRuntime runtime) {
KList<NativeBlockState> data = new KList<>();
KList<IrisBiomePaletteLayer> seaLayers = biome.getSeaLayers();
@@ -284,7 +288,8 @@ final class IrisBiomeLayerGenerator {
return data;
}
KList<CNG> heightGenerators = getLayerSeaHeightGenerators(biome, random, rdata);
BiomeRuntime biomeRuntime = runtime.biome(biome);
KList<CNG> heightGenerators = biomeRuntime.seaLayerHeights(random.getSeed());
for (int i = 0; i < layerCount; i++) {
IrisBiomePaletteLayer layer = seaLayers.get(i);
@@ -296,7 +301,7 @@ final class IrisBiomeLayerGenerator {
continue;
}
appendLayer(data, layer, i, d, wx, wz, random, maxDepth, rdata);
appendLayer(data, layer, biomeRuntime.seaLayer(i), i, d, wx, wz, random, maxDepth);
if (data.size() >= maxDepth) {
break;
@@ -306,46 +311,51 @@ final class IrisBiomeLayerGenerator {
return data;
}
static KList<CNG> getLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData rdata) {
return getHeightGenerators(biome.getLayerHeightGenerators(), biome.getLayers(), 7235, rng, rdata);
static KList<CNG> getLayerHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
return runtime.biome(biome).layerHeights(rng.getSeed());
}
static KList<CNG> getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, IrisData data) {
return getHeightGenerators(biome.getLayerSeaHeightGenerators(), biome.getSeaLayers(), 7735, rng, data);
static KList<CNG> getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
return runtime.biome(biome).seaLayerHeights(rng.getSeed());
}
static KList<CNG> getCaveCeilingLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData data) {
return getHeightGenerators(biome.getLayerCeilingHeightGenerators(), biome.getCaveCeilingLayers(), 7235, rng, data);
static KList<CNG> getCaveCeilingLayerHeightGenerators(IrisBiome biome, RNG rng, PackRuntime runtime) {
return runtime.biome(biome).ceilingLayerHeights(rng.getSeed());
}
private static KList<CNG> getHeightGenerators(IrisBiomeLayerHeightCache cache,
KList<IrisBiomePaletteLayer> layers,
int seedOffset, RNG rng, IrisData data) {
return cache.get(layers, seedOffset, 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 void appendLayer(KList<NativeBlockState> blocks, IrisBiomePaletteLayer layer,
int layerIndex, int thickness, double x, double z,
RNG random, int maxDepth, IrisData data) {
double zoom = layer.getZoom();
PaletteLayerRuntime layerRuntime, int layerIndex, int thickness, double x, double z,
RNG random, int maxDepth) {
double blocksPerSample = layer.blocksPerSample();
for (int offset = 0; offset < thickness && blocks.size() < maxDepth; offset++) {
try {
blocks.add(layer.get(random, layerIndex + offset,
(x + offset) / zoom, offset, (z - offset) / zoom, data));
(x + offset) / blocksPerSample, offset, (z - offset) / blocksPerSample, layerRuntime));
} 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, IrisData idm) {
static NativeBlockState getSurfaceBlock(IrisBiome biome, int x, int z, RNG rng, PackRuntime runtime) {
KList<IrisBiomePaletteLayer> layers = biome.getLayers();
if (layers.isEmpty()) {
return B.getState("AIR");
}
return layers.get(0).get(rng, x, 0, z, idm);
return layers.get(0).get(rng, x, 0, z, runtime);
}
static int getMaxHeight(IrisBiome biome, Engine engine) {
@@ -1,68 +0,0 @@
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.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
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, IrisData data, boolean surface) {
static NativeBlockState generateOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime, boolean surface) {
KList<IrisOreGenerator> localOres = surface ? getSurfaceOres(biome) : getUndergroundOres(biome);
return generateOres(localOres, x, y, z, rng, data);
return generateOres(localOres, 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 generateSurfaceOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime) {
return generateOres(getSurfaceOres(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 NativeBlockState generateUndergroundOres(IrisBiome biome, int x, int y, int z, RNG rng, PackRuntime runtime) {
return generateOres(getUndergroundOres(biome), x, y, z, rng, runtime);
}
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, IrisData data) {
private static NativeBlockState generateOres(KList<IrisOreGenerator> localOres, int x, int y, int z, RNG rng, PackRuntime runtime) {
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, data);
NativeBlockState ore = oreGenerator.generate(x, y, z, rng, runtime);
if (ore != null) {
return ore;
}
@@ -18,6 +18,7 @@
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;
@@ -25,8 +26,6 @@ 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;
@@ -37,17 +36,12 @@ 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)
@@ -56,24 +50,7 @@ import java.util.concurrent.atomic.AtomicReferenceArray;
@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"})
@@ -98,23 +75,17 @@ 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, 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;
public CNG getHeightGenerator(RNG rng, PackRuntime runtime) {
long generatorSeed = rng.getSeed() + minHeight * maxHeight + getBlockData(runtime.data()).size();
return runtime.paletteLayer(this).heightGenerator(generatorSeed);
}
public NativeBlockState get(RNG rng, double x, double y, double z, IrisData data) {
return get(rng, 0, x, y, z, data);
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);
}
/**
@@ -122,44 +93,53 @@ 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, IrisData data) {
KList<NativeBlockState> localBlockData = getBlockData(data);
if (localBlockData.isEmpty()) {
return null;
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);
}
if (localBlockData.size() == 1) {
return localBlockData.get(0);
/** {@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);
}
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);
}
double localZoom = zoom;
double scaledX = x / localZoom;
double scaledY = y / localZoom;
double scaledZ = z / localZoom;
return getLayerGenerator(parent, signature, data).fit(localBlockData, scaledX, scaledY, scaledZ);
return generator.fit(localBlockData, x / localZoom, y / localZoom, z / localZoom);
}
public CNG getLayerGenerator(RNG rng, IrisData data) {
return getLayerGenerator(rng, 0, data);
/** 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 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 rng, PackRuntime runtime) {
return getLayerGenerator(rng, 0, 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 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);
}
public KList<IrisBlockData> add(String b) {
@@ -195,49 +175,4 @@ 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,6 +18,7 @@
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;
@@ -33,10 +34,6 @@ 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;
@@ -62,97 +59,72 @@ 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, IrisData data) {
return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, data);
public CNG getFootprintCng(long baseSeed, PackRuntime runtime) {
return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, runtime);
}
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;
public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, PackRuntime runtime) {
return runtime.floatingChild(this).edgeTaperProfile(baseSeed);
}
public CNG getPickerCng(long baseSeed, IrisData data) {
return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, data);
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 getAltitudeCng(long baseSeed, IrisData data) {
return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, data);
public CNG getPickerCng(long baseSeed, PackRuntime runtime) {
return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, runtime);
}
public CNG getTopShapeCng(long baseSeed, IrisData data) {
return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, data);
public CNG getAltitudeCng(long baseSeed, PackRuntime runtime) {
return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, runtime);
}
public CNG getBottomCng(long baseSeed, IrisData data) {
return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, data);
public CNG getTopShapeCng(long baseSeed, PackRuntime runtime) {
return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, runtime);
}
public CNG getWallWarpCng(long baseSeed, IrisData data) {
public CNG getBottomCng(long baseSeed, PackRuntime runtime) {
return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, runtime);
}
public CNG getWallWarpCng(long baseSeed, PackRuntime runtime) {
IrisGeneratorStyle style = getWallWarpStyle();
if (style == null) {
return null;
}
return style.create(baseSeed ^ 0xA117BA17E0FL, data);
return style.create(baseSeed ^ 0xA117BA17E0FL, runtime);
}
public CNG getCarveCng(long baseSeed, IrisData data) {
public CNG getCarveCng(long baseSeed, PackRuntime runtime) {
IrisGeneratorStyle style = getCarveStyle();
if (style == null) {
return null;
}
return style.create(baseSeed ^ 0xCA5EC1EE5EL, data);
return style.create(baseSeed ^ 0xCA5EC1EE5EL, runtime);
}
public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) {
public IrisCaveProfileSampler getCarvingProfileSampler(PackRuntime runtime) {
if (!hasCarvingReference()) {
return null;
}
return runtime.floatingChild(this).carvingProfileSampler();
}
CachedCarvingProfile recent = recentCarvingProfile;
if (recent != null && recent.key.matches(0L, data, engine)) {
return recent.sampler;
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;
}
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;
return new IrisCaveProfileSampler(engine, resolved.getCaveProfile());
}
public boolean hasCarvingReference() {
@@ -400,28 +372,4 @@ 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) {
}
}
@@ -0,0 +1,57 @@
/*
* 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);
}
}
@@ -84,6 +84,14 @@ public class B {
return state != null && state.isTreeBlock();
}
public static boolean isLog(NativeBlockState state) {
return state != null && state.isLog();
}
public static boolean isLeaves(NativeBlockState state) {
return state != null && state.isLeaves();
}
public static boolean isFoliagePlantable(NativeBlockState state) {
return state != null && state.isFoliagePlantable();
}
@@ -1,49 +0,0 @@
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();
}
}
@@ -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.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
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) {
IrisData data = engine.getData();
PackRuntime runtime = PackRuntime.of(engine, 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), data);
this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data);
this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data);
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);
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), data) : null;
thresholdDensity = thresholdHasNoise ? threshold.getStyle().create(baseRng.nextParallelRNG(489_112), runtime) : 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)), data);
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), runtime);
ModuleState state = new ModuleState(module, moduleDensity);
moduleStates.add(state);
weight += Math.abs(state.weight);
@@ -18,6 +18,7 @@
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;
@@ -46,6 +47,7 @@ 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);
@@ -92,25 +94,27 @@ final class DecoratorCore {
}
static IrisDecorator pickDecorator(IrisBiome biome, IrisDecorationPart part, RNG gRNG,
RNG colRng, IrisData data, double realX, double realZ) {
RNG colRng, PackRuntime runtime, 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 (IrisDecorator d : bucket) {
for (int index = 0; index < bucket.length; index++) {
IrisDecorator d = bucket[index];
try {
if (d.passesChanceGate(gRNG, realX, realZ, data)) {
if (d.passesChanceGate(gRNG, realX, realZ, decoratorRuntimes[index])) {
count++;
if (count == 1 || colRng.nextInt(count) == 0) {
picked = d;
}
}
} catch (Throwable e) {
skip(e, d, data, (int) realX, -1, (int) realZ, biome);
skip(e, d, runtime.data(), (int) realX, -1, (int) realZ, biome);
}
}
@@ -119,14 +123,14 @@ final class DecoratorCore {
static void placeSurfaceSingle(IrisDecorator decorator,
int x, int z, int realX, int height, int realZ,
Hunk<NativeBlockState> data, RNG rng, IrisData irisData,
Hunk<NativeBlockState> data, RNG rng, PackRuntime runtime,
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, irisData, realX, realZ);
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
if (!IrisSpeleothems.isSpike(bd) && !underwater && !canGoOn(bd, bdx)
&& !decorator.isForcePlace() && decorator.getForceBlock() == null) {
@@ -138,14 +142,14 @@ final class DecoratorCore {
return;
}
data.set(x, height, z, fixFacesForHunk(
decorator.getForceBlock().getBlockData(irisData), data, x, z, realX, height, realZ, mantle));
decorator.getForceBlock().getBlockData(runtime.data()), data, x, z, realX, height, realZ, mantle));
}
if (!decorator.isForcePlace()) {
if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(irisData), bdx)) {
if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(runtime.data()), bdx)) {
return;
}
if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(irisData), bdx)) {
if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(runtime.data()), bdx)) {
return;
}
}
@@ -176,7 +180,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, irisData, realX, lowerY, realZ, null);
skip(e, decorator, runtime.data(), realX, lowerY, realZ, null);
}
return;
}
@@ -202,8 +206,8 @@ final class DecoratorCore {
static void placeSingleAt(IrisDecorator decorator, int x, int z,
int realX, int height, int realZ, Hunk<NativeBlockState> data,
RNG rng, IrisData irisData, boolean applyFixFaces, EngineMantle mantle) {
NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
RNG rng, PackRuntime runtime, boolean applyFixFaces, EngineMantle mantle) {
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
if (bd == null) {
return;
}
@@ -212,7 +216,7 @@ final class DecoratorCore {
return;
}
if (IrisSpeleothems.isSpike(bd)) {
if (height + 1 < data.getHeight() && allowsSurface(decorator, data.get(x, height + 1, z), irisData)) {
if (height + 1 < data.getHeight() && allowsSurface(decorator, data.get(x, height + 1, z), runtime.data())) {
placeSingleSpike(bd, data, x, z, height, false, false);
}
return;
@@ -225,17 +229,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, IrisData irisData, PlaceOpts opts) {
RNG rng, PackRuntime runtime, PlaceOpts opts) {
if (height < 0 || height >= data.getHeight()) {
return;
}
NativeBlockState support = data.get(x, height, z);
if (!allowsSurface(decorator, support, irisData)) {
if (!allowsSurface(decorator, support, runtime.data())) {
return;
}
int effectiveMax = opts.underwater ? Math.min(max, opts.fluidHeight - height) : max;
int stack = computeStack(decorator, rng, realX, realZ, irisData, effectiveMax);
int stack = computeStack(decorator, rng, realX, realZ, runtime, effectiveMax);
int placed = 0;
boolean hasSpikes = false;
NativeBlockState sampledBlock = null;
@@ -254,8 +258,8 @@ final class DecoratorCore {
boolean top = threshold >= decorator.getTopThreshold();
if (sampledBlock == null || top != sampledTop) {
sampledBlock = top
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
: decorator.pickBlockData(rng, runtime, realX, realZ);
sampledTop = top;
}
NativeBlockState block = sampledBlock;
@@ -288,15 +292,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, IrisData irisData, int max, PlaceOpts opts, EngineMantle mantle) {
RNG rng, PackRuntime runtime, 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, irisData)) {
if (!allowsSurface(decorator, support, runtime.data())) {
return;
}
int stack = computeStack(decorator, rng, realX, realZ, irisData, max);
int stack = computeStack(decorator, rng, realX, realZ, runtime, max);
int placed = 0;
boolean hasSpikes = false;
NativeBlockState sampledBlock = null;
@@ -315,8 +319,8 @@ final class DecoratorCore {
boolean top = threshold >= decorator.getTopThreshold();
if (sampledBlock == null || top != sampledTop) {
sampledBlock = top
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
: decorator.pickBlockData(rng, runtime, realX, realZ);
sampledTop = top;
}
NativeBlockState block = sampledBlock;
@@ -349,11 +353,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, IrisData irisData, EngineMantle mantle) {
RNG rng, PackRuntime runtime, EngineMantle mantle) {
if (!hasFloatingSurface(data, xf, height, zf)) {
return;
}
NativeBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ);
NativeBlockState bd = decorator.pickBlockData(rng, runtime, realX, realZ);
if (bd == null) {
return;
}
@@ -363,7 +367,7 @@ final class DecoratorCore {
}
if (IrisSpeleothems.isSpike(bd)) {
if (max > 1 && allowsSurface(decorator, data.get(xf, height, zf), irisData)) {
if (max > 1 && allowsSurface(decorator, data.get(xf, height, zf), runtime.data())) {
placeSingleSpike(bd, data, xf, zf, height + 1, true, false);
}
return;
@@ -383,7 +387,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, irisData, realX, lowerY, realZ, null);
skip(e, decorator, runtime.data(), realX, lowerY, realZ, null);
}
return;
}
@@ -396,11 +400,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, IrisData irisData, EngineMantle mantle) {
RNG rng, PackRuntime runtime, EngineMantle mantle) {
if (!hasFloatingSurface(data, xf, height, zf)) {
return 0;
}
int stack = decorator.getHeight(rng, realX, realZ, irisData);
int stack = decorator.getHeight(rng, realX, realZ, runtime);
if (decorator.isScaleStack()) {
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack());
} else {
@@ -420,8 +424,8 @@ final class DecoratorCore {
boolean top = threshold >= decorator.getTopThreshold();
if (sampledBlock == null || top != sampledTop) {
sampledBlock = top
? decorator.pickBlockDataTop(rng, irisData, realX, realZ)
: decorator.pickBlockData(rng, irisData, realX, realZ);
? decorator.pickBlockDataTop(rng, runtime, realX, realZ)
: decorator.pickBlockData(rng, runtime, realX, realZ);
sampledTop = top;
}
NativeBlockState bd = sampledBlock;
@@ -433,7 +437,7 @@ final class DecoratorCore {
break;
}
if (IrisSpeleothems.isSpike(bd)) {
if (!allowsSurface(decorator, data.get(xf, height, zf), irisData)
if (!allowsSurface(decorator, data.get(xf, height, zf), runtime.data())
|| !IrisSpeleothems.canPlace(bd, data, xf, zf, h, true, false)) {
break;
}
@@ -581,8 +585,8 @@ final class DecoratorCore {
}
static int computeStack(IrisDecorator decorator, RNG rng, double realX, double realZ,
IrisData irisData, int max) {
int stack = decorator.getHeight(rng, realX, realZ, irisData);
PackRuntime runtime, int max) {
int stack = decorator.getHeight(rng, realX, realZ, runtime);
if (decorator.isScaleStack()) {
stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack());
} else {
@@ -0,0 +1,57 @@
/*
* 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);
}
}
@@ -0,0 +1,75 @@
/*
* 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,6 +18,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.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -36,7 +37,8 @@ public class FloatingDecorator {
int height, int max, Hunk<NativeBlockState> data, RNG rng,
Runnable candidatesNullCallback) {
RNG gRNG = new RNG(DecoratorCore.partSeed(engine.getSeedManager().getComponent(), part));
IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, engine.getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(engine);
IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, runtime, realX, realZ);
if (decorator == null) {
candidatesNullCallback.run();
@@ -45,11 +47,11 @@ public class FloatingDecorator {
if (!decorator.isStacking()) {
DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data,
gRNG, engine.getData(), engine.getMantle());
gRNG, runtime, engine.getMantle());
return max > 1 ? 1 : 0;
}
return DecoratorCore.placeFloatingStacked(decorator, xf, zf, realX, realZ, height, max, data,
gRNG, engine.getData(), engine.getMantle());
gRNG, runtime, engine.getMantle());
}
}
@@ -1,5 +1,6 @@
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;
@@ -32,7 +33,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, IrisData data) {
public void decorate(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, WaterRole role, Water water, PackRuntime runtime) {
Placement placement = placement(role);
if (placement == Placement.NONE) {
return;
@@ -45,7 +46,7 @@ public final class HydrologyVegetation {
if (ground < 0 || ground + 1 >= output.getHeight()) {
return;
}
Column column = new Column(output, localX, localZ, x, z, ground, water, data);
Column column = new Column(output, localX, localZ, x, z, ground, water, runtime);
if (placement == Placement.SHORE) {
decorateShore(column, decorators.shore);
return;
@@ -112,7 +113,7 @@ public final class HydrologyVegetation {
int count = 0;
for (IrisDecorator decorator : bucket) {
try {
if (!decorator.passesChanceGate(partRng, column.x, column.z, column.data)) {
if (!decorator.passesChanceGate(partRng, column.x, column.z, column.runtime)) {
continue;
}
} catch (Throwable e) {
@@ -213,9 +214,10 @@ 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, IrisData data) {
private Column(Hunk<NativeBlockState> output, int localX, int localZ, int x, int z, int ground, Water water, PackRuntime runtime) {
this.output = output;
this.localX = localX;
this.localZ = localZ;
@@ -223,7 +225,8 @@ public final class HydrologyVegetation {
this.z = z;
this.ground = ground;
this.water = water;
this.data = data;
this.runtime = runtime;
this.data = runtime.data();
}
private boolean accepts(IrisDecorator decorator, NativeBlockState support) {
@@ -231,7 +234,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, data, room)) : 1;
return decorator.isStacking() ? Math.min(room, DecoratorCore.computeStack(decorator, rng, x, z, runtime, room)) : 1;
}
private void place(IrisDecorator decorator, RNG rng, int baseY, int room, Slot slot, NativeBlockState support) {
@@ -243,7 +246,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, data, x, z);
NativeBlockState first = decorator.pickBlockData(rng, runtime, x, z);
if (first == null) {
return;
}
@@ -260,7 +263,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, data, x, z) : decorator.pickBlockData(rng, data, x, z);
sampled = top ? decorator.pickBlockDataTop(rng, runtime, x, z) : decorator.pickBlockData(rng, runtime, x, z);
sampledTop = top;
}
NativeBlockState block = sampled == null ? null : fit(sampled, y, slot, decorator, index == 0 ? support : null);
@@ -18,6 +18,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.generation.terrain.InferredType;
import art.arcane.iris.generation.biome.IrisBiome;
@@ -47,21 +48,22 @@ 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);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
if (decorator == null) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, height, max, caveSkipFluid);
place(decorator, x, z, realX, realZ, data, height, max, caveSkipFluid, runtime);
} 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) {
int height, int max, boolean caveSkipFluid, PackRuntime runtime) {
if (!decorator.isStacking()) {
if (caveSkipFluid) {
NativeBlockState state = data.get(x, height, z);
@@ -69,13 +71,13 @@ public class IrisCeilingDecorator extends IrisEngineDecorator {
return;
}
}
DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, partRNG, getData(), true, getEngine().getMantle());
DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, partRNG, runtime, 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, getData(), max, opts, getEngine().getMantle());
DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, partRNG, runtime, 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,8 +52,6 @@ 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<>();
@@ -118,50 +116,39 @@ 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, IrisData data) {
public int getHeight(RNG rng, double x, double z, PackRuntime runtime) {
if (stackMin == stackMax) {
return stackMin;
}
return getHeightGenerator(rng, data)
return getHeightGenerator(rng, runtime)
.fit(stackMin, stackMax,
x / heightVariance.getZoom(),
z / heightVariance.getZoom());
}
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 getHeightGenerator(RNG rng, PackRuntime runtime) {
return runtime.decorator(this).heightGenerator(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 getGenerator(RNG rng, PackRuntime runtime) {
return runtime.decorator(this).layerGenerator(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 getVarianceGenerator(RNG rng, PackRuntime runtime) {
return runtime.decorator(this).varianceGenerator(rng.getSeed());
}
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 createHeightGenerator(long seed, PackRuntime runtime) {
return heightVariance.create(new RNG(seed).nextParallelRNG(getBlockData(runtime.data()).size() + stackMax + stackMin), runtime);
}
private CNG createVarianceGenerator(RNG rng, IrisData data) {
return variance.createNoCache(deriveVarianceSeed(rng, data), data).scale(1D / variance.getZoom());
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());
}
RNG deriveVarianceSeed(RNG rng, IrisData data) {
@@ -173,27 +160,38 @@ public class IrisDecorator {
return palette;
}
public boolean passesChanceGate(RNG rng, double x, double z, IrisData data) {
if (getBlockData(data).isEmpty()) {
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()) {
return false;
}
double xx = x / style.getZoom();
double zz = z / style.getZoom();
return getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance;
double blocksPerSample = chanceBlocksPerSample();
double xx = x / blocksPerSample;
double zz = z / blocksPerSample;
return decoratorRuntime.layerGenerator(rng.getSeed()).fitDouble(0D, 1D, xx, zz) <= chance;
}
public NativeBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, IrisData data) {
if (!passesChanceGate(rng, x, z, data)) {
/** 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)) {
return null;
}
if (getBlockData(data).size() == 1) {
return getBlockData(data).get(0);
if (getBlockData(runtime.data()).size() == 1) {
return getBlockData(runtime.data()).get(0);
}
return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x);
return getVarianceGenerator(rng, runtime).fit(getBlockData(runtime.data()), z, x);
}
public NativeBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) {
KList<NativeBlockState> palette = getBlockData(data);
public NativeBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, PackRuntime runtime) {
KList<NativeBlockState> palette = getBlockData(runtime.data());
if (palette.isEmpty()) {
IrisLogging.warnOnce("decorator-empty:" + b.getName(), "Empty Block Data for " + b.getName());
return null;
@@ -203,24 +201,25 @@ public class IrisDecorator {
return palette.get(0);
}
return getVarianceGenerator(rng, data).fit(palette, z, y, x); //X and Z must be switched
return getVarianceGenerator(rng, runtime).fit(palette, z, y, x); //X and Z must be switched
}
public NativeBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) {
KList<NativeBlockState> topPalette = getBlockDataTops(data);
public NativeBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, PackRuntime runtime) {
KList<NativeBlockState> topPalette = getBlockDataTops(runtime.data());
if (topPalette.isEmpty()) {
return getBlockData100(b, rng, x, y, z, data);
return getBlockData100(b, rng, x, y, z, runtime);
}
double xx = x / style.getZoom();
double zz = z / style.getZoom();
double blocksPerSample = chanceBlocksPerSample();
double xx = x / blocksPerSample;
double zz = z / blocksPerSample;
if (getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here
if (getGenerator(rng, runtime).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here
if (topPalette.size() == 1) {
return topPalette.get(0);
}
return getVarianceGenerator(rng, data).fit(topPalette, z, y, x); //X and Z must be switched
return getVarianceGenerator(rng, runtime).fit(topPalette, z, y, x); //X and Z must be switched
}
return null;
@@ -336,55 +335,30 @@ public class IrisDecorator {
return resolved;
}
public NativeBlockState pickBlockData(RNG rng, IrisData data, double x, double z) {
NativeBlockState[] arr = getBlockDataArray(data);
public NativeBlockState pickBlockData(RNG rng, PackRuntime runtime, double x, double z) {
NativeBlockState[] arr = getBlockDataArray(runtime.data());
if (arr.length == 0) {
return null;
}
if (arr.length == 1) {
return arr[0];
}
return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))];
return arr[Math.abs((int) getVarianceGenerator(rng, runtime).fit(0, arr.length - 1, z, x))];
}
public NativeBlockState pickBlockDataTop(RNG rng, IrisData data, double x, double z) {
NativeBlockState[] arr = getBlockDataTopsArray(data);
public NativeBlockState pickBlockDataTop(RNG rng, PackRuntime runtime, double x, double z) {
NativeBlockState[] arr = getBlockDataTopsArray(runtime.data());
if (arr.length == 0) {
return pickBlockData(rng, data, x, z);
return pickBlockData(rng, runtime, x, z);
}
if (arr.length == 1) {
return arr[0];
}
return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))];
return arr[Math.abs((int) getVarianceGenerator(rng, runtime).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,6 +18,7 @@
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;
@@ -62,12 +63,10 @@ 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)
@@ -145,54 +144,47 @@ public class IrisDepositGenerator {
@Description("If set to true, this deposit will replace bedrock")
private boolean replaceBedrock = false;
public IrisObject getClump(Engine engine, RNG rng, IrisData rdata) {
public IrisObject getClump(PackRuntime runtime, RNG rng) {
if (shape != IrisDepositShape.IRIS) {
return generateConfiguredClumpObject(rng, rdata, minSize, maxSize);
return generateConfiguredClumpObject(rng, runtime.data(), minSize, maxSize);
}
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;
});
KList<IrisObject> objects = runtime.deposit(this).clumps();
return objects.get(rng.i(0, objects.size()));
}
public IrisObject getClump(Engine engine, RNG rng, IrisData rdata, double sizeMultiplier) {
public IrisObject getClump(PackRuntime runtime, RNG rng, double sizeMultiplier) {
if (sizeMultiplier == 1D) {
return getClump(engine, rng, rdata);
return getClump(runtime, rng);
}
int scaledMinSize = scaledDepositSize(minSize, sizeMultiplier);
int scaledMaxSize = scaledDepositSize(maxSize, sizeMultiplier);
if (shape != IrisDepositShape.IRIS) {
return generateConfiguredClumpObject(rng, rdata, scaledMinSize, scaledMaxSize);
return generateConfiguredClumpObject(rng, runtime.data(), 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;
});
KList<IrisObject> objects = runtime.deposit(this).scaledClumps(scaledMinSize, scaledMaxSize);
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)));
}
@@ -279,7 +271,7 @@ public class IrisDepositGenerator {
}
/**
* Advances {@code rng} exactly as {@link #getClump(Engine, RNG, IrisData)} would and reports the clump's width
* Advances {@code rng} exactly as {@link #getClump(PackRuntime, RNG)} 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.
*/
@@ -682,9 +674,6 @@ 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,7 +1,6 @@
package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.value.IrisRange;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.collection.KList;
@@ -11,20 +10,24 @@ 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 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.
* 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()}.
*/
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 IrisOreGenerator[][] byY;
private final int[][] byY;
private IrisOreBands(IrisOreGenerator[] generators, int minY, int maxY, IrisOreGenerator[][] byY) {
private IrisOreBands(IrisOreGenerator[] generators, int minY, int maxY, int[][] byY) {
this.generators = generators;
this.everyGenerator = new int[generators.length];
Arrays.setAll(everyGenerator, index -> index);
this.minY = minY;
this.maxY = maxY;
this.byY = byY;
@@ -57,19 +60,19 @@ public final class IrisOreBands {
height > MAXIMUM_INDEXED_HEIGHT ? null : index(generators, minY, (int) height));
}
private static IrisOreGenerator[][] index(IrisOreGenerator[] generators, int minY, int height) {
IrisOreGenerator[][] byY = new IrisOreGenerator[height][];
IrisOreGenerator[] scratch = new IrisOreGenerator[generators.length];
IrisOreGenerator[] previous = null;
private static int[][] index(IrisOreGenerator[] generators, int minY, int height) {
int[][] byY = new int[height][];
int[] scratch = new int[generators.length];
int[] previous = null;
for (int offset = 0; offset < height; offset++) {
int y = minY + offset;
int count = 0;
for (IrisOreGenerator generator : generators) {
if (generator.getRange().contains(y)) {
scratch[count++] = generator;
for (int index = 0; index < generators.length; index++) {
if (generators[index].getRange().contains(y)) {
scratch[count++] = index;
}
}
IrisOreGenerator[] candidates = Arrays.copyOf(scratch, count);
int[] candidates = Arrays.copyOf(scratch, count);
byY[offset] = previous != null && Arrays.equals(previous, candidates) ? previous : candidates;
previous = byY[offset];
}
@@ -92,13 +95,18 @@ 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.
*/
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);
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);
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,72 +56,46 @@ 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);
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 void warm(RNG rng, PackRuntime runtime) {
runtime.oreChance(this, rng.getSeed());
palette.getLayerGenerator(rng, runtime);
}
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)) {
public NativeBlockState generate(int x, int y, int z, RNG rng, PackRuntime runtime) {
if (!canPlaceAt(y)) {
return null;
}
return placeByChance(x, y, z, rng, runtime.oreChance(this, rng.getSeed()), runtime);
}
if (palette.getPalette().isEmpty()) {
/** 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)) {
return null;
}
return placeByChance(x, y, z, rng, chance, runtime);
}
if (chance(rng, data, engine).sample(x, y, z) > threshold) {
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) {
return null;
}
return palette.get(rng, x, y, z, data);
return palette.get(rng, x, y, z, 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) {
public OreChance createChance(long seed, PackRuntime runtime) {
return OreChance.of(chanceStyle.create(new RNG(seed), runtime));
}
/**
* 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.
*/
private record OreChance(CNG noise, boolean constant, double value) {
public 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,6 +18,7 @@
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;
@@ -59,7 +60,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, data);
return palette.get(paletteRng, x, y, z, PackRuntime.forPack(data));
}
if (block != null && !block.isEmpty()) {
return B.getStateOrNull(block, false);
@@ -18,6 +18,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.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -42,27 +43,28 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator {
return;
}
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
if (decorator == null) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, biome, height, max, limit);
place(decorator, x, z, realX, realZ, data, biome, height, max, limit, runtime);
} 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) {
IrisBiome biome, int height, int max, int limit, PackRuntime runtime) {
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, getData());
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
if (block != null) {
data.set(x, height, z, block);
}
@@ -70,13 +72,13 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator {
}
int stack = Math.min(limit - height,
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height));
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, 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, getData())
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
if (block == null) {
break;
}
@@ -18,6 +18,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.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -42,25 +43,26 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
return;
}
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
if (decorator == null) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, biome, height, max, maxBaseY);
place(decorator, x, z, realX, realZ, data, biome, height, max, maxBaseY, runtime);
} 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) {
IrisBiome biome, int height, int max, int maxBaseY, PackRuntime runtime) {
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, getData());
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
if (block != null) {
data.set(x, targetY, z, block);
}
@@ -69,7 +71,7 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator {
}
int stack = Math.min(maxBaseY - height,
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height));
DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height));
for (int i = 0; i < stack; i++) {
int h = height + i;
int targetY = h + 1;
@@ -78,8 +80,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, getData())
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
if (block == null) {
break;
}
@@ -18,6 +18,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.generation.biome.IrisBiome;
import art.arcane.volmlib.util.hunk.Hunk;
@@ -78,7 +79,8 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
int max
) {
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
if (decorator == null) {
return;
@@ -90,14 +92,14 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
}
try {
placePicked(decorator, x, z, realX, realZ, data, biome, height, max);
placePicked(decorator, x, z, realX, realZ, data, biome, height, max, runtime);
} 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) {
IrisBiome biome, int height, int max, PackRuntime runtime) {
NativeBlockState support = data.get(x, height, z);
if (support == null || !support.isSolid()) {
return;
@@ -111,7 +113,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
|| !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) {
return;
}
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, getData());
NativeBlockState block = decorator.getBlockData100(biome, partRNG, realX, height, realZ, runtime);
if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)
&& IrisSugarCane.canPlace(block, data, x, targetY, z, realX, realZ, getEngine())) {
data.set(x, targetY, z, block);
@@ -120,7 +122,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
return;
}
int stack = DecoratorCore.computeStack(decorator, partRNG, realX, realZ, getData(), max - height);
int stack = DecoratorCore.computeStack(decorator, partRNG, realX, realZ, runtime, max - height);
if (stack == 1) {
int targetY = height + 1;
@@ -128,7 +130,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
return;
}
NativeBlockState block = decorator.getBlockDataForTop(biome, partRNG, realX, height, realZ, getData());
NativeBlockState block = decorator.getBlockDataForTop(biome, partRNG, realX, height, realZ, runtime);
if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)
&& IrisSugarCane.canPlace(block, data, x, targetY, z, realX, realZ, getEngine())) {
data.set(x, targetY, z, block);
@@ -146,8 +148,8 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator {
}
double threshold = ((double) i) / (stack - 1);
NativeBlockState block = threshold >= decorator.getTopThreshold()
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, getData())
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, getData());
? decorator.getBlockDataForTop(biome, partRNG, realX, h, realZ, runtime)
: decorator.getBlockData100(biome, partRNG, realX, h, realZ, runtime);
if (block == null) {
break;
}
@@ -1,5 +1,6 @@
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;
@@ -79,7 +80,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, engine.getData());
new RNG(engine.getSeedManager().getTerrain()), fluidHeight - terrainHeight, PackRuntime.of(engine));
int depth = fluidHeight - y;
return supportsAdjacent(layers.hasIndex(depth) ? layers.get(depth) : complex.resolveSeaFluid(x, z));
}
@@ -18,6 +18,7 @@
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;
@@ -73,21 +74,22 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator {
}
boolean caveSkipFluid = skipsFluid(inferredType);
RNG rng = getRNG(realX, realZ);
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ);
PackRuntime runtime = PackRuntime.of(getEngine(), getData());
IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, runtime, realX, realZ);
if (decorator == null || !isSlopeValid(decorator, realX, height, realZ)) {
return;
}
try {
place(decorator, x, z, realX, realZ, data, height, max, underwater, fluidHeight, caveSkipFluid);
place(decorator, x, z, realX, realZ, data, height, max, underwater, fluidHeight, caveSkipFluid, runtime);
} 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) {
int height, int max, boolean underwater, int fluidHeight, boolean caveSkipFluid, PackRuntime runtime) {
AquaticPlacementSnapshot aquaticSnapshot = captureAquaticPlacement(
decorator, getData(), data, x, z, height, max);
if (decorator.isStacking()) {
@@ -97,13 +99,17 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator {
opts.fluidHeight = fluidHeight;
opts.caveSkipFluid = caveSkipFluid;
opts.mantle = getEngine().getMantle();
DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, partRNG, getData(), opts);
try {
DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, partRNG, runtime, opts);
} finally {
opts.mantle = null;
}
aquaticSnapshot.restoreIfUnsupported(data, x, z);
return;
}
DecoratorCore.placeSurfaceSingle(decorator, x, z, realX, height, realZ,
data, partRNG, getData(), underwater, caveSkipFluid, getEngine().getMantle());
data, partRNG, runtime, underwater, caveSkipFluid, getEngine().getMantle());
aquaticSnapshot.restoreIfUnsupported(data, x, z);
}
@@ -0,0 +1,68 @@
/*
* 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,6 +18,7 @@
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;
@@ -59,7 +60,7 @@ public final class FormationBlockResolver {
strataRng = new RNG(formation.getSeed() + band * 31L);
strataRngs.put(band, strataRng);
}
NativeBlockState strataState = strata.get(strataRng, x, band, z, data);
NativeBlockState strataState = strata.get(strataRng, x, band, z, PackRuntime.forPack(data));
if (strataState != null) {
return strataState;
}
@@ -18,6 +18,7 @@
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;
@@ -84,7 +85,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(), data);
return tree.getSecondaryLeavesPalette().get(paletteRng, pos.x(), pos.y(), pos.z(), PackRuntime.forPack(data));
}
if (tree.getWeightedSecondaryLeaves() != null && !tree.getWeightedSecondaryLeaves().isEmpty()) {
String picked = pickWeighted(tree, new RNG(tree.getSeed() ^ positionHash(pos)));
@@ -117,7 +118,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(), data);
return palette.get(paletteRng, pos.x(), pos.y(), pos.z(), PackRuntime.forPack(data));
}
if (block != null && !block.isEmpty()) {
return B.getStateOrNull(block, false);
@@ -1,5 +1,6 @@
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;
@@ -78,7 +79,7 @@ public final class HydrologyRuntime {
private final NaturalHeights naturalHeight;
private final BooleanSupplier mainThread;
private final RasterLru rasters;
private final ThreadLocal<LastRaster> last;
private final ThreadSlots<LastRaster> last;
private final Set<Long> queued;
private final ConcurrentHashMap<Long, CompletableFuture<ChunkWaterRaster>> building;
private final RasterFailures failures;
@@ -132,7 +133,7 @@ public final class HydrologyRuntime {
this.naturalHeight = Objects.requireNonNull(naturalHeight, "naturalHeight");
this.mainThread = Objects.requireNonNull(mainThread, "mainThread");
this.rasters = new RasterLru();
this.last = ThreadLocal.withInitial(LastRaster::new);
this.last = new ThreadSlots<>(LastRaster::new);
this.queued = ConcurrentHashMap.newKeySet();
this.building = new ConcurrentHashMap<>();
this.failures = new RasterFailures(ticker);
Loaded 100 of 431 files, more files were not shown because too many files have changed in this diff. Show more