257 lines
12 KiB
Python
257 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Rebuild the quest objective areas of the QPOI dataset from the server's real spawns.
|
|
|
|
quest_poi_from_spawns.py <old dataset .hpp|.bin> <out dataset .bin> [--report report.json]
|
|
|
|
The pinned W16 dataset carries Blizzard's hand-drawn Classic areas; on Turtle they cover places where nothing spawns
|
|
and miss real camps (owner 2026-11-27, Wildkin E'ko). This rebuilds every objective area (storage 0-7) from tw_world:
|
|
|
|
* kill/use objectives (ReqCreatureOrGOId1-4 -> storage 0-3): spawns of that creature (id..id4) or gameobject;
|
|
* item objectives (ReqItemId1-4 -> storage 4-7): spawns of every creature whose loot (incl. one reference level)
|
|
drops the item, and of every gameobject whose loot does;
|
|
* spawns are clustered per map (single linkage, LINK yards); each cluster becomes a convex hull padded by PAD yards,
|
|
at most 12 points (the dataset/native limit), z = mean spawn height;
|
|
* giver (32), turn-in (-1) and exploration (-2) points stay as they are; an objective without any server spawn keeps
|
|
its old areas (scripted objectives);
|
|
* UiMap of a new area = UiMap of the nearest old point on the same map (all 6538 quests' areas cover every zone).
|
|
|
|
Writes the same QPOI v1 layout the gateway parses (include/gateway/quest_poi_dataset.hpp). DB access goes through
|
|
the twq.sh wrapper given in $TWQ (prints tab-separated rows).
|
|
"""
|
|
import argparse, json, math, os, re, struct, subprocess, sys
|
|
from collections import defaultdict
|
|
|
|
LINK = 90.0 # yards: spawns closer than this belong to one camp
|
|
PAD = 18.0 # yards around the outermost spawns
|
|
MAX_POINTS = 12
|
|
MAX_BLOBS = 128
|
|
|
|
|
|
def load_dataset(path):
|
|
raw = open(path, 'rb').read()
|
|
if path.endswith('.hpp'):
|
|
s = raw.decode(); i = s.find('{')
|
|
raw = bytes(int(n) for n in re.findall(r'\d+', s[i:s.rfind('}')]))
|
|
sig, ver, count = struct.unpack_from('<III', raw, 0)
|
|
if sig != 0x494f5051 or ver != 1:
|
|
raise SystemExit('not a QPOI v1 dataset')
|
|
idx = [struct.unpack_from('<II', raw, 12 + 8 * i) for i in range(count)]
|
|
data = raw[12 + 8 * count:]
|
|
out = {}
|
|
for k, (qid, off) in enumerate(idx):
|
|
end = idx[k + 1][1] if k + 1 < count else len(data)
|
|
p = off; n, = struct.unpack_from('<H', data, p); p += 2; blobs = []
|
|
for _ in range(n):
|
|
obj, blob, flags, pts = struct.unpack_from('<bBBB', data, p); p += 4
|
|
o, m, ui = struct.unpack_from('<iHH', data, p); p += 8
|
|
P = [struct.unpack_from('<hhh', data, p + 6 * j) for j in range(pts)]; p += 6 * pts
|
|
blobs.append(dict(objective=obj, blob=blob, flags=flags, object=o, map=m, uimap=ui, points=P))
|
|
if p != end:
|
|
raise SystemExit('dataset record %d length mismatch' % qid)
|
|
out[qid] = blobs
|
|
return out
|
|
|
|
|
|
def write_dataset(records, path):
|
|
body = bytearray(); index = []
|
|
for qid in sorted(records):
|
|
blobs = records[qid]
|
|
if not blobs:
|
|
continue
|
|
index.append((qid, len(body)))
|
|
body += struct.pack('<H', len(blobs))
|
|
for b in blobs:
|
|
body += struct.pack('<bBBB', b['objective'], b['blob'], b['flags'], len(b['points']))
|
|
body += struct.pack('<iHH', b['object'], b['map'], b['uimap'])
|
|
for x, y, z in b['points']:
|
|
body += struct.pack('<hhh', x, y, z)
|
|
head = struct.pack('<III', 0x494f5051, 1, len(index)) + b''.join(struct.pack('<II', q, o) for q, o in index)
|
|
open(path, 'wb').write(head + bytes(body))
|
|
return len(index)
|
|
|
|
|
|
def query(sql):
|
|
out = subprocess.run([os.environ['TWQ'], sql], capture_output=True, text=True, check=True).stdout
|
|
return [line.split('\t') for line in out.splitlines() if line.strip()]
|
|
|
|
|
|
def hull(points):
|
|
pts = sorted(set(points))
|
|
if len(pts) <= 2:
|
|
return pts
|
|
def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
|
|
lower, upper = [], []
|
|
for p in pts:
|
|
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0: lower.pop()
|
|
lower.append(p)
|
|
for p in reversed(pts):
|
|
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0: upper.pop()
|
|
upper.append(p)
|
|
return lower[:-1] + upper[:-1]
|
|
|
|
|
|
def area_shape(points):
|
|
"""Padded convex outline (<= MAX_POINTS vertices) around one camp's spawns."""
|
|
ring = []
|
|
for x, y in points: # pad: an octagon around each spawn, then the hull of all of them
|
|
for k in range(8):
|
|
a = math.pi * k / 4
|
|
ring.append((x + PAD * math.cos(a), y + PAD * math.sin(a)))
|
|
h = hull(ring)
|
|
while len(h) > MAX_POINTS: # drop the vertex whose removal loses the least area
|
|
best, bi = None, 0
|
|
for i in range(len(h)):
|
|
a, b, c = h[i - 1], h[i], h[(i + 1) % len(h)]
|
|
loss = abs((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]))
|
|
if best is None or loss < best: best, bi = loss, i
|
|
h.pop(bi)
|
|
return h
|
|
|
|
|
|
def clusters(points):
|
|
"""Single-linkage camps (grid buckets keep it linear)."""
|
|
cell = LINK; grid = defaultdict(list)
|
|
for i, (x, y, z) in enumerate(points):
|
|
grid[(int(x // cell), int(y // cell))].append(i)
|
|
seen = [False] * len(points); out = []
|
|
for s in range(len(points)):
|
|
if seen[s]: continue
|
|
seen[s] = True; stack = [s]; group = []
|
|
while stack:
|
|
i = stack.pop(); group.append(points[i]); x, y, _ = points[i]
|
|
gx, gy = int(x // cell), int(y // cell)
|
|
for dx in (-1, 0, 1):
|
|
for dy in (-1, 0, 1):
|
|
for j in grid.get((gx + dx, gy + dy), ()):
|
|
if not seen[j] and (points[j][0] - x) ** 2 + (points[j][1] - y) ** 2 <= LINK * LINK:
|
|
seen[j] = True; stack.append(j)
|
|
out.append(group)
|
|
return out
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
ap.add_argument('old'); ap.add_argument('out'); ap.add_argument('--report')
|
|
a = ap.parse_args()
|
|
old = load_dataset(a.old)
|
|
|
|
# UiMap oracle: every old point, per map
|
|
oracle = defaultdict(list)
|
|
for blobs in old.values():
|
|
for b in blobs:
|
|
for x, y, _ in b['points']:
|
|
oracle[b['map']].append((x, y, b['uimap']))
|
|
grid = {m: defaultdict(list) for m in oracle}
|
|
for m, pts in oracle.items():
|
|
for x, y, u in pts:
|
|
grid[m][(int(x // 500), int(y // 500))].append((x, y, u))
|
|
def uimap_at(m, x, y):
|
|
g = grid.get(m)
|
|
if not g: return None
|
|
gx, gy = int(x // 500), int(y // 500)
|
|
for r in range(0, 4): # up to ~2000 yards
|
|
best = None
|
|
for dx in range(-r, r + 1):
|
|
for dy in range(-r, r + 1):
|
|
if max(abs(dx), abs(dy)) != r: continue
|
|
for px, py, u in g.get((gx + dx, gy + dy), ()):
|
|
d = (px - x) ** 2 + (py - y) ** 2
|
|
if best is None or d < best[0]: best = (d, u)
|
|
if best: return best[1]
|
|
return None
|
|
|
|
# server data
|
|
cspawn = defaultdict(list)
|
|
for r in query("SELECT id,id2,id3,id4,map,position_x,position_y,position_z FROM tw_world.creature"):
|
|
p = (int(r[4]), float(r[5]), float(r[6]), float(r[7]))
|
|
for e in r[:4]:
|
|
if e not in ('0', 'NULL', ''): cspawn[int(e)].append(p)
|
|
gspawn = defaultdict(list)
|
|
for r in query("SELECT id,map,position_x,position_y,position_z FROM tw_world.gameobject"):
|
|
gspawn[int(r[0])].append((int(r[1]), float(r[2]), float(r[3]), float(r[4])))
|
|
refs = defaultdict(set)
|
|
for r in query("SELECT entry,item FROM tw_world.reference_loot_template WHERE mincountOrRef >= 0"):
|
|
refs[int(r[0])].add(int(r[1]))
|
|
def loot(table):
|
|
drops = defaultdict(set) # loot id -> items
|
|
for r in query(f"SELECT entry,item,mincountOrRef FROM tw_world.{table}"):
|
|
e, item, mc = int(r[0]), int(r[1]), int(r[2])
|
|
if mc < 0: drops[e] |= refs.get(-mc, set())
|
|
else: drops[e].add(item)
|
|
return drops
|
|
cl, gl = loot('creature_loot_template'), loot('gameobject_loot_template')
|
|
item_sources = defaultdict(list) # item -> spawn lists
|
|
for r in query("SELECT entry,loot_id FROM tw_world.creature_template WHERE loot_id > 0"):
|
|
for item in cl.get(int(r[1]), ()):
|
|
item_sources[item].append(('c', int(r[0])))
|
|
for r in query("SELECT entry,type,data1 FROM tw_world.gameobject_template WHERE type IN (3,25) AND data1 > 0"):
|
|
for item in gl.get(int(r[2]), ()):
|
|
item_sources[item].append(('g', int(r[0])))
|
|
|
|
quests = {}
|
|
for r in query("SELECT entry,ReqCreatureOrGOId1,ReqCreatureOrGOId2,ReqCreatureOrGOId3,ReqCreatureOrGOId4,"
|
|
"ReqItemId1,ReqItemId2,ReqItemId3,ReqItemId4 FROM tw_world.quest_template"):
|
|
quests[int(r[0])] = [int(v) for v in r[1:]]
|
|
|
|
report = dict(quests_old=len(old), rebuilt=0, kept_old=0, objectives_from_spawns=0, objectives_kept=0,
|
|
areas=0, no_uimap=0, new_quests=0)
|
|
records = {}
|
|
for qid in sorted(set(old) | set(quests)):
|
|
prev = old.get(qid, [])
|
|
keep = [b for b in prev if b['objective'] < 0 or b['objective'] == 32]
|
|
req = quests.get(qid)
|
|
if not req:
|
|
records[qid] = prev; report['kept_old'] += 1; continue
|
|
objectives = []
|
|
for s in range(4):
|
|
v = req[s]
|
|
if v > 0: objectives.append((s, v, cspawn.get(v, [])))
|
|
elif v < 0: objectives.append((s, -v, gspawn.get(-v, [])))
|
|
for s in range(4):
|
|
v = req[4 + s]
|
|
if v > 0:
|
|
pts = []
|
|
for kind, e in item_sources.get(v, ()):
|
|
pts += (cspawn if kind == 'c' else gspawn).get(e, [])
|
|
objectives.append((4 + s, v, pts))
|
|
new = []
|
|
for storage, obj, spawns in objectives:
|
|
areas = []
|
|
by_map = defaultdict(list)
|
|
for m, x, y, z in spawns: by_map[m].append((x, y, z))
|
|
for m, pts in by_map.items():
|
|
for group in clusters(pts):
|
|
cx = sum(p[0] for p in group) / len(group); cy = sum(p[1] for p in group) / len(group)
|
|
u = uimap_at(m, cx, cy)
|
|
if not u: report['no_uimap'] += 1; continue
|
|
z = int(round(sum(p[2] for p in group) / len(group)))
|
|
shape = area_shape([(p[0], p[1]) for p in group])
|
|
areas.append((len(group), m, u, [(int(round(x)), int(round(y)), z) for x, y in shape]))
|
|
if areas:
|
|
report['objectives_from_spawns'] += 1
|
|
areas.sort(key=lambda t: -t[0])
|
|
for i, (_, m, u, shape) in enumerate(areas):
|
|
new.append(dict(objective=storage, blob=i, flags=1, object=obj, map=m, uimap=u, points=shape))
|
|
else:
|
|
old_areas = [b for b in prev if b['objective'] == storage]
|
|
if old_areas: report['objectives_kept'] += 1
|
|
new += old_areas
|
|
if not new and not keep:
|
|
continue
|
|
if qid not in old: report['new_quests'] += 1
|
|
# stay inside the native per-quest limit: biggest camps of every objective first
|
|
if len(keep) + len(new) > MAX_BLOBS:
|
|
new.sort(key=lambda b: b['blob']); new = new[:MAX_BLOBS - len(keep)]
|
|
for s in {b['objective'] for b in new}:
|
|
for i, b in enumerate(sorted((b for b in new if b['objective'] == s), key=lambda b: b['blob'])):
|
|
b['blob'] = i
|
|
records[qid] = sorted(new, key=lambda b: (b['objective'] if b['objective'] >= 0 else 99, b['blob'])) + keep
|
|
report['rebuilt'] += 1; report['areas'] += len(new)
|
|
report['quests_written'] = write_dataset(records, a.out)
|
|
print(json.dumps(report, indent=1))
|
|
if a.report: open(a.report, 'w').write(json.dumps(report, indent=1) + '\n')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|