GastinelTpa 1.1.0 : /spawn, /rtp, /rtp spawn (blocs de commande), notation des beaux spots
- /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>
Cette révision appartient à :
1 Parent
3b34a46376
révision
53cfd9f02f
16 fichiers modifiés
+1443
-8
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"_doc": "Réglages de beaux_spots.py (version 0). Poids : importance relative de chaque critère (0 = ignoré). Les poids pen_* sont soustraits. Score final ramené sur 0-10.",
|
||||
"zone": null,
|
||||
"pas_grille_chunks": 1,
|
||||
"rayon_voisinage_chunks": 3,
|
||||
"rayon_vue_chunks": 6,
|
||||
"espacement_min_blocs": 96,
|
||||
"nombre_spots_max": 300,
|
||||
"criteres": {
|
||||
"relief_min": 6,
|
||||
"relief_ideal": 45,
|
||||
"relief_std_plat": 6,
|
||||
"vue_ideal": 20,
|
||||
"eau_min_ideal": 0.05,
|
||||
"eau_max_ideal": 0.30,
|
||||
"eau_trop": 0.75,
|
||||
"canopee_min_ideal": 0.20,
|
||||
"canopee_max_ideal": 0.60,
|
||||
"biomes_varietes_ideal": 4,
|
||||
"ocean_prof_seuil": 0.25,
|
||||
"surete_vue_max": 40
|
||||
},
|
||||
"poids": {
|
||||
"relief": 2.0,
|
||||
"vue": 2.0,
|
||||
"eau": 2.0,
|
||||
"vegetation": 1.5,
|
||||
"biome_variete": 1.0,
|
||||
"biome_rarete": 1.0,
|
||||
"terralith": 0.5,
|
||||
"surete": 1.0,
|
||||
"pen_ocean_profond": 3.0,
|
||||
"pen_desert_plat": 2.0,
|
||||
"pen_village": 0.0,
|
||||
"pen_danger": 2.0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Lecture minimale (lecture seule) du format NBT et des régions Anvil (.mca) de Minecraft 1.21.
|
||||
|
||||
Aucune dépendance hors numpy. Ne modifie jamais les fichiers lus.
|
||||
"""
|
||||
import gzip
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
import numpy as np
|
||||
|
||||
TAG_END, TAG_BYTE, TAG_SHORT, TAG_INT, TAG_LONG, TAG_FLOAT, TAG_DOUBLE = 0, 1, 2, 3, 4, 5, 6
|
||||
TAG_BYTE_ARRAY, TAG_STRING, TAG_LIST, TAG_COMPOUND, TAG_INT_ARRAY, TAG_LONG_ARRAY = 7, 8, 9, 10, 11, 12
|
||||
|
||||
|
||||
class _Lecteur:
|
||||
__slots__ = ("b", "p")
|
||||
|
||||
def __init__(self, data):
|
||||
self.b = data
|
||||
self.p = 0
|
||||
|
||||
def u(self, fmt, n):
|
||||
v = struct.unpack_from(fmt, self.b, self.p)[0]
|
||||
self.p += n
|
||||
return v
|
||||
|
||||
def chaine(self):
|
||||
n = self.u(">H", 2)
|
||||
s = self.b[self.p:self.p + n].decode("utf-8", "replace")
|
||||
self.p += n
|
||||
return s
|
||||
|
||||
def charge(self, t):
|
||||
if t == TAG_BYTE:
|
||||
return self.u(">b", 1)
|
||||
if t == TAG_SHORT:
|
||||
return self.u(">h", 2)
|
||||
if t == TAG_INT:
|
||||
return self.u(">i", 4)
|
||||
if t == TAG_LONG:
|
||||
return self.u(">q", 8)
|
||||
if t == TAG_FLOAT:
|
||||
return self.u(">f", 4)
|
||||
if t == TAG_DOUBLE:
|
||||
return self.u(">d", 8)
|
||||
if t == TAG_BYTE_ARRAY:
|
||||
n = self.u(">i", 4)
|
||||
v = self.b[self.p:self.p + n]
|
||||
self.p += n
|
||||
return v
|
||||
if t == TAG_STRING:
|
||||
return self.chaine()
|
||||
if t == TAG_LIST:
|
||||
et = self.u(">b", 1)
|
||||
n = self.u(">i", 4)
|
||||
return [self.charge(et) for _ in range(n)]
|
||||
if t == TAG_COMPOUND:
|
||||
d = {}
|
||||
while True:
|
||||
ct = self.u(">b", 1)
|
||||
if ct == TAG_END:
|
||||
return d
|
||||
nom = self.chaine()
|
||||
d[nom] = self.charge(ct)
|
||||
if t == TAG_INT_ARRAY:
|
||||
n = self.u(">i", 4)
|
||||
v = np.frombuffer(self.b, dtype=">i4", count=n, offset=self.p)
|
||||
self.p += 4 * n
|
||||
return v
|
||||
if t == TAG_LONG_ARRAY:
|
||||
n = self.u(">i", 4)
|
||||
v = np.frombuffer(self.b, dtype=">u8", count=n, offset=self.p)
|
||||
self.p += 8 * n
|
||||
return v
|
||||
raise ValueError(f"tag NBT inconnu {t}")
|
||||
|
||||
|
||||
def lire_nbt(data):
|
||||
r = _Lecteur(data)
|
||||
t = r.u(">b", 1)
|
||||
if t != TAG_COMPOUND:
|
||||
raise ValueError("racine NBT non compound")
|
||||
r.chaine()
|
||||
return r.charge(TAG_COMPOUND)
|
||||
|
||||
|
||||
def lire_level_dat(chemin):
|
||||
with gzip.open(chemin, "rb") as f:
|
||||
return lire_nbt(f.read())["Data"]
|
||||
|
||||
|
||||
def chunks_de_region(chemin):
|
||||
"""Itère (cx_local, cz_local, nbt) pour chaque chunk présent dans un fichier .mca."""
|
||||
with open(chemin, "rb") as f:
|
||||
data = f.read()
|
||||
if len(data) < 8192:
|
||||
return
|
||||
for i in range(1024):
|
||||
off = int.from_bytes(data[i * 4:i * 4 + 3], "big")
|
||||
nsec = data[i * 4 + 3]
|
||||
if off == 0 or nsec == 0:
|
||||
continue
|
||||
p = off * 4096
|
||||
if p + 5 > len(data):
|
||||
continue
|
||||
longueur = int.from_bytes(data[p:p + 4], "big")
|
||||
comp = data[p + 4]
|
||||
brut = data[p + 5:p + 4 + longueur]
|
||||
try:
|
||||
if comp == 2:
|
||||
nbt = lire_nbt(zlib.decompress(brut))
|
||||
elif comp == 1:
|
||||
nbt = lire_nbt(gzip.decompress(brut))
|
||||
elif comp == 3:
|
||||
nbt = lire_nbt(brut)
|
||||
else:
|
||||
continue # chunk externe (.mcc) ou compression inconnue : ignoré
|
||||
except Exception:
|
||||
continue
|
||||
yield i % 32, i // 32, nbt
|
||||
|
||||
|
||||
def deplier(longs, n_valeurs, bits):
|
||||
"""Décode un tableau compacté (format 1.16+ : les valeurs ne chevauchent pas deux longs)."""
|
||||
par_long = 64 // bits
|
||||
masque = np.uint64((1 << bits) - 1)
|
||||
a = np.asarray(longs, dtype=np.uint64)
|
||||
decal = (np.arange(par_long, dtype=np.uint64) * np.uint64(bits))
|
||||
vals = ((a[:, None] >> decal[None, :]) & masque).reshape(-1)
|
||||
return vals[:n_valeurs].astype(np.int64)
|
||||
|
||||
|
||||
def heightmap(longs, min_y):
|
||||
"""Heightmap 16x16 -> tableau [z, x] de hauteurs absolues (premier bloc libre au-dessus)."""
|
||||
if longs is None or len(longs) == 0:
|
||||
return None
|
||||
par_long = -(-256 // len(longs))
|
||||
bits = 64 // par_long
|
||||
return (deplier(longs, 256, bits) + min_y).reshape(16, 16)
|
||||
|
||||
|
||||
def bits_pour(n, minimum):
|
||||
b = max(1, (n - 1).bit_length())
|
||||
return max(minimum, b) if n > 1 else 0
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur