Line data Source code
1 : package states
2 :
3 : import (
4 : "cmp"
5 : "fmt"
6 : "math"
7 : "slices"
8 :
9 : "github.com/hajimehoshi/ebiten/v2"
10 : "github.com/kijimaD/ruins/internal/activity"
11 : es "github.com/kijimaD/ruins/internal/engine/states"
12 : "github.com/kijimaD/ruins/internal/inputmapper"
13 : "github.com/kijimaD/ruins/internal/keybind"
14 : "github.com/kijimaD/ruins/internal/render3d"
15 : "github.com/kijimaD/ruins/internal/widgets/hud"
16 : "github.com/kijimaD/ruins/internal/widgets/theme"
17 : "github.com/kijimaD/ruins/internal/widgets/uicore"
18 : w "github.com/kijimaD/ruins/internal/world"
19 :
20 : "github.com/kijimaD/ruins/internal/world/query"
21 : "github.com/mlange-42/ark/ecs"
22 : )
23 :
24 : // ShootingState は射撃ターゲット選択モードのステート
25 : // 視界内の敵をTabで巡回し、Enterで射撃、Rでリロード、Escapeでキャンセルする
26 : type ShootingState struct {
27 : es.BaseState[w.World]
28 : enemies []ecs.Entity // 視界内の敵一覧
29 : targetIndex int // 現在選択中の敵インデックス
30 : blinkCounter int // カーソル点滅用カウンタ
31 : cachedHitRate int // キャッシュ済み命中率
32 : cachedDistance float64 // キャッシュ済み距離
33 : }
34 :
35 : var _ es.State[w.World] = &ShootingState{}
36 :
37 : // OnPause はステートが一時停止される際に呼ばれる
38 0 : func (st *ShootingState) OnPause(_ w.World) error { return nil }
39 :
40 : // OnResume はステートが再開される際に呼ばれる
41 0 : func (st *ShootingState) OnResume(_ w.World) error { return nil }
42 :
43 : // OnStart はステートが開始される際に呼ばれる
44 : func (st *ShootingState) OnStart(world w.World) error {
45 1 : if err := st.refreshEnemies(world); err != nil {
46 0 : return err
47 0 : }
48 1 : st.updateTargetCache(world)
49 1 : return nil
50 : }
51 :
52 : // OnStop はステートが終了する際に呼ばれる
53 0 : func (st *ShootingState) OnStop(_ w.World) error { return nil }
54 :
55 : // Update はステートの更新処理
56 : func (st *ShootingState) Update(world w.World) (es.Transition[w.World], error) {
57 1 : st.blinkCounter++
58 1 :
59 1 : if action, ok := keybind.ReadInput(world, shootingBindings); ok {
60 0 : return st.doAction(world, action)
61 0 : }
62 :
63 1 : return st.ConsumeTransition(), nil
64 : }
65 :
66 : // shootingBindings は射撃モードの束縛表。Tab で標的を切り替え、Enter で撃つ。
67 : // Shift+Tab の行を Tab の行より先に置き、Shift 併用を先に判定する
68 : var shootingBindings = []keybind.Binding{
69 : {Key: ebiten.KeyEscape, Action: inputmapper.ActionCloseMenu},
70 : {Key: ebiten.KeyTab, Shift: keybind.ShiftRequired, Action: inputmapper.ActionMenuTabPrev},
71 : {Key: ebiten.KeyTab, Action: inputmapper.ActionMenuTabNext},
72 : {Key: ebiten.KeyEnter, Action: inputmapper.ActionShoot},
73 : {Key: ebiten.KeyR, Action: inputmapper.ActionReload},
74 : }
75 :
76 : // doAction はActionIDを実行する
77 : func (st *ShootingState) doAction(world w.World, action inputmapper.ActionID) (es.Transition[w.World], error) {
78 0 : switch action {
79 : case inputmapper.ActionCloseMenu:
80 0 : return es.Transition[w.World]{Type: es.TransPop}, nil
81 :
82 : case inputmapper.ActionMenuTabNext:
83 0 : if len(st.enemies) > 0 {
84 0 : st.targetIndex = (st.targetIndex + 1) % len(st.enemies)
85 0 : st.updateTargetCache(world)
86 0 : }
87 :
88 : case inputmapper.ActionMenuTabPrev:
89 0 : if len(st.enemies) > 0 {
90 0 : st.targetIndex = (st.targetIndex - 1 + len(st.enemies)) % len(st.enemies)
91 0 : st.updateTargetCache(world)
92 0 : }
93 :
94 : case inputmapper.ActionShoot:
95 0 : if len(st.enemies) > 0 {
96 0 : playerEntity, err := query.GetPlayerEntity(world)
97 0 : if err != nil {
98 0 : return es.Transition[w.World]{}, err
99 0 : }
100 0 : target := st.enemies[st.targetIndex]
101 0 : if _, err := activity.Execute(activity.NewShootActivity(target), playerEntity, world); err != nil {
102 0 : return es.Transition[w.World]{}, err
103 0 : }
104 0 : return es.Transition[w.World]{Type: es.TransPop}, nil
105 : }
106 :
107 : case inputmapper.ActionReload:
108 0 : playerEntity, err := query.GetPlayerEntity(world)
109 0 : if err != nil {
110 0 : return es.Transition[w.World]{}, err
111 0 : }
112 0 : if _, err := activity.Execute(activity.NewReloadActivity(playerEntity, world), playerEntity, world); err != nil {
113 0 : return es.Transition[w.World]{}, err
114 0 : }
115 0 : return es.Transition[w.World]{Type: es.TransPop}, nil
116 :
117 : default:
118 0 : return es.Transition[w.World]{}, fmt.Errorf("unsupported action: %s", action)
119 : }
120 :
121 0 : return st.ConsumeTransition(), nil
122 : }
123 :
124 : // checkFireWeaponStatus は選択中の武器の射撃可否をチェックし、不可の場合は理由メッセージを返す。
125 : // 射撃可能な場合は空文字を返す
126 : func (st *ShootingState) checkFireWeaponStatus(world w.World) string {
127 1 : playerEntity, err := query.GetPlayerEntity(world)
128 1 : if err != nil {
129 0 : return ""
130 0 : }
131 1 : selectedSlot := query.GetWeaponSelection(world).Slot
132 1 : weapons := query.GetWeapons(world, playerEntity)
133 1 : weaponIndex := selectedSlot - 1
134 1 : if weaponIndex < 0 || weaponIndex >= len(weapons) || weapons[weaponIndex] == nil {
135 0 : return query.T(world, "No ranged weapon equipped")
136 0 : }
137 1 : fire := world.Components.Fire.Get(*weapons[weaponIndex])
138 1 : if fire == nil {
139 1 : return query.T(world, "No ranged weapon equipped")
140 1 : }
141 0 : if fire.Magazine <= 0 {
142 0 : return query.T(world, "Not loaded")
143 0 : }
144 0 : return ""
145 : }
146 :
147 : // refreshEnemies は射撃可能な敵一覧を距離順で更新する。
148 : // 視界内の敵から死亡済み・射程外・射線遮断の敵を除外する
149 : func (st *ShootingState) refreshEnemies(world w.World) error {
150 1 : enemies, err := query.GetVisibleEnemies(world)
151 1 : if err != nil {
152 0 : return err
153 0 : }
154 :
155 1 : playerEntity, playerErr := query.GetPlayerEntity(world)
156 1 : if playerErr != nil {
157 0 : return playerErr
158 0 : }
159 :
160 : // 射撃可能な敵のみ残す
161 1 : var shootable []ecs.Entity
162 1 : for _, e := range enemies {
163 0 : if activity.CanShootTarget(playerEntity, e, world) {
164 0 : shootable = append(shootable, e)
165 0 : }
166 : }
167 :
168 : // プレイヤーからの距離順にソート
169 1 : slices.SortFunc(shootable, func(a, b ecs.Entity) int {
170 0 : da := activity.EntityDistance(playerEntity, a, world)
171 0 : db := activity.EntityDistance(playerEntity, b, world)
172 0 : return cmp.Compare(da, db)
173 0 : })
174 :
175 1 : st.enemies = shootable
176 1 : if st.targetIndex >= len(st.enemies) {
177 1 : st.targetIndex = 0
178 1 : }
179 1 : return nil
180 : }
181 :
182 : // updateTargetCache はターゲット変更時に命中率と距離をキャッシュする
183 : func (st *ShootingState) updateTargetCache(world w.World) {
184 1 : if len(st.enemies) == 0 {
185 1 : return
186 1 : }
187 0 : playerEntity, err := query.GetPlayerEntity(world)
188 0 : if err != nil {
189 0 : return
190 0 : }
191 0 : target := st.enemies[st.targetIndex]
192 0 : st.cachedHitRate = activity.CalculateShootHitRate(playerEntity, target, world)
193 0 : st.cachedDistance = activity.EntityDistance(playerEntity, target, world)
194 : }
195 :
196 : // Draw はステートの描画処理
197 : func (st *ShootingState) Draw(world w.World, screen *ebiten.Image) error {
198 1 : if len(st.enemies) > 0 {
199 0 : if err := st.drawTargetCursor(world, screen); err != nil {
200 0 : return err
201 0 : }
202 : }
203 1 : return st.drawShootingPanel(world, screen)
204 : }
205 :
206 : // drawTargetCursor は選択中の敵にカーソルを描画する
207 : func (st *ShootingState) drawTargetCursor(world w.World, screen *ebiten.Image) error {
208 0 : target := st.enemies[st.targetIndex]
209 0 : if !world.Components.GridElement.Has(target) {
210 0 : return nil
211 0 : }
212 0 : targetCoord := world.Components.GridElement.Get(target).Coord
213 0 :
214 0 : projector, err := render3d.WorldProjector(world)
215 0 : if err != nil {
216 0 : return err
217 0 : }
218 0 : corners, ok := projector.TileCorners(targetCoord, render3d.TileTopHeight(world, targetCoord))
219 0 : if !ok {
220 0 : return nil
221 0 : }
222 :
223 0 : cursorColor := theme.CursorShoot
224 0 : if !world.Resources.Config.DisableAnimation {
225 0 : cursorColor = hud.ScaleAlpha(cursorColor, 0.6+0.4*math.Sin(float64(st.blinkCounter)*0.15))
226 0 : }
227 0 : hud.TileFrame(screen, corners, cursorFrameWidth, cursorColor)
228 0 : return nil
229 : }
230 :
231 : // drawShootingPanel は射撃情報パネルを描画する
232 : func (st *ShootingState) drawShootingPanel(world w.World, screen *ebiten.Image) error {
233 1 : face := world.Resources.UIResources.Text.BodyFace
234 1 :
235 1 : const panelHeight = 250
236 1 : panel := hud.NewInfoPanel(uicore.NewEbitenCanvas(screen), hud.Chrome{}, face, screen.Bounds().Dx(), panelHeight)
237 1 : drawText := panel.Line
238 1 :
239 1 : drawText(query.T(world, "== Shooting Mode =="))
240 1 : panel.Gap(5)
241 1 :
242 : // 武器・残弾情報
243 1 : playerEntity, err := query.GetPlayerEntity(world)
244 1 : if err != nil {
245 0 : drawText(query.T(world, "Error: player not found"))
246 0 : return err
247 0 : }
248 :
249 1 : st.drawWeaponInfo(world, playerEntity, drawText)
250 1 : panel.Gap(5)
251 1 :
252 : // ターゲット情報
253 1 : if msg := st.checkFireWeaponStatus(world); msg != "" {
254 1 : drawText(msg)
255 1 : } else if len(st.enemies) == 0 {
256 0 : drawText(query.T(world, "No shooting target"))
257 0 : } else {
258 0 : target := st.enemies[st.targetIndex]
259 0 : st.drawTargetInfo(world, target, drawText)
260 0 : }
261 :
262 : // 操作説明
263 1 : panel.SeekBottom(30)
264 1 : drawText(query.T(world, "Tab: Switch Enter: Fire R: Reload Esc: Back"))
265 1 :
266 1 : return nil
267 : }
268 :
269 : // drawWeaponInfo は武器情報を描画する
270 : func (st *ShootingState) drawWeaponInfo(world w.World, playerEntity ecs.Entity, drawText func(string)) {
271 1 : selectedSlot := query.GetWeaponSelection(world).Slot
272 1 : weapons := query.GetWeapons(world, playerEntity)
273 1 : weaponIndex := selectedSlot - 1
274 1 : if weaponIndex < 0 || weaponIndex >= len(weapons) {
275 0 : drawText(query.T(world, "Weapon slot: invalid"))
276 0 : return
277 0 : }
278 :
279 1 : weaponEntity := weapons[weaponIndex]
280 1 : if weaponEntity == nil {
281 0 : drawText(query.T(world, "Weapon: none"))
282 0 : return
283 0 : }
284 :
285 : // 武器名
286 1 : weaponName := query.GetEntityName(*weaponEntity, world)
287 1 : drawText(fmt.Sprintf("%s: %s", query.T(world, "Weapon"), weaponName))
288 1 :
289 : // 残弾表示
290 1 : fireComp := world.Components.Fire.Get(*weaponEntity)
291 1 : if fireComp != nil {
292 0 : drawText(fmt.Sprintf("%s: %d/%d", query.T(world, "Ammo"), fireComp.Magazine, fireComp.MagazineSize))
293 0 : } else {
294 1 : drawText(query.T(world, "Melee weapon"))
295 1 : }
296 : }
297 :
298 : // drawTargetInfo はターゲット情報を描画する。キャッシュ済みの値を使用する
299 : func (st *ShootingState) drawTargetInfo(world w.World, target ecs.Entity, drawText func(string)) {
300 0 : drawText(fmt.Sprintf("%s: %s (%d/%d)", query.T(world, "Target"),
301 0 : query.GetEntityName(target, world),
302 0 : st.targetIndex+1, len(st.enemies)))
303 0 :
304 : // HP
305 0 : if world.Components.HP.Has(target) {
306 0 : hp := world.Components.HP.Get(target)
307 0 : drawText(fmt.Sprintf("%s: %d/%d", query.T(world, "HP"), hp.Current, hp.Max))
308 0 : }
309 :
310 0 : drawText(fmt.Sprintf("%s: %d%%", query.T(world, "Hit rate"), st.cachedHitRate))
311 0 : drawText(fmt.Sprintf("%s: %.1f", query.T(world, "Distance"), st.cachedDistance))
312 : }
|