diff --git a/app.py b/app.py index 388b030..97177ac 100644 --- a/app.py +++ b/app.py @@ -213,6 +213,187 @@ def bossing_delete_drop(identifier): return jsonify(_bossing()) +# Quanah: the seasonal event-equipment set solver. One global list, no character. +QUANAH_QUEUE = "quanah" + + +@app.get("/api/quanah") +def quanah(): + from quanah import store + + return jsonify(store.payload()) + + +@app.put("/api/quanah/settings") +def quanah_settings(): + from quanah import store + + body = request.get_json(silent=True) or {} + store.configure(class_key=body.get("class"), build=body.get("build")) + return jsonify(store.payload()) + + +@app.post("/api/quanah/items") +def quanah_add_item(): + from quanah import store + + body = request.get_json(silent=True) or {} + store.add_item(body.get("slot"), body.get("lines")) + return jsonify(store.payload()) + + +@app.put("/api/quanah/items/") +def quanah_update_item(identifier): + from quanah import store + + body = request.get_json(silent=True) or {} + store.update_item(identifier, body.get("slot"), body.get("lines")) + return jsonify(store.payload()) + + +@app.delete("/api/quanah/items/") +def quanah_delete_item(identifier): + from quanah import store + + store.delete_item(identifier) + return jsonify(store.payload()) + + +@app.delete("/api/quanah/items") +def quanah_clear_items(): + from quanah import store + + store.clear_items() + return jsonify(store.payload()) + + +@app.post("/api/quanah/scan") +def quanah_scan(): + """Watch the game and capture every event item hovered, until /api/scan/cancel.""" + global generation, preview, job + import hover_queue + import ocr_worker + from quanah import store + + body = request.get_json(silent=True) or {} + if not store.read()["class"]: + raise ValueError("Choose your class first") + if not isinstance(body.get("window"), int) or isinstance(body.get("window"), bool): + raise ValueError("Choose the game window") + with job_lock: + if job.get("active"): + raise ValueError("A capture is already running") + generation += 1 + token = generation + preview = None + hover_queue.reset(QUANAH_QUEUE) + job = {"active": True, "status": "watching", "mode": "quanah", "captured": 0, + "message": "Hover an event item in your inventory or Equipment."} + scan_executor.submit(_quanah_perform, {"mode": "quanah", "window": body["window"]}, token) + state = dict(job) + ocr_worker.warm() + return jsonify(state) + + +def _quanah_perform(body, token): + global job + import scan_worker + + try: + with scan_worker.session(): + _quanah_watch(body, token) + except Exception as exc: + with job_lock: + if token == generation and job.get("active"): + job = {"active": False, "status": "error", "message": str(exc)} + raise + + +QUANAH_FAILED = Path("logs/quanah-failed") + + +def _keep_failed_capture(frame): + """Save a capture that could not be read, keeping the 20 newest, so it can be diagnosed.""" + from utils.image_files import encode_png + + QUANAH_FAILED.mkdir(parents=True, exist_ok=True) + path = QUANAH_FAILED / f"{time.strftime('%Y%m%d-%H%M%S')}-{time.time_ns() % 1_000_000_000:09d}.png" + path.write_bytes(encode_png(frame)) + for old in sorted(QUANAH_FAILED.glob("*.png"))[:-20]: + old.unlink(missing_ok=True) + return path + + +def _save_quanah_piece(frame, anchor): + from ocr_worker import read + from quanah import store + from quanah.lines import SKIPPED + + try: + piece = read(frame, "quanah:%d:%d" % anchor) + except Exception as exc: + # Another item (a shoulder, a medal) is expected, not a failure worth keeping. + if not str(exc).startswith(SKIPPED): + try: + _keep_failed_capture(frame) + except Exception: + pass # The reading failed either way; only the copy for diagnosis is lost. + raise + store.add_item(piece["slot"], piece["lines"], raw=piece["raw"], name=piece["name"], + item_class=piece["item_class"], source="scan") + + +def _quanah_watch(body, token): + global job + import hover_queue + import scan_worker + + previous, captured = None, 0 + + def update(message): + global job + with job_lock: + if token != generation: + return False + job = {"active": True, "status": "watching", "mode": "quanah", "captured": captured, "message": message} + return True + + while True: + with job_lock: + if token != generation: + return + try: + frame, mark, anchor = scan_worker.call("quanah_step", body, previous) + except (ImportError, AttributeError, TypeError) as exc: + with job_lock: + if token == generation: + job = {"active": False, "status": "error", "fatal": True, "message": str(exc)} + return + except Exception as exc: + if not update(str(exc)): + return + time.sleep(0.12) + continue + if frame is None: + # Nothing hovered: the same item may be captured again next time. + previous = None + if not update("Captured " + str(captured) + ". Hover the next item." if captured + else "Hover an event item in your inventory or Equipment."): + return + time.sleep(0.12) + continue + previous = mark + captured += 1 + with job_lock: + if token != generation: + return + hover_queue.submit_task(QUANAH_QUEUE, f"piece-{token}-{captured}", + lambda frame=frame, anchor=anchor: _save_quanah_piece(frame, anchor)) + if not update(f"Captured {captured}. Reading in the background; hover the next item."): + return + time.sleep(0.12) + + @app.get("/api/characters//equipment//icon") def icon(identifier, slot): characters.load(identifier) diff --git a/src/equipment_scan.py b/src/equipment_scan.py index 9efe60a..084de8f 100644 --- a/src/equipment_scan.py +++ b/src/equipment_scan.py @@ -108,6 +108,15 @@ def tooltip_bounds(frame, allow_clipped_footer=False, near=None): x = ax - 155 if x < 0 or x + 323 > frame.shape[1] or ay < 105: raise ReadError("Keep the item name, stars and full tooltip width on screen.") + return x, ay, tooltip_bottom(frame, x, ay, allow_clipped_footer) + + +def tooltip_bottom(frame, x, ay, allow_clipped_footer=False): + """The y just below the tooltip starting at X, searching from AY + 65. + + AY is where a "Currently Equipped" label sits (72 px above Required Level), + whether or not this tooltip shows one. + """ strip = frame[ay + 65 :, x + 20 : x + 300].astype(int) if strip.shape[1] != 280: raise ReadError("Move the full tooltip on screen.") @@ -125,9 +134,9 @@ def tooltip_bounds(frame, allow_clipped_footer=False, near=None): candidates = _verified_bottom_candidates(frame, x, ay, soft.mean(axis=1), coverage_min=.94, corner_min=.85) if not len(candidates): if allow_clipped_footer and frame.shape[:2] == (768, 1366): - return x, ay, frame.shape[0] + return frame.shape[0] raise ReadError("Show the entire item tooltip, including its bottom edge.") - return x, ay, ay + 65 + int(candidates[0]) + 3 + return ay + 65 + int(candidates[0]) + 3 def hover_target(frame, pointer, slots): @@ -167,12 +176,40 @@ def mono(image): return cv2.cvtColor((image.max(axis=2) > 155).astype(np.uint8) * 255, cv2.COLOR_GRAY2BGR) -def row_regions(frame, x, top, bottom): - area = frame[top:bottom, x + 15 : x + 310] - mask = area.max(axis=2) > 155 - ys = np.flatnonzero(mask.sum(axis=1) >= 3) +# Tooltip text spans these columns from the tooltip's left edge; rows are 6 to 19 px tall. +TEXT_LEFT, TEXT_RIGHT = 15, 310 +ROW_MIN, ROW_MAX = 6, 19 + + +def row_crop(frame, x, row): + """A text row of the tooltip at X, as the reader sees it.""" + a, b = row + return mono(frame[a:b, x + TEXT_LEFT : x + TEXT_RIGHT]) + + +def row_regions(frame, x, top, bottom, split=False): + """Text rows as (top, bottom). Blocks taller than a row are dropped, or with SPLIT, + cut at their emptiest row: the mouse cursor on a tooltip's edge joins neighbouring + rows (e.g. the stars and the name) into one such block.""" + counts = (frame[top:bottom, x + TEXT_LEFT : x + TEXT_RIGHT].max(axis=2) > 155).sum(axis=1) + ys = np.flatnonzero(counts >= 3) groups = [g for g in np.split(ys, np.flatnonzero(np.diff(ys) > 2) + 1) if len(g)] - return [(top + int(g[0]) - 2, top + int(g[-1]) + 3) for g in groups if 6 <= g[-1] - g[0] + 1 <= 19] + rows = [] + + def add(first, last): + height = last - first + 1 + if ROW_MIN <= height <= ROW_MAX: + rows.append((top + first - 2, top + last + 3)) + elif split and height > ROW_MAX: + inner = np.arange(first + ROW_MIN, last - ROW_MIN + 1) + cut = int(inner[np.argmin(counts[inner])]) + add(first, cut - 1) + add(cut + 1, last) + + for group in groups: + add(int(group[0]), int(group[-1])) + # With SPLIT, also keep the padded top inside the frame; without it, rows are exactly as before. + return [(max(0, a), b) for a, b in rows] if split else rows def capabilities(slot, name, potential, stats, text): @@ -236,7 +273,7 @@ def level_values(value): return tuple(map(int, re.findall(r"\d+", found[1]))) (text, confidence), accepted = verify( - reader, mono(frame[a:b, x + 15:x + 310]), (text, confidence), level_values, + reader, row_crop(frame, x, (a, b)), (text, confidence), level_values, ) if not accepted: raise ReadError("Required level is unclear; scan again") @@ -408,7 +445,7 @@ def hover(frame, reader, slot=None): clipped_footer = bottom == frame.shape[0] name_row = mono(frame[ay - 70 : ay - 48, x + 15 : x + 310]) rows = row_regions(frame, x, ay + 53, bottom - (4 if clipped_footer else 12)) - crops = [name_row] + [mono(frame[a:b, x + 15 : x + 310]) for a, b in rows] + crops = [name_row] + [row_crop(frame, x, row) for row in rows] readings = reader(crops) name, confidence = _resolve_item_name(reader, frame, x, ay, name_row, *readings[0]) result = {"kind": "hover", "item": name.strip(), "source": "equipped_tooltip", "errors": []} diff --git a/src/flaming/item_tooltip.py b/src/flaming/item_tooltip.py index bbae372..04c8a32 100644 --- a/src/flaming/item_tooltip.py +++ b/src/flaming/item_tooltip.py @@ -9,7 +9,7 @@ from utils.payload_data import read_payload_bytes -def level_anchor(frame): +def _level_scores(frame): # Threshold the translucent background away, retaining the native glyphs. def mask(image): return (image.min(axis=2) > 105).astype(np.uint8) * 255 @@ -25,7 +25,24 @@ def mask(image): if anchor is None: raise ReadError("Could not decode the Required Level reference image") results.append(cv2.matchTemplate(mask(frame), mask(anchor), cv2.TM_CCOEFF_NORMED)) - result = np.maximum.reduce(results) + return np.maximum.reduce(results), anchor + + +def level_anchors(frame, threshold=0.95, limit=4): + """Every visible Required Level label, best first: [(x, y)]. A comparison shows two.""" + scores, _ = _level_scores(frame) + found = [] + while len(found) < limit: + _, quality, _, (x, y) = cv2.minMaxLoc(scores) + if quality < threshold: + break + found.append((x, y)) + scores[max(0, y - 3) : y + 4, max(0, x - 3) : x + 4] = 0 + return found + + +def level_anchor(frame): + result, anchor = _level_scores(frame) _, quality, _, (x, y) = cv2.minMaxLoc(result) if quality < 0.95: raise ReadError("Required Level tooltip label is not visible") diff --git a/src/game_resolution.py b/src/game_resolution.py index f97c450..78277f5 100644 --- a/src/game_resolution.py +++ b/src/game_resolution.py @@ -34,6 +34,9 @@ def normalize_scan(image, mode): path = "images/window/scouter/erda_banner.png" elif mode == "equipment" or mode.startswith("hover:"): path = "images/window/equipment/windows_title.png" + elif mode == "quanah": + # Inventory hovers have no Equipment window; every item tooltip has this label. + path = "images/window/equipment/required_level.png" elif mode == "weapon": path = "images/window/equipment/currently_equipped.png" elif mode == "links": diff --git a/src/quanah/__init__.py b/src/quanah/__init__.py new file mode 100644 index 0000000..049dcd6 --- /dev/null +++ b/src/quanah/__init__.py @@ -0,0 +1 @@ +"""Quanah: the seasonal event-equipment skill-line set solver.""" diff --git a/src/quanah/data/lines.json b/src/quanah/data/lines.json new file mode 100644 index 0000000..0d3118f --- /dev/null +++ b/src/quanah/data/lines.json @@ -0,0 +1,43 @@ +{ + "slots": [ + {"key": "hat", "name": "Hat", "keywords": ["Hat"]}, + {"key": "top", "name": "Top", "keywords": ["Top", "Overall"]}, + {"key": "bottom", "name": "Bottom", "keywords": ["Bottom", "Pants"]}, + {"key": "cape", "name": "Cape", "keywords": ["Cape"]}, + {"key": "gloves", "name": "Gloves", "keywords": ["Gloves", "Glove"]}, + {"key": "shoes", "name": "Shoes", "keywords": ["Shoes", "Shoe"]} + ], + "classes": [ + {"key": "warrior", "name": "Warrior"}, + {"key": "magician", "name": "Magician"}, + {"key": "bowman", "name": "Bowman"}, + {"key": "thief", "name": "Thief"}, + {"key": "pirate", "name": "Pirate"} + ], + "lines": [ + {"key": "dl", "name": "Dimensional Leap", "text": "Dimensional Leap Lv. +1"}, + {"key": "wh", "name": "White Hole", "text": "White Hole Lv. +1"}, + {"key": "reg", "name": "Registry", "text": "[Hologram] Registry Lv. +1"}, + {"key": "atk", "name": "ATK", "text": "[Hologram] Attack Power & Magic ATT Enhancement Skill Lv. +1"}, + {"key": "crit", "name": "Crit DMG", "text": "Critical Damage Enhancement Skill Lv. +1"}, + {"key": "dmg", "name": "DMG", "text": "[Hologram] Damage Enhancement Skill Lv. +1"}, + {"key": "warrior", "name": "Warrior", "text": "[Hologram] Warrior Attack Skill Lv. +1", "job": true}, + {"key": "magician", "name": "Magician", "text": "[Hologram] Magician Attack Skill Lv. +1", "job": true}, + {"key": "bowman", "name": "Bowman", "text": "[Hologram] Bowman Attack Skill Lv. +1", "job": true}, + {"key": "thief", "name": "Thief", "text": "[Hologram] Thief Attack Skill Lv. +1", "job": true}, + {"key": "pirate", "name": "Pirate", "text": "[Hologram] Pirate Attack Skill Lv. +1", "job": true} + ], + "builds": [ + {"key": "skill", "name": "Skill", + "targets": {"dl": 3, "wh": 3, "reg": 3, "atk": 3, "warrior": 1, "magician": 1, "bowman": 1, "thief": 1, "pirate": 1, "crit": 1}}, + {"key": "gandi", "name": "GanDi", + "targets": {"dl": 3, "wh": 3, "reg": 3, "atk": 3, "crit": 3}, + "jobs": {"count": 3, "default": ["magician", "thief", "bowman"]}}, + {"key": "eu", "name": "EU", + "targets": {"dl": 3, "wh": 3, "reg": 3, "atk": 3, "crit": 3, "dmg": 3}}, + {"key": "custom", "name": "Custom", "targets": {}} + ], + "goal": 18, + "max_per_line": 3, + "max_lines": 3 +} diff --git a/src/quanah/lines.py b/src/quanah/lines.py new file mode 100644 index 0000000..eb629cf --- /dev/null +++ b/src/quanah/lines.py @@ -0,0 +1,40 @@ +"""Match a skill line's tooltip text to its catalog key. No image libraries, so the store can use it.""" + +import re +from difflib import SequenceMatcher + +from quanah import solver + +# Messages for items that are not Quanah pieces start with this; they are skipped, not failed. +# It lives here, not in vision, so the web server can check it without loading OpenCV. +SKIPPED = "Skipped" +MATCH_RATIO = 0.92 +SKILL_END = re.compile(r"Lv\.?\s*\+\s*\d+\s*$", re.I) + + +def normalise(text): + # "[Hologram]" prefixes most skill lines, and some job lines read "Attack Skill Level Lv. +1" + # where others read "Attack Skill Lv. +1"; neither word tells lines apart. + return re.sub(r"[^a-z0-9+]", "", re.sub(r"hologram|\blevel\b", "", text.casefold())) + + +def match_line(text): + """The catalog key for a skill line, or "other" for anything else (e.g. boss damage).""" + if not SKILL_END.search(text): + return solver.OTHER + clean = normalise(text) + best, ratio = solver.OTHER, 0.0 + for line in solver.catalog()["lines"]: + score = SequenceMatcher(None, clean, normalise(line["text"])).ratio() + if score > ratio: + best, ratio = line["key"], score + return best if ratio >= MATCH_RATIO else solver.OTHER + + +def rematch(raw): + """Keys for a scanned piece's saved texts, or None when they don't make a valid piece.""" + if not raw or len(raw) > solver.catalog()["max_lines"]: + return None + keys = [match_line(text) for text in raw] + real = [k for k in keys if k != solver.OTHER] + return keys if len(set(real)) == len(real) else None diff --git a/src/quanah/solver.py b/src/quanah/solver.py new file mode 100644 index 0000000..e5a86a9 --- /dev/null +++ b/src/quanah/solver.py @@ -0,0 +1,179 @@ +"""Pick one event piece per slot to fill a build's skill-line targets. + +A port of the community 3L, GanDi and EU set solvers: a DP over capped line +counts, one layer per slot. Lines above a target are wasted; a slot with no +eligible piece is left empty. +""" + +from functools import lru_cache +from itertools import combinations + +from utils.payload_data import read_payload_json + +OTHER = "other" + + +@lru_cache(maxsize=1) +def catalog(): + return read_payload_json("src/quanah/data/lines.json") + + +def slot_keys(): + return [slot["key"] for slot in catalog()["slots"]] + + +def line_keys(): + return [line["key"] for line in catalog()["lines"]] + + +def job_keys(): + return [line["key"] for line in catalog()["lines"] if line.get("job")] + + +def trim_targets(saved): + """Custom targets within the rules: known lines, 1 to 3 each, at most the goal in total. + + The store rejects anything else; a file saved before the 18-point cap is trimmed, in catalog order. + """ + cap, room, targets = catalog()["max_per_line"], catalog()["goal"], {} + for key in line_keys(): + value = min(int((saved or {}).get(key, 0)), cap, room) + if value > 0: + targets[key] = value + room -= value + return targets + + +def resolve_build(build): + """(targets, job rule) for a saved build choice. The job rule is (count, active jobs) or None.""" + presets = {preset["key"]: preset for preset in catalog()["builds"]} + preset = presets.get(build.get("preset"), presets["skill"]) + if preset["key"] == "custom": + return trim_targets(build.get("targets")), None + targets = dict(preset["targets"]) + rule = preset.get("jobs") + if not rule: + return targets, None + if build.get("job_mode") == "any": + return targets, (rule["count"], tuple(job_keys())) + chosen = [k for k in build.get("jobs") or [] if k in job_keys()] + if len(set(chosen)) != rule["count"]: + chosen = rule["default"] + return targets, (rule["count"], tuple(chosen)) + + +class _Plan: + def __init__(self, targets, jobs): + self.targets = {k: v for k, v in targets.items() if v > 0} + self.job_count, self.jobs = jobs if jobs else (0, ()) + # Job-rule lines count once each; fixed targets win if a key is both. + self.keys = list(self.targets) + [k for k in self.jobs if k not in self.targets] + self.caps = [self.targets.get(k, 1) for k in self.keys] + self.index = {k: i for i, k in enumerate(self.keys)} + self.goal = sum(self.targets.values()) + self.job_count + + def add(self, state, lines): + state = list(state) + for key in lines: + i = self.index.get(key) + if i is not None and state[i] < self.caps[i]: + state[i] += 1 + return tuple(state) + + def score(self, state): + fixed = sum(state[self.index[k]] for k in self.targets) + jobs = sum(state[self.index[k]] for k in self.jobs if k not in self.targets) + return fixed + min(self.job_count, jobs) + + def needs(self, state): + """Every line set that would bring STATE up to the goal.""" + base = [k for k in self.targets for _ in range(state[self.index[k]], self.targets[k])] + if not self.job_count: + return [base] + have = [k for k in self.jobs if k not in self.targets and state[self.index[k]]] + open_jobs = [k for k in self.jobs if k not in self.targets and not state[self.index[k]]] + missing = max(0, self.job_count - len(have)) + return [base + list(pick) for pick in combinations(open_jobs, missing)] + + +def _layers(plan, by_slot, skip=None): + current = {tuple(0 for _ in plan.keys): {"ways": 1}} + layers = [] + for slot in slot_keys(): + if slot == skip: + continue + options = by_slot.get(slot) or [None] + following = {} + for state, info in current.items(): + for item in options: + nxt = plan.add(state, item["lines"]) if item else state + entry = following.get(nxt) + if entry: + entry["ways"] += info["ways"] + else: + following[nxt] = {"prev": state, "item": item, "slot": slot, "ways": info["ways"]} + layers.append(following) + current = following + return layers + + +def solve(items, targets, jobs=None): + """Best set for ITEMS (dicts with id, slot, lines) under TARGETS and an optional job rule.""" + plan = _Plan(targets, jobs) + by_slot = {} + for item in items: + by_slot.setdefault(item["slot"], []).append(item) + layers = _layers(plan, by_slot) + final = layers[-1] + best_state = max(final, key=plan.score) # max() keeps the first of equal scores, like the sites. + best = plan.score(best_state) + picks, state = {}, best_state + for layer in reversed(layers): + entry = layer[state] + picks[entry["slot"]] = entry["item"] + state = entry["prev"] + # Which lines of the chosen pieces count toward the goal, in slot order. + run, jobs_used, used = dict.fromkeys(plan.keys, 0), 0, {} + for slot in slot_keys(): + item = picks.get(slot) + flags = [] + for key in item["lines"] if item else []: + if key in plan.targets: + ok = run[key] < plan.targets[key] + elif key in plan.jobs: + ok = not run[key] and jobs_used < plan.job_count + jobs_used += ok + else: + ok = False + if key in run: + run[key] += ok + flags.append(ok) + used[slot] = flags + return { + "score": best, + "goal": plan.goal, + "counts": dict(zip(plan.keys, best_state, strict=True)), + "picks": {slot: (item["id"] if item else None) for slot, item in picks.items()}, + "used": used, + "ways": final[best_state]["ways"], + "missing": plan.needs(best_state)[0] if best < plan.goal else [], + "hunt": _hunt(plan, by_slot) if best < plan.goal else [], + } + + +def _hunt(plan, by_slot): + """Pieces that would finish the set in one drop: (slot, lines) with no repeated line.""" + limit = catalog()["max_lines"] + found, seen = [], set() + for slot in slot_keys(): + for state in _layers(plan, by_slot, skip=slot)[-1]: + if plan.goal - plan.score(state) > limit: + continue + for need in plan.needs(state): + if not 0 < len(need) <= limit or len(set(need)) != len(need): + continue + key = (slot, tuple(need)) + if key not in seen: + seen.add(key) + found.append({"slot": slot, "need": need}) + return found diff --git a/src/quanah/store.py b/src/quanah/store.py new file mode 100644 index 0000000..a86a109 --- /dev/null +++ b/src/quanah/store.py @@ -0,0 +1,200 @@ +"""The saved Quanah class, build and event pieces, plus the solved best set. + +One global list, independent of Hascone's characters. Pieces of another class +are kept, flagged as unwearable and left out of the solver. +""" + +import json +import os +import tempfile +import threading +import uuid +from datetime import UTC, datetime +from pathlib import Path + +from quanah import solver +from quanah.lines import rematch + +PATH = Path("configs/quanah.json") +lock = threading.RLock() + + +def _default(): + gandi = next(b for b in solver.catalog()["builds"] if b["key"] == "gandi") + return { + "class": None, + "build": {"preset": "skill", "job_mode": "custom", "jobs": list(gandi["jobs"]["default"]), "targets": {}}, + "items": [], + } + + +def read(): + with lock: + data = _default() + if PATH.exists(): + saved = json.loads(PATH.read_text(encoding="utf-8")) + data["class"] = saved.get("class") + data["build"].update(saved.get("build") or {}) + # The Skill build was first saved as "original". + if data["build"].get("preset") == "original": + data["build"]["preset"] = "skill" + # So the page shows, and later changes validate, the same targets the solver uses. + data["build"]["targets"] = solver.trim_targets(data["build"].get("targets")) + data["items"] = saved.get("items") or [] + # Re-match scanned pieces from the text the scanner read, so catalog fixes reach + # pieces already saved. A piece the player edited keeps their lines. + for item in data["items"]: + if item.get("source") == "scan" and not item.get("edited"): + item["lines"] = rematch(item.get("raw")) or item["lines"] + return data + + +def _write(data): + PATH.parent.mkdir(parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(dir=PATH.parent, suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as stream: + json.dump(data, stream) + os.replace(name, PATH) + finally: + if os.path.exists(name): + os.unlink(name) + + +def _class_keys(): + return [c["key"] for c in solver.catalog()["classes"]] + + +def configure(class_key=None, build=None): + """Save the player's class and/or build choice.""" + with lock: + data = read() + if class_key is not None: + if class_key not in _class_keys(): + raise ValueError("Choose Warrior, Magician, Bowman, Thief or Pirate") + data["class"] = class_key + if build is not None: + data["build"] = _clean_build({**data["build"], **build}) + _write(data) + return data + + +def _clean_build(build): + presets = [b["key"] for b in solver.catalog()["builds"]] + if build.get("preset") not in presets: + raise ValueError("Unknown build") + if build.get("job_mode") not in ("custom", "any"): + raise ValueError("Unknown job mode") + jobs = build.get("jobs") or [] + if not isinstance(jobs, list) or set(jobs) - set(solver.job_keys()) or len(set(jobs)) != len(jobs) or len(jobs) > 3: + raise ValueError("Choose up to 3 different jobs") + targets = build.get("targets") or {} + cap = solver.catalog()["max_per_line"] + if not isinstance(targets, dict) or set(targets) - set(solver.line_keys()): + raise ValueError("Unknown custom line") + cleaned = {} + for key, value in targets.items(): + if not isinstance(value, int) or isinstance(value, bool) or not 0 <= value <= cap: + raise ValueError(f"Each line target must be 0 to {cap}") + if value: + cleaned[key] = value + goal = solver.catalog()["goal"] + if sum(cleaned.values()) > goal: + raise ValueError(f"Six pieces hold at most {goal} lines") + return {"preset": build["preset"], "job_mode": build["job_mode"], "jobs": jobs, "targets": cleaned} + + +def validate_lines(lines): + """1–3 known lines, no line twice (unrecognized "other" lines may repeat).""" + if not isinstance(lines, list) or not 1 <= len(lines) <= solver.catalog()["max_lines"]: + raise ValueError("A piece has 1 to 3 lines") + if any(key not in solver.line_keys() and key != solver.OTHER for key in lines): + raise ValueError("Unknown line") + real = [key for key in lines if key != solver.OTHER] + if len(set(real)) != len(real): + raise ValueError("A piece cannot roll the same line twice") + return list(lines) + + +def add_item(slot, lines, *, raw=None, name=None, item_class=None, source="manual"): + if slot not in solver.slot_keys(): + raise ValueError("Choose a slot") + lines = validate_lines(lines) + if item_class is not None and item_class not in _class_keys(): + raise ValueError("Unknown item class") + with lock: + data = read() + if not data["class"]: + raise ValueError("Choose your class first") + item = { + "id": uuid.uuid4().hex, + "slot": slot, + "lines": lines, + "raw": list(raw) if raw else None, + "name": name, + # A manual piece is one the player says they can wear. + "item_class": item_class or data["class"], + "source": source, + "added": datetime.now(UTC).isoformat(), + } + data["items"].append(item) + _write(data) + return item + + +def update_item(identifier, slot, lines): + """Correct a piece's slot and lines by hand. A scanned piece keeps what was read, marked edited.""" + if slot not in solver.slot_keys(): + raise ValueError("Choose a slot") + lines = validate_lines(lines) + with lock: + data = read() + item = next((i for i in data["items"] if i["id"] == identifier), None) + if item is None: + raise ValueError("That piece is already gone") + if (item["slot"], item["lines"]) != (slot, lines): + item.update(slot=slot, lines=lines, edited=datetime.now(UTC).isoformat()) + _write(data) + return item + + +def delete_item(identifier): + with lock: + data = read() + kept = [item for item in data["items"] if item["id"] != identifier] + if len(kept) == len(data["items"]): + raise ValueError("That piece is already gone") + data["items"] = kept + _write(data) + + +def clear_items(): + with lock: + data = read() + data["items"] = [] + _write(data) + + +def duplicates(items): + """Ids of pieces sharing a slot and the same lines in any order.""" + groups = {} + for item in items: + groups.setdefault((item["slot"], tuple(sorted(item["lines"]))), []).append(item["id"]) + return {i for ids in groups.values() if len(ids) > 1 for i in ids} + + +def payload(): + """Everything the page needs: catalog, settings, flagged pieces and the best set.""" + data = read() + dupes = duplicates(data["items"]) + items = [{**item, "duplicate": item["id"] in dupes, + "wearable": bool(data["class"]) and item.get("item_class") == data["class"]} + for item in data["items"]] + solution = None + if data["class"]: + targets, jobs = solver.resolve_build(data["build"]) + solution = solver.solve([i for i in items if i["wearable"]], targets, jobs) + solution["targets"] = targets + solution["jobs"] = {"count": jobs[0], "keys": list(jobs[1])} if jobs else None + return {"catalog": solver.catalog(), "class": data["class"], "build": data["build"], + "items": items, "solution": solution} diff --git a/src/quanah/vision.py b/src/quanah/vision.py new file mode 100644 index 0000000..47c1d62 --- /dev/null +++ b/src/quanah/vision.py @@ -0,0 +1,285 @@ +"""Read an event piece's slot, class and skill lines from any item tooltip. + +Works for an inventory hover (where the game always also shows the equipped +item's comparison tooltip) and for an Equipment-window hover. The tooltip is +anchored on its Required Level label; the comparison tooltip is the one that +shows "Currently Equipped", so the hovered item is the other one. + +Skill lines follow the base stats, whose last row is "Enemy DEF Ignored", and +end at "Scroll Enhancement". A long line wraps onto a second row, e.g. +"[Hologram] Attack Power & Magic ATT Enhancement" / "Skill Lv. +1"; rows are +joined until the line ends in "Lv. +N" or a stat value. +""" + +import re + +import numpy as np + +from equipment_scan import ( + TEXT_LEFT, + TEXT_RIGHT, + _find_currently_equipped, + row_crop, + row_regions, + tooltip_bottom, +) +from flaming.item_tooltip import level_anchors +from flaming.stats import ReadError +from ocr_confidence import AGREEMENT_CONFIDENCE, AUTO_CONFIDENCE, verify +from quanah import solver +from quanah.lines import SKILL_END, SKIPPED, match_line + +# Offsets from the Required Level label, measured on GMS hover fixtures and +# event-item screenshots: the tooltip's left edge is 14 px left of it, and a +# "Currently Equipped" label (when shown) sits 72 px above it, 141 px right. +LEFT = 14 +EQUIPPED_DY, EQUIPPED_DX = 72, 141 +WIDTH = 323 +# Event tooltips stack Untradable/Duration rows above the icon, so the name is +# searched for in this many pixels above Required Level rather than at a fixed row. +NAME_SEARCH = 300 +MAX_WRAP = 3 +END_MARKERS = re.compile(r"^(Scroll\s*Enhancement|Jewel\s*Stats|Potential|Bonus\s*Potential|Check\s*the)", re.I) +BASE_END = re.compile(r"^Enemy\s*DEF\s*Ignored", re.I) +STAT_END = re.compile(r"\+\s*\d+(?:\.\d+)?\s*%?\s*(?:\([^)]*\))?\s*$") +SKILL_START = re.compile(r"^\[?\s*Hologram|Lv\.?\s*\+\s*\d", re.I) + + +def _is_equipped(frame, x, y): + quality, _, _ = _find_currently_equipped(frame, near=(x + EQUIPPED_DX, y - EQUIPPED_DY)) + return quality >= 0.95 + + +def locate(frame, pointer=None, anchor=None): + """The hovered piece's tooltip as (x, name search top, Required Level y, bottom), from one frame; no OCR. + + ANCHOR, the Required Level position chosen when the frame was captured (see + anchor_of), reads that same tooltip later, when the cursor is no longer known. + + The bottom edge is used when found. A tooltip pushed against the bottom of + the screen may not show it; the skill lines end well above it, so the + frame's bottom stands in and read_piece requires the Scroll Enhancement row. + """ + anchors = level_anchors(frame) + if not anchors: + raise ReadError("Hover an event item.") + hovered = [a for a in anchors if not _is_equipped(frame, *a)] + if anchor is not None: + if tuple(anchor) not in anchors: + raise ReadError("Hover one item at a time.") + lx, ly = anchor + elif len(hovered) == 1: + lx, ly = hovered[0] + elif not hovered and len(anchors) == 1: + lx, ly = anchors[0] # An Equipment-window hover shows only the equipped item. + elif pointer is not None: + lx, ly = min(hovered or anchors, key=lambda a: (a[0] - pointer[0]) ** 2 + (a[1] - pointer[1]) ** 2) + else: + raise ReadError("Hover one item at a time.") + x = lx - LEFT + # Rows are read up to TEXT_RIGHT; the last few pixels are only the border. + if x < 0 or x + TEXT_RIGHT > frame.shape[1]: + raise ReadError("Move the tooltip fully on screen.") + try: + bottom = tooltip_bottom(frame, x, ly - EQUIPPED_DY) + except ReadError: + bottom = frame.shape[0] + return x, max(0, ly - NAME_SEARCH), ly, bottom + + +def anchor_of(box): + """The Required Level position of a box from locate, to pass to read_piece.""" + x, _, level_y, _ = box + return x + LEFT, level_y + + +def signature(frame, box): + """Bright text below Required Level: equal for the same piece wherever its tooltip is drawn.""" + x, _, level_y, bottom = box + return frame[level_y:bottom, x : x + WIDTH].max(axis=2) > 155 + + +def same_tooltip(a, b, tolerance=0.1): + """Whether two signatures show the same tooltip, allowing for animated sparkles.""" + if a is None or b is None or a.shape != b.shape: + return False + return int((a ^ b).sum()) <= tolerance * max(1, int(a.sum())) + + +def _word(word, text): + return re.search(rf"\b{re.escape(word)}\b", text, re.I) + + +def parse_name(text): + """(slot, class) from an item name like "Libae's Supercharged Hat (Warrior)".""" + catalog = solver.catalog() + if _word("Required", text) or _word("Set", text): + return None + slot = next((s["key"] for s in catalog["slots"] if any(_word(k, text) for k in s["keywords"])), None) + item_class = next((c["key"] for c in catalog["classes"] if _word(c["name"], text)), None) + return (slot, item_class) if slot and item_class else None + + +def _accept(reader, crop, reading, parse): + """A reading's text, retried when uncertain; None if it can't be trusted.""" + if reading[1] >= AUTO_CONFIDENCE: + return reading[0] + (text, confidence), accepted = verify(reader, crop, reading, parse) + return text if accepted and confidence >= AGREEMENT_CONFIDENCE else None + + +def _text(text): + text = re.sub(r"\s+", " ", text).strip() + if not text: + raise ReadError("Empty row") + return text.casefold() + + +def _complete(text): + return bool(SKILL_END.search(text) or STAT_END.search(text)) + + +def section(texts): + """Indexes of the rows holding skill lines, grouped by line: [[row, ...], ...]. Also whether it ended.""" + start = next((i + 1 for i, t in enumerate(texts) if BASE_END.match(t.strip())), None) + if start is None: + start = next((i for i, t in enumerate(texts) if SKILL_START.search(t)), len(texts)) + lines, current = [], [] + for i in range(start, len(texts)): + text = texts[i].strip() + if END_MARKERS.match(text): + if current: + lines.append(current) + return lines, True + if not text: + continue + current.append(i) + if _complete(" ".join(texts[j] for j in current)) or len(current) >= MAX_WRAP: + lines.append(current) + current = [] + if current: + lines.append(current) + return lines, False + + +NAME_WHITE, NAME_PIXELS = 0.8, 120 +BATCH = 6 + + +def tooltip_top(frame, x, search_top, level_y): + """The tooltip's top border: the one 1 px line above its header, or SEARCH_TOP if none is found. + + Rows above it belong to other windows, so the name is looked for only below it. + """ + strip = frame[search_top:level_y, x + 20 : x + 300].astype(int) + if len(strip) < 3: + return search_top + line = ((strip[1:-1] - strip[:-2]).min(axis=2) > 8) & ((strip[1:-1] - strip[2:]).min(axis=2) > 8) + # Even a short tooltip (a medal) has 160 px of header above Required Level; separators sit closer. + found = [search_top + 1 + int(i) for i in np.flatnonzero(line.mean(axis=1) > 0.9)] + found = [y for y in found if y < level_y - 100] + return max(found) if found else search_top + + +def name_rows(frame, x, rows): + """Indexes of the name's row(s): the first white text below the border (stars are yellow, + Untradable and Duration orange). A long name wraps onto a second white row.""" + white = [] + for i, (a, b) in enumerate(rows): + area = frame[a:b, x + TEXT_LEFT : x + TEXT_RIGHT] + bright = int((area.max(axis=2) > 155).sum()) + if bright >= NAME_PIXELS and (area.min(axis=2) > 150).sum() >= NAME_WHITE * bright: + white.append(i) + if not white: + return list(range(min(4, len(rows)))) + first = white[0] + wrap = first + 1 in white and rows[first + 1][0] - rows[first][1] < 8 + return [first, first + 1] if wrap else [first] + + +class _Rows: + """Rows of one tooltip, read only when asked; each model call costs about 0.6 s per row.""" + + def __init__(self, frame, x, rows, reader): + self.rows, self.reader, self.readings = rows, reader, {} + self.crops = [row_crop(frame, x, row) for row in rows] + + def read(self, indexes): + todo = [i for i in indexes if i not in self.readings] + if todo: + for i, reading in zip(todo, self.reader([self.crops[i] for i in todo]), strict=True): + self.readings[i] = reading + return [self.readings[i] for i in indexes] + + def accept(self, i, parse): + return _accept(self.reader, self.crops[i], self.readings[i], parse) + + +def clean_name(text): + """The name without stray marks in front, e.g. the cursor over its first letter read as "_".""" + return re.sub(r"^[^A-Za-z0-9\[(]+", "", text.strip()) + + +def _identify(rows, wanted): + """(name, (slot, class)) from the name rows, or (text read, None).""" + readings = rows.read(wanted) + text = clean_name(" ".join(t.strip() for t, _ in readings if t.strip())) + for parts in ([wanted[0]], wanted): + if not parse_name(" ".join(rows.readings[i][0] for i in parts)): + continue + texts = [rows.accept(i, _text) for i in parts] + if None in texts: + return text, None + name = clean_name(" ".join(t.strip() for t in texts)) + return name, parse_name(name) + return text, None + + +def read_piece(frame, reader, anchor=None): + x, search_top, level_y, bottom = locate(frame, anchor=anchor) + top = tooltip_top(frame, x, search_top, level_y) + found = row_regions(frame, x, top + 2, bottom - (4 if bottom == frame.shape[0] else 12), split=True) + rows = _Rows(frame, x, found, reader) + + # Name first: a shoulder, medal or other item is turned away after one or two rows. + above = [i for i, (a, _) in enumerate(found) if a < level_y] + name, identity = _identify(rows, name_rows(frame, x, [found[i] for i in above])) if above else ("", None) + if not identity: + if name and len(name) > 3: + raise ReadError(f"{SKIPPED} {name}: not a Quanah piece") + raise ReadError("Couldn't read the item name") + + # Then the stats, a few rows at a time, stopping at Scroll Enhancement. + below = [i for i, (a, _) in enumerate(found) if a > level_y] + texts = [] + for n in range(0, len(below), BATCH): + texts += [t for t, _ in rows.read(below[n : n + BATCH])] + groups, ended = section(texts) + if ended: + break + else: + groups, ended = section(texts) + if not ended: + raise ReadError("Skill lines cut off") + lines, raw = [], [] + for group in groups: + parts = [] + for i in (below[j] for j in group): + text = rows.accept(i, _text) + if text is None: + raise ReadError(f"Unclear line: {rows.readings[i][0].strip()}") + parts.append(text.strip()) + full = re.sub(r"\s+", " ", " ".join(parts)) + lines.append(match_line(full)) + raw.append(full) + if not lines: + raise ReadError("No skill lines found") + if len(lines) > solver.catalog()["max_lines"]: + raise ReadError("More than 3 lines read") + real = [k for k in lines if k != solver.OTHER] + if len(set(real)) != len(real): + raise ReadError("Same line read twice") + slot, item_class = identity + return {"kind": "quanah", "name": name, "slot": slot, "item_class": item_class, "lines": lines, "raw": raw} + + diff --git a/src/reader.py b/src/reader.py index f2c418a..f2cd455 100644 --- a/src/reader.py +++ b/src/reader.py @@ -38,6 +38,11 @@ def read(image, mode): return grid(image) with lock: reader = _recognizer() + if mode == 'quanah' or mode.startswith('quanah:'): + from quanah.vision import read_piece + # "quanah:X:Y" names the tooltip chosen at capture time. + anchor = tuple(int(v) for v in mode.split(':')[1:]) or None + return read_piece(image, reader, anchor) if mode.startswith('hover:'): from equipment_scan import hover return hover(image, reader, mode.split(':')[1]) diff --git a/src/scan_steps.py b/src/scan_steps.py index 192833a..5feda92 100644 --- a/src/scan_steps.py +++ b/src/scan_steps.py @@ -44,6 +44,33 @@ def hover_step(body): return slot, second, {slot: hover_icon(second)} +def quanah_step(body, previous=None): + """Look once for a finished event-item tooltip: (frame, signature, Required Level position). + + Two frames must show the same tooltip, so it is not mid-draw; a tooltip + matching PREVIOUS (the last capture) is skipped while it stays hovered. + Returns (None, None, None) when no tooltip is visible, so hovering the same item + again after moving away captures it again (and the page flags the duplicate). + """ + from flaming.item_tooltip import level_anchors + from flaming.stats import ReadError + from quanah.vision import anchor_of, locate, same_tooltip, signature + + first, scale = _frame(body) + if not level_anchors(first): + return None, None, None + box = locate(first, _pointer(body, scale)) + mark = signature(first, box) + if same_tooltip(mark, previous): + raise ReadError("Captured. Hover the next item.") + second, scale = _frame(body) + again = locate(second, _pointer(body, scale)) + if not same_tooltip(mark, signature(second, again)): + raise ReadError("Waiting for the tooltip to finish drawing.") + # The OCR step has no cursor; it reads the tooltip chosen here. + return second, mark, anchor_of(again) + + def character_step(body, info): """Two matching frames of a character panel: (frame, HEXA matrix or None).""" from scouter import capture_ready diff --git a/tests/fixtures/quanah/bottom_comparison.png b/tests/fixtures/quanah/bottom_comparison.png new file mode 100644 index 0000000..34b2d02 Binary files /dev/null and b/tests/fixtures/quanah/bottom_comparison.png differ diff --git a/tests/fixtures/quanah/bottom_equipped.png b/tests/fixtures/quanah/bottom_equipped.png new file mode 100644 index 0000000..b2066e4 Binary files /dev/null and b/tests/fixtures/quanah/bottom_equipped.png differ diff --git a/tests/fixtures/quanah/hat_bottom_clipped.png b/tests/fixtures/quanah/hat_bottom_clipped.png new file mode 100644 index 0000000..0e22c64 Binary files /dev/null and b/tests/fixtures/quanah/hat_bottom_clipped.png differ diff --git a/tests/fixtures/quanah/medal_equipped.png b/tests/fixtures/quanah/medal_equipped.png new file mode 100644 index 0000000..7aa52ae Binary files /dev/null and b/tests/fixtures/quanah/medal_equipped.png differ diff --git a/tests/fixtures/quanah/readings.json b/tests/fixtures/quanah/readings.json new file mode 100644 index 0000000..d06523e --- /dev/null +++ b/tests/fixtures/quanah/readings.json @@ -0,0 +1,274 @@ +{ +"(13, 295, 3)04fa673585d3caee49b5daf6921e0cf850f00ec030cb2a08542a6fcae240b798": [ +"Max HP +15 (0 +15)", +0.9696356654167175 +], +"(13, 295, 3)0952f6dbb03ccfd8e83ce75e5519aa254e3abfadc6025b4ea03349dc669bae63": [ +"STR +143 (80 +6 +57)", +0.9702337384223938 +], +"(13, 295, 3)0c29d061fecd93a1e16b0f42808a956a9013929856a87ef3e06b1c9f5d223575": [ +"All Stats +6% (0% +6%)", +0.9900457859039307 +], +"(13, 295, 3)1b6c497147fbb954886e9cd29b0c3c354539a3b275cb4f17bb98c0052717cc68": [ +"STR +76 (50 +6 +20)", +0.9970875978469849 +], +"(13, 295, 3)1da1317fc7aba38f0e94e5f92b97a81423f5bdfd637c20d84b3f37a8469aa77b": [ +"LUK +25 (0 +25)", +0.9802238345146179 +], +"(13, 295, 3)1e57ed79877756c164f8b632ada8c6b9b44e1a4dcc4d8cc25fde8f3761a8ec65": [ +"STR +60 (50 +10)", +0.9948615431785583 +], +"(13, 295, 3)2272570e14bb128d87be4271c46aa57e0ae87d8d67cb8ab105d265496256f8be": [ +"Max HP +65 (0 +65)", +0.9765195846557617 +], +"(13, 295, 3)2e98fcef96ecbc7bce4c59465b36c33e5393cabb5496c98705fee9c6a8557260": [ +"White Hole Lv. +1", +0.9992758631706238 +], +"(13, 295, 3)353fff3848cb849d01e6669fe6e1c3fc2a00d8f40fb28587f1140157a274233d": [ +"Defense +592 (325 +267)", +0.9980531930923462 +], +"(13, 295, 3)620f2642b37a190d01fd717b571f554f830aab0c4cc3a4c0efc9dd1d0e2d0e4d": [ +"Interact/Harvest key.", +0.9979556798934937 +], +"(13, 295, 3)631960ce92ff8d8806cdc6c9b7a69742bc6ccc94a8dedc91de4808e0ca4c2ee8": [ +"DEX +56 (50 +6)", +0.9800204038619995 +], +"(13, 295, 3)63b14c0a95506fd61e9525f980cf0639bfa46f5ee356d30ed91a89f46e363d22": [ +"Max HP +35 (0 +35)", +0.969538152217865 +], +"(13, 295, 3)738a4ba65e54cd932890cdf65f70218ef34e107b7402cda02b98f6231bf94089": [ +"Jewel Stats", +0.9987406134605408 +], +"(13, 295, 3)75305ae9b6e59013eaacc620455ce0e8fe872a1d4e3d4a023e81f3c1eb1f072e": [ +"Attack Power +6", +0.9733208417892456 +], +"(13, 295, 3)7726d5a08c84bfd7bfd220c203dbb0089aedb27acdee0c9e7fd2e7d02afb1b04": [ +"Defense +461 (325 +136)", +0.9972439408302307 +], +"(13, 295, 3)77326cfa52399eabd3e43830c68b5494f8320826347040819cbba4ae7c794e9d": [ +"LUK +57 (0 +57)", +0.9848549962043762 +], +"(13, 295, 3)79249802ab61fb9bd18162413b401835a1e7a9c1c20419e3ea6594829df3c36b": [ +"Defense +915 (750 +120 +45)", +0.9941231608390808 +], +"(13, 295, 3)7b67a957901e54e1453d54c70b38618840078182da82ca595b5557cacaf979a8": [ +"Max MP +360", +0.9773860573768616 +], +"(13, 295, 3)7c56101a98b48603f2645f8b4193cbb0995e53d021b0a3cadbedda046d2b6546": [ +"DEX +60 (50 +10)", +0.972542405128479 +], +"(13, 295, 3)7dfc6aa661b405fb2fd3d5471702d2b5a6a23ec1c6bbd67e98196c9b1434ab09": [ +"DEX +141 (50 +16 +75)", +0.9787207841873169 +], +"(13, 295, 3)855e14e752c80898c0ce6bcda54fa557c118d4c36b9d81674371e101204482d4": [ +"Dimensional Leap Lv. +1", +0.9990135431289673 +], +"(13, 295, 3)87ffae11092c8f3b8f08c3dd205b8e69c781a569e0b81c16dfb90b1009ca8928": [ +"INT +30 (0 +30)", +0.9956626892089844 +], +"(13, 295, 3)8b2e78de5dfbe8a8e1f3cd66078d00a96bb6aa17a500a0ddc42861342aa78281": [ +"Max HP +255 (0 +255)", +0.9917386770248413 +], +"(13, 295, 3)92b3ca3693b69f04fff807cb79125787604fff60bf4343e08a9f15d89180c462": [ +"DEX +133 (50 +31 +52)", +0.9672754406929016 +], +"(13, 295, 3)96312a7d5f69b1556eeb2cf3ba07ff6cbc0a89aff62c63a983448bcfb59fe93f": [ +"Defense +379 (325 +54)", +0.9962537884712219 +], +"(13, 295, 3)9bc0714f6d536aef6f0cfcba819a0979ef40fb596ae5e9d00b86e67119de78a4": [ +"Defense +759 (325 +434)", +0.9967308044433594 +], +"(13, 295, 3)a08245eb9879731019987ac076f1824c18c6d587f5c44c233ebbdf5d668c8a85": [ +"Attack Power +27 (6 +21)", +0.9979805946350098 +], +"(13, 295, 3)a4f331104fcc34ed4a7b888f42666747cedcbe88e9fc3127e3f7606e50999845": [ +"DEX +86 (80 +6)", +0.977348268032074 +], +"(13, 295, 3)a510ce32a18f40cba404d35cdf118ec433a540b93ec27e4000b7a5ce1f0d927c": [ +"Max HP +180 (0 +180)", +0.9690936803817749 +], +"(13, 295, 3)b420cd2d6e48e98e2601e8f86ea28b63067c8f0db01773213224780df701e26e": [ +"Max MP +2400 (0 +2400)", +0.9542430639266968 +], +"(13, 295, 3)b633cb06c09354628b94c61f5261789c0d2d30d1918e212b9071a869e06a416c": [ +"Defense +418 (325 +93)", +0.9949901700019836 +], +"(13, 295, 3)d27f04ebb72533e0bb36bf83a11f3cbaf595bacb0493d8551ae9e22f4345754d": [ +"Max MP +1440 (0 +1440)", +0.980563223361969 +], +"(13, 295, 3)e60e3076fc964cc21c84b278a818d4cbb931e391cc4dfb852c65ad20638d4b27": [ +"Attack Power +10", +0.9721871614456177 +], +"(13, 295, 3)e858e8c98c5a03beacbedd7ce0581df6622eedc4b09ccde60f06c3b0cb6b3684": [ +"Max HP +375 (360 +15)", +0.9901114106178284 +], +"(13, 295, 3)ec77d1f728d03c618de0f9fd02e650d6703bf5cb9ca50ed8b1bc3410feb59243": [ +"STR +66 (50 +16)", +0.9927198886871338 +], +"(13, 295, 3)f54ea2d1f103da4423c7f8b9adba890aeb5d0d02daa098b4d1523c309a413fd4": [ +"Scroll Enhancement None", +0.9922022819519043 +], +"(13, 295, 3)f55902327d11786cdd58e8607ab6b71df58f002987e3533e0add226c33b82e73": [ +"STR +81 (50 +31)", +0.9981207847595215 +], +"(13, 295, 3)fbf75b05464c42aef8635f23bd6c5316bac474936677baeb8f796ce4bc062ac4": [ +"INT +27 (0 +27)", +0.9987494945526123 +], +"(13, 295, 3)ff50dd683552dd71b35381ab7b8725f6c915ed88d0004d1d26981d0ba0a5f61c": [ +"Skill Lv. +1", +0.984605073928833 +], +"(14, 295, 3)c8981afc4e948e6cf6220fa6455263524f112a439e32b7b90cae20f9bd5b51df": [ +"HYPER BURNING MAX", +0.999557614326477 +], +"(14, 295, 3)da7a5a34c065f4733123f20fd7325246796b0c5f0285a0939b95d56ede826510": [ +"(Warrior)", +0.9994757771492004 +], +"(15, 295, 3)086879c5964875852ef266abc004460bd4fc560e94154d8f0ff1b45e08bdadf2": [ +"Set EffectLibae's Supercharged Equipment Set", +0.9967707991600037 +], +"(15, 295, 3)123fbde6aa6300a12baecfce4f0058da86350cc582d13927a2a765329b7717cd": [ +"(13 Remaining, 0 Restore(s) Available)", +0.9968039989471436 +], +"(15, 295, 3)21f466cf30739e353ddf9fac363714d5f29466c840ce32d3de4dde4528341fe5": [ +"[Hologram] Magician Attack Skill Lv. +1", +0.9986656308174133 +], +"(15, 295, 3)24c961ae84a0075fe4d7daea9ccdcb8a8e1ee9162e08eeae8c60bd7121dc2d70": [ +"Magic ATT +21 (0 +21)", +0.9958407282829285 +], +"(15, 295, 3)28001dc0fbed9c0da1dde9886c84a7e4a4d87524478d72efd205808018687a68": [ +"[Hologram] Registry Lv. +1", +0.9995724558830261 +], +"(15, 295, 3)3454d26e046ab3feed495935ab8943f13cef2e8914069800bab0ca8a9ced9eb6": [ +"INT +50 (0 +50)", +0.9788236021995544 +], +"(15, 295, 3)5d70d8b332fdc9621273c0812f487b33f67186b5ae007e233fa2e623d49a289d": [ +"[Hologram] Damage Enhancement Skill Lv. +1", +0.9887595176696777 +], +"(15, 295, 3)629366f15b1ae724b898fdb392d6701a6c185f378bc063b368237b6923e2c4c7": [ +"Enemy DEF Ignored +5%", +0.9979965686798096 +], +"(15, 295, 3)7dbd81731298f4bb4324f4d13ce0f2975f8189215b835230ba2467ad59e91147": [ +"[Hologram] Attack Power & Magic ATT Enhancement", +0.9986612796783447 +], +"(15, 295, 3)920cbc8d06bfb98d290540e5e5920da1b4d20e60f421ab61ea6d0b8fd4755046": [ +"[Hologram] Bowman Attack Skill Level Lv. +1", +0.9997010231018066 +], +"(15, 295, 3)9f3a17f10f1654bbd2944ba28a234bd47721f2b595d4293434c9ae03c00f0faf": [ +"Check the enhancement details by using the", +0.9997761845588684 +], +"(15, 295, 3)a11d084b034aea53de2959cd192f5073a52d4d25030abbc4f7692f5bc83e4a48": [ +"Speed +5 (0 +5)", +0.9754226207733154 +], +"(15, 295, 3)b2ec3975cd5e5ba541c7b94fe8a24059eea085d40cf76214ed9780d27e752146": [ +"(9 Remaining, 0 Restore(s) Available)", +0.9952574968338013 +], +"(15, 295, 3)b30a31d7506504da8ef6e4a9dbb5799c5a7b686c8aa6ca46d2db6f3d157918bc": [ +"[Hologram] Warrior Attack Skill Level Lv. +1", +0.9997478127479553 +], +"(15, 295, 3)d968b727929f4370de2b289407b0441518a28763fc060b91528b0fc9c40ff2ff": [ +"Jump +5 (0 +5)", +0.9930002093315125 +], +"(15, 295, 3)dd0fbd7176127dd657dc83a61a45a1000d7d4f719ebd5049e18e4f37c5ef4a41": [ +"[Hologram] Critical Damage Enhancement Skill Lv. +1", +0.9997676610946655 +], +"(15, 295, 3)dd1560041e17d685f1db441cfc440ea768ce87e3be7f9af25782eefe437bdaa3": [ +"Magic ATT +5 (0 +5)", +0.9740299582481384 +], +"(15, 295, 3)f70c61a365b604d3b3c383245cbd6bfb01a86f39e96396dcfb4b28f307810301": [ +"Jump +6 (0 +6)", +0.9907435178756714 +], +"(15, 295, 3)ffd27be1cfd5002472fcdbac7d8cf42db6b3ebb9aba5272e5d539a9aeddab15d": [ +"Enemy DEF Ignored +15%", +0.997056782245636 +], +"(16, 295, 3)03fff003d693f64a7255e5993b3ccc9ec74bcce3c8e211d9c33ab9db046124cb": [ +"Potential : Legendary", +0.9840372800827026 +], +"(16, 295, 3)273b22d5db3b0b980424996ce2d7227203c5adae7fe8bf12e891ee7a8543d368": [ +"STR +141 (50 +66 +25) ", +0.9603490233421326 +], +"(17, 295, 3)c2120024b7cb423ecc2e1b2e4f458d4c6257f46c29327c66a279559a7f00485b": [ +"Libae's Supercharged Top (Warrior)", +0.9872431755065918 +], +"(17, 295, 3)eec7ed2ff1394e3d9d06da047ae4717353bd56b69e41b8e54e7b2314c9321218": [ +"Libae's Supercharged Pants (Warrior)", +0.9999071955680847 +], +"(17, 295, 3)ff42518d5fcb65d348e02726856adbaf9885d2a0f129051a2e83a06113362173": [ +"Libae's Supercharged Hat (Warrior)", +0.9998821020126343 +], +"(20, 295, 3)802db591376894d5559b0e3bf55b55cbd6f0d89221229ff71c64b1c542fef715": [ +"DEX +141 (50 +66 +25)", +0.9864703416824341 +], +"(23, 295, 3)21caf5fa2e4449ea181eb0af6f970533b4f828e33eee117c39c034e93600d5bf": [ +"Libae's Supercharged Shoulder Accessory", +0.9865965247154236 +], +"(23, 295, 3)ff2a6cb4b4bdf6349f41aeda1e5e947ea17e42928c13f91b4d39ba6856c94841": [ +"LUK +30 (0 +30)", +0.9908479452133179 +] +} \ No newline at end of file diff --git a/tests/fixtures/quanah/shoulder_equipped.png b/tests/fixtures/quanah/shoulder_equipped.png new file mode 100644 index 0000000..45fa6b0 Binary files /dev/null and b/tests/fixtures/quanah/shoulder_equipped.png differ diff --git a/tests/fixtures/quanah/top2_comparison.png b/tests/fixtures/quanah/top2_comparison.png new file mode 100644 index 0000000..53040eb Binary files /dev/null and b/tests/fixtures/quanah/top2_comparison.png differ diff --git a/tests/fixtures/quanah/top_comparison.png b/tests/fixtures/quanah/top_comparison.png new file mode 100644 index 0000000..ee9d048 Binary files /dev/null and b/tests/fixtures/quanah/top_comparison.png differ diff --git a/tests/fixtures/quanah/top_equipped.png b/tests/fixtures/quanah/top_equipped.png new file mode 100644 index 0000000..850012b Binary files /dev/null and b/tests/fixtures/quanah/top_equipped.png differ diff --git a/tests/js/quanah.test.cjs b/tests/js/quanah.test.cjs new file mode 100644 index 0000000..bf2485f --- /dev/null +++ b/tests/js/quanah.test.cjs @@ -0,0 +1,102 @@ +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const fs=require('node:fs'); +const path=require('node:path'); + +const web=path.join(__dirname,'../../web'); +const catalog=JSON.parse(fs.readFileSync(path.join(__dirname,'../../src/quanah/data/lines.json'),'utf8')); + +function model(extra={}){ + const items=[ + {id:'a',slot:'hat',lines:['dl','wh','dmg'],wearable:true,duplicate:true,item_class:'warrior',source:'scan',raw:['Dimensional Leap Lv. +1']}, + {id:'b',slot:'hat',lines:['dmg','dl','wh'],wearable:true,duplicate:true,item_class:'warrior',source:'manual'}, + {id:'c',slot:'top',lines:['reg',''],wearable:false,duplicate:false,item_class:'bowman',source:'scan',name:'Libae '}, + ]; + const solution={score:3,goal:18,ways:1,targets:{dl:3,wh:3,dmg:3},counts:{dl:1,wh:1,dmg:1},jobs:null, + picks:{hat:'a',top:null,bottom:null,gloves:null,shoes:null,cape:null}, + used:{hat:[true,true,true],top:[],bottom:[],gloves:[],shoes:[],cape:[]},missing:['dl','dl','wh','wh','dmg','dmg'],hunt:[]}; + return {catalog,class:'warrior',build:{preset:'eu',job_mode:'custom',jobs:[],targets:{}},items,solution,...extra}; +} + +test('gear lists duplicates, unwearable pieces and the picked piece, escaping text',async()=>{ + const {renderGear}=await import('../../web/pages/quanah.js'); + const html=renderGear(model()); + assert.equal((html.match(/>Duplicate|undefined|null/); +}); + +test('pieces sit hat/cape, top/gloves, bottom/shoes, unnumbered, each with edit and delete',async()=>{ + const {renderGear}=await import('../../web/pages/quanah.js'); + const html=renderGear(model(),'c'); + const order=[...html.matchAll(/

([^<]+)<\/h3>/g)].map(m=>m[1]); + assert.deepEqual(order,['Hat','Cape','Top','Gloves','Bottom','Shoes']); + assert.doesNotMatch(html,/#\d/); + assert.equal((html.match(/data-act="edit"/g)||[]).length,3); + assert.match(html,/q-piece [^"]*is-unwearable is-editing"/); + assert.match(html,/title="Read as:\nDimensional Leap Lv\. \+1"/); + assert.match(html,/aria-label="Edit Hat: Dimensional Leap, White Hole, DMG"/); +}); + +test('best set shows the score, what is still missing and struck-through waste',async()=>{ + const {renderBest}=await import('../../web/pages/quanah.js'); + let html=renderBest(model()); + assert.match(html,/15 lines short/); + assert.match(html,/Still missing/); + const wasted=model();wasted.solution.used.hat=[true,false,true]; + html=renderBest(wasted); + assert.match(html,/is-wasted/); + assert.match(html,/Struck-through/); +}); + +test('GanDi job rule shows as one requirement of any 3 jobs',async()=>{ + const {requirementRows}=await import('../../web/pages/quanah.js'); + const m=model(); + m.solution={...m.solution,targets:{dl:3},counts:{dl:3,magician:1,thief:1,bowman:0},jobs:{count:3,keys:['magician','thief','bowman']}}; + const rows=requirementRows(m); + assert.deepEqual(rows.at(-1),{label:'Magician · Thief · Bowman',have:2,target:3,jobs:false}); + m.solution.jobs={count:3,keys:['warrior','magician','bowman','thief','pirate']}; + assert.equal(requirementRows(m).at(-1).jobs,true); +}); + +test('requirements are listed by lines needed, then in catalog order',async()=>{ + const {requirementRows}=await import('../../web/pages/quanah.js'); + const m=model(); + // As the server sends them: keys sorted alphabetically. + m.solution={...m.solution,jobs:null,counts:{},targets:{atk:3,bowman:1,crit:1,dl:3,magician:1,pirate:1,reg:3,thief:1,warrior:1,wh:3}}; + assert.deepEqual(requirementRows(m).map(r=>r.label), + ['Dimensional Leap','White Hole','Registry','ATK','Crit DMG','Warrior','Magician','Bowman','Thief','Pirate']); + m.solution={...m.solution,targets:{dl:3,crit:3},jobs:{count:3,keys:['magician','thief','bowman']}}; + assert.deepEqual(requirementRows(m).map(r=>r.label),['Dimensional Leap','Crit DMG','Magician · Thief · Bowman']); +}); + +test('items that are not Quanah pieces are counted as skipped, not failed',async()=>{ + const {scanSummary}=await import('../../web/pages/quanah.js'); + const s=scanSummary({done:['a'],pending:[],failed:{x:'Skipped HYPER BURNING MAX: not a Quanah piece',y:'Skill lines cut off'}}); + assert.equal(s.counts,'1 saved · 0 processing · 1 skipped · 1 failed'); + assert.deepEqual(s.skipped,['HYPER BURNING MAX']); + assert.deepEqual(s.failed,['Skill lines cut off']); + assert.equal(scanSummary({done:[],pending:['p'],failed:{}}).counts,'0 saved · 1 processing'); +}); + +test('a custom build with no targets asks for one instead of claiming a win',async()=>{ + const {renderBest}=await import('../../web/pages/quanah.js'); + const m=model();m.solution={...m.solution,goal:0,score:0,targets:{}}; + const html=renderBest(m); + assert.match(html,/Set at least one line target/); + assert.doesNotMatch(html,/Complete/); +}); + +test('Quanah opens from a pinned roster tile without a character',()=>{ + const app=fs.readFileSync(path.join(web,'app.js'),'utf8'); + const roster=fs.readFileSync(path.join(web,'roster.js'),'utf8'); + assert.match(app,/import \{mountQuanah\} from '\.\/pages\/quanah\.js'/); + // The Quanah branch runs before the no-character early return. + assert.ok(app.indexOf("page==='quanah'){") len(joined) + assert all(b - a <= ROW_MAX + 5 for a, b in split) + + +def test_wrapped_line_is_kept_whole(): + piece = vision.read_piece(cv2.imread(str(QUANAH / "top_comparison.png")), replay) + assert piece["raw"][0] == "[Hologram] Attack Power & Magic ATT Enhancement Skill Lv. +1" + + +@pytest.mark.parametrize("text, key", [ + ("Dimensional Leap Lv. +1", "dl"), + ("Dimensional Leap Lv.+1", "dl"), + ("White Hole Lv. +1", "wh"), + ("[Hologram] Registry Lv. +1", "reg"), + ("Hologram] Registry Lv. +1", "reg"), + ("[Hologram] Damage Enhancement Skill Lv. +1", "dmg"), + ("[Hologram] Attack Power & Magic ATT Enhancement Skill Lv. +1", "atk"), + ("Attack Power & Magic ATT Enhancement Skill Lv. +1", "atk"), + ("Critical Damage Enhancement Skill Lv. +1", "crit"), + ("[Hologram] Critical Damage Enhancement Skill Lv. +1", "crit"), + ("[Hologram] Warrior Attack Skill Lv. +1", "warrior"), + ("[Hologram] Warrior Attack Skill Level Lv. +1", "warrior"), + ("[Hologram] Bowman Attack Skill Level Lv. +1", "bowman"), + ("[Hologram] Magician Attack Skill Lv. +1", "magician"), + ("[Hologram] Bowman Attack Skill Lv. +1", "bowman"), + ("[Hologram] Thief Attack Skill Lv. +1", "thief"), + ("[Hologram] Pirate Attack Skill Lv. +1", "pirate"), + # A wrapped line's second row alone is not a skill line. + ("Skill Lv. +1", "other"), + ("Boss Damage +10%", "other"), + ("Ignored Enemy DEF +10%", "other"), + ("Some Future Skill Lv. +1", "other"), +]) +def test_match_line(text, key): + assert vision.match_line(text) == key + + +def test_section_joins_wrapped_rows_and_stops_at_scroll_enhancement(): + texts = ["Set Effect", "STR +60 (50 +10)", "Enemy DEF Ignored +5%", + "[Hologram] Attack Power & Magic ATT Enhancement", "Skill Lv. +1", + "Boss Damage +10%", "White Hole Lv. +1", "Scroll Enhancement None", "Dimensional Leap Lv. +1"] + assert vision.section(texts) == ([[3, 4], [5], [6]], True) + # Without the Scroll Enhancement row, the skill lines may continue off screen. + assert vision.section(texts[:7])[1] is False + + +def test_section_without_a_base_ied_row_starts_at_the_first_skill_line(): + texts = ["STR +60 (50 +10)", "Defense +418 (325 +93)", "White Hole Lv. +1", "Jewel Stats"] + assert vision.section(texts) == ([[2]], True) + + +def test_clean_name_drops_the_cursor_read_as_a_mark(): + assert vision.clean_name("_ibae's Supercharged Hat (Warrior)") == "ibae's Supercharged Hat (Warrior)" + assert vision.clean_name(" · [Hologram] Top") == "[Hologram] Top" + assert vision.clean_name("Libae's Supercharged Top (Warrior)") == "Libae's Supercharged Top (Warrior)" + + +def test_parse_name(): + assert vision.parse_name("Libae's Supercharged Hat (Warrior)") == ("hat", "warrior") + assert vision.parse_name("Libaes Supercharged Pants ( Bowman )") == ("bottom", "bowman") + assert vision.parse_name("Libae's Supercharged Cape (Magician") == ("cape", "magician") + assert vision.parse_name("Libae's Supercharged Ring (Thief)") is None + assert vision.parse_name("Heroic: Untradable") is None + assert vision.parse_name("Required Job Warrior") is None + assert vision.parse_name("Set Effect Libae's Supercharged Equipment Set") is None + + +def crop_key(crop): + return str(crop.shape) + hashlib.sha256(crop.tobytes()).hexdigest() + + +class Scripted: + """A reader answering by row, as read_piece finds them: NAME on the name row, LINES below Required Level.""" + + def __init__(self, image, name, lines, confidence=0.99): + x, search_top, level_y, bottom = vision.locate(image) + top = vision.tooltip_top(image, x, search_top, level_y) + rows = row_regions(image, x, top + 2, bottom - (4 if bottom == image.shape[0] else 12), split=True) + above = [r for r in rows if r[0] < level_y] + below = [r for r in rows if r[0] > level_y] + texts = {above[i]: ("Heroic: Untradable", 0.99) for i in range(len(above))} + texts[above[vision.name_rows(image, x, above)[0]]] = (name, 0.99) + for i, row in enumerate(below): + text = lines[i] if i < len(lines) else "" + texts[row] = (text, 0.99 if "Lv." not in text else confidence) + self.readings = {crop_key(row_crop(image, x, row)): t for row, t in texts.items()} + self.calls = [] + + def __call__(self, crops, use_cache=True): + self.calls.append(len(crops)) + if not use_cache: # A verification retry reads nothing better. + return [("", 0.0)] * len(crops) + return [self.readings[crop_key(c)] for c in crops] + + +IED, END = "Enemy DEF Ignored +5%", "Scroll Enhancement None" + + +def test_read_piece_with_other_lines(): + image, _, _ = comparison() + reader = Scripted(image, "Libae's Supercharged Hat (Warrior)", + ["STR +143", IED, "Dimensional Leap Lv. +1", "Boss Damage +10%", + "[Hologram] Damage Enhancement Skill Lv. +1", END, "Mystery Skill Lv. +1"]) + piece = vision.read_piece(image, reader) + assert piece["slot"] == "hat" and piece["item_class"] == "warrior" + assert piece["lines"] == ["dl", "other", "dmg"] + assert piece["raw"][1] == "Boss Damage +10%" + + +def test_reading_stops_at_scroll_enhancement(): + image, _, _ = comparison() + reader = Scripted(image, "Libae's Supercharged Hat (Warrior)", + [IED, "White Hole Lv. +1", END] + ["Jewel Stats"] * 20) + assert vision.read_piece(image, reader)["lines"] == ["wh"] + # The name row(s), then one batch: the rows after Scroll Enhancement are never read. + assert reader.calls[0] <= 2 and reader.calls[1:] == [vision.BATCH] + + +def test_other_items_are_turned_away_after_reading_the_name(): + reader = Scripted(cv2.imread(str(QUANAH / "medal_equipped.png")), "HYPER BURNING MAX", []) + with pytest.raises(ReadError, match="^Skipped HYPER BURNING MAX: not a Quanah piece$"): + vision.read_piece(cv2.imread(str(QUANAH / "medal_equipped.png")), reader) + assert reader.calls == [1] + + +def test_tooltip_top_ignores_windows_above_it(): + image = cv2.imread(str(QUANAH / "medal_equipped.png")) + x, search_top, level_y, _ = vision.locate(image) + # The inventory window above the medal's tooltip is not mistaken for its header. + assert search_top < vision.tooltip_top(image, x, search_top, level_y) == 151 + + +def test_read_piece_rejects_impossible_readings(): + image = frame() + for lines, message in [([IED, "Dimensional Leap Lv. +1", "Dimensional Leap Lv. +1", END], "Same line read twice"), + ([IED, END], "No skill lines found"), + ([IED] + ["White Hole Lv. +1"] * 4 + [END], "More than 3 lines read"), + ([IED, "White Hole Lv. +1"], "Skill lines cut off")]: + with pytest.raises(ReadError, match=message): + vision.read_piece(image, Scripted(image, "Libae's Supercharged Top (Thief)", lines)) + with pytest.raises(ReadError, match="^Skipped Arcane Umbra Hat: not a Quanah piece$"): + vision.read_piece(image, Scripted(image, "Arcane Umbra Hat", [IED, "White Hole Lv. +1", END])) + + +def test_uncertain_lines_are_not_guessed(): + image = frame() + with pytest.raises(ReadError, match=r"^Unclear line: White Hole Lv\. \+1$"): + vision.read_piece(image, Scripted(image, "Libae's Supercharged Top (Thief)", + [IED, "White Hole Lv. +1", END], confidence=0.5)) diff --git a/tools/record_quanah_fixtures.py b/tools/record_quanah_fixtures.py new file mode 100644 index 0000000..df222da --- /dev/null +++ b/tools/record_quanah_fixtures.py @@ -0,0 +1,44 @@ +"""Record OCR readings for the Quanah tooltip fixtures in tests/fixtures/quanah. + +Run after adding a screenshot there: every crop the reader asks about (including +verification retries) is read once with the real model and saved to +readings.json, so tests replay them without PaddleOCR. + + .venv/Scripts/python tools/record_quanah_fixtures.py +""" + +import hashlib +import json +import sys +from pathlib import Path + +import cv2 + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) +from flaming.vision import PaddleRecognizer # noqa: E402 +from quanah.vision import read_piece # noqa: E402 + +FIXTURES = ROOT / "tests/fixtures/quanah" + + +def key(crop): + return str(crop.shape) + hashlib.sha256(crop.tobytes()).hexdigest() + + +if __name__ == "__main__": + reader = PaddleRecognizer(str(ROOT / "models/PP-OCRv6_medium_rec")) + readings = {} + + def record(crops, use_cache=True): + rows = reader(crops, use_cache=use_cache) + for crop, row in zip(crops, rows, strict=True): + readings[key(crop)] = [row[0], float(row[1])] + return rows + + for path in sorted(FIXTURES.glob("*.png")): + try: + print(path.name, read_piece(cv2.imread(str(path)), record)) + except Exception as exc: # noqa: BLE001 - report every fixture + print(path.name, "ERROR", exc) + (FIXTURES / "readings.json").write_text(json.dumps(readings, indent=0, sort_keys=True), encoding="utf-8") diff --git a/web/app.js b/web/app.js index cde5aa6..4197276 100644 --- a/web/app.js +++ b/web/app.js @@ -13,6 +13,7 @@ import {mountScouter} from './pages/scouter.js'; import {watchScouterCompletion} from './scouter_completion.js'; import {mountHexa} from './pages/hexa.js'; import {mountBossing} from './pages/bossing.js'; +import {mountQuanah} from './pages/quanah.js'; import {mountUpdates} from './updates.js'; import {openGuide,openEquipmentGuide} from './guide.js'; import {mountEnhancement,flameIcon} from './enhancement.js'; @@ -38,10 +39,17 @@ async function render(){ const all=await api.get('/api/characters'); if(epoch!==renderEpoch)return; if(!all.profiles.some(p=>p.id===selected))selected=all.default_character; - roster.update(all.profiles,selected); + roster.update(all.profiles,selected,page==='quanah'?'quanah':null); document.querySelector('#character').innerHTML=all.profiles.map(p=>``).join(''); document.querySelector('#character').disabled=!all.profiles.length; document.querySelectorAll('[data-page]').forEach(b=>b.classList.toggle('btn-primary',b.dataset.page===page)); + // Quanah is seasonal and character-agnostic, so it opens even with no characters. + if(page==='quanah'){ + const host=document.createElement('div');view.replaceChildren(host); + const cleanup=await mountQuanah(host); + if(epoch!==renderEpoch)cleanup();else dispose=cleanup; + return; + } if(!selected){view.innerHTML='

Your characters, clearly measured.

Scan flames, potentials and character stats. Compare gains with Scouter.

Add your first character to begin.

';document.querySelector('#first-add').onclick=()=>document.querySelector('#add-dialog').showModal();return;} localStorage.setItem('hascone.scouter.character',selected); if(page==='home'){const host=document.createElement('div');view.replaceChildren(host);await mountHome(host,id=>navigate('equipment',id),async()=>{await render();if(selected)localStorage.setItem('hascone.character',selected);else{localStorage.removeItem('hascone.character');localStorage.removeItem('hascone.scouter.character');}});return;} @@ -115,7 +123,9 @@ async function navigate(nextPage,nextCharacter=selected,resultId=null){ view.beforeLeave=null;selected=nextCharacter;page=nextPage;scouterResult=resultId;localStorage.setItem('hascone.character',selected);await render();pageScroller().scrollTo({top:0,behavior:'instant'}); } document.querySelectorAll('[data-page]').forEach(b=>b.onclick=()=>navigate(b.dataset.page).catch(toast)); -document.querySelector('#character').onchange=e=>navigate(page==='home'?'equipment':page,e.target.value).catch(toast); +// Characters open their own pages; Home and seasonal pages fall back to Equipment. +const characterPage=()=>['home','quanah'].includes(page)?'equipment':page; +document.querySelector('#character').onchange=e=>navigate(characterPage(),e.target.value).catch(toast); document.querySelector('#home').onclick=()=>navigate('home').catch(toast); const settingsMenu=document.querySelector('#settings-menu'); window.addEventListener('blur',()=>{settingsMenu.open=false;}); @@ -128,7 +138,7 @@ document.querySelector('#add-cancel').onclick=()=>document.querySelector('#add-d document.querySelector('#add-form').onsubmit=async e=>{e.preventDefault();const b=document.querySelector('#add-submit');b.disabled=true;document.querySelector('#add-error').textContent='Looking up character…';try{const p=await api.post('/api/characters',{name:document.querySelector('#new-name').value});page='equipment';selected=p.id;localStorage.setItem('hascone.character',selected);document.querySelector('#add-dialog').close();await render();await openEquipmentGuide(selected,render);}catch(e){document.querySelector('#add-error').textContent=e.message;}finally{b.disabled=false;}}; window.addEventListener('scouter-guide',async e=>{try{page='scouter';await render();await openGuide(e.detail,await api.get('/api/characters/'+e.detail+'/steps'),render);}catch(e){toast(e.message);}}); window.addEventListener('character-selected',e=>{selected=e.detail;localStorage.setItem('hascone.character',selected);}); -const roster=mountRoster(id=>navigate(page==='home'?'equipment':page,id)); +const roster=mountRoster(id=>navigate(characterPage(),id),()=>navigate('quanah')); render().then(()=>watchScouterCompletion(async(character,resultId)=>{ if(page==='scouter'&&selected===character&&dispose?.showResult){ return dispose.showResult(resultId); diff --git a/web/pages/quanah.js b/web/pages/quanah.js new file mode 100644 index 0000000..a81de46 --- /dev/null +++ b/web/pages/quanah.js @@ -0,0 +1,255 @@ +import {api} from '../api.js'; +import {escapeHtml as esc,toast} from '../ui.js'; + +// Quanah: farm event pieces, scan or add them, and see the best 18-line set for a build. +const QUEUE='quanah'; + +export const lineName=(catalog,key)=>key==='other'?'Other':catalog.lines.find(l=>l.key===key)?.name||key; +const slotName=(catalog,key)=>catalog.slots.find(s=>s.key===key)?.name||key; +const className=(catalog,key)=>catalog.classes.find(c=>c.key===key)?.name||key; +const chip=(catalog,key,extra='')=>`${esc(lineName(catalog,key))}`; +const plural=(n,word)=>`${n} ${word}${n===1?'':'s'}`; + +// The lines this build targets, with their counts toward the goal, for the pips. +export function requirementRows(model){ + const {catalog,solution:s}=model,rows=Object.entries(s.targets).map(([key,target])=>({label:lineName(catalog,key),have:Math.min(s.counts[key]||0,target),target})); + if(s.jobs){ + const have=Math.min(s.jobs.count,s.jobs.keys.filter(k=>!(k in s.targets)&&s.counts[k]).length); + // "any" only when there are more jobs to pick from than the build needs. + rows.push({label:s.jobs.keys.map(k=>lineName(catalog,k)).join(' · '),have,target:s.jobs.count,jobs:s.jobs.keys.length>s.jobs.count}); + } + // Most lines needed first; ties keep the catalog's order (the server sorts target keys alphabetically). + const order=label=>{const i=catalog.lines.findIndex(l=>l.name===label);return i<0?catalog.lines.length:i;}; + return rows.sort((a,b)=>b.target-a.target||order(a.label)-order(b.label)); +} + +export function renderBest(model){ + const {catalog,solution:s}=model; + if(!s.goal)return `

Best set

Set at least one line target to see the best set.

`; + const byId=Object.fromEntries(model.items.map(i=>[i.id,i])); + const done=s.score>=s.goal; + const reqs=requirementRows(model).map(r=>`
${esc(r.label)}${r.jobs?` any ${r.target}`:''}${Array.from({length:r.target},(_,i)=>``).join('')}
`).join(''); + const wasted=Object.values(s.used).some(flags=>flags.includes(false)); + const set=catalog.slots.map(slot=>{ + const item=byId[s.picks[slot.key]]; + return `
  • ${esc(slot.name)}${item?`${item.lines.map((k,i)=>chip(catalog,k,s.used[slot.key][i]?'':'is-wasted')).join('')}`:'Nothing yet'}
  • `; + }).join(''); + let next=''; + if(!done){ + next=s.hunt.length + ?`
    One drop finishes it
      ${s.hunt.slice(0,8).map(h=>`
    • ${esc(slotName(catalog,h.slot))}${h.need.map(k=>chip(catalog,k)).join('')}
    • `).join('')}
    ${s.hunt.length>8?`

    and ${s.hunt.length-8} more options

    `:''}
    ` + :`
    Still missing

    ${s.missing.map(k=>chip(catalog,k)).join('')}

    More than one piece away. Keep farming.

    `; + } + return `
    +

    Best set

    ${done?'Complete':plural(s.goal-s.score,'line')+' short'}
    +

    ${s.score} of ${s.goal} lines${done?` · ${plural(s.ways,'winning combo')}`:''}

    +
    ${reqs}
    + Equip these
      ${set}
    + ${wasted?'

    Struck-through lines do not count toward this build.

    ':''} + ${next} +
    `; +} + +// Background reads: items that aren't Quanah pieces ("Skipped …") are listed apart from real failures. +export function scanSummary(queue){ + if(!queue)return {counts:'',skipped:[],failed:[]}; + const messages=Object.values(queue.failed||{}); + const skipped=messages.filter(m=>m.startsWith('Skipped ')).map(m=>m.slice(8).replace(/: not a Quanah piece$/,'')); + const failed=messages.filter(m=>!m.startsWith('Skipped ')); + const counts=[`${queue.done.length} saved`,`${queue.pending.length} processing`,skipped.length&&`${skipped.length} skipped`,failed.length&&`${failed.length} failed`].filter(Boolean).join(' · '); + return {counts,skipped,failed}; +} + +// Two columns, paired as the slots sit in the game: hat and cape, top and gloves, bottom and shoes. +export const GEAR_ORDER=['hat','cape','top','gloves','bottom','shoes']; +const pencil=''; + +export function renderGear(model,editing=null){ + const {catalog,solution:s}=model; + const picked=new Set(Object.values(s?.picks||{}).filter(Boolean)); + const slots=[...catalog.slots].sort((a,b)=>GEAR_ORDER.indexOf(a.key)-GEAR_ORDER.indexOf(b.key)); + return slots.map(slot=>{ + const pieces=model.items.filter(i=>i.slot===slot.key); + const rows=pieces.map(item=>{ + const flags=[!item.wearable&&`Can't wear · ${esc(className(catalog,item.item_class))}`, + item.duplicate&&'Duplicate'].filter(Boolean).join(''); + const read=item.raw?.length?`Read as:\n${item.raw.join('\n')}`:''; + const label=`${slot.name}: ${item.lines.map(k=>lineName(catalog,k)).join(', ')}`; + const source=item.source==='scan'?(item.edited?'Scanned, edited':'Scanned'):'Manual'; + return `
  • ${item.lines.map(k=>chip(catalog,k)).join('')}${flags}${source}
  • `; + }).join(''); + return `

    ${esc(slot.name)}

    ${plural(pieces.length,'piece')}
    ${rows?`
      ${rows}
    `:`

    No ${esc(slot.name.toLowerCase())} yet

    `}
    `; + }).join(''); +} + +export async function mountQuanah(root){ + // EDITING is the id of a saved piece loaded into the hand-entry panel, or null when adding. + let model,disposed=false,slot='hat',pending=[],confirmClear=false,editing=null; + let scanning=false,windows=[],selectedWindow=null,timer=0,known=new Set(),scanState=null,queue=null; + root.className='quanah-page'; + root.innerHTML='

    Loading Quanah...

    '; + const alive=()=>!disposed&&root.isConnected; + async function save(request){ + try{model=await request;remember();if(alive())draw();} + catch(error){toast(error.message);} + } + // Warn once about each newly scanned piece the player can't wear. + function remember(announce=false){ + for(const item of model.items){ + if(known.has(item.id))continue; + known.add(item.id); + if(announce&&!item.wearable)toast(`${item.name||'That piece'} is a ${className(model.catalog,item.item_class)} item. You can't wear it; don't spend resources on it.`); + } + } + + function classPicker(){ + return `

    Choose your class

    Event pieces are class-locked. Scanned pieces for another class are flagged so you don't spend resources on them.

    ${model.catalog.classes.map(c=>``).join('')}
    `; + } + + function buildPanel(){ + const {catalog,build}=model; + const tabs=catalog.builds.map(b=>``).join(''); + let options=''; + if(build.preset==='gandi'){ + const jobs=catalog.lines.filter(l=>l.job); + options=`
    + ${build.job_mode==='custom'?`
    ${jobs.map(j=>{const on=build.jobs.includes(j.key);return ``;}).join('')}

    ${build.jobs.length}/3 selected. Each needs 1 line.${build.jobs.length!==3?' Until 3 are chosen, Magician, Thief and Bowman are used.':''}

    `:'

    Any 3 different job lines count, 1 each.

    '}
    `; + }else if(build.preset==='custom'){ + const total=Object.values(build.targets).reduce((a,b)=>a+b,0); + options=`
    ${catalog.lines.map(l=>{const v=build.targets[l.key]||0;return `
    ${esc(l.name)}${v}
    `;}).join('')}

    ${total} of ${catalog.goal} lines targeted${total===catalog.goal?' (six pieces hold no more)':'.'}

    `; + } + return `

    Build

    ${tabs}
    ${options}
    `; + } + + function scanPanel(){ + const captured=scanState?.mode==='quanah'?scanState.captured||0:0; + const {counts:reads,skipped,failed}=scanSummary(queue); + const list=(items,cls)=>items.length?`
      ${items.slice(-3).map(m=>`
    • ${esc(m)}
    • `).join('')}
    `:''; + const failures=list(skipped,'is-skipped')+list(failed,'')+(failed.length?'

    Failed captures are kept in logs/quanah-failed.

    ':''); + return `

    Scan pieces

    ${scanning?'':''}
    +

    Hover each event piece in your inventory or Equipment. Every new tooltip is captured; reading happens in the background.

    +
    + +
    +

    ${esc(scanState?.message||'')}${scanning||captured?` · ${plural(captured,'capture')}`:''}

    + ${reads?`

    ${reads}

    `:''}${failures} +
    `; + } + + function addPanel(){ + const {catalog}=model,max=catalog.max_lines; + const buttons=[...catalog.lines.map(l=>l.key),'other'].map(k=>``).join(''); + const slots=catalog.slots.map(s=>``).join(''); + const picked=Array.from({length:max},(_,i)=>pending[i]?chip(catalog,pending[i]):`line ${i+1}`).join(''); + const piece=editing&&model.items.find(i=>i.id===editing); + const read=piece?.raw?.length?`

    Scanner read: ${piece.raw.map(esc).join(' · ')}

    `:''; + return `

    ${editing?'Edit piece':'Add a piece by hand'}

    ${read}
    ${slots}
    ${buttons}
    +
    ${editing?'Editing':'New'} ${esc(slotName(catalog,slot))}${picked} + ${pending.length?'':''} + ${editing?`` + :``}
    `; + } + function startEdit(id){ + const item=model.items.find(i=>i.id===id);if(!item)return; + editing=id;slot=item.slot;pending=[...item.lines];draw(); + const panel=root.querySelector('.q-add'); + panel?.scrollIntoView({block:'nearest',behavior:'smooth'}); + panel?.querySelector('[data-act="save-edit"]')?.focus({preventScroll:true}); + } + function stopEdit(){editing=null;pending=[];} + + function draw(){ + if(!alive())return; + // Keep keyboard focus on the same control across redraws. + const sig=el=>JSON.stringify(el.dataset),active=document.activeElement; + const focus=active&&root.contains(active)&&active.dataset.act?sig(active):null; + const head=`

    Quanah

    Seasonal event equipment. Find the one-per-slot set that completes your build's 18 skill lines.

    `; + if(!model.class){root.innerHTML=head+classPicker();return;} + if(editing&&!model.items.some(i=>i.id===editing))stopEdit(); + const total=model.items.length,dupes=model.items.filter(i=>i.duplicate).length,unwearable=model.items.filter(i=>!i.wearable).length; + root.innerHTML=`${head}
    ${buildPanel()}${scanPanel()}${addPanel()} +

    Your pieces (${total})

    ${total?``:''}
    + ${dupes||unwearable?`

    ${[dupes&&plural(dupes,'duplicate'),unwearable&&`${unwearable} you can't wear`].filter(Boolean).join(' · ')}. Fix a misread with the pencil, or delete with ×.

    `:''} +
    ${renderGear(model,editing)}
    +
    ${renderBest(model)}
    `; + if(focus)[...root.querySelectorAll('[data-act]')].find(el=>sig(el)===focus)?.focus({preventScroll:true}); + } + + const setBuild=build=>save(api.put('/api/quanah/settings',{build})); + + async function loadWindows(){ + try{windows=await api.get('/api/windows');}catch{windows=[];} + if(!windows.some(w=>w.id===selectedWindow))selectedWindow=windows[0]?.id??null; + } + + async function poll(){ + clearTimeout(timer); + if(!alive())return; + try{ + const [state,reads]=await Promise.all([api.get('/api/scan'),api.get('/api/scan/queue/'+QUEUE)]); + if(!alive())return; + const finished=reads.done.length!==(queue?.done.length??0); + scanState=state;queue=reads; + if(scanning&&!state.active){scanning=false;if(state.status==='error')toast(state.message);} + if(finished){model=await api.get('/api/quanah');remember(true);} + draw(); + if(scanning||reads.pending.length)timer=setTimeout(poll,700); + }catch(error){if(alive())timer=setTimeout(poll,2000);} + } + + async function startScan(){ + try{ + scanState=await api.post('/api/quanah/scan',{window:Number(selectedWindow)}); + scanning=true;draw();poll(); + }catch(error){toast(error.message);} + } + async function stopScan(){ + scanning=false; + try{scanState=await api.post('/api/scan/cancel',{release:true});}catch{} + poll(); + } + + root.addEventListener('click',e=>{ + const b=e.target.closest('[data-act]');if(!b||b.tagName==='SELECT')return; + const act=b.dataset.act,build=model.build; + if(act!=='clear')confirmClear=false; + if(act==='class')save(api.put('/api/quanah/settings',{class:b.dataset.class})); + else if(act==='preset')setBuild({preset:b.dataset.preset}); + else if(act==='job-mode')setBuild({job_mode:b.dataset.mode}); + else if(act==='job'){const k=b.dataset.job;setBuild({jobs:build.jobs.includes(k)?build.jobs.filter(j=>j!==k):[...build.jobs,k]});} + else if(act==='target'){const k=b.dataset.key,v=Math.max(0,Math.min(model.catalog.max_per_line,(build.targets[k]||0)+Number(b.dataset.step)));setBuild({targets:{...build.targets,[k]:v}});} + // Moving a piece being edited to another slot keeps its lines. + else if(act==='slot'){slot=b.dataset.slot;if(!editing)pending=[];draw();} + else if(act==='line'){pending.push(b.dataset.key);draw();} + else if(act==='undo'){pending.pop();draw();} + else if(act==='add'){const lines=pending;pending=[];save(api.post('/api/quanah/items',{slot,lines}));} + else if(act==='edit')startEdit(b.dataset.id); + else if(act==='cancel-edit'){stopEdit();draw();} + else if(act==='save-edit'){const id=editing,lines=pending;stopEdit();save(api.put('/api/quanah/items/'+encodeURIComponent(id),{slot,lines}));} + else if(act==='delete')save(api.delete('/api/quanah/items/'+encodeURIComponent(b.dataset.id))); + else if(act==='clear'){if(confirmClear){confirmClear=false;save(api.delete('/api/quanah/items'));}else{confirmClear=true;draw();}} + else if(act==='scan')startScan(); + else if(act==='stop')stopScan(); + else if(act==='windows')loadWindows().then(draw); + }); + root.addEventListener('change',e=>{ + const act=e.target.dataset.act; + if(act==='class-select')save(api.put('/api/quanah/settings',{class:e.target.value})); + else if(act==='window')selectedWindow=Number(e.target.value); + }); + + try{ + [model]=await Promise.all([api.get('/api/quanah'),loadWindows()]); + remember(); + // Pick up a scan still running from before this page was opened. + const state=await api.get('/api/scan'); + if(state.active&&state.mode==='quanah')scanning=true; + draw();poll(); + }catch(error){root.innerHTML=`

    ${esc(error.message)}

    `;} + + return ()=>{ + disposed=true;clearTimeout(timer); + // Leaving the page stops watching the game; captured pieces keep reading in the background. + if(scanning)api.post('/api/scan/cancel',{release:true}).catch(()=>{}); + }; +} diff --git a/web/roster.js b/web/roster.js index d8c5dd6..8977b24 100644 --- a/web/roster.js +++ b/web/roster.js @@ -3,13 +3,17 @@ import {escapeHtml as esc,toast} from './ui.js'; // A slim, permanent roster rail: one avatar per character, with details in its tooltip. // It docks beside the page; the tab on its edge minimises it to a strip that keeps Home. -export function mountRoster(onSelect){ +// Seasonal pages pinned above the characters, opened like a character tile. +const QUANAH='quanah'; +const quanahIcon=''; + +export function mountRoster(onSelect,onQuanah=()=>Promise.resolve()){ const rail=document.querySelector('#roster'); rail.innerHTML=`
    Roster
    `; const list=rail.querySelector('.roster-list'); const toggle=rail.querySelector('.roster-toggle'),count=rail.querySelector('.roster-count'); - let characters=[],stats={},selected=null,queues={},previous='',statsTimer=0,hidden=false; + let characters=[],stats={},selected=null,queues={},previous='',statsTimer=0,hidden=false,quanahOpen=false; try{hidden=localStorage.getItem('hascone.roster.hidden')==='1';}catch{} const label=key=>key.replaceAll('_',' ').replaceAll(':',' / '); function setHidden(value){ @@ -27,8 +31,16 @@ export function mountRoster(onSelect){ for(const [step,error] of Object.entries(q?.failed||{}))lines.push(`${label(step)}: ${error} Rescan this step.`); return lines.join('\n'); } + function quanahRow(){ + const q=queues[QUANAH],busy=!!q?.pending.length; + const text=['Quanah · event set solver',q&&(busy||q.done.length)?`${q.done.length} saved · ${q.pending.length} processing`:''].filter(Boolean).join('\n'); + return `
    `; + } function row(c){ - const q=queues[c.id],busy=!!q?.pending.length,failed=Object.keys(q?.failed||{}).length,current=c.id===selected; + const q=queues[c.id],busy=!!q?.pending.length,failed=Object.keys(q?.failed||{}).length,current=!quanahOpen&&c.id===selected; return `