OSDN Git Service

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