Add Ship Routes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rope 2026-11-11 15:19:19 +00:00
parent 01a351a865
commit 63eebfc8bd
15 changed files with 1426 additions and 2 deletions

139
ShipRoutes/tools/casc.py Normal file
View file

@ -0,0 +1,139 @@
"""Minimal local CASC reader: extract files by FileDataID.
usage: python3 casc.py <WoW dir> <product> <outdir> <fdid> [fdid...]"""
import os, sys, struct, zlib
wow, product, outdir = sys.argv[1], sys.argv[2], sys.argv[3]
fdids = [int(a) for a in sys.argv[4:]]
data = os.path.join(wow, "Data")
# .build.info -> build key
lines = open(os.path.join(wow, ".build.info")).read().splitlines()
cols = [c.split("!")[0] for c in lines[0].split("|")]
build_key = None
for l in lines[1:]:
row = dict(zip(cols, l.split("|")))
if row.get("Product") == product:
build_key = row["Build Key"]
print("version", row["Version"], file=sys.stderr)
assert build_key, "product not found"
def cfg(key):
p = os.path.join(data, "config", key[:2], key[2:4], key)
out = {}
for l in open(p):
if " = " in l:
k, v = l.strip().split(" = ", 1)
out[k] = v.split()
return out
build = cfg(build_key)
# local indices: highest version per bucket
idx = {}
best = {}
for f in os.listdir(os.path.join(data, "data")):
if f.endswith(".idx"):
b, v = int(f[:2], 16), int(f[2:10], 16)
if b not in best or v > best[b][0]:
best[b] = (v, f)
for _, f in best.values():
raw = open(os.path.join(data, "data", f), "rb").read()
hsize = struct.unpack_from("<I", raw, 0)[0]
pos = (8 + hsize + 0x0F) & ~0x0F
esize = struct.unpack_from("<I", raw, pos)[0]
pos += 8
for i in range(esize // 18):
e = raw[pos + i * 18: pos + i * 18 + 18]
key = e[:9]
off = int.from_bytes(e[9:14], "big")
size = struct.unpack_from("<I", e, 14)[0]
idx.setdefault(key, (off >> 30, off & 0x3FFFFFFF, size))
def blte(b):
assert b[:4] == b"BLTE", b[:4]
hsize = struct.unpack_from(">I", b, 4)[0]
if hsize == 0:
chunks = [len(b) - 8]
pos = 8
else:
n = int.from_bytes(b[9:12], "big")
chunks = [struct.unpack_from(">I", b, 12 + i * 24)[0] for i in range(n)]
pos = hsize
out = bytearray()
for c in chunks:
ch = b[pos:pos + c]
pos += c
m = ch[:1]
if m == b"N":
out += ch[1:]
elif m == b"Z":
out += zlib.decompress(ch[1:])
elif m == b"E":
raise ValueError("encrypted chunk")
else:
raise ValueError("chunk mode %r" % m)
return bytes(out)
def read_ekey(ekey):
a, off, size = idx[ekey[:9]]
with open(os.path.join(data, "data", "data.%03d" % a), "rb") as fh:
fh.seek(off)
b = fh.read(size)
return blte(b[30:])
# encoding: ckey -> ekey
enc = read_ekey(bytes.fromhex(build["encoding"][1]))
assert enc[:2] == b"EN"
ck, ek = enc[3], enc[4]
cepage = struct.unpack_from(">H", enc, 5)[0] * 1024
cecount = struct.unpack_from(">I", enc, 9)[0]
espec = struct.unpack_from(">I", enc, 18)[0]
pos = 22 + espec + cecount * 32
ckey2ekey = {}
for p in range(cecount):
page = enc[pos + p * cepage: pos + (p + 1) * cepage]
q = 0
while q + 6 + ck <= len(page):
n = page[q]
if n == 0:
break
c = page[q + 6: q + 6 + ck]
ckey2ekey[c] = page[q + 6 + ck: q + 6 + ck + ek]
q += 6 + ck + ek * n
# root (MFST): fdid -> ckey (prefer enUS / all-locale)
root = read_ekey(ckey2ekey[bytes.fromhex(build["root"][0])])
assert root[:4] == b"TSFM", root[:4]
hs, ver = struct.unpack_from("<II", root, 4)
if hs == 0x18:
pos = hs
else:
ver, pos = 0, 12
want = set(fdids)
found = {}
while pos < len(root):
if ver >= 2:
n, locale, u1, u2 = struct.unpack_from("<IIII", root, pos)
u3 = root[pos + 16]
content = u1 | u2 | (u3 << 17)
pos += 17
else:
n, content, locale = struct.unpack_from("<III", root, pos)
pos += 12
deltas = struct.unpack_from("<%di" % n, root, pos)
pos += 4 * n
keys = root[pos: pos + 16 * n]
pos += 16 * n
if not (content & 0x10000000):
pos += 8 * n
fd = -1
for i, d in enumerate(deltas):
fd = fd + 1 + d
if fd in want and (locale & 0x2 or fd not in found):
found[fd] = keys[i * 16:(i + 1) * 16]
os.makedirs(outdir, exist_ok=True)
for fd in fdids:
b = read_ekey(ckey2ekey[found[fd]])
open(os.path.join(outdir, "%d.db2" % fd), "wb").write(b)
print(fd, len(b), b[:4], file=sys.stderr)

View file

@ -0,0 +1,182 @@
"""Builds ShipRoutes/Data.lua from the client's TaxiPathNode.db2 (FileDataID 1000437).
usage: python3 generate.py <TaxiPathNode.db2> <Data.lua>
Transports sail along TaxiPath node lists. The client has no record of which paths are
transports, so the paths and the dock names below are curated by hand. A path whose stops
don't match a known dock fails the run instead of guessing.
"""
import collections, math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from wdc5 import read, f32
# name, instance (map id), world x, world y
DOCKS = [
("Ratchet", 1, -1006, -3842),
("Booty Bay", 0, -14278, 583),
("Menethil Harbor", 0, -3905, -586),
("Menethil Harbor", 0, -3709, -575),
("Theramore Isle", 1, -4016, -4741),
("Rut'theran Village", 1, 8532, 1024),
("Auberdine", 1, 6594, 760),
("Auberdine", 1, 6406, 823),
("Auberdine", 1, 6548, 942),
("Southshore", 0, -1103, -555),
("Stormwind Harbor", 0, -8654, 1344),
("Feathermoon Stronghold", 1, -4197, 3287),
("The Forgotten Coast", 1, -4348, 2444),
("Steamwheedle Port", 1, -6933, -4951),
("Riverglades", 0, -8232, -5801),
("Grom'gol", 0, -12464, 232),
("Grom'gol", 0, -12407, 212),
("Orgrimmar", 1, 1361, -4631),
("Orgrimmar", 1, 1318, -4658),
("Undercity", 0, 2063, 235),
("Undercity", 0, 2062, 293),
("Dalaran", 0, 545, 424),
("Thunder Bluff", 1, -802, 367),
("Zephras Isle", 2991, 1848, 569),
("Zephras Isle", 2991, 1953, 1019),
]
# path id, noun, kind, faction (None = unknown)
# Path 295 (Menethil - Auberdine direct) is still in the file, but 11167 uses the same
# piers with a Southshore stop, so it is the one that sails in Forever.
ROUTES = [
(241, "Boat", "boat", "Neutral"),
(292, "Boat", "boat", "Alliance"),
(293, "Boat", "boat", "Alliance"),
(303, "Boat", "boat", "Alliance"),
(11167, "Boat", "boat", "Alliance"),
(11616, "Boat", "boat", "Alliance"),
(11391, "Boat", "boat", "Neutral"),
(285, "Zeppelin", "air", "Horde"),
(301, "Zeppelin", "air", "Horde"),
(302, "Zeppelin", "air", "Horde"),
(11398, "Airship", "air", None),
(11457, "Airship", "air", None),
]
TELEPORT = 0x1
def dock_name(m, x, y):
best = min((math.hypot(x - dx, y - dy), n) for n, dm, dx, dy in DOCKS if dm == m) if any(d[1] == m for d in DOCKS) else None
if not best or best[0] > 300:
raise SystemExit("no dock near %d %.0f %.0f" % (m, x, y))
return best[1]
def catmull(points, closed):
"""Subdivide a polyline along a uniform Catmull-Rom spline."""
n = len(points)
if n < 3:
return points
out = []
segs = n if closed else n - 1
for i in range(segs):
p0 = points[(i - 1) % n] if closed or i > 0 else points[i]
p1 = points[i]
p2 = points[(i + 1) % n]
p3 = points[(i + 2) % n] if closed or i + 2 < n else p2
steps = max(1, min(6, int(math.hypot(p2[0] - p1[0], p2[1] - p1[1]) // 60)))
for s in range(steps):
t = s / steps
t2, t3 = t * t, t * t * t
out.append(tuple(
0.5 * (2 * p1[k] + (-p0[k] + p2[k]) * t + (2 * p0[k] - 5 * p1[k] + 4 * p2[k] - p3[k]) * t2
+ (-p0[k] + 3 * p1[k] - 3 * p2[k] + p3[k]) * t3)
for k in (0, 1)))
if not closed:
out.append(points[-1])
return out
def build(path, nodes):
nodes = sorted(nodes) # (index, map, x, y, flags, delay)
n = len(nodes)
brk = [bool(nodes[i][4] & TELEPORT) or nodes[i][1] != nodes[(i + 1) % n][1] for i in range(n)]
closed = not any(brk)
start = 0 if closed else (brk.index(True) + 1) % n
order = nodes[start:] + nodes[:start]
brk = brk[start:] + brk[:start]
# stops in loop order, merging a stop that is split across the loop's seam
stops, stop_at = [], {}
for i, (_, m, x, y, _, delay) in enumerate(order):
if delay:
name = dock_name(m, x, y)
if stops and stops[-1][0] == name and stops[-1][1] == m:
stop_at[i] = len(stops) - 1
continue
stops.append((name, m, x, y))
stop_at[i] = len(stops) - 1
if len(stops) > 2 and stops[0][0] == stops[-1][0]:
stops.pop()
stop_at = {i: (s if s < len(stops) else 0) for i, s in stop_at.items()}
parts, cur = [], []
for i, node in enumerate(order):
cur.append(i)
if brk[i] or i == n - 1:
parts.append(cur)
cur = []
out_parts = []
for p in parts:
if len(p) < 2: # a lone node between two teleports draws nothing
continue
pts = catmull([(order[i][2], order[i][3]) for i in p], closed)
# first stop reached after this part ends, in loop order
nxt = None
for k in list(range(p[-1] + 1, n)) + list(range(0, p[-1] + 1)):
if k in stop_at:
nxt = stop_at[k]
break
out_parts.append({"m": order[p[0]][1], "pts": pts, "next": nxt})
return stops, out_parts, closed
def lua_str(s):
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
def main():
src, dst = sys.argv[1], sys.argv[2]
rows, _ = read(src)
paths = collections.defaultdict(list)
for r in rows:
loc, _id, p, idx, m, flags, delay, _a, _d = r["fields"]
paths[p].append((idx, m, f32(loc[0]), f32(loc[1]), flags, delay))
lines = [
"-- Generated by tools/generate.py from TaxiPathNode.db2. Do not edit by hand.",
"-- stops: { name, instance, worldX, worldY }",
"-- parts: sailed in order; a gap between parts is a teleport or a change of map.",
"-- next: index of the first stop reached after the part ends.",
"local _, ns = ...",
"ns.routes = {",
]
for path, noun, kind, faction in ROUTES:
if path not in paths:
raise SystemExit("path %d missing" % path)
stops, parts, closed = build(path, paths[path])
print(path, noun, " -> ".join(s[0] for s in stops), "%d parts" % len(parts), file=sys.stderr)
lines.append(" { path = %d, noun = %s, kind = %s, faction = %s, closed = %s," % (
path, lua_str(noun), lua_str(kind), lua_str(faction) if faction else "nil", "true" if closed else "false"))
lines.append(" stops = {")
for name, m, x, y in stops:
lines.append(" { %s, %d, %.1f, %.1f }," % (lua_str(name), m, x, y))
lines.append(" },")
lines.append(" parts = {")
for part in parts:
coords = ", ".join("%.0f, %.0f" % pt for pt in part["pts"])
lines.append(" { m = %d, next = %s, %s }," % (
part["m"], part["next"] + 1 if part["next"] is not None else "nil", coords))
lines.append(" },")
lines.append(" },")
lines.append("}")
open(dst, "w").write("\n".join(lines) + "\n")
main()

81
ShipRoutes/tools/icons.py Normal file
View file

@ -0,0 +1,81 @@
"""Draws the map marker textures as 64x64 white-on-transparent TGAs (tinted in game).
usage: python3 icons.py <Icons dir>"""
import math, os, struct, sys
N, SS = 64, 4 # size, supersampling
def seg_dist(px, py, ax, ay, bx, by):
dx, dy = bx - ax, by - ay
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)))
return math.hypot(px - ax - t * dx, py - ay - t * dy)
def in_tri(px, py, a, b, c):
def s(p, q, r):
return (p[0] - r[0]) * (q[1] - r[1]) - (q[0] - r[0]) * (p[1] - r[1])
d1, d2, d3 = s((px, py), a, b), s((px, py), b, c), s((px, py), c, a)
neg = d1 < 0 or d2 < 0 or d3 < 0
pos = d1 > 0 or d2 > 0 or d3 > 0
return not (neg and pos)
def disc(x, y):
return math.hypot(x - 32, y - 32) <= 30
def ring(x, y):
return 25.5 <= math.hypot(x - 32, y - 32) <= 30
def anchor(x, y):
if abs(math.hypot(x - 32, y - 13) - 4.5) <= 1.8: # eye
return True
if seg_dist(x, y, 32, 17, 32, 51) <= 2.2: # shank
return True
if seg_dist(x, y, 23, 23, 41, 23) <= 2.0: # stock
return True
r = math.hypot(x - 32, y - 33)
if y >= 33 and abs(r - 17) <= 2.2: # arms
return True
for side in (-1, 1): # flukes
if in_tri(x, y, (32 + side * 17, 30), (32 + side * 12, 38), (32 + side * 22, 38)):
return True
return False
def zeppelin(x, y):
if ((x - 34) / 21) ** 2 + ((y - 24) / 11) ** 2 <= 1: # envelope
return True
for a, b, c in (((15, 24), (6, 14), (12, 24)), ((15, 24), (6, 34), (12, 24))): # tail fins
if in_tri(x, y, a, b, c):
return True
if seg_dist(x, y, 9, 15, 9, 33) <= 2:
return True
if 26 <= x <= 42 and 40 <= y <= 47: # gondola
return True
if seg_dist(x, y, 29, 33, 29, 40) <= 1.3 or seg_dist(x, y, 39, 33, 39, 40) <= 1.3:
return True
return False
def arrow(x, y): # points right, rotated in game
if seg_dist(x, y, 12, 32, 44, 32) <= 4:
return True
return in_tri(x, y, (54, 32), (36, 18), (36, 46))
def write(path, fn):
px = bytearray()
for j in range(N):
for i in range(N):
hits = sum(fn(i + (a + 0.5) / SS, j + (b + 0.5) / SS) for a in range(SS) for b in range(SS))
alpha = round(255 * hits / (SS * SS))
px += bytes((255, 255, 255, alpha))
header = struct.pack("<BBBHHBHHHHBB", 0, 0, 2, 0, 0, 0, 0, 0, N, N, 32, 0x28)
open(path, "wb").write(header + px)
out = sys.argv[1]
for name, fn in (("disc", disc), ("ring", ring), ("anchor", anchor), ("zeppelin", zeppelin), ("arrow", arrow)):
write(os.path.join(out, name + ".tga"), fn)

96
ShipRoutes/tools/wdc5.py Normal file
View file

@ -0,0 +1,96 @@
"""Generic WDC5 reader: rows as {"id", "fields": [values...], "rel"}; floats left as raw u32."""
import struct
def read(path):
b = open(path, "rb").read()
assert b[:4] == b"WDC5", b[:4]
(rc, fc, rs, sts, th, lh, minid, maxid, loc) = struct.unpack_from("<9I", b, 136)
flags, id_index = struct.unpack_from("<HH", b, 172)
(tfc, bpo, lcc, fsis, cds, pds, sc) = struct.unpack_from("<7I", b, 176)
pos = 204
sections = []
for i in range(sc):
sections.append(struct.unpack_from("<Q8I", b, pos))
pos += 40
fstruct = [struct.unpack_from("<hH", b, pos + i * 4) for i in range(fc)]
pos += fc * 4
finfo = [struct.unpack_from("<HHIIIII", b, pos + i * 24) for i in range(fsis // 24)]
pos += fsis
pallet_start = pos
pos += pds
common_start = pos
pos += cds
# per-field pallet/common offsets
pal_off, com = [], []
po, co = pallet_start, common_start
for (fo, fs, ads, comp, v1, v2, v3) in finfo:
pal_off.append(po if comp in (3, 4) else None)
if comp in (3, 4):
po += ads
if comp == 2:
d = {}
for k in range(ads // 8):
i_, v_ = struct.unpack_from("<II", b, co + k * 8)
d[i_] = v_
com.append(d)
co += ads
else:
com.append(None)
# encrypted id lists
for s in sections:
if s[0] != 0:
n = struct.unpack_from("<I", b, pos)[0]
pos += 4 + 4 * n
rows = []
for (tact, off, src, ssz, ore, idls, rels, omc, ctc) in sections:
if tact != 0 and all(x == 0 for x in b[off:off + 16]):
continue
p = off
recs = b[p:p + src * rs]
p += src * rs + ssz
ids = list(struct.unpack_from("<%dI" % (idls // 4), b, p)) if idls else None
p += idls
copies = [struct.unpack_from("<II", b, p + k * 8) for k in range(ctc)]
p += ctc * 8 + omc * 6
rel = {}
if rels:
n = struct.unpack_from("<I", b, p)[0]
for k in range(n):
fid, ri = struct.unpack_from("<II", b, p + 12 + k * 8)
rel[ri] = fid
for r in range(src):
rec = int.from_bytes(recs[r * rs:(r + 1) * rs], "little")
vals = []
for f, (fo, fs, ads, comp, v1, v2, v3) in enumerate(finfo):
raw = (rec >> fo) & ((1 << fs) - 1)
if comp == 0:
n = max(1, fs // 32)
v = [(raw >> (32 * k)) & 0xFFFFFFFF for k in range(n)] if fs >= 32 else [raw]
vals.append(v if len(v) > 1 else v[0])
elif comp == 1:
vals.append(raw)
elif comp == 5:
vals.append(raw - (1 << fs) if raw >> (fs - 1) else raw)
elif comp == 2:
vals.append(None) # filled after id known
elif comp == 3:
vals.append(struct.unpack_from("<I", b, pal_off[f] + raw * 4)[0])
elif comp == 4:
vals.append(list(struct.unpack_from("<%dI" % v3, b, pal_off[f] + raw * 4 * v3)))
rid = ids[r] if ids else vals[id_index]
for f, (fo, fs, ads, comp, v1, v2, v3) in enumerate(finfo):
if comp == 2:
vals[f] = com[f].get(rid, v1)
rows.append({"id": rid, "fields": vals, "rel": rel.get(r), "base": off + r * rs, "b": b})
for new, old in copies:
src_row = next(x for x in rows if x["id"] == old)
rows.append(dict(src_row, id=new))
return rows, finfo
def f32(u):
return struct.unpack("<f", struct.pack("<I", u & 0xFFFFFFFF))[0]
def string(row, finfo, f):
b = row["b"]
p = row["base"] + finfo[f][0] // 8 + row["fields"][f]
return b[p:b.index(b"\0", p)].decode("utf8", "replace")