LuminaWebsite/includes/map.php
Maaxxs 6b5661dd53 Karte: tactical map tab with own markers and tactic layers
New "Karte" tab: a tiled zoom/pan map of the game world with a category
sidebar (groups, per-category marker counts, show all / hide all, search)
and marker popups, plus tactic layers drawn on top of it.

Markers are placed by clicking the map (map.manage) and live in freely
editable two-level categories, each with its own emoji and colour. A tactic
(map.tactics) is a separate drawing layer that can be toggled on and off:
rally points, dashed routes, areas and text notes in any colour, finished by
double click, an explicit button or Enter, removed by clicking them.

Coordinates are stored as a fraction of the map's width/height rather than
in pixels, so re-tiling the map at a different resolution never moves
anything.

The map data lives entirely in the website database - the Discord bot is not
involved. tools/make_map_tiles.php slices a high-resolution image into the
zoom pyramid locally; the resulting folder is uploaded by FTP and picked up
automatically, one region per folder. Leaflet 1.9.4 is vendored under
assets/vendor/ so there is still no CDN and no build step.

New permissions map.view / map.manage / map.tactics and four new tables -
existing installs have to add both once (see README).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-20 13:25:12 +02:00

285 lines
9.7 KiB
PHP

<?php
declare(strict_types=1);
/**
* Datenschicht der Taktikkarte. Anders als Raids/Premades/Reports/Events haengt die Karte
* nicht am Discord-Bot, sondern liegt komplett in der Website-Datenbank - der Bot kennt
* weder Kartenkacheln noch Marker.
*/
// Verzeichnis, in dem die gekachelten Karten liegen (je Karte ein Unterordner mit
// tiles.json + Zoomstufen-Ordnern, erzeugt von tools/make_map_tiles.php).
const MAP_TILES_DIR = __DIR__ . '/../assets/uploads/maps';
const MAP_TILES_URL = '/assets/uploads/maps';
/**
* Liest die verfuegbaren Karten aus dem Kachel-Verzeichnis. Jede Karte beschreibt sich
* ueber ihre eigene tiles.json selbst, dadurch kommt eine neue Region dazu, ohne dass
* Code oder Datenbank angefasst werden muessen.
*
* @return array<string, array<string, mixed>> Kartenschluessel => Manifest
*/
function map_available(): array
{
if (!is_dir(MAP_TILES_DIR)) {
return [];
}
$maps = [];
foreach (scandir(MAP_TILES_DIR) ?: [] as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
}
$manifestPath = MAP_TILES_DIR . '/' . $entry . '/tiles.json';
if (!is_file($manifestPath)) {
continue;
}
$manifest = json_decode((string) file_get_contents($manifestPath), true);
if (!is_array($manifest) || empty($manifest['width']) || empty($manifest['height'])) {
continue;
}
$manifest['key'] = $entry;
$manifest['name'] = (string) ($manifest['name'] ?? ucfirst($entry));
$manifest['url_template'] = MAP_TILES_URL . '/' . rawurlencode($entry) . '/{z}/{x}_{y}.'
. (string) ($manifest['extension'] ?? 'jpg');
$maps[$entry] = $manifest;
}
ksort($maps);
return $maps;
}
/**
* Kategorien als zweistufige Struktur (Gruppen mit ihren Kategorien), inklusive der
* Marker-Anzahl je Kategorie - genau die Zahlen, die in der Sidebar hinter den Namen
* stehen.
*
* @return array<int, array<string, mixed>>
*/
function map_category_tree(string $mapKey): array
{
$stmt = db()->prepare(
'SELECT c.id, c.parent_id, c.name, c.icon, c.color, c.sort_order,
(SELECT COUNT(*) FROM map_markers m WHERE m.category_id = c.id AND m.map_key = ?) AS marker_count
FROM map_categories c
ORDER BY c.sort_order ASC, c.name ASC'
);
$stmt->execute([$mapKey]);
$rows = $stmt->fetchAll();
$groups = [];
$children = [];
foreach ($rows as $row) {
if ($row['parent_id'] === null) {
$row['children'] = [];
$row['total_count'] = 0;
$groups[(int) $row['id']] = $row;
} else {
$children[(int) $row['parent_id']][] = $row;
}
}
foreach ($groups as $id => $group) {
$groupChildren = $children[$id] ?? [];
$groups[$id]['children'] = $groupChildren;
$groups[$id]['total_count'] = array_sum(array_map(
fn (array $child): int => (int) $child['marker_count'],
$groupChildren
));
}
// Kategorien, deren Gruppe geloescht wurde, waeren sonst unsichtbar.
$orphans = [];
foreach ($children as $parentId => $list) {
if (!isset($groups[$parentId])) {
$orphans = array_merge($orphans, $list);
}
}
if (!empty($orphans)) {
$groups[0] = [
'id' => 0,
'parent_id' => null,
'name' => 'Ohne Gruppe',
'icon' => '',
'color' => '#a0a0a0',
'sort_order' => 9999,
'children' => $orphans,
'total_count' => array_sum(array_map(fn (array $c): int => (int) $c['marker_count'], $orphans)),
];
}
return array_values($groups);
}
/**
* Alle Marker einer Karte, fertig fuer die Uebergabe an das Frontend.
*
* @return array<int, array<string, mixed>>
*/
function map_markers(string $mapKey): array
{
$stmt = db()->prepare(
'SELECT m.id, m.category_id, m.name, m.description, m.pos_x, m.pos_y,
u.display_name, u.username
FROM map_markers m
LEFT JOIN users u ON u.id = m.created_by
WHERE m.map_key = ?
ORDER BY m.id ASC'
);
$stmt->execute([$mapKey]);
return array_map(static function (array $row): array {
$author = trim((string) ($row['display_name'] ?? '')) !== ''
? (string) $row['display_name']
: (string) ($row['username'] ?? '');
return [
'id' => (int) $row['id'],
'category_id' => (int) $row['category_id'],
'name' => (string) $row['name'],
'description' => (string) ($row['description'] ?? ''),
'x' => (float) $row['pos_x'],
'y' => (float) $row['pos_y'],
'author' => $author,
];
}, $stmt->fetchAll());
}
/**
* Taktiken einer Karte samt ihrer Zeichenobjekte.
*
* @return array<int, array<string, mixed>>
*/
function map_tactics(string $mapKey): array
{
$stmt = db()->prepare(
'SELECT t.id, t.name, t.description, t.updated_at, t.created_at, u.display_name, u.username
FROM map_tactics t
LEFT JOIN users u ON u.id = t.created_by
WHERE t.map_key = ?
ORDER BY t.name ASC'
);
$stmt->execute([$mapKey]);
$tactics = $stmt->fetchAll();
if (empty($tactics)) {
return [];
}
$ids = array_map(fn (array $t): int => (int) $t['id'], $tactics);
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$shapeStmt = db()->prepare(
"SELECT id, tactic_id, shape_type, label, color, points, sort_order
FROM map_tactic_shapes WHERE tactic_id IN ($placeholders)
ORDER BY sort_order ASC, id ASC"
);
$shapeStmt->execute($ids);
$shapesByTactic = [];
foreach ($shapeStmt->fetchAll() as $shape) {
$points = json_decode((string) $shape['points'], true);
$shapesByTactic[(int) $shape['tactic_id']][] = [
'id' => (int) $shape['id'],
'type' => (string) $shape['shape_type'],
'label' => (string) $shape['label'],
'color' => (string) $shape['color'],
'points' => is_array($points) ? $points : [],
];
}
return array_map(static function (array $tactic) use ($shapesByTactic): array {
$author = trim((string) ($tactic['display_name'] ?? '')) !== ''
? (string) $tactic['display_name']
: (string) ($tactic['username'] ?? '');
return [
'id' => (int) $tactic['id'],
'name' => (string) $tactic['name'],
'description' => (string) ($tactic['description'] ?? ''),
'author' => $author,
'updated_at' => (string) ($tactic['updated_at'] ?? $tactic['created_at'] ?? ''),
'shapes' => $shapesByTactic[(int) $tactic['id']] ?? [],
];
}, $tactics);
}
/**
* Startbestueckung der Kategorien, angelehnt an die Gliederung gaengiger Aion-Karten.
* Wird nur angeboten, solange ueberhaupt keine Kategorie existiert - danach pflegt ihr
* die Liste selbst.
*
* @return array<int, array{name: string, icon: string, color: string, children: array<int, array{0: string, 1: string}>}>
*/
function map_default_categories(): array
{
return [
['name' => 'Orte', 'icon' => '🏰', 'color' => '#c9a227', 'children' => [
['Siedlung', '🏘'], ['Region', '🚩'], ['Festung', '🛡'], ['Dungeon', '🕳'], ['Rift', '🌀'],
]],
['name' => 'Sammelbares', 'icon' => '💠', 'color' => '#4fc3f7', 'children' => [
['Empyreische Spur', '✨'], ['Versteckter Würfel', '🎁'], ['Boss', '💀'],
]],
['name' => 'NPCs', 'icon' => '🧝', 'color' => '#81c784', 'children' => [
['Händler', '💰'], ['Handwerksstation', '⚒'], ['Lagerverwalter', '📦'], ['Instanz-Eingang', '🚪'],
]],
['name' => 'Quests', 'icon' => '📜', 'color' => '#ffb74d', 'children' => [
['Regionsquest', '❗'], ['Story-Quest', '📖'],
]],
['name' => 'Ressourcen', 'icon' => '⛏', 'color' => '#a1887f', 'children' => [
['Erz', '⛏'], ['Edelstein', '💎'], ['Holz', '🪵'], ['Kraut', '🌿'],
]],
['name' => 'Monster', 'icon' => '🐉', 'color' => '#e57373', 'children' => [
['Namhafter Boss', '👑'], ['Elite', '⚔'], ['Normal', '🐾'],
]],
['name' => 'Gilde', 'icon' => '⚜', 'color' => '#ba68c8', 'children' => [
['Sammelpunkt', '📍'], ['Eigene Notiz', '📝'],
]],
];
}
/**
* Legt die Standard-Kategorien an. Gibt die Anzahl der erzeugten Kategorien zurueck.
*/
function map_seed_default_categories(): int
{
$pdo = db();
$created = 0;
$sort = 0;
foreach (map_default_categories() as $group) {
$sort += 10;
$stmt = $pdo->prepare('INSERT INTO map_categories (parent_id, name, icon, color, sort_order) VALUES (NULL, ?, ?, ?, ?)');
$stmt->execute([$group['name'], $group['icon'], $group['color'], $sort]);
$groupId = (int) $pdo->lastInsertId();
$created++;
$childSort = 0;
foreach ($group['children'] as $child) {
$childSort += 10;
$childStmt = $pdo->prepare('INSERT INTO map_categories (parent_id, name, icon, color, sort_order) VALUES (?, ?, ?, ?, ?)');
$childStmt->execute([$groupId, $child[0], $child[1], $group['color'], $childSort]);
$created++;
}
}
return $created;
}
/**
* Prueft eine normierte Koordinate (0..1). Alles ausserhalb waere ausserhalb des
* Kartenbildes und damit unerreichbar.
*/
function map_valid_coordinate($value): bool
{
return is_numeric($value) && (float) $value >= 0.0 && (float) $value <= 1.0;
}
/**
* Prueft eine Farbangabe im Format #rrggbb.
*/
function map_valid_color(string $color): bool
{
return preg_match('/^#[0-9a-fA-F]{6}$/', $color) === 1;
}