Source:NetHack 5.0.0/src/dungeon.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to dungeon.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/dungeon.c#line12]], for example.

The NetHack General Public License applies to screenshots, source code and other content from NetHack.

This content was modified from the original NetHack source code distribution (by splitting up NetHack content between wiki pages, and possibly further editing). See the page history for a list of who changed it, and on what dates.

1. /* NetHack 5.0	dungeon.c	$NHDT-Date: 1737343478 2025/01/19 19:24:38 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.228 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Robert Patrick Rankin, 2012. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. #include "dgn_file.h"
8. #include "dlb.h"
9. 
10. #define DUNGEON_FILE "dungeon.lua"
11. 
12. #define X_START "x-strt"
13. #define X_LOCATE "x-loca"
14. #define X_GOAL "x-goal"
15. 
16. struct proto_dungeon {
17.     struct tmpdungeon tmpdungeon[MAXDUNGEON];
18.     struct tmplevel tmplevel[LEV_LIMIT];
19.     s_level *final_lev[LEV_LIMIT]; /* corresponding level pointers */
20.     struct tmpbranch tmpbranch[BRANCH_LIMIT];
21. 
22.     int start;  /* starting index of current dungeon sp levels */
23.     int n_levs; /* number of tmplevel entries */
24.     int n_brs;  /* number of tmpbranch entries */
25. };
26. 
27. struct lchoice {
28.     int idx;
29.     schar lev[MAXLINFO];
30.     schar playerlev[MAXLINFO];
31.     xint16 dgn[MAXLINFO];
32.     char menuletter;
33. };
34. 
35. static mapseen *load_mapseen(NHFILE *);
36. 
37. #ifndef SFCTOOL
38. #if 0
39. staticfn void Fread(genericptr_t, int, int, dlb *);
40. #endif
41. staticfn xint16 dname_to_dnum(const char *);
42. staticfn int find_branch(const char *, struct proto_dungeon *);
43. staticfn xint16 parent_dnum(const char *, struct proto_dungeon *);
44. staticfn int level_range(xint16, int, int, int, struct proto_dungeon *,
45.                          int *);
46. staticfn xint16 parent_dlevel(const char *, struct proto_dungeon *);
47. staticfn int correct_branch_type(struct tmpbranch *);
48. staticfn branch *add_branch(int, int, struct proto_dungeon *);
49. staticfn void add_level(s_level *);
50. staticfn void init_level(int, int, struct proto_dungeon *);
51. staticfn int possible_places(int, boolean *, struct proto_dungeon *);
52. staticfn xint16 pick_level(boolean *, int);
53. staticfn boolean place_level(int, struct proto_dungeon *);
54. staticfn int get_dgn_flags(lua_State *);
55. staticfn int get_dgn_align(lua_State *);
56. staticfn void init_dungeon_levels(lua_State *, struct proto_dungeon *, int);
57. staticfn void init_dungeon_branches(lua_State *, struct proto_dungeon *, int);
58. staticfn void init_dungeon_set_entry(struct proto_dungeon *, int);
59. staticfn void init_dungeon_set_depth(struct proto_dungeon *, int);
60. staticfn void init_castle_tune(void);
61. staticfn void fixup_level_locations(void);
62. staticfn void free_proto_dungeon(struct proto_dungeon *);
63. staticfn void earth_sense(void);
64. staticfn boolean init_dungeon_dungeons(lua_State *, struct proto_dungeon *,
65.                                       int);
66. staticfn boolean unplaced_floater(struct dungeon *);
67. staticfn boolean unreachable_level(d_level *, boolean);
68. staticfn void tport_menu(winid, char *, struct lchoice *, d_level *, boolean);
69. staticfn const char *br_string(int) NONNULL;
70. staticfn char chr_u_on_lvl(d_level *);
71. staticfn void print_branch(winid, int, int, int, boolean, struct lchoice *);
72. staticfn char *get_annotation(d_level *);
73. staticfn void query_annotation(d_level *);
74. staticfn mapseen *load_mapseen(NHFILE *);
75. staticfn void save_mapseen(NHFILE *, mapseen *);
76. staticfn mapseen *find_mapseen(d_level *);
77. staticfn mapseen *find_mapseen_by_str(const char *);
78. staticfn void print_mapseen(winid, mapseen *, int, int, boolean);
79. staticfn boolean interest_mapseen(mapseen *);
80. staticfn void count_feat_lastseentyp(mapseen *, coordxy, coordxy);
81. staticfn void traverse_mapseenchn(int, winid, int, int, int *);
82. staticfn const char *seen_string(xint16, const char *) NONNULL NONNULLARG2;
83. staticfn const char *br_string2(branch *) NONNULL NONNULLARG1;
84. staticfn const char *shop_string(int) NONNULL;
85. staticfn char *tunesuffix(mapseen *, char *, size_t) NONNULL NONNULLPTRS;
86. 
87. #ifdef DEBUG
88. staticfn void dumpit(void);
89. 
90. staticfn void
91. dumpit(void)
92. {
93. #define DD svd.dungeons[i]
94.     int i;
95.     s_level *x;
96.     branch *br;
97. 
98.     if (!explicitdebug(__FILE__))
99.         return;
100. 
101.     for (i = 0; i < svn.n_dgns; i++) {
102.         fprintf(stderr, "\n#%d \"%s\" (%s):\n", i, DD.dname, DD.proto);
103.         fprintf(stderr, "    num_dunlevs %d, dunlev_ureached %d\n",
104.                 DD.num_dunlevs, DD.dunlev_ureached);
105.         fprintf(stderr, "    depth_start %d, ledger_start %d\n",
106.                 DD.depth_start, DD.ledger_start);
107.         fprintf(stderr, "    flags:%s%s%s\n",
108.                 DD.flags.rogue_like ? " rogue_like" : "",
109.                 DD.flags.maze_like ? " maze_like" : "",
110.                 DD.flags.hellish ? " hellish" : "");
111.         (void) getchar();
112.     }
113.     fprintf(stderr, "\nSpecial levels:\n");
114.     for (x = svs.sp_levchn; x; x = x->next) {
115.         fprintf(stderr, "%s (%d): ", x->proto, x->rndlevs);
116.         fprintf(stderr, "on %d, %d; ", x->dlevel.dnum, x->dlevel.dlevel);
117.         fprintf(stderr, "flags:%s%s%s%s\n",
118.                 x->flags.rogue_like ? " rogue_like" : "",
119.                 x->flags.maze_like ? " maze_like" : "",
120.                 x->flags.hellish ? " hellish" : "",
121.                 x->flags.town ? " town" : "");
122.         (void) getchar();
123.     }
124.     fprintf(stderr, "\nBranches:\n");
125.     for (br = svb.branches; br; br = br->next) {
126.         fprintf(stderr, "%d: %s, end1 %d %d, end2 %d %d, %s\n", br->id,
127.                 br->type == BR_STAIR
128.                     ? "stair"
129.                     : br->type == BR_NO_END1
130.                         ? "no end1"
131.                         : br->type == BR_NO_END2
132.                             ? "no end2"
133.                             : br->type == BR_PORTAL
134.                                 ? "portal"
135.                                 : "unknown",
136.                 br->end1.dnum, br->end1.dlevel, br->end2.dnum,
137.                 br->end2.dlevel, br->end1_up ? "end1 up" : "end1 down");
138.     }
139.     (void) getchar();
140.     fprintf(stderr, "\nDone\n");
141.     (void) getchar();
142.     return;
143. #undef DD
144. }
145. #endif
146. 
147. /* Save the dungeon structures. */
148. void
149. save_dungeon(
150.     NHFILE *nhfp,
151.     boolean perform_write,
152.     boolean free_data)
153. {
154.     int i, count;
155.     branch *curr, *next;
156.     mapseen *curr_ms, *next_ms;
157. 
158.     if (perform_write) {
159.         Sfo_int(nhfp, &svn.n_dgns, "dungeon_count");
160.         for (i = 0; i < svn.n_dgns; ++i) {
161.             Sfo_dungeon(nhfp, &svd.dungeons[i], "dungeon");
162.         }
163.         Sfo_dgn_topology(nhfp, &svd.dungeon_topology, "svd.dungeon_topology");
164.         Sfo_char(nhfp, svt.tune, "tune", (int) sizeof tune);
165.         for (count = 0, curr = svb.branches; curr; curr = curr->next)
166.             count++;
167.         Sfo_int(nhfp, &count, "branch_count");
168. 
169.         for (curr = svb.branches; curr; curr = curr->next) {
170.             Sfo_branch(nhfp, curr, "branch");
171.         }
172.         count = maxledgerno();
173.         Sfo_int(nhfp, &count, "level_info_count");
174.         for (i = 0; i < count; ++i) {
175.             Sfo_linfo(nhfp, &svl.level_info[i], "svl.level_info");
176.         }
177.         Sfo_nhcoord(nhfp, &svi.inv_pos, "svi.inv_pos");
178. 
179.         for (count = 0, curr_ms = svm.mapseenchn; curr_ms;
180.              curr_ms = curr_ms->next)
181.             count++;
182. 
183.         Sfo_int(nhfp, &count, "mapseen_count");
184. 
185.         for (curr_ms = svm.mapseenchn; curr_ms; curr_ms = curr_ms->next) {
186.             save_mapseen(nhfp, curr_ms);
187.         }
188.     }
189. 
190.     if (free_data) {
191.         for (curr = svb.branches; curr; curr = next) {
192.             next = curr->next;
193.             free((genericptr_t) curr);
194.         }
195.         svb.branches = 0;
196.         for (curr_ms = svm.mapseenchn; curr_ms; curr_ms = next_ms) {
197.             next_ms = curr_ms->next;
198.             if (curr_ms->custom)
199.                 free((genericptr_t) curr_ms->custom);
200.             if (curr_ms->final_resting_place)
201.                 savecemetery(nhfp, &curr_ms->final_resting_place);
202.             free((genericptr_t) curr_ms);
203.         }
204.         svm.mapseenchn = 0;
205.     }
206. }
207. #endif /* !SFCTOOL */
208. 
209. /* Restore the dungeon structures. */
210. void
211. restore_dungeon(NHFILE *nhfp)
212. {
213.     branch *curr, *last;
214.     int count = 0;
215.     int i;
216.     mapseen *curr_ms, *last_ms;
217. 
218.     Sfi_int(nhfp, &svn.n_dgns, "dungeon_count");
219.     for (i = 0; i < svn.n_dgns; ++i) {
220.         Sfi_dungeon(nhfp, &svd.dungeons[i], "dungeon");
221.     }
222.     Sfi_dgn_topology(nhfp, &svd.dungeon_topology, "svd.dungeon_topology");
223.     Sfi_char(nhfp, svt.tune, "tune", (int) sizeof tune);
224. 
225.     last = svb.branches = (branch *) 0;
226. 
227.     Sfi_int(nhfp, &count, "branch_count");
228. 
229.     for (i = 0; i < count; i++) {
230.         curr = (branch *) alloc(sizeof *curr);
231.         Sfi_branch(nhfp, curr, "branch");
232.         curr->next = (branch *) 0;
233.         if (last)
234.             last->next = curr;
235.         else
236.             svb.branches = curr;
237.         last = curr;
238.     }
239. 
240.     Sfi_int(nhfp, &count, "level_info_count");
241. 
242.     if (count >= MAXLINFO)
243.         panic("level information count larger (%d) than allocated size",
244.               count);
245.     for (i = 0; i < count; ++i) {
246.         Sfi_linfo(nhfp, &svl.level_info[i], "svl.level_info");
247.     }
248. 
249.     Sfi_nhcoord(nhfp, &svi.inv_pos, "svi.inv_pos");
250. 
251.     Sfi_int(nhfp, &count, "mapseen_count");
252. 
253.     last_ms = (mapseen *) 0;
254.     for (i = 0; i < count; i++) {
255.         curr_ms = load_mapseen(nhfp);
256.         curr_ms->next = (mapseen *) 0;
257.         if (last_ms)
258.             last_ms->next = curr_ms;
259.         else
260.             svm.mapseenchn = curr_ms;
261.         last_ms = curr_ms;
262.     }
263. }
264. 
265. #ifndef SFCTOOL
266. #if 0
267. staticfn void
268. Fread(genericptr_t ptr, int size, int nitems, dlb *stream)
269. {
270.     int cnt;
271. 
272.     if ((cnt = dlb_fread(ptr, size, nitems, stream)) != nitems) {
273.         panic(
274.   "Premature EOF on dungeon description file!\r\nExpected %d bytes - got %d.",
275.               (size * nitems), (size * cnt));
276.         nh_terminate(EXIT_FAILURE);
277.     }
278. }
279. #endif
280. 
281. DISABLE_WARNING_UNREACHABLE_CODE
282. 
283. staticfn xint16
284. dname_to_dnum(const char *s)
285. {
286.     xint16 i;
287. 
288.     for (i = 0; i < svn.n_dgns; i++)
289.         if (!strcmp(svd.dungeons[i].dname, s))
290.             return i;
291. 
292.     panic("Couldn't resolve dungeon number for name \"%s\".", s);
293.     /*NOT REACHED*/
294.     return (xint16) 0;
295. }
296. 
297. RESTORE_WARNING_UNREACHABLE_CODE
298. 
299. s_level *
300. find_level(const char *s)
301. {
302.     s_level *curr;
303.     for (curr = svs.sp_levchn; curr; curr = curr->next)
304.         if (!strcmpi(s, curr->proto))
305.             break;
306.     return curr;
307. }
308. 
309. /* Find the branch that links the named dungeon. */
310. staticfn int
311. find_branch(
312.     const char *s, /* dungeon name */
313.     struct proto_dungeon *pd)
314. {
315.     int i;
316. 
317.     if (pd) {
318.         for (i = 0; i < pd->n_brs; i++)
319.             if (!strcmp(pd->tmpbranch[i].name, s))
320.                 break;
321.         if (i == pd->n_brs)
322.             panic("find_branch: can't find %s", s);
323.     } else {
324.         /* support for level tport by name */
325.         branch *br;
326.         const char *dnam;
327. 
328.         for (br = svb.branches; br; br = br->next) {
329.             dnam = svd.dungeons[br->end2.dnum].dname;
330.             if (!strcmpi(dnam, s)
331.                 || (!strncmpi(dnam, "The ", 4) && !strcmpi(dnam + 4, s)))
332.                 break;
333.         }
334.         i = br ? ((ledger_no(&br->end1) << 8) | ledger_no(&br->end2)) : -1;
335.     }
336.     return i;
337. }
338. 
339. DISABLE_WARNING_UNREACHABLE_CODE
340. 
341. /*
342.  * Find the "parent" by searching the prototype branch list for the branch
343.  * listing, then figuring out to which dungeon it belongs.
344.  */
345. staticfn xint16
346. parent_dnum(
347.     const char *s, /* dungeon name */
348.     struct proto_dungeon *pd)
349. {
350.     int i;
351.     xint16 pdnum;
352. 
353.     i = find_branch(s, pd);
354.     /*
355.      * Got branch, now find parent dungeon.  Stop if we have reached
356.      * "this" dungeon (if we haven't found it by now it is an error).
357.      */
358.     for (pdnum = 0; strcmp(pd->tmpdungeon[pdnum].name, s); pdnum++)
359.         if ((i -= pd->tmpdungeon[pdnum].branches) < 0)
360.             return pdnum;
361. 
362.     panic("parent_dnum: couldn't resolve branch.");
363.     /*NOT REACHED*/
364.     return (xint16) 0;
365. }
366. 
367. RESTORE_WARNING_UNREACHABLE_CODE
368. 
369. /*
370.  * Return a starting point and number of successive positions a level
371.  * or dungeon entrance can occupy.
372.  *
373.  * Note: This follows the acouple (instead of the rcouple) rules for a
374.  *       negative random component (randc < 0).  These rules are found
375.  *       in dgn_comp.y.  The acouple [absolute couple] section says that
376.  *       a negative random component means from the (adjusted) base to the
377.  *       end of the dungeon.
378.  */
379. staticfn int
380. level_range(
381.     xint16 dgn,
382.     int base, int randc, int chain,
383.     struct proto_dungeon *pd,
384.     int *adjusted_base)
385. {
386.     int lmax = svd.dungeons[dgn].num_dunlevs;
387. 
388.     if (chain >= 0) { /* relative to a special level */
389.         s_level *levtmp = pd->final_lev[chain];
390.         if (!levtmp)
391.             panic("level_range: empty chain level!");
392. 
393.         base += levtmp->dlevel.dlevel;
394.     } else { /* absolute in the dungeon */
395.         /* from end of dungeon */
396.         if (base < 0)
397.             base = (lmax + base + 1);
398.     }
399. 
400.     if (base < 1 || base > lmax)
401.         panic("level_range: base value out of range");
402. 
403.     *adjusted_base = base;
404. 
405.     if (randc == -1) { /* from base to end of dungeon */
406.         return (lmax - base + 1);
407.     } else if (randc) {
408.         /* make sure we don't run off the end of the dungeon */
409.         return (((base + randc - 1) > lmax) ? lmax - base + 1 : randc);
410.     } /* else only one choice */
411.     return 1;
412. }
413. 
414. staticfn xint16
415. parent_dlevel(const char *s, struct proto_dungeon *pd)
416. {
417.     int i, j, num, base, dnum = parent_dnum(s, pd);
418.     branch *curr;
419. 
420.     i = find_branch(s, pd);
421.     num = level_range(dnum, pd->tmpbranch[i].lev.base,
422.                       pd->tmpbranch[i].lev.rand, pd->tmpbranch[i].chain, pd,
423.                       &base);
424. 
425.     /* KMH -- Try our best to find a level without an existing branch */
426.     i = j = rn2(num);
427.     do {
428.         if (++i >= num)
429.             i = 0;
430.         for (curr = svb.branches; curr; curr = curr->next)
431.             if ((curr->end1.dnum == dnum && curr->end1.dlevel == base + i)
432.                 || (curr->end2.dnum == dnum && curr->end2.dlevel == base + i))
433.                 break;
434.     } while (curr && i != j);
435.     return (base + i);
436. }
437. 
438. /* Convert from the temporary branch type to the dungeon branch type. */
439. staticfn int
440. correct_branch_type(struct tmpbranch *tbr)
441. {
442.     switch (tbr->type) {
443.     case TBR_STAIR:
444.         return BR_STAIR;
445.     case TBR_NO_UP:
446.         return tbr->up ? BR_NO_END1 : BR_NO_END2;
447.     case TBR_NO_DOWN:
448.         return tbr->up ? BR_NO_END2 : BR_NO_END1;
449.     case TBR_PORTAL:
450.         return BR_PORTAL;
451.     }
452.     impossible("correct_branch_type: unknown branch type");
453.     return BR_STAIR;
454. }
455. 
456. /*
457.  * Add the given branch to the branch list.  The branch list is ordered
458.  * by end1 dungeon and level followed by end2 dungeon and level.  If
459.  * extract_first is true, then the branch is already part of the list
460.  * but needs to be repositioned.
461.  */
462. void
463. insert_branch(branch *new_branch, boolean extract_first)
464. {
465.     branch *curr, *prev;
466.     long new_val, curr_val, prev_val;
467. 
468.     if (extract_first) {
469.         for (prev = 0, curr = svb.branches; curr;
470.              prev = curr, curr = curr->next)
471.             if (curr == new_branch)
472.                 break;
473. 
474.         if (!curr)
475.             panic("insert_branch: not found");
476.         if (prev)
477.             prev->next = curr->next;
478.         else
479.             svb.branches = curr->next;
480.     }
481.     new_branch->next = (branch *) 0;
482. 
483. /* Convert the branch into a unique number so we can sort them. */
484. #define branch_val(bp) \
485.     ((((long) (bp)->end1.dnum * (MAXLEVEL + 1) + (long) (bp)->end1.dlevel) \
486.       * (MAXDUNGEON + 1) * (MAXLEVEL + 1))                                 \
487.      + ((long) (bp)->end2.dnum * (MAXLEVEL + 1) + (long) (bp)->end2.dlevel))
488. 
489.     /*
490.      * Insert the new branch into the correct place in the branch list.
491.      */
492.     prev = (branch *) 0;
493.     prev_val = -1;
494.     new_val = branch_val(new_branch);
495.     for (curr = svb.branches; curr;
496.          prev_val = curr_val, prev = curr, curr = curr->next) {
497.         curr_val = branch_val(curr);
498.         if (prev_val < new_val && new_val <= curr_val)
499.             break;
500.     }
501.     if (prev) {
502.         new_branch->next = curr;
503.         prev->next = new_branch;
504.     } else {
505.         new_branch->next = svb.branches;
506.         svb.branches = new_branch;
507.     }
508. }
509. 
510. #undef branch_val
511. 
512. /* Add a dungeon branch to the branch list. */
513. staticfn branch *
514. add_branch(
515.     int dgn, int child_entry_level,
516.     struct proto_dungeon *pd)
517. {
518.     static int branch_id = 0;
519.     int branch_num;
520.     branch *new_branch;
521. 
522.     branch_num = find_branch(svd.dungeons[dgn].dname, pd);
523.     new_branch = (branch *) alloc(sizeof(branch));
524.     (void) memset((genericptr_t) new_branch, 0, sizeof(branch));
525.     new_branch->next = (branch *) 0;
526.     new_branch->id = branch_id++;
527.     new_branch->type = correct_branch_type(&pd->tmpbranch[branch_num]);
528.     new_branch->end1.dnum = parent_dnum(svd.dungeons[dgn].dname, pd);
529.     new_branch->end1.dlevel = parent_dlevel(svd.dungeons[dgn].dname, pd);
530.     new_branch->end2.dnum = dgn;
531.     new_branch->end2.dlevel = child_entry_level;
532.     new_branch->end1_up = pd->tmpbranch[branch_num].up ? TRUE : FALSE;
533. 
534.     insert_branch(new_branch, FALSE);
535.     return new_branch;
536. }
537. 
538. /*
539.  * Add new level to special level chain.  Insert it in level order with the
540.  * other levels in this dungeon.  This assumes that we are never given a
541.  * level that has a dungeon number less than the dungeon number of the
542.  * last entry.
543.  */
544. staticfn void
545. add_level(s_level *new_lev)
546. {
547.     s_level *prev, *curr;
548. 
549.     prev = (s_level *) 0;
550.     for (curr = svs.sp_levchn; curr; curr = curr->next) {
551.         if (curr->dlevel.dnum == new_lev->dlevel.dnum
552.             && curr->dlevel.dlevel > new_lev->dlevel.dlevel)
553.             break;
554.         prev = curr;
555.     }
556.     if (!prev) {
557.         new_lev->next = svs.sp_levchn;
558.         svs.sp_levchn = new_lev;
559.     } else {
560.         new_lev->next = curr;
561.         prev->next = new_lev;
562.     }
563. }
564. 
565. staticfn void
566. init_level(int dgn, int proto_index, struct proto_dungeon *pd)
567. {
568.     s_level *new_level;
569.     struct tmplevel *tlevel = &pd->tmplevel[proto_index];
570. 
571.     pd->final_lev[proto_index] = (s_level *) 0; /* no "real" level */
572.     if (!wizard && tlevel->chance <= rn2(100))
573.         return;
574. 
575.     pd->final_lev[proto_index] = new_level =
576.         (s_level *) alloc(sizeof(s_level));
577.     (void) memset((genericptr_t) new_level, 0, sizeof(s_level));
578.     /* load new level with data */
579.     Strcpy(new_level->proto, tlevel->name);
580.     new_level->boneid = tlevel->boneschar;
581.     new_level->dlevel.dnum = dgn;
582.     new_level->dlevel.dlevel = 0; /* for now */
583. 
584.     new_level->flags.town = !!(tlevel->flags & TOWN);
585.     new_level->flags.hellish = !!(tlevel->flags & HELLISH);
586.     new_level->flags.maze_like = !!(tlevel->flags & MAZELIKE);
587.     new_level->flags.rogue_like = !!(tlevel->flags & ROGUELIKE);
588.     new_level->flags.align = ((tlevel->flags & D_ALIGN_MASK) >> 4);
589.     if (!new_level->flags.align)
590.         new_level->flags.align =
591.             ((pd->tmpdungeon[dgn].flags & D_ALIGN_MASK) >> 4);
592. 
593.     new_level->rndlevs = tlevel->rndlevs;
594.     new_level->next = (s_level *) 0;
595. }
596. 
597. staticfn int
598. possible_places(
599.     int idx,      /* prototype index */
600.     boolean *map, /* array MAXLEVEL+1 in length */
601.     struct proto_dungeon *pd)
602. {
603.     int i, start, count;
604.     s_level *lev = pd->final_lev[idx];
605. 
606.     /* init level possibilities */
607.     for (i = 0; i <= MAXLEVEL; i++)
608.         map[i] = FALSE;
609. 
610.     /* get base and range and set those entries to true */
611.     count = level_range(lev->dlevel.dnum, pd->tmplevel[idx].lev.base,
612.                         pd->tmplevel[idx].lev.rand, pd->tmplevel[idx].chain,
613.                         pd, &start);
614.     for (i = start; i < start + count; i++)
615.         map[i] = TRUE;
616. 
617.     /* mark off already placed levels */
618.     for (i = pd->start; i < idx; i++) {
619.         if (pd->final_lev[i] && map[pd->final_lev[i]->dlevel.dlevel]) {
620.             map[pd->final_lev[i]->dlevel.dlevel] = FALSE;
621.             --count;
622.         }
623.     }
624. 
625.     return count;
626. }
627. 
628. DISABLE_WARNING_UNREACHABLE_CODE
629. 
630. /* Pick the nth TRUE entry in the given boolean array. */
631. staticfn xint16
632. pick_level(
633.     boolean *map, /* an array MAXLEVEL+1 in size */
634.     int nth)
635. {
636.     xint16 i;
637.     for (i = 1; i <= MAXLEVEL; i++)
638.         if (map[i] && !nth--)
639.             return i;
640.     panic("pick_level:  ran out of valid levels");
641.     /*NOTREACHED*/
642.     return 0;
643. }
644. 
645. RESTORE_WARNING_UNREACHABLE_CODE
646. 
647. #ifdef DDEBUG
648. staticfn void indent(int);
649. 
650. staticfn void
651. indent(int d)
652. {
653.     while (d-- > 0)
654.         fputs("    ", stderr);
655. }
656. #endif
657. 
658. /*
659.  * Place a level.  First, find the possible places on a dungeon map
660.  * template.  Next pick one.  Then try to place the next level.  If
661.  * successful, we're done.  Otherwise, try another (and another) until
662.  * all possible places have been tried.  If all possible places have
663.  * been exhausted, return false.
664.  */
665. staticfn boolean
666. place_level(int proto_index, struct proto_dungeon *pd)
667. {
668.     boolean map[MAXLEVEL + 1]; /* valid levels are 1..MAXLEVEL inclusive */
669.     s_level *lev;
670.     int npossible;
671. #ifdef DDEBUG
672.     int i;
673. #endif
674. 
675.     if (proto_index == pd->n_levs)
676.         return TRUE; /* at end of proto levels */
677. 
678.     lev = pd->final_lev[proto_index];
679. 
680.     /* No level created for this prototype, goto next. */
681.     if (!lev)
682.         return place_level(proto_index + 1, pd);
683. 
684.     npossible = possible_places(proto_index, map, pd);
685. 
686.     for (; npossible; --npossible) {
687.         lev->dlevel.dlevel = pick_level(map, rn2(npossible));
688. #ifdef DDEBUG
689.         indent(proto_index - pd->start);
690.         fprintf(stderr, "%s: trying %d [ ", lev->proto, lev->dlevel.dlevel);
691.         for (i = 1; i <= MAXLEVEL; i++)
692.             if (map[i])
693.                 fprintf(stderr, "%d ", i);
694.         fprintf(stderr, "]\n");
695. #endif
696.         if (place_level(proto_index + 1, pd))
697.             return TRUE;
698.         map[lev->dlevel.dlevel] = FALSE; /* this choice didn't work */
699.     }
700. #ifdef DDEBUG
701.     indent(proto_index - pd->start);
702.     fprintf(stderr, "%s: failed\n", lev->proto);
703. #endif
704.     return FALSE;
705. }
706. 
707. static struct level_map {
708.     const char *lev_name;
709.     d_level *lev_spec;
710. } level_map[] = { { "air", &air_level },
711.                   { "asmodeus", &asmodeus_level },
712.                   { "astral", &astral_level },
713.                   { "baalz", &baalzebub_level },
714.                   { "bigrm", &bigroom_level },
715.                   { "castle", &stronghold_level },
716.                   { "earth", &earth_level },
717.                   { "fakewiz1", &portal_level },
718.                   { "fire", &fire_level },
719.                   { "juiblex", &juiblex_level },
720.                   { "knox", &knox_level },
721.                   { "medusa", &medusa_level },
722.                   { "oracle", &oracle_level },
723.                   { "orcus", &orcus_level },
724.                   { "rogue", &rogue_level },
725.                   { "sanctum", &sanctum_level },
726.                   { "valley", &valley_level },
727.                   { "water", &water_level },
728.                   { "wizard1", &wiz1_level },
729.                   { "wizard2", &wiz2_level },
730.                   { "wizard3", &wiz3_level },
731.                   { "minend", &mineend_level },
732.                   { "soko1", &sokoend_level },
733.                   { X_START, &qstart_level },
734.                   { X_LOCATE, &qlocate_level },
735.                   { X_GOAL, &nemesis_level },
736.                   { "", (d_level *) 0 }
737. };
738. 
739. #undef X_START
740. #undef X_LOCATE
741. #undef X_GOAL
742. 
743. staticfn int
744. get_dgn_flags(lua_State *L)
745. {
746.     int dgn_flags = 0;
747.     static const char *const flagstrs[] = {
748.         "town", "hellish", "mazelike", "roguelike", "unconnected", NULL
749.     };
750.     static const int flagstrs2i[] = {
751.         TOWN, HELLISH, MAZELIKE, ROGUELIKE, UNCONNECTED, 0
752.     };
753. 
754.     lua_getfield(L, -1, "flags");
755.     if (lua_type(L, -1) == LUA_TTABLE) {
756.         int f, nflags;
757. 
758.         lua_len(L, -1);
759.         nflags = (int) lua_tointeger(L, -1);
760.         lua_pop(L, 1);
761.         for (f = 0; f < nflags; f++) {
762.             lua_pushinteger(L, f + 1);
763.             lua_gettable(L, -2);
764.             if (lua_type(L, -1) == LUA_TSTRING) {
765.                 dgn_flags |= flagstrs2i[luaL_checkoption(L, -1, NULL,
766.                                                          flagstrs)];
767.                 lua_pop(L, 1);
768.             } else
769.                 impossible("flags[%i] is not a string", f);
770.         }
771.     } else if (lua_type(L, -1) == LUA_TSTRING) {
772.         dgn_flags |= flagstrs2i[luaL_checkoption(L, -1, NULL, flagstrs)];
773.     } else if (lua_type(L, -1) != LUA_TNIL)
774.         impossible("flags is not an array or string");
775.     lua_pop(L, 1);
776. 
777.     return dgn_flags;
778. }
779. 
780. staticfn int
781. get_dgn_align(lua_State *L)
782. {
783.     static const char *const dgnaligns[] = {
784.         "unaligned", "noalign", "lawful", "neutral", "chaotic", NULL
785.     };
786.     static const int dgnaligns2i[] = {
787.         D_ALIGN_NONE, D_ALIGN_NONE, D_ALIGN_LAWFUL,
788.         D_ALIGN_NEUTRAL, D_ALIGN_CHAOTIC, D_ALIGN_NONE
789.     };
790. 
791.     int a = dgnaligns2i[get_table_option(L, "alignment",
792.                                          "unaligned", dgnaligns)];
793.     return a;
794. }
795. 
796. staticfn void
797. init_dungeon_levels(
798.     lua_State *L,
799.     struct proto_dungeon *pd,
800.     int dngidx)
801. {
802.     char *lvl_name, *lvl_bonetag, *lvl_chain;
803.     int lvl_base, lvl_range, lvl_nlevels, lvl_chance,
804.         lvl_align, lvl_flags;
805.     struct tmplevel *tmpl;
806.     int bi, f, nlevels;
807. 
808.     lua_len(L, -1);
809.     nlevels = (int) lua_tointeger(L, -1);
810.     pd->tmpdungeon[dngidx].levels = nlevels;
811.     lua_pop(L, 1);
812.     for (f = 0; f < nlevels; f++) {
813.         lua_pushinteger(L, f + 1);
814.         lua_gettable(L, -2);
815.         if (lua_type(L, -1) == LUA_TTABLE) {
816.             lvl_name = get_table_str(L, "name");
817.             lvl_bonetag = get_table_str_opt(L, "bonetag", emptystr);
818.             lvl_chain = get_table_str_opt(L, "chainlevel", NULL);
819.             lvl_base = get_table_int(L, "base");
820.             lvl_range = get_table_int_opt(L, "range", 0);
821.             lvl_nlevels = get_table_int_opt(L, "nlevels", 0);
822.             lvl_chance = get_table_int_opt(L, "chance", 100);
823.             lvl_align = get_dgn_align(L);
824.             lvl_flags = get_dgn_flags(L);
825.             /* array index is offset by cumulative number of levels
826.                defined for preceding branches (iterations of 'while'
827.                loop we're inside, not branch connections below) */
828.             tmpl = &pd->tmplevel[pd->n_levs + f];
829. 
830.             debugpline4("LEVEL[%i]:%s,(%i,%i)",
831.                         f, lvl_name, lvl_base, lvl_range);
832.             tmpl->name = lvl_name;
833.             tmpl->chainlvl = lvl_chain;
834.             tmpl->lev.base = lvl_base;
835.             tmpl->lev.rand = lvl_range;
836.             tmpl->chance = lvl_chance;
837.             tmpl->rndlevs = lvl_nlevels;
838.             tmpl->flags = lvl_flags | lvl_align;
839.             tmpl->boneschar = *lvl_bonetag ? *lvl_bonetag : 0;
840.             free(lvl_bonetag);
841.             tmpl->chain = -1;
842.             if (lvl_chain) {
843.                 debugpline1("CHAINLEVEL: %s", lvl_chain);
844.                 for (bi = 0; bi < pd->n_levs + f; bi++) {
845.                     debugpline2("checking(%i):%s",
846.                                 bi, pd->tmplevel[bi].name);
847.                     if (!strcmp(pd->tmplevel[bi].name, lvl_chain)) {
848.                         tmpl->chain = bi;
849.                         break;
850.                     }
851.                 }
852.                 if (tmpl->chain == -1)
853.                     panic("Could not chain level %s to %s",
854.                           lvl_name, lvl_chain);
855.                 /* free(lvl_chain); -- recorded in pd.tmplevel[] */
856.             }
857.         } else
858.             panic("dungeon[%i].levels[%i] is not a hash", dngidx, f);
859.         lua_pop(L, 1);
860.     }
861.     pd->n_levs += nlevels;
862.     if (pd->n_levs > LEV_LIMIT)
863.         panic("init_dungeon: too many special levels");
864. }
865. 
866. staticfn void
867. init_dungeon_branches(
868.     lua_State *L,
869.     struct proto_dungeon *pd,
870.     int dngidx)
871. {
872.     static const char *const brdirstr[] = { "up", "down", 0 };
873.     static const int brdirstr2i[] = { TRUE, FALSE, FALSE };
874.     static const char *const brtypes[] = {
875.         "stair", "portal", "no_down", "no_up", 0
876.     };
877.     static const int brtypes2i[] = {
878.         TBR_STAIR, TBR_PORTAL, TBR_NO_DOWN, TBR_NO_UP, TBR_STAIR
879.     };
880.     char *br_name, *br_chain;
881.     int br_base, br_range, br_type, br_up;
882.     struct tmpbranch *tmpb;
883.     int bi, f, nbranches;
884. 
885.     lua_len(L, -1);
886.     nbranches = (int) lua_tointeger(L, -1);
887.     pd->tmpdungeon[dngidx].branches = nbranches;
888.     lua_pop(L, 1);
889.     for (f = 0; f < nbranches; f++) {
890.         lua_pushinteger(L, f + 1);
891.         lua_gettable(L, -2);
892.         if (lua_type(L, -1) == LUA_TTABLE) {
893.             br_name = get_table_str(L, "name");
894.             br_chain = get_table_str_opt(L, "chainlevel", NULL);
895.             br_base = get_table_int(L, "base");
896.             br_range = get_table_int_opt(L, "range", 0);
897.             br_type = brtypes2i[get_table_option(L, "branchtype",
898.                                                  "stair", brtypes)];
899.             br_up = brdirstr2i[get_table_option(L, "direction",
900.                                                 "down", brdirstr)];
901.             tmpb = &(pd->tmpbranch[pd->n_brs + f]);
902. 
903.             debugpline4("BRANCH[%i]:%s,(%i,%i)",
904.                         f, br_name, br_base, br_range);
905.             tmpb->name = br_name;
906.             tmpb->lev.base = br_base;
907.             tmpb->lev.rand = br_range;
908.             tmpb->type = br_type;
909.             tmpb->up = br_up;
910.             tmpb->chain = -1;
911.             if (br_chain) {
912.                 debugpline1("CHAINBRANCH:%s", br_chain);
913.                 for (bi = 0; bi < pd->n_levs + f - 1; bi++)
914.                     if (!strcmp(pd->tmplevel[bi].name, br_chain)) {
915.                         tmpb->chain = bi;
916.                         break;
917.                     }
918.                 if (tmpb->chain == -1)
919.                     panic("Could not chain branch %s to level %s",
920.                           br_name, br_chain);
921.                 free(br_chain);
922.             }
923.         } else
924.             panic("dungeon[%i].branches[%i] is not a hash", dngidx, f);
925.         lua_pop(L, 1);
926.     }
927.     pd->n_brs += nbranches;
928.     if (pd->n_brs > BRANCH_LIMIT)
929.         panic("init_dungeon: too many branches");
930. }
931. 
932. staticfn void
933. init_dungeon_set_entry(struct proto_dungeon *pd, int dngidx)
934. {
935.     int dgn_entry = pd->tmpdungeon[dngidx].entry_lev;
936.     /*
937.      * Set the entry level for this dungeon.  The entry value means:
938.      *              < 0     from bottom (-1 == bottom level)
939.      *                0     default (top)
940.      *              > 0     actual level (1 = top)
941.      *
942.      * Note that the entry_lev field in the dungeon structure is
943.      * redundant.  It is used only here and in print_dungeon().
944.      */
945.     if (dgn_entry < 0) {
946.         svd.dungeons[dngidx].entry_lev =
947.             svd.dungeons[dngidx].num_dunlevs + dgn_entry + 1;
948.         if (svd.dungeons[dngidx].entry_lev <= 0)
949.             svd.dungeons[dngidx].entry_lev = 1;
950.     } else if (dgn_entry > 0) {
951.         svd.dungeons[dngidx].entry_lev = dgn_entry;
952.         if (svd.dungeons[dngidx].entry_lev > svd.dungeons[dngidx].num_dunlevs)
953.             svd.dungeons[dngidx].entry_lev = svd.dungeons[dngidx].num_dunlevs;
954.     } else { /* default */
955.         svd.dungeons[dngidx].entry_lev = 1; /* defaults to top level */
956.     }
957. }
958. 
959. staticfn void
960. init_dungeon_set_depth(struct proto_dungeon *pd, int dngidx)
961. {
962.     branch *br;
963.     schar from_depth;
964.     boolean from_up;
965. 
966.     br = add_branch(dngidx, svd.dungeons[dngidx].entry_lev, pd);
967. 
968.     /* Get the depth of the connecting end. */
969.     if (br->end1.dnum == dngidx) {
970.         from_depth = depth(&br->end2);
971.         from_up = !br->end1_up;
972.     } else {
973.         from_depth = depth(&br->end1);
974.         from_up = br->end1_up;
975.     }
976. 
977.     /*
978.      * Calculate the depth of the top of the dungeon via
979.      * its branch.  First, the depth of the entry point:
980.      *
981.      *  depth of branch from "parent" dungeon
982.      *  + -1 or 1 depending on an up or down stair or
983.      *    0 if portal
984.      *
985.      * Followed by the depth of the top of the dungeon:
986.      *
987.      *  - (entry depth - 1)
988.      *
989.      * We'll say that portals stay on the same depth.
990.      */
991.     svd.dungeons[dngidx].depth_start =
992.         from_depth + (br->type == BR_PORTAL ? 0 : (from_up ? -1 : 1))
993.         - (svd.dungeons[dngidx].entry_lev - 1);
994. }
995. 
996. staticfn boolean
997. init_dungeon_dungeons(
998.    lua_State *L,
999.    struct proto_dungeon *pd,
1000.    int dngidx)
1001. {
1002.     char *dgn_name, *dgn_bonetag, *dgn_protoname, *dgn_fill;
1003.     char *dgn_themerms;
1004.     int dgn_base, dgn_range, dgn_align, dgn_entry, dgn_chance, dgn_flags;
1005. 
1006.     dgn_name = get_table_str(L, "name");
1007.     /* TODO: accept single char or "none" for bonetag */
1008.     dgn_bonetag = get_table_str_opt(L, "bonetag", emptystr);
1009.     dgn_protoname = get_table_str_opt(L, "protofile", emptystr);
1010.     dgn_base = get_table_int(L, "base");
1011.     dgn_range = get_table_int_opt(L, "range", 0);
1012.     dgn_align = get_dgn_align(L);
1013.     dgn_entry = get_table_int_opt(L, "entry", 0);
1014.     dgn_chance = get_table_int_opt(L, "chance", 100);
1015.     dgn_flags = get_dgn_flags(L);
1016.     dgn_fill = get_table_str_opt(L, "lvlfill", emptystr);
1017.     dgn_themerms = get_table_str_opt(L, "themerooms", emptystr);
1018. 
1019.     debugpline4("DUNGEON[%i]: %s, base=(%i,%i)",
1020.                 dngidx, dgn_name, dgn_base, dgn_range);
1021. 
1022.     if (!wizard && dgn_chance && (dgn_chance <= rn2(100))) {
1023.         debugpline1("IGNORING %s", dgn_name);
1024.         svn.n_dgns--;
1025.         free((genericptr_t) dgn_name);
1026.         free((genericptr_t) dgn_bonetag);
1027.         free((genericptr_t) dgn_protoname);
1028.         free((genericptr_t) dgn_fill);
1029.         free((genericptr_t) dgn_themerms);
1030.         return FALSE;
1031.     }
1032. 
1033.     /* levels begin */
1034.     lua_getfield(L, -1, "levels");
1035.     if (lua_type(L, -1) == LUA_TTABLE) {
1036.         init_dungeon_levels(L, pd, dngidx);
1037.     } else if (lua_type(L, -1) != LUA_TNIL)
1038.         panic("dungeon[%i].levels is not an array of hashes", dngidx);
1039.     lua_pop(L, 1);
1040.     /* levels end */
1041. 
1042.     /* branches begin */
1043.     lua_getfield(L, -1, "branches");
1044.     if (lua_type(L, -1) == LUA_TTABLE) {
1045.         init_dungeon_branches(L, pd, dngidx);
1046.     } else if (lua_type(L, -1) != LUA_TNIL)
1047.         panic("dungeon[%i].branches is not an array of hashes", dngidx);
1048.     lua_pop(L, 1);
1049.     /* branches end */
1050. 
1051.     pd->tmpdungeon[dngidx].name = dgn_name;
1052.     pd->tmpdungeon[dngidx].protoname = dgn_protoname;
1053.     pd->tmpdungeon[dngidx].boneschar = *dgn_bonetag ? *dgn_bonetag : 0;
1054.     pd->tmpdungeon[dngidx].lev.base = dgn_base;
1055.     pd->tmpdungeon[dngidx].lev.rand = dgn_range;
1056.     pd->tmpdungeon[dngidx].flags = dgn_flags;
1057.     pd->tmpdungeon[dngidx].align = dgn_align;
1058.     pd->tmpdungeon[dngidx].chance = dgn_chance;
1059.     pd->tmpdungeon[dngidx].entry_lev = dgn_entry;
1060. 
1061.     /* FIXME: these should have length checks */
1062.     Strcpy(svd.dungeons[dngidx].fill_lvl, dgn_fill);
1063.     Strcpy(svd.dungeons[dngidx].dname, dgn_name);
1064.     Strcpy(svd.dungeons[dngidx].proto, dgn_protoname);
1065.     Strcpy(svd.dungeons[dngidx].themerms, dgn_themerms);
1066.     /* FIXME: accept "none", convert that to '\0' */
1067.     svd.dungeons[dngidx].boneid = *dgn_bonetag ? *dgn_bonetag : 0;
1068.     free((genericptr) dgn_fill);
1069.     /* free((genericptr) dgn_protoname); -- stored in pd.tmpdungeon[] */
1070.     free((genericptr) dgn_bonetag);
1071.     free((genericptr) dgn_themerms);
1072. 
1073.     if (dgn_range)
1074.         svd.dungeons[dngidx].num_dunlevs = (xint16) rn1(dgn_range, dgn_base);
1075.     else
1076.         svd.dungeons[dngidx].num_dunlevs = (xint16) dgn_base;
1077. 
1078.     if (!dngidx) {
1079.         svd.dungeons[dngidx].ledger_start = 0;
1080.         svd.dungeons[dngidx].depth_start = 1;
1081.         svd.dungeons[dngidx].dunlev_ureached = 1;
1082.     } else {
1083.         svd.dungeons[dngidx].ledger_start
1084.             = svd.dungeons[dngidx - 1].ledger_start
1085.               + svd.dungeons[dngidx - 1].num_dunlevs;
1086.         svd.dungeons[dngidx].dunlev_ureached = 0;
1087.     }
1088. 
1089.     svd.dungeons[dngidx].flags.hellish = !!(dgn_flags & HELLISH);
1090.     svd.dungeons[dngidx].flags.maze_like = !!(dgn_flags & MAZELIKE);
1091.     svd.dungeons[dngidx].flags.rogue_like = !!(dgn_flags & ROGUELIKE);
1092.     svd.dungeons[dngidx].flags.align = dgn_align;
1093.     svd.dungeons[dngidx].flags.unconnected = !!(dgn_flags & UNCONNECTED);
1094. 
1095.     init_dungeon_set_entry(pd, dngidx);
1096. 
1097.     if (svd.dungeons[dngidx].flags.unconnected) {
1098.         svd.dungeons[dngidx].depth_start = 1;
1099.     } else if (dngidx) { /* set depth */
1100.         init_dungeon_set_depth(pd, dngidx);
1101.     }
1102. 
1103.     if (svd.dungeons[dngidx].num_dunlevs > MAXLEVEL)
1104.         svd.dungeons[dngidx].num_dunlevs = MAXLEVEL;
1105. 
1106.     return TRUE;
1107. }
1108. 
1109. /* initialize the Castle drawbridge tune */
1110. staticfn void
1111. init_castle_tune(void)
1112. {
1113.     int i;
1114. 
1115.     for (i = 0; i < 5; i++)
1116.         svt.tune[i] = 'A' + rn2(7);
1117.     svt.tune[5] = 0;
1118. }
1119. 
1120. /* fix up the special level names and locations for quick access */
1121. staticfn void
1122. fixup_level_locations(void)
1123. {
1124.     int i;
1125.     s_level *x;
1126.     struct level_map *lev_map;
1127. 
1128.     /*
1129.      * Find most of the special levels and dungeons so we can access their
1130.      * locations quickly.
1131.      */
1132.     for (lev_map = level_map; lev_map->lev_name[0]; lev_map++) {
1133.         x = find_level(lev_map->lev_name);
1134.         if (x) {
1135.             assign_level(lev_map->lev_spec, &x->dlevel);
1136.             if (!strncmp(lev_map->lev_name, "x-", 2)) {
1137.                 /* This is where the name substitution on the
1138.                  * levels of the quest dungeon occur.
1139.                  */
1140.                 Sprintf(x->proto, "%s%s", gu.urole.filecode,
1141.                         &lev_map->lev_name[1]);
1142.             } else if (lev_map->lev_spec == &knox_level) {
1143.                 branch *br;
1144.                 /*
1145.                  * Kludge to allow floating Knox entrance.  We
1146.                  * specify a floating entrance by the fact that its
1147.                  * entrance (end1) has a bogus dnum, namely n_dgns.
1148.                  */
1149.                 for (br = svb.branches; br; br = br->next)
1150.                     if (on_level(&br->end2, &knox_level))
1151.                         break;
1152. 
1153.                 if (br) {
1154.                     br->end1.dnum = svn.n_dgns;
1155.                     /* adjust the branch's position on the list */
1156.                     insert_branch(br, TRUE);
1157.                 }
1158.             }
1159.         }
1160.     }
1161.     /*
1162.      *  I hate hardwiring these names. :-(
1163.      */
1164.     quest_dnum = dname_to_dnum("The Quest");
1165.     sokoban_dnum = dname_to_dnum("Sokoban");
1166.     mines_dnum = dname_to_dnum("The Gnomish Mines");
1167.     tower_dnum = dname_to_dnum("Vlad's Tower");
1168.     tutorial_dnum = dname_to_dnum("The Tutorial");
1169. 
1170.     /* one special fixup for dummy surface level */
1171.     if ((x = find_level("dummy")) != 0) {
1172.         i = x->dlevel.dnum;
1173.         /* the code above puts earth one level above dungeon level #1,
1174.            making the dummy level overlay level 1; but the whole reason
1175.            for having the dummy level is to make earth have depth -1
1176.            instead of 0, so adjust the start point to shift endgame up */
1177.         if (dunlevs_in_dungeon(&x->dlevel) > 1 - svd.dungeons[i].depth_start)
1178.             svd.dungeons[i].depth_start -= 1;
1179.         /* TODO: strip "dummy" out all the way here,
1180.            so that it's hidden from '#wizwhere' feedback. */
1181.     }
1182. }
1183. 
1184. staticfn void
1185. free_proto_dungeon(struct proto_dungeon *pd)
1186. {
1187.     int i;
1188. 
1189.     for (i = 0; i < pd->n_brs; i++) {
1190.         free((genericptr_t) pd->tmpbranch[i].name);
1191.     }
1192.     for (i = 0; i < pd->n_levs; i++) {
1193.         free((genericptr_t) pd->tmplevel[i].name);
1194.         if (pd->tmplevel[i].chainlvl)
1195.             free((genericptr_t) pd->tmplevel[i].chainlvl);
1196.     }
1197.     for (i = 0; i < svn.n_dgns; i++) {
1198.         free((genericptr_t) pd->tmpdungeon[i].name);
1199.         free((genericptr_t) pd->tmpdungeon[i].protoname);
1200.     }
1201. }
1202. 
1203. /* initialize the "dungeon" structs */
1204. void
1205. init_dungeons(void)
1206. {
1207.     lua_State *L;
1208.     int i, cl = 0;
1209.     struct proto_dungeon pd;
1210.     int tidx;
1211.     nhl_sandbox_info sbi = {NHL_SB_SAFE, 1*1024*1024, 0, 1*1024*1024};
1212. 
1213.     (void) memset(&pd, 0, sizeof (struct proto_dungeon));
1214.     pd.n_levs = pd.n_brs = 0;
1215. 
1216.     L = nhl_init(&sbi); /* private Lua state for this function */
1217.     if (!L) {
1218.         panic1("'nhl_init' failed; can't continue.");
1219.         /*NOTREACHED*/
1220.     }
1221.     if (!nhl_loadlua(L, DUNGEON_FILE)) {
1222.         char tbuf[BUFSZ];
1223.         Sprintf(tbuf, "Cannot open dungeon description - \"%s", DUNGEON_FILE);
1224. #ifdef DLBRSRC /* using a resource from the executable */
1225.         Strcat(tbuf, "\" resource!");
1226. #else /* using a file or DLB file */
1227. #if defined(DLB)
1228.         Strcat(tbuf, "\" from ");
1229. #ifdef PREFIXES_IN_USE
1230.         Strcat(tbuf, "\n\"");
1231.         if (gf.fqn_prefix[DATAPREFIX])
1232.             Strcat(tbuf, gf.fqn_prefix[DATAPREFIX]);
1233. #else
1234.         Strcat(tbuf, "\"");
1235. #endif
1236.         Strcat(tbuf, DLBFILE);
1237. #endif
1238.         Strcat(tbuf, "\" file!");
1239. #endif
1240. #ifdef WIN32
1241.         interject_assistance(1, INTERJECT_PANIC, (genericptr_t) tbuf,
1242.                              (genericptr_t) gf.fqn_prefix[DATAPREFIX]);
1243. #endif
1244.         panic1(tbuf);
1245.     }
1246. 
1247.     if (iflags.window_inited)
1248.         clear_nhwindow(WIN_MAP);
1249. 
1250.     svs.sp_levchn = (s_level *) 0;
1251. 
1252.     lua_settop(L, 0);
1253. 
1254.     lua_getglobal(L, "dungeon");
1255.     if (!lua_istable(L, -1))
1256.         panic("dungeon is not a lua table");
1257. 
1258.     lua_len(L, -1);
1259.     svn.n_dgns = (int) lua_tointeger(L, -1);
1260.     lua_pop(L, 1);
1261. 
1262.     pd.start = 0;
1263.     pd.n_levs = 0;
1264.     pd.n_brs = 0;
1265. 
1266.     /*
1267.      * Read in each dungeon and transfer the results to the internal
1268.      * dungeon arrays.
1269.      */
1270. 
1271.     if (svn.n_dgns >= MAXDUNGEON)
1272.         panic("init_dungeons: too many dungeons");
1273. 
1274.     tidx = lua_gettop(L);
1275. 
1276.     lua_pushnil(L); /* first key */
1277.     i = 0;
1278.     while (lua_next(L, tidx) != 0) {
1279. 
1280.         if (!lua_istable(L, -1))
1281.             panic("dungeon[%i] is not a lua table", i);
1282. 
1283.         if (init_dungeon_dungeons(L, &pd, i)) {
1284.             for (; cl < pd.n_levs; cl++) {
1285.                 init_level(i, cl, &pd);
1286.             }
1287.             /*
1288.              * Recursively place the generated levels for this dungeon.  This
1289.              * routine will attempt all possible combinations before giving
1290.              * up.
1291.              */
1292.             if (!place_level(pd.start, &pd))
1293.                 panic("init_dungeon:  couldn't place levels");
1294. #ifdef DDEBUG
1295.             fprintf(stderr, "--- end of dungeon %d ---\n", i);
1296.             fflush(stderr);
1297.             getchar();
1298. #endif
1299.             for (; pd.start < pd.n_levs; pd.start++)
1300.                 if (pd.final_lev[pd.start])
1301.                     add_level(pd.final_lev[pd.start]);
1302.             /* levels handling end */
1303.             i++;
1304.         }
1305.         lua_pop(L, 1); /* pop the dungeon table */
1306.     }
1307. 
1308.     lua_pop(L, 1); /* get rid of the dungeon global */
1309.     debugpline2("init_dungeon lua DONE (n_levs=%i, n_brs=%i)",
1310.                 pd.n_levs, pd.n_brs);
1311. 
1312.     init_castle_tune();
1313.     fixup_level_locations();
1314.     nhl_done(L);
1315.     free_proto_dungeon(&pd);
1316. #ifdef DEBUG
1317.     dumpit();
1318. #endif
1319. }
1320. 
1321. #undef DUNGEON_FILE
1322. 
1323. /* return the level number for lev in *this* dungeon */
1324. xint16
1325. dunlev(d_level *lev)
1326. {
1327.     return lev->dlevel;
1328. }
1329. 
1330. /* return the lowest level number for *this* dungeon */
1331. xint16
1332. dunlevs_in_dungeon(d_level *lev)
1333. {
1334.     return svd.dungeons[lev->dnum].num_dunlevs;
1335. }
1336. 
1337. /* return the lowest level explored in the game*/
1338. xint16
1339. deepest_lev_reached(boolean noquest)
1340. {
1341.     /* this function is used for three purposes: to provide a factor
1342.      * of difficulty in monster generation; to provide a factor of
1343.      * difficulty in experience calculations (botl.c and end.c); and
1344.      * to insert the deepest level reached in the game in the topten
1345.      * display.  the 'noquest' arg switch is required for the latter.
1346.      *
1347.      * from the player's point of view, going into the Quest is _not_
1348.      * going deeper into the dungeon -- it is going back "home", where
1349.      * the dungeon starts at level 1.  given the setup in dungeon.def,
1350.      * the depth of the Quest (thought of as starting at level 1) is
1351.      * never lower than the level of entry into the Quest, so we exclude
1352.      * the Quest from the topten "deepest level reached" display
1353.      * calculation.  _However_ the Quest is a difficult dungeon, so we
1354.      * include it in the factor of difficulty calculations.
1355.      */
1356.     int i;
1357.     d_level tmp;
1358.     xint16 ret = 0;
1359. 
1360.     for (i = 0; i < svn.n_dgns; i++) {
1361.         if (noquest && i == quest_dnum)
1362.             continue;
1363.         tmp.dlevel = svd.dungeons[i].dunlev_ureached;
1364.         if (tmp.dlevel == 0)
1365.             continue;
1366.         tmp.dnum = i;
1367.         if (depth(&tmp) > ret)
1368.             ret = depth(&tmp);
1369.     }
1370.     return ret;
1371. }
1372. 
1373. /* return a bookkeeping level number for purpose of comparisons and
1374.    save/restore */
1375. xint16
1376. ledger_no(d_level *lev)
1377. {
1378.     return (xint16) (lev->dlevel + svd.dungeons[lev->dnum].ledger_start);
1379. }
1380. 
1381. /*
1382.  * The last level in the bookkeeping list of level is the bottom of the last
1383.  * dungeon in the svd.dungeons[] array.
1384.  *
1385.  * Maxledgerno() -- which is the max number of levels in the bookkeeping
1386.  * list, should not be confused with dunlevs_in_dungeon(lev) -- which
1387.  * returns the max number of levels in lev's dungeon, and both should
1388.  * not be confused with deepest_lev_reached() -- which returns the lowest
1389.  * depth visited by the player.
1390.  */
1391. xint16
1392. maxledgerno(void)
1393. {
1394.     return (xint16) (svd.dungeons[svn.n_dgns - 1].ledger_start
1395.                     + svd.dungeons[svn.n_dgns - 1].num_dunlevs);
1396. }
1397. 
1398. DISABLE_WARNING_UNREACHABLE_CODE
1399. 
1400. /* return the dungeon that this ledgerno exists in */
1401. xint16
1402. ledger_to_dnum(xint16 ledgerno)
1403. {
1404.     xint16 i;
1405. 
1406.     /* find i such that (i->base + 1) <= ledgerno <= (i->base + i->count) */
1407.     for (i = 0; i < svn.n_dgns; i++)
1408.         if (svd.dungeons[i].ledger_start < ledgerno
1409.             && ledgerno <= (svd.dungeons[i].ledger_start
1410.                             + svd.dungeons[i].num_dunlevs))
1411.             return i;
1412. 
1413.     panic("level number out of range [ledger_to_dnum(%d)]", (int) ledgerno);
1414.     /*NOT REACHED*/
1415.     return (xint16) 0;
1416. }
1417. 
1418. RESTORE_WARNING_UNREACHABLE_CODE
1419. 
1420. /* return the level of the dungeon this ledgerno exists in */
1421. xint16
1422. ledger_to_dlev(xint16 ledgerno)
1423. {
1424.     return (xint16) (ledgerno
1425.                     - svd.dungeons[ledger_to_dnum(ledgerno)].ledger_start);
1426. }
1427. 
1428. /* returns the depth of a level, in floors below the surface
1429.    (note levels in different dungeons can have the same depth) */
1430. schar
1431. depth(d_level *lev)
1432. {
1433.     return (schar) (svd.dungeons[lev->dnum].depth_start + lev->dlevel - 1);
1434. }
1435. #endif /* !SFCTOOL */
1436. 
1437. /* are "lev1" and "lev2" actually the same? */
1438. boolean
1439. on_level(d_level *lev1, d_level *lev2)
1440. {
1441.     return (boolean) (lev1->dnum == lev2->dnum
1442.                       && lev1->dlevel == lev2->dlevel);
1443. }
1444. 
1445. #ifndef SFCTOOL
1446. /* is this level referenced in the special level chain? */
1447. s_level *
1448. Is_special(d_level *lev)
1449. {
1450.     s_level *levtmp;
1451. 
1452.     for (levtmp = svs.sp_levchn; levtmp; levtmp = levtmp->next)
1453.         if (on_level(lev, &levtmp->dlevel))
1454.             return levtmp;
1455. 
1456.     return (s_level *) 0;
1457. }
1458. 
1459. /*
1460.  * Is this a multi-dungeon branch level?  If so, return a pointer to the
1461.  * branch.  Otherwise, return null.
1462.  */
1463. branch *
1464. Is_branchlev(d_level *lev)
1465. {
1466.     branch *curr;
1467. 
1468.     for (curr = svb.branches; curr; curr = curr->next) {
1469.         if (on_level(lev, &curr->end1) || on_level(lev, &curr->end2))
1470.             return curr;
1471.     }
1472.     return (branch *) 0;
1473. }
1474. 
1475. /* returns True iff the branch 'lev' is in a branch which builds up */
1476. boolean
1477. builds_up(d_level *lev)
1478. {
1479.     dungeon *dptr = &svd.dungeons[lev->dnum];
1480.     branch *br;
1481.     if (dptr->num_dunlevs > 1)
1482.         return (boolean) (dptr->entry_lev == dptr->num_dunlevs);
1483.     /* else, single-level branch; find branch connection that connects this
1484.      * dungeon from a parent dungeon and determine whether it builds up from
1485.      * that */
1486.     for (br = svb.branches; br; br = br->next) {
1487.         if (on_level(lev, &br->end2)) {
1488.             return br->end1_up;
1489.         }
1490.     }
1491.     impossible("builds_up: can't find branch for dungeon %d", lev->dnum);
1492.     return FALSE;
1493. }
1494. 
1495. /* goto the next level (or appropriate dungeon) */
1496. void
1497. next_level(boolean at_stairs)
1498. {
1499.     stairway *stway = stairway_at(u.ux, u.uy);
1500.     d_level newlevel;
1501. 
1502.     if (at_stairs && stway)
1503.         stway->u_traversed = TRUE;
1504. 
1505.     if (at_stairs && stway) {
1506.         newlevel.dnum = stway->tolev.dnum;
1507.         newlevel.dlevel = stway->tolev.dlevel;
1508.         goto_level(&newlevel, at_stairs, FALSE, FALSE);
1509.     } else {
1510.         newlevel.dnum = u.uz.dnum;
1511.         newlevel.dlevel = u.uz.dlevel + 1;
1512.         goto_level(&newlevel, at_stairs, !at_stairs, FALSE);
1513.     }
1514. }
1515. 
1516. /* goto the previous level (or appropriate dungeon) */
1517. void
1518. prev_level(boolean at_stairs)
1519. {
1520.     stairway *stway = stairway_at(u.ux, u.uy);
1521.     d_level newlevel;
1522. 
1523.     if (at_stairs && stway)
1524.         stway->u_traversed = TRUE;
1525. 
1526.     if (at_stairs && stway && stway->tolev.dnum != u.uz.dnum) {
1527.         /* Taking an up dungeon branch. */
1528.         /* KMH -- Upwards branches are okay if not level 1 */
1529.         /* (Just make sure it doesn't go above depth 1) */
1530.         if (!u.uz.dnum && u.uz.dlevel == 1 && !u.uhave.amulet)
1531.             done(ESCAPED);
1532.         else {
1533.             newlevel.dnum = stway->tolev.dnum;
1534.             newlevel.dlevel = stway->tolev.dlevel;
1535.             goto_level(&newlevel, at_stairs, FALSE, FALSE);
1536.         }
1537.     } else {
1538.         /* Going up a stairs or rising through the ceiling. */
1539.         newlevel.dnum = u.uz.dnum;
1540.         newlevel.dlevel = u.uz.dlevel - 1;
1541.         goto_level(&newlevel, at_stairs, FALSE, FALSE);
1542.     }
1543. }
1544. 
1545. /* Dwarves have "earth sense",
1546.    able to sense if something is buried under their feet */
1547. staticfn void
1548. earth_sense(void)
1549. {
1550.     struct obj *otmp;
1551. 
1552.     if (!Race_if(PM_DWARF))
1553.         return;
1554.     if (u.usteed || Flying || Levitation || Upolyd)
1555.         return;
1556.     if (levl[u.ux][u.uy].typ != CORR
1557.         && levl[u.ux][u.uy].typ != ROOM)
1558.         return;
1559. 
1560.     for (otmp = svl.level.buriedobjlist; otmp; otmp = otmp->nobj)
1561.         if (u_at(otmp->ox, otmp->oy)) {
1562.             You("sense something below your %s.", makeplural(body_part(FOOT)));
1563.             return;
1564.         }
1565. }
1566. 
1567. void
1568. u_on_newpos(coordxy x, coordxy y)
1569. {
1570.     if (!isok(x, y)) { /* validate location */
1571.         void (*func)(const char *, ...) PRINTF_F_PTR(1, 2);
1572. 
1573.         func = (x < 0 || y < 0 || x > COLNO - 1 || y > ROWNO - 1) ? panic
1574.                : impossible;
1575.         (*func)("u_on_newpos: trying to place hero off map <%d,%d>", x, y);
1576.     }
1577.     u.ux = x;
1578.     u.uy = y;
1579. #ifdef CLIPPING
1580.     cliparound(u.ux, u.uy);
1581. #endif
1582.     u.uundetected = 0;
1583.     /* ridden steed always shares hero's location */
1584.     if (u.usteed)
1585.         u.usteed->mx = u.ux, u.usteed->my = u.uy;
1586.     /* when changing levels, don't leave old position set with
1587.        stale values from previous level */
1588.     if (!on_level(&u.uz, &u.uz0)) {
1589.         u.ux0 = u.ux, u.uy0 = u.uy;
1590.         /* sets lastseentyp[u.ux][u.uy]; needed for switch_terrain()
1591.            somewhere back up the call chain */
1592.         map_location(u.ux, u.uy, FALSE);
1593.         iflags.terrain_typ = MAX_TYPE; /* "none of the above" value */
1594.     } else {
1595.         /* still on same level; might have come close enough to
1596.            generic object(s) to redisplay them as specific objects */
1597.         if (!Blind && !Hallucination && !u.uswallow)
1598.             see_nearby_objects();
1599.     }
1600.     earth_sense();
1601. }
1602. 
1603. /* place you on a random location when arriving on a level */
1604. void
1605. u_on_rndspot(int upflag)
1606. {
1607.     int up = (upflag & 1), was_in_W_tower = (upflag & 2);
1608. 
1609.     /*
1610.      * Place the hero at a random location within the relevant region.
1611.      * place_lregion(xTELE) -> put_lregion_here(xTELE) -> u_on_newpos()
1612.      * Unspecified region (.lx == 0) defaults to entire level.
1613.      */
1614.     if (was_in_W_tower && On_W_tower_level(&u.uz))
1615.         /* Stay inside the Wizard's tower when feasible.
1616.            We use the W Tower's exclusion region for the
1617.            destination instead of its enclosing region.
1618.            Note: up vs down doesn't matter in this case
1619.            because both specify the same exclusion area. */
1620.         place_lregion(svd.dndest.nlx, svd.dndest.nly,
1621.                       svd.dndest.nhx, svd.dndest.nhy,
1622.                       0, 0, 0, 0, LR_DOWNTELE, (d_level *) 0);
1623.     else if (up)
1624.         place_lregion(svu.updest.lx, svu.updest.ly,
1625.                       svu.updest.hx, svu.updest.hy,
1626.                       svu.updest.nlx, svu.updest.nly,
1627.                       svu.updest.nhx, svu.updest.nhy,
1628.                       LR_UPTELE, (d_level *) 0);
1629.     else
1630.         place_lregion(svd.dndest.lx, svd.dndest.ly,
1631.                       svd.dndest.hx, svd.dndest.hy,
1632.                       svd.dndest.nlx, svd.dndest.nly,
1633.                       svd.dndest.nhx, svd.dndest.nhy,
1634.                       LR_DOWNTELE, (d_level *) 0);
1635. 
1636.     /* might have just left solid rock and unblocked levitation */
1637.     switch_terrain();
1638. }
1639. 
1640. #endif /* !SFCTOOL */
1641. #ifndef SFCTOOL
1642. boolean
1643. Is_botlevel(d_level *lev)
1644. {
1645.     return (boolean) (lev->dlevel == svd.dungeons[lev->dnum].num_dunlevs);
1646. }
1647. 
1648. boolean
1649. Can_dig_down(d_level *lev)
1650. {
1651.     return (boolean) (!svl.level.flags.hardfloor
1652.                       && !Is_botlevel(lev)
1653.                       && !Invocation_lev(lev));
1654. }
1655. 
1656. /*
1657.  * Like Can_dig_down (above), but also allows falling through on the
1658.  * stronghold level.  Normally, the bottom level of a dungeon resists
1659.  * both digging and falling.
1660.  */
1661. boolean
1662. Can_fall_thru(d_level *lev)
1663. {
1664.     return (boolean) (Can_dig_down(lev) || Is_stronghold(lev));
1665. }
1666. 
1667. /*
1668.  * True if one can rise up a level (e.g. cursed gain level).
1669.  * This happens on intermediate dungeon levels or on any top dungeon
1670.  * level that has a stairwell style branch to the next higher dungeon.
1671.  * Checks for amulets and such must be done elsewhere.
1672.  */
1673. boolean
1674. Can_rise_up(coordxy x, coordxy y, d_level *lev)
1675. {
1676.     stairway *stway = stairway_find_special_dir(FALSE);
1677. 
1678.     /* can't rise up from inside the top of the Wizard's tower */
1679.     /* KMH -- or in sokoban */
1680.     if (In_endgame(lev) || In_sokoban(lev)
1681.         || (Is_wiz1_level(lev) && In_W_tower(x, y, lev)))
1682.         return FALSE;
1683.     return (boolean) (lev->dlevel > 1
1684.                       || (svd.dungeons[lev->dnum].entry_lev == 1
1685.                           && ledger_no(lev) != 1
1686.                           && stway && stway->up));
1687. }
1688. 
1689. boolean
1690. has_ceiling(d_level *lev)
1691. {
1692.     /* FIXME: some (most? all?) of the quest home levels are conceptually
1693.        above ground and don't have ceilings outside of their buildings
1694.        but we don't presently check for that */
1695.     if (In_endgame(lev) && !Is_earthlevel(lev))
1696.         return FALSE;
1697.     return TRUE;
1698. }
1699. 
1700. boolean
1701. avoid_ceiling(d_level *lev)
1702. {
1703.     /* The quest is challenging since parts of the level
1704.        may have ceilings and other parts may not; Avoid
1705.        the ambiguity there by testing with avoid_ceiling()
1706.        and using alternative messaging that avoids the term
1707.        ceiling altogether there */
1708.     if (In_quest(lev) || !has_ceiling(lev))
1709.         return TRUE;
1710.     return FALSE;
1711. }
1712. 
1713. const char *
1714. ceiling(coordxy x, coordxy y)
1715. {
1716.     struct rm *lev = &levl[x][y];
1717.     const char *what;
1718. 
1719.     /* other room types will no longer exist when we're interested --
1720.      * see check_special_room()
1721.      */
1722.     if (*in_rooms(x, y, VAULT))
1723.         what = "vault's ceiling";
1724.     else if (*in_rooms(x, y, TEMPLE))
1725.         what = "temple's ceiling";
1726.     else if (*in_rooms(x, y, SHOPBASE))
1727.         what = "shop's ceiling";
1728.     else if (Is_waterlevel(&u.uz))
1729.         /* water plane has no surface; its air bubbles aren't below sky */
1730.         what = "water above";
1731.     else if (IS_AIR(lev->typ))
1732.         what = "sky";
1733.     else if (Is_firelevel(&u.uz))
1734.         what = "flames above";
1735.     else if (In_quest(&u.uz))
1736.         /* just in case; try to avoid in caller if you can */
1737.         what = "expanse above";
1738.     else if (Underwater)
1739.         what = "water's surface";
1740.     else if ((IS_ROOM(lev->typ) && !Is_earthlevel(&u.uz))
1741.              || IS_WALL(lev->typ) || IS_DOOR(lev->typ) || lev->typ == SDOOR)
1742.         what = "ceiling";
1743.     else
1744.         what = "rock cavern";
1745. 
1746.     return what;
1747. }
1748. 
1749. const char *
1750. surface(coordxy x, coordxy y)
1751. {
1752.     struct rm *lev = &levl[x][y];
1753.     int levtyp = SURFACE_AT(x, y);
1754. 
1755.     if (u_at(x, y) && u.uswallow && is_animal(u.ustuck->data))
1756.         /* 'husk' is iffy but maw is wrong for 't' class */
1757.         return digests(u.ustuck->data) ? "maw"
1758.                : enfolds(u.ustuck->data) ? "husk"
1759.                  : "nonesuch"; /* can't happen (fingers crossed...) */
1760.     else if (IS_AIR(levtyp))
1761.         return Is_waterlevel(&u.uz) ? "air bubble"
1762.                                     : (levtyp == CLOUD) ? "cloud" : "air";
1763.     else if (is_pool(x, y))
1764.         return (Underwater && !Is_waterlevel(&u.uz))
1765.             ? "bottom" : hliquid("water");
1766.     else if (is_ice(x, y))
1767.         return "ice";
1768.     else if (is_lava(x, y))
1769.         return hliquid("lava");
1770.     else if (lev->typ == DRAWBRIDGE_DOWN)
1771.         return "bridge";
1772.     else if (IS_ALTAR(levtyp))
1773.         return "altar";
1774.     else if (IS_GRAVE(levtyp))
1775.         return "headstone";
1776.     else if (IS_FOUNTAIN(levtyp))
1777.         return "fountain";
1778.     else if (On_stairs(x, y))
1779.         return "stairs";
1780.     else if (IS_WALL(levtyp) || levtyp == SDOOR)
1781.         return "wall"; /* 'surface' during Passes_walls */
1782.     else if (IS_DOOR(levtyp))
1783.         return "doorway"; /* even for closed door */
1784.     else if (IS_ROOM(levtyp) && !Is_earthlevel(&u.uz))
1785.         return "floor";
1786.     else
1787.         return "ground";
1788. }
1789. 
1790. /*
1791.  * It is expected that the second argument of get_level is a depth value,
1792.  * either supplied by the user (teleport control) or randomly generated.
1793.  * But more than one level can be at the same depth.  If the target level
1794.  * is "above" the present depth location, get_level must trace "up" from
1795.  * the player's location (through the ancestors dungeons) the dungeon
1796.  * within which the target level is located.  With only one exception
1797.  * which does not pass through this routine (see level_tele), teleporting
1798.  * "down" is confined to the current dungeon.  At present, level teleport
1799.  * in dungeons that build up is confined within them.
1800.  */
1801. void
1802. get_level(d_level *newlevel, int levnum)
1803. {
1804.     branch *br;
1805.     xint16 dgn = u.uz.dnum;
1806. 
1807.     if (levnum <= 0) {
1808.         /* can only currently happen in endgame */
1809.         levnum = u.uz.dlevel;
1810.     } else if (levnum > (svd.dungeons[dgn].depth_start
1811.                          + svd.dungeons[dgn].num_dunlevs - 1)) {
1812.         /* beyond end of dungeon, jump to last level */
1813.         levnum = svd.dungeons[dgn].num_dunlevs;
1814.     } else {
1815.         /* The desired level is in this dungeon or a "higher" one. */
1816. 
1817.         /*
1818.          * Branch up the tree until we reach a dungeon that contains the
1819.          * levnum.
1820.          */
1821.         if (levnum < svd.dungeons[dgn].depth_start) {
1822.             do {
1823.                 /*
1824.                  * Find the parent dungeon of this dungeon.
1825.                  *
1826.                  * This assumes that end2 is always the "child" and it is
1827.                  * unique.
1828.                  */
1829.                 for (br = svb.branches; br; br = br->next)
1830.                     if (br->end2.dnum == dgn)
1831.                         break;
1832.                 if (!br)
1833.                     panic("get_level: can't find parent dungeon");
1834. 
1835.                 dgn = br->end1.dnum;
1836.             } while (levnum < svd.dungeons[dgn].depth_start);
1837.         }
1838. 
1839.         /* We're within the same dungeon; calculate the level. */
1840.         levnum = levnum - svd.dungeons[dgn].depth_start + 1;
1841.     }
1842. 
1843.     newlevel->dnum = dgn;
1844.     newlevel->dlevel = levnum;
1845. }
1846. 
1847. /* are you in the quest dungeon? */
1848. boolean
1849. In_quest(d_level *lev)
1850. {
1851.     return (boolean) (lev->dnum == quest_dnum);
1852. }
1853. 
1854. /* are you in the mines dungeon? */
1855. boolean
1856. In_mines(d_level *lev)
1857. {
1858.     return (boolean) (lev->dnum == mines_dnum);
1859. }
1860. 
1861. /*
1862.  * Return the branch for the given dungeon.
1863.  *
1864.  * This function assumes:
1865.  *      + This is not called with "Dungeons of Doom".
1866.  *      + There is only _one_ branch to a given dungeon.
1867.  *      + Field end2 is the "child" dungeon.
1868.  */
1869. branch *
1870. dungeon_branch(const char *s)
1871. {
1872.     branch *br;
1873.     xint16 dnum;
1874. 
1875.     dnum = dname_to_dnum(s);
1876. 
1877.     /* Find the branch that connects to dungeon i's branch. */
1878.     for (br = svb.branches; br; br = br->next)
1879.         if (br->end2.dnum == dnum)
1880.             break;
1881. 
1882.     if (!br)
1883.         panic("dgn_entrance: can't find entrance to %s", s);
1884. 
1885.     return br;
1886. }
1887. 
1888. /*
1889.  * This returns true if the hero is on the same level as the entrance to
1890.  * the named dungeon.
1891.  *
1892.  * Called from do.c and mklev.c.
1893.  *
1894.  * Assumes that end1 is always the "parent".
1895.  */
1896. boolean
1897. at_dgn_entrance(const char *s)
1898. {
1899.     branch *br;
1900. 
1901.     br = dungeon_branch(s);
1902.     return on_level(&u.uz, &br->end1) ? TRUE : FALSE;
1903. }
1904. 
1905. /* is `lev' part of Vlad's tower? */
1906. boolean
1907. In_V_tower(d_level *lev)
1908. {
1909.     return (boolean) (lev->dnum == tower_dnum);
1910. }
1911. 
1912. /* is `lev' a level containing the Wizard's tower? */
1913. boolean
1914. On_W_tower_level(d_level *lev)
1915. {
1916.     return (boolean) (Is_wiz1_level(lev)
1917.                       || Is_wiz2_level(lev)
1918.                       || Is_wiz3_level(lev));
1919. }
1920. 
1921. /* is <x,y> of `lev' inside the Wizard's tower? */
1922. boolean
1923. In_W_tower(coordxy x, coordxy y, d_level *lev)
1924. {
1925.     if (!On_W_tower_level(lev))
1926.         return FALSE;
1927.     if (!svd.dndest.nlx) {
1928.         impossible("No boundary for Wizard's Tower?");
1929.         return FALSE;
1930.     }
1931.     /*
1932.      * Both of the exclusion regions for arriving via level teleport
1933.      * (from above or below) define the tower's boundary.
1934.      *  assert( svu.updest.nIJ == svd.dndest.nIJ for I={l|h},J={x|y} );
1935.      */
1936.     return (boolean) within_bounded_area(x, y, svd.dndest.nlx, svd.dndest.nly,
1937.                                          svd.dndest.nhx, svd.dndest.nhy);
1938. }
1939. 
1940. /* are you in one of the Hell levels? */
1941. boolean
1942. In_hell(d_level *lev)
1943. {
1944.     return (boolean) (svd.dungeons[lev->dnum].flags.hellish);
1945. }
1946. 
1947. /* sets *lev to be the gateway to Gehennom... */
1948. void
1949. find_hell(d_level *lev)
1950. {
1951.     lev->dnum = valley_level.dnum;
1952.     lev->dlevel = 1;
1953. }
1954. 
1955. /* go directly to hell... */
1956. void
1957. goto_hell(boolean at_stairs, boolean falling)
1958. {
1959.     d_level lev;
1960. 
1961.     find_hell(&lev);
1962.     goto_level(&lev, at_stairs, falling, FALSE);
1963. }
1964. 
1965. /* is 'lev' the only level in its branch?  affects level teleporters */
1966. boolean
1967. single_level_branch(d_level *lev)
1968. {
1969.     /*
1970.      * TODO:  this should be generalized instead of assuming that
1971.      * Fort Ludios is the only single level branch in the dungeon.
1972.      */
1973.     return Is_knox(lev);
1974. }
1975. 
1976. /* equivalent to dest = source */
1977. void
1978. assign_level(d_level *dest, d_level *src)
1979. {
1980.     dest->dnum = src->dnum;
1981.     dest->dlevel = src->dlevel;
1982. }
1983. 
1984. /* dest = src + rn1(range) */
1985. void
1986. assign_rnd_level(d_level *dest, d_level *src, int range)
1987. {
1988.     dest->dnum = src->dnum;
1989.     dest->dlevel = src->dlevel + ((range > 0) ? rnd(range) : -rnd(-range));
1990. 
1991.     if (dest->dlevel > dunlevs_in_dungeon(dest))
1992.         dest->dlevel = dunlevs_in_dungeon(dest);
1993.     else if (dest->dlevel < 1)
1994.         dest->dlevel = 1;
1995. }
1996. 
1997. /* return an alignment mask */
1998. unsigned int
1999. induced_align(int pct)
2000. {
2001.     s_level *lev = Is_special(&u.uz);
2002.     aligntyp al;
2003. 
2004.     if (lev && lev->flags.align)
2005.         if (rn2(100) < pct)
2006.             return lev->flags.align;
2007. 
2008.     if (svd.dungeons[u.uz.dnum].flags.align)
2009.         if (rn2(100) < pct)
2010.             return svd.dungeons[u.uz.dnum].flags.align;
2011. 
2012.     al = rn2(3) - 1;
2013.     return Align2amask(al);
2014. }
2015. 
2016. boolean
2017. Invocation_lev(d_level *lev)
2018. {
2019.     return (boolean) (In_hell(lev)
2020.                    && lev->dlevel == svd.dungeons[lev->dnum].num_dunlevs - 1);
2021. }
2022. 
2023. /* use instead of depth() wherever a degree of difficulty is made
2024.  * dependent on the location in the dungeon (eg. monster creation).
2025.  */
2026. xint16
2027. level_difficulty(void)
2028. {
2029.     xint16 res;
2030. 
2031.     if (In_endgame(&u.uz)) {
2032.         res = depth(&sanctum_level) + u.ulevel / 2;
2033.     } else if (u.uhave.amulet) {
2034.         res = deepest_lev_reached(FALSE);
2035.     } else {
2036.         res = depth(&u.uz);
2037.         /* depth() is the number of elevation units (levels) below
2038.            the theoretical surface; in a builds-up branch, that value
2039.            ends up making the harder to reach levels be treated as if
2040.            they were easier; adjust for the extra effort involved in
2041.            going down to the entrance and then up to the location */
2042.         if (builds_up(&u.uz))
2043.             res += 2 * (svd.dungeons[u.uz.dnum].entry_lev - u.uz.dlevel + 1);
2044.             /*
2045.              * 'Proof' by example:  suppose the entrance to sokoban is
2046.              * on dungeon level 9, leading up to bottom sokoban level
2047.              * of 8 [entry_lev].  When the hero is on sokoban level 8
2048.              * [uz.dlevel], depth() yields eight but he has ventured
2049.              * one level beyond 9, so difficulty depth should be 10:
2050.              *   8 + 2 * (8 - 8 + 1) => 10.
2051.              * Going up to 7, depth is 7 but hero will be two beyond 9:
2052.              *   7 + 2 * (8 - 7 + 1) => 11.
2053.              * When he goes up to level 6, three levels beyond 9:
2054.              *   6 + 2 * (8 - 6 + 1) => 12.
2055.              * And the top level of sokoban at 5, four levels beyond 9:
2056.              *   5 + 2 * (8 - 5 + 1) => 13.
2057.              * The same applies to Vlad's Tower, although the increment
2058.              * there is inconsequential compared to overall depth.
2059.              */
2060. #if 0
2061.         /*
2062.          * The inside of the Wizard's Tower is also effectively a
2063.          * builds-up area, reached from a portal an arbitrary distance
2064.          * below rather than stairs 1 level beneath the entry level.
2065.          */
2066.         else if (On_W_tower_level(&u.uz) && In_W_tower(some_X, some_Y, &u.uz))
2067.             res += (fakewiz1.dlevel - u.uz.dlevel);
2068.             /*
2069.              * Handling this properly would need more information here:
2070.              * an inside/outside flag, or coordinates to calculate it.
2071.              * Unfortunately level difficulty may be wanted before
2072.              * coordinates have been chosen so simply extending this
2073.              * routine to take extra arguments is not sufficient to cope.
2074.              * The difference beyond naive depth-from-surface is small
2075.              * relative to the overall depth, so just ignore complications
2076.              * posed by W_tower.
2077.              */
2078. #endif /*0*/
2079.     }
2080.     /* ring of aggravate monster */
2081.     if (EAggravate_monster)
2082.         res = res > 25 ? 50 : res * 2;
2083.     return res;
2084. }
2085. 
2086. /* within same branch, or else main dungeon <-> gehennom */
2087. #define dlev_in_current_branch(dlev) \
2088.     (dlev.dnum == u.uz.dnum                     \
2089.      || (u.uz.dnum == valley_level.dnum         \
2090.          && dlev.dnum == medusa_level.dnum)     \
2091.      || (u.uz.dnum == medusa_level.dnum         \
2092.          && dlev.dnum == valley_level.dnum))
2093. 
2094. /* Take one word and try to match it to a level.
2095.  * Recognized levels are as shown by print_dungeon().
2096.  */
2097. schar
2098. lev_by_name(const char *nam)
2099. {
2100.     schar lev = 0;
2101.     s_level *slev = (s_level *) 0;
2102.     d_level dlev;
2103.     const char *p;
2104.     int idx, idxtoo;
2105.     char buf[BUFSZ];
2106.     mapseen *mseen;
2107. 
2108.     /* look at the player's custom level annotations first */
2109.     if ((mseen = find_mapseen_by_str(nam)) != 0) {
2110.         dlev = mseen->lev;
2111.     } else {
2112.         /* no matching annotation, check whether they used a name we know */
2113. 
2114.         /* allow strings like "the oracle level" to find "oracle" */
2115.         if (!strncmpi(nam, "the ", 4))
2116.             nam += 4;
2117.         if ((p = strstri(nam, " level")) != 0 && p == eos((char *) nam) - 6) {
2118.             nam = strcpy(buf, nam);
2119.             *(eos(buf) - 6) = '\0';
2120.         }
2121.         /* hell is the old name, and wouldn't match; gehennom would match its
2122.            branch, yielding the castle level instead of valley of the dead */
2123.         if (!strcmpi(nam, "gehennom") || !strcmpi(nam, "hell")) {
2124.             if (In_V_tower(&u.uz))
2125.                 nam = " to Vlad's tower"; /* branch to... */
2126.             else
2127.                 nam = "valley";
2128.         } else if (!strcmpi(nam, "delphi")) {
2129.             /* Oracle says "welcome to Delphi" so recognize that name too */
2130.             nam = "oracle";
2131.         }
2132. 
2133.         if ((slev = find_level(nam)) != 0)
2134.             dlev = slev->dlevel;
2135.     }
2136. 
2137.     if (mseen || slev) {
2138.         idx = ledger_no(&dlev);
2139.         if (dlev_in_current_branch(dlev)
2140.             /* either wizard mode or else seen and not forgotten;
2141.                note: used to be '(flags & (FORGOTTEN|VISITED)) == VISITED'
2142.                back when amnesia could cause levels to be forgotten */
2143.             && (wizard || (svl.level_info[idx].flags & VISITED) == VISITED)) {
2144.             lev = depth(&dlev);
2145.         }
2146.     } else { /* not a specific level; try branch names */
2147.         idx = find_branch(nam, (struct proto_dungeon *) 0);
2148.         /* "<branch> to Xyzzy" */
2149.         if (idx < 0 && (p = strstri(nam, " to ")) != 0)
2150.             idx = find_branch(p + 4, (struct proto_dungeon *) 0);
2151. 
2152.         if (idx >= 0) {
2153.             idxtoo = (idx >> 8) & 0x00FF;
2154.             idx &= 0x00FF;
2155.             /* either wizard mode, or else _both_ sides of branch seen; */
2156.             /* (flags & VISITED)==VISITED: see comment about amnesia above */
2157.             if (wizard || (((svl.level_info[idx].flags & VISITED) == VISITED)
2158.                            && ((svl.level_info[idxtoo].flags & VISITED)
2159.                                == VISITED))) {
2160.                 if (ledger_to_dnum(idxtoo) == u.uz.dnum)
2161.                     idx = idxtoo;
2162.                 dlev.dnum = ledger_to_dnum(idx);
2163.                 dlev.dlevel = ledger_to_dlev(idx);
2164.                 if (dlev_in_current_branch(dlev))
2165.                     lev = depth(&dlev);
2166.             }
2167.         }
2168.     }
2169.     return lev;
2170. }
2171. 
2172. #undef dlev_in_current_branch
2173. 
2174. staticfn boolean
2175. unplaced_floater(struct dungeon *dptr)
2176. {
2177.     branch *br;
2178.     int idx = (int) (dptr - svd.dungeons);
2179. 
2180.     /* if other floating branches are added, this will need to change */
2181.     if (idx != knox_level.dnum)
2182.         return FALSE;
2183.     for (br = svb.branches; br; br = br->next)
2184.         if (br->end1.dnum == svn.n_dgns && br->end2.dnum == idx)
2185.             return TRUE;
2186.     return FALSE;
2187. }
2188. 
2189. staticfn boolean
2190. unreachable_level(d_level *lvl_p, boolean unplaced)
2191. {
2192.     s_level *dummy;
2193. 
2194.     if (unplaced)
2195.         return TRUE;
2196.     if (In_endgame(&u.uz) && !In_endgame(lvl_p))
2197.         return TRUE;
2198.     if ((dummy = find_level("dummy")) != 0 && on_level(lvl_p, &dummy->dlevel))
2199.         return TRUE;
2200.     return FALSE;
2201. }
2202. 
2203. staticfn void
2204. tport_menu(
2205.     winid win,
2206.     char *entry,
2207.     struct lchoice *lchoices,
2208.     d_level *lvl_p,
2209.     boolean cannotreach)
2210. {
2211.     char tmpbuf[BUFSZ];
2212.     anything any;
2213.     int clr = NO_COLOR;
2214. 
2215.     lchoices->lev[lchoices->idx] = lvl_p->dlevel;
2216.     lchoices->dgn[lchoices->idx] = lvl_p->dnum;
2217.     lchoices->playerlev[lchoices->idx] = depth(lvl_p);
2218.     any = cg.zeroany;
2219.     if (cannotreach) {
2220.         /* not selectable, but still consumes next menuletter;
2221.            prepend padding in place of missing menu selector */
2222.         Sprintf(tmpbuf, "    %s", entry);
2223.         entry = tmpbuf;
2224.     } else {
2225.         any.a_int = lchoices->idx + 1;
2226.     }
2227.     add_menu(win, &nul_glyphinfo, &any, lchoices->menuletter, 0,
2228.              ATR_NONE, clr, entry, MENU_ITEMFLAGS_NONE);
2229.     /* this assumes there are at most 52 interesting levels */
2230.     if (lchoices->menuletter == 'z')
2231.         lchoices->menuletter = 'A';
2232.     else
2233.         lchoices->menuletter++;
2234.     lchoices->idx++;
2235.     return;
2236. }
2237. 
2238. /* Convert a branch type to a string usable by print_dungeon(). */
2239. staticfn const char *
2240. br_string(int type)
2241. {
2242.     switch (type) {
2243.     case BR_PORTAL:
2244.         return "Portal";
2245.     case BR_NO_END1:
2246.         return "Connection";
2247.     case BR_NO_END2:
2248.         return "One way stair";
2249.     case BR_STAIR:
2250.         return "Stair";
2251.     }
2252.     return " (unknown)";
2253. }
2254. 
2255. staticfn char
2256. chr_u_on_lvl(d_level *dlev)
2257. {
2258.     return u.uz.dnum == dlev->dnum && u.uz.dlevel == dlev->dlevel ? '*' : ' ';
2259. }
2260. 
2261. /* Print all child branches between the lower and upper bounds. */
2262. staticfn void
2263. print_branch(
2264.     winid win,
2265.     int dnum, int lower_bound, int upper_bound,
2266.     boolean bymenu, struct lchoice *lchoices_p)
2267. {
2268.     branch *br;
2269.     char buf[BUFSZ];
2270. 
2271.     /* This assumes that end1 is the "parent". */
2272.     for (br = svb.branches; br; br = br->next) {
2273.         if (br->end1.dnum == dnum && lower_bound < br->end1.dlevel
2274.             && br->end1.dlevel <= upper_bound) {
2275.             Sprintf(buf, "%c %s to %s: %d",
2276.                     bymenu ? chr_u_on_lvl(&br->end1) : ' ',
2277.                     br_string(br->type),
2278.                     svd.dungeons[br->end2.dnum].dname, depth(&br->end1));
2279.             if (bymenu)
2280.                 tport_menu(win, buf, lchoices_p, &br->end1,
2281.                            unreachable_level(&br->end1, FALSE));
2282.             else
2283.                 putstr(win, 0, buf);
2284.         }
2285.     }
2286. }
2287. 
2288. /* Print available dungeon information. */
2289. schar
2290. print_dungeon(boolean bymenu, schar *rlev, xint16 *rdgn)
2291. {
2292.     int i, last_level, nlev;
2293.     char buf[BUFSZ];
2294.     const char *descr;
2295.     boolean first, unplaced;
2296.     s_level *slev;
2297.     dungeon *dptr;
2298.     branch *br;
2299.     struct lchoice lchoices;
2300.     winid win = create_nhwindow(NHW_MENU);
2301. 
2302.     if (bymenu) {
2303.         start_menu(win, MENU_BEHAVE_STANDARD);
2304.         lchoices.idx = 0;
2305.         lchoices.menuletter = 'a';
2306.     }
2307. 
2308.     for (i = 0, dptr = svd.dungeons; i < svn.n_dgns; i++, dptr++) {
2309.         if (bymenu && In_endgame(&u.uz) && i != astral_level.dnum)
2310.             continue;
2311.         unplaced = unplaced_floater(dptr);
2312.         descr = unplaced ? "depth" : "level";
2313.         nlev = dptr->num_dunlevs;
2314.         if (nlev > 1)
2315.             Snprintf(buf, sizeof buf, "%s: %s %d to %d", dptr->dname,
2316.                      makeplural(descr), dptr->depth_start,
2317.                      dptr->depth_start + nlev - 1);
2318.         else
2319.             Snprintf(buf, sizeof buf, "%s: %s %d", dptr->dname,
2320.                      descr, dptr->depth_start);
2321. 
2322.         /* Most entrances are uninteresting. */
2323.         if (dptr->entry_lev != 1) {
2324.             if (dptr->entry_lev == nlev)
2325.                 Strcat(buf, ", entrance from below");
2326.             else
2327.                 Sprintf(eos(buf), ", entrance on %d",
2328.                         dptr->depth_start + dptr->entry_lev - 1);
2329.         }
2330.         if (bymenu) {
2331.             add_menu_heading(win, buf);
2332.         } else
2333.             putstr(win, 0, buf);
2334. 
2335.         /*
2336.          * Circle through the special levels to find levels that are in
2337.          * this dungeon.
2338.          */
2339.         for (slev = svs.sp_levchn, last_level = 0; slev; slev = slev->next) {
2340.             if (slev->dlevel.dnum != i)
2341.                 continue;
2342. 
2343.             /* print any branches before this level */
2344.             print_branch(win, i, last_level, slev->dlevel.dlevel, bymenu,
2345.                          &lchoices);
2346. 
2347.             Sprintf(buf, "%c %s: %d",
2348.                     chr_u_on_lvl(&slev->dlevel),
2349.                     slev->proto, depth(&slev->dlevel));
2350.             if (Is_stronghold(&slev->dlevel))
2351.                 Sprintf(eos(buf), " (tune %s)", svt.tune);
2352.             if (bymenu)
2353.                 tport_menu(win, buf, &lchoices, &slev->dlevel,
2354.                            unreachable_level(&slev->dlevel, unplaced));
2355.             else
2356.                 putstr(win, 0, buf);
2357. 
2358.             last_level = slev->dlevel.dlevel;
2359.         }
2360.         /* print branches after the last special level */
2361.         print_branch(win, i, last_level, MAXLEVEL, bymenu, &lchoices);
2362.     }
2363. 
2364.     if (bymenu) {
2365.         int n;
2366.         menu_item *selected;
2367.         int idx;
2368. 
2369.         end_menu(win, "Level teleport to where:");
2370.         n = select_menu(win, PICK_ONE, &selected);
2371.         destroy_nhwindow(win);
2372.         if (n > 0) {
2373.             idx = selected[0].item.a_int - 1;
2374.             free((genericptr_t) selected);
2375.             if (rlev && rdgn) {
2376.                 *rlev = lchoices.lev[idx];
2377.                 *rdgn = lchoices.dgn[idx];
2378.                 return lchoices.playerlev[idx];
2379.             }
2380.         }
2381.         return 0;
2382.     }
2383. 
2384.     /* Print out floating branches (if any). */
2385.     for (first = TRUE, br = svb.branches; br; br = br->next) {
2386.         if (br->end1.dnum == svn.n_dgns) {
2387.             if (first) {
2388.                 putstr(win, 0, "");
2389.                 putstr(win, 0, "Floating branches");
2390.                 first = FALSE;
2391.             }
2392.             Sprintf(buf, "   %s to %s", br_string(br->type),
2393.                     svd.dungeons[br->end2.dnum].dname);
2394.             putstr(win, 0, buf);
2395.         }
2396.     }
2397. 
2398.     /* I hate searching for the invocation pos while debugging. -dean */
2399.     if (Invocation_lev(&u.uz)) {
2400.         putstr(win, 0, "");
2401.         Sprintf(buf, "Invocation position @ (%d,%d), hero @ (%d,%d)",
2402.                 svi.inv_pos.x, svi.inv_pos.y, u.ux, u.uy);
2403.         putstr(win, 0, buf);
2404.     } else {
2405.         struct trap *trap;
2406. 
2407.         /* if current level has a magic portal, report its location;
2408.            this assumes that there is at most one magic portal on any
2409.            given level; quest and ft.ludios have pairs (one in main
2410.            dungeon matched with one in the corresponding branch), the
2411.            elemental planes have singletons (connection to next plane) */
2412.         *buf = '\0';
2413.         for (trap = gf.ftrap; trap; trap = trap->ntrap)
2414.             if (trap->ttyp == MAGIC_PORTAL)
2415.                 break;
2416. 
2417.         if (trap)
2418.             Sprintf(buf, "Portal @ (%d,%d), hero @ (%d,%d)",
2419.                     trap->tx, trap->ty, u.ux, u.uy);
2420. 
2421.         /* only report "no portal found" when actually expecting a portal */
2422.         else if (Is_earthlevel(&u.uz) || Is_waterlevel(&u.uz)
2423.                  || Is_firelevel(&u.uz) || Is_airlevel(&u.uz)
2424.                  || Is_qstart(&u.uz) || at_dgn_entrance("The Quest")
2425.                  || Is_knox(&u.uz))
2426.             Strcpy(buf, "No portal found.");
2427. 
2428.         /* only give output if we found a portal or expected one and didn't */
2429.         if (*buf) {
2430.             putstr(win, 0, "");
2431.             putstr(win, 0, buf);
2432.         }
2433.     }
2434. 
2435.     display_nhwindow(win, TRUE);
2436.     destroy_nhwindow(win);
2437.     return 0;
2438. }
2439. 
2440. /* Record that the player knows about a branch from a level. This function
2441.  * will determine whether or not it was a "real" branch that was taken.
2442.  * This function should not be called for a transition done via level
2443.  * teleport or via the Eye.
2444.  */
2445. void
2446. recbranch_mapseen(d_level *source, d_level *dest)
2447. {
2448.     mapseen *mptr;
2449.     branch *br;
2450. 
2451.     /* not a branch */
2452.     if (source->dnum == dest->dnum)
2453.         return;
2454. 
2455.     /* we only care about forward branches */
2456.     for (br = svb.branches; br; br = br->next) {
2457.         if (on_level(source, &br->end1) && on_level(dest, &br->end2))
2458.             break;
2459.         if (on_level(source, &br->end2) && on_level(dest, &br->end1))
2460.             return;
2461.     }
2462. 
2463.     /* branch not found, so not a real branch. */
2464.     if (!br)
2465.         return;
2466. 
2467.     if ((mptr = find_mapseen(source)) != 0) {
2468.         if (mptr->br && br != mptr->br)
2469.             impossible("Two branches on the same level?");
2470.         mptr->br = br;
2471.     } else {
2472.         impossible("Can't note branch for unseen level (%d, %d)",
2473.                    source->dnum, source->dlevel);
2474.     }
2475. }
2476. 
2477. staticfn char *
2478. get_annotation(d_level *lev)
2479. {
2480.     mapseen *mptr;
2481. 
2482.     if ((mptr = find_mapseen(lev)))
2483.         return mptr->custom;
2484.     return NULL;
2485. }
2486. 
2487. /* print the annotation for the current level, if it exists */
2488. void
2489. print_level_annotation(void)
2490. {
2491.     const char *annotation;
2492. 
2493.     if ((annotation = get_annotation(&u.uz)) != 0)
2494.         You("remember this level as %s.", annotation);
2495. }
2496. 
2497. /* ask user to annotate level lev.
2498.    if lev is NULL, uses current level. */
2499. staticfn void
2500. query_annotation(d_level *lev)
2501. {
2502.     mapseen *mptr;
2503.     char nbuf[BUFSZ]; /* Buffer for response */
2504. 
2505.     if (!(mptr = find_mapseen(lev ? lev : &u.uz)))
2506.         return;
2507. 
2508.     nbuf[0] = '\0';
2509. #ifdef EDIT_GETLIN
2510.     if (mptr->custom) {
2511.         (void) strncpy(nbuf, mptr->custom, BUFSZ);
2512.         nbuf[BUFSZ - 1] = '\0';
2513.     }
2514. #else
2515.     if (mptr->custom) {
2516.         char tmpbuf[BUFSZ];
2517. 
2518.         Sprintf(tmpbuf, "Replace annotation \"%.30s%s\" with?", mptr->custom,
2519.                 (strlen(mptr->custom) > 30) ? "..." : "");
2520.         getlin(tmpbuf, nbuf);
2521.     } else
2522. #endif
2523.     {
2524.         char qbuf[QBUFSZ], lbuf[QBUFSZ]; /* level description */
2525. 
2526.         if (!lev || on_level(&u.uz, lev)) {
2527.             Strcpy(lbuf, "this dungeon level");
2528.         } else {
2529.             int dflgs = (lev->dnum == u.uz.dnum) ? 0 : 2;
2530.             d_level save_uz = u.uz;
2531. 
2532.             u.uz = *lev;
2533.             (void) describe_level(lbuf, dflgs);
2534.             u.uz = save_uz;
2535. 
2536.             (void) strsubst(lbuf, "Dlvl:", "level ");
2537.             /* even though we've told describe_level() not to append
2538.                a trailing space (by not including '1' in dflgs), the
2539.                level number is formatted with %-2d so single digit
2540.                values will end up with one anyway; remove it */
2541.             (void) trimspaces(lbuf);
2542.         }
2543.         Snprintf(qbuf, sizeof qbuf, "What do you want to call %s?", lbuf);
2544.         getlin(qbuf, nbuf);
2545.     }
2546. 
2547.     /* empty input or ESC means don't add or change annotation;
2548.        space-only means discard current annotation without adding new one */
2549.     if (!*nbuf || *nbuf == '\033')
2550.         return;
2551.     /* strip leading and trailing spaces, compress out consecutive spaces */
2552.     (void) mungspaces(nbuf);
2553. 
2554.     /* discard old annotation, if any */
2555.     if (mptr->custom) {
2556.         free((genericptr_t) mptr->custom);
2557.         mptr->custom = (char *) 0;
2558.         mptr->custom_lth = 0;
2559.     }
2560.     /* add new annotation, unless it's all spaces (which will be an
2561.        empty string after mungspaces() above) */
2562.     if (*nbuf && strcmp(nbuf, " ")) {
2563.         mptr->custom = dupstr(nbuf);
2564.         /* _lth field does not include trailing '\0' in the count */
2565.         mptr->custom_lth = (unsigned) strlen(mptr->custom);
2566.     }
2567. }
2568. 
2569. /* #annotate command - add a custom name to the current level */
2570. int
2571. donamelevel(void)
2572. {
2573.     if (iflags.menu_requested)
2574.         return dooverview();
2575.     query_annotation((d_level *) 0);
2576.     return ECMD_OK;
2577. }
2578. #endif /* !SFCTOOL */
2579. 
2580. /* exclusion zones */
2581. void
2582. free_exclusions(void)
2583. {
2584.     struct exclusion_zone *ez = sve.exclusion_zones;
2585. 
2586.     while (ez) {
2587.         struct exclusion_zone *nxtez = ez->next;
2588. 
2589.         free(ez);
2590.         ez = nxtez;
2591.     }
2592.     sve.exclusion_zones = (struct exclusion_zone *) 0;
2593. }
2594. 
2595. void
2596. save_exclusions(NHFILE *nhfp)
2597. {
2598.     struct exclusion_zone *ez;
2599.     int nez;
2600. 
2601.     for (nez = 0, ez = sve.exclusion_zones; ez; ez = ez->next, ++nez)
2602.         ;
2603. 
2604.     if (update_file(nhfp)) {
2605.         Sfo_int(nhfp, &nez, "exclusion_count");
2606.         for (ez = sve.exclusion_zones; ez; ez = ez->next) {
2607.             Sfo_xint16(nhfp, &ez->zonetype, "exclusion-zonetype");
2608.             Sfo_coordxy(nhfp, &ez->lx, "exclusion-lx");
2609.             Sfo_coordxy(nhfp, &ez->ly, "exclusion-ly");
2610.             Sfo_coordxy(nhfp, &ez->hx, "exclusion-hx");
2611.             Sfo_coordxy(nhfp, &ez->hy, "exclusion-hy");
2612.         }
2613.     }
2614. }
2615. 
2616. void
2617. load_exclusions(NHFILE *nhfp)
2618. {
2619.     struct exclusion_zone *ez;
2620.     int nez = 0;
2621. 
2622.     Sfi_int(nhfp, &nez, "exclusion_count");
2623. 
2624.     while (nez-- > 0) {
2625.         ez = (struct exclusion_zone *) alloc(sizeof *ez);
2626.         Sfi_xint16(nhfp, &ez->zonetype, "exclusion-zonetype");
2627.         Sfi_coordxy(nhfp, &ez->lx, "exclusion-lx");
2628.         Sfi_coordxy(nhfp, &ez->ly, "exclusion-ly");
2629.         Sfi_coordxy(nhfp, &ez->hx, "exclusion-hx");
2630.         Sfi_coordxy(nhfp, &ez->hy, "exclusion-hy");
2631.         ez->next = sve.exclusion_zones;
2632.         sve.exclusion_zones = ez;
2633.     }
2634. }
2635. 
2636. #ifndef SFCTOOL
2637. 
2638. /* find the particular mapseen object in the chain; may return null */
2639. staticfn mapseen *
2640. find_mapseen(d_level *lev)
2641. {
2642.     mapseen *mptr;
2643. 
2644.     for (mptr = svm.mapseenchn; mptr; mptr = mptr->next)
2645.         if (on_level(&(mptr->lev), lev))
2646.             break;
2647. 
2648.     return mptr;
2649. }
2650. 
2651. staticfn mapseen *
2652. find_mapseen_by_str(const char *s)
2653. {
2654.     mapseen *mptr;
2655. 
2656.     for (mptr = svm.mapseenchn; mptr; mptr = mptr->next)
2657.         if (mptr->custom && !strcmpi(s, mptr->custom))
2658.             break;
2659. 
2660.     return mptr;
2661. }
2662. 
2663. 
2664. void
2665. rm_mapseen(int ledger_num)
2666. {
2667.     mapseen *mptr, *mprev = (mapseen *) 0;
2668.     struct cemetery *bp, *bpnext;
2669. 
2670.     for (mptr = svm.mapseenchn; mptr; mprev = mptr, mptr = mptr->next)
2671.         if (svd.dungeons[mptr->lev.dnum].ledger_start + mptr->lev.dlevel
2672.             == ledger_num)
2673.             break;
2674.     if (!mptr)
2675.         return;
2676. 
2677.     if (mptr->custom)
2678.         free((genericptr_t) mptr->custom), mptr->custom = (char *) NULL;
2679. 
2680.     bpnext = mptr->final_resting_place;
2681.     while ((bp = bpnext) != NULL) {
2682.         bpnext = bp->next;
2683.         free((genericptr_t) bp);
2684.     }
2685. 
2686.     if (mprev) {
2687.         mprev->next = mptr->next;
2688.     } else {
2689.         svm.mapseenchn = mptr->next;
2690.     }
2691.     free(mptr);
2692. }
2693. 
2694. staticfn void
2695. save_mapseen(NHFILE *nhfp, mapseen *mptr)
2696. {
2697.     branch *curr;
2698.     int i, brindx;
2699. 
2700.     for (brindx = 0, curr = svb.branches; curr; curr = curr->next, ++brindx)
2701.         if (curr == mptr->br)
2702.             break;
2703.     Sfo_int(nhfp, &brindx, "mapseen-branch_index");
2704.     Sfo_d_level(nhfp, &mptr->lev, "mapseen-d_level");
2705.     Sfo_mapseen_feat(nhfp, &mptr->feat, "mapseen-feat");
2706.     Sfo_mapseen_flags(nhfp, &mptr->flags, "mapseen-flags");
2707.     Sfo_unsigned(nhfp, &mptr->custom_lth, "mapseen-custom_lth");
2708. 
2709.     if (mptr->custom_lth) {
2710.         Sfo_char(nhfp, mptr->custom, "mapseen-custom",
2711.                  (int) mptr->custom_lth);
2712.     }
2713.     for (i = 0; i < ((MAXNROFROOMS + 1) * 2); ++i) {
2714.         Sfo_mapseen_rooms(nhfp, &mptr->msrooms[i], "mapseen-msrooms");
2715.     }
2716.     savecemetery(nhfp, &mptr->final_resting_place);
2717. }
2718. #endif /* !SFCTOOL */
2719. 
2720. staticfn mapseen *
2721. load_mapseen(NHFILE *nhfp)
2722. {
2723.     int i, branchnum = 0, brindx;
2724.     mapseen *load;
2725.     branch *curr;
2726. 
2727.     load = (mapseen *) alloc(sizeof *load);
2728. 
2729.     Sfi_int(nhfp, &branchnum, "mapseen-branch_index");
2730.     for (brindx = 0, curr = svb.branches; curr; curr = curr->next, ++brindx)
2731.         if (brindx == branchnum)
2732.             break;
2733.     load->br = curr;
2734. 
2735.     Sfi_d_level(nhfp, &load->lev, "mapseen-d_level");
2736.     Sfi_mapseen_feat(nhfp, &load->feat, "mapseen-feat");
2737.     Sfi_mapseen_flags(nhfp, &load->flags, "mapseen-flags");
2738.     Sfi_unsigned(nhfp, &load->custom_lth, "mapseen-custom_lth");
2739. 
2740.     if (load->custom_lth) {
2741.         /* length doesn't include terminator (which isn't saved & restored) */
2742.         load->custom = (char *) alloc(load->custom_lth + 1);
2743.         Sfi_char(nhfp, load->custom, "mapseen-custom",
2744.                  (int) load->custom_lth);
2745.         load->custom[load->custom_lth] = '\0';
2746.     } else {
2747.         load->custom = 0;
2748.     }
2749.     for (i = 0; i < ((MAXNROFROOMS + 1) * 2); ++i) {
2750.         Sfi_mapseen_rooms(nhfp, &load->msrooms[i], "mapseen-msrooms");
2751.     }
2752.     restcemetery(nhfp, &load->final_resting_place);
2753.     return load;
2754. }
2755. #ifndef SFCTOOL
2756. 
2757. DISABLE_WARNING_FORMAT_NONLITERAL
2758. 
2759. /* for '#stats' wizard-mode command, to show memory used for #overview data */
2760. void
2761. overview_stats(
2762.     winid win, /* output window */
2763.     const char *statsfmt, /* format */
2764.     long *total_count, long *total_size) /* args for the format */
2765. {
2766.     char buf[BUFSZ], hdrbuf[QBUFSZ];
2767.     long ocount, osize, bcount, bsize, acount, asize;
2768.     struct cemetery *ce;
2769.     mapseen *mptr;
2770. 
2771.     ocount = bcount = acount = osize = bsize = asize = 0L;
2772.     for (mptr = svm.mapseenchn; mptr; mptr = mptr->next) {
2773.         ++ocount;
2774.         osize += (long) sizeof *mptr;
2775.         for (ce = mptr->final_resting_place; ce; ce = ce->next) {
2776.             ++bcount;
2777.             bsize += (long) sizeof *ce;
2778.         }
2779.         if (mptr->custom_lth) {
2780.             ++acount;
2781.             asize += (long) (mptr->custom_lth + 1);
2782.         }
2783.     }
2784. 
2785.     Sprintf(hdrbuf, "general, size %ld", (long) sizeof (mapseen));
2786.     Sprintf(buf, statsfmt, hdrbuf, ocount, osize);
2787.     putstr(win, 0, buf);
2788.     if (bcount) {
2789.         Sprintf(hdrbuf, "cemetery, size %ld",
2790.                 (long) sizeof (struct cemetery));
2791.         Sprintf(buf, statsfmt, hdrbuf, bcount, bsize);
2792.         putstr(win, 0, buf);
2793.     }
2794.     if (acount) {
2795.         Sprintf(hdrbuf, "annotations, text");
2796.         Sprintf(buf, statsfmt, hdrbuf, acount, asize);
2797.         putstr(win, 0, buf);
2798.     }
2799.     *total_count += ocount + bcount + acount;
2800.     *total_size += osize + bsize + asize;
2801. }
2802. 
2803. RESTORE_WARNING_FORMAT_NONLITERAL
2804. 
2805. /* Remove all mapseen objects for a particular dnum.
2806.  * Useful during quest expulsion to remove quest levels.
2807.  * [No longer deleted, just marked as notreachable.  #overview will
2808.  * ignore such levels, end of game disclosure will include them.]
2809.  */
2810. void
2811. remdun_mapseen(int dnum)
2812. {
2813.     mapseen *mptr, **mptraddr;
2814. 
2815.     mptraddr = &svm.mapseenchn;
2816.     while ((mptr = *mptraddr) != 0) {
2817.         if (mptr->lev.dnum == dnum) {
2818. #if 1 /* use this... */
2819.             mptr->flags.notreachable = 1;
2820.         }
2821. #else /* old deletion code */
2822.             *mptraddr = mptr->next;
2823.             if (mptr->custom)
2824.                 free((genericptr_t) mptr->custom);
2825.             if (mptr->final_resting_place)
2826.                 savecemetery(-1, FREE_SAVE, &mptr->final_resting_place);
2827.             free((genericptr_t) mptr);
2828.         } else
2829. #endif
2830.         mptraddr = &mptr->next;
2831.     }
2832. }
2833. 
2834. void
2835. init_mapseen(d_level *lev)
2836. {
2837.     /* Create a level and insert in "sorted" order.  This is an insertion
2838.      * sort first by dungeon (in order of discovery) and then by level number.
2839.      */
2840.     mapseen *mptr, *init, *prev;
2841. 
2842.     init = (mapseen *) alloc(sizeof *init);
2843.     (void) memset((genericptr_t) init, 0, sizeof *init);
2844.     /* memset is fine for feature bits, flags, and rooms array;
2845.        explicitly initialize pointers to null */
2846.     init->next = 0, init->br = 0, init->custom = 0;
2847.     init->final_resting_place = 0;
2848.     /* svl.lastseentyp[][] is reused for each level, so get rid of
2849.        previous level's data */
2850.     (void) memset((genericptr_t) svl.lastseentyp, 0, sizeof svl.lastseentyp);
2851. 
2852.     init->lev.dnum = lev->dnum;
2853.     init->lev.dlevel = lev->dlevel;
2854. 
2855.     /* walk until we get to the place where we should insert init */
2856.     for (mptr = svm.mapseenchn, prev = 0; mptr;
2857.          prev = mptr, mptr = mptr->next) {
2858.         if (mptr->lev.dnum > init->lev.dnum
2859.             || (mptr->lev.dnum == init->lev.dnum
2860.                 && mptr->lev.dlevel > init->lev.dlevel))
2861.             break;
2862.     }
2863.     if (!prev) {
2864.         init->next = svm.mapseenchn;
2865.         svm.mapseenchn = init;
2866.     } else {
2867.         mptr = prev->next;
2868.         prev->next = init;
2869.         init->next = mptr;
2870.     }
2871. }
2872. 
2873. #define OF_INTEREST(feat) \
2874.     ((feat).nfount || (feat).nsink || (feat).nthrone || (feat).naltar   \
2875.      || (feat).ngrave || (feat).ntree || (feat).nshop || (feat).ntemple)
2876.   /* || (feat).water || (feat).ice || (feat).lava */
2877. 
2878. /* returns true if this level has something interesting to print out */
2879. staticfn boolean
2880. interest_mapseen(mapseen *mptr)
2881. {
2882.     if (on_level(&u.uz, &mptr->lev))
2883.         return TRUE;
2884.     if (mptr->flags.notreachable || mptr->flags.forgot)
2885.         return FALSE;
2886.     /* when in tutorial, show all tutorial levels visited whether interesting
2887.        or not and don't show any other levels; when outside tutorial, don't
2888.        show any tutorial levels even if they're considered interesting */
2889.     if (In_tutorial(&u.uz)) {
2890.         return In_tutorial(&mptr->lev);
2891.     } else {
2892.         if (In_tutorial(&mptr->lev))
2893.             return FALSE;
2894.     }
2895.     /* level is of interest if it has an auto-generated annotation */
2896.     if (mptr->flags.oracle || mptr->flags.bigroom || mptr->flags.roguelevel
2897.         || mptr->flags.castle || mptr->flags.valley
2898.         || mptr->flags.msanctum || mptr->flags.vibrating_square
2899.         || mptr->flags.quest_summons || mptr->flags.questing)
2900.         return TRUE;
2901.     /* when in Sokoban, list all sokoban levels visited; when not in it,
2902.        list any visited Sokoban level which remains unsolved (will usually
2903.        only be furthest one reached, but it's possible to enter pits and
2904.        climb out on the far side on the first Sokoban level; also, wizard
2905.        mode overrides teleport restrictions) */
2906.     if (In_sokoban(&mptr->lev)
2907.         && (In_sokoban(&u.uz) || !mptr->flags.sokosolved))
2908.         return TRUE;
2909.     /* when in the endgame, list all endgame levels visited, whether they
2910.        have annotations or not, so that #overview doesn't become extremely
2911.        sparse once the rest of the dungeon has been flagged as notreachable */
2912.     if (In_endgame(&u.uz))
2913.         return (boolean) In_endgame(&mptr->lev);
2914.     /* level is of interest if it has non-zero feature count or known bones
2915.        or user annotation or known connection to another dungeon branch
2916.        or is the furthest level reached in its branch */
2917.     return (boolean) (OF_INTEREST(mptr->feat)
2918.                       || (mptr->final_resting_place
2919.                           && (mptr->flags.knownbones || wizard))
2920.                       || mptr->custom || mptr->br
2921.                       || (mptr->lev.dlevel
2922.                           == svd.dungeons[mptr->lev.dnum].dunlev_ureached));
2923. }
2924. 
2925. /* update the lastseentyp at x,y */
2926. void
2927. update_lastseentyp(coordxy x, coordxy y)
2928. {
2929.     struct monst *mtmp;
2930.     int ltyp = levl[x][y].typ;
2931. 
2932.     if (ltyp == DRAWBRIDGE_UP)
2933.         ltyp = db_under_typ(levl[x][y].drawbridgemask);
2934.     if ((mtmp = m_at(x, y)) != 0
2935.         && M_AP_TYPE(mtmp) == M_AP_FURNITURE && canseemon(mtmp))
2936.         ltyp = cmap_to_type(mtmp->mappearance);
2937.     svl.lastseentyp[x][y] = ltyp;
2938. }
2939. 
2940. /* for some cases where deferred update needs to be done immediately;
2941.    hide details from caller */
2942. int
2943. update_mapseen_for(coordxy x, coordxy y)
2944. {
2945.     recalc_mapseen(); /* whole level */
2946.     return svl.lastseentyp[x][y];
2947. }
2948. 
2949. /* count mapseen feature from lastseentyp at x,y */
2950. staticfn void
2951. count_feat_lastseentyp(
2952.     mapseen *mptr, /* remembered data for a level; update feat.X counts */
2953.     coordxy x, coordxy y)
2954. {
2955.     int count;
2956.     unsigned atmp;
2957. 
2958.     switch (svl.lastseentyp[x][y]) {
2959. #if 0   /* levels that have these tend of have a lot of them */
2960.     /*
2961.      * FIXME?  due to theme rooms, lots of levels have an increased
2962.      * chance of having these so automatic annotations for them may
2963.      * have become more worthwhile now.
2964.      */
2965.     case ICE:
2966.         count = mptr->feat.ice + 1;
2967.         if (count <= 3)
2968.             mptr->feat.ice = count;
2969.         break;
2970.     case POOL:
2971.     case MOAT:
2972.     case WATER:
2973.         count = mptr->feat.water + 1;
2974.         if (count <= 3)
2975.             mptr->feat.water = count;
2976.         break;
2977.     case LAVAPOOL:
2978.     case LAVAWALL:
2979.         count = mptr->feat.lava + 1;
2980.         if (count <= 3)
2981.             mptr->feat.lava = count;
2982.         break;
2983. #endif
2984.     case TREE:
2985.         count = mptr->feat.ntree + 1;
2986.         if (count <= 3)
2987.             mptr->feat.ntree = count;
2988.         break;
2989.     case FOUNTAIN:
2990.         count = mptr->feat.nfount + 1;
2991.         if (count <= 3)
2992.             mptr->feat.nfount = count;
2993.         break;
2994.     case THRONE:
2995.         count = mptr->feat.nthrone + 1;
2996.         if (count <= 3)
2997.             mptr->feat.nthrone = count;
2998.         break;
2999.     case SINK:
3000.         count = mptr->feat.nsink + 1;
3001.         if (count <= 3)
3002.             mptr->feat.nsink = count;
3003.         break;
3004.     case GRAVE:
3005.         count = mptr->feat.ngrave + 1;
3006.         if (count <= 3)
3007.             mptr->feat.ngrave = count;
3008.         break;
3009.     case ALTAR:
3010.         /* get the altarmask for this location; might be a mimic */
3011.         atmp = altarmask_at(x, y);
3012.         /* convert to index: 0..3 */
3013.         atmp = (Is_astralevel(&u.uz) && (levl[x][y].seenv & SVALL) != SVALL)
3014.                ? MSA_NONE
3015.                : Amask2msa(atmp);
3016.         if (!mptr->feat.naltar)
3017.             mptr->feat.msalign = atmp;
3018.         else if (mptr->feat.msalign != atmp)
3019.             mptr->feat.msalign = MSA_NONE;
3020.         count = mptr->feat.naltar + 1;
3021.         if (count <= 3)
3022.             mptr->feat.naltar = count;
3023.         break;
3024.         /*  An automatic annotation is added to the Castle and
3025.          *  to Fort Ludios once their structure's main entrance
3026.          *  has been seen (in person or via magic mapping).
3027.          *  For the Fort, that entrance is just a secret door
3028.          *  which will be converted into a regular one when
3029.          *  located (or destroyed).
3030.          * DOOR: possibly a lowered drawbridge's open portcullis;
3031.          * DBWALL: a raised drawbridge's "closed door";
3032.          * DRAWBRIDGE_DOWN: the span provided by lowered bridge,
3033.          *  with moat or other terrain hidden underneath;
3034.          * DRAWBRIDGE_UP: moat in front of a raised drawbridge,
3035.          *  not recognizable as a bridge location unless/until
3036.          *  the adjacent DBWALL has been seen.
3037.          */
3038.     case DOOR:
3039.         if (Is_knox(&u.uz)) {
3040.             int ty, tx = x - 4;
3041. 
3042.             /* Throne is four columns to left, either directly in
3043.              * line or one row higher or lower, and doesn't have
3044.              * to have been seen yet.
3045.              *   ......|}}}.
3046.              *   ..\...S}...
3047.              *   ..\...S}...
3048.              *   ......|}}}.
3049.              * For 3.6.0 and earlier, it was always in direct line:
3050.              * both throne and door on the lower of the two rows.
3051.              */
3052.             for (ty = y - 1; ty <= y + 1; ++ty)
3053.                 if (isok(tx, ty) && IS_THRONE(levl[tx][ty].typ)) {
3054.                     mptr->flags.ludios = 1;
3055.                     break;
3056.                 }
3057.             break;
3058.         }
3059.         if (is_drawbridge_wall(x, y) < 0)
3060.             break;
3061.         FALLTHROUGH;
3062.         /*FALLTHRU*/
3063.     case DBWALL:
3064.     case DRAWBRIDGE_DOWN:
3065.         if (Is_stronghold(&u.uz))
3066.             mptr->flags.castle = 1, mptr->flags.castletune = 1;
3067.         break;
3068.     default:
3069.         break;
3070.     }
3071. }
3072. 
3073. /* recalculate mapseen for the current level */
3074. void
3075. recalc_mapseen(void)
3076. {
3077.     mapseen *mptr, *oth_mptr;
3078.     struct monst *mtmp;
3079.     struct cemetery *bp, **bonesaddr;
3080.     struct trap *t;
3081.     unsigned i, ridx;
3082.     int count;
3083.     coordxy x, y;
3084.     char uroom;
3085. 
3086.     /* Should not happen in general, but possible if in the process
3087.      * of being booted from the quest.  The mapseen object gets
3088.      * removed during the expulsion but prior to leaving the level
3089.      * [Since quest expulsion no longer deletes quest mapseen data,
3090.      * null return from find_mapseen() should now be impossible.]
3091.      */
3092.     if (!(mptr = find_mapseen(&u.uz)))
3093.         return;
3094. 
3095.     /* reset all features; mptr->feat.* = 0; */
3096.     (void) memset((genericptr_t) &mptr->feat, 0, sizeof mptr->feat);
3097.     /* reset most flags; some level-specific ones are left as-is */
3098.     if (mptr->flags.notreachable) {
3099.         mptr->flags.notreachable = 0; /* reached it; Eye of the Aethiopica? */
3100.         if (In_quest(&u.uz)) {
3101.             mapseen *mptrtmp = svm.mapseenchn;
3102. 
3103.             /* when quest was notreachable due to ejection and portal removal,
3104.                getting back to it via arti-invoke should revive annotation
3105.                data for all quest levels, not just the one we're on now */
3106.             do {
3107.                 if (mptrtmp->lev.dnum == mptr->lev.dnum)
3108.                     mptrtmp->flags.notreachable = 0;
3109.                 mptrtmp = mptrtmp->next;
3110.             } while (mptrtmp);
3111.         }
3112.     }
3113.     mptr->flags.knownbones = 0;
3114.     mptr->flags.sokosolved = In_sokoban(&u.uz) && !Sokoban;
3115.     /* mptr->flags.bigroom retains previous value when hero can't see */
3116.     if (!Blind)
3117.         mptr->flags.bigroom = Is_bigroom(&u.uz);
3118.     else if (mptr->flags.forgot)
3119.         mptr->flags.bigroom = 0;
3120.     mptr->flags.roguelevel = Is_rogue_level(&u.uz);
3121.     mptr->flags.oracle = 0; /* recalculated during room traversal below */
3122.     mptr->flags.castletune = 0;
3123.     /* flags.castle retains previous value */
3124.     mptr->flags.forgot = 0;
3125.     /* flags.quest_summons disabled once quest finished */
3126.     mptr->flags.quest_summons = (at_dgn_entrance("The Quest")
3127.                                  && u.uevent.qcalled
3128.                                  && !(u.uevent.qcompleted
3129.                                       || u.uevent.qexpelled
3130.                                       || svq.quest_status.leader_is_dead));
3131.     mptr->flags.questing = (on_level(&u.uz, &qstart_level)
3132.                             && svq.quest_status.got_quest);
3133.     /* flags.msanctum, .valley, and .vibrating_square handled below */
3134. 
3135.     /* track rooms the hero is in */
3136.     for (i = 0; (uroom = u.urooms[i]) != '\0'; ++i) {
3137.         ridx = (unsigned) uroom - ROOMOFFSET;
3138.         mptr->msrooms[ridx].seen = 1;
3139.         mptr->msrooms[ridx].untended =
3140.             (svr.rooms[ridx].rtype >= SHOPBASE)
3141.                 ? (!(mtmp = shop_keeper(uroom)) || !inhishop(mtmp))
3142.                 : (svr.rooms[ridx].rtype == TEMPLE)
3143.                       ? (!(mtmp = findpriest(uroom)) || !inhistemple(mtmp))
3144.                       : 0;
3145.     }
3146. 
3147.     /* recalculate room knowledge: for now, just shops and temples
3148.      * this could be extended to an array of 0..SHOPBASE
3149.      */
3150.     for (i = 0; i < SIZE(mptr->msrooms); ++i) {
3151.         if (mptr->msrooms[i].seen) {
3152.             if (svr.rooms[i].rtype >= SHOPBASE) {
3153.                 if (mptr->msrooms[i].untended)
3154.                     mptr->feat.shoptype = SHOPBASE - 1;
3155.                 else if (!mptr->feat.nshop)
3156.                     mptr->feat.shoptype = svr.rooms[i].rtype;
3157.                 else if (mptr->feat.shoptype != (unsigned) svr.rooms[i].rtype)
3158.                     mptr->feat.shoptype = 0;
3159.                 count = mptr->feat.nshop + 1;
3160.                 if (count <= 3)
3161.                     mptr->feat.nshop = count;
3162.             } else if (svr.rooms[i].rtype == TEMPLE) {
3163.                 /* altar and temple alignment handled below */
3164.                 count = mptr->feat.ntemple + 1;
3165.                 if (count <= 3)
3166.                     mptr->feat.ntemple = count;
3167.             } else if (svr.rooms[i].orig_rtype == DELPHI) {
3168.                 mptr->flags.oracle = 1;
3169.             }
3170.         }
3171.     }
3172. 
3173.     /* Update svl.lastseentyp with typ if and only if it is in sight or the
3174.      * hero can feel it on their current location (i.e. not levitating).
3175.      * This *should* give the "last known typ" for each dungeon location.
3176.      * (At the very least, it's a better assumption than determining what
3177.      * the player knows from the glyph and the typ (which is isn't quite
3178.      * enough information in some cases)).
3179.      *
3180.      * It was reluctantly added to struct rm to track.  Alternatively
3181.      * we could track "features" and then update them all here, and keep
3182.      * track of when new features are created or destroyed, but this
3183.      * seemed the most elegant, despite adding more data to struct rm.
3184.      * [3.6.0: we're using svl.lastseentyp[][] rather than level.locations
3185.      * to track the features seen.]
3186.      *
3187.      * Although no current windowing systems (can) do this, this would add
3188.      * the ability to have non-dungeon glyphs float above the last known
3189.      * dungeon glyph (i.e. items on fountains).
3190.      */
3191.     if (!Levitation)
3192.         update_lastseentyp(u.ux, u.uy);
3193. 
3194.     for (x = 1; x < COLNO; x++) {
3195.         for (y = 0; y < ROWNO; y++) {
3196.             count_feat_lastseentyp(mptr, x, y);
3197.         }
3198.     }
3199. 
3200.     /* Moloch's Sanctum and the Valley of the Dead are normally given an
3201.        automatic annotation when you enter a temple attended by a priest,
3202.        but it is possible for the priest to be killed prior to that; we
3203.        assume that both of those levels only contain one altar, so add the
3204.        annotation if that altar has been mapped (seen or magic mapping) */
3205.     if (Is_valley(&u.uz)) {
3206.         /* don't clear valley if naltar==0; maybe altar got destroyed? */
3207.         if (mptr->feat.naltar > 0)
3208.             mptr->flags.valley = 1;
3209. 
3210.     /* Sanctum and Gateway-to-Sanctum are mutually exclusive automatic
3211.        annotations but handling that is tricky because they're stored
3212.        with data for different levels */
3213.     } else if (Is_sanctum(&u.uz)) {
3214.         if (mptr->feat.naltar > 0)
3215.             mptr->flags.msanctum = 1;
3216. 
3217.         if (mptr->flags.msanctum) {
3218.             d_level invocat_lvl;
3219. 
3220.             invocat_lvl = u.uz;
3221.             invocat_lvl.dlevel -= 1;
3222.             if ((oth_mptr = find_mapseen(&invocat_lvl)) != 0)
3223.                 oth_mptr->flags.vibrating_square = 0;
3224.         }
3225.     } else if (Invocation_lev(&u.uz)) {
3226.         /* annotate vibrating square's level if vibr_sqr 'trap' has been
3227.            found or if that trap is gone (indicating that invocation has
3228.            happened) provided that the sanctum's annotation hasn't been
3229.            added (either hero hasn't descended to that level yet or hasn't
3230.            mapped its temple) */
3231.         for (t = gf.ftrap; t; t = t->ntrap)
3232.             if (t->ttyp == VIBRATING_SQUARE)
3233.                 break;
3234.         mptr->flags.vibrating_square = t ? t->tseen
3235.                       /* no trap implies that invocation has been performed */
3236.                              : ((oth_mptr = find_mapseen(&sanctum_level)) == 0
3237.                                 || !oth_mptr->flags.msanctum);
3238.     }
3239. 
3240.     if (svl.level.bonesinfo && !mptr->final_resting_place) {
3241.         /* clone the bonesinfo so we aren't dependent upon this
3242.            level being in memory */
3243.         bonesaddr = &mptr->final_resting_place;
3244.         bp = svl.level.bonesinfo;
3245.         do {
3246.             *bonesaddr = (struct cemetery *) alloc(sizeof **bonesaddr);
3247.             **bonesaddr = *bp;
3248.             bp = bp->next;
3249.             bonesaddr = &(*bonesaddr)->next;
3250.         } while (bp);
3251.         *bonesaddr = 0;
3252.     }
3253.     /* decide which past hero deaths have become known; there's no
3254.        guarantee of either a grave or a ghost, so we go by whether the
3255.        current hero has seen the map location where each old one died */
3256.     for (bp = mptr->final_resting_place; bp; bp = bp->next)
3257.         if (svl.lastseentyp[bp->frpx][bp->frpy]) {
3258.             bp->bonesknown = TRUE;
3259.             mptr->flags.knownbones = 1;
3260.         }
3261. }
3262. 
3263. /*ARGUSED*/
3264. /* valley and sanctum levels get automatic annotation once their temple
3265.    is entered */
3266. void
3267. mapseen_temple(
3268.     struct monst *priest UNUSED) /* not used; might be useful someday */
3269. {
3270.     mapseen *mptr = find_mapseen(&u.uz);
3271. 
3272.     if (!mptr)
3273.         return;
3274.     if (Is_valley(&u.uz))
3275.         mptr->flags.valley = 1;
3276.     else if (Is_sanctum(&u.uz))
3277.         mptr->flags.msanctum = 1;
3278. }
3279. 
3280. /* room entry message has just been delivered so learn room even if blind */
3281. void
3282. room_discovered(int roomno)
3283. {
3284.     mapseen *mptr = find_mapseen(&u.uz);
3285. 
3286.     if (mptr && !mptr->msrooms[roomno].seen) {
3287.         mptr->msrooms[roomno].seen = 1;
3288.         recalc_mapseen();
3289.     }
3290. }
3291. 
3292. /* #overview command */
3293. int
3294. dooverview(void)
3295. {
3296.     /* game in progress; 'why' is 0 for normal #overview, -1 if user prefixed
3297.        #overview with 'm'; 'reason' for end of game isn't applicable: use 0 */
3298.     show_overview(iflags.menu_requested ? -1 : 0, 0);
3299.     iflags.menu_requested = FALSE;
3300.     return ECMD_OK;
3301. }
3302. 
3303. /* called for #overview or for end of game disclosure */
3304. void
3305. show_overview(
3306.     int why, /* 0 => normal #overview command, -1 => 'm' prefix #overview;
3307.               * 1 or 2 => final disclosure (1: hero lived, 2: hero died) */
3308.     int reason) /* how hero died; used when disclosing end-of-game level */
3309. {
3310.     winid win;
3311.     int lastdun = -1;
3312.     menu_item *selected;
3313.     int n;
3314. 
3315.     /* lazy initialization */
3316.     (void) recalc_mapseen();
3317. 
3318.     win = create_nhwindow(NHW_MENU);
3319.     start_menu(win, MENU_BEHAVE_STANDARD);
3320.     /* show the endgame levels before the rest of the dungeon,
3321.        so that the Planes (dnum 5-ish) come out above main dungeon (dnum 0) */
3322.     if (In_endgame(&u.uz))
3323.         traverse_mapseenchn(1, win, why, reason, &lastdun);
3324.     /* if game is over or we're not in the endgame yet, show the dungeon */
3325.     if (why > 0 || !In_endgame(&u.uz))
3326.         traverse_mapseenchn(0, win, why, reason, &lastdun);
3327.     end_menu(win, (char *) 0);
3328.     n = select_menu(win, (why != -1) ? PICK_NONE : PICK_ONE, &selected);
3329.     if (n > 0) {
3330.         int ledger;
3331.         d_level lev;
3332. 
3333.         ledger = selected[0].item.a_int - 1;
3334.         lev.dnum = ledger_to_dnum(ledger);
3335.         lev.dlevel = ledger_to_dlev(ledger);
3336.         query_annotation(&lev);
3337.         free((genericptr_t) selected);
3338.     }
3339.     destroy_nhwindow(win);
3340. }
3341. 
3342. /* display endgame levels or non-endgame levels, not both */
3343. staticfn void
3344. traverse_mapseenchn(
3345.     int viewendgame,    /* 0: show endgame branch; 1: show other branches */
3346.     winid win,      /* output window */
3347.     int why,        /* -1: menu, 0: normal, 1 and 2: end of game disclosure */
3348.     int reason,     /* when 'why'==1 or 2, how the game ended */
3349.     int *lastdun_p) /* where to restart if called twice */
3350. {
3351.     mapseen *mptr;
3352.     boolean showheader;
3353. 
3354.     for (mptr = svm.mapseenchn; mptr; mptr = mptr->next) {
3355.         if (viewendgame ^ In_endgame(&mptr->lev))
3356.             continue;
3357. 
3358.         /* only print out info for a level or a dungeon if it's of interest */
3359.         if (why != 0 || interest_mapseen(mptr)) {
3360.             showheader = (boolean) (mptr->lev.dnum != *lastdun_p);
3361.             print_mapseen(win, mptr, why, reason, showheader);
3362.             *lastdun_p = mptr->lev.dnum;
3363.         }
3364.     }
3365. }
3366. 
3367. staticfn const char *
3368. seen_string(xint16 x, const char *obj)
3369. {
3370.     /* players are computer scientists: 0, 1, 2, n */
3371.     switch (x) {
3372.     case 0:
3373.         return "no";
3374.     /* an() returns too much.  index/strchr is ok in this case */
3375.     case 1:
3376.         return strchr(vowels, *obj) ? "an" : "a";
3377.     case 2:
3378.         return "some";
3379.     case 3:
3380.         return "many";
3381.     }
3382. 
3383.     return "(unknown)";
3384. }
3385. 
3386. /* better br_string */
3387. staticfn const char *
3388. br_string2(branch *br)
3389. {
3390.     /* Special case: quest portal says closed if kicked from quest */
3391.     boolean closed_portal = (br->end2.dnum == quest_dnum
3392.                              && u.uevent.qexpelled);
3393. 
3394.     switch (br->type) {
3395.     case BR_PORTAL:
3396.         return closed_portal ? "Sealed portal" : "Portal";
3397.     case BR_NO_END1:
3398.         return "Connection";
3399.     case BR_NO_END2:
3400.         return br->end1_up ? "One way stairs up" : "One way stairs down";
3401.     case BR_STAIR:
3402.         return br->end1_up ? "Stairs up" : "Stairs down";
3403.     }
3404. 
3405.     return "(unknown)";
3406. }
3407. 
3408. /* get the name of an endgame level; topten.c does something similar */
3409. const char *
3410. endgamelevelname(char *outbuf, int indx)
3411. {
3412.     const char *planename = 0;
3413. 
3414.     *outbuf = '\0';
3415.     switch (indx) {
3416.     case -5:
3417.         Strcpy(outbuf, "Astral Plane");
3418.         break;
3419.     case -4:
3420.         planename = "Water";
3421.         break;
3422.     case -3:
3423.         planename = "Fire";
3424.         break;
3425.     case -2:
3426.         planename = "Air";
3427.         break;
3428.     case -1:
3429.         planename = "Earth";
3430.         break;
3431.     }
3432.     if (planename)
3433.         Sprintf(outbuf, "Plane of %s", planename);
3434.     else if (!*outbuf)
3435.         Sprintf(outbuf, "unknown plane #%d", indx);
3436.     return outbuf;
3437. }
3438. 
3439. /* short shop description */
3440. staticfn const char *
3441. shop_string(int rtype)
3442. {
3443.     extern const struct shclass shtypes[]; /* defined in shknam.c */
3444.     int shoptype = rtype - SHOPBASE; /* convert room type to shop type */
3445.     const char *str = "shop?"; /* catchall */
3446. 
3447.     if (shoptype < 0) {
3448.         str = "untended shop";
3449.     } else if (shtypes[shoptype].annotation) {
3450.         str = shtypes[shoptype].annotation;
3451.     } else if (shtypes[shoptype].name) {
3452.         str = shtypes[shoptype].name;
3453.     }
3454.     return str;
3455. }
3456. 
3457. /* if player knows about the mastermind tune, append it to Castle annotation;
3458.    if drawbridge has been destroyed, flags.castletune will be zero */
3459. staticfn char *
3460. tunesuffix(
3461.     mapseen *mptr,
3462.     char *outbuf,
3463.     size_t bsz) /* size of outbuf */
3464. {
3465.     *outbuf = '\0';
3466.     if (mptr->flags.castletune && u.uevent.uheard_tune) {
3467.         char tmp[BUFSZ];
3468. 
3469.         if (u.uevent.uheard_tune == 2)
3470.             Sprintf(tmp, "notes \"%s\"", svt.tune);
3471.         else
3472.             Strcpy(tmp, "5-note tune");
3473.         Snprintf(outbuf, bsz, " (play %s to open or close drawbridge)", tmp);
3474.     }
3475.     return outbuf;
3476. }
3477. 
3478. /* some utility macros for print_mapseen */
3479. #define TAB "   " /* three spaces */
3480. #if 0
3481. #define BULLET "" /* empty; otherwise output becomes cluttered */
3482. #define PREFIX TAB TAB BULLET
3483. #else                   /*!0*/
3484. /* K&R: don't require support for concatenation of adjacent string literals */
3485. #define PREFIX "      " /* two TABs + empty BULLET: six spaces */
3486. #endif
3487. #define COMMA (i++ > 0 ? ", " : PREFIX)
3488. /* "iterate" once; safe to use as ``if (cond) ADDTOBUF(); else whatever; */
3489. #define ADDTOBUF(nam, var) \
3490.     do {                                             \
3491.         if (var)                                     \
3492.             Sprintf(eos(buf), "%s%s", COMMA, (nam)); \
3493.     } while (0)
3494. #define ADDNTOBUF(nam, var) \
3495.     do {                                                                     \
3496.         if (var)                                                             \
3497.             Sprintf(eos(buf), "%s%s %s%s", COMMA, seen_string((var), (nam)), \
3498.                     (nam), plur(var));                                       \
3499.     } while (0)
3500. /* ADD2NTOBUF: for "M temples and N altars"; seen_string() is safe to use
3501.    multiple times within one expression; so is plur() */
3502. #define ADD2NTOBUF(nam, var, nam2, var2) \
3503.     do {                                                                \
3504.         if (var && var2) {                                              \
3505.             Sprintf(eos(buf), "%s%s %s%s and %s %s%s", COMMA,           \
3506.                     seen_string((var), (nam)), (nam), plur(var),        \
3507.                     seen_string((var2), (nam2)), (nam2), plur(var2));   \
3508.         } else if (var) {                                               \
3509.             ADDNTOBUF(nam, var);                                        \
3510.         } else if (var2) {                                              \
3511.             ADDNTOBUF(nam2, var2);                                      \
3512.         }                                                               \
3513.     } while (0)
3514. 
3515. staticfn void
3516. print_mapseen(
3517.     winid win, mapseen *mptr,
3518.     int final, /* -1: as menu; 0: not final;
3519.                 * 1: game over, alive; 2: game over, dead */
3520.     int how,   /* cause of death; only used if final==2 and mptr->lev==u.uz */
3521.     boolean printdun)
3522. {
3523.     char buf[BUFSZ], tmpbuf[BUFSZ];
3524.     int i, depthstart, dnum;
3525.     boolean died_here = (final == 2 && on_level(&u.uz, &mptr->lev));
3526.     anything any;
3527. 
3528.     /* Damnable special cases */
3529.     /* The quest and knox should appear to be level 1 to match
3530.      * other text.
3531.      */
3532.     dnum = mptr->lev.dnum;
3533.     if (dnum == quest_dnum || dnum == knox_level.dnum)
3534.         depthstart = 1;
3535.     else
3536.         depthstart = svd.dungeons[dnum].depth_start;
3537. 
3538.     if (printdun) {
3539.         if (svd.dungeons[dnum].dunlev_ureached == svd.dungeons[dnum].entry_lev
3540.             /* suppress the negative numbers in the endgame */
3541.             || In_endgame(&mptr->lev))
3542.             Sprintf(buf, "%s:", svd.dungeons[dnum].dname);
3543.         else if (builds_up(&mptr->lev))
3544.             Sprintf(buf, "%s: levels %d up to %d",
3545.                     svd.dungeons[dnum].dname,
3546.                     depthstart + svd.dungeons[dnum].entry_lev - 1,
3547.                     depthstart + svd.dungeons[dnum].dunlev_ureached - 1);
3548.         else
3549.             Sprintf(buf, "%s: levels %d to %d",
3550.                     svd.dungeons[dnum].dname, depthstart,
3551.                     depthstart + svd.dungeons[dnum].dunlev_ureached - 1);
3552. 
3553.         add_menu_heading(win, buf);
3554.     }
3555. 
3556.     /* calculate level number */
3557.     i = depthstart + mptr->lev.dlevel - 1;
3558.     if (In_endgame(&mptr->lev))
3559.         Sprintf(buf, "%s%s:", (final != -1) ? TAB : "",
3560.                 endgamelevelname(tmpbuf, i));
3561.     else
3562.         Sprintf(buf, "%sLevel %d:", (final != -1) ? TAB : "", i);
3563. 
3564.     /* wizmode prints out proto dungeon names for clarity */
3565.     if (wizard) {
3566.         s_level *slev;
3567. 
3568.         if ((slev = Is_special(&mptr->lev)) != 0)
3569.             Sprintf(eos(buf), " [%s]", slev->proto);
3570.     }
3571.     /* [perhaps print custom annotation on its own line when it's long] */
3572.     if (mptr->custom)
3573.         Sprintf(eos(buf), " \"%s\"", mptr->custom);
3574.     if (on_level(&u.uz, &mptr->lev))
3575.         Sprintf(eos(buf), " <- You %s here.",
3576.                 (final <= 0 || (final == 1 && how == ASCENDED)) ? "are"
3577.                   : (final == 1 && how == ESCAPED) ? "left from"
3578.                     : "were");
3579. 
3580.     any = cg.zeroany;
3581.     if (final == -1)
3582.         any.a_int = ledger_no(&(mptr->lev)) + 1;
3583.     add_menu(win, &nul_glyphinfo, &any, 0, 0, ATR_NONE, NO_COLOR,
3584.              buf, MENU_ITEMFLAGS_NONE);
3585. 
3586.     if (mptr->flags.forgot)
3587.         return;
3588. 
3589.     if (OF_INTEREST(mptr->feat)) {
3590.         buf[0] = 0;
3591. 
3592.         i = 0; /* interest counter */
3593.         /* List interests in an order vaguely corresponding to
3594.          * how important they are.
3595.          */
3596.         if (mptr->feat.nshop > 0) {
3597.             if (mptr->feat.nshop > 1)
3598.                 ADDNTOBUF("shop", mptr->feat.nshop);
3599.             else
3600.                 Sprintf(eos(buf), "%s%s", COMMA,
3601.                         an(shop_string(mptr->feat.shoptype)));
3602.         }
3603.         if (mptr->feat.naltar > 0 || mptr->feat.ntemple > 0) {
3604.             unsigned atmp;
3605. 
3606.             /* being aware of a temple doesn't guarantee being aware of its
3607.                altar (via entrance message when entering while blinded, or
3608.                possibly it being out of view in an irregularly shaped room);
3609.                FIXME: if all temples present have been desecrated, we ought
3610.                to say so */
3611.             ADD2NTOBUF("temple", mptr->feat.ntemple,
3612.                        "altar", mptr->feat.naltar);
3613. 
3614.             /* only print out altar's god if they are all to your god */
3615.             atmp = mptr->feat.msalign;              /*    0,  1,  2,  3 */
3616.             atmp = Msa2amask(atmp);                 /*    0,  1,  2,  4 */
3617.             if (Amask2align(atmp) == u.ualign.type) /* -128, -1,  0, +1 */
3618.                 Sprintf(eos(buf), " to %s", align_gname(u.ualign.type));
3619.         }
3620.         ADDNTOBUF("throne", mptr->feat.nthrone);
3621.         ADDNTOBUF("fountain", mptr->feat.nfount);
3622.         ADDNTOBUF("sink", mptr->feat.nsink);
3623.         ADDNTOBUF("grave", mptr->feat.ngrave);
3624.         ADDNTOBUF("tree", mptr->feat.ntree);
3625. #if 0
3626.         ADDTOBUF("water", mptr->feat.water);
3627.         ADDTOBUF("lava", mptr->feat.lava);
3628.         ADDTOBUF("ice", mptr->feat.ice);
3629. #endif
3630.         /* capitalize afterwards */
3631.         i = strlen(PREFIX);
3632.         buf[i] = highc(buf[i]);
3633.         /* capitalizing it makes it a sentence; terminate with '.' */
3634.         Strcat(buf, ".");
3635.         add_menu_str(win, buf);
3636.     }
3637. 
3638.     /* we assume that these are mutually exclusive */
3639.     *buf = '\0';
3640.     if (mptr->flags.oracle) {
3641.         Sprintf(buf, "%sOracle of Delphi.", PREFIX);
3642.     } else if (In_sokoban(&mptr->lev)) {
3643.         Sprintf(buf, "%s%s.", PREFIX,
3644.                 mptr->flags.sokosolved ? "Solved" : "Unsolved");
3645.     } else if (mptr->flags.bigroom) {
3646.         Sprintf(buf, "%sA very big room.", PREFIX);
3647.     } else if (mptr->flags.roguelevel) {
3648.         Sprintf(buf, "%sA primitive area.", PREFIX);
3649.     } else if (on_level(&mptr->lev, &qstart_level)) {
3650.         Sprintf(buf, "%sHome%s.", PREFIX,
3651.                 mptr->flags.notreachable ? " (no way back...)" : "");
3652.         if (u.uevent.qcompleted)
3653.             Sprintf(buf, "%sCompleted quest for %s.", PREFIX, ldrname());
3654.         else if (mptr->flags.questing)
3655.             Sprintf(buf, "%sGiven quest by %s.", PREFIX, ldrname());
3656.     } else if (mptr->flags.ludios) {
3657.         /* presence of the ludios branch in #overview output indicates that
3658.            the player has made it onto the level; presence of this annotation
3659.            indicates that the fort's entrance has been seen (or mapped) */
3660.         Sprintf(buf, "%sFort Ludios.", PREFIX);
3661.     } else if (mptr->flags.castle) {
3662.         Snprintf(buf, sizeof buf, "%sThe castle%s.", PREFIX,
3663.                 tunesuffix(mptr, tmpbuf, sizeof tmpbuf));
3664.     } else if (mptr->flags.valley) {
3665.         Sprintf(buf, "%sValley of the Dead.", PREFIX);
3666.     } else if (mptr->flags.vibrating_square) {
3667.         Sprintf(buf, "%sGateway to Moloch's Sanctum.", PREFIX);
3668.     } else if (mptr->flags.msanctum) {
3669.         Sprintf(buf, "%sMoloch's Sanctum.", PREFIX);
3670.     }
3671.     if (*buf) {
3672.         add_menu_str(win, buf);
3673.     }
3674.     /* quest entrance is not mutually-exclusive with bigroom or rogue level */
3675.     if (mptr->flags.quest_summons) {
3676.         Sprintf(buf, "%sSummoned by %s.", PREFIX, ldrname());
3677.         add_menu_str(win, buf);
3678.     }
3679. 
3680.     /* print out branches */
3681.     if (mptr->br) {
3682.         Sprintf(buf, "%s%s to %s", PREFIX, br_string2(mptr->br),
3683.                 svd.dungeons[mptr->br->end2.dnum].dname);
3684. 
3685.         /* Since mapseen objects are printed out in increasing order
3686.          * of dlevel, clarify which level this branch is going to
3687.          * if the branch goes upwards.  Unless it's the end game.
3688.          */
3689.         if (mptr->br->end1_up && !In_endgame(&(mptr->br->end2)))
3690.             Sprintf(eos(buf), ", level %d", depth(&(mptr->br->end2)));
3691.         Strcat(buf, ".");
3692.         add_menu_str(win, buf);
3693.     }
3694. 
3695.     /* maybe print out bones details */
3696.     if (mptr->final_resting_place || final > 0) {
3697.         struct cemetery *bp;
3698.         int kncnt = !died_here ? 0 : 1;
3699. 
3700.         for (bp = mptr->final_resting_place; bp; bp = bp->next)
3701.             if (bp->bonesknown || wizard || final > 0)
3702.                 ++kncnt;
3703.         if (kncnt) {
3704.             Sprintf(buf, "%s%s", PREFIX, "Final resting place for");
3705.             add_menu_str(win, buf);
3706.             if (died_here) {
3707.                 /* disclosure occurs before bones creation, so listing dead
3708.                    hero here doesn't give away whether bones are produced */
3709.                 formatkiller(tmpbuf, sizeof tmpbuf, how, TRUE);
3710.                 /* rephrase a few death reasons to work with "you" */
3711.                 (void) strsubst(tmpbuf, " himself", " yourself");
3712.                 (void) strsubst(tmpbuf, " herself", " yourself");
3713.                 (void) strsubst(tmpbuf, " his ", " your ");
3714.                 (void) strsubst(tmpbuf, " her ", " your ");
3715.                 Snprintf(buf, sizeof(buf), "%s%syou, %s%c", PREFIX, TAB,
3716.                          tmpbuf, --kncnt ? ',' : '.');
3717.                 add_menu_str(win, buf);
3718.             }
3719.             for (bp = mptr->final_resting_place; bp; bp = bp->next) {
3720.                 if (bp->bonesknown || wizard || final > 0) {
3721.                     Sprintf(buf, "%s%s%s, %s%c", PREFIX, TAB, bp->who,
3722.                             bp->how, --kncnt ? ',' : '.');
3723.                     add_menu_str(win, buf);
3724.                 }
3725.             }
3726.         }
3727.     }
3728. }
3729. #endif /* !SFCTOOL */
3730. #undef OF_INTEREST
3731. #undef ADDNTOBUF
3732. #undef ADDTOBUF
3733. 
3734. /*dungeon.c*/