- /spawn : spawn du monde (getSharedSpawnPos), délai annulé si mouvement/blessure, recharge. - /rtp : zone déjà générée uniquement (chunk + 8 voisins complets sur disque, région absente jamais lue), atterrissage sûr, évite les claims GastinelClaims, recharge, messages FR. - /rtp spawn : réservé aux blocs de commande, tirage pondéré parmi le top N de beaux-spots.json. - /rtp diagnostic (op) : recherche sans téléportation, avec motifs de rejet. - outils/beaux_spots.py : notation de beauté v0 sur une copie du monde. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
328 lignes
14 KiB
Python
328 lignes
14 KiB
Python
#!/usr/bin/env python3
|
|
"""Notation de « beauté » des lieux d'un monde Minecraft prégénéré (version 0).
|
|
|
|
Lit en LECTURE SEULE les régions (.mca) d'une COPIE du monde, résume chaque chunk
|
|
(hauteurs, eau, arbres, biomes, sûreté d'atterrissage), puis note des candidats
|
|
(un par chunk, sur une grille) avec des critères pondérés définis dans un fichier JSON.
|
|
Produit beaux-spots.json, lu par le mod GastinelTpa pour /rtp spawn.
|
|
|
|
Usage (sur cornafserver, avec nice) :
|
|
nice -n 19 python3 -I beaux_spots.py --monde <copie-du-monde> \
|
|
--config beaux-spots-config.json --sortie beaux-spots.json [--echantillon 20]
|
|
|
|
Aucune écriture dans le monde : seuls level.dat et region/*.mca sont ouverts en lecture.
|
|
"""
|
|
import argparse
|
|
import glob
|
|
import json
|
|
import math
|
|
import os
|
|
import re
|
|
import sys
|
|
import time
|
|
from collections import Counter
|
|
from multiprocessing import Pool
|
|
|
|
import numpy as np
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
from nbt_anvil import bits_pour, chunks_de_region, deplier, heightmap, lire_level_dat # noqa: E402
|
|
|
|
# Blocs sur lesquels on n'atterrit jamais (ou qu'on ne veut pas à côté des pieds).
|
|
DANGEREUX = {
|
|
"minecraft:lava", "minecraft:fire", "minecraft:soul_fire", "minecraft:magma_block",
|
|
"minecraft:cactus", "minecraft:sweet_berry_bush", "minecraft:campfire", "minecraft:soul_campfire",
|
|
"minecraft:powder_snow", "minecraft:pointed_dripstone", "minecraft:wither_rose",
|
|
}
|
|
LIQUIDES = {"minecraft:water", "minecraft:lava", "minecraft:bubble_column"}
|
|
SABLE = {"minecraft:sand", "minecraft:red_sand", "minecraft:sandstone", "minecraft:red_sandstone",
|
|
"minecraft:terracotta"}
|
|
RE_PAS_SOL = re.compile(r"(_log|_wood|_stem|_hyphae|leaves|_fence|_wall|_pane|glass|ice|"
|
|
r"bamboo|_slab|_stairs|_door|_trapdoor|scaffolding|chest|barrel|bed$|"
|
|
r"_sign|lantern|chain|bell|_rail|rail$|piston|hopper)")
|
|
|
|
|
|
def bloc_sur(nom):
|
|
"""Bloc plein « naturel » où l'on peut poser les pieds."""
|
|
if nom in DANGEREUX or nom in LIQUIDES:
|
|
return False
|
|
if nom in ("minecraft:air", "minecraft:cave_air", "minecraft:void_air"):
|
|
return False
|
|
return not RE_PAS_SOL.search(nom)
|
|
|
|
|
|
def _sections(nbt):
|
|
out = {}
|
|
for s in nbt.get("sections", []):
|
|
out[s.get("Y")] = s
|
|
return out
|
|
|
|
|
|
def _blocs_section(section, cache):
|
|
"""Tableau (4096,) d'indices + palette des noms, décodé une fois par section."""
|
|
y = section.get("Y")
|
|
if y in cache:
|
|
return cache[y]
|
|
bs = section.get("block_states") or {}
|
|
pal = [p.get("Name", "minecraft:air") for p in bs.get("palette", [])] or ["minecraft:air"]
|
|
data = bs.get("data")
|
|
if data is None or len(pal) == 1:
|
|
idx = np.zeros(4096, dtype=np.int64)
|
|
else:
|
|
idx = deplier(data, 4096, bits_pour(len(pal), 4))
|
|
cache[y] = (idx, pal)
|
|
return cache[y]
|
|
|
|
|
|
def _bloc(sections, cache, x, y, z):
|
|
sy = y >> 4
|
|
s = sections.get(sy)
|
|
if s is None:
|
|
return "minecraft:air"
|
|
idx, pal = _blocs_section(s, cache)
|
|
i = idx[((y & 15) * 16 + z) * 16 + x]
|
|
return pal[i] if i < len(pal) else "minecraft:air"
|
|
|
|
|
|
def _biome(sections, x, y, z):
|
|
s = sections.get(y >> 4)
|
|
if s is None:
|
|
return "?"
|
|
bm = s.get("biomes") or {}
|
|
pal = bm.get("palette", [])
|
|
if not pal:
|
|
return "?"
|
|
if len(pal) == 1 or bm.get("data") is None:
|
|
return pal[0]
|
|
vals = deplier(bm["data"], 64, bits_pour(len(pal), 1))
|
|
i = vals[(((y & 15) >> 2) * 4 + (z >> 2)) * 4 + (x >> 2)]
|
|
return pal[i] if i < len(pal) else "?"
|
|
|
|
|
|
def resumer_chunk(nbt):
|
|
"""Résumé compact d'un chunk FULL (None sinon)."""
|
|
if nbt.get("Status") not in ("minecraft:full", "full"):
|
|
return None
|
|
hm = nbt.get("Heightmaps") or {}
|
|
min_y = nbt.get("yPos", -4) * 16
|
|
sol = heightmap(hm.get("MOTION_BLOCKING_NO_LEAVES"), min_y) # sol, eau comprise, sans feuilles
|
|
fond = heightmap(hm.get("OCEAN_FLOOR"), min_y) # sol solide (sans liquides)
|
|
haut = heightmap(hm.get("MOTION_BLOCKING"), min_y) # avec feuilles
|
|
if sol is None or fond is None or haut is None:
|
|
return None
|
|
sections = _sections(nbt)
|
|
cache = {}
|
|
prof = sol - fond
|
|
canopee = haut > sol
|
|
# Blocs de surface : un sur deux (64 colonnes)
|
|
surf = Counter()
|
|
danger = 0
|
|
for z in range(0, 16, 2):
|
|
for x in range(0, 16, 2):
|
|
b = _bloc(sections, cache, x, int(sol[z, x]) - 1, z)
|
|
surf[b] += 1
|
|
if b in DANGEREUX:
|
|
danger += 1
|
|
# Colonne d'atterrissage : la plus proche du centre qui est sûre
|
|
meilleure = None
|
|
for d2, x, z in sorted(((x - 7.5) ** 2 + (z - 7.5) ** 2, x, z)
|
|
for x in range(2, 14) for z in range(2, 14)):
|
|
if prof[z, x] > 0:
|
|
continue
|
|
y = int(sol[z, x])
|
|
voisins = sol[z - 1:z + 2, x - 1:x + 2]
|
|
if voisins.max() - voisins.min() > 2 or (prof[z - 1:z + 2, x - 1:x + 2] > 0).any():
|
|
continue
|
|
if not bloc_sur(_bloc(sections, cache, x, y - 1, z)):
|
|
continue
|
|
if _bloc(sections, cache, x, y, z) not in ("minecraft:air", "minecraft:cave_air") and \
|
|
not _bloc(sections, cache, x, y, z).endswith(("short_grass", "fern", "snow")):
|
|
continue
|
|
if _bloc(sections, cache, x, y + 1, z) not in ("minecraft:air", "minecraft:cave_air"):
|
|
continue
|
|
if any(_bloc(sections, cache, x + dx, y - 1 + dy, z + dz) in DANGEREUX
|
|
for dx in (-1, 0, 1) for dz in (-1, 0, 1) for dy in (0, 1)):
|
|
continue
|
|
meilleure = (x, y, z)
|
|
break
|
|
biomes = Counter(_biome(sections, x, int(sol[z, x]), z) for x in (2, 13) for z in (2, 13))
|
|
centre_biome = _biome(sections, 8, int(sol[8, 8]), 8)
|
|
biomes[centre_biome] += 1
|
|
refs = (nbt.get("structures") or {}).get("References") or {}
|
|
village = any("village" in k for k in refs)
|
|
total = 64
|
|
return {
|
|
"h": float(sol.mean()), "hmin": int(sol.min()), "hmax": int(sol.max()),
|
|
"eau": float((prof > 0).mean()), "eau_prof": float((prof >= 4).mean()),
|
|
"canopee": float(canopee.mean()), "danger": danger / total,
|
|
"sable": sum(v for k, v in surf.items() if k in SABLE) / total,
|
|
"biome": centre_biome, "biomes": sorted(biomes),
|
|
"atterrissage": meilleure, "village": village,
|
|
}
|
|
|
|
|
|
def traiter_region(chemin):
|
|
m = re.search(r"r\.(-?\d+)\.(-?\d+)\.mca$", chemin)
|
|
rx, rz = int(m.group(1)), int(m.group(2))
|
|
out = {}
|
|
for lx, lz, nbt in chunks_de_region(chemin):
|
|
try:
|
|
r = resumer_chunk(nbt)
|
|
except Exception:
|
|
r = None
|
|
if r is not None:
|
|
out[(rx * 32 + lx, rz * 32 + lz)] = r
|
|
return out
|
|
|
|
|
|
# ---------- Notation ----------
|
|
|
|
def rampe(v, a, b):
|
|
"""0 sous a, 1 au-dessus de b, linéaire entre les deux."""
|
|
if b == a:
|
|
return 1.0 if v >= b else 0.0
|
|
return min(1.0, max(0.0, (v - a) / (b - a)))
|
|
|
|
|
|
def plateau(v, a, b, c, d):
|
|
"""0 avant a, monte jusqu'à b, 1 entre b et c, redescend à 0 en d."""
|
|
return min(rampe(v, a, b), 1.0 - rampe(v, c, d))
|
|
|
|
|
|
def noter(chunks, cfg):
|
|
c = cfg["criteres"]
|
|
p = cfg["poids"]
|
|
R = cfg.get("rayon_voisinage_chunks", 3)
|
|
RV = cfg.get("rayon_vue_chunks", 6)
|
|
pas = cfg.get("pas_grille_chunks", 1)
|
|
freq = Counter(r["biome"] for r in chunks.values())
|
|
fmax = max(freq.values())
|
|
candidats = []
|
|
for (cx, cz), r in chunks.items():
|
|
if cx % pas or cz % pas or r["atterrissage"] is None:
|
|
continue
|
|
voisins = [chunks.get((cx + dx, cz + dz)) for dx in range(-R, R + 1) for dz in range(-R, R + 1)]
|
|
voisins = [v for v in voisins if v is not None]
|
|
if len(voisins) < 0.8 * (2 * R + 1) ** 2:
|
|
continue # bord de la zone générée : voisinage incomplet
|
|
loin = [chunks.get((cx + dx, cz + dz)) for dx in range(-RV, RV + 1, 2) for dz in range(-RV, RV + 1, 2)]
|
|
loin = [v for v in loin if v is not None]
|
|
lx, ly, lz = r["atterrissage"]
|
|
hs = [v["h"] for v in voisins]
|
|
relief = max(v["hmax"] for v in voisins) - min(v["hmin"] for v in voisins)
|
|
vue = ly - float(np.mean([v["h"] for v in loin]))
|
|
eau = float(np.mean([v["eau"] for v in voisins]))
|
|
eau_prof = float(np.mean([v["eau_prof"] for v in voisins]))
|
|
canopee = float(np.mean([v["canopee"] for v in voisins]))
|
|
sable = float(np.mean([v["sable"] for v in voisins]))
|
|
danger = float(np.mean([v["danger"] for v in voisins]))
|
|
biomes = set()
|
|
for v in voisins:
|
|
biomes.update(v["biomes"])
|
|
biomes.discard("?")
|
|
rarete = 1.0 - freq[r["biome"]] / fmax
|
|
terralith = 1.0 if r["biome"].startswith("terralith:") else 0.0
|
|
s_relief = rampe(relief, c["relief_min"], c["relief_ideal"])
|
|
s_vue = rampe(vue, 0, c["vue_ideal"])
|
|
s_eau = plateau(eau, 0.0, c["eau_min_ideal"], c["eau_max_ideal"], c["eau_trop"])
|
|
s_veg = plateau(canopee, 0.0, c["canopee_min_ideal"], c["canopee_max_ideal"], 1.0)
|
|
s_var = rampe(len(biomes), 1, c["biomes_varietes_ideal"])
|
|
plat = 1.0 - rampe(float(np.std(hs)), 0, c["relief_std_plat"])
|
|
pen_ocean = rampe(eau_prof, c["ocean_prof_seuil"], 1.0)
|
|
pen_desert = sable * plat
|
|
pen_village = 1.0 if any(v["village"] for v in voisins) else 0.0
|
|
pen_danger = rampe(danger, 0.0, 0.1)
|
|
s_surete = 1.0 if abs(vue) < c["surete_vue_max"] else 0.5
|
|
detail = {
|
|
"relief": round(s_relief, 2), "vue": round(s_vue, 2), "eau": round(s_eau, 2),
|
|
"vegetation": round(s_veg, 2), "biome_variete": round(s_var, 2),
|
|
"biome_rarete": round(rarete, 2), "terralith": terralith, "surete": s_surete,
|
|
"pen_ocean_profond": round(pen_ocean, 2), "pen_desert_plat": round(pen_desert, 2),
|
|
"pen_village": pen_village, "pen_danger": round(pen_danger, 2),
|
|
}
|
|
positif = sum(p[k] for k in p if not k.startswith("pen_"))
|
|
brut = sum(p[k] * detail[k] for k in p if not k.startswith("pen_")) \
|
|
- sum(p[k] * detail[k] for k in p if k.startswith("pen_"))
|
|
score = 10.0 * min(1.0, max(0.0, brut / positif))
|
|
candidats.append({
|
|
"x": cx * 16 + lx, "y": ly, "z": cz * 16 + lz, "score": round(score, 2),
|
|
"biome": r["biome"],
|
|
"mesures": {"relief_blocs": relief, "vue_blocs": round(vue, 1), "eau": round(eau, 2),
|
|
"canopee": round(canopee, 2), "biomes_proches": len(biomes)},
|
|
"detail": detail,
|
|
})
|
|
candidats.sort(key=lambda s: -s["score"])
|
|
# Espacement minimal entre spots retenus
|
|
dmin2 = cfg.get("espacement_min_blocs", 96) ** 2
|
|
retenus = []
|
|
for s in candidats:
|
|
if all((s["x"] - t["x"]) ** 2 + (s["z"] - t["z"]) ** 2 >= dmin2 for t in retenus):
|
|
retenus.append(s)
|
|
if len(retenus) >= cfg.get("nombre_spots_max", 300):
|
|
break
|
|
return candidats, retenus, freq
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--monde", required=True)
|
|
ap.add_argument("--config", required=True)
|
|
ap.add_argument("--sortie", required=True)
|
|
ap.add_argument("--processus", type=int, default=3)
|
|
ap.add_argument("--echantillon", type=int, default=20)
|
|
a = ap.parse_args()
|
|
with open(a.config, encoding="utf-8") as f:
|
|
cfg = json.load(f)
|
|
t0 = time.time()
|
|
level = lire_level_dat(os.path.join(a.monde, "level.dat"))
|
|
zone = cfg.get("zone")
|
|
fichiers = sorted(glob.glob(os.path.join(a.monde, "region", "r.*.mca")))
|
|
if zone:
|
|
def dans_zone(fp):
|
|
m = re.search(r"r\.(-?\d+)\.(-?\d+)\.mca$", fp)
|
|
rx, rz = int(m.group(1)), int(m.group(2))
|
|
return (rx * 512 + 511 >= zone["xmin"] and rx * 512 <= zone["xmax"]
|
|
and rz * 512 + 511 >= zone["zmin"] and rz * 512 <= zone["zmax"])
|
|
fichiers = [fp for fp in fichiers if dans_zone(fp)]
|
|
chunks = {}
|
|
with Pool(a.processus) as pool:
|
|
for i, res in enumerate(pool.imap_unordered(traiter_region, fichiers)):
|
|
chunks.update(res)
|
|
print(f"\r{i + 1}/{len(fichiers)} régions, {len(chunks)} chunks", end="", file=sys.stderr)
|
|
print(file=sys.stderr)
|
|
if zone:
|
|
chunks = {k: v for k, v in chunks.items()
|
|
if zone["xmin"] <= k[0] * 16 + 8 <= zone["xmax"] and zone["zmin"] <= k[1] * 16 + 8 <= zone["zmax"]}
|
|
xs = [k[0] for k in chunks]
|
|
zs = [k[1] for k in chunks]
|
|
candidats, retenus, freq = noter(chunks, cfg)
|
|
scores = np.array([c["score"] for c in candidats]) if candidats else np.zeros(1)
|
|
sortie = {
|
|
"version": 0,
|
|
"genere_le": time.strftime("%Y-%m-%d %H:%M:%S"),
|
|
"monde": os.path.basename(os.path.normpath(a.monde)),
|
|
"spawn_monde": [level.get("SpawnX"), level.get("SpawnY"), level.get("SpawnZ")],
|
|
"bordure_monde": {"centre": [level.get("BorderCenterX"), level.get("BorderCenterZ")],
|
|
"taille": level.get("BorderSize")},
|
|
"etendue_generee": {"chunks_full": len(chunks),
|
|
"xmin": min(xs) * 16, "xmax": max(xs) * 16 + 15,
|
|
"zmin": min(zs) * 16, "zmax": max(zs) * 16 + 15},
|
|
"candidats_notes": len(candidats),
|
|
"repartition_scores": {"p50": round(float(np.percentile(scores, 50)), 2),
|
|
"p90": round(float(np.percentile(scores, 90)), 2),
|
|
"max": round(float(scores.max()), 2)},
|
|
"biomes_frequents": freq.most_common(15),
|
|
"config": cfg,
|
|
"spots": retenus,
|
|
}
|
|
with open(a.sortie, "w", encoding="utf-8") as f:
|
|
json.dump(sortie, f, ensure_ascii=False, indent=1)
|
|
print(f"{len(chunks)} chunks, {len(candidats)} candidats, {len(retenus)} spots retenus "
|
|
f"en {time.time() - t0:.0f} s -> {a.sortie}", file=sys.stderr)
|
|
for s in retenus[:a.echantillon]:
|
|
print(f"{s['score']:5.2f} ({s['x']}, {s['y']}, {s['z']}) {s['biome']} {s['mesures']}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|