Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 297
src/client/java/com/potatohorizons/PotatoHorizonsClient.java
package com.potatohorizons;
import com.mojang.blaze3d.vertex.PoseStack;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientChunkEvents;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.rendering.v1.level.LevelRenderEvents;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.rendertype.RenderTypes;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.storage.LevelResource;
import net.minecraft.world.phys.Vec3;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
public final class PotatoHorizonsClient implements ClientModInitializer {
private static final int GRID = 4;
private static final int MAX_CACHED_CHUNKS = 8192;
private static final int MAX_RENDERED_CHUNKS = 2048;
private static final int FORMAT = 1;
private final ThreadPoolExecutor io = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(2048), r -> {
Thread thread = new Thread(r, "potato-horizons-cache");
thread.setDaemon(true);
return thread;
}, new ThreadPoolExecutor.DiscardPolicy());
private volatile Cache cache;
private ClientLevel currentLevel;
private int distance = 32;
private record Surface(int chunkX, int chunkZ, int[] heights, int[] colors) {}
private record Cache(Path directory, Map<Long, Surface> surfaces) {}
@Override
public void onInitializeClient() {
readConfig();
ClientTickEvents.END_CLIENT_TICK.register(client -> updateWorld(client));
ClientChunkEvents.CHUNK_LOAD.register(this::capture);
ClientChunkEvents.CHUNK_UNLOAD.register(this::capture);
ClientLifecycleEvents.CLIENT_STOPPING.register(client -> io.shutdown());
LevelRenderEvents.COLLECT_SUBMITS.register(context -> {
Cache active = cache;
Minecraft client = Minecraft.getInstance();
if (active == null || client.level == null) return;
Vec3 camera = context.levelState().cameraRenderState.pos;
int near = client.options.getEffectiveRenderDistance();
int far = Math.min(distance, near * 4 - 1);
if (far <= near) return;
int cameraX = (int) Math.floor(camera.x() / 16.0);
int cameraZ = (int) Math.floor(camera.z() / 16.0);
List<Surface> visible = new ArrayList<>();
for (Surface surface : active.surfaces().values()) {
int dx = Math.abs(surface.chunkX() - cameraX);
int dz = Math.abs(surface.chunkZ() - cameraZ);
int radius = Math.max(dx, dz);
if (radius > near + 1 && radius <= far) visible.add(surface);
}
visible.sort((a, b) -> Long.compare(distanceSquared(a, cameraX, cameraZ), distanceSquared(b, cameraX, cameraZ)));
if (visible.size() > MAX_RENDERED_CHUNKS) visible = visible.subList(0, MAX_RENDERED_CHUNKS);
List<Surface> draw = visible;
PoseStack poses = context.poseStack();
poses.pushPose();
poses.translate(-camera.x(), -camera.y(), -camera.z());
context.submitNodeCollector().submitCustomGeometry(poses, RenderTypes.debugQuads(), (pose, vertices) -> {
for (Surface surface : draw) {
int baseX = surface.chunkX() * 16;
int baseZ = surface.chunkZ() * 16;
for (int z = 0; z < GRID; z++) {
for (int x = 0; x < GRID; x++) {
int index = z * GRID + x;
int y = surface.heights()[index] + 1;
int color = 0xff000000 | surface.colors()[index];
int x0 = baseX + x * 4;
int z0 = baseZ + z * 4;
vertices.addVertex(pose, x0, y, z0).setColor(color);
vertices.addVertex(pose, x0, y, z0 + 4).setColor(color);
vertices.addVertex(pose, x0 + 4, y, z0 + 4).setColor(color);
vertices.addVertex(pose, x0 + 4, y, z0).setColor(color);
}
}
}
});
poses.popPose();
});
}
private static long distanceSquared(Surface surface, int x, int z) {
long dx = (long) surface.chunkX() - x;
long dz = (long) surface.chunkZ() - z;
return dx * dx + dz * dz;
}
private void readConfig() {
Path path = Minecraft.getInstance().gameDirectory.toPath().resolve("config/potato-horizons.properties");
Properties properties = new Properties();
try {
if (Files.exists(path)) {
try (var input = Files.newInputStream(path)) {
properties.load(input);
}
distance = Math.max(2, Math.min(128, Integer.parseInt(properties.getProperty("lodDistanceChunks", "32"))));
} else {
Files.createDirectories(path.getParent());
properties.setProperty("lodDistanceChunks", "32");
try (var output = Files.newOutputStream(path)) {
properties.store(output, "Potato Horizons: LOD distance in chunks (2-128)");
}
}
} catch (IOException | NumberFormatException e) {
System.err.println("Potato Horizons: unable to read configuration: " + e.getMessage());
}
}
private void updateWorld(Minecraft client) {
ClientLevel level = client.level;
if (level == currentLevel) return;
currentLevel = level;
cache = null;
if (level == null || !client.hasSingleplayerServer() || client.getSingleplayerServer() == null) return;
String dimension = level.dimension().identifier().toString().replace(':', '_').replace('/', '_');
Path directory = client.getSingleplayerServer().getWorldPath(LevelResource.ROOT)
.resolve("potato-horizons").resolve(dimension);
Cache next = new Cache(directory, new ConcurrentHashMap<>());
cache = next;
io.execute(() -> loadCache(next));
}
private void capture(ClientLevel level, LevelChunk chunk) {
Cache active = cache;
if (active == null || level != currentLevel) return;
int chunkX = chunk.getPos().x();
int chunkZ = chunk.getPos().z();
int[] heights = new int[GRID * GRID];
int[] colors = new int[GRID * GRID];
for (int z = 0; z < GRID; z++) {
for (int x = 0; x < GRID; x++) {
int wx = chunkX * 16 + x * 4 + 2;
int wz = chunkZ * 16 + z * 4 + 2;
int y = Math.max(level.getMinY(), chunk.getHeight(Heightmap.Types.WORLD_SURFACE, wx, wz));
BlockPos pos = new BlockPos(wx, y, wz);
int index = z * GRID + x;
heights[index] = y;
colors[index] = level.getBlockState(pos).getMapColor(level, pos).col;
}
}
Surface surface = new Surface(chunkX, chunkZ, heights, colors);
if (active.surfaces().size() < MAX_CACHED_CHUNKS || active.surfaces().containsKey(key(chunkX, chunkZ))) {
active.surfaces().put(key(chunkX, chunkZ), surface);
}
io.execute(() -> writeSurface(active.directory(), surface));
}
private static long key(int x, int z) {
return ((long) x << 32) | (z & 0xffffffffL);
}
private static void writeSurface(Path directory, Surface surface) {
try {
Files.createDirectories(directory);
Path file = directory.resolve(surface.chunkX() + "_" + surface.chunkZ() + ".lod");
try (DataOutputStream output = new DataOutputStream(Files.newOutputStream(file))) {
output.writeInt(FORMAT);
output.writeInt(surface.chunkX());
output.writeInt(surface.chunkZ());
for (int i = 0; i < GRID * GRID; i++) {
output.writeInt(surface.heights()[i]);
output.writeInt(surface.colors()[i]);
}
}
} catch (IOException e) {
System.err.println("Potato Horizons: cache write failed: " + e.getMessage());
}
}
private static void loadCache(Cache cache) {
if (!Files.isDirectory(cache.directory())) return;
try (Stream<Path> files = Files.list(cache.directory())) {
files.filter(path -> path.getFileName().toString().endsWith(".lod"))
.limit(MAX_CACHED_CHUNKS).forEach(path -> {
try (DataInputStream input = new DataInputStream(Files.newInputStream(path))) {
if (input.readInt() != FORMAT) return;
int x = input.readInt();
int z = input.readInt();