"""cubiomes.search — fast multi-process Minecraft seed searcher. This module provides both a Python API and a CLI for finding world seeds that satisfy a combination of biome, structure, and misc requirements. **Basic CLI quick-start**:: # Seeds with mushroom fields AND badlands within 4000 blocks python -m cubiomes.search --mc 1.21 \\ --biome mushroom_fields badlands --biome-radius 4000 --count 3 # Village AND Monument within 1500 blocks python -m cubiomes.search --mc 1.21 \\ --structure Village Monument --struct-radius 1500 --count 5 # Inspect one seed in detail python -m cubiomes.search --seed 123456789 --info **Advanced CLI**:: # Quad witch-hut base python -m cubiomes.search --mc 1.21 --quad Swamp_Hut --quad-dist 128 --count 3 # Village within 300 blocks AND spawn in plains AND first stronghold < 2000 blocks python -m cubiomes.search --mc 1.21 \\ --structure Village --struct-radius 300 \\ --spawn-biome plains --spawn-max-dist 1000 \\ --stronghold-radius 2000 # OR-semantics: any ocean biome within 500 blocks python -m cubiomes.search --mc 1.21 --any-biome warm_ocean lukewarm_ocean cold_ocean \\ --biome-radius 500 --count 5 # Two structures near each other (not just near origin) python -m cubiomes.search --mc 1.21 --proximity Village Monument 400 # At least 30% badlands in a 2-km area + badlands density check python -m cubiomes.search --mc 1.21 --biome-density badlands 0.30 --count 5 # At least 6 slime chunks in the 7×7 area around origin python -m cubiomes.search --mc 1.21 --min-slime-chunks 6 --count 10 **Library quick-start**:: from cubiomes.search import ( SearchCriteria, BiomeCondition, StructureCondition, SpawnCondition, StrongholdCondition, ProximityCondition, QuadStructureCondition, BiomeDensityCondition, SlimeDensityCondition, AnyOfBiomes, CustomCondition, SeedSearch, ) from cubiomes import MCVersion, BiomeID, StructureType criteria = SearchCriteria( mc=MCVersion.MC_1_21, biomes=[BiomeCondition(BiomeID.mushroom_fields, radius=2000)], conditions=[ SpawnCondition(max_distance=500), StrongholdCondition(count=1, max_distance=2000), ], ) for result in SeedSearch(criteria).run(seed_range=(0, 10_000_000), workers=4): print(result) """ from __future__ import annotations import argparse import json import math import multiprocessing import random import sys import time from dataclasses import dataclass, field, asdict from typing import Any, Callable, Iterator, List, Optional from .enums import MCVersion, Dimension, BiomeID, StructureType, LARGE_BIOMES from ._wrapper import ( Generator, setup_biome_filter, get_structure_config, get_structure_pos, is_viable_structure_pos, is_slime_chunk, biome_exists, iter_strongholds, init_first_stronghold, ) # ─── Basic condition types ──────────────────────────────────────────────────── @dataclass class BiomeCondition: """Require a specific biome within a radius of the origin. Args: biome_id (int): :class:`~cubiomes.BiomeID` to search for. radius (int): Search radius in biome coordinates (blocks ÷ 4). scale (int): Sampling scale — 4 (default) or 16 for a quick coarse check. """ biome_id: int radius: int = 1024 scale: int = 4 @dataclass class StructureCondition: """Require a structure to have a viable spawn within a block radius. Args: struct_type (int): :class:`~cubiomes.StructureType` constant. radius (int): Max block distance from the world origin. """ struct_type: int radius: int = 2048 # ─── Advanced condition types ───────────────────────────────────────────────── @dataclass class SpawnCondition: """Constrain world spawn location and/or biome. Args: max_distance (int | None): World spawn must be within this many blocks of (0, 0). ``None`` disables the distance check. biome_id (int | None): World spawn must be in this biome. fast (bool): Use ``estimate_spawn`` (default, fast) vs ``get_spawn`` (slow, exact). """ max_distance: Optional[int] = None biome_id: Optional[int] = None fast: bool = True @dataclass class StrongholdCondition: """Require the first N strongholds to be within a block radius. Args: count (int): Number of strongholds to check (checked in generation order). max_distance (int): Maximum block distance from origin for each. """ count: int = 1 max_distance: int = 5000 @dataclass class ProximityCondition: """Require two different structure types to be close to each other. Finds the nearest viable instance of each structure type within ``search_radius`` of the origin, then checks their mutual distance. Args: struct_a (int): First :class:`~cubiomes.StructureType`. struct_b (int): Second :class:`~cubiomes.StructureType`. max_dist (int): Maximum block distance between the two structures. search_radius (int): Block radius from origin to scan for each structure. """ struct_a: int struct_b: int max_dist: int = 1000 search_radius: int = 3000 @dataclass class QuadStructureCondition: """Require four viable instances of a structure in a 2×2 region grid (classic quad-farm base). All four positions must be viable (pass the biome check) and all fall within ``max_dist`` blocks of their common centroid. Args: struct_type (int): :class:`~cubiomes.StructureType` to find a quad of. max_dist (int): Max block distance from any position to the centroid. 128 blocks is the standard for witch-hut quad farms. max_regions (int): Search ±``max_regions`` regions from origin. """ struct_type: int max_dist: int = 128 max_regions: int = 4 @dataclass class BiomeDensityCondition: """Require that at least a given fraction of a rectangular area consists of a specific biome. Args: biome_id (int): Target :class:`~cubiomes.BiomeID`. min_fraction (float): Minimum coverage fraction in ``[0, 1]``. x, z (int): North-west corner of the area in biome coordinates. sx, sz (int): Width and depth of the area in biome coordinates. scale (int): Sampling scale (4 = default biome scale). """ biome_id: int min_fraction: float = 0.05 x: int = -256 z: int = -256 sx: int = 512 sz: int = 512 scale: int = 4 @dataclass class SlimeDensityCondition: """Require at least ``min_count`` slime chunks in a chunk-coordinate area. Args: min_count (int): Minimum number of slime chunks. cx, cz (int): Top-left corner of the search area in chunk coordinates. cw, ch (int): Width and height of the search area in chunks. """ min_count: int = 4 cx: int = -4 cz: int = -4 cw: int = 9 ch: int = 9 @dataclass class AnyOfBiomes: """Require that at least one biome from a list exists near the origin (OR semantics — contrasted with multiple :class:`BiomeCondition` entries which are AND). Args: biome_ids (list[int]): At least one of these biomes must be found. radius (int): Search radius in biome coordinates. scale (int): Sampling scale. """ biome_ids: list radius: int = 1024 scale: int = 4 @dataclass class CustomCondition: """Arbitrary Python callable used as a final filter. The function receives ``(seed: int, mc: int)`` and should return ``True`` / ``False``, or a ``dict`` of extra data on success. .. note:: ``CustomCondition`` is applied in the **main process** after all other conditions have been checked by workers. It does not benefit from ``--workers`` parallelism and should be reserved for lightweight final checks. Example:: def near_mansion(seed, mc): g = Generator(mc) g.apply_seed(Dimension.DIM_OVERWORLD, seed) cfg = get_structure_config(StructureType.Mansion, mc) for rx in range(-2, 3): for rz in range(-2, 3): pos = get_structure_pos(StructureType.Mansion, mc, seed, rx, rz) if pos and is_viable_structure_pos(StructureType.Mansion, g, *pos): d = pos[0]**2 + pos[1]**2 if d < 500**2: return {"mansion_at": pos} return False criteria = SearchCriteria( mc=MCVersion.MC_1_21, conditions=[CustomCondition(near_mansion)], ) """ func: Any # callable(seed: int, mc: int) -> bool | dict # ─── SearchCriteria ─────────────────────────────────────────────────────────── @dataclass class SearchCriteria: """Complete set of requirements a seed must satisfy. The ``biomes``, ``structures``, ``slime_chunk``, and ``spawn_biome`` fields are retained for backward compatibility. New code should prefer the ``conditions`` list which accepts any condition type. All conditions are evaluated with AND semantics — the seed must satisfy every single one. Args: mc (int): Minecraft version — a :class:`~cubiomes.MCVersion` value. dim (int): Dimension — a :class:`~cubiomes.Dimension` value. biomes: List of :class:`BiomeCondition` (all must be met). structures: List of :class:`StructureCondition` (all must be met). slime_chunk (tuple | None): ``(chunk_x, chunk_z)`` must be a slime chunk. spawn_biome (int | None): Quick spawn-biome check (deprecated, prefer ``conditions=[SpawnCondition(biome_id=...)]``). large_biomes (bool): Use the large-biomes world type. conditions (list): Advanced condition objects — accepts any of :class:`SpawnCondition`, :class:`StrongholdCondition`, :class:`ProximityCondition`, :class:`QuadStructureCondition`, :class:`BiomeDensityCondition`, :class:`SlimeDensityCondition`, :class:`AnyOfBiomes`, :class:`CustomCondition`. """ mc: int = MCVersion.MC_1_21 dim: int = Dimension.DIM_OVERWORLD # ── Legacy fields (still supported) ────────────────────────────────────── biomes: list = field(default_factory=list) structures: list = field(default_factory=list) slime_chunk: Optional[tuple] = None spawn_biome: Optional[int] = None large_biomes: bool = False # ── Advanced conditions ─────────────────────────────────────────────────── conditions: list = field(default_factory=list) # ─── SeedResult ─────────────────────────────────────────────────────────────── @dataclass class SeedResult: """Data returned for each seed that passes all criteria. Attributes: seed (int): The world seed. mc (int): MC version used. biome_positions (dict): ``{biome_name: (x, z)}`` in biome coordinates. structure_positions (dict): ``{struct_name: (x, z)}`` in block coords. spawn (tuple | None): World spawn ``(x, z)`` if checked. spawn_biome (int | None): Biome ID at spawn. strongholds (list): Stronghold positions if checked. quad (dict | None): Quad result — ``center``, ``positions``, ``name``. extra (dict): Extra data from advanced conditions and CustomCondition. """ seed: int mc: int biome_positions: dict = field(default_factory=dict) structure_positions: dict = field(default_factory=dict) spawn: Optional[tuple] = None spawn_biome: Optional[int] = None strongholds: list = field(default_factory=list) quad: Optional[dict] = None extra: dict = field(default_factory=dict) def as_dict(self) -> dict: """Return a JSON-serialisable representation.""" d = asdict(self) d["mc_name"] = _mc_name(self.mc) return d def __str__(self) -> str: lines = [f"seed={self.seed} ({_mc_name(self.mc)})"] if self.spawn: lines.append(f" spawn: {self.spawn}") if self.spawn_biome is not None: lines.append(f" spawn biome: {_biome_name(self.spawn_biome)}") for name, pos in self.biome_positions.items(): lines.append(f" biome {name:<28s} biome-coords {pos}") for name, pos in self.structure_positions.items(): lines.append(f" struct {name:<28s} block-coords {pos}") if self.quad: lines.append( f" quad {self.quad['name']:<28s} center {self.quad['center']} " f"positions {self.quad['positions']}" ) for i, sh in enumerate(self.strongholds): lines.append(f" stronghold {i}: {sh}") for k, v in self.extra.items(): lines.append(f" {k}: {v}") return "\n".join(lines) # ─── Condition serialisation (for worker pickling) ──────────────────────────── _PICKLABLE_TYPES = { "BiomeCondition", "StructureCondition", "SpawnCondition", "StrongholdCondition", "ProximityCondition", "QuadStructureCondition", "BiomeDensityCondition", "SlimeDensityCondition", "AnyOfBiomes", } def _serialize_cond(c) -> Optional[dict]: """Return a picklable dict for a condition, or None if not picklable.""" tname = type(c).__name__ if tname not in _PICKLABLE_TYPES: return None d = {k: (list(v) if isinstance(v, (list, tuple)) else v) for k, v in c.__dict__.items()} d["_type"] = tname return d def _collect_conditions(criteria: SearchCriteria): """Return (native_dicts, custom_conditions) from a SearchCriteria.""" native, custom = [], [] # Legacy fields for bc in criteria.biomes: native.append(_serialize_cond(bc)) for sc in criteria.structures: native.append(_serialize_cond(sc)) if criteria.slime_chunk is not None: native.append({"_type": "_SlimeChunk", "chunk_x": criteria.slime_chunk[0], "chunk_z": criteria.slime_chunk[1]}) if criteria.spawn_biome is not None: native.append({"_type": "SpawnCondition", "max_distance": None, "biome_id": criteria.spawn_biome, "fast": True}) # Advanced conditions list for cond in criteria.conditions: if isinstance(cond, CustomCondition): custom.append(cond) else: d = _serialize_cond(cond) if d is not None: native.append(d) return native, custom # ─── Worker function ────────────────────────────────────────────────────────── def _worker_check_batch(args: tuple) -> list: """Worker: check a batch of seeds; return result dicts for matches.""" seeds_batch, job = args mc = job["mc"] dim = job["dim"] flags = LARGE_BIOMES if job.get("large_biomes") else 0 conds = job["conditions"] extra_opts = job["extra_opts"] results = [] for seed in seeds_batch: r = _check_one_seed(seed, mc, dim, flags, conds, extra_opts) if r is not None: results.append(r) return results def _check_one_seed(seed, mc, dim, flags, cond_list, extra_opts): """Return a result dict if seed satisfies all conditions, else None.""" g = Generator(mc, flags) g.apply_seed(dim, seed) biome_positions = {} struct_positions = {} spawn_info = {} strongholds_list = [] quad_info = None extra = {} for cond in cond_list: t = cond["_type"] if t == "_SlimeChunk": if not is_slime_chunk(seed, cond["chunk_x"], cond["chunk_z"]): return None elif t == "BiomeCondition": pos = _find_biome(g, cond["biome_id"], cond["radius"], cond["scale"]) if pos is None: return None biome_positions[_biome_name(cond["biome_id"])] = pos elif t == "StructureCondition": pos = _find_structure(g, cond["struct_type"], mc, seed, cond["radius"]) if pos is None: return None struct_positions[_struct_name(cond["struct_type"])] = pos elif t == "SpawnCondition": info = _check_spawn_cond(g, seed, mc, dim, cond) if info is None: return None spawn_info.update(info) elif t == "StrongholdCondition": sh_list = _check_stronghold_cond(g, seed, mc, cond) if sh_list is None: return None strongholds_list.extend(sh_list) elif t == "ProximityCondition": pos_pair = _check_proximity_cond(g, seed, mc, cond) if pos_pair is None: return None struct_positions.update(pos_pair) elif t == "QuadStructureCondition": qr = _check_quad_cond(g, seed, mc, cond) if qr is None: return None quad_info = qr # also record individual positions sname = _struct_name(cond["struct_type"]) for i, p in enumerate(qr["positions"]): struct_positions[f"{sname}_quad_{i}"] = p elif t == "BiomeDensityCondition": bdc = _check_density_cond(g, cond) if bdc is None: return None extra[f"density_{_biome_name(cond['biome_id'])}"] = bdc elif t == "SlimeDensityCondition": sdc = _check_slime_density(seed, cond) if sdc is None: return None extra["slime_chunk_count"] = sdc elif t == "AnyOfBiomes": result = _check_any_biomes(g, cond) if result is None: return None biome_positions[f"any_of({_biome_name(result[0])})"] = result[1] else: pass # unknown / non-picklable types are skipped in workers # ── Optional extras requested by CLI ──────────────────────────────────── show_spawn = extra_opts.get("show_spawn", False) show_strongholds = extra_opts.get("show_strongholds", 0) if show_spawn and not spawn_info: sp = g.estimate_spawn() sb = g.get_biome_at(sp[0] >> 2, 0, sp[1] >> 2, scale=4) spawn_info = {"spawn": sp, "spawn_biome": sb} if show_strongholds > 0 and not strongholds_list: for i, pos in enumerate(iter_strongholds(g, seed)): strongholds_list.append(pos) if i + 1 >= show_strongholds: break return { "seed": seed, "mc": mc, "biome_positions": biome_positions, "structure_positions": struct_positions, "spawn": spawn_info.get("spawn"), "spawn_biome": spawn_info.get("spawn_biome"), "strongholds": strongholds_list, "quad": quad_info, "extra": extra, } # ─── Per-condition check helpers ────────────────────────────────────────────── def _find_biome(g: Generator, biome_id: int, radius: int, scale: int) -> Optional[tuple]: """Return a (x, z) biome-coordinate position where biome_id exists, or None. Uses a deterministic C-level scan rather than a random walk.""" # get_biome_centers scans at scale=4; radius is in biome coordinates. # For coarser scale hints (scale=16) we still search at scale=4 for accuracy. centers = g.get_biome_centers( x=-radius, z=-radius, sx=radius * 2, sz=radius * 2, match=biome_id, min_size=1, tolerance=4, max_results=1, ) return centers[0] if centers else None def _find_structure(g: Generator, struct_type: int, mc: int, seed: int, radius_blocks: int) -> Optional[tuple]: cfg = get_structure_config(struct_type, mc) if cfg is None or cfg["dim"] != g.dim: return None region_blocks = cfg["region_size"] * 16 max_reg = math.ceil(radius_blocks / region_blocks) + 1 best, best_d2 = None, float("inf") for rx in range(-max_reg, max_reg + 1): for rz in range(-max_reg, max_reg + 1): pos = get_structure_pos(struct_type, mc, seed, rx, rz) if pos is None: continue x, z = pos if abs(x) > radius_blocks or abs(z) > radius_blocks: continue d2 = x * x + z * z if d2 < best_d2 and is_viable_structure_pos(struct_type, g, x, z): best, best_d2 = pos, d2 return best def _check_spawn_cond(g, seed, mc, dim, cond) -> Optional[dict]: sp = g.estimate_spawn() if cond["fast"] else g.get_spawn() sb = g.get_biome_at(sp[0] >> 2, 0, sp[1] >> 2, scale=4) if cond.get("max_distance") is not None: if math.sqrt(sp[0] ** 2 + sp[1] ** 2) > cond["max_distance"]: return None if cond.get("biome_id") is not None and sb != cond["biome_id"]: return None return {"spawn": sp, "spawn_biome": sb} def _check_stronghold_cond(g, seed, mc, cond) -> Optional[list]: count = cond["count"] max_dist = cond["max_distance"] result = [] for i, pos in enumerate(iter_strongholds(g, seed)): d = math.sqrt(pos[0] ** 2 + pos[1] ** 2) if d > max_dist: return None result.append(pos) if i + 1 >= count: break if len(result) < count: return None return result def _check_proximity_cond(g, seed, mc, cond) -> Optional[dict]: radius = cond["search_radius"] pos_a = _find_structure(g, cond["struct_a"], mc, seed, radius) pos_b = _find_structure(g, cond["struct_b"], mc, seed, radius) if pos_a is None or pos_b is None: return None dx = pos_a[0] - pos_b[0] dz = pos_a[1] - pos_b[1] if math.sqrt(dx * dx + dz * dz) > cond["max_dist"]: return None na = _struct_name(cond["struct_a"]) nb = _struct_name(cond["struct_b"]) return {na: pos_a, nb: pos_b} def _check_quad_cond(g, seed, mc, cond) -> Optional[dict]: struct_type = cond["struct_type"] max_dist = cond["max_dist"] max_reg = cond["max_regions"] cfg = get_structure_config(struct_type, mc) if cfg is None or cfg["dim"] != g.dim: return None for rx in range(-max_reg, max_reg): for rz in range(-max_reg, max_reg): positions = [] ok = True for dx in range(2): for dz in range(2): pos = get_structure_pos(struct_type, mc, seed, rx + dx, rz + dz) if pos is None or not is_viable_structure_pos( struct_type, g, pos[0], pos[1]): ok = False break positions.append(pos) if not ok: break if not ok or len(positions) != 4: continue # Centroid cx = sum(p[0] for p in positions) / 4.0 cz = sum(p[1] for p in positions) / 4.0 dists = [math.sqrt((p[0] - cx) ** 2 + (p[1] - cz) ** 2) for p in positions] if max(dists) <= max_dist: return { "name": _struct_name(struct_type), "center": (int(cx), int(cz)), "positions": positions, "max_r": round(max(dists), 1), } return None def _check_density_cond(g: Generator, cond: dict) -> Optional[float]: biome_ids = g.gen_biomes( cond["x"], cond["z"], cond["sx"], cond["sz"], scale=cond["scale"], ) target = cond["biome_id"] total = len(biome_ids) count = sum(1 for b in biome_ids if b == target) frac = count / total if total else 0.0 if frac < cond["min_fraction"]: return None return round(frac, 4) def _check_slime_density(seed: int, cond: dict) -> Optional[int]: cx, cz = cond["cx"], cond["cz"] cw, ch = cond["cw"], cond["ch"] count = sum( 1 for ix in range(cw) for iz in range(ch) if is_slime_chunk(seed, cx + ix, cz + iz) ) if count < cond["min_count"]: return None return count def _check_any_biomes(g: Generator, cond: dict) -> Optional[tuple]: """Return (biome_id, pos) for the first matching biome, or None.""" for bid in cond["biome_ids"]: pos = _find_biome(g, int(bid), cond["radius"], cond["scale"]) if pos is not None: return (int(bid), pos) return None # ─── SeedSearch ─────────────────────────────────────────────────────────────── class SeedSearch: """Multi-process seed searcher supporting all condition types. Args: criteria (SearchCriteria): Requirements every returned seed must meet. Example:: from cubiomes.search import ( SearchCriteria, BiomeCondition, QuadStructureCondition, SeedSearch, ) from cubiomes import MCVersion, BiomeID, StructureType criteria = SearchCriteria( mc=MCVersion.MC_1_21, biomes=[BiomeCondition(BiomeID.mushroom_fields, radius=2000)], conditions=[ QuadStructureCondition(StructureType.Swamp_Hut, max_dist=128), ], ) for result in SeedSearch(criteria).run(seed_range=(0, 100_000_000), count=3, workers=4): print(result) """ def __init__(self, criteria: SearchCriteria): self.criteria = criteria # ── Single seed ─────────────────────────────────────────────────────────── def check_seed(self, seed: int, show_spawn: bool = False, show_strongholds: int = 0) -> Optional[SeedResult]: """Check one seed against all criteria. Args: seed (int): World seed to evaluate. show_spawn (bool): Include estimated spawn in result. show_strongholds (int): Include first N stronghold positions. Returns: SeedResult | None """ c = self.criteria flags = LARGE_BIOMES if c.large_biomes else 0 native_conds, custom_conds = _collect_conditions(c) r = _check_one_seed( seed, c.mc, c.dim, flags, native_conds, {"show_spawn": show_spawn, "show_strongholds": show_strongholds}, ) if r is None: return None result = _dict_to_result(r) # Apply custom conditions for cc in custom_conds: ret = cc.func(seed, c.mc) if not ret: return None if isinstance(ret, dict): result.extra.update(ret) return result # ── Multi-seed search ───────────────────────────────────────────────────── def run( self, seed_range: Optional[tuple] = None, seeds: Optional[Iterator[int]] = None, count: int = 1, workers: int = 1, batch_size: int = 4096, show_spawn: bool = False, show_strongholds: int = 0, progress_cb=None, ) -> Iterator[SeedResult]: """Search over seeds and yield matches. Provide *either* ``seed_range`` or ``seeds``. If neither is given, seeds are drawn from the full 64-bit space at random. Args: seed_range (tuple | None): ``(start, stop)`` inclusive range. seeds (iterator | None): Arbitrary seed iterator. count (int): Stop after finding this many (0 = unlimited). workers (int): Parallel worker processes. batch_size (int): Seeds per worker batch. show_spawn (bool): Include spawn in results. show_strongholds (int): Include this many stronghold positions. progress_cb: Optional ``(checked, found, rate)`` callback. Yields: SeedResult """ c = self.criteria flags = LARGE_BIOMES if c.large_biomes else 0 native_conds, custom_conds = _collect_conditions(c) job = { "mc": c.mc, "dim": c.dim, "large_biomes": c.large_biomes, "conditions": native_conds, "extra_opts": {"show_spawn": show_spawn, "show_strongholds": show_strongholds}, } seed_iter = _make_seed_iter(seed_range, seeds) found = 0 checked = 0 t0 = time.monotonic() def _postfilter(r_dict) -> Optional[SeedResult]: result = _dict_to_result(r_dict) for cc in custom_conds: ret = cc.func(result.seed, c.mc) if not ret: return None if isinstance(ret, dict): result.extra.update(ret) return result if workers <= 1: for batch in _batched(seed_iter, batch_size): for r in _worker_check_batch((batch, job)): result = _postfilter(r) if result is not None: yield result found += 1 if count and found >= count: return checked += len(batch) if progress_cb: dt = time.monotonic() - t0 or 1e-9 progress_cb(checked, found, checked / dt) else: ctx = multiprocessing.get_context("spawn") with ctx.Pool(workers) as pool: batch_args = ( (batch, job) for batch in _batched(seed_iter, batch_size) ) for rs in pool.imap_unordered( _worker_check_batch, batch_args, chunksize=1 ): checked += batch_size for r in rs: result = _postfilter(r) if result is not None: yield result found += 1 if count and found >= count: pool.terminate() return if progress_cb: dt = time.monotonic() - t0 or 1e-9 progress_cb(checked, found, checked / dt) # ─── Helpers ────────────────────────────────────────────────────────────────── def _make_seed_iter(seed_range, seeds): if seeds is not None: return seeds if seed_range is not None: start, stop = seed_range return iter(range(start, stop + 1)) return _random_seeds() def _random_seeds(): while True: yield random.randint(-(2 ** 63), 2 ** 63 - 1) def _batched(it, n): batch = [] for item in it: batch.append(item) if len(batch) >= n: yield batch batch = [] if batch: yield batch def _dict_to_result(d: dict) -> SeedResult: return SeedResult( seed=d["seed"], mc=d["mc"], biome_positions=d["biome_positions"], structure_positions=d["structure_positions"], spawn=tuple(d["spawn"]) if d.get("spawn") else None, spawn_biome=d.get("spawn_biome"), strongholds=[tuple(sh) for sh in d.get("strongholds", [])], quad=d.get("quad"), extra=d.get("extra", {}), ) def _mc_name(mc: int) -> str: try: name = MCVersion(mc).name # "MC_1_21_11" return name.removeprefix("MC_").replace("_", ".") except ValueError: return str(mc) def _biome_name(bid: int) -> str: try: return BiomeID(bid).name except ValueError: return str(bid) def _struct_name(stype: int) -> str: try: return StructureType(stype).name except ValueError: return str(stype) # ─── CLI ────────────────────────────────────────────────────────────────────── def _build_parser() -> argparse.ArgumentParser: p = argparse.ArgumentParser( prog="python -m cubiomes.search", description=( "Search Minecraft world seeds.\n\n" "Examples:\n" " %(prog)s --mc 1.21 --biome mushroom_fields --count 5\n" " %(prog)s --mc 1.21 --quad Swamp_Hut --quad-dist 128 --count 3\n" " %(prog)s --mc 1.21 --proximity Village Monument 400 --count 5\n" " %(prog)s --seed 123456789 --info" ), formatter_class=argparse.RawDescriptionHelpFormatter, ) # ── Seed source ──────────────────────────────────────────────────────── sg = p.add_argument_group("Seed source (mutually exclusive)") mx = sg.add_mutually_exclusive_group() mx.add_argument("--seed", type=_parse_seed, metavar="N", help="Check a specific seed.") mx.add_argument("--seeds", type=_parse_range, metavar="START:STOP", help="Inclusive range, e.g. '0:10000000'.") mx.add_argument("--random-seeds", action="store_true", help="Random 64-bit seeds (default).") # ── Version ──────────────────────────────────────────────────────────── p.add_argument("--mc", default="1.21", metavar="VERSION", help="MC version, e.g. '1.21', '1.18', 'b1.7' (default: 1.21).") p.add_argument("--large-biomes", action="store_true", help="Use Large Biomes world type.") # ── Basic biome conditions ───────────────────────────────────────────── bg = p.add_argument_group("Basic biome conditions") bg.add_argument("--biome", nargs="+", dest="biomes", metavar="NAME", help="Biomes that ALL must exist near origin (AND).") bg.add_argument("--biome-radius", type=int, default=1024, metavar="R", help="Search radius in biome coords (≈R×4 blocks). Default: 1024.") bg.add_argument("--any-biome", nargs="+", dest="any_biomes", metavar="NAME", help="At least ONE of these biomes must exist (OR).") # ── Basic structure conditions ───────────────────────────────────────── stg = p.add_argument_group("Basic structure conditions") stg.add_argument("--structure", nargs="+", dest="structures", metavar="NAME", help="Structures that ALL must be viable near origin (AND).") stg.add_argument("--struct-radius", type=int, default=2048, metavar="R", help="Max block distance from origin per structure. Default: 2048.") # ── Advanced conditions ──────────────────────────────────────────────── adv = p.add_argument_group("Advanced conditions") adv.add_argument( "--spawn-biome", metavar="NAME", help="World spawn must be in this biome.", ) adv.add_argument( "--spawn-max-dist", type=int, metavar="D", help="World spawn must be within D blocks of (0, 0).", ) adv.add_argument( "--stronghold-radius", type=int, metavar="R", help="First stronghold must be within R blocks of origin.", ) adv.add_argument( "--stronghold-count", type=int, default=1, metavar="N", help="All first N strongholds must satisfy --stronghold-radius (default: 1).", ) adv.add_argument( "--proximity", nargs=3, action="append", metavar=("STRUCT_A", "STRUCT_B", "DIST"), help=( "STRUCT_A and STRUCT_B must be within DIST blocks of each other " "(repeatable). E.g. --proximity Village Monument 400" ), ) adv.add_argument( "--quad", metavar="STRUCT", help="Find a quad-structure base (4 viable instances in a 2×2 region grid).", ) adv.add_argument( "--quad-dist", type=int, default=128, metavar="R", help="Max block distance from quad centroid to each structure (default: 128).", ) adv.add_argument( "--quad-max-regions", type=int, default=4, metavar="N", help="Search ±N regions from origin for quad base (default: 4).", ) adv.add_argument( "--biome-density", nargs=2, metavar=("BIOME", "FRACTION"), help=( "At least FRACTION (0–1) of the search area must be BIOME. " "Area is controlled by --biome-density-area." ), ) adv.add_argument( "--biome-density-area", nargs=4, type=int, metavar=("X", "Z", "SX", "SZ"), default=[-256, -256, 512, 512], help="Biome-coordinate area for --biome-density (default: -256 -256 512 512).", ) adv.add_argument( "--min-slime-chunks", type=int, metavar="N", help="Minimum slime chunks in a 9×9 area centred on chunk origin.", ) adv.add_argument( "--slime-area", nargs=4, type=int, metavar=("CX", "CZ", "CW", "CH"), default=[-4, -4, 9, 9], help="Chunk area for --min-slime-chunks (default: -4 -4 9 9).", ) adv.add_argument( "--slime-chunk", nargs=2, type=int, metavar=("CX", "CZ"), help="Specific chunk (CX, CZ) must be a slime chunk.", ) # ── Output ──────────────────────────────────────────────────────────── out = p.add_argument_group("Output") out.add_argument("--count", type=int, default=1, metavar="N", help="Stop after N results (0 = unlimited). Default: 1.") out.add_argument("--format", choices=["text", "json", "csv"], default="text", help="Output format (default: text).") out.add_argument("--info", action="store_true", help="For --seed: show detailed info.") out.add_argument("--show-spawn", action="store_true", help="Include estimated spawn in results.") out.add_argument("--show-strongholds", type=int, default=0, metavar="N", help="Include first N stronghold positions.") # ── Performance ─────────────────────────────────────────────────────── perf = p.add_argument_group("Performance") perf.add_argument("--workers", type=int, default=1, metavar="N", help="Parallel worker processes (default: 1).") perf.add_argument("--batch-size", type=int, default=4096, metavar="N", help="Seeds per batch (default: 4096).") perf.add_argument("--no-progress", action="store_true", help="Suppress progress counter.") return p def _parse_seed(s: str) -> int: s = s.strip() return int(s, 16) if s.startswith(("0x", "0X")) else int(s) def _parse_range(s: str) -> tuple: parts = s.split(":") if len(parts) != 2: raise argparse.ArgumentTypeError(f"Expected START:STOP, got {s!r}") return (int(parts[0]), int(parts[1])) def _resolve_mc(version_str: str) -> int: v = version_str.strip().lower().replace(".", "_") aliases = {"b1_7": MCVersion.MC_B1_7, "b1_8": MCVersion.MC_B1_8, "newest": MCVersion.MC_NEWEST} if v in aliases: return int(aliases[v]) candidate = "MC_" + v.upper() if hasattr(MCVersion, candidate): return int(getattr(MCVersion, candidate)) raise argparse.ArgumentTypeError( f"Unknown MC version: {version_str!r}. Try '1.21', '1.18', 'b1.7'." ) def _resolve_biome(name: str) -> int: if name.lstrip("-").isdigit(): return int(name) try: return int(BiomeID[name]) except KeyError: raise argparse.ArgumentTypeError( f"Unknown biome: {name!r}. Use a BiomeID name, e.g. 'mushroom_fields'." ) def _resolve_structure(name: str) -> int: if name.lstrip("-").isdigit(): return int(name) try: return int(StructureType[name]) except KeyError: raise argparse.ArgumentTypeError( f"Unknown structure: {name!r}. Use a StructureType name, e.g. 'Village'." ) class _Progress: def __init__(self, enabled: bool = True): self._on = enabled and sys.stderr.isatty() self._t0 = time.monotonic() self._last = 0.0 def update(self, checked, found, rate): if not self._on: return now = time.monotonic() if now - self._last < 0.25: return self._last = now elapsed = now - self._t0 print( f"\r checked {checked:>12,} | found {found:>5} |" f" {rate:>9,.0f} seeds/s | {elapsed:>6.1f}s ", end="", file=sys.stderr, flush=True, ) def done(self, checked, found): if self._on: elapsed = time.monotonic() - self._t0 or 1e-9 print( f"\r checked {checked:>12,} | found {found:>5} |" f" {checked/elapsed:>9,.0f} seeds/s | {elapsed:>6.1f}s \n", file=sys.stderr, flush=True, ) def _print_seed_info(seed: int, mc: int): g = Generator(mc) g.apply_seed(Dimension.DIM_OVERWORLD, seed) print(f"Seed: {seed} ({_mc_name(mc)})") print(f"Shadow: {-(7379792620528906219 + seed) & 0xFFFFFFFFFFFFFFFF}") sp = g.estimate_spawn() sb = g.get_biome_at(sp[0] >> 2, 0, sp[1] >> 2, scale=4) print(f"Spawn: {sp} biome={_biome_name(sb)}") print("\nFirst 5 strongholds:") for i, pos in enumerate(iter_strongholds(g, seed)): d = math.sqrt(pos[0] ** 2 + pos[1] ** 2) print(f" [{i}] {pos} ({d:.0f} blocks)") if i >= 4: break print("\nBiomes at scale 4 (sample points):") for x, z in [(0,0),(256,0),(0,256),(-256,0),(0,-256),(512,512),(-512,-512)]: b = g.get_biome_at(x, 0, z, scale=4) print(f" ({x:6d},{z:6d}) {_biome_name(b)}") print("\nCommon structures near origin:") for stype in [StructureType.Village, StructureType.Monument, StructureType.Mansion, StructureType.Desert_Pyramid, StructureType.Igloo, StructureType.Outpost, StructureType.Ancient_City, StructureType.Trial_Chambers, StructureType.Treasure]: cfg = get_structure_config(stype, mc) if cfg is None or cfg["dim"] != Dimension.DIM_OVERWORLD: continue region_blocks = cfg["region_size"] * 16 best, best_d2 = None, float("inf") for rx in range(-3, 4): for rz in range(-3, 4): pos = get_structure_pos(stype, mc, seed, rx, rz) if pos is None: continue d2 = pos[0] ** 2 + pos[1] ** 2 if d2 < best_d2 and is_viable_structure_pos(stype, g, pos[0], pos[1]): best, best_d2 = pos, d2 if best: print(f" {_struct_name(stype):<20s} {best} ({math.sqrt(best_d2):.0f} blocks)") slimes = [(cx, cz) for cx in range(-4, 5) for cz in range(-4, 5) if is_slime_chunk(seed, cx, cz)] print(f"\nSlime chunks (9×9 area): {len(slimes)} found") if slimes: print(" " + " ".join(str(s) for s in slimes[:10])) def _format_csv_header(): return "seed,mc,biomes,structures,spawn_x,spawn_z,spawn_biome,quad_center,extra" def _format_csv_row(r: SeedResult) -> str: biomes = "|".join(f"{k}@{v[0]},{v[1]}" for k, v in r.biome_positions.items()) structs = "|".join(f"{k}@{v[0]},{v[1]}" for k, v in r.structure_positions.items()) sx = r.spawn[0] if r.spawn else "" sz = r.spawn[1] if r.spawn else "" sb = _biome_name(r.spawn_biome) if r.spawn_biome is not None else "" qc = f"{r.quad['center'][0]},{r.quad['center'][1]}" if r.quad else "" ex = "|".join(f"{k}={v}" for k, v in r.extra.items()) return f"{r.seed},{_mc_name(r.mc)},{biomes},{structs},{sx},{sz},{sb},{qc},{ex}" def main(argv=None): """CLI entry point — also callable from Python with a list of args.""" parser = _build_parser() args = parser.parse_args(argv) try: mc = _resolve_mc(args.mc) except argparse.ArgumentTypeError as e: parser.error(str(e)) if args.seed is not None and args.info: _print_seed_info(args.seed, mc) return 0 # ── Build conditions ─────────────────────────────────────────────────── biome_conds = [] if args.biomes: for name in args.biomes: try: biome_conds.append( BiomeCondition(_resolve_biome(name), radius=args.biome_radius) ) except argparse.ArgumentTypeError as e: parser.error(str(e)) struct_conds = [] if args.structures: for name in args.structures: try: struct_conds.append( StructureCondition(_resolve_structure(name), radius=args.struct_radius) ) except argparse.ArgumentTypeError as e: parser.error(str(e)) slime_ck = tuple(args.slime_chunk) if args.slime_chunk else None # Advanced conditions adv_conds = [] # any_biome (OR semantics) if args.any_biomes: try: bids = [_resolve_biome(n) for n in args.any_biomes] except argparse.ArgumentTypeError as e: parser.error(str(e)) adv_conds.append(AnyOfBiomes(bids, radius=args.biome_radius)) # spawn if args.spawn_biome or args.spawn_max_dist: sb_id = None if args.spawn_biome: try: sb_id = _resolve_biome(args.spawn_biome) except argparse.ArgumentTypeError as e: parser.error(str(e)) adv_conds.append(SpawnCondition( max_distance=args.spawn_max_dist, biome_id=sb_id, )) # stronghold if args.stronghold_radius: adv_conds.append(StrongholdCondition( count=args.stronghold_count, max_distance=args.stronghold_radius, )) # proximity if args.proximity: for sa, sb, dist in args.proximity: try: adv_conds.append(ProximityCondition( struct_a=_resolve_structure(sa), struct_b=_resolve_structure(sb), max_dist=int(dist), search_radius=max(args.struct_radius, int(dist) * 2), )) except (argparse.ArgumentTypeError, ValueError) as e: parser.error(str(e)) # quad if args.quad: try: stype = _resolve_structure(args.quad) except argparse.ArgumentTypeError as e: parser.error(str(e)) adv_conds.append(QuadStructureCondition( struct_type=stype, max_dist=args.quad_dist, max_regions=args.quad_max_regions, )) # biome density if args.biome_density: bname, frac_str = args.biome_density try: bid = _resolve_biome(bname) frac = float(frac_str) except (argparse.ArgumentTypeError, ValueError) as e: parser.error(str(e)) bx, bz, bsx, bsz = args.biome_density_area adv_conds.append(BiomeDensityCondition( biome_id=bid, min_fraction=frac, x=bx, z=bz, sx=bsx, sz=bsz, )) # slime density if args.min_slime_chunks: cx, cz, cw, ch = args.slime_area adv_conds.append(SlimeDensityCondition( min_count=args.min_slime_chunks, cx=cx, cz=cz, cw=cw, ch=ch, )) criteria = SearchCriteria( mc=mc, biomes=biome_conds, structures=struct_conds, slime_chunk=slime_ck, large_biomes=args.large_biomes, conditions=adv_conds, ) # ── Single seed ──────────────────────────────────────────────────────── if args.seed is not None: result = SeedSearch(criteria).check_seed( args.seed, show_spawn=args.show_spawn, show_strongholds=args.show_strongholds, ) if result is None: print(f"Seed {args.seed} does NOT match criteria.", file=sys.stderr) return 1 _emit(result, args.format, first=True) return 0 # ── Range / random search ────────────────────────────────────────────── seed_range = args.seeds search = SeedSearch(criteria) progress = _Progress(enabled=not args.no_progress and args.format == "text") checked = [0] found_cnt = [0] def _on_progress(c, f, rate): checked[0] = c found_cnt[0] = f progress.update(c, f, rate) first = True if args.format == "csv": print(_format_csv_header()) if args.format == "json": sys.stdout.write("[") try: for result in search.run( seed_range=seed_range, count=args.count, workers=args.workers, batch_size=args.batch_size, show_spawn=args.show_spawn, show_strongholds=args.show_strongholds, progress_cb=_on_progress, ): _emit(result, args.format, first=first) first = False except KeyboardInterrupt: pass finally: if args.format == "json": sys.stdout.write("\n]\n") progress.done(checked[0], found_cnt[0]) return 0 def _emit(result: SeedResult, fmt: str, first: bool = True): if fmt == "text": print(result) print() elif fmt == "json": if not first: sys.stdout.write(",\n") sys.stdout.write(json.dumps(result.as_dict(), indent=2)) sys.stdout.flush() elif fmt == "csv": print(_format_csv_row(result)) if __name__ == "__main__": sys.exit(main())