Source:NetHack 5.0.0/src/mklev.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to mklev.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/mklev.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	mklev.c	$NHDT-Date: 1737387068 2025/01/20 07:31:08 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.194 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Alex Smith, 2017. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. 
8. /* for UNIX, Rand #def'd to (long)lrand48() or (long)random() */
9. /* croom->lx etc are schar (width <= int), so % arith ensures that */
10. /* conversion of result to int is reasonable */
11. 
12. staticfn boolean generate_stairs_room_good(struct mkroom *, int);
13. staticfn struct mkroom *generate_stairs_find_room(void);
14. staticfn void generate_stairs(void);
15. staticfn void mkfount(struct mkroom *);
16. staticfn boolean find_okay_roompos(struct mkroom *, coord *) NONNULLARG12;
17. staticfn void mksink(struct mkroom *);
18. staticfn void mkaltar(struct mkroom *);
19. staticfn void mkgrave(struct mkroom *);
20. staticfn void mkinvpos(coordxy, coordxy, int);
21. staticfn int mkinvk_check_wall(coordxy x, coordxy y);
22. staticfn void mk_knox_portal(coordxy, coordxy);
23. staticfn void makevtele(void);
24. staticfn void fill_ordinary_room(struct mkroom *, boolean) NONNULLARG1;
25. staticfn void themerooms_post_level_generate(void);
26. staticfn boolean chk_okdoor(coordxy, coordxy);
27. staticfn void mklev_sanity_check(void);
28. staticfn void makelevel(void);
29. staticfn boolean water_has_kelp(coordxy, coordxy, int, int);
30. staticfn boolean bydoor(coordxy, coordxy);
31. staticfn void mktrap_victim(struct trap *);
32. staticfn int traptype_rnd(unsigned);
33. staticfn int traptype_roguelvl(void);
34. staticfn struct mkroom *find_branch_room(coord *) NONNULLARG1;
35. staticfn struct mkroom *pos_to_room(coordxy, coordxy);
36. staticfn boolean cardinal_nextto_room(struct mkroom *, coordxy, coordxy);
37. staticfn boolean place_niche(struct mkroom *, int *, coordxy *, coordxy *);
38. staticfn void makeniche(int);
39. staticfn void make_niches(void);
40. staticfn int QSORTCALLBACK mkroom_cmp(const genericptr, const genericptr);
41. staticfn void dosdoor(coordxy, coordxy, struct mkroom *, int);
42. staticfn void join(int, int, boolean);
43. staticfn void alloc_doors(void);
44. staticfn void do_room_or_subroom(struct mkroom *,
45.                                coordxy, coordxy, coordxy, coordxy,
46.                                boolean, schar, boolean, boolean);
47. staticfn void makerooms(void);
48. staticfn boolean good_rm_wall_doorpos(coordxy, coordxy, int, struct mkroom *);
49. staticfn boolean finddpos_shift(coordxy *, coordxy *, int, struct mkroom *);
50. 
51. staticfn boolean finddpos(coord *, int, struct mkroom *);
52. 
53. #define create_vault() create_room(-1, -1, 2, 2, -1, -1, VAULT, TRUE)
54. #define init_vault() gv.vault_x = -1
55. #define do_vault() (gv.vault_x != -1)
56. 
57. /* Args must be (const genericptr) so that qsort will always be happy. */
58. 
59. staticfn int QSORTCALLBACK
60. mkroom_cmp(const genericptr vx, const genericptr vy)
61. {
62.     const struct mkroom *x, *y;
63. 
64.     x = (const struct mkroom *) vx;
65.     y = (const struct mkroom *) vy;
66.     if (x->lx < y->lx)
67.         return -1;
68.     return (x->lx > y->lx);
69. }
70. 
71. /* is x,y a good location for a door into room? */
72. staticfn boolean
73. good_rm_wall_doorpos(coordxy x, coordxy y, int dir, struct mkroom *room)
74. {
75.     coordxy tx, ty;
76.     int rmno;
77. 
78.     if (!isok(x, y) || !room->needjoining)
79.         return FALSE;
80. 
81.     if (!(levl[x][y].typ == HWALL
82.           || levl[x][y].typ == VWALL
83.           || IS_DOOR(levl[x][y].typ)
84.           || levl[x][y].typ == SDOOR))
85.         return FALSE;
86. 
87.     if (bydoor(x, y))
88.         return FALSE;
89. 
90.     tx = x + xdir[dir];
91.     ty = y + ydir[dir];
92. 
93.     if (!isok(tx,ty) || IS_OBSTRUCTED(levl[tx][ty].typ))
94.         return FALSE;
95. 
96.     rmno = (room - svr.rooms) + ROOMOFFSET;
97. 
98.     if (rmno != (int) levl[tx][ty].roomno)
99.         return FALSE;
100. 
101.     return TRUE;
102. }
103. 
104. /* starting from x,y going towards dir, find a good location for a door */
105. staticfn boolean
106. finddpos_shift(coordxy *x, coordxy *y, int dir, struct mkroom *aroom)
107. {
108.     coordxy dx, dy;
109. 
110.     dir = DIR_180(dir);
111. 
112.     dx = xdir[dir];
113.     dy = ydir[dir];
114. 
115.     if (good_rm_wall_doorpos(*x, *y, dir, aroom))
116.         return TRUE;
117. 
118.     /* irregular rooms may have the room wall away from the room rectangular
119.        area; go into the area until we encounter something */
120.     if (aroom->irregular) {
121.         coordxy rx = *x, ry = *y;
122.         boolean fail = FALSE;
123. 
124.         while (!fail && isok(rx, ry)
125.                && (levl[rx][ry].typ == STONE || levl[rx][ry].typ == CORR)) {
126.             rx += dx;
127.             ry += dy;
128.             if (good_rm_wall_doorpos(rx, ry, dir, aroom)) {
129.                 *x = rx;
130.                 *y = ry;
131.                 return TRUE;
132.             }
133.             if (!(levl[rx][ry].typ == STONE || levl[rx][ry].typ == CORR))
134.                 fail = TRUE;
135.             if (rx < aroom->lx || rx > aroom->hx
136.                 || ry < aroom->ly || ry > aroom->hy)
137.                 fail = TRUE;
138.         }
139.     }
140.     return FALSE;
141. }
142. 
143. /* find a valid door position at room edge.
144.    dir is the preferred edge of the room.
145.    if found, returns TRUE and the coordinate in cc */
146. staticfn boolean
147. finddpos(coord *cc, int dir, struct mkroom *aroom)
148. {
149.     coordxy x, y;
150.     coordxy x1, y1, x2, y2;
151.     int tryct = 0;
152. 
153.     switch (dir) {
154.     case DIR_N:
155.         x1 = aroom->lx;
156.         x2 = aroom->hx;
157.         y1 = aroom->ly - 1;
158.         y2 = aroom->ly - 1;
159.         break;
160.     case DIR_S:
161.         x1 = aroom->lx;
162.         x2 = aroom->hx;
163.         y1 = aroom->hy + 1;
164.         y2 = aroom->hy + 1;
165.         break;
166.     case DIR_W:
167.         x1 = aroom->lx - 1;
168.         x2 = aroom->lx - 1;
169.         y1 = aroom->ly;
170.         y2 = aroom->hy;
171.         break;
172.     case DIR_E:
173.         x1 = aroom->hx + 1;
174.         x2 = aroom->hx + 1;
175.         y1 = aroom->ly;
176.         y2 = aroom->hy;
177.         break;
178.     default:
179.         impossible("finddpos: illegal dir");
180.         return FALSE;
181.     }
182. 
183.     /* try random points */
184.     do {
185.         x = (x2 - x1) ? rn1(x2 - x1 + 1, x1) : x1;
186.         y = (y2 - y1) ? rn1(y2 - y1 + 1, y1) : y1;
187.         if (finddpos_shift(&x, &y, dir, aroom))
188.           goto gotit;
189.     } while (++tryct < 20);
190. 
191.     /* try all the points */
192.     for (x = x1; x <= x2; x++)
193.         for (y = y1; y <= y2; y++)
194.             if (finddpos_shift(&x, &y, dir, aroom))
195.                 goto gotit;
196. 
197.     /* cannot find something reasonable -- strange */
198.     cc->x = x1;
199.     cc->y = y1;
200.     return FALSE;
201.  gotit:
202.     cc->x = x;
203.     cc->y = y;
204.     return TRUE;
205. }
206. 
207. /* Sort rooms on the level so they're ordered from left to right on the map.
208.    makecorridors() by default links rooms N and N+1 */
209. void
210. sort_rooms(void)
211. {
212.     coordxy x, y;
213.     unsigned i, ri[MAXNROFROOMS + 1] = { 0U }, n = (unsigned) svn.nroom;
214. 
215.     qsort((genericptr_t) svr.rooms, n, sizeof (struct mkroom), mkroom_cmp);
216. 
217.     /* Update the roomnos on the map */
218.     for (i = 0; i < n; i++)
219.         ri[svr.rooms[i].roomnoidx] = i;
220. 
221.     for (x = 1; x < COLNO; x++)
222.         for (y = 0; y < ROWNO; y++) {
223.             unsigned rno = levl[x][y].roomno;
224. 
225.             if (rno >= ROOMOFFSET && rno < MAXNROFROOMS + 1)
226.                 levl[x][y].roomno = ri[rno - ROOMOFFSET] + ROOMOFFSET;
227.         }
228. }
229. 
230. staticfn void
231. do_room_or_subroom(struct mkroom *croom,
232.                    coordxy lowx, coordxy lowy, coordxy hix, coordxy hiy,
233.                    boolean lit, schar rtype, boolean special, boolean is_room)
234. {
235.     coordxy x, y;
236.     struct rm *lev;
237. 
238.     /* locations might bump level edges in wall-less rooms */
239.     /* add/subtract 1 to allow for edge locations */
240.     if (!lowx)
241.         lowx++;
242.     if (!lowy)
243.         lowy++;
244.     if (hix >= COLNO - 1)
245.         hix = COLNO - 2;
246.     if (hiy >= ROWNO - 1)
247.         hiy = ROWNO - 2;
248. 
249.     if (lit) {
250.         for (x = lowx - 1; x <= hix + 1; x++) {
251.             lev = &levl[x][max(lowy - 1, 0)];
252.             for (y = lowy - 1; y <= hiy + 1; y++)
253.                 lev++->lit = 1;
254.         }
255.         croom->rlit = 1;
256.     } else
257.         croom->rlit = 0;
258. 
259.     croom->roomnoidx = (croom - svr.rooms);
260.     croom->lx = lowx;
261.     croom->hx = hix;
262.     croom->ly = lowy;
263.     croom->hy = hiy;
264.     croom->rtype = rtype;
265.     croom->doorct = 0;
266.     /* if we're not making a vault, gd.doorindex will still be 0
267.      * if we are, we'll have problems adding niches to the previous room
268.      * unless fdoor is at least gd.doorindex
269.      */
270.     croom->fdoor = gd.doorindex;
271.     croom->irregular = FALSE;
272. 
273.     croom->nsubrooms = 0;
274.     croom->sbrooms[0] = (struct mkroom *) 0;
275.     if (!special) {
276.         croom->needjoining = TRUE;
277.         for (x = lowx - 1; x <= hix + 1; x++)
278.             for (y = lowy - 1; y <= hiy + 1; y += (hiy - lowy + 2)) {
279.                 levl[x][y].typ = HWALL;
280.                 levl[x][y].horizontal = 1; /* For open/secret doors. */
281.             }
282.         for (x = lowx - 1; x <= hix + 1; x += (hix - lowx + 2))
283.             for (y = lowy; y <= hiy; y++) {
284.                 levl[x][y].typ = VWALL;
285.                 levl[x][y].horizontal = 0; /* For open/secret doors. */
286.             }
287.         for (x = lowx; x <= hix; x++) {
288.             lev = &levl[x][lowy];
289.             for (y = lowy; y <= hiy; y++)
290.                 lev++->typ = ROOM;
291.         }
292.         if (is_room) {
293.             levl[lowx - 1][lowy - 1].typ = TLCORNER;
294.             levl[hix + 1][lowy - 1].typ = TRCORNER;
295.             levl[lowx - 1][hiy + 1].typ = BLCORNER;
296.             levl[hix + 1][hiy + 1].typ = BRCORNER;
297.         } else { /* a subroom */
298.             wallification(lowx - 1, lowy - 1, hix + 1, hiy + 1);
299.         }
300.     }
301. }
302. 
303. void
304. add_room(coordxy lowx, coordxy lowy, coordxy hix, coordxy hiy,
305.          boolean lit, schar rtype, boolean special)
306. {
307.     struct mkroom *croom;
308. 
309. #ifdef DEBUG
310.     if (svn.nroom >= MAXNROFROOMS)
311.         panic("level has too many rooms");
312. #endif /*DEBUG*/
313.     croom = &svr.rooms[svn.nroom];
314.     do_room_or_subroom(croom, lowx, lowy, hix, hiy, lit, rtype, special,
315.                        (boolean) TRUE);
316.     croom++;
317.     croom->hx = -1;
318.     svn.nroom++;
319. }
320. 
321. void
322. add_subroom(struct mkroom *proom,
323.             coordxy lowx, coordxy lowy,
324.             coordxy hix, coordxy hiy,
325.             boolean lit, schar rtype, boolean special)
326. {
327.     struct mkroom *croom;
328. 
329. #ifdef DEBUG
330.     if (gn.nsubroom >= MAXNROFROOMS)
331.         panic("level has too many subrooms");
332.     if (proom->nsubrooms >= MAX_SUBROOMS)
333.         panic("room has too many subrooms");
334. #endif /*DEBUG*/
335.     croom = &gs.subrooms[gn.nsubroom];
336.     do_room_or_subroom(croom, lowx, lowy, hix, hiy, lit, rtype, special,
337.                        (boolean) FALSE);
338.     proom->sbrooms[proom->nsubrooms++] = croom;
339.     croom++;
340.     croom->hx = -1;
341.     gn.nsubroom++;
342. }
343. 
344. void
345. free_luathemes(enum lua_theme_group theme_group)
346. {
347.     int i;
348. 
349.     /*
350.      * Release which group(s)?
351.      *  tut_themes  => leaving tutorial, free tutorial themes only;
352.      *  most_themes => entering endgame, free non-endgame themes;
353.      *  all_themes  => end of game, free all themes.
354.      */
355.     for (i = 0; i < svn.n_dgns; ++i) {
356.         if ((theme_group == tut_themes && i != tutorial_dnum)
357.             || (theme_group == most_themes && i == astral_level.dnum))
358.             continue;
359.         if (gl.luathemes[i]) {
360.             nhl_done((lua_State *) gl.luathemes[i]);
361.             gl.luathemes[i] = (lua_State *) 0;
362.         }
363.     }
364. }
365. 
366. staticfn void
367. makerooms(void)
368. {
369.     boolean tried_vault = FALSE;
370.     int themeroom_tries = 0;
371.     char *fname;
372.     nhl_sandbox_info sbi = {NHL_SB_SAFE, 1*1024*1024, 0, 1*1024*1024};
373.     lua_State *themes = (lua_State *) gl.luathemes[u.uz.dnum];
374. 
375.     if (!themes && *(fname = svd.dungeons[u.uz.dnum].themerms)) {
376.         if ((themes = nhl_init(&sbi)) != 0) {
377.             if (!nhl_loadlua(themes, fname)) {
378.                 /* loading lua failed, don't use themed rooms */
379.                 nhl_done(themes);
380.                 themes = (lua_State *) 0;
381.             } else {
382.                 /* success; save state for this dungeon branch */
383.                 gl.luathemes[u.uz.dnum] = (genericptr_t) themes;
384.                 /* keep themes context, so not 'nhl_done(themes);' */
385.                 iflags.in_lua = FALSE; /* can affect error messages */
386.             }
387.         }
388.         if (!themes) /* don't try again when making next level */
389.             *fname = '\0'; /* svd.dungeons[u.uz.dnum].themerms */
390.     }
391. 
392.     if (themes) {
393.         create_des_coder();
394.         iflags.in_lua = gi.in_mk_themerooms = TRUE;
395.         gt.themeroom_failed = FALSE;
396.         lua_getglobal(themes, "pre_themerooms_generate");
397.         nhl_pcall_handle(themes, 0, 0, "makerooms-1", NHLpa_impossible);
398.         iflags.in_lua = gi.in_mk_themerooms = FALSE;
399.     }
400. 
401.     /* make rooms until satisfied */
402.     /* rnd_rect() will returns 0 if no more rects are available... */
403.     while (svn.nroom < (MAXNROFROOMS - 1) && rnd_rect()) {
404.         if (svn.nroom >= (MAXNROFROOMS / 6) && rn2(2) && !tried_vault) {
405.             tried_vault = TRUE;
406.             if (create_vault()) {
407.                 gv.vault_x = svr.rooms[svn.nroom].lx;
408.                 gv.vault_y = svr.rooms[svn.nroom].ly;
409.                 svr.rooms[svn.nroom].hx = -1;
410.             }
411.         } else {
412.             if (themes) {
413.                 iflags.in_lua = gi.in_mk_themerooms = TRUE;
414.                 gt.themeroom_failed = FALSE;
415.                 lua_getglobal(themes, "themerooms_generate");
416.                 nhl_pcall_handle(themes, 0, 0, "makerooms-2", NHLpa_panic);
417.                 iflags.in_lua = gi.in_mk_themerooms = FALSE;
418.                 if (gt.themeroom_failed
419.                     && ((themeroom_tries++ > 10)
420.                         || (svn.nroom >= (MAXNROFROOMS / 6))))
421.                     break;
422.             } else {
423.                 if (!create_room(-1, -1, -1, -1, -1, -1, OROOM, -1))
424.                     break;;
425.             }
426.         }
427.     }
428.     if (themes) {
429.         reset_xystart_size();
430.         iflags.in_lua = gi.in_mk_themerooms = TRUE;
431.         gt.themeroom_failed = FALSE;
432.         lua_getglobal(themes, "post_themerooms_generate");
433.         nhl_pcall_handle(themes, 0, 0, "makerooms-3", NHLpa_panic);
434.         iflags.in_lua = gi.in_mk_themerooms = FALSE;
435.     }
436. }
437. 
438. staticfn void
439. join(int a, int b, boolean nxcor)
440. {
441.     coord cc, tt, org, dest;
442.     coordxy tx, ty, xx, yy;
443.     struct mkroom *croom, *troom;
444.     int dx, dy;
445.     int npoints;
446.     boolean dig_result;
447. 
448.     croom = &svr.rooms[a];
449.     troom = &svr.rooms[b];
450. 
451.     if (!croom->needjoining || !troom->needjoining)
452.         return;
453. 
454.     /* find positions cc and tt for doors in croom and troom
455.        and direction for a corridor between them */
456. 
457.     if (troom->hx < 0 || croom->hx < 0)
458.         return;
459.     if (troom->lx > croom->hx) {
460.         dx = 1;
461.         dy = 0;
462.         if (!finddpos(&cc, DIR_E, croom))
463.             return;
464.         if (!finddpos(&tt, DIR_W, troom))
465.             return;
466.     } else if (troom->hy < croom->ly) {
467.         dy = -1;
468.         dx = 0;
469.         if (!finddpos(&cc, DIR_N, croom))
470.             return;
471.         if (!finddpos(&tt, DIR_S, troom))
472.             return;
473.     } else if (troom->hx < croom->lx) {
474.         dx = -1;
475.         dy = 0;
476.         if (!finddpos(&cc, DIR_W, croom))
477.             return;
478.         if (!finddpos(&tt, DIR_E, troom))
479.             return;
480.     } else {
481.         dy = 1;
482.         dx = 0;
483.         if (!finddpos(&cc, DIR_S, croom))
484.             return;
485.         if (!finddpos(&tt, DIR_N, troom))
486.             return;
487.     }
488.     xx = cc.x;
489.     yy = cc.y;
490.     tx = tt.x - dx;
491.     ty = tt.y - dy;
492.     if (nxcor && levl[xx + dx][yy + dy].typ != STONE)
493.         return;
494. 
495.     org.x = xx + dx;
496.     org.y = yy + dy;
497.     dest.x = tx;
498.     dest.y = ty;
499. 
500.     dig_result = dig_corridor(&org, &dest, &npoints, nxcor,
501.                               svl.level.flags.arboreal ? ROOM : CORR, STONE);
502. 
503.     /* we created at least 1 tile of corridor, even if it failed */
504.     if ((npoints > 0) && (okdoor(xx, yy) || !nxcor))
505.         dodoor(xx, yy, croom);
506. 
507.     if (!dig_result)
508.         return;
509. 
510.     /* we succeeded in digging the corridor */
511.     if (okdoor(tt.x, tt.y) || !nxcor)
512.         dodoor(tt.x, tt.y, troom);
513. 
514.     if (gs.smeq[a] < gs.smeq[b])
515.         gs.smeq[b] = gs.smeq[a];
516.     else
517.         gs.smeq[a] = gs.smeq[b];
518. }
519. 
520. /* create random corridors between rooms */
521. void
522. makecorridors(void)
523. {
524.     int a, b, i;
525.     boolean any = TRUE;
526. 
527.     for (a = 0; a < svn.nroom - 1; a++) {
528.         join(a, a + 1, FALSE);
529.         if (!rn2(50))
530.             break; /* allow some randomness */
531.     }
532.     for (a = 0; a < svn.nroom - 2; a++)
533.         if (gs.smeq[a] != gs.smeq[a + 2])
534.             join(a, a + 2, FALSE);
535.     for (a = 0; any && a < svn.nroom; a++) {
536.         any = FALSE;
537.         for (b = 0; b < svn.nroom; b++)
538.             if (gs.smeq[a] != gs.smeq[b]) {
539.                 join(a, b, FALSE);
540.                 any = TRUE;
541.             }
542.     }
543.     /* add some extra corridors which may be blocked off */
544.     if (svn.nroom > 2)
545.         for (i = rn2(svn.nroom) + 4; i; i--) {
546.             a = rn2(svn.nroom);
547.             b = rn2(svn.nroom - 2);
548.             if (b >= a)
549.                 b += 2;
550.             join(a, b, TRUE);
551.         }
552. }
553. 
554. /* (re)allocate space for svd.doors array */
555. staticfn void
556. alloc_doors(void)
557. {
558.     if (!svd.doors || gd.doorindex >= svd.doors_alloc) {
559.         int c = svd.doors_alloc + DOORINC;
560.         coord *doortmp = (coord *) alloc(c * sizeof (coord));
561. 
562.         (void) memset((genericptr_t) doortmp, 0, c * sizeof (coord));
563.         if (svd.doors) {
564.             (void) memcpy(doortmp, svd.doors,
565.                           svd.doors_alloc * sizeof (coord));
566.             free(svd.doors);
567.         }
568.         svd.doors = doortmp;
569.         svd.doors_alloc = c;
570.     }
571. }
572. 
573. void
574. add_door(coordxy x, coordxy y, struct mkroom *aroom)
575. {
576.     struct mkroom *broom;
577.     int tmp;
578.     int i;
579. 
580.     alloc_doors();
581. 
582.     if (aroom->doorct) {
583.         for (i = 0; i < aroom->doorct; i++) {
584.             tmp = aroom->fdoor + i;
585.             if (svd.doors[tmp].x == x && svd.doors[tmp].y == y)
586.                 return;
587.         }
588.     }
589. 
590.     if (aroom->doorct == 0)
591.         aroom->fdoor = gd.doorindex;
592. 
593.     aroom->doorct++;
594. 
595.     for (tmp = gd.doorindex; tmp > aroom->fdoor; tmp--)
596.         svd.doors[tmp] = svd.doors[tmp - 1];
597. 
598.     for (i = 0; i < svn.nroom; i++) {
599.         broom = &svr.rooms[i];
600.         if (broom != aroom && broom->doorct && broom->fdoor >= aroom->fdoor)
601.             broom->fdoor++;
602.     }
603.     for (i = 0; i < gn.nsubroom; i++) {
604.         broom = &gs.subrooms[i];
605.         if (broom != aroom && broom->doorct && broom->fdoor >= aroom->fdoor)
606.             broom->fdoor++;
607.     }
608. 
609.     gd.doorindex++;
610.     svd.doors[aroom->fdoor].x = x;
611.     svd.doors[aroom->fdoor].y = y;
612. }
613. 
614. staticfn void
615. dosdoor(coordxy x, coordxy y, struct mkroom *aroom, int type)
616. {
617.     boolean shdoor = *in_rooms(x, y, SHOPBASE) ? TRUE : FALSE;
618. 
619.     if (!IS_WALL(levl[x][y].typ)) /* avoid S.doors on already made doors */
620.         type = DOOR;
621.     levl[x][y].typ = type;
622.     if (type == DOOR) {
623.         if (!rn2(3)) { /* is it a locked door, closed, or a doorway? */
624.             if (!rn2(5))
625.                 levl[x][y].doormask = D_ISOPEN;
626.             else if (!rn2(6))
627.                 levl[x][y].doormask = D_LOCKED;
628.             else
629.                 levl[x][y].doormask = D_CLOSED;
630. 
631.             if (levl[x][y].doormask != D_ISOPEN && !shdoor
632.                 && level_difficulty() >= 5 && !rn2(25))
633.                 levl[x][y].doormask |= D_TRAPPED;
634.         } else {
635. #ifdef STUPID
636.             if (shdoor)
637.                 levl[x][y].doormask = D_ISOPEN;
638.             else
639.                 levl[x][y].doormask = D_NODOOR;
640. #else
641.             levl[x][y].doormask = (shdoor ? D_ISOPEN : D_NODOOR);
642. #endif
643.         }
644. 
645.         /* also done in roguecorr(); doing it here first prevents
646.            making mimics in place of trapped doors on rogue svl.level */
647.         if (Is_rogue_level(&u.uz))
648.             levl[x][y].doormask = D_NODOOR;
649. 
650.         if (levl[x][y].doormask & D_TRAPPED) {
651.             struct monst *mtmp;
652. 
653.             if (level_difficulty() >= 9 && !rn2(5)
654.                 && !((svm.mvitals[PM_SMALL_MIMIC].mvflags & G_GONE)
655.                      && (svm.mvitals[PM_LARGE_MIMIC].mvflags & G_GONE)
656.                      && (svm.mvitals[PM_GIANT_MIMIC].mvflags & G_GONE))) {
657.                 /* make a mimic instead */
658.                 levl[x][y].doormask = D_NODOOR;
659.                 mtmp = makemon(mkclass(S_MIMIC, 0), x, y, NO_MM_FLAGS);
660.                 if (mtmp)
661.                     set_mimic_sym(mtmp);
662.             }
663.         }
664.         /* newsym(x,y); */
665.     } else { /* SDOOR */
666.         if (shdoor || !rn2(5))
667.             levl[x][y].doormask = D_LOCKED;
668.         else
669.             levl[x][y].doormask = D_CLOSED;
670. 
671.         if (!shdoor && level_difficulty() >= 4 && !rn2(20))
672.             levl[x][y].doormask |= D_TRAPPED;
673.     }
674. 
675.     add_door(x, y, aroom);
676. }
677. 
678. /* is x,y location such that NEWS direction from it is inside aroom,
679.    excluding subrooms */
680. staticfn boolean
681. cardinal_nextto_room(struct mkroom *aroom, coordxy x, coordxy y)
682. {
683.     int rmno = (int) ((aroom - svr.rooms) + ROOMOFFSET);
684. 
685.     if (isok(x - 1, y) && !levl[x - 1][y].edge
686.         && (int) levl[x - 1][y].roomno == rmno)
687.         return TRUE;
688.     if (isok(x + 1, y) && !levl[x + 1][y].edge
689.         && (int) levl[x + 1][y].roomno == rmno)
690.         return TRUE;
691.     if (isok(x, y - 1) && !levl[x][y - 1].edge
692.         && (int) levl[x][y - 1].roomno == rmno)
693.         return TRUE;
694.     if (isok(x, y + 1) && !levl[x][y + 1].edge
695.         && (int) levl[x][y + 1].roomno == rmno)
696.         return TRUE;
697.     return FALSE;
698. }
699. 
700. staticfn boolean
701. place_niche(
702.     struct mkroom *aroom,
703.     int *dy,
704.     coordxy *xx, coordxy *yy)
705. {
706.     coord dd;
707. 
708.     if (rn2(2)) {
709.         *dy = 1;
710.         if (!finddpos(&dd, DIR_S, aroom))
711.             return FALSE;
712.     } else {
713.         *dy = -1;
714.         if (!finddpos(&dd, DIR_N, aroom))
715.             return FALSE;
716.     }
717.     *xx = dd.x;
718.     *yy = dd.y;
719.     return (boolean) ((isok(*xx, *yy + *dy)
720.                        && levl[*xx][*yy + *dy].typ == STONE)
721.                       && (isok(*xx, *yy - *dy)
722.                           && !IS_POOL(levl[*xx][*yy - *dy].typ)
723.                           && !IS_FURNITURE(levl[*xx][*yy - *dy].typ))
724.                       && cardinal_nextto_room(aroom, *xx, *yy));
725. }
726. 
727. /* there should be one of these per trap, in the same order as trap.h */
728. static NEARDATA const char *trap_engravings[TRAPNUM] = {
729.     (char *) 0,      (char *) 0,    (char *) 0,    (char *) 0, (char *) 0,
730.     (char *) 0,      (char *) 0,    (char *) 0,    (char *) 0, (char *) 0,
731.     (char *) 0,      (char *) 0,    (char *) 0,    (char *) 0,
732.     /* 14..16: trap door, teleport, level-teleport */
733.     "Vlad was here", "ad aerarium", "ad aerarium", (char *) 0, (char *) 0,
734.     (char *) 0,      (char *) 0,    (char *) 0,    (char *) 0, (char *) 0,
735.     /* 24..25 */
736.     (char *) 0, (char *) 0,
737. };
738. 
739. staticfn void
740. makeniche(int trap_type)
741. {
742.     struct mkroom *aroom;
743.     struct rm *rm;
744.     int dy, vct = 8;
745.     coordxy xx, yy;
746.     struct trap *ttmp;
747. 
748.     while (vct--) {
749.         aroom = &svr.rooms[rn2(svn.nroom)];
750.         if (aroom->rtype != OROOM)
751.             continue; /* not an ordinary room */
752.         if (aroom->doorct == 1 && rn2(5))
753.             continue;
754.         if (!place_niche(aroom, &dy, &xx, &yy))
755.             continue;
756. 
757.         rm = &levl[xx][yy + dy];
758.         if (trap_type || !rn2(4)) {
759.             rm->typ = SCORR;
760.             if (trap_type) {
761.                 if (is_hole(trap_type) && !Can_fall_thru(&u.uz))
762.                     trap_type = ROCKTRAP;
763.                 ttmp = maketrap(xx, yy + dy, trap_type);
764.                 if (ttmp) {
765.                     if (trap_type != ROCKTRAP)
766.                         ttmp->once = 1;
767.                     if (trap_engravings[trap_type]) {
768.                         make_engr_at(xx, yy - dy,
769.                                      trap_engravings[trap_type], NULL, 0L,
770.                                      DUST);
771.                         wipe_engr_at(xx, yy - dy, 5,
772.                                      FALSE); /* age it a little */
773.                     }
774.                 }
775.             }
776.             dosdoor(xx, yy, aroom, SDOOR);
777.         } else {
778.             rm->typ = CORR;
779.             if (rn2(7)) {
780.                 dosdoor(xx, yy, aroom, rn2(5) ? SDOOR : DOOR);
781.             } else {
782.                 /* inaccessible niches occasionally have iron bars */
783.                 if (!rn2(5) && IS_WALL(levl[xx][yy].typ)) {
784.                     (void) set_levltyp(xx, yy, IRONBARS);
785.                     if (rn2(3))
786.                         (void) mkcorpstat(CORPSE, (struct monst *) 0,
787.                                           mkclass(S_HUMAN, 0), xx,
788.                                           yy + dy, TRUE);
789.                 }
790.                 if (!svl.level.flags.noteleport)
791.                     (void) mksobj_at(SCR_TELEPORTATION, xx, yy + dy, TRUE,
792.                                      FALSE);
793.                 if (!rn2(3))
794.                     (void) mkobj_at(RANDOM_CLASS, xx, yy + dy, TRUE);
795.             }
796.         }
797.         return;
798.     }
799. }
800. 
801. staticfn void
802. make_niches(void)
803. {
804.     int ct = rnd((svn.nroom >> 1) + 1), dep = depth(&u.uz);
805.     boolean ltptr = (!svl.level.flags.noteleport && dep > 15),
806.             vamp = (dep > 5 && dep < 25);
807. 
808.     while (ct--) {
809.         if (ltptr && !rn2(6)) {
810.             ltptr = FALSE;
811.             makeniche(LEVEL_TELEP);
812.         } else if (vamp && !rn2(6)) {
813.             vamp = FALSE;
814.             makeniche(TRAPDOOR);
815.         } else
816.             makeniche(NO_TRAP);
817.     }
818. }
819. 
820. staticfn void
821. makevtele(void)
822. {
823.     makeniche(TELEP_TRAP);
824. }
825. 
826. /* count the tracked features (sinks, fountains) present on the level */
827. void
828. count_level_features(void)
829. {
830.     coordxy x, y;
831. 
832.     svl.level.flags.nfountains = svl.level.flags.nsinks = 0;
833.     for (y = 0; y < ROWNO; y++)
834.         for (x = 1; x < COLNO; x++) {
835.             int typ = levl[x][y].typ;
836. 
837.             if (typ == FOUNTAIN)
838.                 svl.level.flags.nfountains++;
839.             else if (typ == SINK)
840.                 svl.level.flags.nsinks++;
841.         }
842. }
843. 
844. /* clear out various globals that keep information on the current level.
845.  * some of this is only necessary for some types of levels (maze, normal,
846.  * special) but it's easier to put it all in one place than make sure
847.  * each type initializes what it needs to separately.
848.  */
849. void
850. clear_level_structures(void)
851. {
852.     static struct rm zerorm = { GLYPH_UNEXPLORED,
853.                                 0, 0, 0, 0, 0, 0, 0, 0, 0 };
854.     coordxy x, y;
855.     struct rm *lev;
856. 
857.     /* note:  normally we'd start at x=1 because map column #0 isn't used
858.        (except for placing vault guard at <0,0> when removed from the map
859.        but not from the level); explicitly reset column #0 along with the
860.        rest so that we start the new level with a completely clean slate */
861.     for (x = 0; x < COLNO; x++) {
862.         lev = &levl[x][0];
863.         for (y = 0; y < ROWNO; y++) {
864.             *lev++ = zerorm;
865.             svl.level.objects[x][y] = (struct obj *) 0;
866.             svl.level.monsters[x][y] = (struct monst *) 0;
867.         }
868.     }
869.     svl.level.objlist = (struct obj *) 0;
870.     svl.level.buriedobjlist = (struct obj *) 0;
871.     svl.level.monlist = (struct monst *) 0;
872.     svl.level.damagelist = (struct damage *) 0;
873.     svl.level.bonesinfo = (struct cemetery *) 0;
874. 
875.     svl.level.flags.nfountains = 0;
876.     svl.level.flags.nsinks = 0;
877.     svl.level.flags.has_shop = 0;
878.     svl.level.flags.has_vault = 0;
879.     svl.level.flags.has_zoo = 0;
880.     svl.level.flags.has_court = 0;
881.     svl.level.flags.has_morgue = svl.level.flags.graveyard = 0;
882.     svl.level.flags.has_beehive = 0;
883.     svl.level.flags.has_barracks = 0;
884.     svl.level.flags.has_temple = 0;
885.     svl.level.flags.has_swamp = 0;
886.     svl.level.flags.noteleport = 0;
887.     svl.level.flags.hardfloor = 0;
888.     svl.level.flags.nommap = 0;
889.     svl.level.flags.hero_memory = 1;
890.     svl.level.flags.shortsighted = 0;
891.     svl.level.flags.sokoban_rules = 0;
892.     svl.level.flags.is_maze_lev = 0;
893.     svl.level.flags.is_cavernous_lev = 0;
894.     svl.level.flags.arboreal = 0;
895.     svl.level.flags.has_town = 0;
896.     svl.level.flags.wizard_bones = 0;
897.     svl.level.flags.corrmaze = 0;
898.     svl.level.flags.temperature = In_hell(&u.uz) ? 1 : 0;
899.     svl.level.flags.rndmongen = 1;
900.     svl.level.flags.deathdrops = 1;
901.     svl.level.flags.noautosearch = 0;
902.     svl.level.flags.fumaroles = 0;
903.     svl.level.flags.stormy = 0;
904.     svl.level.flags.stasis_until = 0L;
905. 
906.     svn.nroom = 0;
907.     svr.rooms[0].hx = -1;
908.     gn.nsubroom = 0;
909.     gs.subrooms[0].hx = -1;
910.     gd.doorindex = 0;
911.     if (svd.doors_alloc) {
912.         free((genericptr_t) svd.doors);
913.         svd.doors = (coord *) 0;
914.         svd.doors_alloc = 0;
915.     }
916.     init_rect();
917.     init_vault();
918.     stairway_free_all();
919.     gm.made_branch = FALSE;
920.     clear_regions();
921.     free_exclusions();
922.     reset_xystart_size();
923.     if (gl.lev_message) {
924.         free(gl.lev_message);
925.         gl.lev_message = (char *) 0;
926.     }
927. }
928. 
929. #define ROOM_IS_FILLABLE(croom) \
930.     ((croom->rtype == OROOM || croom->rtype == THEMEROOM)       \
931.      && croom->needfill == FILL_NORMAL)
932. 
933. /* Fill a "random" room (i.e. a typical non-special room in the Dungeons of
934.    Doom) with random monsters, objects, and dungeon features.
935. 
936.    If bonus_items is TRUE, there may be an additional special item
937.    generated, depending on depth. */
938. staticfn void
939. fill_ordinary_room(
940.     struct mkroom *croom,
941.     boolean bonus_items)
942. {
943.     int trycnt = 0;
944.     coord pos;
945.     struct monst *tmonst; /* always put a web with a spider */
946.     coordxy x, y;
947.     boolean skip_chests = FALSE;
948. 
949.     if (croom->rtype != OROOM && croom->rtype != THEMEROOM)
950.         return;
951. 
952.     /* If there are subrooms, fill them now - we don't want an outer room
953.      * that's specified to be unfilled to block an inner subroom that's
954.      * specified to be filled. */
955.     for (x = 0; x < croom->nsubrooms; ++x) {
956.         struct mkroom *subroom = croom->sbrooms[x];
957. 
958.         if (!subroom) {
959.             impossible("fill_ordinary_room: Null subroom");
960.             return;
961.         }
962.         fill_ordinary_room(subroom, FALSE);
963.     }
964. 
965.     if (croom->needfill != FILL_NORMAL)
966.         return;
967. 
968.     /* put a sleeping monster inside */
969.     /* Note: monster may be on the stairs. This cannot be
970.        avoided: maybe the player fell through a trap door
971.        while a monster was on the stairs. Conclusion:
972.        we have to check for monsters on the stairs anyway. */
973. 
974.     if ((u.uhave.amulet || !rn2(3)) && somexyspace(croom, &pos)) {
975.         tmonst = makemon((struct permonst *) 0, pos.x, pos.y, MM_NOGRP);
976.         if (tmonst && tmonst->data == &mons[PM_GIANT_SPIDER]
977.             && !occupied(pos.x, pos.y))
978.             (void) maketrap(pos.x, pos.y, WEB);
979.     }
980.     /* put traps and mimics inside */
981.     x = 8 - (level_difficulty() / 6);
982.     if (x <= 1)
983.         x = 2;
984.     while (!rn2(x) && (++trycnt < 1000))
985.         mktrap(0, MKTRAP_NOFLAGS, croom, (coord *) 0);
986.     if (!rn2(3) && somexyspace(croom, &pos))
987.         (void) mkgold(0L, pos.x, pos.y);
988.     if (Is_rogue_level(&u.uz))
989.         goto skip_nonrogue;
990.     if (!rn2(10))
991.         mkfount(croom);
992.     if (!rn2(60))
993.         mksink(croom);
994.     if (!rn2(60))
995.         mkaltar(croom);
996.     x = 80 - (depth(&u.uz) * 2);
997.     if (x < 2)
998.         x = 2;
999.     if (!rn2(x))
1000.         mkgrave(croom);
1001. 
1002.     /* put statues inside */
1003.     if (!rn2(20) && somexyspace(croom, &pos))
1004.         (void) mkcorpstat(STATUE, (struct monst *) 0,
1005.                             (struct permonst *) 0, pos.x,
1006.                             pos.y, CORPSTAT_INIT);
1007. 
1008.     /*
1009.      * bonus_items means that this is the room where the bonus item
1010.      * should be placed, if there is one; but there might not be a
1011.      * bonus item on any given level.
1012.      *
1013.      * Bonus items are currently as follows:
1014.      * a) on the Mines branch level, 100% chance of a fairly filling
1015.      *    comestible;
1016.      * b) on other levels above the Oracle, 2/3 chance of a "supply
1017.      *    chest" that contains an early-game survivability item
1018.      *    (there are therefore more of these when Sokoban is deep,
1019.      *    which is intentional as those games are harder).
1020.      * This mechanism could be expanded in the future to place
1021.      * near-guaranteed items on particular levels (but, it is possible
1022.      * that no room will be given a bonus item if there is no suitable
1023.      * room to place it in, so it should not be used for plot-critical
1024.      * items).
1025.      */
1026.     if (bonus_items && somexyspace(croom, &pos)) {
1027.         branch *uz_branch = Is_branchlev(&u.uz);
1028. 
1029.         if (uz_branch && u.uz.dnum != mines_dnum
1030.             && (uz_branch->end1.dnum == mines_dnum
1031.                 || uz_branch->end2.dnum == mines_dnum)) {
1032.             (void) mksobj_at((rn2(5) < 3) ? FOOD_RATION
1033.                              : rn2(2) ? CRAM_RATION
1034.                                : LEMBAS_WAFER,
1035.                              pos.x, pos.y, TRUE, FALSE);
1036.         } else if (u.uz.dnum == oracle_level.dnum
1037.                    && u.uz.dlevel < oracle_level.dlevel && rn2(3)) {
1038.             struct obj *otmp;
1039.             int otyp, tryct = 0;
1040.             boolean cursed;
1041.             /* reverse probabilities compared to non-supply chests;
1042.                these are twice as likely to be chests than large
1043.                boxes, rather than vice versa */
1044.             struct obj *supply_chest = mksobj_at(rn2(3) ? CHEST : LARGE_BOX,
1045.                                                  pos.x, pos.y, FALSE, FALSE);
1046. 
1047.             supply_chest->olocked = !!(rn2(6));
1048. 
1049.             do {
1050.                 static const int supply_items[] = {
1051.                     POT_EXTRA_HEALING,
1052.                     POT_SPEED,
1053.                     POT_GAIN_ENERGY,
1054.                     SCR_ENCHANT_WEAPON,
1055.                     SCR_ENCHANT_ARMOR,
1056.                     SCR_CONFUSE_MONSTER,
1057.                     SCR_SCARE_MONSTER,
1058.                     WAN_DIGGING,
1059.                     SPE_HEALING,
1060.                 };
1061. 
1062.                 /* 50% this is a potion of healing */
1063.                 otyp = rn2(2) ? POT_HEALING : ROLL_FROM(supply_items);
1064.                 otmp = mksobj(otyp, TRUE, FALSE);
1065.                 if (otyp == POT_HEALING && rn2(2)) {
1066.                     otmp->quan = 2;
1067.                     otmp->owt = weight(otmp);
1068.                 }
1069.                 cursed = otmp->cursed;
1070.                 add_to_container(supply_chest, otmp); /* owt updated below */
1071. 
1072.                 ++tryct;
1073.                 if (tryct == 50) {
1074.                     impossible("couldn't generate supply chest item");
1075.                     break;
1076.                 }
1077.                 /* guarantee at least one noncursed item, with a small
1078.                    probability of more; if we generate a cursed item, it's
1079.                    added to the supply chest but we reroll for a noncursed
1080.                    item and add that too */
1081.             } while (cursed || !rn2(5));
1082. 
1083.             /* maybe put a random item into the supply chest, biased
1084.                slightly towards low-level spellbooks; avoid tools
1085.                because chests don't fit into other chests */
1086.             if (rn2(3)) {
1087.                 static const int extra_classes[] = {
1088.                     FOOD_CLASS,
1089.                     WEAPON_CLASS,
1090.                     ARMOR_CLASS,
1091.                     GEM_CLASS,
1092.                     SCROLL_CLASS,
1093.                     POTION_CLASS,
1094.                     RING_CLASS,
1095.                     SPBOOK_no_NOVEL,
1096.                     SPBOOK_no_NOVEL,
1097.                     SPBOOK_no_NOVEL
1098.                 };
1099.                 int oclass = ROLL_FROM(extra_classes);
1100. 
1101.                 otmp = mkobj(oclass, FALSE);
1102.                 if (oclass == SPBOOK_no_NOVEL) {
1103.                     int pass, maxpass = (depth(&u.uz) > 2) ? 2 : 3;
1104. 
1105.                     /* bias towards lower level by generating again
1106.                        and taking the lower-level book; do that three
1107.                        times if on level 1 or 2, twice when deeper */
1108.                     for (pass = 1; pass <= maxpass; ++pass) {
1109.                         struct obj *otmp2 = mkobj(oclass, FALSE);
1110. 
1111.                         if (objects[otmp->otyp].oc_level
1112.                             <= objects[otmp2->otyp].oc_level) {
1113.                             dealloc_obj(otmp2);
1114.                         } else {
1115.                             dealloc_obj(otmp);
1116.                             otmp = otmp2;
1117.                         }
1118.                     }
1119.                 }
1120.                 add_to_container(supply_chest, otmp); /* owt updated below */
1121.             }
1122. 
1123.             /* add_to_container() doesn't update the container's weight */
1124.             supply_chest->owt = weight(supply_chest);
1125. 
1126.             skip_chests = TRUE; /* don't want a second chest in this room */
1127.         }
1128.     }
1129. 
1130. 
1131.     /* put box/chest inside;
1132.      *  40% chance for at least 1 box, regardless of number
1133.      *  of rooms; about 5 - 7.5% for 2 boxes, least likely
1134.      *  when few rooms; chance for 3 or more is negligible.
1135.      */
1136.     /*assert(svn.nroom > 0); // must be true because we're filling a room*/
1137.     if (!skip_chests && !rn2(svn.nroom * 5 / 2) && somexyspace(croom, &pos))
1138.         (void) mksobj_at(rn2(3) ? LARGE_BOX : CHEST,
1139.                          pos.x, pos.y, TRUE, FALSE);
1140. 
1141.     /* maybe make some graffiti */
1142.     if (!rn2(27 + 3 * abs(depth(&u.uz)))) {
1143.         char buf[BUFSZ], pristinebuf[BUFSZ];
1144.         const char *mesg = random_engraving(buf, pristinebuf);
1145. 
1146.         if (mesg) {
1147.             do {
1148.                 (void) somexyspace(croom, &pos);
1149.                 x = pos.x;
1150.                 y = pos.y;
1151.             } while (levl[x][y].typ != ROOM && !rn2(40));
1152.             if (levl[x][y].typ == ROOM)
1153.                 make_engr_at(x, y, mesg, pristinebuf, 0L, MARK);
1154.         }
1155.     }
1156. 
1157.  skip_nonrogue:
1158.     if (!rn2(3) && somexyspace(croom, &pos)) {
1159.         (void) mkobj_at(RANDOM_CLASS, pos.x, pos.y, TRUE);
1160.         trycnt = 0;
1161.         while (!rn2(5)) {
1162.             if (++trycnt > 100) {
1163.                 impossible("trycnt overflow4");
1164.                 break;
1165.             }
1166.             if (somexyspace(croom, &pos)) {
1167.                 (void) mkobj_at(RANDOM_CLASS, pos.x, pos.y, TRUE);
1168.             }
1169.         }
1170.     }
1171. }
1172. 
1173. staticfn void
1174. themerooms_post_level_generate(void)
1175. {
1176.     lua_State *themes = (lua_State *) gl.luathemes[u.uz.dnum];
1177. 
1178.      /* themes should already be loaded by makerooms();
1179.       * if not, we don't run this either */
1180.     if (!themes)
1181.         return;
1182. 
1183.     reset_xystart_size();
1184.     iflags.in_lua = gi.in_mk_themerooms = TRUE;
1185.     gt.themeroom_failed = FALSE;
1186.     lua_getglobal(themes, "post_level_generate");
1187.     nhl_pcall_handle(themes, 0, 0, "post_level_generate", NHLpa_panic);
1188.     iflags.in_lua = gi.in_mk_themerooms = FALSE;
1189. 
1190.     wallification(1, 0, COLNO - 1, ROWNO - 1);
1191.     if (gc.coder)
1192.         free(gc.coder), gc.coder = NULL;
1193.     lua_gc(themes, LUA_GCCOLLECT);
1194. }
1195. 
1196. /* if x,y is door, does it open into solid terrain */
1197. staticfn boolean
1198. chk_okdoor(coordxy x, coordxy y)
1199. {
1200.     if (IS_DOOR(levl[x][y].typ)) {
1201.         if (levl[x][y].horizontal) {
1202.             if ((isok(x, y-1) && (levl[x][y-1].typ > TREE))
1203.                 && (isok(x, y+1) && (levl[x][y+1].typ <= TREE)))
1204.                 return FALSE;
1205.             if ((isok(x, y-1) && (levl[x][y-1].typ <= TREE))
1206.                 && (isok(x, y+1) && (levl[x][y+1].typ > TREE)))
1207.                 return FALSE;
1208.         } else {
1209.             if ((isok(x-1, y) && (levl[x-1][y].typ > TREE))
1210.                 && (isok(x+1, y) && (levl[x+1][y].typ <= TREE)))
1211.                 return FALSE;
1212.             if ((isok(x-1, y) && (levl[x-1][y].typ <= TREE))
1213.                 && (isok(x+1, y) && (levl[x+1][y].typ > TREE)))
1214.                 return FALSE;
1215.         }
1216.         return TRUE;
1217.     }
1218.     return TRUE;
1219. }
1220. 
1221. /* check mklev created level sanity */
1222. staticfn void
1223. mklev_sanity_check(void)
1224. {
1225.     coordxy x, y;
1226.     int i;
1227.     int rmno = -1;
1228. 
1229.     if (!(iflags.sanity_check || iflags.debug_fuzzer))
1230.         return;
1231. 
1232.     for (y = 0; y < ROWNO; y++) {
1233.         for (x = 1; x < COLNO; x++) {
1234.             if (!chk_okdoor(x,y))
1235.                 impossible("levl[%i][%i] door not ok", x, y);
1236.         }
1237.     }
1238. 
1239.     for (i = 0; i < svn.nroom; i++) {
1240.         if (!svr.rooms[i].needjoining)
1241.             continue;
1242.         if (rmno == -1)
1243.             rmno = gs.smeq[i];
1244.         if (rmno != -1 && gs.smeq[i] != rmno)
1245.             impossible("room %i not connected?", i);
1246.     }
1247. }
1248. 
1249. 
1250. staticfn void
1251. makelevel(void)
1252. {
1253.     struct mkroom *croom;
1254.     branch *branchp;
1255.     stairway *prevstairs;
1256.     int room_threshold;
1257.     s_level *slev;
1258.     int i;
1259. 
1260.     if (wiz1_level.dlevel == 0) {
1261.         impossible("makelevel() called when dungeon not yet initialized.");
1262.         init_dungeons();
1263.     }
1264.     oinit(); /* assign level dependent obj probabilities */
1265.     clear_level_structures();
1266. 
1267.     slev = Is_special(&u.uz);
1268.     /* check for special levels */
1269.     if (slev && !Is_rogue_level(&u.uz)) {
1270.         makemaz(slev->proto);
1271.     } else if (svd.dungeons[u.uz.dnum].proto[0]) {
1272.         makemaz("");
1273.     } else if (svd.dungeons[u.uz.dnum].fill_lvl[0]) {
1274.         makemaz(svd.dungeons[u.uz.dnum].fill_lvl);
1275.     } else if (In_quest(&u.uz)) {
1276.         char fillname[9];
1277.         s_level *loc_lev;
1278. 
1279.         Sprintf(fillname, "%s-loca", gu.urole.filecode);
1280.         loc_lev = find_level(fillname);
1281. 
1282.         Sprintf(fillname, "%s-fil", gu.urole.filecode);
1283.         Strcat(fillname,
1284.                 (u.uz.dlevel < loc_lev->dlevel.dlevel) ? "a" : "b");
1285.         makemaz(fillname);
1286.     } else if (In_hell(&u.uz)
1287.                 || (rn2(5) && u.uz.dnum == medusa_level.dnum
1288.                     && depth(&u.uz) > depth(&medusa_level))) {
1289.         makemaz("");
1290.     } else {
1291.         /* otherwise, fall through - it's a "regular" level. */
1292.         int u_depth = depth(&u.uz);
1293. 
1294.         if (Is_rogue_level(&u.uz)) {
1295.             makeroguerooms();
1296.             makerogueghost();
1297.         } else {
1298.             makerooms();
1299.         }
1300.         assert(svn.nroom > 0);
1301.         sort_rooms();
1302. 
1303.         generate_stairs(); /* up and down stairs */
1304. 
1305.         branchp = Is_branchlev(&u.uz);    /* possible dungeon branch */
1306.         room_threshold = branchp ? 4 : 3; /* minimum number of rooms needed
1307.                                             to allow a random special room */
1308.         if (Is_rogue_level(&u.uz))
1309.             goto skip0;
1310.         makecorridors();
1311.         make_niches();
1312. 
1313.         mklev_sanity_check();
1314. 
1315.         /* make a secret treasure vault, not connected to the rest */
1316.         if (do_vault()) {
1317.             coordxy w, h;
1318. 
1319.             debugpline0("trying to make a vault...");
1320.             w = 1;
1321.             h = 1;
1322.             if (check_room(&gv.vault_x, &w, &gv.vault_y, &h, TRUE)) {
1323.  fill_vault:
1324.                 add_room(gv.vault_x, gv.vault_y,
1325.                          gv.vault_x + w, gv.vault_y + h,
1326.                          TRUE, VAULT, FALSE);
1327.                 svl.level.flags.has_vault = 1;
1328.                 ++room_threshold;
1329.                 svr.rooms[svn.nroom - 1].needfill = FILL_NORMAL;
1330.                 fill_special_room(&svr.rooms[svn.nroom - 1]);
1331.                 mk_knox_portal(gv.vault_x + w, gv.vault_y + h);
1332.                 if (!svl.level.flags.noteleport && !rn2(3))
1333.                     makevtele();
1334.             } else if (rnd_rect() && create_vault()) {
1335.                 gv.vault_x = svr.rooms[svn.nroom].lx;
1336.                 gv.vault_y = svr.rooms[svn.nroom].ly;
1337.                 if (check_room(&gv.vault_x, &w, &gv.vault_y, &h, TRUE))
1338.                     goto fill_vault;
1339.                 else
1340.                     svr.rooms[svn.nroom].hx = -1;
1341.             }
1342.         }
1343. 
1344.         /* make up to 1 special room, with type dependent on depth;
1345.            note that mkroom doesn't guarantee a room gets created, and that
1346.            this step only sets the room's rtype - it doesn't fill it yet. */
1347.         if (wizard && nh_getenv("SHOPTYPE"))
1348.             do_mkroom(SHOPBASE);
1349.         else if (u_depth > 1 && u_depth < depth(&medusa_level)
1350.                  && svn.nroom >= room_threshold && rn2(u_depth) < 3)
1351.             do_mkroom(SHOPBASE);
1352.         else if (u_depth > 4 && !rn2(6))
1353.             do_mkroom(COURT);
1354.         else if (u_depth > 5 && !rn2(8)
1355.                  && !(svm.mvitals[PM_LEPRECHAUN].mvflags & G_GONE))
1356.             do_mkroom(LEPREHALL);
1357.         else if (u_depth > 6 && !rn2(7))
1358.             do_mkroom(ZOO);
1359.         else if (u_depth > 8 && !rn2(5))
1360.             do_mkroom(TEMPLE);
1361.         else if (u_depth > 9 && !rn2(5)
1362.                  && !(svm.mvitals[PM_KILLER_BEE].mvflags & G_GONE))
1363.             do_mkroom(BEEHIVE);
1364.         else if (u_depth > 11 && !rn2(6))
1365.             do_mkroom(MORGUE);
1366.         else if (u_depth > 12 && !rn2(8) && antholemon())
1367.             do_mkroom(ANTHOLE);
1368.         else if (u_depth > 14 && !rn2(4)
1369.                  && !(svm.mvitals[PM_SOLDIER].mvflags & G_GONE))
1370.             do_mkroom(BARRACKS);
1371.         else if (u_depth > 15 && !rn2(6))
1372.             do_mkroom(SWAMP);
1373.         else if (u_depth > 16 && !rn2(8)
1374.                  && !(svm.mvitals[PM_COCKATRICE].mvflags & G_GONE))
1375.             do_mkroom(COCKNEST);
1376. 
1377.  skip0:
1378.         prevstairs = gs.stairs; /* used to test for place_branch() success */
1379.         /* Place multi-dungeon branch. */
1380.         place_branch(branchp, 0, 0);
1381. 
1382.         /* for main dungeon level 1, the stairs up where the hero starts
1383.            are branch stairs; treat them as if hero had just come down
1384.            them by marking them as having been traversed; most recently
1385.            created stairway is held in 'gs.stairs' */
1386.         if (u.uz.dnum == 0 && u.uz.dlevel == 1 && gs.stairs != prevstairs)
1387.             gs.stairs->u_traversed = TRUE;
1388. 
1389.         /* some levels have specially generated items in ordinary
1390.            rooms (intended to be indistinguishable from the normally
1391.            generated items); work out which room these will be placed in */
1392.         int fillable_room_count = 0;
1393.         for (croom = svr.rooms; croom->hx > 0; croom++) {
1394.             if (ROOM_IS_FILLABLE(croom))
1395.                 fillable_room_count++;
1396.         }
1397.         /* choose a random fillable room to be the one that gets the
1398.            bonus items, if there are any; if there aren't any we don't
1399.            generate the bonus items (but levels with no fillable rooms
1400.            typically don't have any bonus items to generate anyway) */
1401.         int bonus_item_room_countdown = fillable_room_count
1402.                                         ? rn2(fillable_room_count) : -1;
1403. 
1404.         /* for each room: put things inside */
1405.         for (croom = svr.rooms; croom->hx > 0; croom++) {
1406.             boolean fillable = ROOM_IS_FILLABLE(croom);
1407. 
1408.             fill_ordinary_room(croom,
1409.                                fillable && bonus_item_room_countdown == 0);
1410.             if (fillable)
1411.                 --bonus_item_room_countdown;
1412.         }
1413.     }
1414.     /* Fill all special rooms now, regardless of whether this is a special
1415.      * level, proto level, or ordinary level. */
1416.     for (i = 0; i < svn.nroom; ++i) {
1417.         fill_special_room(&svr.rooms[i]);
1418.     }
1419. 
1420.     themerooms_post_level_generate();
1421. 
1422.     if (gl.luacore && nhcb_counts[NHCB_LVL_ENTER]) {
1423.         lua_getglobal(gl.luacore, "nh_callback_run");
1424.         lua_pushstring(gl.luacore, nhcb_name[NHCB_LVL_ENTER]);
1425.         nhl_pcall_handle(gl.luacore, 1, 0, "makelevel", NHLpa_panic);
1426.         lua_settop(gl.luacore, 0);
1427.     }
1428. }
1429. 
1430. /* return TRUE if water location at (x,y) should have kelp. */
1431. staticfn boolean
1432. water_has_kelp(coordxy x, coordxy y, int kelp_pool, int kelp_moat)
1433. {
1434.     if ((kelp_pool && (levl[x][y].typ == POOL
1435.                        || (levl[x][y].typ == WATER && !Is_waterlevel(&u.uz)))
1436.          && !rn2(kelp_pool))
1437.         || (kelp_moat && levl[x][y].typ == MOAT && !rn2(kelp_moat)))
1438.         return TRUE;
1439.     return FALSE;
1440. }
1441. 
1442. /*
1443.  *      Place deposits of minerals (gold and misc gems) in the stone
1444.  *      surrounding the rooms on the map.
1445.  *      Also place kelp in water.
1446.  *      mineralize(-1, -1, -1, -1, FALSE); => "default" behavior
1447.  */
1448. void
1449. mineralize(int kelp_pool, int kelp_moat, int goldprob, int gemprob,
1450.            boolean skip_lvl_checks)
1451. {
1452.     s_level *sp;
1453.     struct obj *otmp;
1454.     coordxy x, y;
1455.     int cnt;
1456. 
1457.     if (kelp_pool < 0)
1458.         kelp_pool = 10;
1459.     if (kelp_moat < 0)
1460.         kelp_moat = 30;
1461. 
1462.     /* Place kelp, except on the plane of water */
1463.     if (!skip_lvl_checks && In_endgame(&u.uz))
1464.         return;
1465.     for (x = 2; x < (COLNO - 2); x++)
1466.         for (y = 1; y < (ROWNO - 1); y++)
1467.             if (water_has_kelp(x, y, kelp_pool, kelp_moat))
1468.                 (void) mksobj_at(KELP_FROND, x, y, TRUE, FALSE);
1469. 
1470.     /* determine if it is even allowed;
1471.        almost all special levels are excluded */
1472.     if (!skip_lvl_checks
1473.         && (In_hell(&u.uz) || In_V_tower(&u.uz) || Is_rogue_level(&u.uz)
1474.             || svl.level.flags.arboreal
1475.             || ((sp = Is_special(&u.uz)) != 0 && !Is_oracle_level(&u.uz)
1476.                 && (!In_mines(&u.uz) || sp->flags.town))))
1477.         return;
1478. 
1479.     /* basic level-related probabilities */
1480.     if (goldprob < 0)
1481.         goldprob = 20 + depth(&u.uz) / 3;
1482.     if (gemprob < 0)
1483.         gemprob = goldprob / 4;
1484. 
1485.     /* mines have ***MORE*** goodies - otherwise why mine? */
1486.     if (!skip_lvl_checks) {
1487.         if (In_mines(&u.uz)) {
1488.             goldprob *= 2;
1489.             gemprob *= 3;
1490.         } else if (In_quest(&u.uz)) {
1491.             goldprob /= 4;
1492.             gemprob /= 6;
1493.         }
1494.     }
1495. 
1496.     /*
1497.      * Seed rock areas with gold and/or gems.
1498.      * We use fairly low level object handling to avoid unnecessary
1499.      * overhead from placing things in the floor chain prior to burial.
1500.      */
1501.     for (x = 2; x < (COLNO - 2); x++)
1502.         for (y = 1; y < (ROWNO - 1); y++)
1503.             if (levl[x][y + 1].typ != STONE) { /* <x,y> spot not eligible */
1504.                 y += 2; /* next two spots aren't eligible either */
1505.             } else if (levl[x][y].typ != STONE) { /* this spot not eligible */
1506.                 y += 1; /* next spot isn't eligible either */
1507.             } else if (!(levl[x][y].wall_info & W_NONDIGGABLE)
1508.                        && levl[x][y - 1].typ == STONE
1509.                        && levl[x + 1][y - 1].typ == STONE
1510.                        && levl[x - 1][y - 1].typ == STONE
1511.                        && levl[x + 1][y].typ == STONE
1512.                        && levl[x - 1][y].typ == STONE
1513.                        && levl[x + 1][y + 1].typ == STONE
1514.                        && levl[x - 1][y + 1].typ == STONE) {
1515.                 if (rn2(1000) < goldprob) {
1516.                     if ((otmp = mksobj(GOLD_PIECE, FALSE, FALSE)) != 0) {
1517.                         otmp->ox = x, otmp->oy = y;
1518.                         otmp->quan = 1L + rnd(goldprob * 3);
1519.                         otmp->owt = weight(otmp);
1520.                         if (!rn2(3))
1521.                             add_to_buried(otmp);
1522.                         else
1523.                             place_object(otmp, x, y);
1524.                     }
1525.                 }
1526.                 if (rn2(1000) < gemprob) {
1527.                     for (cnt = rnd(2 + dunlev(&u.uz) / 3); cnt > 0; cnt--)
1528.                         if ((otmp = mkobj(GEM_CLASS, FALSE)) != 0) {
1529.                             if (otmp->otyp == ROCK) {
1530.                                 dealloc_obj(otmp); /* discard it */
1531.                             } else {
1532.                                 otmp->ox = x, otmp->oy = y;
1533.                                 if (!rn2(3))
1534.                                     add_to_buried(otmp);
1535.                                 else
1536.                                     place_object(otmp, x, y);
1537.                             }
1538.                         }
1539.                 }
1540.             }
1541. }
1542. 
1543. void
1544. level_finalize_topology(void)
1545. {
1546.     struct mkroom *croom;
1547.     int ridx;
1548. 
1549.     bound_digging();
1550.     mineralize(-1, -1, -1, -1, FALSE);
1551.     gi.in_mklev = FALSE;
1552.     /* avoid coordinates in future lua-loads for this level being thrown off
1553.      * because xstart and ystart aren't saved with the level and will be 0
1554.      * after leaving and returning */
1555.     gx.xstart = gy.ystart = 0;
1556.     /* has_morgue gets cleared once morgue is entered; graveyard stays
1557.        set (graveyard might already be set even when has_morgue is clear
1558.        [see fixup_special()], so don't update it unconditionally) */
1559.     if (svl.level.flags.has_morgue)
1560.         svl.level.flags.graveyard = 1;
1561.     if (!svl.level.flags.is_maze_lev) {
1562.         for (croom = &svr.rooms[0]; croom != &svr.rooms[svn.nroom]; croom++)
1563. #ifdef SPECIALIZATION
1564.             topologize(croom, FALSE);
1565. #else
1566.             topologize(croom);
1567. #endif
1568.     }
1569.     set_wall_state();
1570.     /* for many room types, svr.rooms[].rtype is zeroed once the room has been
1571.        entered; svr.rooms[].orig_rtype always retains original rtype value */
1572.     for (ridx = 0; ridx < SIZE(svr.rooms); ridx++)
1573.         svr.rooms[ridx].orig_rtype = svr.rooms[ridx].rtype;
1574. }
1575. 
1576. void
1577. mklev(void)
1578. {
1579.     reseed_random(rn2);
1580.     reseed_random(rn2_on_display_rng);
1581. 
1582.     init_mapseen(&u.uz);
1583.     if (getbones())
1584.         return;
1585. 
1586.     gi.in_mklev = TRUE;
1587.     makelevel();
1588. 
1589.     level_finalize_topology();
1590. 
1591.     reseed_random(rn2);
1592.     reseed_random(rn2_on_display_rng);
1593. }
1594. 
1595. void
1596. #ifdef SPECIALIZATION
1597. topologize(struct mkroom *croom, boolean do_ordinary)
1598. #else
1599. topologize(struct mkroom *croom)
1600. #endif
1601. {
1602.     coordxy x, y;
1603.     int roomno = (int) ((croom - svr.rooms) + ROOMOFFSET);
1604.     coordxy lowx = croom->lx, lowy = croom->ly;
1605.     coordxy hix = croom->hx, hiy = croom->hy;
1606. #ifdef SPECIALIZATION
1607.     schar rtype = croom->rtype;
1608. #endif
1609.     int subindex, nsubrooms = croom->nsubrooms;
1610. 
1611.     /* skip the room if already done; i.e. a shop handled out of order */
1612.     /* also skip if this is non-rectangular (it _must_ be done already) */
1613.     if ((int) levl[lowx][lowy].roomno == roomno || croom->irregular)
1614.         return;
1615. #ifdef SPECIALIZATION
1616.     if (Is_rogue_level(&u.uz))
1617.         do_ordinary = TRUE; /* vision routine helper */
1618.     if ((rtype != OROOM) || do_ordinary)
1619. #endif
1620.         {
1621.         /* do innards first */
1622.         for (x = lowx; x <= hix; x++)
1623.             for (y = lowy; y <= hiy; y++)
1624. #ifdef SPECIALIZATION
1625.                 if (rtype == OROOM)
1626.                     levl[x][y].roomno = NO_ROOM;
1627.                 else
1628. #endif
1629.                     levl[x][y].roomno = roomno;
1630.         /* top and bottom edges */
1631.         for (x = lowx - 1; x <= hix + 1; x++)
1632.             for (y = lowy - 1; y <= hiy + 1; y += (hiy - lowy + 2)) {
1633.                 levl[x][y].edge = 1;
1634.                 if (levl[x][y].roomno)
1635.                     levl[x][y].roomno = SHARED;
1636.                 else
1637.                     levl[x][y].roomno = roomno;
1638.             }
1639.         /* sides */
1640.         for (x = lowx - 1; x <= hix + 1; x += (hix - lowx + 2))
1641.             for (y = lowy; y <= hiy; y++) {
1642.                 levl[x][y].edge = 1;
1643.                 if (levl[x][y].roomno)
1644.                     levl[x][y].roomno = SHARED;
1645.                 else
1646.                     levl[x][y].roomno = roomno;
1647.             }
1648.     }
1649.     /* gs.subrooms */
1650.     for (subindex = 0; subindex < nsubrooms; subindex++)
1651. #ifdef SPECIALIZATION
1652.         topologize(croom->sbrooms[subindex], (boolean) (rtype != OROOM));
1653. #else
1654.         topologize(croom->sbrooms[subindex]);
1655. #endif
1656. }
1657. 
1658. /* Find an unused room for a branch location. */
1659. staticfn struct mkroom *
1660. find_branch_room(coord *mp)
1661. {
1662.     struct mkroom *croom = 0;
1663. 
1664.     if (svn.nroom == 0) {
1665.         mazexy(mp); /* already verifies location */
1666.     } else {
1667.         croom = generate_stairs_find_room();
1668.         assert(croom != NULL); /* Null iff nroom==0 which won't get here */
1669.         if (!somexyspace(croom, mp))
1670.             impossible("Can't place branch!");
1671.     }
1672.     return croom;
1673. }
1674. 
1675. /* Find the room for (x,y).  Return null if not in a room. */
1676. staticfn struct mkroom *
1677. pos_to_room(coordxy x, coordxy y)
1678. {
1679.     int i;
1680.     struct mkroom *curr;
1681. 
1682.     for (curr = svr.rooms, i = 0; i < svn.nroom; curr++, i++)
1683.         if (inside_room(curr, x, y))
1684.             return curr;
1685.     ;
1686.     return (struct mkroom *) 0;
1687. }
1688. 
1689. /* If given a branch, randomly place a special stair or portal. */
1690. void
1691. place_branch(
1692.     branch *br,       /* branch to place */
1693.     coordxy x, coordxy y) /* location */
1694. {
1695.     coord m = {0};
1696.     d_level *dest;
1697.     boolean make_stairs;
1698. 
1699.     /*
1700.      * Return immediately if there is no branch to make or we have
1701.      * already made one.  This routine can be called twice when
1702.      * a special level is loaded that specifies an SSTAIR location
1703.      * as a favored spot for a branch.
1704.      */
1705.     if (!br || gm.made_branch)
1706.         return;
1707. 
1708.     if (!x) { /* find random coordinates for branch */
1709.         /* br_room = find_branch_room(&m); */
1710.         (void) find_branch_room(&m);  /* sets m via mazexy() or somexy() */
1711.         x = m.x;
1712.         y = m.y;
1713.     } else {
1714.         (void) pos_to_room(x, y);
1715.     }
1716. 
1717.     if (on_level(&br->end1, &u.uz)) {
1718.         /* we're on end1 */
1719.         make_stairs = br->type != BR_NO_END1;
1720.         dest = &br->end2;
1721.     } else {
1722.         /* we're on end2 */
1723.         make_stairs = br->type != BR_NO_END2;
1724.         dest = &br->end1;
1725.     }
1726. 
1727.     if (br->type == BR_PORTAL) {
1728.         if (iflags.debug_fuzzer && (u.ucamefrom.dnum || u.ucamefrom.dlevel))
1729.             mkportal(x, y, u.ucamefrom.dnum, u.ucamefrom.dlevel);
1730.         else
1731.             mkportal(x, y, dest->dnum, dest->dlevel);
1732.     } else if (make_stairs) {
1733.         boolean goes_up = on_level(&br->end1, &u.uz) ? br->end1_up
1734.                                                      : !br->end1_up;
1735. 
1736.         stairway_add(x, y, goes_up, FALSE, dest);
1737.         (void) set_levltyp(x, y, STAIRS);
1738.         levl[x][y].ladder = goes_up ? LA_UP : LA_DOWN;
1739.     }
1740.     /*
1741.      * Set made_branch to TRUE even if we didn't make a stairwell (i.e.
1742.      * make_stairs is false) since there is currently only one branch
1743.      * per level, if we failed once, we're going to fail again on the
1744.      * next call.
1745.      */
1746.     gm.made_branch = TRUE;
1747. }
1748. 
1749. staticfn boolean
1750. bydoor(coordxy x, coordxy y)
1751. {
1752.     int typ;
1753. 
1754.     if (isok(x + 1, y)) {
1755.         typ = levl[x + 1][y].typ;
1756.         if (IS_DOOR(typ) || typ == SDOOR)
1757.             return TRUE;
1758.     }
1759.     if (isok(x - 1, y)) {
1760.         typ = levl[x - 1][y].typ;
1761.         if (IS_DOOR(typ) || typ == SDOOR)
1762.             return TRUE;
1763.     }
1764.     if (isok(x, y + 1)) {
1765.         typ = levl[x][y + 1].typ;
1766.         if (IS_DOOR(typ) || typ == SDOOR)
1767.             return TRUE;
1768.     }
1769.     if (isok(x, y - 1)) {
1770.         typ = levl[x][y - 1].typ;
1771.         if (IS_DOOR(typ) || typ == SDOOR)
1772.             return TRUE;
1773.     }
1774.     return FALSE;
1775. }
1776. 
1777. /* see whether it is allowable to create a door at [x,y] */
1778. int
1779. okdoor(coordxy x, coordxy y)
1780. {
1781.     boolean near_door = bydoor(x, y);
1782. 
1783.     return ((levl[x][y].typ == HWALL || levl[x][y].typ == VWALL)
1784.             && ((isok(x - 1, y) && !IS_OBSTRUCTED(levl[x - 1][y].typ))
1785.                 || (isok(x + 1, y) && !IS_OBSTRUCTED(levl[x + 1][y].typ))
1786.                 || (isok(x, y - 1) && !IS_OBSTRUCTED(levl[x][y - 1].typ))
1787.                 || (isok(x, y + 1) && !IS_OBSTRUCTED(levl[x][y + 1].typ)))
1788.             && !near_door);
1789. }
1790. 
1791. /* do we want a secret door/corridor? */
1792. boolean
1793. maybe_sdoor(int chance)
1794. {
1795.     return (depth(&u.uz) > 2) && !rn2(max(2, chance));
1796. }
1797. 
1798. /* create a door at x,y in room aroom */
1799. void
1800. dodoor(coordxy x, coordxy y, struct mkroom *aroom)
1801. {
1802.     dosdoor(x, y, aroom, maybe_sdoor(8) ? SDOOR : DOOR);
1803. }
1804. 
1805. boolean
1806. occupied(coordxy x, coordxy y)
1807. {
1808.     return (boolean) (t_at(x, y) || IS_FURNITURE(levl[x][y].typ)
1809.                       || is_lava(x, y) || is_pool(x, y)
1810.                       || invocation_pos(x, y));
1811. }
1812. 
1813. /* generate a corpse and some items on top of a trap */
1814. staticfn void
1815. mktrap_victim(struct trap *ttmp)
1816. {
1817.     /* Object generated by the trap; initially NULL, stays NULL if
1818.        the trap doesn't generate objects. */
1819.     struct obj *otmp = NULL;
1820.     int victim_mnum; /* race of the victim */
1821.     unsigned lvl = level_difficulty();
1822.     int kind = ttmp->ttyp;
1823.     coordxy x = ttmp->tx, y = ttmp->ty;
1824. 
1825.     assert(x > 0 && x < COLNO && y >= 0 && y < ROWNO);
1826.     /* Not all trap types have special handling here; only the ones
1827.        that kill in a specific way that's obvious after the fact. */
1828.     switch (kind) {
1829.     case ARROW_TRAP:
1830.         otmp = mksobj(ARROW, TRUE, FALSE);
1831.         otmp->opoisoned = 0;
1832.         /* don't adjust the quantity; maybe the trap shot multiple
1833.            times, there was an untrapping attempt, etc... */
1834.         break;
1835.     case DART_TRAP:
1836.         otmp = mksobj(DART, TRUE, FALSE);
1837.         break;
1838.     case ROCKTRAP:
1839.         otmp = mksobj(ROCK, TRUE, FALSE);
1840.         break;
1841.     default:
1842.         /* no item dropped by the trap */
1843.         break;
1844.     }
1845.     if (otmp) {
1846.         place_object(otmp, x, y);
1847.     }
1848. 
1849.     /* now otmp is reused for other items we're placing */
1850. 
1851.     /* Place a random possession. This could be a weapon, tool,
1852.        food, or gem, i.e. the item classes that are typically
1853.        nonmagical and not worthless. */
1854.     do {
1855.         int poss_class = RANDOM_CLASS; /* init => lint suppression */
1856. 
1857.         switch (rn2(4)) {
1858.         case 0:
1859.             poss_class = WEAPON_CLASS;
1860.             break;
1861.         case 1:
1862.             poss_class = TOOL_CLASS;
1863.             break;
1864.         case 2:
1865.             poss_class = FOOD_CLASS;
1866.             break;
1867.         case 3:
1868.             poss_class = GEM_CLASS;
1869.             break;
1870.         }
1871. 
1872.         /* these items are always cursed, both for flavour (owned
1873.            by a dead adventurer, bones-pile-style) and for balance
1874.            (less useful to use, and encourage pets to avoid the trap) */
1875.         otmp = mkobj(poss_class, FALSE);
1876.         curse(otmp);
1877.         /* for mktrap_victim(), PIT is actually an exploded LANDMINE */
1878.         if (ttmp->ttyp == PIT && breaktest(otmp)) {
1879.             /* landmine: if fragile object has been created, destroy it;
1880.                don't worry about non-empty containers--they aren't
1881.                breakable--nor about breakable contents of such */
1882.             dealloc_obj(otmp);
1883.         } else {
1884.             place_object(otmp, x, y);
1885.         }
1886. 
1887.         /* 20% chance of placing an additional item, recursively */
1888.     } while (!rn2(5));
1889. 
1890.     /* Place a corpse. */
1891.     switch (rn2(15)) {
1892.     case 0:
1893.         /* elf corpses are the rarest as they're the most useful */
1894.         victim_mnum = PM_ELF;
1895.         /* elven adventurers get sleep resistance early; so don't
1896.            generate elf corpses on sleeping gas traps unless a)
1897.            we're on dlvl 2 (1 is impossible) and b) we pass a coin
1898.            flip */
1899.         if (kind == SLP_GAS_TRAP && !(lvl <= 2 && rn2(2)))
1900.             victim_mnum = PM_HUMAN;
1901.         break;
1902.     case 1: case 2:
1903.         victim_mnum = PM_DWARF;
1904.         break;
1905.     case 3: case 4: case 5:
1906.         victim_mnum = PM_ORC;
1907.         break;
1908.     case 6: case 7: case 8: case 9:
1909.         /* more common as they could have come from the Mines */
1910.         victim_mnum = PM_GNOME;
1911.         /* 10% chance of a candle too */
1912.         if (!rn2(10)) {
1913.             otmp = mksobj(rn2(4) ? TALLOW_CANDLE : WAX_CANDLE, TRUE, FALSE);
1914.             otmp->quan = 1;
1915.             otmp->owt = weight(otmp);
1916.             curse(otmp);
1917.             place_object(otmp, x, y);
1918.             if (!levl[x][y].lit)
1919.                 begin_burn(otmp, FALSE);
1920.         }
1921.         break;
1922.     default:
1923.         /* human is the most common result */
1924.         victim_mnum = PM_HUMAN;
1925.         break;
1926.     }
1927.     /* PM_HUMAN is a placeholder monster primarily used for zombie, mummy,
1928.        and vampire corpses; usually change it into a fake player monster
1929.        instead (always human); no role-specific equipment is provided */
1930.     if (victim_mnum == PM_HUMAN && rn2(25))
1931.         victim_mnum = rn1(PM_WIZARD - PM_ARCHEOLOGIST, PM_ARCHEOLOGIST);
1932.     otmp = mkcorpstat(CORPSE, NULL, &mons[victim_mnum], x, y, CORPSTAT_INIT);
1933.     otmp->age -= (TAINT_AGE + 1); /* died too long ago to safely eat */
1934. }
1935. 
1936. /* pick a random trap type, return NO_TRAP if "too hard" */
1937. staticfn int
1938. traptype_rnd(unsigned mktrapflags)
1939. {
1940.     unsigned lvl = level_difficulty();
1941.     int kind = rnd(TRAPNUM - 1);
1942. 
1943.     switch (kind) {
1944.         /* these are controlled by the feature or object they guard,
1945.            not by the map so mustn't be created on it */
1946.     case TRAPPED_DOOR:
1947.     case TRAPPED_CHEST:
1948.         kind = NO_TRAP;
1949.         break;
1950.         /* these can have a random location but can't be generated
1951.            randomly */
1952.     case MAGIC_PORTAL:
1953.     case VIBRATING_SQUARE:
1954.         kind = NO_TRAP;
1955.         break;
1956.     case ROLLING_BOULDER_TRAP:
1957.     case SLP_GAS_TRAP:
1958.         if (lvl < 2)
1959.             kind = NO_TRAP;
1960.         break;
1961.     case LEVEL_TELEP:
1962.         if (lvl < 5 || svl.level.flags.noteleport
1963.             || single_level_branch(&u.uz))
1964.             kind = NO_TRAP;
1965.         break;
1966.     case SPIKED_PIT:
1967.         if (lvl < 5)
1968.             kind = NO_TRAP;
1969.         break;
1970.     case LANDMINE:
1971.         if (lvl < 6)
1972.             kind = NO_TRAP;
1973.         break;
1974.     case WEB:
1975.         if (lvl < 7 && !(mktrapflags & MKTRAP_NOSPIDERONWEB))
1976.             kind = NO_TRAP;
1977.         break;
1978.     case STATUE_TRAP:
1979.     case POLY_TRAP:
1980.         if (lvl < 8)
1981.             kind = NO_TRAP;
1982.         break;
1983.     case FIRE_TRAP:
1984.         if (!Inhell)
1985.             kind = NO_TRAP;
1986.         break;
1987.     case TELEP_TRAP:
1988.         if (svl.level.flags.noteleport)
1989.             kind = NO_TRAP;
1990.         break;
1991.     case HOLE:
1992.         /* make these much less often than other traps */
1993.         if (rn2(7))
1994.             kind = NO_TRAP;
1995.         break;
1996.     }
1997.     return kind;
1998. }
1999. 
2000. /* random trap type for the Rogue level */
2001. staticfn int
2002. traptype_roguelvl(void)
2003. {
2004.     int kind;
2005. 
2006.     switch (rn2(7)) {
2007.     default:
2008.         kind = BEAR_TRAP;
2009.         break; /* 0 */
2010.     case 1:
2011.         kind = ARROW_TRAP;
2012.         break;
2013.     case 2:
2014.         kind = DART_TRAP;
2015.         break;
2016.     case 3:
2017.         kind = TRAPDOOR;
2018.         break;
2019.     case 4:
2020.         kind = PIT;
2021.         break;
2022.     case 5:
2023.         kind = SLP_GAS_TRAP;
2024.         break;
2025.     case 6:
2026.         kind = RUST_TRAP;
2027.         break;
2028.     }
2029.     return kind;
2030. }
2031. 
2032. /* mktrap(): select trap type and location, then use maketrap() to create it;
2033.    make it at location 'tm' when that isn't Null, otherwise in 'croom'
2034.    if mktrapflags doesn't have MKTRAP_MAZEFLAG set, else in maze corridor */
2035. void
2036. mktrap(
2037.     int num,              /* if non-zero, specific type of trap to make */
2038.     unsigned mktrapflags, /* MKTRAP_{SEEN,MAZEFLAG,NOSPIDERONWEB,NOVICTIM} */
2039.     struct mkroom *croom, /* room to hold trap */
2040.     coord *tm)            /* specific location for trap */
2041. {
2042.     static int mktrap_err = 0; /* move to struct g? */
2043.     struct trap *t;
2044.     coord m;
2045.     int kind;
2046.     unsigned lvl = level_difficulty();
2047. 
2048.     if (!tm && !croom && !(mktrapflags & MKTRAP_MAZEFLAG)) {
2049.         /* complain when the combination of arguments will never set 'm' */
2050.         if (!mktrap_err++) {
2051.             char errbuf[BUFSZ];
2052. 
2053.             Snprintf(errbuf, sizeof errbuf,
2054.                      "args (%d,%d,%s,%s) are invalid",
2055.                      num, mktrapflags, "null room", "null location");
2056.             paniclog("mktrap", errbuf);
2057.         }
2058.         return;
2059.     }
2060.     m.x = m.y = 0;
2061. 
2062.     /* no traps in pools */
2063.     if (tm && is_pool_or_lava(tm->x, tm->y))
2064.         return;
2065. 
2066.     if (num > NO_TRAP && num < TRAPNUM) {
2067.         kind = num;
2068.     } else if (Is_rogue_level(&u.uz)) {
2069.         kind = traptype_roguelvl();
2070.     } else if (Inhell && !rn2(5)) {
2071.         /* bias the frequency of fire traps in Gehennom */
2072.         kind = FIRE_TRAP;
2073.     } else {
2074.         do {
2075.             kind = traptype_rnd(mktrapflags);
2076.         } while (kind == NO_TRAP);
2077.     }
2078. 
2079.     if (is_hole(kind) && !Can_fall_thru(&u.uz))
2080.         kind = ROCKTRAP;
2081. 
2082.     if (tm) {
2083.         m = *tm;
2084.     } else {
2085.         int tryct = 0;
2086.         boolean avoid_boulder = (is_pit(kind) || is_hole(kind));
2087. 
2088.         do {
2089.             if (++tryct > 200)
2090.                 return;
2091.             if ((mktrapflags & MKTRAP_MAZEFLAG) != 0)
2092.                 mazexy(&m);
2093.             else if (croom && !somexyspace(croom, &m))
2094.                 return;
2095.         } while (occupied(m.x, m.y)
2096.                  || (avoid_boulder && sobj_at(BOULDER, m.x, m.y)));
2097.     }
2098. 
2099.     t = maketrap(m.x, m.y, kind);
2100.     /* we should always get type of trap we're asking for (occupied() test
2101.        should prevent cases where that might not happen) but be paranoid */
2102.     kind = t ? t->ttyp : NO_TRAP;
2103. 
2104.     if (kind == WEB && !(mktrapflags & MKTRAP_NOSPIDERONWEB))
2105.         (void) makemon(&mons[PM_GIANT_SPIDER], m.x, m.y, NO_MM_FLAGS);
2106.     if (t && (mktrapflags & MKTRAP_SEEN))
2107.         t->tseen = TRUE;
2108.     if (kind == MAGIC_PORTAL && (u.ucamefrom.dnum || u.ucamefrom.dlevel)) {
2109.         assign_level(&t->dst, &u.ucamefrom);
2110.     }
2111. 
2112.     /* The hero isn't the only person who's entered the dungeon in
2113.        search of treasure. On the very shallowest levels, there's a
2114.        chance that a created trap will have killed something already
2115.        (and this is guaranteed on the first level).
2116. 
2117.        This isn't meant to give any meaningful treasure (in fact, any
2118.        items we drop here are typically cursed, other than ammo fired
2119.        by the trap). Rather, it's mostly just for flavour and to give
2120.        players on very early levels a sufficient chance to avoid traps
2121.        that may end up killing them before they have a fair chance to
2122.        build max HP. Including cursed items gives the same fair chance
2123.        to the starting pet, and fits the rule that possessions of the
2124.        dead are normally cursed.
2125. 
2126.        Some types of traps are excluded because they're entirely
2127.        nonlethal, even indirectly. We also exclude all of the
2128.        later/fancier traps because they tend to have special
2129.        considerations (e.g. webs, portals), often are indirectly
2130.        lethal, and tend not to generate on shallower levels anyway
2131.        (exception: magic traps can generate on dlvl 1 and be
2132.        immediately lethal). Finally, pits are excluded because it's
2133.        weird to see an item in a pit and yet not be able to identify
2134.        that the pit is there. */
2135.     if (gi.in_mklev
2136.         && kind != NO_TRAP && !(mktrapflags & MKTRAP_NOVICTIM)
2137.         && lvl <= (unsigned) rnd(4)
2138.         && kind != SQKY_BOARD && kind != RUST_TRAP
2139.         /* rolling boulder trap might not have a boulder if there was no
2140.            viable path (such as when placed in the corner of a room), in
2141.            which case tx,ty==launch.x,y; no boulder => no dead predecessor */
2142.         && !(kind == ROLLING_BOULDER_TRAP
2143.              && t->launch.x == t->tx && t->launch.y == t->ty)
2144.         && !is_pit(kind) && (kind < HOLE || kind == MAGIC_TRAP)) {
2145.         if (kind == LANDMINE) {
2146.             /* if victim was killed by a land mine, we won't scatter objects;
2147.                treat it as exploded, converting it into an unconcealed pit */
2148.             t->ttyp = PIT;
2149.             t->tseen = 1;
2150.         }
2151.         mktrap_victim(t);
2152.     }
2153.     return;
2154. }
2155. 
2156. /* Create stairs up or down at x,y.
2157.    If force is TRUE, change the terrain to ROOM first */
2158. void
2159. mkstairs(
2160.     coordxy x, coordxy y,
2161.     char up,       /* [why 'char' when usage is boolean?] */
2162.     struct mkroom *croom UNUSED,
2163.     boolean force)
2164. {
2165.     int ltyp;
2166.     d_level dest;
2167. 
2168.     if (!x || !isok(x, y)) {
2169.         impossible("mkstairs:  bogus stair attempt at <%d,%d>", x, y);
2170.         return;
2171.     }
2172.     if (force)
2173.         levl[x][y].typ = ROOM;
2174.     ltyp = levl[x][y].typ; /* somexyspace() allows ice */
2175.     if (ltyp != ROOM && ltyp != CORR && ltyp != ICE) {
2176.         int glyph = back_to_glyph(x, y),
2177.             sidx = glyph_to_cmap(glyph);
2178. 
2179.         impossible("mkstairs:  placing stairs %s on %s at <%d,%d>",
2180.                    up ? "up" : "down", defsyms[sidx].explanation, x, y);
2181.     }
2182. 
2183.     /*
2184.      * We can't make a regular stair off an end of the dungeon.  This
2185.      * attempt can happen when a special level is placed at an end and
2186.      * has an up or down stair specified in its description file.
2187.      */
2188.     if (dunlev(&u.uz) == (up ? 1 : dunlevs_in_dungeon(&u.uz)))
2189.         return;
2190. 
2191.     dest.dnum = u.uz.dnum;
2192.     dest.dlevel = u.uz.dlevel + (up ? -1 : 1);
2193.     stairway_add(x, y, up ? TRUE : FALSE, FALSE, &dest);
2194. 
2195.     (void) set_levltyp(x, y, STAIRS);
2196.     levl[x][y].ladder = up ? LA_UP : LA_DOWN;
2197. }
2198. 
2199. /* is room a good one to generate up or down stairs in? */
2200. staticfn boolean
2201. generate_stairs_room_good(struct mkroom *croom, int phase)
2202. {
2203.     /*
2204.      * phase values, smaller allows for more relaxed criteria:
2205.      *  2 == no relaxed criteria;
2206.      *  1 == allow a themed room;
2207.      *  0 == allow same room as existing up/downstairs;
2208.      * -1 == allow an unjoined room.
2209.      */
2210.     return (croom && (croom->needjoining || (phase < 0))
2211.             && ((!has_dnstairs(croom) && !has_upstairs(croom))
2212.                 || phase < 1)
2213.             && (croom->rtype == OROOM
2214.                 || ((phase < 2) && croom->rtype == THEMEROOM)));
2215. }
2216. 
2217. /* find a good room to generate an up or down stairs in */
2218. staticfn struct mkroom *
2219. generate_stairs_find_room(void)
2220. {
2221.     struct mkroom *croom;
2222.     int i, phase, ai;
2223.     int *rmarr;
2224. 
2225.     if (!svn.nroom)
2226.         return (struct mkroom *) 0;
2227. 
2228.     rmarr = (int *) alloc(sizeof(int) * svn.nroom);
2229. 
2230.     for (phase = 2; phase > -1; phase--) {
2231.         ai = 0;
2232.         for (i = 0; i < svn.nroom; i++)
2233.             if (generate_stairs_room_good(&svr.rooms[i], phase))
2234.                 rmarr[ai++] = i;
2235.         if (ai > 0) {
2236.             i = rmarr[rn2(ai)];
2237.             free(rmarr);
2238.             return &svr.rooms[i];
2239.         }
2240.     }
2241. 
2242.     free(rmarr);
2243.     croom = &svr.rooms[rn2(svn.nroom)];
2244.     return croom;
2245. }
2246. 
2247. /* construct stairs up and down within the same branch,
2248.    up and down in different rooms if possible */
2249. staticfn void
2250. generate_stairs(void)
2251. {
2252.     /* generate_stairs_find_room() returns Null if nroom == 0, but that
2253.        should never happen for a rooms+corridors style level */
2254.     static const char
2255.         gen_stairs_panic[] = "generate_stairs: failed to find a room! (%d)";
2256.     struct mkroom *croom;
2257.     coord pos;
2258. 
2259.     if (!Is_botlevel(&u.uz)) {
2260.         if ((croom = generate_stairs_find_room()) == NULL)
2261.             panic(gen_stairs_panic, svn.nroom);
2262. 
2263.         if (!somexyspace(croom, &pos)) {
2264.             pos.x = somex(croom);
2265.             pos.y = somey(croom);
2266.         }
2267.         mkstairs(pos.x, pos.y, 0, croom, FALSE); /* down */
2268.     }
2269. 
2270.     if (u.uz.dlevel != 1) {
2271.         /* if there is only 1 room and we found it above, this will find
2272.            it again */
2273.         if ((croom = generate_stairs_find_room()) == NULL)
2274.             panic(gen_stairs_panic, svn.nroom);
2275. 
2276.         if (!somexyspace(croom, &pos)) {
2277.             pos.x = somex(croom);
2278.             pos.y = somey(croom);
2279.         }
2280.         mkstairs(pos.x, pos.y, 1, croom, FALSE); /* up */
2281.     }
2282. }
2283. 
2284. staticfn void
2285. mkfount(struct mkroom *croom)
2286. {
2287.     coord m;
2288. 
2289.     if (!find_okay_roompos(croom, &m))
2290.         return;
2291. 
2292.     /* Put a fountain at m.x, m.y */
2293.     if (!set_levltyp(m.x, m.y, FOUNTAIN))
2294.         return;
2295.     /* Is it a "blessed" fountain? (affects drinking from fountain) */
2296.     if (!rn2(7))
2297.         levl[m.x][m.y].blessedftn = 1;
2298. 
2299.     svl.level.flags.nfountains++;
2300. }
2301. 
2302. staticfn boolean
2303. find_okay_roompos(struct mkroom *croom, coord *crd)
2304. {
2305.     int tryct = 0;
2306. 
2307.     do {
2308.         if (++tryct > 200)
2309.             return FALSE;
2310.         if (!somexyspace(croom, crd))
2311.             return FALSE;
2312.     } while (occupied(crd->x, crd->y) || bydoor(crd->x, crd->y));
2313.     return TRUE;
2314. }
2315. 
2316. staticfn void
2317. mksink(struct mkroom *croom)
2318. {
2319.     coord m;
2320. 
2321.     if (!find_okay_roompos(croom, &m))
2322.         return;
2323. 
2324.     /* Put a sink at m.x, m.y */
2325.     if (!set_levltyp(m.x, m.y, SINK))
2326.         return;
2327. 
2328.     svl.level.flags.nsinks++;
2329. }
2330. 
2331. staticfn void
2332. mkaltar(struct mkroom *croom)
2333. {
2334.     coord m;
2335.     aligntyp al;
2336. 
2337.     if (croom->rtype != OROOM)
2338.         return;
2339. 
2340.     if (!find_okay_roompos(croom, &m))
2341.         return;
2342. 
2343.     /* Put an altar at m.x, m.y */
2344.     if (!set_levltyp(m.x, m.y, ALTAR))
2345.         return;
2346. 
2347.     /* -1 - A_CHAOTIC, 0 - A_NEUTRAL, 1 - A_LAWFUL */
2348.     al = rn2((int) A_LAWFUL + 2) - 1;
2349.     levl[m.x][m.y].altarmask = Align2amask(al);
2350. }
2351. 
2352. staticfn void
2353. mkgrave(struct mkroom *croom)
2354. {
2355.     coord m;
2356.     int tryct = 0;
2357.     struct obj *otmp;
2358.     boolean dobell = !rn2(10);
2359. 
2360.     if (croom->rtype != OROOM)
2361.         return;
2362. 
2363.     if (!find_okay_roompos(croom, &m))
2364.         return;
2365. 
2366.     /* Put a grave at <m.x,m.y> */
2367.     make_grave(m.x, m.y, dobell ? "Saved by the bell!" : (char *) 0);
2368. 
2369.     /* Possibly fill it with objects */
2370.     if (!rn2(3)) {
2371.         /* this used to use mkgold(), which puts a stack of gold on
2372.            the ground (or merges it with an existing one there if
2373.            present), and didn't bother burying it; now we create a
2374.            loose, easily buriable, stack but we make no attempt to
2375.            replicate mkgold()'s level-based formula for the amount */
2376.         struct obj *gold = mksobj(GOLD_PIECE, TRUE, FALSE);
2377. 
2378.         gold->quan = (long) (rnd(20) + level_difficulty() * rnd(5));
2379.         gold->owt = weight(gold);
2380.         gold->ox = m.x, gold->oy = m.y;
2381.         add_to_buried(gold);
2382.     }
2383.     for (tryct = rn2(5); tryct; tryct--) {
2384.         otmp = mkobj(RANDOM_CLASS, TRUE);
2385.         if (!otmp)
2386.             return;
2387.         curse(otmp);
2388.         otmp->ox = m.x;
2389.         otmp->oy = m.y;
2390.         add_to_buried(otmp);
2391.     }
2392. 
2393.     /* Leave a bell, in case we accidentally buried someone alive */
2394.     if (dobell)
2395.         (void) mksobj_at(BELL, m.x, m.y, TRUE, FALSE);
2396.     return;
2397. }
2398. 
2399. /*
2400.  * Major level transmutation:  add a set of stairs (to the Sanctum) after
2401.  * an earthquake that leaves behind a new topology, centered at inv_pos.
2402.  * Assumes there are no rooms within the invocation area and that svi.inv_pos
2403.  * is not too close to the edge of the map.  Also assume the hero can see,
2404.  * which is guaranteed for normal play due to the fact that sight is needed
2405.  * to read the Book of the Dead.  [That assumption is not valid; it is
2406.  * possible that "the Book reads the hero" rather than vice versa if
2407.  * attempted while blind (in order to make blind-from-birth conduct viable).]
2408.  */
2409. void
2410. mkinvokearea(void)
2411. {
2412.     int dist, wallct;
2413.     coordxy xmin, xmax, ymin, ymax;
2414.     coordxy i;
2415. 
2416.     /* slightly odd if levitating, but not wrong */
2417.     pline_The("floor shakes violently under you!");
2418.     /* decide whether to issue the crumbling walls message */
2419.     {
2420.         xmin = xmax = svi.inv_pos.x;
2421.         ymin = ymax = svi.inv_pos.y;
2422.         wallct = mkinvk_check_wall(xmin, ymin);
2423.         /* this replicates the somewhat convoluted loop below, working
2424.            out from the stair position, except for stopping early when
2425.            walls are found */
2426.         for (dist = 1; !wallct && dist < 7; ++dist) {
2427.             xmin--, xmax++;
2428.             /* top and bottom */
2429.             if (dist != 3) { /* the area is wider that it is high */
2430.                 ymin--, ymax++;
2431.                 for (i = xmin + 1; i < xmax; i++) {
2432.                     if (mkinvk_check_wall(i, ymin))
2433.                         ++wallct; /* we could break after finding first wall
2434.                                    * but it isn't a significant optimization
2435.                                    * for code which only executes once */
2436.                     if (mkinvk_check_wall(i, ymax))
2437.                         ++wallct;
2438.                 }
2439.             }
2440.             /* left and right */
2441.             if (!wallct) { /* skip y loop if x loop found any walls */
2442.                 for (i = ymin; i <= ymax; i++) {
2443.                     if (mkinvk_check_wall(xmin, i))
2444.                         ++wallct;
2445.                     if (mkinvk_check_wall(xmax, i))
2446.                         ++wallct;
2447.                 }
2448.             }
2449.         }
2450.         /* message won't appear if the maze 'walls' on this level are lava
2451.            or if all the walls within range have been dug away; when it does
2452.            appear, it will describe iron bars as "walls" (which is ok) */
2453.         if (wallct)
2454.             pline_The("walls around you begin to bend and crumble!");
2455.     }
2456.     display_nhwindow(WIN_MESSAGE, TRUE);
2457. 
2458.     /* any trap hero is stuck in will be going away now */
2459.     if (u.utrap) {
2460.         if (u.utraptype == TT_BURIEDBALL)
2461.             buried_ball_to_punishment();
2462.         reset_utrap(FALSE);
2463.     }
2464. 
2465.     xmin = xmax = svi.inv_pos.x; /* reset after the check for walls */
2466.     ymin = ymax = svi.inv_pos.y;
2467.     mkinvpos(xmin, ymin, 0); /* middle, before placing stairs */
2468. 
2469.     for (dist = 1; dist < 7; dist++) {
2470.         xmin--;
2471.         xmax++;
2472. 
2473.         /* top and bottom */
2474.         if (dist != 3) { /* the area is wider that it is high */
2475.             ymin--;
2476.             ymax++;
2477.             for (i = xmin + 1; i < xmax; i++) {
2478.                 mkinvpos(i, ymin, dist);
2479.                 mkinvpos(i, ymax, dist);
2480.             }
2481.         }
2482. 
2483.         /* left and right */
2484.         for (i = ymin; i <= ymax; i++) {
2485.             mkinvpos(xmin, i, dist);
2486.             mkinvpos(xmax, i, dist);
2487.         }
2488. 
2489.         flush_screen(1); /* make sure the new glyphs shows up */
2490.         nh_delay_output();
2491.     }
2492. 
2493.     You("are standing at the top of a stairwell leading down!");
2494.     mkstairs(u.ux, u.uy, 0, (struct mkroom *) 0, FALSE); /* down */
2495.     newsym(u.ux, u.uy);
2496.     gv.vision_full_recalc = 1; /* everything changed */
2497. }
2498. 
2499. /* Change level topology.  Boulders in the vicinity are eliminated.
2500.  * Temporarily overrides vision in the name of a nice effect.
2501.  */
2502. staticfn void
2503. mkinvpos(coordxy x, coordxy y, int dist)
2504. {
2505.     struct trap *ttmp;
2506.     struct obj *otmp;
2507.     boolean make_rocks;
2508.     struct rm *lev = &levl[x][y];
2509.     struct monst *mon;
2510.     /* maze levels have slightly different constraints from normal levels;
2511.        these are also defined in mkmaze.c and may not be appropriate for
2512.        mazes with corridors wider than 1 or for cavernous levels */
2513. #define x_maze_min 2
2514. #define y_maze_min 2
2515. 
2516.     /* clip at existing map borders if necessary */
2517.     if (!within_bounded_area(x, y, x_maze_min, y_maze_min,
2518.                              gx.x_maze_max, gy.y_maze_max)) {
2519.         /* outermost 2 columns and/or rows may be truncated due to edge */
2520.         if (dist < (7 - 2)) { /* panic() or impossible() */
2521.             void (*errfunc)(const char *, ...) PRINTF_F(1, 2);
2522. 
2523.             errfunc = !isok(x, y) ? panic : impossible;
2524.             (*errfunc)("mkinvpos: <%d,%d> (%d) off map edge!", x, y, dist);
2525.         }
2526.         return;
2527.     }
2528. 
2529.     /* clear traps */
2530.     if ((ttmp = t_at(x, y)) != 0)
2531.         deltrap(ttmp);
2532. 
2533.     /* clear boulders; leave some rocks for non-{moat|trap} locations */
2534.     make_rocks = (dist != 1 && dist != 4 && dist != 5) ? TRUE : FALSE;
2535.     while ((otmp = sobj_at(BOULDER, x, y)) != 0) {
2536.         if (make_rocks) {
2537.             fracture_rock(otmp);
2538.             make_rocks = FALSE; /* don't bother with more rocks */
2539.         } else {
2540.             obj_extract_self(otmp);
2541.             obfree(otmp, (struct obj *) 0);
2542.         }
2543.     }
2544. 
2545.     /* fake out saved state */
2546.     lev->seenv = 0;
2547.     lev->doormask = 0;
2548.     if (dist < 6)
2549.         lev->lit = TRUE;
2550.     lev->waslit = TRUE;
2551.     lev->horizontal = FALSE;
2552.     /* short-circuit vision recalc */
2553.     gv.viz_array[y][x] = (dist < 6) ? (IN_SIGHT | COULD_SEE) : COULD_SEE;
2554. 
2555.     switch (dist) {
2556.     case 1: /* fire traps */
2557.         if (is_pool(x, y))
2558.             break;
2559.         lev->typ = ROOM;
2560.         ttmp = maketrap(x, y, FIRE_TRAP);
2561.         if (ttmp)
2562.             ttmp->tseen = TRUE;
2563.         break;
2564.     case 0: /* lit room locations */
2565.     case 2:
2566.     case 3:
2567.     case 6: /* unlit room locations */
2568.         lev->typ = ROOM;
2569.         break;
2570.     case 4: /* pools (aka a wide moat) */
2571.     case 5:
2572.         lev->typ = MOAT;
2573.         /* No kelp! */
2574.         break;
2575.     default:
2576.         impossible("mkinvpos called with dist %d", dist);
2577.         break;
2578.     }
2579. 
2580.     if ((mon = m_at(x, y)) != 0) {
2581.         /* wake up mimics, don't want to deal with them blocking vision */
2582.         if (mon->m_ap_type)
2583.             seemimic(mon);
2584. 
2585.         if ((ttmp = t_at(x, y)) != 0)
2586.             (void) mintrap(mon, NO_TRAP_FLAGS);
2587.         else
2588.             (void) minliquid(mon);
2589.     }
2590. 
2591.     if (!does_block(x, y, lev))
2592.         unblock_point(x, y); /* make sure vision knows location is open */
2593. 
2594.     /* display new value of position; could have a monster/object on it */
2595.     newsym(x, y);
2596. #undef x_maze_min
2597. #undef y_maze_min
2598. }
2599. 
2600. /* reduces clutter in mkinvokearea() while avoiding potential static analyzer
2601.    confusion about using isok(x,y) to control access to levl[x][y] */
2602. staticfn int
2603. mkinvk_check_wall(coordxy x, coordxy y)
2604. {
2605.     unsigned ltyp;
2606. 
2607.     if (!isok(x, y))
2608.         return 0;
2609.     assert(x > 0 && x < COLNO);
2610.     assert(y >= 0 && y < ROWNO);
2611.     ltyp = levl[x][y].typ;
2612.     return (IS_STWALL(ltyp) || ltyp == IRONBARS) ? 1 : 0;
2613. }
2614. 
2615. /*
2616.  * The portal to Ludios is special.  The entrance can only occur within a
2617.  * vault in the main dungeon at a depth greater than 10.  The Ludios branch
2618.  * structure reflects this by having a bogus "source" dungeon:  the value
2619.  * of n_dgns (thus, Is_branchlev() will never find it).
2620.  *
2621.  * Ludios will remain isolated until the branch is corrected by this function.
2622.  */
2623. staticfn void
2624. mk_knox_portal(coordxy x, coordxy y)
2625. {
2626.     d_level *source;
2627.     branch *br;
2628.     schar u_depth;
2629. 
2630.     br = dungeon_branch("Fort Ludios");
2631.     /* dungeon_branch() panics (so never returns) if result would be Null */
2632.     assert(br != NULL);
2633. 
2634.     if (on_level(&knox_level, &br->end1)) {
2635.         source = &br->end2;
2636.     } else {
2637.         /* disallow Knox branch on a level with one branch already */
2638.         if (Is_branchlev(&u.uz))
2639.             return;
2640.         source = &br->end1;
2641.     }
2642. 
2643.     /* Already set or 2/3 chance of deferring until a later level. */
2644.     if (source->dnum < svn.n_dgns || (rn2(3) && !wizard))
2645.         return;
2646. 
2647.     if (!(u.uz.dnum == oracle_level.dnum      /* in main dungeon */
2648.           && !at_dgn_entrance("The Quest")    /* but not Quest's entry */
2649.           && (u_depth = depth(&u.uz)) > 10    /* beneath 10 */
2650.           && u_depth < depth(&medusa_level))) /* and above Medusa */
2651.         return;
2652. 
2653.     /* Adjust source to be current level and re-insert branch. */
2654.     *source = u.uz;
2655.     insert_branch(br, TRUE);
2656. 
2657.     debugpline0("Made knox portal.");
2658.     place_branch(br, x, y);
2659. }
2660. 
2661. /*mklev.c*/