Ver Fonte

perf: reduce offline NPC pathfinding cost with connectivity checks

detopoi há 2 semanas atrás
pai
commit
6d215f378a

+ 17 - 7
client_local/algo/aStar.py

@@ -1,4 +1,4 @@
-from queue import PriorityQueue
+import heapq
 from client_local.level import level
 
 
@@ -85,18 +85,17 @@ def reverse(came_from, hero_grid, npc_grid):
     return go_to
 
 
-def cal_path(npc_grid, hero_grid, limit1, limit2, is_ghost=False):
+def _search_path(npc_grid, hero_grid, limit1, limit2, is_ghost=False):
     # limit1 区域左上角
     # limit2 区域右下角
-    frontier = PriorityQueue()
-    frontier.put((0, npc_grid))
+    frontier = [(0, npc_grid)]
     came_from = dict()
     cost_so_far = dict()
     came_from[npc_grid] = None
     cost_so_far[npc_grid] = 0
 
-    while not frontier.empty():
-        current = frontier.get()[1]
+    while frontier:
+        current = heapq.heappop(frontier)[1]
         if current == hero_grid:
             break
         for next in neighbors(current, npc_grid, limit1, limit2, is_ghost):
@@ -104,7 +103,18 @@ def cal_path(npc_grid, hero_grid, limit1, limit2, is_ghost=False):
             if next not in cost_so_far or new_cost < cost_so_far[next]:
                 cost_so_far[next] = new_cost
                 priority = new_cost + heuristic(next, hero_grid)
-                frontier.put((priority, next))
+                heapq.heappush(frontier, (priority, next))
                 came_from[next] = current
 
     return reverse(came_from, hero_grid, npc_grid)
+
+
+def cal_path(npc_grid, hero_grid, limit1, limit2, is_ghost=False):
+    from client_local.algo.navigation import NavigationCache
+    cl = level.current_level
+    cache = getattr(cl, '_npc_navigation', None)
+    if cache is None:
+        cache = cl._npc_navigation = NavigationCache()
+    if not is_ghost and cache.disconnected(cl, npc_grid, hero_grid, limit1, limit2):
+        return {}
+    return _search_path(npc_grid, hero_grid, limit1, limit2, is_ghost)

+ 56 - 0
client_local/algo/navigation.py

@@ -0,0 +1,56 @@
+"""Static connectivity rejection; reachable A* paths remain unchanged."""
+
+
+def invalidate_navigation(level):
+    level.npc_topology_revision = getattr(level, 'npc_topology_revision', 0) + 1
+    level.recal_npc_paths = True
+
+
+class NavigationCache:
+    def __init__(self):
+        self.block = None
+        self.signature = None
+        self.labels = None
+        self.builds = 0
+        self.rejections = 0
+
+    def disconnected(self, level, start, target, lower, upper):
+        width, height = level.map_x, level.map_y
+        # Legacy searches can extend outside map bounds; do not prune those.
+        if not all(len(p) == 2 and all(isinstance(v, int) for v in p)
+                   and 0 <= p[0] < width and 0 <= p[1] < height
+                   for p in (start, target, lower, upper)):
+            return False
+        signature = (width, height, getattr(level, 'npc_topology_revision', 0))
+        if self.block is not level.block or self.signature != signature:
+            self.block, self.signature = level.block, signature
+            self._build(width, height)
+        if self.labels[start[0]][start[1]] != self.labels[target[0]][target[1]]:
+            self.rejections += 1
+            return True
+        return False
+
+    def _build(self, width, height):
+        horizontal, vertical = self.block
+        labels = [[-1] * height for _ in range(width)]
+        component = 0
+        for x in range(width):
+            for y in range(height):
+                if labels[x][y] != -1:
+                    continue
+                labels[x][y] = component
+                pending = [(x, y)]
+                while pending:
+                    cx, cy = pending.pop()
+                    for nx, ny, edge in (
+                            (cx, cy - 1, horizontal[cx][cy]),
+                            (cx + 1, cy, vertical[cx + 1][cy]),
+                            (cx, cy + 1, horizontal[cx][cy + 1]),
+                            (cx - 1, cy, vertical[cx][cy])):
+                        if (edge <= 0 and 0 <= nx < width and 0 <= ny < height
+                                and labels[nx][ny] == -1):
+                            labels[nx][ny] = component
+                            pending.append((nx, ny))
+                component += 1
+        self.labels = labels
+        self.builds += 1

+ 8 - 0
client_local/sprite/obstacle_instance.py

@@ -126,11 +126,16 @@ class ObstacleInstance(Updatable):
                 self.obstacle_instances_dict[(x + self.x), (y + self.y)] = self
 
         # 添加block三维数组
+        navigation_changed = False
         for orient in range(2):
             for x in range(len(self.obstacle["BLOCK"][orient])):
                 for y in range(len(self.obstacle["BLOCK"][orient][x])):
                     level.current_level.block[orient][x + self.x][y + self.y] += self.obstacle["BLOCK"][orient][x][y]
                     level.current_level.block_flame[orient][x + self.x][y + self.y] += self.obstacle["BLOCK_FLAME"][orient][x][y]
+                    navigation_changed |= bool(self.obstacle["BLOCK"][orient][x][y])
+        if navigation_changed:
+            from client_local.algo.navigation import invalidate_navigation
+            invalidate_navigation(level.current_level)
 
         if self.obstacle["CAN_HIDE"]:
             self.obstacle_can_hide = True
@@ -434,6 +439,9 @@ class ObstacleInstance(Updatable):
                 for y in range(len(self.obstacle["BLOCK"][orient][x])):
                     level.current_level.block[orient][x + self.x][y + self.y] -= self.obstacle["BLOCK"][orient][x][y]
                     level.current_level.block_flame[orient][x + self.x][y + self.y] -= self.obstacle["BLOCK_FLAME"][orient][x][y]
+        if any(value for plane in self.obstacle["BLOCK"] for column in plane for value in column):
+            from client_local.algo.navigation import invalidate_navigation
+            invalidate_navigation(level.current_level)
 
         if "SLIDE" in self.obstacle.keys():
             del level.current_level.slide_orientation[(self.x, self.y)]

+ 46 - 0
tests/navigation_benchmark_20261117.md

@@ -0,0 +1,46 @@
+# 单机寻路优化对照(2026-11-17)
+
+## 来源与取舍
+
+- 参考联机提交 `07c076b0ecde486b45fd870b2cd097e3d09aeb92` 的静态连通区域拒绝。
+- 单机 A* 将线程安全 PriorityQueue 换为 heapq。原优先级、邻居顺序、穿墙和返回路径格式不变。
+- 不移植短时失败缓存:临时糖泡仍即时参与原 A*,无需引入额外过期和炸弹修订管理。
+- 不移植 `37e341e7436430d31749cec133b1f15fc9296a88` 的五套危险区合并刷新:该流水线只存在于联机服务端,单机没有对应热路径。
+
+## 测试方式
+
+Windows / Python 3.8.9 / NumPy,40×30 格地图,固定随机种子和 NPC 坐标。
+执行生产代码 `Npc.chase_hero` 和生产 A*;通过 AST 隔离游戏启动和存档。
+模拟每帧需要重算路径的密集追击。每个场景两种实现各跑 3 轮,每轮 5 帧,交替先后顺序;表为每帧全部 NPC 寻路刷新阶段耗时中位数。
+初版 A* 原样保存在 navigation_reference.py,供复现和逐项路径比较。
+
+| 场景 | NPC | 优化前 ms | 优化后 ms | 阶段加速 |
+|---|---:|---:|---:|---:|
+| 可达追击 | 80 | 25.769 | 16.397 | 1.57× |
+| 可达追击 | 240 | 79.092 | 47.970 | 1.65× |
+| 完全隔墙 | 80 | 505.799 | 0.248 | 2036× |
+| 完全隔墙 | 240 | 1492.145 | 0.758 | 1968× |
+| 糖泡临时封路 | 160 | 997.157 | 665.128 | 1.50× |
+| 动态开关墙 | 160 | 54.205 | 30.486 | 1.78× |
+| 一半可达、一半隔墙 | 160 | 502.255 | 7.166 | 70.08× |
+
+首次构建连通区域也计入采样:240 怪隔墙场景每轮首帧中位数为 1546.366 → 2.022 ms。
+静态图的首次构建有一次性成本,少量 NPC 的冷启动未承诺改善。
+
+## 正确性与限制
+
+- 80 个随机地图 × 15 个查询:1200 组精确路径比较。
+- 2×2 地图全部 16 种墙体 × 16 种糖泡 × 16 种起终点:4096 组比较。
+- 1200 次动态墙体和糖泡变化,另测真实障碍安装/卸载代码、地图替换、穿墙和边界兼容。
+- 所有压测逐帧比较完整路径和 NPC 下一步方向,不只比较是否可达。
+- 单机当前工作区 43 项测试通过,包括原有渲染、糖泡索引及技能测试。
+
+这是寻路刷新阶段的构造场景基准,不包括渲染、技能攻击、真实怪物动画和资源加载,不是整场游戏 FPS 或完整实机战斗验收。
+糖泡封路仍需做实际 A*,因此该场景仍较重;本提交不为改变怪物行为而限制搜索。
+
+复现:
+
+```text
+python -m unittest discover -s tests -p test_*.py
+python tests/test_navigation_optimization.py --benchmark .codex_build/navigation-20261117/results.json
+```

+ 110 - 0
tests/navigation_reference.py

@@ -0,0 +1,110 @@
+from queue import PriorityQueue
+from client_local.level import level
+
+
+def r_block(x, y):
+    return level.current_level.block[1][x + 1][y] > 0
+
+
+def u_block(x, y):
+    return level.current_level.block[0][x][y] > 0
+
+
+def l_block(x, y):
+    return level.current_level.block[1][x][y] > 0
+
+
+def d_block(x, y):
+    return level.current_level.block[0][x][y + 1] > 0
+
+
+def bomb_exist(x, y):
+    return len(level.current_level.get_bomb_instance(x, y)) > 0
+
+
+def can_reach_r(x, y):
+    return not r_block(x, y) and not bomb_exist(x + 1, y)
+
+
+def can_reach_u(x, y):
+    return not u_block(x, y) and not bomb_exist(x, y - 1)
+
+
+def can_reach_l(x, y):
+    return not l_block(x, y) and not bomb_exist(x - 1, y)
+
+
+def can_reach_d(x, y):
+    return not d_block(x, y) and not bomb_exist(x, y + 1)
+
+
+# PVE优先级:下>左>上>右
+def neighbors(current, npc_grid, limit1, limit2, is_ghost):
+    # 计算四个邻位是否可达
+    points = []
+    x, y = current  # 当前坐标
+    x1, y1 = limit1  # 区域左上角坐标
+    x2, y2 = limit2  # 区域右下角坐标
+    if is_ghost:
+        return [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
+    if heuristic(current, npc_grid) == 1 and bomb_exist(*npc_grid):
+        if not r_block(x, y) and x + 1 <= x2:
+            points.append((x + 1, y))
+        if not u_block(x, y) and y - 1 >= y1:
+            points.append((x, y - 1))
+        if not l_block(x, y) and x - 1 >= x1:
+            points.append((x - 1, y))
+        if not d_block(x, y) and y + 1 <= y2:
+            points.append((x, y + 1))
+    else:
+        if can_reach_r(x, y) and x + 1 <= x2:
+            points.append((x + 1, y))
+        if can_reach_u(x, y) and y - 1 >= y1:
+            points.append((x, y - 1))
+        if can_reach_l(x, y) and x - 1 >= x1:
+            points.append((x - 1, y))
+        if can_reach_d(x, y) and y + 1 <= y2:
+            points.append((x, y + 1))
+    return points
+
+
+# 原版优先级:右>下>上>左
+def heuristic(next, npc_grid):
+    x1, y1 = next
+    x2, y2 = npc_grid
+    return (x1 - x2)**2 + (y1 - y2)**2
+
+
+def reverse(came_from, hero_grid, npc_grid):
+    go_to = dict()
+    while hero_grid != npc_grid:
+        if hero_grid not in came_from.keys():
+            break
+        go_to[came_from[hero_grid]] = hero_grid
+        hero_grid = came_from[hero_grid]
+    return go_to
+
+
+def cal_path(npc_grid, hero_grid, limit1, limit2, is_ghost=False):
+    # limit1 区域左上角
+    # limit2 区域右下角
+    frontier = PriorityQueue()
+    frontier.put((0, npc_grid))
+    came_from = dict()
+    cost_so_far = dict()
+    came_from[npc_grid] = None
+    cost_so_far[npc_grid] = 0
+
+    while not frontier.empty():
+        current = frontier.get()[1]
+        if current == hero_grid:
+            break
+        for next in neighbors(current, npc_grid, limit1, limit2, is_ghost):
+            new_cost = cost_so_far[current] + 1
+            if next not in cost_so_far or new_cost < cost_so_far[next]:
+                cost_so_far[next] = new_cost
+                priority = new_cost + heuristic(next, hero_grid)
+                frontier.put((priority, next))
+                came_from[next] = current
+
+    return reverse(came_from, hero_grid, npc_grid)

+ 208 - 0
tests/test_navigation_optimization.py

@@ -0,0 +1,208 @@
+"""Route equivalence and synthetic many-NPC chase-stage benchmarks."""
+import ast
+import argparse
+import json
+from pathlib import Path
+import random
+import statistics
+import sys
+import time
+from types import SimpleNamespace as NS
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+import numpy as np
+from client_local.algo.navigation import invalidate_navigation
+
+
+def load_search(path, scene):
+    tree = ast.parse(path.read_text(encoding='utf-8-sig'))
+    tree.body = [n for n in tree.body if not (isinstance(n, ast.ImportFrom)
+                 and n.module == 'client_local.level')]
+    scope = {'level': NS(current_level=scene)}
+    exec(compile(tree, str(path), 'exec'), scope)
+    return NS(**scope)
+
+
+def scene(width=12, height=10):
+    value = NS(map_x=width, map_y=height,
+               block=np.zeros((2, width + 1, height + 1), dtype=np.int64), bombs=set(),
+               recal_npc_paths=True, me=NS(x=width - 2, y=height // 2),
+               district_square_grid={'x1': 0, 'y1': 0, 'x2': width - 1, 'y2': height - 1})
+    value.get_bomb_instance = lambda x, y: [1] if (x, y) in value.bombs else []
+    return value
+
+
+def searches(value):
+    return (load_search(ROOT / 'tests/navigation_reference.py', value),
+            load_search(ROOT / 'client_local/algo/aStar.py', value))
+
+
+class NavigationTests(unittest.TestCase):
+    def test_all_small_wall_and_bomb_combinations(self):
+        cl = scene(2, 2)
+        old, new = searches(cl)
+        edges = [(0, 0, 1), (0, 1, 1), (1, 1, 0), (1, 1, 1)]
+        points = [(x, y) for x in range(2) for y in range(2)]
+        for wall_bits in range(16):
+            for bit, (plane, x, y) in enumerate(edges):
+                cl.block[plane][x][y] = (wall_bits >> bit) & 1
+            invalidate_navigation(cl)
+            for bomb_bits in range(16):
+                cl.bombs = {point for bit, point in enumerate(points) if bomb_bits & (1 << bit)}
+                for start in points:
+                    for target in points:
+                        self.assertEqual(old.cal_path(start, target, (0, 0), (1, 1)),
+                                         new.cal_path(start, target, (0, 0), (1, 1)))
+
+    def test_random_routes_match_exactly(self):
+        for seed in range(80):
+            rng = random.Random(seed)
+            cl = scene(9, 7)
+            cl.block[:] = np.array([rng.choice((0, 0, 0, 1, 2, -1))
+                                   for _ in range(cl.block.size)]).reshape(cl.block.shape)
+            cl.bombs = {(rng.randrange(9), rng.randrange(7)) for _ in range(10)}
+            old, new = searches(cl)
+            for _ in range(15):
+                start, target = [(rng.randrange(9), rng.randrange(7)) for _ in range(2)]
+                lower = rng.randrange(9), rng.randrange(7)
+                upper = rng.randrange(lower[0], 9), rng.randrange(lower[1], 7)
+                with self.subTest(seed=seed, start=start, target=target):
+                    self.assertEqual(old.cal_path(start, target, lower, upper),
+                                     new.cal_path(start, target, lower, upper))
+
+    def test_obstacle_hooks_invalidate_connectivity(self):
+        cl = scene(5, 3)
+        old, new = searches(cl)
+        args = (0, 1), (4, 1), (0, 0), (4, 2)
+        self.assertTrue(new.cal_path(*args))
+        tree = ast.parse((ROOT / 'client_local/sprite/obstacle_instance.py').read_text(encoding='utf-8-sig'))
+        cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'ObstacleInstance')
+        obstacle = NS(x=2, y=0, obstacle={'BLOCK': [[[0] * 4 for _ in range(2)], [[1] * 3]] ,
+                                       'BLOCK_FLAME': [[[0] * 4 for _ in range(2)], [[0] * 3]]})
+        cl.block_flame = cl.block.copy()
+        for method_name, expected in (('setup', False), ('uninstall', True)):
+            method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == method_name)
+            nodes = []
+            for node in method.body:
+                dumped = ast.dump(node)
+                if ('navigation_changed' in dumped or 'invalidate_navigation' in dumped
+                        or isinstance(node, ast.For) and 'block_flame' in dumped):
+                    nodes.append(node)
+            exec(compile(ast.Module(body=nodes, type_ignores=[]), '<obstacle-hooks>', 'exec'),
+                 {'self': obstacle, 'level': NS(current_level=cl)})
+            self.assertEqual(bool(new.cal_path(*args)), expected)
+            self.assertEqual(new.cal_path(*args), old.cal_path(*args))
+            self.assertTrue(cl.recal_npc_paths)
+        self.assertEqual(cl._npc_navigation.builds, 3)
+
+    def test_bomb_move_throw_remove_and_map_reload_have_no_stale_answers(self):
+        cl = scene(7, 1)
+        old, new = searches(cl)
+        args = (0, 0), (6, 0), (0, 0), (6, 0)
+        for bombs in ({(3, 0)}, set(), {(4, 0)}, set(), {(0, 0)}, set()):
+            cl.bombs = bombs
+            self.assertEqual(old.cal_path(*args), new.cal_path(*args))
+        self.assertEqual(cl._npc_navigation.builds, 1)
+        cl.block = cl.block.copy()
+        cl.block[1][3][0] = 1
+        self.assertEqual(old.cal_path(*args), new.cal_path(*args))
+        self.assertEqual(cl._npc_navigation.builds, 2)
+
+    def test_dynamic_wall_and_bomb_mutations(self):
+        cl = scene(9, 7)
+        old, new = searches(cl)
+        rng = random.Random(3007)
+        for _ in range(1200):
+            plane, x, y = rng.randrange(2), rng.randrange(9), rng.randrange(7)
+            cl.block[plane][x][y] = rng.choice((0, 1, 2, -1))
+            invalidate_navigation(cl)
+            cl.bombs = {(rng.randrange(9), rng.randrange(7)) for _ in range(4)}
+            args = (rng.randrange(9), rng.randrange(7)), (rng.randrange(9), rng.randrange(7)), (0, 0), (8, 6)
+            self.assertEqual(old.cal_path(*args), new.cal_path(*args))
+
+    def test_ghosts_same_point_and_boundary_queries_match(self):
+        cl = scene(7, 6)
+        cl.block[1][3][:6] = 1
+        old, new = searches(cl)
+        for ghost in (True, False):
+            for start, target, lower, upper in (
+                    ((0, 0), (6, 5), (0, 0), (6, 5)),
+                    ((2, 2), (2, 2), (0, 0), (6, 5)),
+                    ((0, 0), (1, 0), (-1, 0), (6, 5))):
+                self.assertEqual(old.cal_path(start, target, lower, upper, ghost),
+                                 new.cal_path(start, target, lower, upper, ghost))
+
+
+def chase_function(search, cl):
+    tree = ast.parse((ROOT / 'client_local/sprite/npc.py').read_text(encoding='utf-8-sig'))
+    cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Npc')
+    method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == 'chase_hero')
+    scope = {'aStar': search, 'level': NS(current_level=cl)}
+    exec(compile(ast.Module(body=[method], type_ignores=[]), '<real-chase>', 'exec'), scope)
+    return scope['chase_hero']
+
+
+def benchmark(output):
+    results = []
+    for kind, count in [('open', 80), ('open', 240), ('wall', 80), ('wall', 240),
+                        ('bomb', 160), ('dynamic-wall', 160), ('mixed', 160)]:
+        cl = scene(40, 30)
+        if kind in ('wall', 'mixed', 'dynamic-wall'):
+            cl.block[1][20][:30] = 1
+        if kind == 'bomb':
+            cl.bombs = {(20, y) for y in range(30)}
+        old, new = searches(cl)
+        rng = random.Random(441)
+        units = []
+        for i in range(count):
+            x = rng.randrange(1, 19) if kind != 'mixed' or i % 2 else rng.randrange(21, 38)
+            npc = NS(x=x, y=rng.randrange(1, 29), resentful=True, mocking=False, friendly=False,
+                     imitating=False, speed=1, original_speed=1, free_chasing=False,
+                     chasing_monster=False, is_ghost=False, chase_path={}, motion=None)
+            npc.set_motion = lambda motion=None, npc=npc: setattr(npc, 'motion', motion)
+            units.append(npc)
+        samples = {'before': [], 'after': []}
+        cold = {}
+        snapshots = {}
+        for cycle in range(3):
+            for name, search in ((('before', old), ('after', new)) if cycle % 2 == 0 else
+                                 (('after', new), ('before', old))):
+                cl._npc_navigation = None
+                chase = chase_function(search, cl)
+                states = []
+                for frame in range(5):
+                    if kind == 'dynamic-wall':
+                        cl.block[1][20][15] = frame % 2
+                        invalidate_navigation(cl)
+                    started = time.perf_counter()
+                    for npc in units:
+                        chase(npc)
+                    elapsed = (time.perf_counter() - started) * 1000
+                    if frame == 0:
+                        cold.setdefault(name, []).append(elapsed)
+                    samples[name].append(elapsed)
+                    states.append([(npc.motion, npc.chase_path.copy()) for npc in units])
+                if cycle == 0:
+                    snapshots[name] = states
+        assert snapshots['before'] == snapshots['after'], (kind, count)
+        before, after = (statistics.median(samples[name]) for name in ('before', 'after'))
+        row = dict(scene=kind, npcs=count, before_ms=round(before, 3), after_ms=round(after, 3),
+                   speedup=round(before / after, 2), cold_before_ms=round(statistics.median(cold['before']), 3),
+                   cold_after_ms=round(statistics.median(cold['after']), 3), identical=True)
+        results.append(row)
+        print(json.dumps(row), flush=True)
+    Path(output).parent.mkdir(parents=True, exist_ok=True)
+    Path(output).write_text(json.dumps(results, indent=2), encoding='utf-8')
+
+
+if __name__ == '__main__':
+    import sys
+    if '--benchmark' in sys.argv:
+        parser = argparse.ArgumentParser()
+        parser.add_argument('--benchmark', required=True)
+        benchmark(parser.parse_args().benchmark)
+    else:
+        unittest.main()