Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 998
src/client/java/com/kodari/lod/client/KodariLodClient.java
package com.kodari.lod.client;
import com.mojang.blaze3d.vertex.PoseStack;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.FutureTask;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientChunkEvents;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.screen.v1.ScreenEvents;
import net.fabricmc.fabric.api.client.screen.v1.Screens;
import net.fabricmc.fabric.api.client.rendering.v1.level.LevelRenderContext;
import net.fabricmc.fabric.api.client.rendering.v1.level.LevelRenderEvents;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.gui.screens.options.OptionsScreen;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.client.renderer.rendertype.RenderTypes;
import net.minecraft.client.renderer.state.level.CameraRenderState;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.status.ChunkStatus;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.material.MapColor;
import net.minecraft.world.phys.Vec3;
public final class KodariLodClient implements ClientModInitializer {
private static final int MAX_TILE_LEVEL = 11;
private static final int CACHE_MAGIC = 0x4B4C4F44;
private static final int CACHE_VERSION = 1;
private static final int SAMPLE_COUNT = 17 * 17;
private static final int MAX_VERTICES = 20_000;
private static final int MAX_QUEUED_JOBS = 256;
private static final int CHUNKS_PER_TICK = 2;
private static final double LOD_START_DISTANCE = 128.0;
private static final ConcurrentMap<ChunkPosKey, SurfaceSnapshot> snapshots = new ConcurrentHashMap<>();
private static final ConcurrentMap<TileKey, TileNode> nodes = new ConcurrentHashMap<>();
private static final ConcurrentMap<TileKey, AtomicInteger> descendantCounts = new ConcurrentHashMap<>();
private static final java.util.Set<JobKey> jobsInFlight = ConcurrentHashMap.newKeySet();
private static final AtomicInteger pendingJobs = new AtomicInteger();
private static final AtomicLong taskSequence = new AtomicLong();
private static final Config config = Config.load();
private static final ThreadPoolExecutor workers = createWorkers();
private static volatile ClientLevel activeLevel;
private static volatile Path cacheDirectory;
private static volatile long worldEpoch;
private static volatile double cameraX;
private static volatile double cameraY;
private static volatile double cameraZ;
private static volatile double velocityX;
private static volatile double velocityZ;
private static volatile long lastCameraNanos;
private static volatile long generationNanos;
private static volatile int sampleCursor;
private static long tickCount;
private static long lastTickNanos;
private static double averageTickMillis = 50.0;
private static int activeWorkers;
@Override
public void onInitializeClient() {
activeWorkers = config.workers;
workers.setCorePoolSize(activeWorkers);
ClientChunkEvents.CHUNK_LOAD.register(KodariLodClient::captureChunk);
ClientTickEvents.END_LEVEL_TICK.register(KodariLodClient::tick);
LevelRenderEvents.COLLECT_SUBMITS.register(KodariLodClient::collectSubmits);
ScreenEvents.AFTER_INIT.register((client, screen, scaledWidth, scaledHeight) -> {
if (screen instanceof OptionsScreen) {
Button toggleButton = Button.builder(toggleLabel(), button -> {
config.setEnabled(!config.enabled);
button.setMessage(toggleLabel());
}).bounds(scaledWidth - 105, 8, 100, 20).build();
Screens.getWidgets(screen).add(toggleButton);
}
});
}
private static Component toggleLabel() {
return Component.literal("Distant LOD: " + (config.enabled ? "ON" : "OFF"));
}
private static ThreadPoolExecutor createWorkers() {
int maximum = config.workers;
ThreadFactory factory = task -> {
Thread thread = new Thread(task, "Kodari LOD worker");
thread.setDaemon(true);
thread.setPriority(Math.max(Thread.MIN_PRIORITY, Thread.NORM_PRIORITY - 1));
return thread;
};
return new ThreadPoolExecutor(1, maximum, 30, TimeUnit.SECONDS, new PriorityBlockingQueue<>(), factory);
}
private static void captureChunk(ClientLevel level, LevelChunk chunk) {
if (!config.enabled) {
return;
}
ensureWorld(level);
ChunkPos pos = chunk.getPos();
int[] heights = new int[16 * 16];
int[] colors = new int[16 * 16];
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
int index = z * 16 + x;
int y = Math.max(level.getMinY(), chunk.getHeight(Heightmap.Types.WORLD_SURFACE, x, z));
BlockPos blockPos = pos.getBlockAt(x, y, z);
BlockState state = chunk.getBlockState(blockPos);
MapColor mapColor = state.getMapColor(chunk, blockPos);
heights[index] = y;
int rgb = mapColor.col & 0xFFFFFF;
colors[index] = state.isAir() || rgb == 0 ? 0x596C58 : rgb;
}
}
ChunkPosKey key = new ChunkPosKey(pos.x(), pos.z());
SurfaceSnapshot snapshot = new SurfaceSnapshot(key, heights, colors, fingerprint(heights, colors));
SurfaceSnapshot previous = snapshots.put(key, snapshot);
if (previous == null) {
for (int levelIndex = 1; levelIndex <= MAX_TILE_LEVEL; levelIndex++) {
TileKey ancestor = TileKey.forChunk(key.x, key.z, levelIndex);
descendantCounts.computeIfAbsent(ancestor, ignored -> new AtomicInteger()).incrementAndGet();
}
}
if (previous == null || previous.fingerprint != snapshot.fingerprint) {
invalidateChunkNodes(key);
scheduleLeaf(snapshot, worldEpoch);
}
}
private static void ensureWorld(ClientLevel level) {
if (activeLevel == level) {
return;
}
synchronized (KodariLodClient.class) {
if (activeLevel == level) {
return;
}
activeLevel = level;
worldEpoch++;
snapshots.clear();
nodes.clear();
descendantCounts.clear();
jobsInFlight.clear();
String dimension = level.dimension().identifier().toString().replaceAll("[^A-Za-z0-9._-]", "_");
cacheDirectory = Minecraft.getInstance().gameDirectory.toPath().resolve("config/kodarilod/cache").resolve(dimension);
sampleCursor = 0;
}
}
private static void tick(ClientLevel level) {
if (!config.enabled) {
return;
}
ensureWorld(level);
long now = System.nanoTime();
if (lastTickNanos != 0L) {
double elapsed = (now - lastTickNanos) / 1_000_000.0;
averageTickMillis = averageTickMillis * 0.95 + elapsed * 0.05;
}
lastTickNanos = now;
tickCount++;
if (lastCameraNanos == 0L) {
return;
}
int centerX = floorChunk(cameraX);
int centerZ = floorChunk(cameraZ);
int side = 25;
int total = side * side;
for (int i = 0; i < CHUNKS_PER_TICK; i++) {
int cursor = Math.floorMod(sampleCursor++, total);
int chunkX = centerX + cursor % side - side / 2;
int chunkZ = centerZ + cursor / side - side / 2;
LevelChunk chunk = level.getChunkSource().getChunk(chunkX, chunkZ, ChunkStatus.FULL, false);
if (chunk != null) {
captureChunk(level, chunk);
}
}