Line data Source code
1 : package query
2 :
3 : import (
4 : gc "github.com/kijimaD/ruins/internal/components"
5 : "github.com/kijimaD/ruins/internal/geometry"
6 : w "github.com/kijimaD/ruins/internal/world"
7 : "github.com/mlange-42/ark/ecs"
8 : )
9 :
10 : // FindNearestEntity は条件を満たす最寄りのエンティティを全 GridElement から探す。
11 : // selfは検索対象から除外されるエンティティで、Deadエンティティも自動的に除外する。
12 : // matchはターゲット候補を絞り込む述語。見つからない場合はnilを返す。
13 : // キャラクター探索のホットパスは FindNearestCharacter を使うこと。本関数は床・壁タイルも走査する。
14 : func FindNearestEntity(world w.World, self ecs.Entity, from *gc.GridElement, match func(ecs.Entity) bool) (*ecs.Entity, *gc.GridElement, int) {
15 1 : var nearestEntity *ecs.Entity
16 1 : var nearestGrid *gc.GridElement
17 1 : nearestDist := -1
18 1 :
19 : // 座標が重なる退避中ステージのエンティティを最近傍探索に混ぜない
20 1 : nearestQuery := ActiveFilter1[gc.GridElement](world).Query()
21 1 : for nearestQuery.Next() {
22 1 : entity := nearestQuery.Entity()
23 1 : if entity == self {
24 1 : continue
25 : }
26 1 : if world.Components.Dead.Has(entity) {
27 1 : continue
28 : }
29 1 : if !match(entity) {
30 1 : continue
31 : }
32 1 : grid := world.Components.GridElement.Get(entity)
33 1 : dist := geometry.ChebyshevDistance(from.Coord, grid.Coord)
34 1 : if nearestDist < 0 || dist < nearestDist {
35 1 : nearestEntity = new(entity)
36 1 : nearestGrid = grid
37 1 : nearestDist = dist
38 1 : }
39 : }
40 :
41 1 : return nearestEntity, nearestGrid, nearestDist
42 : }
43 :
44 : // FindNearestCharacter は条件を満たす最寄りのキャラクターを探す。
45 : //
46 : // 床・壁・void も GridElement を持つエンティティのため、全 GridElement を走査するとマップ全タイル
47 : // を毎回舐めることになる。空間インデックスのキャラクター位置を候補にして
48 : // O(タイル数+キャラ数) → O(キャラ数) に削減する。AI のターゲット探索はすべて
49 : // キャラクター対象なので、この関数を使う。
50 : //
51 : // 同距離は entity.ID() の小さい方を選び、マップ反復順に依存しない決定的な結果を返して
52 : // 固定 seed の再現性を保つ。位置は live な GridElement を読むため、インデックスキーが多少
53 : // ずれても正しい。インデックスが使えないときは全走査にフォールバックする。
54 : func FindNearestCharacter(world w.World, self ecs.Entity, from *gc.GridElement, match func(ecs.Entity) bool) (*ecs.Entity, *gc.GridElement, int) {
55 1 : si := GetSpatialIndex(world)
56 1 : if si == nil || si.Characters == nil {
57 1 : return FindNearestEntity(world, self, from, match)
58 1 : }
59 :
60 1 : var nearest ecs.Entity
61 1 : var nearestGrid *gc.GridElement
62 1 : nearestDist := -1
63 1 : found := false
64 1 :
65 1 : for _, entity := range si.Characters {
66 1 : if entity == self || !world.ECS.Alive(entity) || world.Components.Dead.Has(entity) {
67 1 : continue
68 : }
69 1 : if !match(entity) {
70 1 : continue
71 : }
72 1 : grid := world.Components.GridElement.Get(entity)
73 1 : dist := geometry.ChebyshevDistance(from.Coord, grid.Coord)
74 1 : if !found || dist < nearestDist || (dist == nearestDist && entity.ID() < nearest.ID()) {
75 1 : nearest = entity
76 1 : nearestGrid = grid
77 1 : nearestDist = dist
78 1 : found = true
79 1 : }
80 : }
81 :
82 1 : if !found {
83 1 : return nil, nil, -1
84 1 : }
85 1 : return &nearest, nearestGrid, nearestDist
86 : }
|