OSDN Git Service

Merge pull request #1406 from habu1010/feature/enum-to-integral-function
[hengbandforosx/hengbandosx.git] / src / grid / grid.cpp
1 /*!
2  * @brief グリッドの実装 / low level dungeon routines -BEN-
3  * @date 2013/12/30
4  * @author
5  * Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke\n
6  *\n
7  * This software may be copied and distributed for educational, research,\n
8  * and not for profit purposes provided that this copyright and statement\n
9  * are included in all such copies.  Other copyrights may also apply.\n
10  * \n
11  * Support for Adam Bolt's tileset, lighting and transparency effects\n
12  * by Robert Ruehlmann (rr9@angband.org)\n
13  * \n
14  * 2013 Deskull Doxygen向けのコメント整理\n
15  */
16
17 #include "grid/grid.h"
18 #include "core/window-redrawer.h"
19 #include "dungeon/dungeon-flag-types.h"
20 #include "dungeon/dungeon.h"
21 #include "dungeon/quest.h"
22 #include "effect/effect-characteristics.h"
23 #include "effect/effect-processor.h"
24 #include "floor/cave.h"
25 #include "floor/floor-generator.h"
26 #include "floor/geometry.h"
27 #include "game-option/game-play-options.h"
28 #include "game-option/map-screen-options.h"
29 #include "game-option/special-options.h"
30 #include "grid/feature-action-flags.h"
31 #include "grid/feature.h"
32 #include "grid/object-placer.h"
33 #include "grid/trap.h"
34 #include "io/screen-util.h"
35 #include "monster-floor/monster-remover.h"
36 #include "monster-race/monster-race.h"
37 #include "monster-race/race-flags2.h"
38 #include "monster-race/race-flags7.h"
39 #include "monster/monster-info.h"
40 #include "monster/monster-status.h"
41 #include "monster/monster-update.h"
42 #include "object/item-tester-hooker.h"
43 #include "object/object-mark-types.h"
44 #include "player/player-class.h"
45 #include "player/player-status-flags.h"
46 #include "player/player-status.h"
47 #include "room/rooms-builder.h"
48 #include "spell/spell-types.h"
49 #include "system/floor-type-definition.h"
50 #include "system/grid-type-definition.h"
51 #include "system/monster-race-definition.h"
52 #include "system/monster-type-definition.h"
53 #include "system/object-type-definition.h"
54 #include "system/player-type-definition.h"
55 #include "term/term-color-types.h"
56 #include "util/bit-flags-calculator.h"
57 #include "util/enum-converter.h"
58 #include "util/point-2d.h"
59 #include "view/display-map.h"
60 #include "view/display-messages.h"
61 #include "window/main-window-util.h"
62 #include "world/world.h"
63 #include <queue>
64
65 #define MONSTER_FLOW_DEPTH                                                                                                                                     \
66     32 /*!< 敵のプレイヤーに対する移動道のりの最大値(この値以上は処理を打ち切る) / OPTION: Maximum flow depth when using "MONSTER_FLOW" */
67
68 /*!
69  * @brief 新規フロアに入りたてのプレイヤーをランダムな場所に配置する / Returns random co-ordinates for player/monster/object
70  * @param creature_ptr 配置したいクリーチャーの参照ポインタ
71  * @return 配置に成功したらTRUEを返す
72  */
73 bool new_player_spot(player_type *creature_ptr)
74 {
75     POSITION y = 0, x = 0;
76     int max_attempts = 10000;
77
78     grid_type *g_ptr;
79     feature_type *f_ptr;
80
81     while (max_attempts--) {
82         /* Pick a legal spot */
83         y = (POSITION)rand_range(1, creature_ptr->current_floor_ptr->height - 2);
84         x = (POSITION)rand_range(1, creature_ptr->current_floor_ptr->width - 2);
85
86         g_ptr = &creature_ptr->current_floor_ptr->grid_array[y][x];
87
88         /* Must be a "naked" floor grid */
89         if (g_ptr->m_idx)
90             continue;
91         if (is_in_dungeon(creature_ptr)) {
92             f_ptr = &f_info[g_ptr->feat];
93
94             if (max_attempts > 5000) /* Rule 1 */
95             {
96                 if (f_ptr->flags.has_not(FF::FLOOR))
97                     continue;
98             } else /* Rule 2 */
99             {
100                 if (f_ptr->flags.has_not(FF::MOVE))
101                     continue;
102                 if (f_ptr->flags.has(FF::HIT_TRAP))
103                     continue;
104             }
105
106             /* Refuse to start on anti-teleport grids in dungeon */
107             if (f_ptr->flags.has_not(FF::TELEPORTABLE))
108                 continue;
109         }
110         if (!player_can_enter(creature_ptr, g_ptr->feat, 0))
111             continue;
112         if (!in_bounds(creature_ptr->current_floor_ptr, y, x))
113             continue;
114
115         /* Refuse to start on anti-teleport grids */
116         if (g_ptr->is_icky())
117             continue;
118
119         break;
120     }
121
122     if (max_attempts < 1) /* Should be -1, actually if we failed... */
123         return false;
124
125     /* Save the new player grid */
126     creature_ptr->y = y;
127     creature_ptr->x = x;
128
129     return true;
130 }
131
132 /*!
133  * @brief マスに隠されたドアがあるかの判定を行う。 / Return TRUE if the given grid is a hidden closed door
134  * @param player_ptr プレーヤーへの参照ポインタ
135  * @param g_ptr マス構造体の参照ポインタ
136  * @return 隠されたドアがあるならTRUEを返す。
137  */
138 bool is_hidden_door(player_type *player_ptr, grid_type *g_ptr)
139 {
140     if ((g_ptr->mimic || g_ptr->cave_has_flag(FF::SECRET)) && is_closed_door(player_ptr, g_ptr->feat))
141         return true;
142     else
143         return false;
144 }
145
146 /*!
147  * @brief 指定された座標のマスが現在照らされているかを返す。 / Check for "local" illumination
148  * @param y y座標
149  * @param x x座標
150  * @return 指定された座標に照明がかかっているならTRUEを返す。。
151  */
152 bool check_local_illumination(player_type *creature_ptr, POSITION y, POSITION x)
153 {
154     /* Hack -- move towards player */
155     POSITION yy = (y < creature_ptr->y) ? (y + 1) : (y > creature_ptr->y) ? (y - 1) : y;
156     POSITION xx = (x < creature_ptr->x) ? (x + 1) : (x > creature_ptr->x) ? (x - 1) : x;
157
158     /* Check for "local" illumination */
159
160     /* Check for "complex" illumination */
161     auto *floor_ptr = creature_ptr->current_floor_ptr;
162     if ((feat_supports_los(floor_ptr->grid_array[yy][xx].get_feat_mimic())
163             && (floor_ptr->grid_array[yy][xx].info & CAVE_GLOW))
164         || (feat_supports_los(floor_ptr->grid_array[y][xx].get_feat_mimic())
165             && (floor_ptr->grid_array[y][xx].info & CAVE_GLOW))
166         || (feat_supports_los(floor_ptr->grid_array[yy][x].get_feat_mimic())
167             && (floor_ptr->grid_array[yy][x].info & CAVE_GLOW))) {
168         return true;
169     } else
170         return false;
171 }
172
173 /*! 対象座標のマスの照明状態を更新する際の補助処理マクロ */
174 #define update_local_illumination_aux(C, Y, X)                                                                                                                 \
175     {                                                                                                                                                          \
176         if (player_has_los_bold((C), (Y), (X))) {                                                                                                              \
177             /* Update the monster */                                                                                                                           \
178             if ((C)->current_floor_ptr->grid_array[(Y)][(X)].m_idx)                                                                                            \
179                 update_monster((C), (C)->current_floor_ptr->grid_array[(Y)][(X)].m_idx, false);                                                                \
180                                                                                                                                                                \
181             /* Notice and redraw */                                                                                                                            \
182             note_spot((C), (Y), (X));                                                                                                                          \
183             lite_spot((C), (Y), (X));                                                                                                                          \
184         }                                                                                                                                                      \
185     }
186
187 /*!
188  * @brief 指定された座標の照明状態を更新する / Update "local" illumination
189  * @param creature_ptr 視界元のクリーチャー
190  * @param y 視界先y座標
191  * @param x 視界先x座標
192  */
193 void update_local_illumination(player_type *creature_ptr, POSITION y, POSITION x)
194 {
195     int i;
196     POSITION yy, xx;
197
198     if (!in_bounds(creature_ptr->current_floor_ptr, y, x))
199         return;
200
201     if ((y != creature_ptr->y) && (x != creature_ptr->x)) {
202         yy = (y < creature_ptr->y) ? (y - 1) : (y + 1);
203         xx = (x < creature_ptr->x) ? (x - 1) : (x + 1);
204         update_local_illumination_aux(creature_ptr, yy, xx);
205         update_local_illumination_aux(creature_ptr, y, xx);
206         update_local_illumination_aux(creature_ptr, yy, x);
207     } else if (x != creature_ptr->x) /* y == creature_ptr->y */
208     {
209         xx = (x < creature_ptr->x) ? (x - 1) : (x + 1);
210         for (i = -1; i <= 1; i++) {
211             yy = y + i;
212             update_local_illumination_aux(creature_ptr, yy, xx);
213         }
214         yy = y - 1;
215         update_local_illumination_aux(creature_ptr, yy, x);
216         yy = y + 1;
217         update_local_illumination_aux(creature_ptr, yy, x);
218     } else if (y != creature_ptr->y) /* x == creature_ptr->x */
219     {
220         yy = (y < creature_ptr->y) ? (y - 1) : (y + 1);
221         for (i = -1; i <= 1; i++) {
222             xx = x + i;
223             update_local_illumination_aux(creature_ptr, yy, xx);
224         }
225         xx = x - 1;
226         update_local_illumination_aux(creature_ptr, y, xx);
227         xx = x + 1;
228         update_local_illumination_aux(creature_ptr, y, xx);
229     } else /* Player's grid */
230     {
231         for (i = 0; i < 8; i++) {
232             yy = y + ddy_cdd[i];
233             xx = x + ddx_cdd[i];
234             update_local_illumination_aux(creature_ptr, yy, xx);
235         }
236     }
237 }
238
239 /*!
240  * @brief 指定された座標をプレイヤー収められていない状態かどうか / Returns true if the player's grid is dark
241  * @return 視覚に収められていないならTRUEを返す
242  * @details player_can_see_bold()関数の返り値の否定を返している。
243  */
244 bool no_lite(player_type *creature_ptr)
245 {
246     return (!player_can_see_bold(creature_ptr, creature_ptr->y, creature_ptr->x));
247 }
248
249 /*
250  * Place an attr/char pair at the given map coordinate, if legal.
251  */
252 void print_rel(player_type *subject_ptr, SYMBOL_CODE c, TERM_COLOR a, POSITION y, POSITION x)
253 {
254     /* Only do "legal" locations */
255     if (panel_contains(y, x)) {
256         /* Hack -- fake monochrome */
257         if (!use_graphics) {
258             if (current_world_ptr->timewalk_m_idx)
259                 a = TERM_DARK;
260             else if (is_invuln(subject_ptr) || subject_ptr->timewalk)
261                 a = TERM_WHITE;
262             else if (subject_ptr->wraith_form)
263                 a = TERM_L_DARK;
264         }
265
266         /* Draw the char using the attr */
267         term_queue_bigchar(panel_col_of(x), y - panel_row_prt, a, c, 0, 0);
268     }
269 }
270
271 /*!
272  * @todo ここにplayer_type を追加した時のコンパイルエラーに対処できなかったので保留
273  * Memorize interesting viewable object/features in the given grid
274  *
275  * This function should only be called on "legal" grids.
276  *
277  * This function will memorize the object and/or feature in the given
278  * grid, if they are (1) viewable and (2) interesting.  Note that all
279  * objects are interesting, all terrain features except floors (and
280  * invisible traps) are interesting, and floors (and invisible traps)
281  * are interesting sometimes (depending on various options involving
282  * the illumination of floor grids).
283  *
284  * The automatic memorization of all objects and non-floor terrain
285  * features as soon as they are displayed allows incredible amounts
286  * of optimization in various places, especially "map_info()".
287  *
288  * Note that the memorization of objects is completely separate from
289  * the memorization of terrain features, preventing annoying floor
290  * memorization when a detected object is picked up from a dark floor,
291  * and object memorization when an object is dropped into a floor grid
292  * which is memorized but out-of-sight.
293  *
294  * This function should be called every time the "memorization" of
295  * a grid (or the object in a grid) is called into question, such
296  * as when an object is created in a grid, when a terrain feature
297  * "changes" from "floor" to "non-floor", when any grid becomes
298  * "illuminated" or "viewable", and when a "floor" grid becomes
299  * "torch-lit".
300  *
301  * Note the relatively efficient use of this function by the various
302  * "update_view()" and "update_lite()" calls, to allow objects and
303  * terrain features to be memorized (and drawn) whenever they become
304  * viewable or illuminated in any way, but not when they "maintain"
305  * or "lose" their previous viewability or illumination.
306  *
307  * Note the butchered "internal" version of "player_can_see_bold()",
308  * optimized primarily for the most common cases, that is, for the
309  * non-marked floor grids.
310  */
311 void note_spot(player_type *player_ptr, POSITION y, POSITION x)
312 {
313     grid_type *g_ptr = &player_ptr->current_floor_ptr->grid_array[y][x];
314
315     /* Blind players see nothing */
316     if (player_ptr->blind)
317         return;
318
319     /* Analyze non-torch-lit grids */
320     if (!(g_ptr->info & (CAVE_LITE | CAVE_MNLT))) {
321         /* Require line of sight to the grid */
322         if (!(g_ptr->info & (CAVE_VIEW)))
323             return;
324
325         /* Require "perma-lite" of the grid */
326         if ((g_ptr->info & (CAVE_GLOW | CAVE_MNDK)) != CAVE_GLOW) {
327             /* Not Ninja */
328             if (!player_ptr->see_nocto)
329                 return;
330         }
331     }
332
333     /* Hack -- memorize objects */
334     for (const auto this_o_idx : g_ptr->o_idx_list) {
335         object_type *o_ptr = &player_ptr->current_floor_ptr->o_list[this_o_idx];
336
337         /* Memorize objects */
338         o_ptr->marked |= OM_FOUND;
339     }
340
341     /* Hack -- memorize grids */
342     if (!g_ptr->is_mark()) {
343         /* Feature code (applying "mimic" field) */
344         feature_type *f_ptr = &f_info[g_ptr->get_feat_mimic()];
345
346         /* Memorize some "boring" grids */
347         if (f_ptr->flags.has_not(FF::REMEMBER)) {
348             /* Option -- memorize all torch-lit floors */
349             if (view_torch_grids && ((g_ptr->info & (CAVE_LITE | CAVE_MNLT)) || player_ptr->see_nocto)) {
350                 g_ptr->info |= (CAVE_MARK);
351             }
352
353             /* Option -- memorize all perma-lit floors */
354             else if (view_perma_grids && ((g_ptr->info & (CAVE_GLOW | CAVE_MNDK)) == CAVE_GLOW)) {
355                 g_ptr->info |= (CAVE_MARK);
356             }
357         }
358
359         /* Memorize normal grids */
360         else if (f_ptr->flags.has(FF::LOS)) {
361             g_ptr->info |= (CAVE_MARK);
362         }
363
364         /* Memorize torch-lit walls */
365         else if (g_ptr->info & (CAVE_LITE | CAVE_MNLT)) {
366             g_ptr->info |= (CAVE_MARK);
367         }
368
369         /* Memorize walls seen by noctovision of Ninja */
370         else if (player_ptr->see_nocto) {
371             g_ptr->info |= (CAVE_MARK);
372         }
373
374         /* Memorize certain non-torch-lit wall grids */
375         else if (check_local_illumination(player_ptr, y, x)) {
376             g_ptr->info |= (CAVE_MARK);
377         }
378     }
379
380     /* Memorize terrain of the grid */
381     g_ptr->info |= (CAVE_KNOWN);
382 }
383
384 /*
385  * Redraw (on the screen) a given MAP location
386  *
387  * This function should only be called on "legal" grids
388  */
389 void lite_spot(player_type *player_ptr, POSITION y, POSITION x)
390 {
391     /* Redraw if on screen */
392     if (panel_contains(y, x) && in_bounds2(player_ptr->current_floor_ptr, y, x)) {
393         TERM_COLOR a;
394         SYMBOL_CODE c;
395         TERM_COLOR ta;
396         SYMBOL_CODE tc;
397
398         map_info(player_ptr, y, x, &a, &c, &ta, &tc);
399
400         /* Hack -- fake monochrome */
401         if (!use_graphics) {
402             if (current_world_ptr->timewalk_m_idx)
403                 a = TERM_DARK;
404             else if (is_invuln(player_ptr) || player_ptr->timewalk)
405                 a = TERM_WHITE;
406             else if (player_ptr->wraith_form)
407                 a = TERM_L_DARK;
408         }
409
410         /* Hack -- Queue it */
411         term_queue_bigchar(panel_col_of(x), y - panel_row_prt, a, c, ta, tc);
412
413         /* Update sub-windows */
414         player_ptr->window_flags |= (PW_OVERHEAD | PW_DUNGEON);
415     }
416 }
417
418 /*
419  * Some comments on the grid flags.  -BEN-
420  *
421  *
422  * One of the major bottlenecks in previous versions of Angband was in
423  * the calculation of "line of sight" from the player to various grids,
424  * such as monsters.  This was such a nasty bottleneck that a lot of
425  * silly things were done to reduce the dependancy on "line of sight",
426  * for example, you could not "see" any grids in a lit room until you
427  * actually entered the room, and there were all kinds of bizarre grid
428  * flags to enable this behavior.  This is also why the "call light"
429  * spells always lit an entire room.
430  *
431  * The code below provides functions to calculate the "field of view"
432  * for the player, which, once calculated, provides extremely fast
433  * calculation of "line of sight from the player", and to calculate
434  * the "field of torch lite", which, again, once calculated, provides
435  * extremely fast calculation of "which grids are lit by the player's
436  * lite source".  In addition to marking grids as "GRID_VIEW" and/or
437  * "GRID_LITE", as appropriate, these functions maintain an array for
438  * each of these two flags, each array containing the locations of all
439  * of the grids marked with the appropriate flag, which can be used to
440  * very quickly scan through all of the grids in a given set.
441  *
442  * To allow more "semantically valid" field of view semantics, whenever
443  * the field of view (or the set of torch lit grids) changes, all of the
444  * grids in the field of view (or the set of torch lit grids) are "drawn"
445  * so that changes in the world will become apparent as soon as possible.
446  * This has been optimized so that only grids which actually "change" are
447  * redrawn, using the "temp" array and the "GRID_TEMP" flag to keep track
448  * of the grids which are entering or leaving the relevent set of grids.
449  *
450  * These new methods are so efficient that the old nasty code was removed.
451  *
452  * Note that there is no reason to "update" the "viewable space" unless
453  * the player "moves", or walls/doors are created/destroyed, and there
454  * is no reason to "update" the "torch lit grids" unless the field of
455  * view changes, or the "light radius" changes.  This means that when
456  * the player is resting, or digging, or doing anything that does not
457  * involve movement or changing the state of the dungeon, there is no
458  * need to update the "view" or the "lite" regions, which is nice.
459  *
460  * Note that the calls to the nasty "los()" function have been reduced
461  * to a bare minimum by the use of the new "field of view" calculations.
462  *
463  * I wouldn't be surprised if slight modifications to the "update_view()"
464  * function would allow us to determine "reverse line-of-sight" as well
465  * as "normal line-of-sight", which would allow monsters to use a more
466  * "correct" calculation to determine if they can "see" the player.  For
467  * now, monsters simply "cheat" somewhat and assume that if the player
468  * has "line of sight" to the monster, then the monster can "pretend"
469  * that it has "line of sight" to the player.
470  *
471  *
472  * The "update_lite()" function maintains the "CAVE_LITE" flag for each
473  * grid and maintains an array of all "CAVE_LITE" grids.
474  *
475  * This set of grids is the complete set of all grids which are lit by
476  * the players light source, which allows the "player_can_see_bold()"
477  * function to work very quickly.
478  *
479  * Note that every "CAVE_LITE" grid is also a "CAVE_VIEW" grid, and in
480  * fact, the player (unless blind) can always "see" all grids which are
481  * marked as "CAVE_LITE", unless they are "off screen".
482  *
483  *
484  * The "update_view()" function maintains the "CAVE_VIEW" flag for each
485  * grid and maintains an array of all "CAVE_VIEW" grids.
486  *
487  * This set of grids is the complete set of all grids within line of sight
488  * of the player, allowing the "player_has_los_bold()" macro to work very
489  * quickly.
490  *
491  *
492  * The current "update_view()" algorithm uses the "CAVE_XTRA" flag as a
493  * temporary internal flag to mark those grids which are not only in view,
494  * but which are also "easily" in line of sight of the player.  This flag
495  * is always cleared when we are done.
496  *
497  *
498  * The current "update_lite()" and "update_view()" algorithms use the
499  * "CAVE_TEMP" flag, and the array of grids which are marked as "CAVE_TEMP",
500  * to keep track of which grids were previously marked as "CAVE_LITE" or
501  * "CAVE_VIEW", which allows us to optimize the "screen updates".
502  *
503  * The "CAVE_TEMP" flag, and the array of "CAVE_TEMP" grids, is also used
504  * for various other purposes, such as spreading lite or darkness during
505  * "lite_room()" / "unlite_room()", and for calculating monster flow.
506  *
507  *
508  * Any grid can be marked as "CAVE_GLOW" which means that the grid itself is
509  * in some way permanently lit.  However, for the player to "see" anything
510  * in the grid, as determined by "player_can_see()", the player must not be
511  * blind, the grid must be marked as "CAVE_VIEW", and, in addition, "wall"
512  * grids, even if marked as "perma lit", are only illuminated if they touch
513  * a grid which is not a wall and is marked both "CAVE_GLOW" and "CAVE_VIEW".
514  *
515  *
516  * To simplify various things, a grid may be marked as "CAVE_MARK", meaning
517  * that even if the player cannot "see" the grid, he "knows" the terrain in
518  * that grid.  This is used to "remember" walls/doors/stairs/floors when they
519  * are "seen" or "detected", and also to "memorize" floors, after "wiz_lite()",
520  * or when one of the "memorize floor grids" options induces memorization.
521  *
522  * Objects are "memorized" in a different way, using a special "marked" flag
523  * on the object itself, which is set when an object is observed or detected.
524  *
525  *
526  * A grid may be marked as "CAVE_ROOM" which means that it is part of a "room",
527  * and should be illuminated by "lite room" and "darkness" spells.
528  *
529  *
530  * A grid may be marked as "CAVE_ICKY" which means it is part of a "vault",
531  * and should be unavailable for "teleportation" destinations.
532  *
533  *
534  * The "view_perma_grids" allows the player to "memorize" every perma-lit grid
535  * which is observed, and the "view_torch_grids" allows the player to memorize
536  * every torch-lit grid.  The player will always memorize important walls,
537  * doors, stairs, and other terrain features, as well as any "detected" grids.
538  *
539  * Note that the new "update_view()" method allows, among other things, a room
540  * to be "partially" seen as the player approaches it, with a growing cone of
541  * floor appearing as the player gets closer to the door.  Also, by not turning
542  * on the "memorize perma-lit grids" option, the player will only "see" those
543  * floor grids which are actually in line of sight.
544  *
545  * And my favorite "plus" is that you can now use a special option to draw the
546  * "floors" in the "viewable region" brightly (actually, to draw the *other*
547  * grids dimly), providing a "pretty" effect as the player runs around, and
548  * to efficiently display the "torch lite" in a special color.
549  *
550  *
551  * Some comments on the "update_view()" algorithm...
552  *
553  * The algorithm is very fast, since it spreads "obvious" grids very quickly,
554  * and only has to call "los()" on the borderline cases.  The major axes/diags
555  * even terminate early when they hit walls.  I need to find a quick way
556  * to "terminate" the other scans.
557  *
558  * Note that in the worst case (a big empty area with say 5% scattered walls),
559  * each of the 1500 or so nearby grids is checked once, most of them getting
560  * an "instant" rating, and only a small portion requiring a call to "los()".
561  *
562  * The only time that the algorithm appears to be "noticeably" too slow is
563  * when running, and this is usually only important in town, since the town
564  * provides about the worst scenario possible, with large open regions and
565  * a few scattered obstructions.  There is a special "efficiency" option to
566  * allow the player to reduce his field of view in town, if needed.
567  *
568  * In the "best" case (say, a normal stretch of corridor), the algorithm
569  * makes one check for each viewable grid, and makes no calls to "los()".
570  * So running in corridors is very fast, and if a lot of monsters are
571  * nearby, it is much faster than the old methods.
572  *
573  * Note that resting, most normal commands, and several forms of running,
574  * plus all commands executed near large groups of monsters, are strictly
575  * more efficient with "update_view()" that with the old "compute los() on
576  * demand" method, primarily because once the "field of view" has been
577  * calculated, it does not have to be recalculated until the player moves
578  * (or a wall or door is created or destroyed).
579  *
580  * Note that we no longer have to do as many "los()" checks, since once the
581  * "view" region has been built, very few things cause it to be "changed"
582  * (player movement, and the opening/closing of doors, changes in wall status).
583  * Note that door/wall changes are only relevant when the door/wall itself is
584  * in the "view" region.
585  *
586  * The algorithm seems to only call "los()" from zero to ten times, usually
587  * only when coming down a corridor into a room, or standing in a room, just
588  * misaligned with a corridor.  So if, say, there are five "nearby" monsters,
589  * we will be reducing the calls to "los()".
590  *
591  * I am thinking in terms of an algorithm that "walks" from the central point
592  * out to the maximal "distance", at each point, determining the "view" code
593  * (above).  For each grid not on a major axis or diagonal, the "view" code
594  * depends on the "cave_los_bold()" and "view" of exactly two other grids
595  * (the one along the nearest diagonal, and the one next to that one, see
596  * "update_view_aux()"...).
597  *
598  * We "memorize" the viewable space array, so that at the cost of under 3000
599  * bytes, we reduce the time taken by "forget_view()" to one assignment for
600  * each grid actually in the "viewable space".  And for another 3000 bytes,
601  * we prevent "erase + redraw" ineffiencies via the "seen" set.  These bytes
602  * are also used by other routines, thus reducing the cost to almost nothing.
603  *
604  * A similar thing is done for "forget_lite()" in which case the savings are
605  * much less, but save us from doing bizarre maintenance checking.
606  *
607  * In the worst "normal" case (in the middle of the town), the reachable space
608  * actually reaches to more than half of the largest possible "circle" of view,
609  * or about 800 grids, and in the worse case (in the middle of a dungeon level
610  * where all the walls have been removed), the reachable space actually reaches
611  * the theoretical maximum size of just under 1500 grids.
612  *
613  * Each grid G examines the "state" of two (?) other (adjacent) grids, G1 & G2.
614  * If G1 is lite, G is lite.  Else if G2 is lite, G is half.  Else if G1 and G2
615  * are both half, G is half.  Else G is dark.  It only takes 2 (or 4) bits to
616  * "name" a grid, so (for MAX_RAD of 20) we could use 1600 bytes, and scan the
617  * entire possible space (including initialization) in one step per grid.  If
618  * we do the "clearing" as a separate step (and use an array of "view" grids),
619  * then the clearing will take as many steps as grids that were viewed, and the
620  * algorithm will be able to "stop" scanning at various points.
621  * Oh, and outside of the "torch radius", only "lite" grids need to be scanned.
622  */
623
624 /*
625  * Hack - speed up the update_flow algorithm by only doing
626  * it everytime the player moves out of LOS of the last
627  * "way-point".
628  */
629 static POSITION flow_x = 0;
630 static POSITION flow_y = 0;
631
632 /*
633  * Hack -- fill in the "cost" field of every grid that the player
634  * can "reach" with the number of steps needed to reach that grid.
635  * This also yields the "distance" of the player from every grid.
636  *
637  * In addition, mark the "when" of the grids that can reach
638  * the player with the incremented value of "flow_n".
639  *
640  * Hack -- use the "seen" array as a "circular queue".
641  *
642  * We do not need a priority queue because the cost from grid
643  * to grid is always "one" and we process them in order.
644  */
645 void update_flow(player_type *subject_ptr)
646 {
647     POSITION x, y;
648     DIRECTION d;
649     floor_type *f_ptr = subject_ptr->current_floor_ptr;
650
651     /* The last way-point is on the map */
652     if (subject_ptr->running && in_bounds(f_ptr, flow_y, flow_x)) {
653         /* The way point is in sight - do not update.  (Speedup) */
654         if (f_ptr->grid_array[flow_y][flow_x].info & CAVE_VIEW)
655             return;
656     }
657
658     /* Erase all of the current flow information */
659     for (y = 0; y < f_ptr->height; y++) {
660         for (x = 0; x < f_ptr->width; x++) {
661             memset(&f_ptr->grid_array[y][x].costs, 0, sizeof(f_ptr->grid_array[y][x].costs));
662             memset(&f_ptr->grid_array[y][x].dists, 0, sizeof(f_ptr->grid_array[y][x].dists));
663         }
664     }
665
666     /* Save player position */
667     flow_y = subject_ptr->y;
668     flow_x = subject_ptr->x;
669
670     for (int i = 0; i < FLOW_MAX; i++) {
671         // 幅優先探索用のキュー。
672         std::queue<Pos2D> que;
673         que.emplace(subject_ptr->y, subject_ptr->x);
674
675         /* Now process the queue */
676         while (!que.empty()) {
677             /* Extract the next entry */
678             const auto [ty, tx] = que.front();
679             que.pop();
680
681             /* Add the "children" */
682             for (d = 0; d < 8; d++) {
683                 byte m = subject_ptr->current_floor_ptr->grid_array[ty][tx].costs[i] + 1;
684                 byte n = subject_ptr->current_floor_ptr->grid_array[ty][tx].dists[i] + 1;
685
686                 /* Child location */
687                 y = ty + ddy_ddd[d];
688                 x = tx + ddx_ddd[d];
689
690                 /* Ignore player's grid */
691                 if (player_bold(subject_ptr, y, x))
692                     continue;
693
694                 grid_type *g_ptr = &subject_ptr->current_floor_ptr->grid_array[y][x];
695
696                 if (is_closed_door(subject_ptr, g_ptr->feat))
697                     m += 3;
698
699                 /* Ignore "pre-stamped" entries */
700                 if (g_ptr->dists[i] != 0 && g_ptr->dists[i] <= n && g_ptr->costs[i] <= m)
701                     continue;
702
703                 /* Ignore "walls", "holes" and "rubble" */
704                 bool can_move = false;
705                 switch (i) {
706                 case FLOW_CAN_FLY:
707                     can_move = g_ptr->cave_has_flag(FF::MOVE) || g_ptr->cave_has_flag(FF::CAN_FLY);
708                     break;
709                 default:
710                     can_move = g_ptr->cave_has_flag(FF::MOVE);
711                     break;
712                 }
713
714                 if (!can_move && !is_closed_door(subject_ptr, g_ptr->feat))
715                     continue;
716
717                 /* Save the flow cost */
718                 if (g_ptr->costs[i] == 0 || g_ptr->costs[i] > m)
719                     g_ptr->costs[i] = m;
720                 if (g_ptr->dists[i] == 0 || g_ptr->dists[i] > n)
721                     g_ptr->dists[i] = n;
722
723                 /* Hack -- limit flow depth */
724                 if (n == MONSTER_FLOW_DEPTH)
725                     continue;
726
727                 /* Enqueue that entry */
728                 que.emplace(y, x);
729             }
730         }
731     }
732 }
733
734 /*
735  * Take a feature, determine what that feature becomes
736  * through applying the given action.
737  */
738 FEAT_IDX feat_state(floor_type *floor_ptr, FEAT_IDX feat, FF action)
739 {
740     feature_type *f_ptr = &f_info[feat];
741     int i;
742
743     /* Get the new feature */
744     for (i = 0; i < MAX_FEAT_STATES; i++) {
745         if (f_ptr->state[i].action == action)
746             return conv_dungeon_feat(floor_ptr, f_ptr->state[i].result);
747     }
748
749     if (f_ptr->flags.has(FF::PERMANENT))
750         return feat;
751
752     return (feature_action_flags[enum2i(action)] & FAF_DESTROY) ? conv_dungeon_feat(floor_ptr, f_ptr->destroyed) : feat;
753 }
754
755 /*
756  * Takes a location and action and changes the feature at that
757  * location through applying the given action.
758  */
759 void cave_alter_feat(player_type *player_ptr, POSITION y, POSITION x, FF action)
760 {
761     /* Set old feature */
762     floor_type *floor_ptr = player_ptr->current_floor_ptr;
763     FEAT_IDX oldfeat = floor_ptr->grid_array[y][x].feat;
764
765     /* Get the new feat */
766     FEAT_IDX newfeat = feat_state(player_ptr->current_floor_ptr, oldfeat, action);
767
768     /* No change */
769     if (newfeat == oldfeat)
770         return;
771
772     /* Set the new feature */
773     cave_set_feat(player_ptr, y, x, newfeat);
774
775     if (!(feature_action_flags[enum2i(action)] & FAF_NO_DROP)) {
776         feature_type *old_f_ptr = &f_info[oldfeat];
777         feature_type *f_ptr = &f_info[newfeat];
778         bool found = false;
779
780         /* Handle gold */
781         if (old_f_ptr->flags.has(FF::HAS_GOLD) && f_ptr->flags.has_not(FF::HAS_GOLD)) {
782             /* Place some gold */
783             place_gold(player_ptr, y, x);
784             found = true;
785         }
786
787         /* Handle item */
788         if (old_f_ptr->flags.has(FF::HAS_ITEM) && f_ptr->flags.has_not(FF::HAS_ITEM) && (randint0(100) < (15 - floor_ptr->dun_level / 2))) {
789             /* Place object */
790             place_object(player_ptr, y, x, 0L);
791             found = true;
792         }
793
794         if (found && current_world_ptr->character_dungeon && player_can_see_bold(player_ptr, y, x)) {
795             msg_print(_("何かを発見した!", "You have found something!"));
796         }
797     }
798
799     if (feature_action_flags[enum2i(action)] & FAF_CRASH_GLASS) {
800         feature_type *old_f_ptr = &f_info[oldfeat];
801
802         if (old_f_ptr->flags.has(FF::GLASS) && current_world_ptr->character_dungeon) {
803             project(player_ptr, PROJECT_WHO_GLASS_SHARDS, 1, y, x, MIN(floor_ptr->dun_level, 100) / 4, GF_SHARDS,
804                 (PROJECT_GRID | PROJECT_ITEM | PROJECT_KILL | PROJECT_HIDE | PROJECT_JUMP | PROJECT_NO_HANGEKI));
805         }
806     }
807 }
808
809 /* Remove a mirror */
810 void remove_mirror(player_type *caster_ptr, POSITION y, POSITION x)
811 {
812     grid_type *g_ptr = &caster_ptr->current_floor_ptr->grid_array[y][x];
813
814     /* Remove the mirror */
815     g_ptr->info &= ~(CAVE_OBJECT);
816     g_ptr->mimic = 0;
817
818     if (d_info[caster_ptr->dungeon_idx].flags.has(DF::DARKNESS)) {
819         g_ptr->info &= ~(CAVE_GLOW);
820         if (!view_torch_grids)
821             g_ptr->info &= ~(CAVE_MARK);
822         if (g_ptr->m_idx)
823             update_monster(caster_ptr, g_ptr->m_idx, false);
824
825         update_local_illumination(caster_ptr, y, x);
826     }
827
828     note_spot(caster_ptr, y, x);
829
830     lite_spot(caster_ptr, y, x);
831 }
832
833 /*!
834  * @brief 指定されたマスがモンスターのテレポート可能先かどうかを判定する。
835  * @param player_ptr プレーヤーへの参照ポインタ
836  * @param m_idx モンスターID
837  * @param y 移動先Y座標
838  * @param x 移動先X座標
839  * @param mode オプション
840  * @return テレポート先として妥当ならばtrue
841  */
842 bool cave_monster_teleportable_bold(player_type *player_ptr, MONSTER_IDX m_idx, POSITION y, POSITION x, teleport_flags mode)
843 {
844     monster_type *m_ptr = &player_ptr->current_floor_ptr->m_list[m_idx];
845     grid_type *g_ptr = &player_ptr->current_floor_ptr->grid_array[y][x];
846     feature_type *f_ptr = &f_info[g_ptr->feat];
847
848     /* Require "teleportable" space */
849     if (f_ptr->flags.has_not(FF::TELEPORTABLE))
850         return false;
851
852     if (g_ptr->m_idx && (g_ptr->m_idx != m_idx))
853         return false;
854     if (player_bold(player_ptr, y, x))
855         return false;
856
857     /* Hack -- no teleport onto rune of protection */
858     if (g_ptr->is_rune_protection())
859         return false;
860     if (g_ptr->is_rune_explosion())
861         return false;
862
863     if (!(mode & TELEPORT_PASSIVE)) {
864         if (!monster_can_cross_terrain(player_ptr, g_ptr->feat, &r_info[m_ptr->r_idx], 0))
865             return false;
866     }
867
868     return true;
869 }
870
871 /*!
872  * @brief 指定されたマスにプレイヤーがテレポート可能かどうかを判定する。
873  * @param player_ptr プレーヤーへの参照ポインタ
874  * @param y 移動先Y座標
875  * @param x 移動先X座標
876  * @param mode オプション
877  * @return テレポート先として妥当ならばtrue
878  */
879 bool cave_player_teleportable_bold(player_type *player_ptr, POSITION y, POSITION x, teleport_flags mode)
880 {
881     grid_type *g_ptr = &player_ptr->current_floor_ptr->grid_array[y][x];
882     feature_type *f_ptr = &f_info[g_ptr->feat];
883
884     /* Require "teleportable" space */
885     if (f_ptr->flags.has_not(FF::TELEPORTABLE))
886         return false;
887
888     /* No magical teleporting into vaults and such */
889     if (!(mode & TELEPORT_NONMAGICAL) && g_ptr->is_icky())
890         return false;
891
892     if (g_ptr->m_idx && (g_ptr->m_idx != player_ptr->riding))
893         return false;
894
895     /* don't teleport on a trap. */
896     if (f_ptr->flags.has(FF::HIT_TRAP))
897         return false;
898
899     if (!(mode & TELEPORT_PASSIVE)) {
900         if (!player_can_enter(player_ptr, g_ptr->feat, 0))
901             return false;
902
903         if (f_ptr->flags.has_all_of({FF::WATER, FF::DEEP})) {
904             if (!player_ptr->levitation && !player_ptr->can_swim)
905                 return false;
906         }
907
908         if (f_ptr->flags.has(FF::LAVA) && !has_immune_fire(player_ptr) && !is_invuln(player_ptr)) {
909             /* Always forbid deep lava */
910             if (f_ptr->flags.has(FF::DEEP))
911                 return false;
912
913             /* Forbid shallow lava when the player don't have levitation */
914             if (!player_ptr->levitation)
915                 return false;
916         }
917     }
918
919     return true;
920 }
921
922 /*!
923  * @brief 地形は開くものであって、かつ開かれているかを返す /
924  * Attempt to open the given chest at the given location
925  * @param feat 地形ID
926  * @return 開いた地形である場合TRUEを返す /  Return TRUE if the given feature is an open door
927  */
928 bool is_open(player_type *player_ptr, FEAT_IDX feat)
929 {
930     return f_info[feat].flags.has(FF::CLOSE) && (feat != feat_state(player_ptr->current_floor_ptr, feat, FF::CLOSE));
931 }
932
933 /*!
934  * @brief プレイヤーが地形踏破可能かを返す
935  * @param feature 判定したい地形ID
936  * @param mode 移動に関するオプションフラグ
937  * @return 移動可能ならばTRUEを返す
938  */
939 bool player_can_enter(player_type *creature_ptr, FEAT_IDX feature, BIT_FLAGS16 mode)
940 {
941     feature_type *f_ptr = &f_info[feature];
942
943     if (creature_ptr->riding)
944         return monster_can_cross_terrain(
945             creature_ptr, feature, &r_info[creature_ptr->current_floor_ptr->m_list[creature_ptr->riding].r_idx], mode | CEM_RIDING);
946
947     if (f_ptr->flags.has(FF::PATTERN)) {
948         if (!(mode & CEM_P_CAN_ENTER_PATTERN))
949             return false;
950     }
951
952     if (f_ptr->flags.has(FF::CAN_FLY) && creature_ptr->levitation)
953         return true;
954     if (f_ptr->flags.has(FF::CAN_SWIM) && creature_ptr->can_swim)
955         return true;
956     if (f_ptr->flags.has(FF::CAN_PASS) && has_pass_wall(creature_ptr))
957         return true;
958
959     if (f_ptr->flags.has_not(FF::MOVE))
960         return false;
961
962     return true;
963 }
964
965 void place_grid(player_type *player_ptr, grid_type *g_ptr, grid_bold_type gb_type)
966 {
967     switch (gb_type) {
968     case GB_FLOOR: {
969         g_ptr->feat = feat_ground_type[randint0(100)];
970         g_ptr->info &= ~(CAVE_MASK);
971         g_ptr->info |= CAVE_FLOOR;
972         break;
973     }
974     case GB_EXTRA: {
975         g_ptr->feat = feat_wall_type[randint0(100)];
976         g_ptr->info &= ~(CAVE_MASK);
977         g_ptr->info |= CAVE_EXTRA;
978         break;
979     }
980     case GB_EXTRA_PERM: {
981         g_ptr->feat = feat_permanent;
982         g_ptr->info &= ~(CAVE_MASK);
983         g_ptr->info |= CAVE_EXTRA;
984         break;
985     }
986     case GB_INNER: {
987         g_ptr->feat = feat_wall_inner;
988         g_ptr->info &= ~(CAVE_MASK);
989         g_ptr->info |= CAVE_INNER;
990         break;
991     }
992     case GB_INNER_PERM: {
993         g_ptr->feat = feat_permanent;
994         g_ptr->info &= ~(CAVE_MASK);
995         g_ptr->info |= CAVE_INNER;
996         break;
997     }
998     case GB_OUTER: {
999         g_ptr->feat = feat_wall_outer;
1000         g_ptr->info &= ~(CAVE_MASK);
1001         g_ptr->info |= CAVE_OUTER;
1002         break;
1003     }
1004     case GB_OUTER_NOPERM: {
1005         feature_type *f_ptr = &f_info[feat_wall_outer];
1006         if (permanent_wall(f_ptr)) {
1007             g_ptr->feat = (int16_t)feat_state(player_ptr->current_floor_ptr, feat_wall_outer, FF::UNPERM);
1008         } else {
1009             g_ptr->feat = feat_wall_outer;
1010         }
1011
1012         g_ptr->info &= ~(CAVE_MASK);
1013         g_ptr->info |= (CAVE_OUTER | CAVE_VAULT);
1014         break;
1015     }
1016     case GB_SOLID: {
1017         g_ptr->feat = feat_wall_solid;
1018         g_ptr->info &= ~(CAVE_MASK);
1019         g_ptr->info |= CAVE_SOLID;
1020         break;
1021     }
1022     case GB_SOLID_PERM: {
1023         g_ptr->feat = feat_permanent;
1024         g_ptr->info &= ~(CAVE_MASK);
1025         g_ptr->info |= CAVE_SOLID;
1026         break;
1027     }
1028     case GB_SOLID_NOPERM: {
1029         feature_type *f_ptr = &f_info[feat_wall_solid];
1030         if ((g_ptr->info & CAVE_VAULT) && permanent_wall(f_ptr))
1031             g_ptr->feat = (int16_t)feat_state(player_ptr->current_floor_ptr, feat_wall_solid, FF::UNPERM);
1032         else
1033             g_ptr->feat = feat_wall_solid;
1034         g_ptr->info &= ~(CAVE_MASK);
1035         g_ptr->info |= CAVE_SOLID;
1036         break;
1037     }
1038     default:
1039         // 未知の値が渡されたら何もしない。
1040         return;
1041     }
1042
1043     if (g_ptr->m_idx > 0)
1044         delete_monster_idx(player_ptr, g_ptr->m_idx);
1045 }
1046
1047 /*!
1048  * モンスターにより照明が消されている地形か否かを判定する。 / Is this grid "darkened" by monster?
1049  * @param player_ptr プレーヤーへの参照ポインタ
1050  * @param g_ptr グリッドへの参照ポインタ
1051  * @return 照明が消されている地形ならばTRUE
1052  */
1053 bool darkened_grid(player_type *player_ptr, grid_type *g_ptr)
1054 {
1055     return ((g_ptr->info & (CAVE_VIEW | CAVE_LITE | CAVE_MNLT | CAVE_MNDK)) == (CAVE_VIEW | CAVE_MNDK)) && !player_ptr->see_nocto;
1056 }
1057
1058 void place_bold(player_type *player_ptr, POSITION y, POSITION x, grid_bold_type gb_type)
1059 {
1060     grid_type *const g_ptr = &player_ptr->current_floor_ptr->grid_array[y][x];
1061     place_grid(player_ptr, g_ptr, gb_type);
1062 }
1063
1064 void set_cave_feat(floor_type *floor_ptr, POSITION y, POSITION x, FEAT_IDX feature_idx)
1065 {
1066     floor_ptr->grid_array[y][x].feat = feature_idx;
1067 }
1068
1069 /*!
1070  * @brief プレイヤーの周辺9マスに該当する地形がいくつあるかを返す /
1071  * Attempt to open the given chest at the given location
1072  * @param y 該当する地形の中から1つのY座標を返す参照ポインタ
1073  * @param x 該当する地形の中から1つのX座標を返す参照ポインタ
1074  * @param test 地形条件を判定するための関数ポインタ
1075  * @param under TRUEならばプレイヤーの直下の座標も走査対象にする
1076  * @return 該当する地形の数
1077  * @details Return the number of features around (or under) the character.
1078  * Usually look for doors and floor traps.
1079  */
1080 int count_dt(player_type *creature_ptr, POSITION *y, POSITION *x, bool (*test)(player_type *, FEAT_IDX), bool under)
1081 {
1082     int count = 0;
1083     for (DIRECTION d = 0; d < 9; d++) {
1084         grid_type *g_ptr;
1085         FEAT_IDX feat;
1086         if ((d == 8) && !under)
1087             continue;
1088
1089         POSITION yy = creature_ptr->y + ddy_ddd[d];
1090         POSITION xx = creature_ptr->x + ddx_ddd[d];
1091         g_ptr = &creature_ptr->current_floor_ptr->grid_array[yy][xx];
1092         if (!g_ptr->is_mark())
1093             continue;
1094
1095         feat = g_ptr->get_feat_mimic();
1096         if (!((*test)(creature_ptr, feat)))
1097             continue;
1098
1099         ++count;
1100         *y = yy;
1101         *x = xx;
1102     }
1103
1104     return count;
1105 }
1106
1107 /*!
1108  * @brief マス構造体のspecial要素を利用する地形かどうかを判定する.
1109  */
1110 bool feat_uses_special(FEAT_IDX f_idx)
1111 {
1112     return f_info[(f_idx)].flags.has(FF::SPECIAL);
1113 }
1114
1115 /*
1116  * This function allows us to efficiently add a grid to the "lite" array,
1117  * note that we are never called for illegal grids, or for grids which
1118  * have already been placed into the "lite" array, and we are never
1119  * called when the "lite" array is full.
1120  */
1121 void cave_lite_hack(floor_type *floor_ptr, POSITION y, POSITION x)
1122 {
1123     auto *g_ptr = &floor_ptr->grid_array[y][x];
1124     if (g_ptr->is_lite()) {
1125         return;
1126     }
1127
1128     g_ptr->info |= CAVE_LITE;
1129     floor_ptr->lite_y[floor_ptr->lite_n] = y;
1130     floor_ptr->lite_x[floor_ptr->lite_n++] = x;
1131 }
1132
1133 /*
1134  * For delayed visual update
1135  */
1136 void cave_redraw_later(floor_type *floor_ptr, POSITION y, POSITION x)
1137 {
1138     auto *g_ptr = &floor_ptr->grid_array[y][x];
1139     if (g_ptr->is_redraw()) {
1140         return;
1141     }
1142
1143     g_ptr->info |= CAVE_REDRAW;
1144     floor_ptr->redraw_y[floor_ptr->redraw_n] = y;
1145     floor_ptr->redraw_x[floor_ptr->redraw_n++] = x;
1146 }
1147
1148 /*
1149  * For delayed visual update
1150  */
1151 void cave_note_and_redraw_later(floor_type *floor_ptr, POSITION y, POSITION x)
1152 {
1153     floor_ptr->grid_array[y][x].info |= CAVE_NOTE;
1154     cave_redraw_later(floor_ptr, y, x);
1155 }
1156
1157 void cave_view_hack(floor_type *floor_ptr, POSITION y, POSITION x)
1158 {
1159     auto *g_ptr = &floor_ptr->grid_array[y][x];
1160     if (g_ptr->is_view()) {
1161         return;
1162     }
1163
1164     g_ptr->info |= CAVE_VIEW;
1165     floor_ptr->view_y[floor_ptr->view_n] = y;
1166     floor_ptr->view_x[floor_ptr->view_n] = x;
1167     floor_ptr->view_n++;
1168 }