Pistache Guy

--- 📎 Attached 1 file(s):

File: pasted-code-1791054690393.txt

txt
Create a high-performance **Minecraft LOD (Level of Detail) generator inspired by the concepts and workflow of Ecstatic**, designed to dramatically improve rendering performance at extreme view distances while preserving visual quality.

Build this as a **real, production-oriented system**, not a simplified demo. Use everything you know about Minecraft rendering, LOD systems, terrain generation, mesh optimization, chunk rendering, occlusion, mipmaps, GPU/CPU optimization, and modern game-engine techniques.

### Core Goal
Create a system that can take Minecraft world/chunk data and generate multiple levels of detail for terrain and other appropriate world geometry.

The farther something is from the player, the lower its geometric and texture complexity should become.

For example:

- **LOD 0:** Extremely close terrain — full Minecraft-quality geometry.
- **LOD 1:** Nearby terrain — reduced mesh complexity while retaining important shapes.
- **LOD 2:** Medium distance — aggressively simplified terrain.
- **LOD 3:** Far distance — very low-poly terrain representing large geographic features.
- **LOD 4+:** Extremely distant terrain — highly compressed representations suitable for massive render distances.

The system should support **very large view distances** without attempting to render every distant Minecraft block at full resolution.

### Terrain LOD
Develop a hierarchical terrain representation that can:

- Convert Minecraft chunks/regions into optimized LOD meshes.
- Combine many chunks into larger LOD regions.
- Preserve mountains, valleys, cliffs, oceans, structures, and major terrain silhouettes.
- Automatically simplify geometry based on distance.
- Use adaptive mesh simplification instead of simply deleting blocks.
- Preserve important terrain boundaries and height changes.
- Avoid visible cracks between different LOD levels.
- Use skirts, stitching, or another robust solution for LOD transitions.
- Dynamically load and unload LOD regions around the player.
- Generate LODs asynchronously so world generation/rendering does not freeze the game.

### Minecraft-Specific Optimization
Design the system specifically around Minecraft's world structure.

Take advantage of:

- Chunks
- Chunk sections
- Regions
- Heightmaps
- Biomes
- Block states
- Block transparency
- Block faces
- Lighting information
- Water/lava
- Structures
- Caves where appropriate
- World height
- Seed/world-generation information when available
- Minecraft's existing chunk rendering pipeline

Avoid generating unnecessary geometry.

For distant terrain, intelligently represent groups of blocks as simplified surfaces rather than individually rendering every block.

### Rendering Architecture
Use a modern GPU-friendly rendering architecture.

Prioritize:

- GPU instancing where useful
- Batched rendering
- Indirect drawing where appropriate
- Frustum culling
- Distance culling
- Occlusion culling
- Hierarchical spatial structures
- Aggressive draw-call reduction
- GPU-friendly vertex/index buffers
- Persistent buffers where appropriate
- Asynchronous uploads
- Multithreaded mesh generation
- Background LOD generation
- Streaming
- Memory pooling
- Efficient cache management

Design the system so that **CPU work does not become the bottleneck when view distance becomes extremely large**.

### LOD Selection
Create a sophisticated LOD selection algorithm.

LOD selection should consider:

- Distance from camera
- Screen-space error
- Camera FOV
- Resolution
- Terrain height
- Camera altitude
- Player movement speed
- GPU/CPU performance
- Current frame time
- Available memory
- LOD generation queue
- Visibility
- Importance of terrain features

Use **screen-space error or a similar metric** instead of relying only on fixed distance thresholds.

The system should dynamically choose the highest-detail LOD that is actually necessary to maintain visual quality.

### Streaming System
Create a streaming system that continuously manages LOD data around the player.

It should:

1. Detect the player's movement.
2. Determine which regions need high-detail LODs.
3. Determine which regions can use lower-detail LODs.
4. Generate missing LODs asynchronously.
5. Upload completed meshes efficiently.
6. Remove data that is no longer needed.
7. Predictively load terrain in the player's movement direction.
8. Prevent sudden pop-in whenever possible.

Use priority queues so the closest and most visible terrain is generated first.

### Caching
Implement persistent and runtime caching.

Cache:

- Generated LOD meshes
- Height data
- Material information
- Region metadata
- Visibility information
- Simplification results

If the same world is loaded again, avoid regenerating LOD data unnecessarily.

Use a versioned cache format so changes to the LOD algorithm do not corrupt old cache data.

### Terrain Simplification
Use advanced mesh simplification techniques.

Consider algorithms such as:

- Quadric Error Metrics
- Hierarchical meshes
- Adaptive subdivision
- Heightfield simplification
- Cluster-based simplification
- Geometric error metrics

The simplifier should preserve visually important features.

For example:

A giant mountain should remain recognizable at extreme distance, while tiny bumps on the mountain should disappear.

### Textures and Materials
Implement a distance-aware texture system.

Close terrain should use normal Minecraft textures.

As distance increases:

- Reduce texture resolution.
- Use mipmaps.
- Combine materials where possible.
- Use texture atlases when beneficial.
- Generate lower-resolution material representations.
- Reduce unnecessary texture sampling.
- Use simplified material information for extremely distant terrain.

Consider generating **terrain-specific LOD textures** rather than simply relying on normal block textures.

### Lighting
Create an efficient distant-lighting representation.

For far-away terrain:

- Do not calculate expensive per-block lighting.
- Approximate lighting using terrain normals, height, biome information, or precomputed lighting.
- Preserve the overall appearance of mountains, valleys, and large terrain features.
- Transition smoothly between normal Minecraft lighting and LOD lighting.

### Water
Handle oceans, lakes, and rivers intelligently.

Distant water should not require rendering thousands of individual water blocks.

Instead, generate simplified water surfaces while preserving:

- Shorelines
- Major rivers
- Large lakes
- Oceans
- Terrain/water boundaries

### Structures
Determine how structures should be represented at different distances.

For example:

- Close structures → normal Minecraft rendering.
- Medium distance → simplified geometry.
- Far distance → simplified silhouettes or specialized impostors.
- Extremely far distance → potentially omit insignificant structures.

Important landmarks should remain visible from much farther away.

### Caves and Underground Terrain
Do not waste LOD resources rendering underground geometry that cannot be seen.

Prioritize geometry based on visibility.

Surface terrain should receive substantially more LOD resources than completely hidden underground blocks.

### Occlusion and Visibility
Implement hierarchical visibility determination.

Use spatial structures such as:

- Quadtrees
- Octrees
- BVHs
- Hierarchical Z-buffer techniques where appropriate

The goal is to avoid processing terrain that cannot contribute to the final frame.

### Seamless LOD Transitions
LOD transitions must be visually stable.

Avoid:

- Cracks
- Holes
- Floating terrain
- Sudden height changes
- Obvious popping

Use:

- Geomorphing
- Transition meshes
- Stitching
- Skirts
- Error-based transitions

where appropriate.

### Multithreading
Make heavy work asynchronous.

Separate:

- World data acquisition
- LOD selection
- Mesh generation
- Mesh simplification
- Texture generation
- Cache operations
- GPU uploads

Use worker threads and job queues.

Never perform expensive LOD generation on the main rendering thread.

### Performance Target
Optimize aggressively.

The system should aim for:

- Extremely large render distances
- Stable frame times
- Minimal stuttering
- Minimal RAM usage
- Minimal VRAM usage
- Low CPU overhead
- Low GPU overhead
- Fast world startup
- Fast LOD generation

Do not optimize only for maximum FPS. Optimize for **frame-time stability and scalability**.

### Adaptive Performance
Add a dynamic performance controller.

Monitor:

- FPS
- Frame time
- CPU utilization
- GPU utilization
- RAM
- VRAM
- LOD generation time
- Number of visible regions
- Number of pending LOD jobs

Automatically adjust:

- LOD distances
- Mesh complexity
- Generation priority
- Texture resolution
- Streaming radius
- Number of worker jobs

The system should automatically find a good performance/quality balance.

### Extreme View Distance
The defining feature should be the ability to display terrain at extremely large distances.

Design the architecture so that rendering a view distance of:

10,000+ blocks

is conceptually possible without treating all 10,000 blocks as normal Minecraft geometry.

Use hierarchical LODs so the amount of rendered geometry grows much more slowly than the actual world size.

### Minecraft Integration
If implementing this as a Minecraft mod, integrate cleanly with the appropriate rendering APIs and avoid unnecessary replacement of Minecraft systems.

Support modern Minecraft versions where practical.

If using Fabric, structure the project cleanly and use Mixins only where necessary.

Do not hard-code assumptions that make the system fragile across Minecraft versions.

### Configuration
Provide a configuration system with settings such as:

- Maximum LOD distance
- LOD levels
- LOD quality
- Mesh
📎 1 file 10,071 chars
📄
pasted-code-1791054753604.txt
txt 334 lines
▶
Create a high-performance **Minecraft LOD (Level of Detail) generator inspired by the concepts and workflow of Ecstatic**, designed to dramatically improve rendering performance at extreme view distances while preserving visual quality.

Build this as a **real, production-oriented system**, not a simplified demo. Use everything you know about Minecraft rendering, LOD systems, terrain generation, mesh optimization, chunk rendering, occlusion, mipmaps, GPU/CPU optimization, and modern game-engine techniques.

### Core Goal
Create a system that can take Minecraft world/chunk data and generate multiple levels of detail for terrain and other appropriate world geometry.

The farther something is from the player, the lower its geometric and texture complexity should become.

For example:

- **LOD 0:** Extremely close terrain — full Minecraft-quality geometry.
- **LOD 1:** Nearby terrain — reduced mesh complexity while retaining important shapes.
- **LOD 2:** Medium distance — aggressively simplified terrain.
- **LOD 3:** Far distance — very low-poly terrain representing large geographic features.
- **LOD 4+:** Extremely distant terrain — highly compressed representations suitable for massive render distances.

The system should support **very large view distances** without attempting to render every distant Minecraft block at full resolution.

### Terrain LOD
Develop a hierarchical terrain representation that can:

- Convert Minecraft chunks/regions into optimized LOD meshes.
- Combine many chunks into larger LOD regions.
- Preserve mountains, valleys, cliffs, oceans, structures, and major terrain silhouettes.
- Automatically simplify geometry based on distance.
- Use adaptive mesh simplification instead of simply deleting blocks.
- Preserve important terrain boundaries and height changes.
- Avoid visible cracks between different LOD levels.
- Use skirts, stitching, or another robust solution for LOD transitions.
- Dynamically load and unload LOD regions around the player.
- Generate LODs asynchronously so world generation/rendering does not freeze the game.

### Minecraft-Specific Optimization
Design the system specifically around Minecraft's world structure.

Take advantage of:

- Chunks
- Chunk sections
- Regions
- Heightmaps
- Biomes
- Block states
- Block transparency
- Block faces
- Lighting information
- Water/lava
- Structures
- Caves where appropriate
- World height
- Seed/world-generation information when available
- Minecraft's existing chunk rendering pipeline

Avoid generating unnecessary geometry.

For distant terrain, intelligently represent groups of blocks as simplified surfaces rather than individually rendering every block.

### Rendering Architecture
Use a modern GPU-friendly rendering architecture.

Prioritize:

- GPU instancing where useful
- Batched rendering
- Indirect drawing where appropriate
- Frustum culling
- Distance culling
- Occlusion culling
- Hierarchical spatial structures
- Aggressive draw-call reduction
- GPU-friendly vertex/index buffers
- Persistent buffers where appropriate
- Asynchronous uploads
- Multithreaded mesh generation
- Background LOD generation
- Streaming
- Memory pooling
- Efficient cache management

Design the system so that **CPU work does not become the bottleneck when view distance becomes extremely large**.

### LOD Selection
Create a sophisticated LOD selection algorithm.

LOD selection should consider:

- Distance from camera
- Screen-space error
- Camera FOV
- Resolution
- Terrain height
- Camera altitude
- Player movement speed
- GPU/CPU performance
- Current frame time
- Available memory
- LOD generation queue
- Visibility
- Importance of terrain features

Use **screen-space error or a similar metric** instead of relying only on fixed distance thresholds.

The system should dynamically choose the highest-detail LOD that is actually necessary to maintain visual quality.

### Streaming System
Create a streaming system that continuously manages LOD data around the player.

It should:

1. Detect the player's movement.
2. Determine which regions need high-detail LODs.
3. Determine which regions can use lower-detail LODs.
4. Generate missing LODs asynchronously.
5. Upload completed meshes efficiently.
6. Remove data that is no longer needed.
7. Predictively load terrain in the player's movement direction.
8. Prevent sudden pop-in whenever possible.

Use priority queues so the closest and most visible terrain is generated first.

### Caching
Implement persistent and runtime caching.

Cache:

- Generated LOD meshes
- Height data
- Material information
- Region metadata
- Visibility information
- Simplification results

If the same world is loaded again, avoid regenerating LOD data unnecessarily.

Use a versioned cache format so changes to the LOD algorithm do not corrupt old cache data.

### Terrain Simplification
Use advanced mesh simplification techniques.

Consider algorithms such as:

- Quadric Error Metrics
- Hierarchical meshes
- Adaptive subdivision
- Heightfield simplification
- Cluster-based simplification
- Geometric error metrics

The simplifier should preserve visually important features.

For example:

A giant mountain should remain recognizable at extreme distance, while tiny bumps on the mountain should disappear.

### Textures and Materials
Implement a distance-aware texture system.

Close terrain should use normal Minecraft textures.

As distance increases:

- Reduce texture resolution.
- Use mipmaps.
- Combine materials where possible.
- Use texture atlases when beneficial.
- Generate lower-resolution material representations.
- Reduce unnecessary texture sampling.
- Use simplified material information for extremely distant terrain.

Consider generating **terrain-specific LOD textures** rather than simply relying on normal block textures.

### Lighting
Create an efficient distant-lighting representation.

For far-away terrain:

- Do not calculate expensive per-block lighting.
- Approximate lighting using terrain normals, height, biome information, or precomputed lighting.
- Preserve the overall appearance of mountains, valleys, and large terrain features.
- Transition smoothly between normal Minecraft lighting and LOD lighting.

### Water
Handle oceans, lakes, and rivers intelligently.

Distant water should not require rendering thousands of individual water blocks.

Instead, generate simplified water surfaces while preserving:

- Shorelines
- Major rivers
- Large lakes
- Oceans
- Terrain/water boundaries

### Structures
Determine how structures should be represented at different distances.

For example:

- Close structures → normal Minecraft rendering.
- Medium distance → simplified geometry.
- Far distance → simplified silhouettes or specialized impostors.
- Extremely far distance → potentially omit insignificant structures.

Important landmarks should remain visible from much farther away.

### Caves and Underground Terrain
Do not waste LOD resources rendering underground geometry that cannot be seen.

Prioritize geometry based on visibility.

Surface terrain should receive substantially more LOD resources than completely hidden underground blocks.

### Occlusion and Visibility
Implement hierarchical visibility determination.

Use spatial structures such as:

- Quadtrees
- Octrees
- BVHs
- Hierarchical Z-buffer techniques where appropriate

The goal is to avoid processing terrain that cannot contribute to the final frame.

### Seamless LOD Transitions
LOD transitions must be visually stable.

Avoid:

- Cracks
- Holes
- Floating terrain
- Sudden height changes
- Obvious popping

Use:

- Geomorphing
- Transition meshes
- Stitching
- Skirts
- Error-based transitions

where appropriate.

### Multithreading
Make heavy work asynchronous.

Separate:

- World data acquisition
- LOD selection
- Mesh generation
- Mesh simplification
- Texture generation
- Cache operations
- GPU uploads

Use worker threads and job queues.

Never perform expensive LOD generation on the main rendering thread.

### Performance Target
Optimize aggressively.

The system should aim for:

- Extremely large render distances
- Stable frame times
- Minimal stuttering
- Minimal RAM usage
- Minimal VRAM usage
- Low CPU overhead
- Low GPU overhead
- Fast world startup
- Fast LOD generation

Do not optimize only for maximum FPS. Optimize for **frame-time stability and scalability**.

### Adaptive Performance
Add a dynamic performance controller.

Monitor:

- FPS
- Frame time
- CPU utilization
- GPU utilization
- RAM
- VRAM
- LOD generation time
- Number of visible regions
- Number of pending LOD jobs

Automatically adjust:

- LOD distances
- Mesh complexity
- Generation priority
- Texture resolution
- Streaming radius
- Number of worker jobs

The system should automatically find a good performance/quality balance.

### Extreme View Distance
The defining feature should be the ability to display terrain at extremely large distances.

Design the architecture so that rendering a view distance of:

10,000+ blocks

is conceptually possible without treating all 10,000 blocks as normal Minecraft geometry.

Use hierarchical LODs so the amount of rendered geometry grows much more slowly than the actual world size.

### Minecraft Integration
If implementing this as a Minecraft mod, integrate cleanly with the appropriate rendering APIs and avoid unnecessary replacement of Minecraft systems.

Support modern Minecraft versions where practical.

If using Fabric, structure the project cleanly and use Mixins only where necessary.

Do not hard-code assumptions that make the system fragile across Minecraft versions.

### Configuration
Provide a configuration system with settings such as:

- Maximum LOD distance
- LOD levels
- LOD quality
- Mesh
Kodari AI
KodariOct 3 at 7:49 pm 4
EcstaticLODGenerator
Generates hierarchical level-of-detail terrain meshes for Minecraft worlds, enabling extreme view distances beyond vanilla limits. Converts chunk data into simplified multi-resolution regions preserving terrain silhouettes, water surfaces, and structures. Uses screen-space error metrics for adaptive LOD selection, asynchronous multithreaded mesh generation, and seamless stitching transitions. Implements persistent caching, priority-based streaming, and dynamic performance scaling to maintain stable frame times. Optimizes GPU rendering through batched draws, frustum culling, and simplified distant lighting while avoiding cracks and pop-in.
  1. Build a client-side terrain LOD pipeline: chunk capture, hierarchical simplification, screen-space selection, and asynchronous prioritized generation.

  2. Add versioned disk caching and bounded streaming so distant terrain does not become unbounded memory or main-thread work.

  3. Integrate the generated terrain into Fabric’s world-render path with conservative transitions and configurable distance/quality.

Created Kodari LOD, a Fabric 26.2 client mod with asynchronous terrain mesh generation, hierarchical region selection, screen-error-based LOD, seam skirts, prioritized jobs, adaptive worker counts, and versioned disk caching. Settings are created at config/kodarilod.properties; the default LOD range is 10,000 blocks.

The current renderer uses a map-colored surface heightfield. It can only display terrain from chunks the client has received—it does not generate or request distant terrain beyond the server’s chunk stream—and it does not yet represent caves, structures, or full block textures.

Pistache Guy

so ouput the file please so i can download it

Kodari AI
KodariOct 4 at 2:27 pm 1

To download the mod jar:

  1. Click Compile in the top bar (on phone: ⋮ → Compile Project).

  2. Click Compile in the window that opens.

  3. When the build succeeds, click Download or Download {name}.jar in the chat.

Pistache Guy

now make sure i can toggle it on and off by adding a little button in the settings menu

Kodari AI
KodariOct 4 at 3:05 pm 1
  • Add a saved enabled setting, defaulting to on.

  • Add a small ON/OFF button to the Options settings screen.

  • Stop LOD capture, ticking, and rendering while disabled.

Added a Distant LOD: ON/OFF button to the Options settings screen. The setting is saved and remembered across restarts; turning it off stops LOD capture, ticking, and rendering.

Kodari can make mistakes. Review important code before using.
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);
			}
		}