mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 00:34:19 +00:00
Stabilized shutdown and Studio
- Shutdown protection initializes before enable and drains inline when retention fails - Cleanup preserves class loader retention and closes native providers in order - Error reports retain context and handle empty stack traces - Studio maps retain partial coverage and suspend hidden views - Hydrology previews refresh when plans and rasters complete - Terrain scratch hashing spreads lattice samples across cache slots - Plugin and probe artifacts include LWJGL libraries and native resources - Regression tests cover shutdown, error reporting, map progress, and terrain scratch
This commit is contained in:
1 parent
f64a7c6753
commit
3dc958edcf
31 files changed
+1973
-217
No files matched your search
+9
-1
@@ -47,6 +47,7 @@ import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntBinaryOperator;
|
||||
@@ -79,6 +80,7 @@ public final class HydrologyRuntime {
|
||||
private final HydrologyBinding binding;
|
||||
private final Function<PreparedHydrologyCacheIdentity, HydrologyPlanStore> stores;
|
||||
private final boolean caveFluidPolicies;
|
||||
private final AtomicLong rasterRevision = new AtomicLong();
|
||||
private volatile PreparedHydrologyCacheIdentity storeIdentity;
|
||||
private boolean storeOpen;
|
||||
private volatile boolean closed;
|
||||
@@ -210,6 +212,10 @@ public final class HydrologyRuntime {
|
||||
return settings;
|
||||
}
|
||||
|
||||
public long previewRevision() {
|
||||
return cache == null ? 0L : cache.readyRevision() + rasterRevision.get();
|
||||
}
|
||||
|
||||
public PreviewScope preview() {
|
||||
return new PreviewScope(cache == null ? null : last.get());
|
||||
}
|
||||
@@ -696,7 +702,9 @@ public final class HydrologyRuntime {
|
||||
|
||||
private ChunkWaterRaster remember(long key, ChunkWaterRaster raster) {
|
||||
synchronized (rasters) {
|
||||
rasters.put(key, raster);
|
||||
if (rasters.put(key, raster) == null) {
|
||||
rasterRevision.incrementAndGet();
|
||||
}
|
||||
}
|
||||
last.get().remember(key, raster);
|
||||
return raster;
|
||||
|
||||
+8
-1
@@ -57,6 +57,7 @@ public final class HydrologyPlanCache {
|
||||
private final AtomicLong demands = new AtomicLong();
|
||||
private final AtomicLong speculations = new AtomicLong();
|
||||
private final AtomicLong previewStamps = new AtomicLong(Long.MIN_VALUE);
|
||||
private final AtomicLong readyRevision = new AtomicLong();
|
||||
private final Shelf<RegionKey, RegionPlan> regions = new Shelf<>(REGION_CAPACITY, this::startRegion);
|
||||
private final Shelf<WindowKey, IndexedWindow> windows = new Shelf<>(WINDOW_CAPACITY, this::startWindow);
|
||||
private final Map<Object, Set<Slot<?, ?>>> epochSlots = new HashMap<>();
|
||||
@@ -112,6 +113,10 @@ public final class HydrologyPlanCache {
|
||||
return windows.evictions.get();
|
||||
}
|
||||
|
||||
public long readyRevision() {
|
||||
return readyRevision.get();
|
||||
}
|
||||
|
||||
public RegionPlan region(RegionKey key) {
|
||||
Objects.requireNonNull(key, "key");
|
||||
requireOffMainThread("region " + key.rx() + "," + key.rz());
|
||||
@@ -759,7 +764,9 @@ public final class HydrologyPlanCache {
|
||||
|
||||
private void succeed(V value) {
|
||||
release();
|
||||
future.complete(value);
|
||||
if (future.complete(value)) {
|
||||
readyRevision.incrementAndGet();
|
||||
}
|
||||
shelf.evict();
|
||||
}
|
||||
|
||||
|
||||
@@ -78,8 +78,10 @@ public final class TerrainBatchScratch {
|
||||
int lattice(double x, double z) {
|
||||
long xBits = Double.doubleToRawLongBits(x);
|
||||
long zBits = Double.doubleToRawLongBits(z);
|
||||
long mixed = xBits * 0x9E3779B97F4A7C15L ^ Long.rotateLeft(zBits * 0xC2B2AE3D27D4EB4FL, 31);
|
||||
mixed ^= mixed >>> 29;
|
||||
long mixed = xBits ^ Long.rotateLeft(zBits, 32);
|
||||
mixed = (mixed ^ (mixed >>> 33)) * 0xFF51AFD7ED558CCDL;
|
||||
mixed = (mixed ^ (mixed >>> 33)) * 0xC4CEB9FE1A85EC53L;
|
||||
mixed ^= mixed >>> 33;
|
||||
int mask = latticeCapacity - 1;
|
||||
int slot = (int) mixed & mask;
|
||||
while (true) {
|
||||
|
||||
@@ -1668,7 +1668,6 @@ public class IrisEngine implements Engine {
|
||||
} catch (GenerationSessionException e) {
|
||||
throw e;
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
fail("Failed to generate " + x + ", " + z, e);
|
||||
if (e instanceof WrongEngineBroException wrongEngine) {
|
||||
throw wrongEngine;
|
||||
|
||||
@@ -365,4 +365,10 @@ public final class BukkitPlatform implements IrisPlatform {
|
||||
public void reportError(Throwable error) {
|
||||
bridge().errorSink().accept(error);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reportError(String context, Throwable error) {
|
||||
log(LogLevel.ERROR, context == null || context.isBlank() ? "Unhandled Iris failure." : context);
|
||||
reportError(error);
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -1,6 +1,7 @@
|
||||
package art.arcane.iris.platform.bukkit.nms;
|
||||
|
||||
import art.arcane.iris.platform.agent.Agent;
|
||||
import art.arcane.iris.platform.bootstrap.SlimJar;
|
||||
import art.arcane.iris.platform.generation.PlatformChunkGenerator;
|
||||
import art.arcane.iris.generation.runtime.EngineTarget;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
@@ -8,6 +9,7 @@ import art.arcane.iris.world.lifecycle.WorldLifecycleStaging;
|
||||
import art.arcane.volmlib.nativelib.terrain.NativeWorldLifecyclePolicy;
|
||||
import org.bukkit.generator.ChunkGenerator;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.instrument.Instrumentation;
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -41,7 +43,23 @@ public enum BukkitWorldLifecyclePolicy implements NativeWorldLifecyclePolicy {
|
||||
|
||||
@Override
|
||||
public void releaseClassLoader(ClassLoader loader) {
|
||||
Agent.releaseClassLoader(loader);
|
||||
Throwable providerFailure = null;
|
||||
try {
|
||||
SlimJar.closeNativeProviders();
|
||||
} catch (IOException | RuntimeException | Error failure) {
|
||||
providerFailure = failure;
|
||||
}
|
||||
try {
|
||||
Agent.releaseClassLoader(loader);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
if (providerFailure != null) {
|
||||
failure.addSuppressed(providerFailure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
if (providerFailure != null) {
|
||||
throw new IllegalStateException("Failed to close Iris native providers", providerFailure);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -290,6 +290,10 @@ public interface INMSBinding extends NativeTerrainAccess {
|
||||
|
||||
boolean missingDimensionTypes(String... keys);
|
||||
|
||||
default void initializeLifecycle(ClassLoader loader) {
|
||||
throw new IllegalStateException("Plugin class loader shutdown protection is unavailable");
|
||||
}
|
||||
|
||||
default boolean injectBukkit() {
|
||||
return true;
|
||||
}
|
||||
@@ -301,8 +305,8 @@ public interface INMSBinding extends NativeTerrainAccess {
|
||||
default void uninjectBukkit() {
|
||||
}
|
||||
|
||||
default boolean deferPluginClassLoaderClose() {
|
||||
return false;
|
||||
default void deferPluginClassLoaderClose() {
|
||||
throw new IllegalStateException("Plugin class loader shutdown protection is unavailable");
|
||||
}
|
||||
|
||||
default void releasePluginClassLoaderClose() {
|
||||
|
||||
@@ -276,9 +276,21 @@ final class MapCanvas extends JPanel {
|
||||
|
||||
// Tiles keep loading in the background only for the view on screen; a hidden canvas stops asking for new ones.
|
||||
void setActive(boolean nextActive) {
|
||||
if (closed || active == nextActive) {
|
||||
return;
|
||||
}
|
||||
active = nextActive;
|
||||
if (active) {
|
||||
markerTimer.start();
|
||||
provisionalTimer.start();
|
||||
requestRender();
|
||||
} else {
|
||||
controller.suspend();
|
||||
hoverTimer.stop();
|
||||
legendTimer.stop();
|
||||
markerTimer.stop();
|
||||
provisionalTimer.stop();
|
||||
clearHover();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1021,6 +1033,9 @@ final class MapCanvas extends JPanel {
|
||||
}
|
||||
|
||||
private void onTilesChanged() {
|
||||
if (closed || !active) {
|
||||
return;
|
||||
}
|
||||
tileLayerStale = true;
|
||||
repaint();
|
||||
refreshStatus();
|
||||
|
||||
@@ -112,6 +112,7 @@ public final class MapWindow implements MapCanvas.Listener {
|
||||
private double worldCenterX;
|
||||
private double worldCenterZ;
|
||||
private MapView currentView;
|
||||
private boolean windowVisible = true;
|
||||
private double paletteCenterX;
|
||||
private double paletteCenterZ;
|
||||
|
||||
@@ -190,11 +191,55 @@ public final class MapWindow implements MapCanvas.Listener {
|
||||
frame.setMinimumSize(StudioTheme.scaledSize(820, 520));
|
||||
frame.setLocationRelativeTo(null);
|
||||
frame.addWindowListener(new WindowAdapter() {
|
||||
@Override
|
||||
public void windowIconified(WindowEvent event) {
|
||||
updateWindowVisibility();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void windowDeiconified(WindowEvent event) {
|
||||
updateWindowVisibility();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void windowClosed(WindowEvent event) {
|
||||
close();
|
||||
}
|
||||
});
|
||||
frame.addComponentListener(new ComponentAdapter() {
|
||||
@Override
|
||||
public void componentShown(ComponentEvent event) {
|
||||
updateWindowVisibility();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void componentHidden(ComponentEvent event) {
|
||||
updateWindowVisibility();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void updateWindowVisibility() {
|
||||
boolean visible = isWindowVisible();
|
||||
boolean wasVisible = windowVisible;
|
||||
windowVisible = visible;
|
||||
canvas.setActive(visible && currentView != null && currentView.isTileMap());
|
||||
if (currentView == MapView.WORLD_3D && worldExplorer != null) {
|
||||
if (visible && !wasVisible) {
|
||||
worldExplorer.show(worldCenterX, worldCenterZ, false);
|
||||
} else if (!visible) {
|
||||
worldExplorer.hide();
|
||||
}
|
||||
}
|
||||
if (visible) {
|
||||
resourceUsage.start();
|
||||
} else {
|
||||
resourceUsage.stop();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isWindowVisible() {
|
||||
return frame.isShowing() && (frame.getExtendedState() & JFrame.ICONIFIED) == 0;
|
||||
}
|
||||
|
||||
private JToolBar buildToolbar() {
|
||||
@@ -265,6 +310,7 @@ public final class MapWindow implements MapCanvas.Listener {
|
||||
}
|
||||
frame.getRootPane().revalidate();
|
||||
frame.getRootPane().repaint();
|
||||
updateWindowVisibility();
|
||||
}
|
||||
|
||||
private void showMap(MapView previousView, MapView view) {
|
||||
@@ -272,7 +318,7 @@ public final class MapWindow implements MapCanvas.Listener {
|
||||
canvas.centerOn(paletteExplorer.centerX(), paletteExplorer.centerZ());
|
||||
}
|
||||
canvas.showView(view);
|
||||
canvas.setActive(true);
|
||||
canvas.setActive(isWindowVisible());
|
||||
showControls(mapControls);
|
||||
waterToggle.setVisible(view == MapView.BIOMES);
|
||||
if (view == MapView.REGIONS) {
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
package art.arcane.iris.studio.map;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.generation.stream.ProvisionalSampling;
|
||||
import art.arcane.iris.studio.map.components.MapTileRenderer;
|
||||
import art.arcane.iris.studio.map.components.MapLabels;
|
||||
import art.arcane.iris.studio.map.components.MapLayer;
|
||||
@@ -39,6 +38,7 @@ import java.util.Set;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
@@ -48,6 +48,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
/**
|
||||
* Renders the map as tiles on fixed zoom levels, so zooming within a level and panning reuse tiles that are already drawn.
|
||||
@@ -67,6 +68,7 @@ final class VisionRenderController implements AutoCloseable {
|
||||
private static final long CACHE_BYTES = 256L * 1024L * 1024L;
|
||||
|
||||
private final Runnable listener;
|
||||
private final LongSupplier nanoTime;
|
||||
private final int workerCount;
|
||||
private final ThreadPoolExecutor renderExecutor;
|
||||
private final ThreadPoolExecutor probeExecutor;
|
||||
@@ -79,9 +81,15 @@ final class VisionRenderController implements AutoCloseable {
|
||||
private final AtomicBoolean publicationQueued = new AtomicBoolean();
|
||||
private final AtomicBoolean publicationDirty = new AtomicBoolean();
|
||||
private volatile Frame currentFrame;
|
||||
private Future<?> activeProbe;
|
||||
|
||||
VisionRenderController(Runnable listener) {
|
||||
this(listener, System::nanoTime);
|
||||
}
|
||||
|
||||
VisionRenderController(Runnable listener, LongSupplier nanoTime) {
|
||||
this.listener = Objects.requireNonNull(listener, "listener");
|
||||
this.nanoTime = Objects.requireNonNull(nanoTime, "nanoTime");
|
||||
int processors = Math.max(1, Runtime.getRuntime().availableProcessors());
|
||||
this.workerCount = Math.max(1, Math.min(6, processors / 2));
|
||||
AtomicInteger threadSequence = new AtomicInteger();
|
||||
@@ -123,11 +131,10 @@ final class VisionRenderController implements AutoCloseable {
|
||||
List<VisibleTile> tiles = visibleTiles(spec, renderScale);
|
||||
Frame frame = new Frame(viewSequence.incrementAndGet(), spec, renderScale, tiles);
|
||||
for (VisibleTile tile : tiles) {
|
||||
tile.setTile(cachedTileServing(tile.key()));
|
||||
tile.state = cachedTileServing(tile.key());
|
||||
}
|
||||
currentFrame = frame;
|
||||
probeSequence.incrementAndGet();
|
||||
probeExecutor.getQueue().clear();
|
||||
cancelProbe();
|
||||
startWorkers();
|
||||
publish();
|
||||
return frame;
|
||||
@@ -141,25 +148,41 @@ final class VisionRenderController implements AutoCloseable {
|
||||
startWorkers();
|
||||
}
|
||||
|
||||
synchronized void suspend() {
|
||||
currentFrame = null;
|
||||
cancelProbe();
|
||||
}
|
||||
|
||||
/**
|
||||
* A tile from another zoom level covering the given one, to draw while the real tile renders.
|
||||
*/
|
||||
Fallback fallback(Frame frame, VisibleTile tile) {
|
||||
MapTile withoutHeights = cache.get(tile.key().withHeights(false));
|
||||
Fallback complete = fallback(tile.key(), false);
|
||||
return complete != null || tile.tile() != null ? complete : fallback(tile.key(), true);
|
||||
}
|
||||
|
||||
private Fallback fallback(TileKey key, boolean provisional) {
|
||||
MapTile withoutHeights = fallbackTile(key.withHeights(false), provisional);
|
||||
if (withoutHeights != null) {
|
||||
return new Fallback(List.of(new FallbackPiece(withoutHeights, 0, 0, TILE_PIXELS, 0D, 0D, 1D)));
|
||||
}
|
||||
Fallback coarser = coarserFallback(frame, tile);
|
||||
return coarser != null ? coarser : finerFallback(frame, tile);
|
||||
Fallback coarser = coarserFallback(key, provisional);
|
||||
return coarser != null ? coarser : finerFallback(key, provisional);
|
||||
}
|
||||
|
||||
// A tile drawn with heights serves just as well where no heights are needed, so turning shading off redraws nothing.
|
||||
private MapTile cachedTileServing(TileKey key) {
|
||||
MapTile exact = cache.get(key);
|
||||
private TileState cachedTileServing(TileKey key) {
|
||||
CacheEntry exact = cache.get(key);
|
||||
if (exact != null || key.heights()) {
|
||||
return exact;
|
||||
return exact == null ? null : exact.state();
|
||||
}
|
||||
return cache.get(key.withHeights(true));
|
||||
CacheEntry shaded = cache.get(key.withHeights(true));
|
||||
return shaded != null && !shaded.state().provisional() ? shaded.state() : null;
|
||||
}
|
||||
|
||||
private MapTile fallbackTile(TileKey key, boolean provisional) {
|
||||
CacheEntry entry = cache.get(key);
|
||||
return entry != null && entry.state().provisional() == provisional ? entry.state().tile() : null;
|
||||
}
|
||||
|
||||
Progress progress(Frame frame) {
|
||||
@@ -168,34 +191,44 @@ final class VisionRenderController implements AutoCloseable {
|
||||
}
|
||||
int ready = 0;
|
||||
for (VisibleTile tile : frame.tiles()) {
|
||||
if (tile.tile() != null && !tile.provisional) {
|
||||
if (tile.tile() != null && !tile.provisional()) {
|
||||
ready++;
|
||||
}
|
||||
}
|
||||
return new Progress(frame.tiles().size(), ready, activeWorkers.get());
|
||||
}
|
||||
|
||||
<T> void submitProbe(Frame frame, Callable<T> probe, Consumer<T> consumer) {
|
||||
synchronized <T> void submitProbe(Frame frame, Callable<T> probe, Consumer<T> consumer) {
|
||||
Objects.requireNonNull(probe, "probe");
|
||||
Objects.requireNonNull(consumer, "consumer");
|
||||
if (frame == null || closed.get() || currentFrame != frame) {
|
||||
return;
|
||||
}
|
||||
long probeRevision = probeSequence.incrementAndGet();
|
||||
probeExecutor.getQueue().clear();
|
||||
cancelProbe();
|
||||
long probeRevision = probeSequence.get();
|
||||
try {
|
||||
probeExecutor.execute(() -> runProbe(probeRevision, probe, consumer));
|
||||
activeProbe = probeExecutor.submit(() -> runProbe(probeRevision, probe, consumer));
|
||||
} catch (RejectedExecutionException ignored) {
|
||||
probeExecutor.getQueue().clear();
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelProbe() {
|
||||
probeSequence.incrementAndGet();
|
||||
if (activeProbe != null) {
|
||||
activeProbe.cancel(true);
|
||||
activeProbe = null;
|
||||
}
|
||||
probeExecutor.getQueue().clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void close() {
|
||||
if (!closed.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
currentFrame = null;
|
||||
cancelProbe();
|
||||
renderExecutor.shutdownNow();
|
||||
probeExecutor.shutdownNow();
|
||||
cache.clear();
|
||||
@@ -285,7 +318,7 @@ final class VisionRenderController implements AutoCloseable {
|
||||
|
||||
private synchronized boolean hasWork() {
|
||||
Frame frame = currentFrame;
|
||||
return frame != null && frame.nextMissing(tilesInFlight, false) != null;
|
||||
return frame != null && frame.nextMissing(tilesInFlight, false, nanoTime.getAsLong()) != null;
|
||||
}
|
||||
|
||||
private synchronized TileJob claimNextTile() {
|
||||
@@ -293,51 +326,63 @@ final class VisionRenderController implements AutoCloseable {
|
||||
if (frame == null || closed.get()) {
|
||||
return null;
|
||||
}
|
||||
VisibleTile tile = frame.nextMissing(tilesInFlight, true);
|
||||
VisibleTile tile = frame.nextMissing(tilesInFlight, true, nanoTime.getAsLong());
|
||||
if (tile == null) {
|
||||
return null;
|
||||
}
|
||||
tilesInFlight.add(tile.key());
|
||||
return new TileJob(frame.spec().renderer(), tile.key());
|
||||
CacheEntry cached = cache.get(tile.key());
|
||||
return new TileJob(frame.spec().renderer(), tile.key(), cached == null ? null : cached.work(), tile.state);
|
||||
}
|
||||
|
||||
private synchronized void release(TileKey key) {
|
||||
private synchronized void release(TileKey key, boolean cancelled) {
|
||||
tilesInFlight.remove(key);
|
||||
Frame frame = currentFrame;
|
||||
VisibleTile visible = frame == null ? null : frame.tile(key);
|
||||
if (cancelled && visible != null && visible.needsRender(nanoTime.getAsLong(), frame.spec().renderer().previewRevision())) {
|
||||
frame.nextCandidate = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void render(TileJob job) {
|
||||
TileKey key = job.key();
|
||||
boolean cancelled = false;
|
||||
try {
|
||||
long previewRevision = job.renderer().previewRevision();
|
||||
double tileSpan = TILE_PIXELS * key.blocksPerPixel();
|
||||
long revision = ProvisionalSampling.revision();
|
||||
MapTile tile = job.renderer().renderTile(
|
||||
key.tileX() * tileSpan,
|
||||
key.tileZ() * tileSpan,
|
||||
key.blocksPerPixel(),
|
||||
TILE_PIXELS,
|
||||
key.layer(),
|
||||
key.heights(),
|
||||
() -> !isWanted(key)
|
||||
);
|
||||
boolean provisional = revision != ProvisionalSampling.revision();
|
||||
MapTileRenderer.TileRender work = job.work();
|
||||
if (work == null) {
|
||||
work = job.renderer().prepareTile(key.tileX() * tileSpan, key.tileZ() * tileSpan,
|
||||
key.blocksPerPixel(), TILE_PIXELS, key.layer(), key.heights());
|
||||
}
|
||||
MapTile tile = work.render(() -> !isWanted(key));
|
||||
boolean provisional = !work.complete();
|
||||
TileState previous = job.previous();
|
||||
long delay = 0L;
|
||||
if (provisional) {
|
||||
delay = previous == null || previous.retryDelay() == 0L
|
||||
? FIRST_RETRY_NANOS : Math.min(LAST_RETRY_NANOS, previous.retryDelay() * 2L);
|
||||
}
|
||||
long completedAt = nanoTime.getAsLong();
|
||||
TileState state = new TileState(tile, provisional, delay, completedAt + delay,
|
||||
completedAt + FIRST_RETRY_NANOS, previewRevision);
|
||||
synchronized (this) {
|
||||
if (!isWanted(key)) {
|
||||
if (closed.get()) {
|
||||
return;
|
||||
}
|
||||
VisibleTile visible = currentFrame.tile(key);
|
||||
if (provisional) {
|
||||
visible.markProvisional(tile, System.nanoTime());
|
||||
} else {
|
||||
cache.put(key, tile);
|
||||
visible.setTile(tile);
|
||||
cache.put(key, state, provisional ? work : null);
|
||||
if (isWanted(key)) {
|
||||
currentFrame.tile(key).state = state;
|
||||
}
|
||||
}
|
||||
publish();
|
||||
} catch (CancellationException ignored) {
|
||||
cancelled = true;
|
||||
cache.discardWork(key);
|
||||
} catch (Throwable error) {
|
||||
IrisLogging.debug("Vision tile render failed: " + error.getClass().getSimpleName() + ": " + error.getMessage());
|
||||
} finally {
|
||||
release(key);
|
||||
release(key, cancelled);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,8 +391,7 @@ final class VisionRenderController implements AutoCloseable {
|
||||
return !closed.get() && frame != null && frame.tile(key) != null;
|
||||
}
|
||||
|
||||
private Fallback coarserFallback(Frame frame, VisibleTile tile) {
|
||||
TileKey key = tile.key();
|
||||
private Fallback coarserFallback(TileKey key, boolean provisional) {
|
||||
for (int level = 1; level <= COARSER_FALLBACK_LEVELS; level++) {
|
||||
long scale = 1L << level;
|
||||
int sourceSize = TILE_PIXELS >> level;
|
||||
@@ -357,8 +401,8 @@ final class VisionRenderController implements AutoCloseable {
|
||||
}
|
||||
long parentX = Math.floorDiv(key.tileX(), scale);
|
||||
long parentZ = Math.floorDiv(key.tileZ(), scale);
|
||||
MapTile parent = cache.get(new TileKey(key.contentRevision(), key.layer(), key.heights(), parentScale, parentX,
|
||||
parentZ));
|
||||
MapTile parent = fallbackTile(new TileKey(key.contentRevision(), key.layer(), key.heights(), parentScale,
|
||||
parentX, parentZ), provisional);
|
||||
if (parent != null) {
|
||||
int sourceX = (int) (key.tileX() - parentX * scale) * sourceSize;
|
||||
int sourceZ = (int) (key.tileZ() - parentZ * scale) * sourceSize;
|
||||
@@ -368,8 +412,7 @@ final class VisionRenderController implements AutoCloseable {
|
||||
return null;
|
||||
}
|
||||
|
||||
private Fallback finerFallback(Frame frame, VisibleTile tile) {
|
||||
TileKey key = tile.key();
|
||||
private Fallback finerFallback(TileKey key, boolean provisional) {
|
||||
double childScale = key.blocksPerPixel() / 2D;
|
||||
if (childScale < MINIMUM_RENDER_BLOCKS_PER_PIXEL) {
|
||||
return null;
|
||||
@@ -377,8 +420,8 @@ final class VisionRenderController implements AutoCloseable {
|
||||
List<FallbackPiece> pieces = new ArrayList<>(4);
|
||||
for (int childZ = 0; childZ < 2; childZ++) {
|
||||
for (int childX = 0; childX < 2; childX++) {
|
||||
MapTile child = cache.get(new TileKey(key.contentRevision(), key.layer(), key.heights(), childScale,
|
||||
key.tileX() * 2L + childX, key.tileZ() * 2L + childZ));
|
||||
MapTile child = fallbackTile(new TileKey(key.contentRevision(), key.layer(), key.heights(), childScale,
|
||||
key.tileX() * 2L + childX, key.tileZ() * 2L + childZ), provisional);
|
||||
if (child != null) {
|
||||
pieces.add(new FallbackPiece(child, 0, 0, TILE_PIXELS, childX * 0.5D, childZ * 0.5D, 0.5D));
|
||||
}
|
||||
@@ -528,10 +571,11 @@ final class VisionRenderController implements AutoCloseable {
|
||||
}
|
||||
|
||||
// Tiles are sorted centre first, and everything before the cursor is drawn or claimed, so each search resumes there.
|
||||
private VisibleTile nextMissing(Set<TileKey> inFlight, boolean advance) {
|
||||
private VisibleTile nextMissing(Set<TileKey> inFlight, boolean advance, long now) {
|
||||
long previewRevision = spec.renderer().previewRevision();
|
||||
for (int index = nextCandidate; index < tiles.size(); index++) {
|
||||
VisibleTile tile = tiles.get(index);
|
||||
if (tile.needsRender(System.nanoTime()) && !inFlight.contains(tile.key())) {
|
||||
if (tile.needsRender(now, previewRevision) && !inFlight.contains(tile.key())) {
|
||||
if (advance) {
|
||||
nextCandidate = index + 1;
|
||||
}
|
||||
@@ -548,10 +592,7 @@ final class VisionRenderController implements AutoCloseable {
|
||||
static final class VisibleTile {
|
||||
private final TileKey key;
|
||||
private final double distanceSquared;
|
||||
private volatile MapTile tile;
|
||||
private volatile boolean provisional;
|
||||
private long retryDelay;
|
||||
private long retryAt;
|
||||
private volatile TileState state;
|
||||
|
||||
private VisibleTile(TileKey key, double distanceSquared) {
|
||||
this.key = key;
|
||||
@@ -575,28 +616,19 @@ final class VisionRenderController implements AutoCloseable {
|
||||
}
|
||||
|
||||
MapTile tile() {
|
||||
return tile;
|
||||
TileState current = state;
|
||||
return current == null ? null : current.tile();
|
||||
}
|
||||
|
||||
boolean provisional() {
|
||||
return provisional;
|
||||
TileState current = state;
|
||||
return current != null && current.provisional();
|
||||
}
|
||||
|
||||
private void setTile(MapTile tile) {
|
||||
this.tile = tile;
|
||||
provisional = false;
|
||||
retryDelay = 0L;
|
||||
}
|
||||
|
||||
private void markProvisional(MapTile tile, long now) {
|
||||
this.tile = tile;
|
||||
retryDelay = retryDelay == 0L ? FIRST_RETRY_NANOS : Math.min(LAST_RETRY_NANOS, retryDelay * 2L);
|
||||
retryAt = now + retryDelay;
|
||||
provisional = true;
|
||||
}
|
||||
|
||||
private boolean needsRender(long now) {
|
||||
return tile == null || provisional && now - retryAt >= 0L;
|
||||
private boolean needsRender(long now, long previewRevision) {
|
||||
TileState current = state;
|
||||
return current == null || current.provisional() && (now - current.retryAt() >= 0L
|
||||
|| previewRevision != current.previewRevision() && now - current.earliestRetryAt() >= 0L);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,7 +677,11 @@ final class VisionRenderController implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
private record TileJob(MapTileRenderer renderer, TileKey key) {
|
||||
private record TileJob(MapTileRenderer renderer, TileKey key, MapTileRenderer.TileRender work, TileState previous) {
|
||||
}
|
||||
|
||||
private record TileState(MapTile tile, boolean provisional, long retryDelay, long retryAt, long earliestRetryAt,
|
||||
long previewRevision) {
|
||||
}
|
||||
|
||||
private static final class WeightedTileCache {
|
||||
@@ -658,14 +694,13 @@ final class VisionRenderController implements AutoCloseable {
|
||||
this.entries = new LinkedHashMap<>(128, 0.75F, true);
|
||||
}
|
||||
|
||||
synchronized MapTile get(TileKey key) {
|
||||
CacheEntry entry = entries.get(key);
|
||||
return entry == null ? null : entry.tile();
|
||||
synchronized CacheEntry get(TileKey key) {
|
||||
return entries.get(key);
|
||||
}
|
||||
|
||||
synchronized void put(TileKey key, MapTile tile) {
|
||||
long tileBytes = tile.bytes();
|
||||
CacheEntry previous = entries.put(key, new CacheEntry(tile, tileBytes));
|
||||
synchronized void put(TileKey key, TileState state, MapTileRenderer.TileRender work) {
|
||||
long tileBytes = state.tile().bytes() + (work == null ? 0L : work.bytes());
|
||||
CacheEntry previous = entries.put(key, new CacheEntry(state, work, tileBytes));
|
||||
if (previous != null) {
|
||||
bytes -= previous.bytes();
|
||||
}
|
||||
@@ -682,8 +717,18 @@ final class VisionRenderController implements AutoCloseable {
|
||||
entries.clear();
|
||||
bytes = 0L;
|
||||
}
|
||||
|
||||
synchronized void discardWork(TileKey key) {
|
||||
CacheEntry entry = entries.get(key);
|
||||
if (entry == null || entry.work() == null) {
|
||||
return;
|
||||
}
|
||||
long retainedBytes = entry.state().tile().bytes();
|
||||
entries.put(key, new CacheEntry(entry.state(), null, retainedBytes));
|
||||
bytes -= entry.bytes() - retainedBytes;
|
||||
}
|
||||
}
|
||||
|
||||
private record CacheEntry(MapTile tile, long bytes) {
|
||||
private record CacheEntry(TileState state, MapTileRenderer.TileRender work, long bytes) {
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ package art.arcane.iris.studio.map.components;
|
||||
import art.arcane.iris.generation.runtime.IrisComplex;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
|
||||
import art.arcane.iris.generation.stream.ProvisionalSampling;
|
||||
import art.arcane.iris.generation.terrain.InferredType;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.terrain.IrisDimension;
|
||||
@@ -30,7 +31,6 @@ import art.arcane.iris.studio.render.RenderType;
|
||||
import art.arcane.volmlib.util.stream.ProceduralStream;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumMap;
|
||||
import java.util.IdentityHashMap;
|
||||
@@ -73,6 +73,11 @@ public final class MapTileRenderer {
|
||||
return labels;
|
||||
}
|
||||
|
||||
public long previewRevision() {
|
||||
HydrologyRuntime runtime = engine.getComplex().getHydrologyRuntime();
|
||||
return runtime == null ? 0L : runtime.previewRevision();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the square of {@code size} pixels whose top left pixel samples the given world position.
|
||||
*
|
||||
@@ -87,6 +92,13 @@ public final class MapTileRenderer {
|
||||
boolean withHeights,
|
||||
BooleanSupplier cancelled
|
||||
) {
|
||||
Objects.requireNonNull(cancelled, "cancelled");
|
||||
checkCancelled(cancelled);
|
||||
return prepareTile(startX, startZ, blocksPerPixel, size, layer, withHeights).render(cancelled);
|
||||
}
|
||||
|
||||
public TileRender prepareTile(double startX, double startZ, double blocksPerPixel, int size, MapLayer layer,
|
||||
boolean withHeights) {
|
||||
if (!Double.isFinite(startX) || !Double.isFinite(startZ) || !Double.isFinite(blocksPerPixel) || blocksPerPixel <= 0D) {
|
||||
throw new IllegalArgumentException("Map tile coordinates and scale must be finite");
|
||||
}
|
||||
@@ -94,35 +106,7 @@ public final class MapTileRenderer {
|
||||
throw new IllegalArgumentException("Map tile size must be positive");
|
||||
}
|
||||
Objects.requireNonNull(layer, "layer");
|
||||
Objects.requireNonNull(cancelled, "cancelled");
|
||||
TileType type = layer.type();
|
||||
checkCancelled(cancelled);
|
||||
|
||||
TileGrid grid = new TileGrid(size + 2, startX - blocksPerPixel, startZ - blocksPerPixel, blocksPerPixel, cancelled);
|
||||
int[] identities = sampleIdentities(grid, layer);
|
||||
double[] heights = withHeights || type == TileType.HEIGHT ? sampleHeights(grid) : null;
|
||||
short[] subjects = new short[identities.length];
|
||||
short[] regions = new short[identities.length];
|
||||
for (int index = 0; index < identities.length; index++) {
|
||||
subjects[index] = subjectOf(identities[index]);
|
||||
regions[index] = regionOf(identities[index]);
|
||||
}
|
||||
int[] colors = switch (type) {
|
||||
case HEIGHT -> null;
|
||||
case RIVER -> riverColors(startX, startZ, blocksPerPixel, size, cancelled);
|
||||
default -> tileColors(size, type, subjects);
|
||||
};
|
||||
if (layer.display() != PickDisplay.PICKS) {
|
||||
drawPickNoise(colors, grid, size, layer);
|
||||
}
|
||||
if (layer.waterOverlay()) {
|
||||
BufferedImage base = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
|
||||
base.setRGB(0, 0, size, size, colors, 0, size);
|
||||
BufferedImage water = hydrologyRenderer.refineStudioBiome(startX, startZ, blocksPerPixel * size, base, cancelled);
|
||||
colors = water.getRGB(0, 0, size, size, null, 0, size);
|
||||
}
|
||||
MapLabels.Kind subjectKind = type == TileType.REGION ? MapLabels.Kind.REGION : MapLabels.Kind.BIOME;
|
||||
return new MapTile(size, blocksPerPixel, labels, subjectKind, colors, defaultHeightRange(), subjects, regions, heights);
|
||||
return new TileRender(new TileRequest(startX, startZ, blocksPerPixel, size, layer, withHeights));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -166,15 +150,15 @@ public final class MapTileRenderer {
|
||||
return sampler.identities;
|
||||
}
|
||||
|
||||
private double[] sampleHeights(TileGrid grid) {
|
||||
private double[] sampleHeights(HeightLattice lattice, BooleanSupplier cancelled) {
|
||||
IrisComplex complex = engine.getComplex();
|
||||
IrisDimension dimension = engine.getDimension();
|
||||
HydrologyRuntime water = complex.getHydrologyRuntime();
|
||||
if (water == null || !water.enabled() || dimension != null && dimension.getTerrainTransform() != null) {
|
||||
return new HeightLattice(grid, complex.getHeightStream()).interpolatedHeights();
|
||||
return lattice.interpolatedHeights(cancelled);
|
||||
}
|
||||
try (HydrologyRuntime.PreviewScope ignored = water.preview()) {
|
||||
return new HeightLattice(grid, complex.getHeightStream()).interpolatedHeights();
|
||||
return lattice.interpolatedHeights(cancelled);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,17 +261,6 @@ public final class MapTileRenderer {
|
||||
};
|
||||
}
|
||||
|
||||
// Rivers are drawn by the hydrology renderer the engine ships; the biomes under them stay the tile's subjects.
|
||||
private int[] riverColors(double startX, double startZ, double blocksPerPixel, int size, BooleanSupplier cancelled) {
|
||||
BufferedImage rivers = hydrologyRenderer.renderStudio(startX, startZ, blocksPerPixel * size, size, RenderType.RIVER,
|
||||
cancelled);
|
||||
int[] colors = rivers.getRGB(0, 0, size, size, null, 0, size);
|
||||
for (int index = 0; index < colors.length; index++) {
|
||||
colors[index] &= 0xFFFFFF;
|
||||
}
|
||||
return colors;
|
||||
}
|
||||
|
||||
private int[] tileColors(int size, TileType type, short[] subjects) {
|
||||
int[] colors = new int[size * size];
|
||||
short previousSubject = MapLabels.NONE;
|
||||
@@ -376,6 +349,124 @@ public final class MapTileRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
public final class TileRender {
|
||||
private final TileRequest request;
|
||||
private short[] subjects;
|
||||
private short[] regions;
|
||||
private int[] baseColors;
|
||||
private int[] finalColors;
|
||||
private double[] heights;
|
||||
private HeightLattice heightLattice;
|
||||
private IrisRenderer.WaterTile water;
|
||||
private boolean identitiesComplete;
|
||||
private boolean baseComplete;
|
||||
private boolean heightsComplete;
|
||||
private boolean waterComplete;
|
||||
private volatile boolean complete;
|
||||
private volatile long bytes;
|
||||
|
||||
private TileRender(TileRequest request) {
|
||||
this.request = request;
|
||||
heightsComplete = !request.withHeights() && request.layer().type() != TileType.HEIGHT;
|
||||
waterComplete = request.layer().type() != TileType.RIVER && !request.layer().waterOverlay();
|
||||
}
|
||||
|
||||
public MapTile render(BooleanSupplier cancelled) {
|
||||
Objects.requireNonNull(cancelled, "cancelled");
|
||||
checkCancelled(cancelled);
|
||||
TileGrid grid = new TileGrid(request.size() + 2, request.startX() - request.blocksPerPixel(),
|
||||
request.startZ() - request.blocksPerPixel(), request.blocksPerPixel(), cancelled);
|
||||
sampleSubjects(grid);
|
||||
sampleBaseColors(grid);
|
||||
sampleTerrain(grid, cancelled);
|
||||
int[] colors = sampleWater(cancelled);
|
||||
checkCancelled(cancelled);
|
||||
complete = baseComplete && heightsComplete && waterComplete;
|
||||
bytes = (heightLattice == null ? 0L : heightLattice.bytes()) + (water == null ? 0L : water.bytes())
|
||||
+ (baseColors == null || colors == baseColors ? 0L : (long) baseColors.length * Integer.BYTES);
|
||||
if (!complete) {
|
||||
ProvisionalSampling.mark();
|
||||
}
|
||||
MapLabels.Kind kind = request.layer().type() == TileType.REGION ? MapLabels.Kind.REGION : MapLabels.Kind.BIOME;
|
||||
return new MapTile(request.size(), request.blocksPerPixel(), labels, kind, colors, defaultHeightRange(), subjects,
|
||||
regions, heights);
|
||||
}
|
||||
|
||||
public boolean complete() {
|
||||
return complete;
|
||||
}
|
||||
|
||||
public long bytes() {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private void sampleSubjects(TileGrid grid) {
|
||||
if (identitiesComplete) {
|
||||
return;
|
||||
}
|
||||
long revision = ProvisionalSampling.revision();
|
||||
int[] identities = sampleIdentities(grid, request.layer());
|
||||
subjects = new short[identities.length];
|
||||
regions = new short[identities.length];
|
||||
for (int index = 0; index < identities.length; index++) {
|
||||
subjects[index] = subjectOf(identities[index]);
|
||||
regions[index] = regionOf(identities[index]);
|
||||
}
|
||||
identitiesComplete = revision == ProvisionalSampling.revision();
|
||||
}
|
||||
|
||||
private void sampleBaseColors(TileGrid grid) {
|
||||
if (baseComplete) {
|
||||
return;
|
||||
}
|
||||
long revision = ProvisionalSampling.revision();
|
||||
baseColors = switch (request.layer().type()) {
|
||||
case HEIGHT, RIVER -> null;
|
||||
default -> tileColors(request.size(), request.layer().type(), subjects);
|
||||
};
|
||||
if (request.layer().display() != PickDisplay.PICKS) {
|
||||
drawPickNoise(baseColors, grid, request.size(), request.layer());
|
||||
}
|
||||
baseComplete = identitiesComplete && revision == ProvisionalSampling.revision();
|
||||
}
|
||||
|
||||
private void sampleTerrain(TileGrid grid, BooleanSupplier cancelled) {
|
||||
if (heightsComplete) {
|
||||
return;
|
||||
}
|
||||
if (heightLattice == null) {
|
||||
heightLattice = new HeightLattice(grid, engine.getComplex().getHeightStream());
|
||||
}
|
||||
heights = sampleHeights(heightLattice, cancelled);
|
||||
heightsComplete = heightLattice.complete();
|
||||
if (heightsComplete) {
|
||||
heightLattice = null;
|
||||
}
|
||||
}
|
||||
|
||||
private int[] sampleWater(BooleanSupplier cancelled) {
|
||||
if (waterComplete) {
|
||||
return finalColors == null ? baseColors : finalColors;
|
||||
}
|
||||
if (water == null) {
|
||||
water = hydrologyRenderer.prepareStudioWater(request.startX(), request.startZ(), request.blocksPerPixel(),
|
||||
request.size());
|
||||
}
|
||||
int[] colors = water.render(baseColors, request.layer().waterOverlay(), cancelled);
|
||||
if (baseComplete && water.complete()) {
|
||||
finalColors = colors;
|
||||
baseColors = null;
|
||||
waterComplete = true;
|
||||
water = null;
|
||||
}
|
||||
return colors;
|
||||
}
|
||||
}
|
||||
|
||||
private record TileRequest(double startX, double startZ, double blocksPerPixel, int size, MapLayer layer,
|
||||
boolean withHeights) {
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface IdentityShader {
|
||||
int identity(double x, double z);
|
||||
@@ -554,16 +645,20 @@ public final class MapTileRenderer {
|
||||
private final ProceduralStream<Double> stream;
|
||||
private final int pointsPerSide;
|
||||
private final double[] points;
|
||||
private final boolean[] resolved;
|
||||
private int pending;
|
||||
|
||||
private HeightLattice(TileGrid grid, ProceduralStream<Double> stream) {
|
||||
this.grid = grid;
|
||||
this.stream = stream;
|
||||
this.pointsPerSide = (grid.size() - 2) / LATTICE_PIXELS + LATTICE_MARGIN * 2 + 1;
|
||||
this.points = new double[pointsPerSide * pointsPerSide];
|
||||
this.resolved = new boolean[points.length];
|
||||
this.pending = points.length;
|
||||
}
|
||||
|
||||
double[] interpolatedHeights() {
|
||||
samplePoints();
|
||||
double[] interpolatedHeights(BooleanSupplier cancelled) {
|
||||
samplePoints(cancelled);
|
||||
int size = grid.size();
|
||||
double[] heights = new double[size * size];
|
||||
for (int gridZ = 0; gridZ < size; gridZ++) {
|
||||
@@ -574,16 +669,33 @@ public final class MapTileRenderer {
|
||||
return heights;
|
||||
}
|
||||
|
||||
boolean complete() {
|
||||
return pending == 0;
|
||||
}
|
||||
|
||||
long bytes() {
|
||||
return (long) points.length * (Double.BYTES + 1L);
|
||||
}
|
||||
|
||||
// Lattice point 0 sits on the tile's first pixel; the margin covers the border ring and the curve's reach.
|
||||
private void samplePoints() {
|
||||
private void samplePoints(BooleanSupplier cancelled) {
|
||||
double latticeStep = grid.step() * LATTICE_PIXELS;
|
||||
double firstX = grid.worldX(1) - LATTICE_MARGIN * latticeStep;
|
||||
double firstZ = grid.worldZ(1) - LATTICE_MARGIN * latticeStep;
|
||||
for (int pointZ = 0; pointZ < pointsPerSide; pointZ++) {
|
||||
checkCancelled(grid.cancelled());
|
||||
checkCancelled(cancelled);
|
||||
for (int pointX = 0; pointX < pointsPerSide; pointX++) {
|
||||
points[pointZ * pointsPerSide + pointX] = stream.getDouble(firstX + pointX * latticeStep,
|
||||
int index = pointZ * pointsPerSide + pointX;
|
||||
if (resolved[index]) {
|
||||
continue;
|
||||
}
|
||||
long revision = ProvisionalSampling.revision();
|
||||
points[index] = stream.getDouble(firstX + pointX * latticeStep,
|
||||
firstZ + pointZ * latticeStep);
|
||||
if (revision == ProvisionalSampling.revision()) {
|
||||
resolved[index] = true;
|
||||
pending--;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +70,13 @@ public final class IrisRenderer {
|
||||
this.renderer = Objects.requireNonNull(renderer, "renderer");
|
||||
}
|
||||
|
||||
public WaterTile prepareStudioWater(double startX, double startZ, double step, int resolution) {
|
||||
if (!Double.isFinite(startX) || !Double.isFinite(startZ) || !Double.isFinite(step) || step <= 0D || resolution < 1) {
|
||||
throw new IllegalArgumentException("Water tile coordinates, scale and resolution must be valid");
|
||||
}
|
||||
return new WaterTile(startX, startZ, step, resolution);
|
||||
}
|
||||
|
||||
public BufferedImage render(double sx, double sz, double size, int resolution, RenderType currentType) {
|
||||
return render(sx, sz, size, resolution, currentType, () -> false);
|
||||
}
|
||||
@@ -445,6 +452,71 @@ public final class IrisRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
public final class WaterTile {
|
||||
private final double startX;
|
||||
private final double startZ;
|
||||
private final double step;
|
||||
private final int resolution;
|
||||
private final WaterMap map;
|
||||
private boolean complete;
|
||||
|
||||
private WaterTile(double startX, double startZ, double step, int resolution) {
|
||||
this.startX = startX;
|
||||
this.startZ = startZ;
|
||||
this.step = step;
|
||||
this.resolution = resolution;
|
||||
HydrologyRuntime runtime = renderer.getComplex().getHydrologyRuntime();
|
||||
this.map = runtime == null || !runtime.enabled() || step > WaterMap.MAX_STEP
|
||||
? null : new WaterMap(runtime, resolution, startX, startZ, step);
|
||||
complete = map == null;
|
||||
}
|
||||
|
||||
public int[] render(int[] base, boolean composite, BooleanSupplier cancelled) {
|
||||
Objects.requireNonNull(cancelled, "cancelled");
|
||||
checkCancelled(cancelled);
|
||||
if (composite && (base == null || base.length != resolution * resolution)) {
|
||||
throw new IllegalArgumentException("Water overlay requires matching base pixels");
|
||||
}
|
||||
if (!complete) {
|
||||
map.advance(cancelled);
|
||||
map.drawCavePools(GenerationSemanticQueries.recordedCavePools(renderer,
|
||||
Math.floorDiv((int) Math.floor(startX), 16), Math.floorDiv((int) Math.floor(startZ), 16),
|
||||
Math.floorDiv((int) Math.ceil(startX + resolution * step) - 1, 16),
|
||||
Math.floorDiv((int) Math.ceil(startZ + resolution * step) - 1, 16)));
|
||||
complete = !map.provisional();
|
||||
}
|
||||
int[] colors = composite ? base.clone() : new int[resolution * resolution];
|
||||
if (!composite) {
|
||||
Arrays.fill(colors, NO_RIVER & 0xFFFFFF);
|
||||
}
|
||||
if (map != null) {
|
||||
for (int z = 0; z < resolution; z++) {
|
||||
checkCancelled(cancelled);
|
||||
for (int x = 0; x < resolution; x++) {
|
||||
HydrologyFeatureType type = map.at(x, z);
|
||||
if (type != null) {
|
||||
int index = z * resolution + x;
|
||||
int color = hydrologyFeatureColor(type);
|
||||
colors[index] = (composite ? blend(colors[index], color, RIVER_OVERLAY) : color) & 0xFFFFFF;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!complete) {
|
||||
ProvisionalSampling.mark();
|
||||
}
|
||||
return colors;
|
||||
}
|
||||
|
||||
public boolean complete() {
|
||||
return complete;
|
||||
}
|
||||
|
||||
public long bytes() {
|
||||
return map == null ? 0L : map.bytes();
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface PixelShader {
|
||||
int color(double x, double z);
|
||||
|
||||
@@ -36,35 +36,85 @@ final class WaterMap {
|
||||
private final double startX;
|
||||
private final double startZ;
|
||||
private final double step;
|
||||
private final BooleanSupplier cancelled;
|
||||
private final int[] ranks;
|
||||
private final boolean[] resolved;
|
||||
private final IdentityHashMap<HydrologyTier, HydrologyFeatureType> channels = new IdentityHashMap<>();
|
||||
private final Set<Long> lakes = new HashSet<>();
|
||||
private BooleanSupplier cancelled;
|
||||
private int[] plannedRanks;
|
||||
private boolean plansComplete;
|
||||
private boolean provisional;
|
||||
|
||||
private WaterMap(HydrologyRuntime runtime, int resolution, double startX, double startZ, double step, BooleanSupplier cancelled) {
|
||||
WaterMap(HydrologyRuntime runtime, int resolution, double startX, double startZ, double step) {
|
||||
this.runtime = runtime;
|
||||
this.resolution = resolution;
|
||||
this.startX = startX;
|
||||
this.startZ = startZ;
|
||||
this.step = step;
|
||||
this.cancelled = cancelled;
|
||||
this.ranks = new int[resolution * resolution];
|
||||
this.resolved = step <= RASTER_STEP ? new boolean[ranks.length] : null;
|
||||
Arrays.fill(ranks, DRY);
|
||||
provisional = true;
|
||||
}
|
||||
|
||||
static WaterMap draw(HydrologyRuntime runtime, int resolution, double startX, double startZ, double step, BooleanSupplier cancelled) {
|
||||
WaterMap map = new WaterMap(runtime, resolution, startX, startZ, step, cancelled);
|
||||
HydrologyPlanPreview plans = runtime.planPreview((int) Math.floor(startX), (int) Math.floor(startZ),
|
||||
(int) Math.ceil(startX + resolution * step) - 1, (int) Math.ceil(startZ + resolution * step) - 1);
|
||||
map.provisional = !plans.complete();
|
||||
if (step <= RASTER_STEP) {
|
||||
map.drawRasters(plans);
|
||||
} else {
|
||||
map.drawPlans(plans);
|
||||
}
|
||||
WaterMap map = new WaterMap(runtime, resolution, startX, startZ, step);
|
||||
map.advance(cancelled);
|
||||
return map;
|
||||
}
|
||||
|
||||
void advance(BooleanSupplier cancelled) {
|
||||
if (!provisional) {
|
||||
return;
|
||||
}
|
||||
this.cancelled = cancelled;
|
||||
HydrologyPlanPreview plans = null;
|
||||
if (!plansComplete) {
|
||||
plans = preview();
|
||||
plannedRanks = null;
|
||||
lakes.clear();
|
||||
for (Pond lake : plans.lakes()) {
|
||||
lakes.add(lake.id());
|
||||
}
|
||||
if (step > RASTER_STEP) {
|
||||
prepareFallback(plans);
|
||||
}
|
||||
plansComplete = plans.complete();
|
||||
}
|
||||
if (step <= RASTER_STEP) {
|
||||
provisional = drawRasters(plans) || !plansComplete;
|
||||
} else {
|
||||
prepareFallback(plans);
|
||||
System.arraycopy(plannedRanks, 0, ranks, 0, ranks.length);
|
||||
provisional = !plansComplete;
|
||||
}
|
||||
if (!provisional) {
|
||||
plannedRanks = null;
|
||||
lakes.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private HydrologyPlanPreview preview() {
|
||||
return runtime.planPreview((int) Math.floor(startX), (int) Math.floor(startZ),
|
||||
(int) Math.ceil(startX + resolution * step) - 1, (int) Math.ceil(startZ + resolution * step) - 1);
|
||||
}
|
||||
|
||||
private void prepareFallback(HydrologyPlanPreview plans) {
|
||||
if (plannedRanks != null) {
|
||||
return;
|
||||
}
|
||||
WaterMap planned = new WaterMap(runtime, resolution, startX, startZ, step);
|
||||
planned.cancelled = cancelled;
|
||||
planned.drawPlans(plans == null ? preview() : plans);
|
||||
plannedRanks = planned.ranks;
|
||||
}
|
||||
|
||||
long bytes() {
|
||||
return (long) ranks.length * Integer.BYTES + (resolved == null ? 0L : resolved.length)
|
||||
+ (plannedRanks == null ? 0L : (long) plannedRanks.length * Integer.BYTES)
|
||||
+ (long) lakes.size() * 64L;
|
||||
}
|
||||
|
||||
HydrologyFeatureType at(int pixelX, int pixelZ) {
|
||||
int rank = ranks[pixelZ * resolution + pixelX];
|
||||
return rank == DRY ? null : DRAWN.get(rank);
|
||||
@@ -84,37 +134,39 @@ final class WaterMap {
|
||||
}
|
||||
}
|
||||
|
||||
private void drawRasters(HydrologyPlanPreview plans) {
|
||||
Set<Long> lakes = new HashSet<>();
|
||||
for (Pond lake : plans.lakes()) {
|
||||
lakes.add(lake.id());
|
||||
}
|
||||
private boolean drawRasters(HydrologyPlanPreview plans) {
|
||||
Map<Long, ChunkWaterRaster> rasters = new HashMap<>();
|
||||
WaterMap planned = null;
|
||||
boolean pending = false;
|
||||
for (int pixelZ = 0; pixelZ < resolution; pixelZ++) {
|
||||
checkCancelled();
|
||||
int minimumZ = (int) Math.floor(startZ + pixelZ * step);
|
||||
int maximumZ = Math.max(minimumZ, (int) Math.ceil(startZ + (pixelZ + 1) * step) - 1);
|
||||
for (int pixelX = 0; pixelX < resolution; pixelX++) {
|
||||
int index = pixelZ * resolution + pixelX;
|
||||
if (resolved[index]) {
|
||||
continue;
|
||||
}
|
||||
ranks[index] = DRY;
|
||||
boolean ready = plansComplete;
|
||||
int minimumX = (int) Math.floor(startX + pixelX * step);
|
||||
int maximumX = Math.max(minimumX, (int) Math.ceil(startX + (pixelX + 1) * step) - 1);
|
||||
for (int z = minimumZ; z <= maximumZ; z++) {
|
||||
for (int x = minimumX; x <= maximumX; x++) {
|
||||
ChunkWaterRaster raster = raster(rasters, x >> 4, z >> 4);
|
||||
if (raster.provisional()) {
|
||||
provisional = true;
|
||||
if (planned == null) {
|
||||
planned = new WaterMap(runtime, resolution, startX, startZ, step, cancelled);
|
||||
planned.drawPlans(plans);
|
||||
}
|
||||
stamp(pixelX, pixelZ, planned.at(pixelX, pixelZ));
|
||||
pending = true;
|
||||
ready = false;
|
||||
prepareFallback(plans);
|
||||
ranks[index] = Math.min(ranks[index], plannedRanks[index]);
|
||||
} else if (!raster.empty()) {
|
||||
stamp(pixelX, pixelZ, columnType(raster, x & 15, z & 15, lakes));
|
||||
}
|
||||
}
|
||||
}
|
||||
resolved[index] = ready;
|
||||
}
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
private ChunkWaterRaster raster(Map<Long, ChunkWaterRaster> rasters, int chunkX, int chunkZ) {
|
||||
@@ -251,7 +303,7 @@ final class WaterMap {
|
||||
}
|
||||
|
||||
private void checkCancelled() {
|
||||
if (cancelled.getAsBoolean()) {
|
||||
if (cancelled.getAsBoolean() || Thread.currentThread().isInterrupted()) {
|
||||
throw new CancellationException("Vision render was cancelled");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user