Files
TarkovMaps/tools/extract_markers.py
T

597 lines
25 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Extract semantic marker records from PSD layer metadata.
The PSD artwork is never composited. Visible leaf layers inside on-map marker
groups become normalized JSON records which the viewer renders with one shared
HTML/CSS style.
python tools/extract_markers.py
python tools/extract_markers.py customs woods
python tools/extract_markers.py --source-root C:/path/to/checkout
"""
from __future__ import annotations
from collections import Counter
import hashlib
import json
import re
import sys
from pathlib import Path
from psd_tools import PSDImage
from common import DATA, ROOT, find_map, load_config
CONTEXT = (
"overlay", "onmap", "on map", "map marker", "mapmarker",
"extractinformation", "extractnames", "extractmarkers",
)
EXCLUDED = (
"legend", "credit", "title section", "raid detail", "compass", "coloredmarkers",
"colored markers", "mapinfo", "duration", "sideindicator",
"side indicator", "extract letter overlay", "description", "requirement",
"only for bw", "onlyforbw",
)
LEAF_KINDS = {"type", "smartobject", "pixel"}
GENERIC = re.compile(
r"^(layer|group|shape|form|icon|marker|scav|boss|pmcspawn|player ?spawn|extractbg|"
r"cache|corpse|aiscav)(?:\s*\d+)?$",
re.IGNORECASE,
)
CATEGORY_LABELS = {
"extract-pmc": "PMC extract", "extract-scav": "Scav extract",
"extract-neutral": "Co-op extract", "extract-hidden": "Hidden extract",
"transit": "Transit", "spawn": "PMC spawn", "scav": "Scav area",
"boss": "Boss area", "cultist": "Cultist area", "sniper": "Sniper area",
"cache": "Cache", "key": "Key", "loot": "Loot", "hazard": "Hazard",
"quest": "Quest", "location": "Location", "poi": "Point of interest",
}
LABEL_CORRECTIONS = {
"holeinthefence": "HOLE IN THE FENCE",
"powerstation v-ex": "POWER STATION V-EX",
"pier boat": "PIER BOAT",
}
MAP_CATEGORY_OVERRIDES = {
("reserve", "sewer manhole"): "extract-pmc",
("ground-zero", "emercom checkpoint"): "extract-pmc",
}
EXTRACT_CATEGORIES = {
"extract-pmc", "extract-scav", "extract-neutral", "extract-hidden", "transit",
}
EXTRACT_PRIORITY = (
"extract-pmc", "extract-neutral", "extract-scav", "transit", "extract-hidden",
)
def highest_priority_extract_category(*categories: str | None) -> str | None:
available = {category for category in categories if category}
return next((category for category in EXTRACT_PRIORITY if category in available), None)
EXTRACT_LABEL_PATHS = (
"overlay captions", "extract name text / extract text pmc",
"extract name text / extract text scav", "extract name text / extract text neutral",
"extract name text / transit text", "onmap exfil names / text",
"onmap exfil names", "on map exfil names", "on-map extract names", "on map extract names",
"extract names smaller",
"new onmap / exfil names", "on map extract text", "extract names / pmc",
"extract names / scav", "extract names / neutral", "extract names / transit",
"on map overlay / extracts / text",
)
EXTRACT_LABEL_NOISE = (
"requires ", "req. ", "warning", "not always", "this extract",
"check legend", "approach exfil", "located in the sniper zone",
)
EXTRACT_ANCHOR_PATHS = (
"overlay pmc extracts", "overlay scav extracts", "overlay neutral",
"overlay transit", "overlay hidden", "extract dots", "onmap exfil icons",
"onmap extracts", "on map extracts", "pmc extract icons", "scav extract icons",
"transit / on map icons", "transit / on map letters",
"hidden / on map", "hidden / onmap",
"map markers / pmc extracts", "map markers / scav extracts",
"map markers / neutral extracts", "running man markers", "hidden exfil onmap",
"transit onmap", "on map overlay / extracts / pmc",
"on map overlay / extracts / scav", "on map overlay / extracts / transit",
"extract markers for bw",
)
def clean_name(value: str) -> str:
value = "".join(char if char.isprintable() else " " for char in value)
value = re.sub(r"\s+(?:copy|kopiera)(?:\s+\d+)?$", "", value, flags=re.IGNORECASE)
value = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", value)
value = value.replace("_", " ")
value = re.sub(r"\s+", " ", value).strip(" _-")
return value[:80]
def display_label(category: str, value: str) -> str:
value = clean_name(value)
lower = value.lower()
value = LABEL_CORRECTIONS.get(lower, value)
noisy = (not any(char.isalnum() for char in value)
or GENERIC.match(value)
or len(value) > 48
or lower.startswith(("layer ", "shape ", "form ", "ellipse ", "handpainted"))
or lower.startswith("read description")
or set(value) <= {".", " ", "•"})
if (category.startswith("extract-") or category == "transit") \
and 0 < len(value) <= 4 and any(c.isalnum() for c in value):
return value.upper()
if category in {"spawn", "cache", "loot"}:
return CATEGORY_LABELS[category]
if noisy:
return CATEGORY_LABELS.get(category, "Point of interest")
if category in EXTRACT_CATEGORIES:
return value.upper()
return value or CATEGORY_LABELS.get(category, "Point of interest")
def category_for(path: tuple[str, ...]) -> str | None:
# Normalize camel-case PSD group names (OnMapLetters, ExfilNames, etc.)
# before matching. Newer re3mr files use these spellings extensively.
text = normalized_path(path)
excluded = [term for term in EXCLUDED if term != "legend" and not (
term in {"only for bw", "onlyforbw"} and "extractmarkersforbw" in text.replace(" ", "")
)]
if any(term in text for term in excluded):
return None
# Several real on-map icons retain source names such as PMCLegend copy.
# Exclude legend artwork by location, not merely by a leaf-name fragment.
if "legend" in text and not any(term in text for term in EXTRACT_ANCHOR_PATHS):
return None
if not any(term in text for term in CONTEXT):
return None
if "extract" in text or "exfil" in text:
if "transit" in text:
return "transit"
if "co-op" in text or "coop" in text or "neutral" in text:
return "extract-neutral"
if "hidden" in text:
return "extract-hidden"
if "scav" in text:
return "extract-scav"
return "extract-pmc"
if "overlay captions" in text:
if "scav" in text:
return "extract-scav"
if "hidden" in text:
return "extract-hidden"
if "neutral" in text:
return "extract-neutral"
if "pmc" in text:
return "extract-pmc"
if "overlay neutral" in text:
return "extract-neutral"
if "overlay hidden" in text:
return "extract-hidden"
if "transit" in text:
return "transit"
if "player spawn" in text or "playerspawn" in text or "pmcspawn" in text or "pmc spawn" in text:
return "spawn"
if "sniper" in text:
return "sniper"
if any(term in text for term in ("boss", "glukhar", "killa", "sanitar", "goons")):
return "boss"
if "cultist" in text:
return "cultist"
if "scav" in text:
return "scav"
if "cache" in text or "stash" in text:
return "cache"
if "key" in text:
return "key"
if any(term in text for term in ("corpse", "loot", "gun")):
return "loot"
if any(term in text for term in ("mine", "deathzone", "border")):
return "hazard"
if "quest" in text:
return "quest"
if any(term in text for term in ("location", "caption", "house name", "housename", "room")):
return "location"
if any(term in text for term in ("poi", "point of interest", "note", "address")):
return "poi"
return None
def normalized_path(path: tuple[str, ...]) -> str:
return " / ".join(clean_name(part).lower().replace("_", " ") for part in path)
def is_extract_label_path(path: tuple[str, ...], label: str) -> bool:
text = normalized_path(path)
return (any(term in text for term in EXTRACT_LABEL_PATHS)
and not label.lower().startswith(EXTRACT_LABEL_NOISE))
def explicit_extract_category(path: tuple[str, ...], label: str) -> str | None:
lower_label = label.lower()
if ("smuggler" in lower_label and "basement" in lower_label) \
or "passage by the lake" in lower_label \
or "ariadne’s path" in lower_label \
or "ariadne's path" in lower_label:
return "extract-hidden"
label_category = None
if any(term in lower_label for term in ("co-op", "coop")) \
or any(term in lower_label for term in (
"scav camp", "factory gate", "scav lands", "emercom checkpoint",
"railway exfil", "armored train", "bunker hermetic door",
"road to customs", "smuggler’s path", "smuggler's path",
)):
label_category = "extract-neutral"
# Walk from the leaf upward so a direct PMC/SCAV subgroup wins over a
# broad ancestor such as Shoreline's "Hidden + Transit" container.
path_category = None
for raw_part in reversed(path):
part = clean_name(raw_part).lower().replace("_", " ")
words = set(re.findall(r"[a-z]+", part))
if "neutral" in words or ("pmc" in words and "scav" in words):
path_category = "extract-neutral"
break
if part in {"scav", "scav extracts", "extract dots scav", "extract dot scav"}:
path_category = "extract-scav"
break
if part in {"pmc", "pmc extracts", "extract dots pmc", "extract dot pmc"}:
path_category = "extract-pmc"
break
if part in {"hidden", "hidden exfil", "hidden exfil onmap"}:
path_category = "extract-hidden"
break
if part in {"transit", "transits", "transit dots", "transit onmap"}:
path_category = "transit"
break
return highest_priority_extract_category(path_category, label_category)
def semantic_path_label(path: tuple[str, ...], category: str) -> str:
ignored = {
"all", "icons", "main", "letters", "text", "pmc", "scav", "neutral", "hidden",
"transit", "extracts", "extract dots", "extract dot pmc", "extract dots scav",
"extract dots neutral", "transit dots", "onmap", "overlay", "overlays",
"markers", "map overlay", "running man markers", "on map extracts",
"on map extract information",
"pmc small markers", "scav small markers", "pmc extract icons", "scav extract icons",
"neutral extracts", "pmc extracts", "scav extracts",
"transit letters", "transit onmap", "hidden+transit", "re3mr.com",
}
for part in reversed(path[:-1]):
label = clean_name(part)
normalized = label.lower().replace("_", " ")
if normalized in ignored or any(term in normalized for term in ("copy", "background")):
continue
if normalized.startswith(("overlay ", "onmap ", "extract", "map marker")):
continue
if len(label) > 2:
return display_label(category, label)
return CATEGORY_LABELS[category]
def point_segment_distance(px: float, py: float, ax: float, ay: float,
bx: float, by: float) -> float:
dx, dy = bx - ax, by - ay
if dx == 0 and dy == 0:
return ((px - ax) ** 2 + (py - ay) ** 2) ** 0.5
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)))
qx, qy = ax + t * dx, ay + t * dy
return ((px - qx) ** 2 + (py - qy) ** 2) ** 0.5
def inside_playable(m: dict, x: float, y: float, margin: float = 0.018) -> bool:
points = m.get("trim", {}).get("points", [])
if len(points) < 3:
return True
inside = False
for index, (xi, yi) in enumerate(points):
xj, yj = points[index - 1]
if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / (yj - yi) + xi:
inside = not inside
if point_segment_distance(x, y, xi, yi, xj, yj) <= margin:
return True
return inside
def cluster_candidates(candidates: list[dict], radius: float) -> list[dict]:
clusters: list[list[dict]] = []
for candidate in sorted(candidates, key=lambda item: -item["score"]):
cluster = next((items for items in clusters
if items[0]["category"] == candidate["category"]
and (sum(item["x"] for item in items) / len(items) - candidate["x"]) ** 2
+ (sum(item["y"] for item in items) / len(items) - candidate["y"]) ** 2
< radius ** 2), None)
if cluster is None:
clusters.append([candidate])
else:
cluster.append(candidate)
result = []
for items in clusters:
best = max(items, key=lambda item: item["score"])
result.append({
**best,
"x": sum(item["x"] for item in items) / len(items),
"y": sum(item["y"] for item in items) / len(items),
})
return result
def anchor_matches_label(anchor_label: str, label: str) -> bool:
ignored = {"extract", "exfil", "transit", "to", "of", "tarkov", "v", "ex"}
anchor_words = set(re.findall(r"[a-z0-9]+", anchor_label.lower())) - ignored
label_words = set(re.findall(r"[a-z0-9]+", label.lower())) - ignored
if anchor_words and anchor_words <= label_words:
return True
compact_anchor = re.sub(r"[^a-z0-9]", "", anchor_label.lower())
compact_label = re.sub(r"[^a-z0-9]", "", label.lower())
return len(compact_anchor) >= 5 and compact_anchor in compact_label
def layer_text(layer) -> str:
if layer.kind == "type":
try:
text = clean_name(layer.text)
if text:
return text
except Exception: # noqa: BLE001 - malformed text engine data is common
pass
return clean_name(layer.name)
def marker_score(layer, label: str) -> int:
score = {"type": 4, "smartobject": 3, "pixel": 2}.get(layer.kind, 0)
if label and not GENERIC.match(label):
score += 3
if len(label) <= 30:
score += 1
return score
def source_path(m: dict, source_root: Path | None) -> Path:
local = ROOT / m["psd"]
if local.exists():
return local
if source_root:
fallback = source_root / m["psd"]
if fallback.exists():
return fallback
raise FileNotFoundError(f"{m['psd']} is unavailable")
def extract_map(m: dict, source_root: Path | None) -> list[dict]:
path = source_path(m, source_root)
print(f"[{m['id']}] reading marker metadata from {path.name}")
psd = PSDImage.open(path)
crop = m.get("crop") or [0, 0, psd.width, psd.height]
left, top, right, bottom = map(float, crop)
width, height = right - left, bottom - top
candidates: list[dict] = []
extract_labels: list[dict] = []
extract_anchors: list[dict] = []
def walk(node, prefix: tuple[str, ...], ancestors_visible: bool) -> None:
for layer in node:
visible = ancestors_visible and layer.visible
layer_path = prefix + (layer.name,)
if layer.is_group():
walk(layer, layer_path, visible)
continue
if not visible or layer.kind not in LEAF_KINDS:
continue
category = category_for(layer_path)
if not category:
continue
x0, y0, x1, y1 = map(float, layer.bbox)
if x1 <= x0 or y1 <= y0:
continue
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
if not (left <= cx <= right and top <= cy <= bottom):
continue
# Very large leaves are region overlays or artwork, not point data.
# Text labels can legitimately be wider on tightly cropped maps
# (Ground Zero's extract names take up roughly a quarter-width).
max_width = width * (0.32 if layer.kind == "type" else 0.16)
if x1 - x0 > max_width or y1 - y0 > height * 0.16:
continue
label = layer_text(layer)
if label in {"☠", "☢"}:
category = "hazard"
record = {
"x": (cx - left) / width,
"y": (cy - top) / height,
"category": category,
"label": display_label(category, label),
"source": "/".join(layer_path),
"score": marker_score(layer, label),
}
if category in EXTRACT_CATEGORIES:
path_text = normalized_path(layer_path)
label_context = any(term in path_text for term in EXTRACT_LABEL_PATHS)
if label_context:
if layer.kind != "type" or not is_extract_label_path(layer_path, label):
continue
explicit = explicit_extract_category(layer_path, label)
explicit = MAP_CATEGORY_OVERRIDES.get(
(m["id"], clean_name(label).lower()), explicit,
)
record["explicitCategory"] = explicit
if explicit:
record["category"] = explicit
record["label"] = display_label(record["category"], label)
extract_labels.append(record)
else:
if not any(term in path_text for term in EXTRACT_ANCHOR_PATHS):
continue
# Some PSDs place PMC and Scav marker groups inside a broad
# "Hidden + Transit" parent. Prefer the closest semantic
# group over that inherited parent-folder wording.
explicit = explicit_extract_category(layer_path, label)
if explicit:
record["category"] = explicit
leaf_label = display_label(record["category"], label)
if layer.kind == "type" and len(clean_name(label)) > 4 \
and not GENERIC.match(clean_name(label)):
record["label"] = leaf_label
else:
record["label"] = semantic_path_label(layer_path, record["category"])
extract_anchors.append(record)
else:
candidates.append(record)
walk(psd, (), True)
# PSD extracts are usually represented twice: a semantic text label and a
# nearby icon made from several leaves. Cluster the icon components, then
# pair each visible on-map name with its nearest compatible icon. This
# keeps the exact extract position and readable name without duplicating
# the background, letter, caption and side-indicator layers.
anchors = cluster_candidates(extract_anchors, 0.01)
used_anchors: set[int] = set()
extracts: list[dict] = []
unmatched_labels = set(range(len(extract_labels)))
# Assign globally closest pairs first. A top-to-bottom greedy pass can
# steal a nearby icon from the correct label on dense maps such as Shoreline.
pairs = []
for label_index, label in enumerate(extract_labels):
explicit = label.get("explicitCategory")
special_neutral = explicit == "extract-neutral" and any(
term in label["label"].lower() for term in ("co-op", "coop", "scav camp", "factory gate", "scav lands")
)
for anchor_index, anchor in enumerate(anchors):
if explicit is not None and not special_neutral and anchor["category"] != explicit:
continue
distance = ((anchor["x"] - label["x"]) ** 2
+ (anchor["y"] - label["y"]) ** 2)
if distance <= 0.12 ** 2:
pairs.append((distance, label_index, anchor_index))
for _, label_index, anchor_index in sorted(pairs):
if label_index not in unmatched_labels or anchor_index in used_anchors:
continue
label = extract_labels[label_index]
anchor = anchors[anchor_index]
explicit = label.get("explicitCategory")
unmatched_labels.remove(label_index)
used_anchors.add(anchor_index)
anchor_is_playable = inside_playable(m, anchor["x"], anchor["y"])
extracts.append({
**label,
"x": anchor["x"] if anchor_is_playable else label["x"],
"y": anchor["y"] if anchor_is_playable else label["y"],
"category": highest_priority_extract_category(explicit, anchor["category"])
or anchor["category"],
})
for label_index in sorted(unmatched_labels):
extracts.append(extract_labels[label_index])
# A shared gate can carry overlapping PMC and Scav icons. Once its label
# is paired, fold any nearly coincident unused icon into that record and
# apply the configured extract priority instead of emitting a duplicate.
# Explicit co-op extracts remain neutral/yellow by design.
for anchor_index, anchor in enumerate(anchors):
if anchor_index in used_anchors:
continue
nearby = next((record for record in extracts
if record["category"] != "extract-neutral"
and (record["x"] - anchor["x"]) ** 2
+ (record["y"] - anchor["y"]) ** 2 < 0.02 ** 2), None)
if nearby is None:
continue
nearby["category"] = highest_priority_extract_category(
nearby["category"], anchor["category"],
) or nearby["category"]
used_anchors.add(anchor_index)
unmatched = [anchor for index, anchor in enumerate(anchors) if index not in used_anchors]
unmatched_by_name: dict[tuple[str, str], dict] = {}
for anchor in unmatched:
if m["id"] == "factory" and anchor["category"] == "extract-hidden":
anchor["label"] = "SMUGGLER’S PASSAGE"
if anchor["label"] == CATEGORY_LABELS[anchor["category"]]:
continue
if any(anchor_matches_label(anchor["label"], label["label"])
for label in extract_labels):
continue
key = (anchor["category"], anchor["label"].lower())
existing = unmatched_by_name.get(key)
if existing is None or anchor["source"].lower().count("copy") \
< existing["source"].lower().count("copy"):
unmatched_by_name[key] = anchor
extracts.extend(unmatched_by_name.values())
icon_summary = ", ".join(
f"{category}={count}" for category, count in sorted(Counter(
anchor["category"] for anchor in anchors
).items())
)
print(f"[{m['id']}] reconciled {len(extract_labels)} extract label(s) "
f"with {len(anchors)} icon cluster(s) ({icon_summary or 'none'}) "
f"into {len(extracts)} marker(s)")
# Non-extract icons still commonly contain a background, glyph and label.
# A slightly larger visual cluster removes those redundant leaves.
if m.get("parent"):
extracts = []
kept = cluster_candidates(candidates, 0.006) + extracts
kept = [item for item in kept if inside_playable(m, item["x"], item["y"])]
for marker in kept:
marker.pop("score", None)
marker.pop("explicitCategory", None)
kept.sort(key=lambda item: (item["category"], item["y"], item["x"]))
used_ids: set[str] = set()
for marker in kept:
seed = f"{marker['source']}|{marker['category']}|{marker['x']:.5f}|{marker['y']:.5f}"
digest = hashlib.sha1(seed.encode("utf-8")).hexdigest()[:12]
marker_id = f"{m['id']}-{digest}"
suffix = 2
while marker_id in used_ids:
marker_id = f"{m['id']}-{digest}-{suffix}"
suffix += 1
used_ids.add(marker_id)
marker["id"] = marker_id
marker["mapId"] = m["id"]
print(f"[{m['id']}] extracted {len(kept)} marker(s)")
return kept
def main(argv: list[str]) -> None:
source_root = None
if "--source-root" in argv:
index = argv.index("--source-root")
try:
source_root = Path(argv[index + 1]).resolve()
except IndexError as exc:
raise SystemExit("--source-root needs a path") from exc
del argv[index:index + 2]
cfg = load_config()
targets = [find_map(cfg, map_id) for map_id in argv] if argv else cfg.maps
destination_dir = DATA / "markers"
destination_dir.mkdir(parents=True, exist_ok=True)
written = 0
errors = []
for m in targets:
try:
markers = extract_map(m, source_root)
for marker in markers:
marker["label"] = display_label(marker["category"], marker.get("label", ""))
markers.sort(key=lambda item: (item["category"], item["id"]))
destination = destination_dir / f"{m['id']}.json"
destination.write_text(json.dumps({
"version": 2,
"mapId": m["id"],
"markers": markers,
}, indent=2) + "\n", encoding="utf-8")
written += len(markers)
print(f"wrote {destination.relative_to(ROOT)} with {len(markers)} marker(s)")
except Exception as exc: # noqa: BLE001
errors.append(f"{m['id']}: {exc}")
print(f"[{m['id']}] SKIPPED: {exc}")
print(f"wrote {written} marker(s) across {len(targets) - len(errors)} map file(s)")
if errors:
print("skipped maps: " + "; ".join(errors))
if __name__ == "__main__":
main(sys.argv[1:])