Improve minimap, switch to block palette, update faster

This commit is contained in:
Tanner committed 2026-11-14 18:40:42 +00:00
1 parent 8c75502966
commit 9be381c2de
6 files changed
+166 -38

No files matched your search

+72 -24
View File
@@ -1,3 +1,4 @@
import base64
import importlib
import json
import os
@@ -174,24 +175,47 @@ def api_global():
return response
def _minimap_surface_cell(chunks, x, z):
def _minimap_surface_cell(chunks, x, z, section_cache=None):
"""Return the uppermost solid/water block in a loaded world column."""
from mosfet.info import blocks
chunk_x, chunk_z = floor(x / 16), floor(z / 16)
chunk = chunks.chunks.get((chunk_x, chunk_z))
key = (chunk_x, chunk_z)
chunk = chunks.chunks.get(key)
if chunk is None:
return None
if section_cache is not None and key in section_cache:
sections = section_cache[key]
else:
sections = sorted(chunk.sections.items(), reverse=True)
if section_cache is not None:
section_cache[key] = sections
local_x, local_z = x - chunk_x * 16, z - chunk_z * 16
min_y = getattr(chunks, 'min_y', -64)
for section_y in sorted(chunk.sections, reverse=True):
if section_y * 16 + 15 < min_y:
for section_y, section in sections:
section_base = section_y * 16
if section_base + 15 < min_y:
continue
section = chunk.sections[section_y]
if section.get('non_empty_blocks') == 0:
continue
for y in range(section_y * 16 + 15, max(min_y, section_y * 16) - 1, -1):
section_blocks = section.get('blocks')
if section_blocks is not None and hasattr(section_blocks, 'get'):
min_local_y = max(0, min_y - section_base)
for local_y in range(15, min_local_y - 1, -1):
index = ((local_y * 16 + local_z) * 16 + local_x)
state_id = section_blocks.get(index)
y = section_base + local_y
if state_id is None or state_id == blocks.AIR:
continue
if (state_id in blocks.NON_SOLID_IDS and
state_id not in blocks.WATER_IDS):
continue
return {'block': blocks.BLOCKS.get(state_id, 'unknown'), 'y': y}
else:
for y in range(section_base + 15, max(min_y, section_base) - 1, -1):
state_id = chunk.get_block_at(local_x, y, local_z)
if state_id is None or state_id == blocks.AIR:
continue
@@ -208,13 +232,13 @@ def api_minimap():
chunks = g.get('chunks')
if (not g.get('connected') or position is None or position is False or
chunks is None or not hasattr(chunks, 'chunks')):
return jsonify(ready=False, cells=[])
return jsonify(ready=False, palette=[], cell_bits=8, cells_b64='')
try:
radius = int(request.args.get('radius', 12))
except (TypeError, ValueError):
radius = 12
radius = max(4, min(32, radius))
radius = max(4, min(36, radius))
try:
radius_x = int(request.args.get('radius_x', radius))
except (TypeError, ValueError):
@@ -224,23 +248,42 @@ def api_minimap():
except (TypeError, ValueError):
radius_z = radius
radius_x = max(4, min(48, radius_x))
radius_z = max(4, min(32, radius_z))
radius_z = max(4, min(36, radius_z))
center_x, center_z = floor(position.x), floor(position.z)
center_y = floor(position.y)
section_cache = {}
palette = []
palette_indices = {}
cell_indices = []
lock = getattr(chunks, 'lock', None)
if lock is not None:
lock.acquire()
try:
cells = [
[_minimap_surface_cell(chunks, center_x + dx, center_z + dz)
for dx in range(-radius_x, radius_x + 1)]
for dz in range(-radius_z, radius_z + 1)
]
for dz in range(-radius_z, radius_z + 1):
for dx in range(-radius_x, radius_x + 1):
cell = _minimap_surface_cell(
chunks, center_x + dx, center_z + dz, section_cache)
if cell is None:
cell_indices.append(0)
else:
name = cell['block']
palette_index = palette_indices.get(name)
if palette_index is None:
palette_index = len(palette) + 1
palette_indices[name] = palette_index
palette.append(name)
cell_indices.append(palette_index)
finally:
if lock is not None:
lock.release()
ready = any(cell is not None for row in cells for cell in row)
ready = bool(palette)
cell_bits = 8 if len(palette) <= 255 else 16
if cell_bits == 8:
cell_data = bytes(cell_indices)
else:
cell_data = b''.join(index.to_bytes(2, 'little')
for index in cell_indices)
path_nodes = []
for node in (g.get('path') or ())[:512]:
try:
@@ -252,16 +295,21 @@ def api_minimap():
continue
path_nodes.append({'x': path_x, 'z': path_z})
return jsonify(
ready=ready,
center={'x': center_x, 'y': center_y, 'z': center_z},
yaw=float(g.get('yaw', 0.0) or 0.0),
radius=radius,
radius_x=radius_x,
radius_z=radius_z,
cells=cells if ready else [],
path=path_nodes,
response_data = {
'ready': ready,
'center': {'x': center_x, 'y': center_y, 'z': center_z},
'yaw': float(g.get('yaw', 0.0) or 0.0),
'radius': radius,
'radius_x': radius_x,
'radius_z': radius_z,
'path': path_nodes,
}
response_data.update(
palette=palette,
cell_bits=cell_bits,
cells_b64=base64.b64encode(cell_data).decode('ascii'),
)
return jsonify(response_data)
@app.route('/api/items')
+60 -3
View File
@@ -1,3 +1,4 @@
import base64
import importlib.util
from pathlib import Path
import threading
@@ -126,9 +127,65 @@ class TestWebInventoryAPI(unittest.TestCase):
])
self.assertEqual(data['radius_x'], 6)
self.assertEqual(data['radius_z'], 4)
self.assertEqual(len(data['cells']), 9)
self.assertEqual(len(data['cells'][0]), 13)
self.assertEqual(data['cells'][4][6], {'block': 'grass_block', 'y': 5})
self.assertEqual(data['palette'], ['grass_block'])
indices = base64.b64decode(data['cells_b64'])
self.assertEqual(len(indices), 9 * 13)
self.assertEqual(indices[4 * 13 + 6], 1)
self.assertNotIn('cells', data)
def test_minimap_returns_palette_encoded_surface_grid(self):
grass = blocks.MCD_BLOCKS['grass_block']['minStateId']
target_index = ((5 * 16 + 1) * 16 + 1)
class FakePalette:
def get(self, index):
return grass if index == target_index else blocks.AIR
class FakeChunk:
sections = {0: {
'non_empty_blocks': 1,
'blocks': FakePalette(),
}}
def get_block_at(self, *_args):
raise AssertionError('palette lookup should avoid per-block API')
class FakeChunks:
min_y = 0
chunks = {(0, 0): FakeChunk()}
self.g.connected = True
self.g.chunks = FakeChunks()
self.g.pos = Munch(x=1.5, y=6.0, z=1.5)
response = self.client.get(
'/api/minimap?radius=4&radius_x=4&radius_z=4')
self.assertEqual(response.status_code, 200)
data = response.get_json()
self.assertTrue(data['ready'])
self.assertEqual(data['palette'], ['grass_block'])
self.assertNotIn('cells', data)
indices = base64.b64decode(data['cells_b64'])
self.assertEqual(len(indices), 9 * 9)
self.assertEqual(indices[4 * 9 + 4], 1)
def test_minimap_api_allows_three_additional_zoom_out_levels(self):
class EmptyChunks:
chunks = {}
self.g.connected = True
self.g.chunks = EmptyChunks()
self.g.pos = Munch(x=0.0, y=64.0, z=0.0)
response = self.client.get(
'/api/minimap?radius=36&radius_x=48&radius_z=36')
self.assertEqual(response.status_code, 200)
data = response.get_json()
self.assertEqual(data['radius'], 36)
self.assertEqual(data['radius_x'], 48)
self.assertEqual(data['radius_z'], 36)
def test_global_api_exposes_world_time_ticks(self):
self.g.time = 12345.5
+1 -1
View File
@@ -81,7 +81,7 @@
<div class="minimap-controls" aria-label="Minimap controls">
<button id="minimap-zoom-out" type="button" aria-label="Zoom out" title="Zoom out">−</button>
<button id="minimap-zoom-in" type="button" aria-label="Zoom in" title="Zoom in">+</button>
<button id="minimap-north-lock" type="button" aria-label="Lock north to the top" aria-pressed="false" title="Lock north to the top">N ↑</button>
<button id="minimap-north-lock" type="button" aria-label="Rotate with the bot" aria-pressed="true" title="Rotate with the bot">N ↑</button>
<button id="minimap-size" type="button" aria-label="Enlarge minimap" aria-pressed="false" title="Enlarge minimap">⤢</button>
</div>
</section>
+1 -1
View File
@@ -81,7 +81,7 @@
<div class="minimap-controls" aria-label="Minimap controls">
<button id="minimap-zoom-out" type="button" aria-label="Zoom out" title="Zoom out">−</button>
<button id="minimap-zoom-in" type="button" aria-label="Zoom in" title="Zoom in">+</button>
<button id="minimap-north-lock" type="button" aria-label="Lock north to the top" aria-pressed="false" title="Lock north to the top">N ↑</button>
<button id="minimap-north-lock" type="button" aria-label="Rotate with the bot" aria-pressed="true" title="Rotate with the bot">N ↑</button>
<button id="minimap-size" type="button" aria-label="Enlarge minimap" aria-pressed="false" title="Enlarge minimap">⤢</button>
</div>
</section>
+31 -8
View File
@@ -2,9 +2,9 @@
'use strict';
const POLL_MS = 1000;
const MINIMAP_POLL_MS = 2000;
const MINIMAP_POLL_MS = 250;
const MINIMAP_MIN_RADIUS = 4;
const MINIMAP_MAX_RADIUS = 24;
const MINIMAP_MAX_RADIUS = 36;
const MINIMAP_ZOOM_STEP = 4;
const $ = (id) => document.getElementById(id);
let itemNames = {};
@@ -15,7 +15,7 @@
let menuAnchor = null;
let toastTimer = null;
let minimapRadius = 12;
let minimapNorthLocked = false;
let minimapNorthLocked = true;
let minimapLarge = false;
let minimapRequestPending = false;
let lastMinimapData = null;
@@ -100,6 +100,27 @@
return '#7a806f';
}
function decodeMinimapPalette(data) {
if (typeof data?.cells_b64 !== 'string' || !Array.isArray(data.palette)) {
return data;
}
const binary = atob(data.cells_b64);
const bits = Number(data.cell_bits) === 16 ? 16 : 8;
if (bits === 8) {
data.cellIndices = Uint8Array.from(binary, (character) =>
character.charCodeAt(0));
} else {
const indices = new Uint16Array(binary.length / 2);
for (let index = 0; index < indices.length; index++) {
indices[index] = binary.charCodeAt(index * 2) |
(binary.charCodeAt(index * 2 + 1) << 8);
}
data.cellIndices = indices;
}
data.paletteColors = data.palette.map(minimapBlockColor);
return data;
}
function drawMinimap(data = lastMinimapData) {
const canvas = $('minimap-canvas');
if (!canvas) return;
@@ -112,7 +133,7 @@
context.fillStyle = '#111411';
context.fillRect(0, 0, width, height);
if (!data?.ready || !Array.isArray(data.cells)) {
if (!data?.ready || !data.cellIndices || !Array.isArray(data.paletteColors)) {
$('minimap-caption').textContent = 'Waiting for loaded terrain';
updateMinimapControls();
return;
@@ -131,10 +152,12 @@
const rasterContext = raster.getContext('2d');
const rasterPixels = rasterContext.createImageData(columns, rows);
for (let rowIndex = 0; rowIndex < rows; rowIndex++) {
const row = data.cells[rowIndex] || [];
for (let columnIndex = 0; columnIndex < columns; columnIndex++) {
const surface = row[columnIndex];
const color = surface ? minimapBlockColor(surface.block) : '#171b17';
const flatIndex = rowIndex * columns + columnIndex;
const paletteIndex = data.cellIndices[flatIndex];
const color = paletteIndex
? data.paletteColors[paletteIndex - 1]
: '#171b17';
const value = Number.parseInt(color.slice(1), 16);
const pixel = (rowIndex * columns + columnIndex) * 4;
rasterPixels.data[pixel] = value >> 16;
@@ -698,7 +721,7 @@
{cache: 'no-store'},
);
if (!response.ok) throw new Error(`API ${response.status}`);
const data = await response.json();
const data = decodeMinimapPalette(await response.json());
const currentRadii = minimapRadii();
if (requestedRadius !== minimapRadius ||
requestKey !== `${currentRadii.x}:${currentRadii.z}` ||
+1 -1
View File
@@ -81,7 +81,7 @@
<div class="minimap-controls" aria-label="Minimap controls">
<button id="minimap-zoom-out" type="button" aria-label="Zoom out" title="Zoom out">−</button>
<button id="minimap-zoom-in" type="button" aria-label="Zoom in" title="Zoom in">+</button>
<button id="minimap-north-lock" type="button" aria-label="Lock north to the top" aria-pressed="false" title="Lock north to the top">N ↑</button>
<button id="minimap-north-lock" type="button" aria-label="Rotate with the bot" aria-pressed="true" title="Rotate with the bot">N ↑</button>
<button id="minimap-size" type="button" aria-label="Enlarge minimap" aria-pressed="false" title="Enlarge minimap">⤢</button>
</div>
</section>