Source:NetHack 5.0.0/src/mkmaze.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to mkmaze.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/mkmaze.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	mkmaze.c	$NHDT-Date: 1745114235 2025/04/19 17:57:15 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.179 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Pasi Kallinen, 2018. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. #include "sp_lev.h"
8. 
9. #ifndef SFCTOOL
10. staticfn int iswall(coordxy, coordxy);
11. staticfn int iswall_or_stone(coordxy, coordxy);
12. staticfn boolean is_solid(coordxy, coordxy);
13. staticfn int extend_spine(int[3][3], int, int, int);
14. staticfn void wall_cleanup(coordxy, coordxy, coordxy, coordxy);
15. staticfn boolean okay(coordxy, coordxy, coordxy);
16. staticfn void maze0xy(coord *);
17. staticfn boolean put_lregion_here(coordxy, coordxy, coordxy, coordxy, coordxy,
18.                                 coordxy, xint16, boolean, d_level *);
19. staticfn void baalz_fixup(void);
20. staticfn void setup_waterlevel(void);
21. staticfn void unsetup_waterlevel(void);
22. staticfn void check_ransacked(const char *);
23. staticfn void migr_booty_item(int, const char *);
24. staticfn void migrate_orc(struct monst *, unsigned long);
25. staticfn void shiny_orc_stuff(struct monst *);
26. staticfn void stolen_booty(void);
27. staticfn boolean maze_inbounds(coordxy, coordxy);
28. staticfn void maze_remove_deadends(xint16);
29. staticfn void populate_maze(void);
30. 
31. /* adjust a coordinate one step in the specified direction */
32. #define mz_move(X, Y, dir) \
33.     do {                                                         \
34.         switch (dir) {                                           \
35.         case 0:  --(Y);  break;                                  \
36.         case 1:  (X)++;  break;                                  \
37.         case 2:  (Y)++;  break;                                  \
38.         case 3:  --(X);  break;                                  \
39.         default: panic("mz_move: bad direction %d", dir);        \
40.         }                                                        \
41.     } while (0)
42. 
43. /* used to determine if wall spines can join this location */
44. staticfn int
45. iswall(coordxy x, coordxy y)
46. {
47.     int type;
48. 
49.     if (!isok(x, y))
50.         return 0;
51.     type = levl[x][y].typ;
52.     return (IS_WALL(type) || IS_DOOR(type)
53.             || type == LAVAWALL || type == WATER
54.             || type == SDOOR || type == IRONBARS);
55. }
56. 
57. /* used to determine if wall spines can join this location */
58. staticfn int
59. iswall_or_stone(coordxy x, coordxy y)
60. {
61.     /* out of bounds = stone */
62.     if (!isok(x, y))
63.         return 1;
64. 
65.     return (levl[x][y].typ == STONE || iswall(x, y));
66. }
67. 
68. /* return TRUE if out of bounds, wall or rock */
69. staticfn boolean
70. is_solid(coordxy x, coordxy y)
71. {
72.     return (boolean) (!isok(x, y) || IS_STWALL(levl[x][y].typ));
73. }
74. 
75. /* set map terrain type, handling lava lit, ice melt timers, etc */
76. boolean
77. set_levltyp(coordxy x, coordxy y, schar newtyp)
78. {
79.     if (isok(x, y) && newtyp >= STONE && newtyp < MAX_TYPE) {
80.         schar oldtyp = levl[x][y].typ;
81. 
82.         /* hack for secret doors in garden theme rooms */
83.         if (oldtyp == SDOOR && newtyp == AIR) {
84.             /* levl[][].typ stays SDOOR rather than change to AIR */
85.             levl[x][y].arboreal_sdoor = 1;
86.             return TRUE;
87.         }
88. 
89.         if (CAN_OVERWRITE_TERRAIN(oldtyp)) {
90.             /* typ==ICE || (typ==DRAWBRIDGE_UP && drawbridgemask==DB_ICE) */
91.             boolean was_ice = is_ice(x, y);
92. 
93.             levl[x][y].typ = newtyp;
94.             /* TODO?
95.              *  if oldtyp used flags or horizontal differently from
96.              *  the way newtyp will use them, clear them.
97.              */
98. 
99.             if (IS_LAVA(newtyp)) /* [what about IS_LAVA(oldtyp)=>.lit = 0?] */
100.                 levl[x][y].lit = 1;
101.             if (was_ice && newtyp != ICE) {
102.                 /* frozen corpses resume rotting, no more ice to melt away */
103.                 obj_ice_effects(x, y, TRUE);
104.                 spot_stop_timers(x, y, MELT_ICE_AWAY);
105.             }
106.             if ((IS_FOUNTAIN(oldtyp) != IS_FOUNTAIN(newtyp))
107.                 || (IS_SINK(oldtyp) != IS_SINK(newtyp)))
108.                 count_level_features(); /* level.flags.nfountains,nsinks */
109. 
110.             return TRUE;
111.         }
112. #ifdef EXTRA_SANITY_CHECKS
113.     } else {
114.         impossible("set_levltyp(%d,%d,%d)%s%s",
115.                    (int) x, (int) y, (int) newtyp,
116.                    !isok(x, y) ? " not isok()" : "",
117.                    (newtyp < STONE || newtyp >= MAX_TYPE) ? " bad type" : "");
118. #endif /*EXTRA_SANITY_CHECKS*/
119.     }
120.     return FALSE;
121. }
122. 
123. /* set map terrain type and light state */
124. boolean
125. set_levltyp_lit(coordxy x, coordxy y, schar typ, schar lit)
126. {
127.     boolean ret = set_levltyp(x, y, typ);
128. 
129.     if (ret && isok(x, y)) {
130.         if (lit != SET_LIT_NOCHANGE) {
131. #ifdef EXTRA_SANITY_CHECKS
132.             if (lit < SET_LIT_NOCHANGE || lit > 1)
133.                 impossible("set_levltyp_lit(%d,%d,%d,%d)",
134.                            (int) x, (int) y, (int) typ, (int) lit);
135. #endif /*EXTRA_SANITY_CHECKS*/
136.             if (IS_LAVA(typ))
137.                 lit = 1;
138.             else if (lit == SET_LIT_RANDOM)
139.                 lit = rn2(2);
140. 
141.             levl[x][y].lit = lit;
142.         }
143.     }
144.     return ret;
145. }
146. 
147. /*
148.  * Return 1 (not TRUE - we're doing bit vectors here) if we want to extend
149.  * a wall spine in the (dx,dy) direction.  Return 0 otherwise.
150.  *
151.  * To extend a wall spine in that direction, first there must be a wall there.
152.  * Then, extend a spine unless the current position is surrounded by walls
153.  * in the direction given by (dx,dy).  E.g. if 'x' is our location, 'W'
154.  * a wall, '.' a room, 'a' anything (we don't care), and our direction is
155.  * (0,1) - South or down - then:
156.  *
157.  *              a a a
158.  *              W x W           This would not extend a spine from x down
159.  *              W W W           (a corridor of walls is formed).
160.  *
161.  *              a a a
162.  *              W x W           This would extend a spine from x down.
163.  *              . W W
164.  */
165. staticfn int
166. extend_spine(int locale[3][3], int wall_there, int dx, int dy)
167. {
168.     int spine, nx, ny;
169. 
170.     nx = 1 + dx;
171.     ny = 1 + dy;
172. 
173.     if (wall_there) { /* wall in that direction */
174.         if (dx) {
175.             if (locale[1][0] && locale[1][2]         /* EW are wall/stone */
176.                 && locale[nx][0] && locale[nx][2]) { /* diag are wall/stone */
177.                 spine = 0;
178.             } else {
179.                 spine = 1;
180.             }
181.         } else { /* dy */
182.             if (locale[0][1] && locale[2][1]         /* NS are wall/stone */
183.                 && locale[0][ny] && locale[2][ny]) { /* diag are wall/stone */
184.                 spine = 0;
185.             } else {
186.                 spine = 1;
187.             }
188.         }
189.     } else {
190.         spine = 0;
191.     }
192. 
193.     return spine;
194. }
195. 
196. /* Remove walls totally surrounded by stone */
197. staticfn void
198. wall_cleanup(coordxy x1, coordxy y1, coordxy x2, coordxy y2)
199. {
200.     uchar type;
201.     coordxy x, y;
202.     struct rm *lev;
203. 
204.     /* sanity check on incoming variables */
205.     if (x1 < 0 || x2 >= COLNO || x1 > x2 || y1 < 0 || y2 >= ROWNO || y1 > y2)
206.         panic("wall_cleanup: bad bounds (%d,%d) to (%d,%d)", x1, y1, x2, y2);
207. 
208.     /* change walls surrounded by rock to rock. */
209.     for (x = x1; x <= x2; x++)
210.         for (y = y1; y <= y2; y++) {
211.             if (within_bounded_area(x, y,
212.                                   gb.bughack.inarea.x1, gb.bughack.inarea.y1,
213.                                   gb.bughack.inarea.x2, gb.bughack.inarea.y2))
214.                 continue;
215.             lev = &levl[x][y];
216.             type = lev->typ;
217.             if (IS_WALL(type) && type != DBWALL) {
218.                 if (is_solid(x - 1, y - 1) && is_solid(x - 1, y)
219.                     && is_solid(x - 1, y + 1) && is_solid(x, y - 1)
220.                     && is_solid(x, y + 1) && is_solid(x + 1, y - 1)
221.                     && is_solid(x + 1, y) && is_solid(x + 1, y + 1))
222.                     lev->typ = STONE;
223.             }
224.         }
225. }
226. 
227. /* Correct wall types so they extend and connect to each other */
228. void
229. fix_wall_spines(coordxy x1, coordxy y1, coordxy x2, coordxy y2)
230. {
231.     uchar type;
232.     coordxy x, y;
233.     struct rm *lev;
234.     int (*loc_f)(coordxy, coordxy);
235.     int bits;
236.     int locale[3][3]; /* rock or wall status surrounding positions */
237. 
238.     /*
239.      * Value 0 represents a free-standing wall.  It could be anything,
240.      * so even though this table says VWALL, we actually leave whatever
241.      * typ was there alone.
242.      */
243.     static xint16 spine_array[16] = { VWALL, HWALL,    HWALL,    HWALL,
244.                                      VWALL, TRCORNER, TLCORNER, TDWALL,
245.                                      VWALL, BRCORNER, BLCORNER, TUWALL,
246.                                      VWALL, TLWALL,   TRWALL,   CROSSWALL };
247. 
248.     /* sanity check on incoming variables */
249.     if (x1 < 0 || x2 >= COLNO || x1 > x2 || y1 < 0 || y2 >= ROWNO || y1 > y2)
250.         panic("wall_extends: bad bounds (%d,%d) to (%d,%d)", x1, y1, x2, y2);
251. 
252.     /* set the correct wall type. */
253.     for (x = x1; x <= x2; x++)
254.         for (y = y1; y <= y2; y++) {
255.             lev = &levl[x][y];
256.             type = lev->typ;
257.             if (!(IS_WALL(type) && type != DBWALL))
258.                 continue;
259. 
260.             /* set the locations TRUE if rock or wall or out of bounds */
261.             loc_f = within_bounded_area(x, y, /* for baalz insect */
262.                                    gb.bughack.inarea.x1, gb.bughack.inarea.y1,
263.                                    gb.bughack.inarea.x2, gb.bughack.inarea.y2)
264.                        ? iswall
265.                        : iswall_or_stone;
266.             locale[0][0] = (*loc_f)(x - 1, y - 1);
267.             locale[1][0] = (*loc_f)(x, y - 1);
268.             locale[2][0] = (*loc_f)(x + 1, y - 1);
269. 
270.             locale[0][1] = (*loc_f)(x - 1, y);
271.             locale[2][1] = (*loc_f)(x + 1, y);
272. 
273.             locale[0][2] = (*loc_f)(x - 1, y + 1);
274.             locale[1][2] = (*loc_f)(x, y + 1);
275.             locale[2][2] = (*loc_f)(x + 1, y + 1);
276. 
277.             /* determine if wall should extend to each direction NSEW */
278.             bits = (extend_spine(locale, iswall(x, y - 1), 0, -1) << 3)
279.                    | (extend_spine(locale, iswall(x, y + 1), 0, 1) << 2)
280.                    | (extend_spine(locale, iswall(x + 1, y), 1, 0) << 1)
281.                    | extend_spine(locale, iswall(x - 1, y), -1, 0);
282. 
283.             /* don't change typ if wall is free-standing */
284.             if (bits)
285.                 lev->typ = spine_array[bits];
286.         }
287. }
288. 
289. void
290. wallification(coordxy x1, coordxy y1, coordxy x2, coordxy y2)
291. {
292.     wall_cleanup(x1, y1, x2, y2);
293.     fix_wall_spines(x1, y1, x2, y2);
294. }
295. 
296. staticfn boolean
297. okay(coordxy x, coordxy y, coordxy dir)
298. {
299.     mz_move(x, y, dir);
300.     mz_move(x, y, dir);
301.     if (x < 3 || y < 3 || x > gx.x_maze_max || y > gy.y_maze_max
302.         || levl[x][y].typ != STONE)
303.         return FALSE;
304.     return TRUE;
305. }
306. 
307. /* find random starting point for maze generation */
308. staticfn void
309. maze0xy(coord *cc)
310. {
311.     cc->x = 3 + 2 * rn2((gx.x_maze_max >> 1) - 1);
312.     cc->y = 3 + 2 * rn2((gy.y_maze_max >> 1) - 1);
313.     return;
314. }
315. 
316. boolean
317. is_exclusion_zone(xint16 type, coordxy x, coordxy y)
318. {
319.     struct exclusion_zone *ez = sve.exclusion_zones;
320. 
321.     while (ez) {
322.         if (((type == LR_DOWNTELE
323.               && (ez->zonetype == LR_DOWNTELE || ez->zonetype == LR_TELE))
324.              || (type == LR_UPTELE
325.                  && (ez->zonetype == LR_UPTELE || ez->zonetype == LR_TELE))
326.              || type == ez->zonetype)
327.             && within_bounded_area(x, y, ez->lx, ez->ly, ez->hx, ez->hy))
328.             return TRUE;
329.         ez = ez->next;
330.     }
331.     return FALSE;
332. }
333. 
334. /*
335.  * Bad if:
336.  *      pos is occupied OR
337.  *      pos is inside restricted region (nlx,nly,nhx,nhy) OR
338.  *      NOT (pos is corridor and a maze level OR pos is a room OR pos is air)
339.  */
340. boolean
341. bad_location(
342.     coordxy x, coordxy y,
343.     coordxy nlx, coordxy nly, coordxy nhx, coordxy nhy)
344. {
345.     return (boolean) (occupied(x, y)
346.                       || within_bounded_area(x, y, nlx, nly, nhx, nhy)
347.                       || !((levl[x][y].typ == CORR
348.                             && svl.level.flags.is_maze_lev)
349.                            || levl[x][y].typ == ROOM
350.                            || levl[x][y].typ == AIR));
351. }
352. 
353. /* pick a location in area (lx, ly, hx, hy) but not in (nlx, nly, nhx, nhy)
354.    and place something (based on rtype) in that region */
355. void
356. place_lregion(
357.     coordxy lx, coordxy ly, coordxy hx, coordxy hy,
358.     coordxy nlx, coordxy nly, coordxy nhx, coordxy nhy,
359.     xint16 rtype,
360.     d_level *lev)
361. {
362.     int trycnt;
363.     boolean oneshot;
364.     coordxy x, y;
365. 
366.     if (!lx) { /* default to whole level */
367.         /*
368.          * if there are rooms and this a branch, let place_branch choose
369.          * the branch location (to avoid putting branches in corridors).
370.          */
371.         if (rtype == LR_BRANCH && svn.nroom) {
372.             place_branch(Is_branchlev(&u.uz), 0, 0);
373.             return;
374.         }
375. 
376.         lx = 1; /* column 0 is not used */
377.         hx = COLNO - 1;
378.         ly = 0; /* 3.6.0 and earlier erroneously had 1 here */
379.         hy = ROWNO - 1;
380.     }
381. 
382.     /* clamp the area to the map */
383.     if (lx < 1)
384.         lx = 1;
385.     if (hx > COLNO - 1)
386.         hx = COLNO - 1;
387.     if (ly < 0)
388.         ly = 0;
389.     if (hy > ROWNO - 1)
390.         hy = ROWNO - 1;
391. 
392.     /* first a probabilistic approach */
393. 
394.     oneshot = (lx == hx && ly == hy);
395.     for (trycnt = 0; trycnt < 200; trycnt++) {
396.         x = rn1((hx - lx) + 1, lx);
397.         y = rn1((hy - ly) + 1, ly);
398.         if (put_lregion_here(x, y, nlx, nly, nhx, nhy, rtype, oneshot, lev))
399.             return;
400.     }
401. 
402.     /* then a deterministic one */
403. 
404.     for (x = lx; x <= hx; x++)
405.         for (y = ly; y <= hy; y++)
406.             if (put_lregion_here(x, y, nlx, nly, nhx, nhy, rtype, TRUE, lev))
407.                 return;
408. 
409.     impossible("Couldn't place lregion type %d!", rtype);
410. }
411. 
412. staticfn boolean
413. put_lregion_here(
414.     coordxy x, coordxy y,
415.     coordxy nlx, coordxy nly, coordxy nhx, coordxy nhy,
416.     xint16 rtype,
417.     boolean oneshot,
418.     d_level *lev)
419. {
420.     struct monst *mtmp;
421. 
422.     if (bad_location(x, y, nlx, nly, nhx, nhy)
423.         || is_exclusion_zone(rtype, x, y)) {
424.         if (!oneshot) {
425.             return FALSE; /* caller should try again */
426.         } else {
427.             /* Must make do with the only location possible;
428.                avoid failure due to a misplaced trap.
429.                It might still fail if there's a dungeon feature here. */
430.             struct trap *t = t_at(x, y);
431. 
432.             if (t && !undestroyable_trap(t->ttyp)) {
433.                 if (((mtmp = m_at(x, y)) != 0) && mtmp->mtrapped)
434.                     mtmp->mtrapped = 0;
435.                 deltrap(t);
436.             }
437.             if (bad_location(x, y, nlx, nly, nhx, nhy)
438.                 || is_exclusion_zone(rtype, x, y))
439.                 return FALSE;
440.         }
441.     }
442.     switch (rtype) {
443.     case LR_TELE:
444.     case LR_UPTELE:
445.     case LR_DOWNTELE:
446.         /* "something" means the player in this case */
447.         if ((mtmp = m_at(x, y)) != 0) {
448.             /* move the monster if no choice, or just try again */
449.             if (oneshot) {
450.                 if (!rloc(mtmp, RLOC_NOMSG))
451.                     m_into_limbo(mtmp);
452.             } else
453.                 return FALSE;
454.         }
455.         u_on_newpos(x, y);
456.         break;
457.     case LR_PORTAL:
458.         mkportal(x, y, lev->dnum, lev->dlevel);
459.         break;
460.     case LR_DOWNSTAIR:
461.     case LR_UPSTAIR:
462.         mkstairs(x, y, (char) rtype, (struct mkroom *) 0, FALSE);
463.         break;
464.     case LR_BRANCH:
465.         place_branch(Is_branchlev(&u.uz), x, y);
466.         break;
467.     }
468.     return TRUE;
469. }
470. 
471. /* fix up Baalzebub's lair, which depicts a level-sized beetle;
472.    its legs are walls within solid rock--regular wallification
473.    classifies them as superfluous and gets rid of them */
474. staticfn void
475. baalz_fixup(void)
476. {
477.     struct monst *mtmp;
478.     int x, y, lastx, lasty;
479. 
480.     /*
481.      * baalz level's nondiggable region surrounds the "insect" and rooms.
482.      * The outermost perimeter of that region is subject to wall cleanup
483.      * (hence 'x + 1' and 'y + 1' for starting don't-clean column and row,
484.      * 'lastx - 1' and 'lasty - 1' for ending don't-clean column and row)
485.      * and the interior is protected against that (in wall_cleanup()).
486.      *
487.      * Assumes level.flags.corrmaze is True, otherwise the bug legs will
488.      * have already been "cleaned" away by general wallification.
489.      */
490. 
491.     /* find low and high x for to-be-wallified portion of level */
492.     y = ROWNO / 2;
493.     for (lastx = x = 0; x < COLNO; ++x)
494.         if ((levl[x][y].wall_info & W_NONDIGGABLE) != 0) {
495.             if (!lastx)
496.                 gb.bughack.inarea.x1 = x + 1;
497.             lastx = x;
498.         }
499.     gb.bughack.inarea.x2 = ((lastx > gb.bughack.inarea.x1) ? lastx : x) - 1;
500.     /* find low and high y for to-be-wallified portion of level */
501.     x = gb.bughack.inarea.x1;
502.     for (lasty = y = 0; y < ROWNO; ++y)
503.         if ((levl[x][y].wall_info & W_NONDIGGABLE) != 0) {
504.             if (!lasty)
505.                 gb.bughack.inarea.y1 = y + 1;
506.             lasty = y;
507.         }
508.     gb.bughack.inarea.y2 = ((lasty > gb.bughack.inarea.y1) ? lasty : y) - 1;
509.     /* two pools mark where special post-wallify fix-ups are needed */
510.     for (x = gb.bughack.inarea.x1; x <= gb.bughack.inarea.x2; ++x)
511.         for (y = gb.bughack.inarea.y1; y <= gb.bughack.inarea.y2; ++y)
512.             if (levl[x][y].typ == POOL) {
513.                 levl[x][y].typ = HWALL;
514.                 if (gb.bughack.delarea.x1 == COLNO)
515.                     gb.bughack.delarea.x1 = x, gb.bughack.delarea.y1 = y;
516.                 else
517.                     gb.bughack.delarea.x2 = x, gb.bughack.delarea.y2 = y;
518.             } else if (levl[x][y].typ == IRONBARS) {
519.                 /* novelty effect; allowing digging in front of 'eyes' */
520.                 if (isok(x - 1, y)
521.                     && (levl[x - 1][y].wall_info & W_NONDIGGABLE) != 0) {
522.                     levl[x - 1][y].wall_info &= ~W_NONDIGGABLE;
523.                     if (isok(x - 2, y))
524.                         levl[x - 2][y].wall_info &= ~W_NONDIGGABLE;
525.                 } else if (isok(x + 1, y)
526.                     && (levl[x + 1][y].wall_info & W_NONDIGGABLE) != 0) {
527.                     levl[x + 1][y].wall_info &= ~W_NONDIGGABLE;
528.                     if (isok(x + 2, y))
529.                         levl[x + 2][y].wall_info &= ~W_NONDIGGABLE;
530.                 }
531.             }
532. 
533.     wallification(max(gb.bughack.inarea.x1 - 2, 1),
534.                   max(gb.bughack.inarea.y1 - 2, 0),
535.                   min(gb.bughack.inarea.x2 + 2, COLNO - 1),
536.                   min(gb.bughack.inarea.y2 + 2, ROWNO - 1));
537. 
538.     /* bughack hack for rear-most legs on baalz level; first joint on
539.        both top and bottom gets a bogus extra connection to room area,
540.        producing unwanted rectangles; change back to separated legs */
541.     x = gb.bughack.delarea.x1, y = gb.bughack.delarea.y1;
542.     if (isok(x, y) && (levl[x][y].typ == TLWALL || levl[x][y].typ == TRWALL)
543.         && isok(x, y + 1) && levl[x][y + 1].typ == TUWALL) {
544.         levl[x][y].typ = (levl[x][y].typ == TLWALL) ? BRCORNER : BLCORNER;
545.         levl[x][y + 1].typ = HWALL;
546.         if ((mtmp = m_at(x, y)) != 0) /* something at temporary pool... */
547.             (void) rloc(mtmp, RLOC_ERR|RLOC_NOMSG);
548.     }
549. 
550.     x = gb.bughack.delarea.x2, y = gb.bughack.delarea.y2;
551.     if (isok(x, y) && (levl[x][y].typ == TLWALL || levl[x][y].typ == TRWALL)
552.         && isok(x, y - 1) && levl[x][y - 1].typ == TDWALL) {
553.         levl[x][y].typ = (levl[x][y].typ == TLWALL) ? TRCORNER : TLCORNER;
554.         levl[x][y - 1].typ = HWALL;
555.         if ((mtmp = m_at(x, y)) != 0) /* something at temporary pool... */
556.             (void) rloc(mtmp, RLOC_ERR|RLOC_NOMSG);
557.     }
558. 
559.     /* reset bughack region; set low end to <COLNO,ROWNO> so that
560.        within_bounded_region() in fix_wall_spines() will fail
561.        most quickly--on its first test--when loading other levels */
562.     gb.bughack.inarea.x1 = gb.bughack.delarea.x1 = COLNO;
563.     gb.bughack.inarea.y1 = gb.bughack.delarea.y1 = ROWNO;
564.     gb.bughack.inarea.x2 = gb.bughack.delarea.x2 = 0;
565.     gb.bughack.inarea.y2 = gb.bughack.delarea.y2 = 0;
566. }
567. 
568. /* this is special stuff that the level compiler cannot (yet) handle */
569. void
570. fixup_special(void)
571. {
572.     lev_region *r = gl.lregions;
573.     s_level *sp;
574.     struct d_level lev;
575.     int x, y;
576.     struct mkroom *croom;
577.     boolean added_branch = FALSE;
578. 
579.     if (Is_waterlevel(&u.uz) || Is_airlevel(&u.uz)) {
580.         svl.level.flags.hero_memory = 0;
581.         /* water level is an odd beast - it has to be set up
582.            before calling place_lregions etc. */
583.         setup_waterlevel();
584.     }
585.     for (x = 0; x < gn.num_lregions; x++, r++) {
586.         switch (r->rtype) {
587.         case LR_BRANCH:
588.             added_branch = TRUE;
589.             goto place_it;
590. 
591.         case LR_PORTAL:
592.             if (*r->rname.str >= '0' && *r->rname.str <= '9') {
593.                 /* "chutes and ladders" */
594.                 lev = u.uz;
595.                 lev.dlevel = atoi(r->rname.str);
596.             } else {
597.                 sp = find_level(r->rname.str);
598.                 lev = sp->dlevel;
599.             }
600.             FALLTHROUGH;
601.             /*FALLTHRU*/
602. 
603.         case LR_UPSTAIR:
604.         case LR_DOWNSTAIR:
605.  place_it:
606.             place_lregion(r->inarea.x1, r->inarea.y1, r->inarea.x2,
607.                           r->inarea.y2, r->delarea.x1, r->delarea.y1,
608.                           r->delarea.x2, r->delarea.y2, r->rtype, &lev);
609.             break;
610. 
611.         case LR_TELE:
612.         case LR_UPTELE:
613.         case LR_DOWNTELE:
614.             /* save the region outlines for goto_level() */
615.             if (r->rtype == LR_TELE || r->rtype == LR_UPTELE) {
616.                 svu.updest.lx = r->inarea.x1;
617.                 svu.updest.ly = r->inarea.y1;
618.                 svu.updest.hx = r->inarea.x2;
619.                 svu.updest.hy = r->inarea.y2;
620.                 svu.updest.nlx = r->delarea.x1;
621.                 svu.updest.nly = r->delarea.y1;
622.                 svu.updest.nhx = r->delarea.x2;
623.                 svu.updest.nhy = r->delarea.y2;
624.             }
625.             if (r->rtype == LR_TELE || r->rtype == LR_DOWNTELE) {
626.                 svd.dndest.lx = r->inarea.x1;
627.                 svd.dndest.ly = r->inarea.y1;
628.                 svd.dndest.hx = r->inarea.x2;
629.                 svd.dndest.hy = r->inarea.y2;
630.                 svd.dndest.nlx = r->delarea.x1;
631.                 svd.dndest.nly = r->delarea.y1;
632.                 svd.dndest.nhx = r->delarea.x2;
633.                 svd.dndest.nhy = r->delarea.y2;
634.             }
635.             /* place_lregion gets called from goto_level() */
636.             break;
637.         }
638. 
639.         if (r->rname.str)
640.             free((genericptr_t) r->rname.str), r->rname.str = 0;
641.     }
642. 
643.     /* place dungeon branch if not placed above */
644.     if (!added_branch && Is_branchlev(&u.uz)) {
645.         place_lregion(0, 0, 0, 0, 0, 0, 0, 0, LR_BRANCH, (d_level *) 0);
646.     }
647. 
648.     /* Still need to add some stuff to level file */
649.     if (Is_medusa_level(&u.uz)) {
650.         struct obj *otmp;
651.         int tryct;
652. 
653.         croom = &svr.rooms[0]; /* the first room defined on the medusa level */
654.         for (tryct = rnd(4); tryct; tryct--) {
655.             x = somex(croom);
656.             y = somey(croom);
657.             if (goodpos(x, y, (struct monst *) 0, 0)) {
658.                 int tryct2 = 0;
659. 
660.                 otmp = mk_tt_object(STATUE, x, y);
661.                 while (++tryct2 < 100 && otmp
662.                        && (poly_when_stoned(&mons[otmp->corpsenm])
663.                                 || pm_resistance(&mons[otmp->corpsenm],
664.                                                  MR_STONE))) {
665.                     /* set_corpsenm() handles weight too */
666.                     set_corpsenm(otmp, rndmonnum());
667.                 }
668.             }
669.         }
670. 
671.         if (rn2(2))
672.             otmp = mk_tt_object(STATUE, somex(croom), somey(croom));
673.         else /* Medusa statues don't contain books */
674.             otmp =
675.                 mkcorpstat(STATUE, (struct monst *) 0, (struct permonst *) 0,
676.                            somex(croom), somey(croom), CORPSTAT_NONE);
677.         if (otmp) {
678.             tryct = 0;
679.             while (++tryct < 100
680.                    && (pm_resistance(&mons[otmp->corpsenm], MR_STONE)
681.                        || poly_when_stoned(&mons[otmp->corpsenm]))) {
682.                 /* set_corpsenm() handles weight too */
683.                 set_corpsenm(otmp, rndmonnum());
684.             }
685.         }
686.     } else if (Role_if(PM_CLERIC) && In_quest(&u.uz)) {
687.         /* less chance for undead corpses (lured from lower morgues) */
688.         svl.level.flags.graveyard = 1;
689.     } else if (Is_stronghold(&u.uz)) {
690.         svl.level.flags.graveyard = 1;
691.     } else if (on_level(&u.uz, &baalzebub_level)) {
692.         /* custom wallify the "beetle" potion of the level */
693.         baalz_fixup();
694.     } else if (u.uz.dnum == mines_dnum && gr.ransacked) {
695.        stolen_booty();
696.     }
697. 
698.     if ((sp = Is_special(&u.uz)) != 0 && sp->flags.town) /* Mine Town */
699.         svl.level.flags.has_town = 1;
700. 
701.     if (gl.lregions)
702.         free((genericptr_t) gl.lregions), gl.lregions = 0;
703.     gn.num_lregions = 0;
704. }
705. 
706. staticfn void
707. check_ransacked(const char *s)
708. {
709.     /* this kludge only works as long as orctown is minetn-1 */
710.     gr.ransacked = (u.uz.dnum == mines_dnum && !strcmp(s, "minetn-1"));
711. }
712. 
713. #define ORC_LEADER 1
714. static const char *const orcfruit[] = { "paddle cactus", "dwarven root" };
715. 
716. staticfn void
717. migrate_orc(struct monst *mtmp, unsigned long mflags)
718. {
719.     int nlev, max_depth, cur_depth;
720.     d_level dest;
721. 
722.     cur_depth = (int) depth(&u.uz);
723.     max_depth = dunlevs_in_dungeon(&u.uz)
724.                 + (svd.dungeons[u.uz.dnum].depth_start - 1);
725.     if (mflags == ORC_LEADER) {
726.         /* Note that the orc leader will take possession of any
727.          * remaining stuff not already delivered to other
728.          * orcs between here and the bottom of the mines.
729.          */
730.         nlev = max_depth;
731.         /* once in a blue moon, he won't be at the very bottom */
732.         if (!rn2(40))
733.             nlev--;
734.         mtmp->migflags |= MIGR_LEFTOVERS;
735.     } else {
736.         nlev = rn2((max_depth - cur_depth) + 1) + cur_depth;
737.         if (nlev == cur_depth)
738.             nlev++;
739.         if (nlev > max_depth)
740.             nlev = max_depth;
741.         mtmp->migflags = (mtmp->migflags & ~MIGR_LEFTOVERS);
742.     }
743.     get_level(&dest, nlev);
744.     migrate_to_level(mtmp, ledger_no(&dest), MIGR_RANDOM, (coord *) 0);
745. }
746. 
747. staticfn void
748. shiny_orc_stuff(struct monst *mtmp)
749. {
750.     int gemprob, goldprob, otyp;
751.     struct obj *otmp;
752.     boolean is_captain = (mtmp->data == &mons[PM_ORC_CAPTAIN]);
753. 
754.     /* probabilities */
755.     goldprob = is_captain ? 600 : 300;
756.     gemprob = goldprob / 4;
757.     if (rn2(1000) < goldprob) {
758.         if ((otmp = mksobj(GOLD_PIECE, TRUE, FALSE)) != 0) {
759.             otmp->quan = 1L + rnd(goldprob);
760.             otmp->owt = weight(otmp);
761.             add_to_minv(mtmp, otmp);
762.         }
763.     }
764.     if (rn2(1000) < gemprob) {
765.         if ((otmp = mkobj(GEM_CLASS, FALSE)) != 0) {
766.             if (otmp->otyp == ROCK)
767.                 dealloc_obj(otmp);
768.             else
769.                 add_to_minv(mtmp, otmp);
770.         }
771.     }
772.     if (is_captain || !rn2(8)) {
773.         otyp = shiny_obj(RING_CLASS);
774.         if (otyp != STRANGE_OBJECT && (otmp = mksobj(otyp, TRUE, FALSE)) != 0)
775.             add_to_minv(mtmp, otmp);
776.     }
777. }
778. 
779. staticfn void
780. migr_booty_item(int otyp, const char *gang)
781. {
782.     struct obj *otmp;
783. 
784.     otmp = mksobj_migr_to_species(otyp, (unsigned long) M2_ORC, TRUE, FALSE);
785.     if (otmp && gang) {
786.         new_oname(otmp, Strlen(gang) + 1); /* removes old name if present */
787.         Strcpy(ONAME(otmp), gang);
788.         if (objects[otyp].oc_class == FOOD_CLASS) {
789.             if (otyp == SLIME_MOLD)
790.                 otmp->spe = fruitadd((char *) ROLL_FROM(orcfruit),
791.                                      (struct fruit *) 0);
792.             otmp->quan += (long) rn2(3);
793.             otmp->owt = weight(otmp);
794.         }
795.     }
796. }
797. 
798. staticfn void
799. stolen_booty(void)
800. {
801.     char *gang, gang_name[BUFSZ];
802.     struct monst *mtmp;
803.     int cnt, i, otyp;
804. 
805.     /*
806.      * --------------------------------------------------------
807.      * Mythos:
808.      *
809.      *      A tragic accident has occurred in Frontier Town...
810.      *      It has been overrun by orcs.
811.      *
812.      *      The booty that the orcs took from the town is now
813.      *      in the possession of the orcs that did this and
814.      *      have long since fled the level.
815.      * --------------------------------------------------------
816.      */
817. 
818.     gang = rndorcname(gang_name);
819.     /* create the stuff that the gang took */
820.     cnt = rnd(4);
821.     for (i = 0; i < cnt; ++i)
822.         migr_booty_item(rn2(4) ? TALLOW_CANDLE : WAX_CANDLE, gang);
823.     cnt = rnd(3);
824.     for (i = 0; i < cnt; ++i)
825.         migr_booty_item(SKELETON_KEY, gang);
826.     otyp = rn1((GAUNTLETS_OF_DEXTERITY - LEATHER_GLOVES) + 1, LEATHER_GLOVES);
827.     migr_booty_item(otyp, gang);
828.     cnt = rnd(10);
829.     for (i = 0; i < cnt; ++i) {
830.         /* Food items - but no lembas! (or some other weird things) */
831.         otyp = rn1(TIN - TRIPE_RATION + 1, TRIPE_RATION);
832.         if (otyp != LEMBAS_WAFER
833.             /* exclude meat <anything>, globs of <anything>, kelp
834.                which all have random generation probability of 0
835.                (K-/C-rations do too, but we want to include those) */
836.             && (objects[otyp].oc_prob != 0
837.                 || otyp == C_RATION || otyp == K_RATION)
838.             /* exclude food items which utilize obj->corpsenm because
839.                that field is going to be overloaded for delivery purposes */
840.             && otyp != CORPSE && otyp != EGG && otyp != TIN)
841.             migr_booty_item(otyp, gang);
842.     }
843.     migr_booty_item(rn2(2) ? LONG_SWORD : SILVER_SABER, gang);
844.     /* create the leader of the orc gang */
845.     mtmp = makemon(&mons[PM_ORC_CAPTAIN], 0, 0, MM_NONAME);
846.     if (mtmp) {
847.         mtmp = christen_monst(mtmp, upstart(gang));
848.         mtmp->mpeaceful = 0;
849.         set_malign(mtmp);
850.         shiny_orc_stuff(mtmp);
851.         migrate_orc(mtmp, ORC_LEADER);
852.     }
853.     /* Make most of the orcs on the level be part of the invading gang */
854.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
855.         if (DEADMONSTER(mtmp))
856.             continue;
857. 
858.         if (is_orc(mtmp->data) && !has_mgivenname(mtmp) && rn2(10)) {
859.             /*
860.              * We'll consider the orc captain from the level
861.              * description to be the captain of a rival orc horde
862.              * who is there to see what has transpired, and to
863.              * contemplate future action.
864.              *
865.              * Don't christen the orc captain as a subordinate
866.              * member of the main orc horde.
867.              */
868.             if (mtmp->data != &mons[PM_ORC_CAPTAIN])
869.                 mtmp = christen_orc(mtmp, upstart(gang), "");
870.         }
871.     }
872.     /* Lastly, ensure there's several more orcs from the gang along the way.
873.      * The mechanics are such that they aren't actually identified as
874.      * members of the invading gang until they get their spoils assigned
875.      * to the inventory; handled during that assignment.
876.      */
877.     cnt = rn2(10) + 5;
878.     for (i = 0; i < cnt; ++i) {
879.         int mtyp;
880. 
881.         mtyp = rn2((PM_ORC_SHAMAN - PM_ORC) + 1) + PM_ORC;
882.         mtmp = makemon(&mons[mtyp], 0, 0, MM_NONAME);
883.         if (mtmp) {
884.             shiny_orc_stuff(mtmp);
885.             migrate_orc(mtmp, 0UL);
886.         }
887.     }
888.     gr.ransacked = 0;
889. }
890. 
891. #undef ORC_LEADER
892. 
893. staticfn boolean
894. maze_inbounds(coordxy x, coordxy y)
895. {
896.     return (x >= 2 && y >= 2
897.             && x < gx.x_maze_max && y < gy.y_maze_max
898.             /* isok() test is superfluous here (unless something has
899.                clobbered the static *_maze_max variables) */
900.             && isok(x, y));
901. }
902. 
903. staticfn void
904. maze_remove_deadends(xint16 typ)
905. {
906.     char dirok[4];
907.     coordxy x, y, dir, idx, idx2, dx, dy, dx2, dy2;
908. 
909.     dirok[0] = 0; /* lint suppression */
910.     for (x = 2; x < gx.x_maze_max; x++)
911.         for (y = 2; y < gy.y_maze_max; y++)
912.             if (ACCESSIBLE(levl[x][y].typ) && (x % 2) && (y % 2)) {
913.                 idx = idx2 = 0;
914.                 for (dir = 0; dir < 4; dir++) {
915.                     /* note: mz_move() is a macro which modifies
916.                        one of its first two parameters */
917.                     dx = dx2 = x;
918.                     dy = dy2 = y;
919.                     mz_move(dx, dy, dir);
920.                     if (!maze_inbounds(dx, dy)) {
921.                         idx2++;
922.                         continue;
923.                     }
924.                     mz_move(dx2, dy2, dir);
925.                     mz_move(dx2, dy2, dir);
926.                     if (!maze_inbounds(dx2, dy2)) {
927.                         idx2++;
928.                         continue;
929.                     }
930.                     if (!ACCESSIBLE(levl[dx][dy].typ)
931.                         && ACCESSIBLE(levl[dx2][dy2].typ)) {
932.                         dirok[idx++] = dir;
933.                         idx2++;
934.                     }
935.                 }
936.                 if (idx2 >= 3 && idx > 0) {
937.                     dx = x;
938.                     dy = y;
939.                     dir = dirok[rn2(idx)];
940.                     mz_move(dx, dy, dir);
941.                     levl[dx][dy].typ = typ;
942.                 }
943.             }
944. }
945. 
946. /* Create a maze with specified corridor width and wall thickness
947.  * TODO: rewrite walkfrom so it works on temp space, not levl
948.  */
949. void
950. create_maze(int corrwid, int wallthick, boolean rmdeadends)
951. {
952.     coordxy x,y;
953.     coord mm;
954.     int tmp_xmax = gx.x_maze_max;
955.     int tmp_ymax = gy.y_maze_max;
956.     int rdx = 0;
957.     int rdy = 0;
958.     int scale;
959. 
960.     if (corrwid == -1)
961.         corrwid = rnd(4);
962. 
963.     if (wallthick == -1)
964.         wallthick = rnd(4) - corrwid;
965. 
966.     if (wallthick < 1)
967.         wallthick = 1;
968.     else if (wallthick > 5)
969.         wallthick = 5;
970. 
971.     if (corrwid < 1)
972.         corrwid = 1;
973.     else if (corrwid > 5)
974.         corrwid = 5;
975. 
976.     scale = corrwid + wallthick;
977.     rdx = (gx.x_maze_max / scale);
978.     rdy = (gy.y_maze_max / scale);
979. 
980.     if (svl.level.flags.corrmaze)
981.         for (x = 2; x < (rdx * 2); x++)
982.             for (y = 2; y < (rdy * 2); y++)
983.                 levl[x][y].typ = STONE;
984.     else
985.         for (x = 2; x <= (rdx * 2); x++)
986.             for (y = 2; y <= (rdy * 2); y++)
987.                 levl[x][y].typ = ((x % 2) && (y % 2)) ? STONE : HWALL;
988. 
989.     /* set upper bounds for maze0xy and walkfrom */
990.     gx.x_maze_max = (rdx * 2);
991.     gy.y_maze_max = (rdy * 2);
992. 
993.     /* create maze */
994.     maze0xy(&mm);
995.     walkfrom((int) mm.x, (int) mm.y, 0);
996. 
997.     if (rmdeadends)
998.         maze_remove_deadends((svl.level.flags.corrmaze) ? CORR : ROOM);
999. 
1000.     /* restore bounds */
1001.     gx.x_maze_max = tmp_xmax;
1002.     gy.y_maze_max = tmp_ymax;
1003. 
1004.     /* scale maze up if needed */
1005.     if (scale > 2) {
1006.         char tmpmap[COLNO][ROWNO];
1007.         int mx, my, dx, dy, rx = 1, ry = 1;
1008. 
1009.         /* back up the existing smaller maze */
1010.         for (x = 1; x < gx.x_maze_max; x++)
1011.             for (y = 1; y < gy.y_maze_max; y++) {
1012.                 tmpmap[x][y] = levl[x][y].typ;
1013.             }
1014. 
1015.         /* do the scaling */
1016.         rx = x = 2;
1017.         while (rx < gx.x_maze_max) {
1018.             mx = (x % 2) ? corrwid : (x == 2 || x == rdx * 2) ? 1 : wallthick;
1019.             ry = y = 2;
1020.             while (ry < gy.y_maze_max) {
1021.                 my = (y % 2) ? corrwid
1022.                      : (y == 2 || y == rdy * 2) ? 1
1023.                        : wallthick;
1024.                 for (dx = 0; dx < mx; dx++)
1025.                     for (dy = 0; dy < my; dy++) {
1026.                         if (rx + dx >= gx.x_maze_max
1027.                             || ry + dy >= gy.y_maze_max)
1028.                             break;
1029.                         levl[rx + dx][ry + dy].typ = tmpmap[x][y];
1030.                     }
1031.                 ry += my;
1032.                 y++;
1033.             }
1034.             rx += mx;
1035.             x++;
1036.         }
1037. 
1038.     }
1039. }
1040. 
1041. void
1042. pick_vibrasquare_location(void)
1043. {
1044.     coordxy x, y;
1045.     stairway *stway;
1046.     int trycnt = 0;
1047.     /* these are also defined in mklev.c and they may not be appropriate
1048.        for mazes with corridors wider than 1 or for cavernous levels */
1049. #define x_maze_min 2
1050. #define y_maze_min 2
1051. 
1052.     /*
1053.      * Pick a position where the stairs down to Moloch's Sanctum
1054.      * level will ultimately be created.  At that time, an area
1055.      * will be altered:  walls removed, moat and traps generated,
1056.      * boulders destroyed.  The position picked here must ensure
1057.      * that that invocation area won't extend off the map.
1058.      *
1059.      * We actually allow up to 2 squares around the usual edge of
1060.      * the area to get truncated; see mkinvokearea(mklev.c).
1061.      */
1062. #define INVPOS_X_MARGIN (6 - 2)
1063. #define INVPOS_Y_MARGIN (5 - 2)
1064. #define INVPOS_DISTANCE 11
1065.     int x_range = gx.x_maze_max - x_maze_min - 2 * INVPOS_X_MARGIN - 1,
1066.         y_range = gy.y_maze_max - y_maze_min - 2 * INVPOS_Y_MARGIN - 1;
1067. 
1068.     if (x_range <= INVPOS_X_MARGIN || y_range <= INVPOS_Y_MARGIN
1069.         || (x_range * y_range) <= (INVPOS_DISTANCE * INVPOS_DISTANCE)) {
1070.         debugpline2("svi.inv_pos: maze is too small! (%d x %d)",
1071.                     gx.x_maze_max, gy.y_maze_max);
1072.     }
1073.     svi.inv_pos.x = svi.inv_pos.y = 0; /*{occupied() => invocation_pos()}*/
1074.     do {
1075.         x = rn1(x_range, x_maze_min + INVPOS_X_MARGIN + 1);
1076.         y = rn1(y_range, y_maze_min + INVPOS_Y_MARGIN + 1);
1077.         /* we don't want it to be too near the stairs, nor
1078.            to be on a spot that's already in use (wall|trap) */
1079.         if (++trycnt > 1000)
1080.             break;
1081.     } while (((stway = stairway_find_dir(TRUE)) != 0)
1082.              && (x == stway->sx || y == stway->sy /*(direct line)*/
1083.                  || abs(x - stway->sx) == abs(y - stway->sy)
1084.                  || distmin(x, y, stway->sx, stway->sy) <= INVPOS_DISTANCE
1085.                  || !SPACE_POS(levl[x][y].typ) || occupied(x, y)));
1086.     svi.inv_pos.x = x;
1087.     svi.inv_pos.y = y;
1088. #undef INVPOS_X_MARGIN
1089. #undef INVPOS_Y_MARGIN
1090. #undef INVPOS_DISTANCE
1091. #undef x_maze_min
1092. #undef y_maze_min
1093. }
1094. 
1095. /* add objects and monsters to random maze */
1096. staticfn void
1097. populate_maze(void)
1098. {
1099.     int i;
1100.     coord mm;
1101. 
1102.     for (i = rn1(8, 11); i; i--) {
1103.         mazexy(&mm);
1104.         (void) mkobj_at(rn2(2) ? GEM_CLASS : RANDOM_CLASS, mm.x, mm.y, TRUE);
1105.     }
1106.     for (i = rn1(10, 2); i; i--) {
1107.         mazexy(&mm);
1108.         (void) mksobj_at(BOULDER, mm.x, mm.y, TRUE, FALSE);
1109.     }
1110.     for (i = rn2(3); i; i--) {
1111.         mazexy(&mm);
1112.         (void) makemon(&mons[PM_MINOTAUR], mm.x, mm.y, NO_MM_FLAGS);
1113.     }
1114.     for (i = rn1(5, 7); i; i--) {
1115.         mazexy(&mm);
1116.         (void) makemon((struct permonst *) 0, mm.x, mm.y, NO_MM_FLAGS);
1117.     }
1118.     for (i = rn1(6, 7); i; i--) {
1119.         mazexy(&mm);
1120.         (void) mkgold(0L, mm.x, mm.y);
1121.     }
1122.     for (i = rn1(6, 7); i; i--)
1123.         mktrap(0, MKTRAP_MAZEFLAG, (struct mkroom *) 0, (coord *) 0);
1124. }
1125. 
1126. void
1127. makemaz(const char *s)
1128. {
1129.     char protofile[20];
1130.     s_level *sp = Is_special(&u.uz);
1131.     coord mm;
1132. 
1133.     if (*s) {
1134.         if (sp && sp->rndlevs)
1135.             Snprintf(protofile, sizeof protofile,
1136.                      "%s-%d", s, rnd((int) sp->rndlevs));
1137.         else
1138.             Strcpy(protofile, s);
1139.     } else if (*(svd.dungeons[u.uz.dnum].proto)) {
1140.         if (dunlevs_in_dungeon(&u.uz) > 1) {
1141.             if (sp && sp->rndlevs)
1142.                 Snprintf(protofile, sizeof protofile,
1143.                          "%s%d-%d", svd.dungeons[u.uz.dnum].proto,
1144.                          dunlev(&u.uz), rnd((int) sp->rndlevs));
1145.             else
1146.                 Snprintf(protofile, sizeof protofile,
1147.                          "%s%d", svd.dungeons[u.uz.dnum].proto,
1148.                          dunlev(&u.uz));
1149.         } else if (sp && sp->rndlevs) {
1150.             Snprintf(protofile, sizeof protofile,
1151.                      "%s-%d", svd.dungeons[u.uz.dnum].proto,
1152.                      rnd((int) sp->rndlevs));
1153.         } else
1154.             Strcpy(protofile, svd.dungeons[u.uz.dnum].proto);
1155. 
1156.     } else
1157.         Strcpy(protofile, "");
1158. 
1159.     /* SPLEVTYPE format is "level-choice,level-choice"... */
1160.     if (wizard && *protofile && sp && sp->rndlevs) {
1161.         char *ep = getenv("SPLEVTYPE"); /* not nh_getenv */
1162. 
1163.         if (ep) {
1164.             /* strrchr always succeeds due to code in prior block */
1165.             int len = (int) ((strrchr(protofile, '-') - protofile) + 1);
1166. 
1167.             while (ep && *ep) {
1168.                 if (!strncmp(ep, protofile, len)) {
1169.                     int pick = atoi(ep + len);
1170. 
1171.                     /* use choice only if valid */
1172.                     if (pick > 0 && pick <= (int) sp->rndlevs)
1173.                         Sprintf(protofile + len, "%d", pick);
1174.                     break;
1175.                 } else {
1176.                     ep = strchr(ep, ',');
1177.                     if (ep)
1178.                         ++ep;
1179.                 }
1180.             }
1181.         }
1182.     }
1183. 
1184.     if (*protofile) {
1185.         check_ransacked(protofile);
1186.         Strcat(protofile, LEV_EXT);
1187.         gi.in_mk_themerooms = FALSE;
1188.         if (load_special(protofile)) {
1189.             /* some levels can end up with monsters
1190.                on dead mon list, including light source monsters */
1191.             dmonsfree();
1192.             return; /* no mazification right now */
1193.         }
1194.         impossible("Couldn't load \"%s\" - making a maze.", protofile);
1195.     }
1196. 
1197.     svl.level.flags.is_maze_lev = 1;
1198.     svl.level.flags.corrmaze = !rn2(3);
1199. 
1200.     if (!Invocation_lev(&u.uz) && rn2(2)) {
1201.         create_maze(-1, -1, !rn2(5));
1202.     } else {
1203.         create_maze(1, 1, FALSE);
1204.     }
1205. 
1206.     if (!svl.level.flags.corrmaze)
1207.         wallification(2, 2, gx.x_maze_max, gy.y_maze_max);
1208. 
1209.     mazexy(&mm);
1210.     mkstairs(mm.x, mm.y, 1, (struct mkroom *) 0, FALSE); /* up */
1211.     if (!Invocation_lev(&u.uz)) {
1212.         mazexy(&mm);
1213.         mkstairs(mm.x, mm.y, 0, (struct mkroom *) 0, FALSE); /* down */
1214.     } else { /* choose "vibrating square" location */
1215.         pick_vibrasquare_location();
1216.         maketrap(svi.inv_pos.x, svi.inv_pos.y, VIBRATING_SQUARE);
1217.     }
1218. 
1219.     /* place branch stair or portal */
1220.     place_branch(Is_branchlev(&u.uz), 0, 0);
1221. 
1222.     populate_maze();
1223. }
1224. 
1225. #ifdef MICRO
1226. /* Make the mazewalk iterative by faking a stack.  This is needed to
1227.  * ensure the mazewalk is successful in the limited stack space of
1228.  * the program.  This iterative version uses the minimum amount of stack
1229.  * that is totally safe.
1230.  */
1231. void
1232. walkfrom(coordxy x, coordxy y, schar typ)
1233. {
1234. #define CELLS (ROWNO * COLNO) / 4            /* a maze cell is 4 squares */
1235.     char mazex[CELLS + 1], mazey[CELLS + 1]; /* char's are OK */
1236.     int q, a, dir, pos;
1237.     int dirs[4];
1238. 
1239.     if (!typ) {
1240.         if (svl.level.flags.corrmaze)
1241.             typ = CORR;
1242.         else
1243.             typ = ROOM;
1244.     }
1245. 
1246.     pos = 1;
1247.     mazex[pos] = (char) x;
1248.     mazey[pos] = (char) y;
1249.     while (pos) {
1250.         x = (int) mazex[pos];
1251.         y = (int) mazey[pos];
1252.         if (!IS_DOOR(levl[x][y].typ)) {
1253.             /* might still be on edge of MAP, so don't overwrite */
1254.             levl[x][y].typ = typ;
1255.             levl[x][y].flags = 0;
1256.         }
1257.         q = 0;
1258.         for (a = 0; a < 4; a++)
1259.             if (okay(x, y, a))
1260.                 dirs[q++] = a;
1261.         if (!q)
1262.             pos--;
1263.         else {
1264.             dir = dirs[rn2(q)];
1265.             mz_move(x, y, dir);
1266.             levl[x][y].typ = typ;
1267.             mz_move(x, y, dir);
1268.             pos++;
1269.             if (pos > CELLS)
1270.                 panic("Overflow in walkfrom");
1271.             mazex[pos] = (char) x;
1272.             mazey[pos] = (char) y;
1273.         }
1274.     }
1275. }
1276. #else /* !MICRO */
1277. 
1278. void
1279. walkfrom(coordxy x, coordxy y, schar typ)
1280. {
1281.     int q, a, dir;
1282.     int dirs[4];
1283. 
1284.     if (!typ) {
1285.         if (svl.level.flags.corrmaze)
1286.             typ = CORR;
1287.         else
1288.             typ = ROOM;
1289.     }
1290. 
1291.     if (!IS_DOOR(levl[x][y].typ)) {
1292.         /* might still be on edge of MAP, so don't overwrite */
1293.         levl[x][y].typ = typ;
1294.         levl[x][y].flags = 0;
1295.     }
1296. 
1297.     while (1) {
1298.         q = 0;
1299.         for (a = 0; a < 4; a++)
1300.             if (okay(x, y, a))
1301.                 dirs[q++] = a;
1302.         if (!q)
1303.             return;
1304.         dir = dirs[rn2(q)];
1305.         mz_move(x, y, dir);
1306.         levl[x][y].typ = typ;
1307.         mz_move(x, y, dir);
1308.         walkfrom(x, y, typ);
1309.     }
1310. }
1311. #endif /* ?MICRO */
1312. 
1313. /* find random point in generated corridors,
1314.    so we don't create items in moats, bunkers, or walls */
1315. void
1316. mazexy(coord *cc)
1317. {
1318.     coordxy x, y;
1319.     int allowedtyp = (svl.level.flags.corrmaze ? CORR : ROOM);
1320.     int cpt = 0;
1321. 
1322.     do {
1323.         /* once upon a time this only considered odd values greater than 2
1324.            and less than N (for N=={x,y}_maze_max) because even values were
1325.            where maze walls always got placed; when wider maze corridors
1326.            were introduced it was changed to 1+rn2(N) which is just an
1327.            obscure way to get rnd(N); probably ought to be using 2+rn2(N-1)
1328.            to exclude the maze's outer boundary walls; trying and rejecting
1329.            those walls will waste some of the 100 random attempts... */
1330.         x = rnd(gx.x_maze_max);
1331.         y = rnd(gy.y_maze_max);
1332.         if (levl[x][y].typ == allowedtyp) {
1333.             cc->x = x;
1334.             cc->y = y;
1335.             return;
1336.         }
1337.     } while (++cpt < 100);
1338.     /* 100 random attempts failed; systematically try every possibility */
1339.     for (x = 1; x <= gx.x_maze_max; x++)
1340.         for (y = 1; y <= gy.y_maze_max; y++)
1341.             if (levl[x][y].typ == allowedtyp) {
1342.                 cc->x = x;
1343.                 cc->y = y;
1344.                 return;
1345.             }
1346.     /* every spot on the area of map allowed for mazes has been rejected */
1347.     panic("mazexy: can't find a place!");
1348.     /*NOTREACHED*/
1349.     return;
1350. }
1351. 
1352. void
1353. get_level_extends(
1354.     coordxy *left, coordxy *top,
1355.     coordxy *right, coordxy *bottom)
1356. {
1357.     coordxy x, y;
1358.     unsigned typ;
1359.     struct rm *lev;
1360.     boolean found, nonwall;
1361.     coordxy xmin, xmax, ymin, ymax;
1362. 
1363.     found = nonwall = FALSE;
1364.     for (xmin = 0; !found && xmin <= COLNO; xmin++) {
1365.         lev = &levl[xmin][0];
1366.         for (y = 0; y <= ROWNO - 1; y++, lev++) {
1367.             typ = lev->typ;
1368.             if (typ != STONE) {
1369.                 found = TRUE;
1370.                 if (!IS_WALL(typ))
1371.                     nonwall = TRUE;
1372.             }
1373.         }
1374.     }
1375.     xmin -= (nonwall || !svl.level.flags.is_maze_lev) ? 2 : 1;
1376.     if (xmin < 0)
1377.         xmin = 0;
1378. 
1379.     found = nonwall = FALSE;
1380.     for (xmax = COLNO - 1; !found && xmax >= 0; xmax--) {
1381.         lev = &levl[xmax][0];
1382.         for (y = 0; y <= ROWNO - 1; y++, lev++) {
1383.             typ = lev->typ;
1384.             if (typ != STONE) {
1385.                 found = TRUE;
1386.                 if (!IS_WALL(typ))
1387.                     nonwall = TRUE;
1388.             }
1389.         }
1390.     }
1391.     xmax += (nonwall || !svl.level.flags.is_maze_lev) ? 2 : 1;
1392.     if (xmax >= COLNO)
1393.         xmax = COLNO - 1;
1394. 
1395.     found = nonwall = FALSE;
1396.     for (ymin = 0; !found && ymin <= ROWNO; ymin++) {
1397.         lev = &levl[xmin][ymin];
1398.         for (x = xmin; x <= xmax; x++, lev += ROWNO) {
1399.             typ = lev->typ;
1400.             if (typ != STONE) {
1401.                 found = TRUE;
1402.                 if (!IS_WALL(typ))
1403.                     nonwall = TRUE;
1404.             }
1405.         }
1406.     }
1407.     ymin -= (nonwall || !svl.level.flags.is_maze_lev) ? 2 : 1;
1408. 
1409.     found = nonwall = FALSE;
1410.     for (ymax = ROWNO - 1; !found && ymax >= 0; ymax--) {
1411.         lev = &levl[xmin][ymax];
1412.         for (x = xmin; x <= xmax; x++, lev += ROWNO) {
1413.             typ = lev->typ;
1414.             if (typ != STONE) {
1415.                 found = TRUE;
1416.                 if (!IS_WALL(typ))
1417.                     nonwall = TRUE;
1418.             }
1419.         }
1420.     }
1421.     ymax += (nonwall || !svl.level.flags.is_maze_lev) ? 2 : 1;
1422. 
1423.     *left = xmin;
1424.     *right = xmax;
1425.     *top = ymin;
1426.     *bottom = ymax;
1427. }
1428. 
1429. /* put a non-diggable/non-phaseable boundary around the initial portion
1430.  * of a level map. assumes that no level will initially put things
1431.  * beyond the isok() range.
1432.  *
1433.  * we can't bound unconditionally on the last line with something in it,
1434.  * because that something might be a niche which was already reachable,
1435.  * so the boundary would be breached
1436.  *
1437.  * we can't bound unconditionally on one beyond the last line, because
1438.  * that provides a window of abuse for wallified special levels
1439.  */
1440. void
1441. bound_digging(void)
1442. {
1443.     coordxy x, y;
1444.     coordxy xmin, xmax, ymin, ymax;
1445. 
1446.     if (Is_earthlevel(&u.uz))
1447.         return; /* everything diggable here */
1448. 
1449.     get_level_extends(&xmin, &ymin, &xmax, &ymax);
1450. 
1451.     for (x = 0; x < COLNO; x++)
1452.         for (y = 0; y < ROWNO; y++)
1453.             if (IS_STWALL(levl[x][y].typ)) {
1454.                 /* undiggable walls at edges, ... */
1455.                 if (y <= ymin || y >= ymax || x <= xmin || x >= xmax)
1456.                     levl[x][y].wall_info |= W_NONDIGGABLE;
1457.                 /* one tile past that, everything is also unphaseable */
1458.                 if (y < ymin || y > ymax || x < xmin || x > xmax)
1459.                     levl[x][y].wall_info |= W_NONPASSWALL;
1460.             }
1461. }
1462. 
1463. void
1464. mkportal(coordxy x, coordxy y, xint16 todnum, xint16 todlevel)
1465. {
1466.     /* a portal "trap" must be matched by a
1467.        portal in the destination dungeon/dlevel */
1468.     struct trap *ttmp = maketrap(x, y, MAGIC_PORTAL);
1469. 
1470.     if (!ttmp) {
1471.         impossible("portal on top of portal?");
1472.         return;
1473.     }
1474.     debugpline4("mkportal: at <%d,%d>, to %s, level %d", x, y,
1475.                 svd.dungeons[todnum].dname, todlevel);
1476.     ttmp->dst.dnum = todnum;
1477.     ttmp->dst.dlevel = todlevel;
1478.     return;
1479. }
1480. 
1481. /* augment the Plane of Fire; called from goto_level() when arriving and
1482.    moveloop_core() when on the level */
1483. void
1484. fumaroles(void)
1485. {
1486.     xint16 n, nmax = rn2(3);
1487.     int sizemin = 5;
1488.     boolean snd = FALSE, loud = FALSE;
1489. 
1490.     if (Is_firelevel(&u.uz)) {
1491.         nmax++;
1492.         sizemin += 5;
1493.     }
1494.     if (svl.level.flags.temperature > 0) {
1495.         nmax++;
1496.         sizemin += 5;
1497.     }
1498. 
1499.     for (n = nmax; n; n--) {
1500.         coordxy x = rn1(COLNO - 4, 3);
1501.         coordxy y = rn1(ROWNO - 4, 3);
1502. 
1503.         if (levl[x][y].typ == LAVAPOOL) {
1504.             NhRegion *r = create_gas_cloud(x, y, rn1(10, sizemin), rn1(10, 5));
1505. 
1506.             clear_heros_fault(r);
1507.             snd = TRUE;
1508.             if (distu(x, y) < 15)
1509.                 loud = TRUE;
1510.         }
1511.     }
1512.     if (snd && !Deaf)
1513.         Norep("You hear a %swhoosh!", loud ? "loud " : "");  /* Deaf-aware */
1514. }
1515. 
1516. /*
1517.  * Special waterlevel stuff in endgame (TH).
1518.  *
1519.  * Some of these functions would probably logically belong to some
1520.  * other source files, but they are all so nicely encapsulated here.
1521.  */
1522. 
1523. /* bubble movement boundaries */
1524. #define gbxmin (svx.xmin + 1)
1525. #define gbymin (svy.ymin + 1)
1526. #define gbxmax (svx.xmax - 1)
1527. #define gbymax (svy.ymax - 1)
1528. 
1529. /* the bubble hero is in */
1530. static struct bubble *hero_bubble = NULL;
1531. 
1532. staticfn void set_wportal(void);
1533. staticfn void mk_bubble(coordxy, coordxy, int);
1534. staticfn void mv_bubble(struct bubble *, coordxy, coordxy, boolean);
1535. 
1536. /* augment the Planes of Water (for bubbles) and Air (for clouds); called
1537.    from goto_level() when arriving and moveloop_core() when on the level */
1538. void
1539. movebubbles(void)
1540. {
1541.     static const struct rm water_pos = {
1542.         cmap_b_to_glyph(S_water), WATER, 0, 0, 0, 0, 0, 0, 0, 0
1543.     }, air_pos = {
1544.         cmap_b_to_glyph(S_cloud), AIR, 0, 0, 0, 1, 0, 0, 0, 0
1545.     };
1546.     static boolean up = FALSE;
1547.     struct bubble *b;
1548.     struct container *cons;
1549.     struct trap *btrap;
1550.     coordxy x, y;
1551.     int i, j, bcpin = 0;
1552. 
1553.     /* set up the portal the first time bubbles are moved */
1554.     if (!gw.wportal)
1555.         set_wportal();
1556. 
1557.     vision_recalc(2);
1558. 
1559.     hero_bubble = NULL;
1560. 
1561.     if (Is_waterlevel(&u.uz)) {
1562.         /* keep attached ball&chain separate from bubble objects */
1563.         if (Punished)
1564.             bcpin = unplacebc_and_covet_placebc();
1565. 
1566.         /*
1567.          * Pick up everything inside of a bubble then fill all bubble
1568.          * locations.
1569.          */
1570.         for (b = up ? svb.bbubbles : ge.ebubbles; b;
1571.              b = up ? b->next : b->prev) {
1572.             if (b->cons)
1573.                 panic("movebubbles: cons != null");
1574.             for (i = 0, x = b->x; i < (int) b->bm[0]; i++, x++)
1575.                 for (j = 0, y = b->y; j < (int) b->bm[1]; j++, y++)
1576.                     if (b->bm[j + 2] & (1 << i)) {
1577.                         if (!isok(x, y)) {
1578.                             impossible("movebubbles: bad pos (%d,%d)", x, y);
1579.                             continue;
1580.                         }
1581. 
1582.                         /* pick up objects, monsters, hero, and traps */
1583.                         if (OBJ_AT(x, y)) {
1584.                             struct obj *olist = (struct obj *) 0, *otmp;
1585. 
1586.                             while ((otmp = svl.level.objects[x][y]) != 0) {
1587.                                 remove_object(otmp);
1588.                                 otmp->ox = otmp->oy = 0;
1589.                                 otmp->nexthere = olist;
1590.                                 olist = otmp;
1591.                             }
1592. 
1593.                             cons = (struct container *) alloc(sizeof *cons);
1594.                             cons->x = x;
1595.                             cons->y = y;
1596.                             cons->what = CONS_OBJ;
1597.                             cons->list = (genericptr_t) olist;
1598.                             cons->next = b->cons;
1599.                             b->cons = cons;
1600.                         }
1601.                         if (MON_AT(x, y)) {
1602.                             struct monst *mon = m_at(x, y);
1603. 
1604.                             cons = (struct container *) alloc(sizeof *cons);
1605.                             cons->x = x;
1606.                             cons->y = y;
1607.                             cons->what = CONS_MON;
1608.                             cons->list = (genericptr_t) mon;
1609. 
1610.                             cons->next = b->cons;
1611.                             b->cons = cons;
1612. 
1613.                             if (mon->wormno)
1614.                                 remove_worm(mon);
1615.                             else
1616.                                 remove_monster(x, y);
1617. 
1618.                             newsym(x, y); /* clean up old position */
1619.                             mon->mx = mon->my = 0;
1620.                             mon->mstate |= MON_BUBBLEMOVE;
1621.                         }
1622.                         if (!u.uswallow && u_at(x, y)) {
1623.                             cons = (struct container *) alloc(sizeof *cons);
1624.                             cons->x = x;
1625.                             cons->y = y;
1626.                             cons->what = CONS_HERO;
1627.                             cons->list = (genericptr_t) 0;
1628. 
1629.                             cons->next = b->cons;
1630.                             b->cons = cons;
1631.                             hero_bubble = b;
1632.                         }
1633.                         if ((btrap = t_at(x, y)) != 0) {
1634.                             cons = (struct container *) alloc(sizeof *cons);
1635.                             cons->x = x;
1636.                             cons->y = y;
1637.                             cons->what = CONS_TRAP;
1638.                             cons->list = (genericptr_t) btrap;
1639. 
1640.                             cons->next = b->cons;
1641.                             b->cons = cons;
1642.                         }
1643. 
1644.                         levl[x][y] = water_pos;
1645.                         block_point(x, y);
1646.                     }
1647.         }
1648.     } else if (Is_airlevel(&u.uz)) {
1649.         boolean xedge, yedge;
1650. 
1651.         for (x = 1; x <= (COLNO - 1); x++)
1652.             for (y = 0; y <= (ROWNO - 1); y++) {
1653.                 levl[x][y] = air_pos;
1654.                 recalc_block_point(x, y);
1655.                 /* all air or all cloud around the perimeter of the Air
1656.                    level tends to look strange; break up the pattern */
1657.                 xedge = (boolean) (x < gbxmin || x > gbxmax);
1658.                 yedge = (boolean) (y < gbymin || y > gbymax);
1659.                 if (xedge || yedge) {
1660.                     if (!rn2(xedge ? 3 : 5)) {
1661.                         levl[x][y].typ = CLOUD;
1662.                         block_point(x, y);
1663.                     }
1664.                 }
1665.             }
1666.     }
1667. 
1668.     /*
1669.      * Every second time traverse down.  This is because otherwise
1670.      * all the junk that changes owners when bubbles overlap
1671.      * would eventually end up in the last bubble in the chain.
1672.      */
1673.     up = !up;
1674.     for (b = up ? svb.bbubbles : ge.ebubbles; b; b = up ? b->next : b->prev) {
1675.         int rx = rn2(3), ry = rn2(3);
1676. 
1677.         mv_bubble(b, b->dx + 1 - (!b->dx ? rx : (rx ? 1 : 0)),
1678.                   b->dy + 1 - (!b->dy ? ry : (ry ? 1 : 0)), FALSE);
1679.     }
1680. 
1681.     /* put attached ball&chain back */
1682.     if (Is_waterlevel(&u.uz) && Punished)
1683.         lift_covet_and_placebc(bcpin);
1684.     gv.vision_full_recalc = 1;
1685. }
1686. 
1687. /* when moving in water, possibly (1 in 3) alter the intended destination */
1688. void
1689. water_friction(void)
1690. {
1691.     coordxy x, y, dx, dy;
1692.     boolean eff = FALSE;
1693. 
1694.     if (Swimming && rn2(4))
1695.         return; /* natural swimmers have advantage */
1696. 
1697.     if (u.dx && !rn2(!u.dy ? 3 : 6)) { /* 1/3 chance or half that */
1698.         /* cancel delta x and choose an arbitrary delta y value */
1699.         x = u.ux;
1700.         do {
1701.             dy = rn2(3) - 1; /* -1, 0, 1 */
1702.             y = u.uy + dy;
1703.         } while (dy && (!isok(x, y) || !is_pool(x, y)));
1704.         u.dx = 0;
1705.         u.dy = dy;
1706.         eff = TRUE;
1707.     } else if (u.dy && !rn2(!u.dx ? 3 : 5)) { /* 1/3 or 1/5*(5/6) */
1708.         /* cancel delta y and choose an arbitrary delta x value */
1709.         y = u.uy;
1710.         do {
1711.             dx = rn2(3) - 1; /* -1 .. 1 */
1712.             x = u.ux + dx;
1713.         } while (dx && (!isok(x, y) || !is_pool(x, y)));
1714.         u.dy = 0;
1715.         u.dx = dx;
1716.         eff = TRUE;
1717.     }
1718.     if (eff)
1719.         pline("Water turbulence affects your movements.");
1720. }
1721. 
1722. void
1723. save_waterlevel(NHFILE *nhfp)
1724. {
1725.     struct bubble *b;
1726. 
1727.     if (!svb.bbubbles)
1728.         return;
1729. 
1730.     if (update_file(nhfp)) {
1731.         int n = 0;
1732.         for (b = svb.bbubbles; b; b = b->next)
1733.             ++n;
1734.         Sfo_int(nhfp, &n, "waterlevel-bubble_count");
1735.         Sfo_int(nhfp, &svx.xmin, "waterlevel-xmin");
1736.         Sfo_int(nhfp, &svy.ymin, "waterlevel-ymin");
1737.         Sfo_int(nhfp, &svx.xmax, "waterlevel-xmax");
1738.         Sfo_int(nhfp, &svy.ymax, "waterlevel-ymax");
1739.         for (b = svb.bbubbles; b; b = b->next) {
1740.             Sfo_bubble(nhfp, b, "waterlevel-bubble");
1741.         }
1742.     }
1743.     if (release_data(nhfp))
1744.         unsetup_waterlevel();
1745. }
1746. #endif /* !SFCTOOL */
1747. 
1748. /* restoring air bubbles on Plane of Water or clouds on Plane of Air */
1749. void
1750. restore_waterlevel(NHFILE *nhfp)
1751. {
1752.     struct bubble *b = (struct bubble *) 0, *btmp;
1753.     int i, n = 0;
1754. 
1755. #ifdef SFCTOOL
1756.     svb.bbubbles = (struct bubble *) 0;
1757.     /* set_wportal(); */
1758. #endif
1759. 
1760.     Sfi_int(nhfp, &n, "waterlevel-bubble_count");
1761.     Sfi_int(nhfp, &svx.xmin, "waterlevel-xmin");
1762.     Sfi_int(nhfp, &svy.ymin, "waterlevel-ymin");
1763.     Sfi_int(nhfp, &svx.xmax, "waterlevel-xmax");
1764.     Sfi_int(nhfp, &svy.ymax, "waterlevel-ymax");
1765.     for (i = 0; i < n; i++) {
1766.         btmp = b;
1767.         b = (struct bubble *) alloc((unsigned) sizeof *b);
1768.         Sfi_bubble(nhfp, b, "waterlevel-bubble");
1769.         if (btmp) {
1770.             btmp->next = b;
1771.             b->prev = btmp;
1772.         } else {
1773.             svb.bbubbles = b;
1774.             b->prev = (struct bubble *) 0;
1775.         }
1776. #ifndef SFCTOOL
1777.         mv_bubble(b, 0, 0, TRUE);
1778. #endif
1779.     }
1780. #ifndef SFCTOOL
1781.     ge.ebubbles = b;
1782.     if (b) {
1783.         b->next = (struct bubble *) 0;
1784.     } else {
1785.         /* avoid "saving and reloading may fix this" */
1786.         program_state.something_worth_saving = 0;
1787.         /* during restore, information about what level this is might not
1788.            be available so we're wishy-washy about what we describe */
1789.         impossible("No %s to restore?",
1790.                    (Is_waterlevel(&u.uz) || Is_waterlevel(&gu.uz_save))
1791.                    ? "air bubbles"
1792.                    : (Is_airlevel(&u.uz) || Is_airlevel(&gu.uz_save))
1793.                      ? "clouds"
1794.                      : "air bubbles or clouds");
1795.         program_state.something_worth_saving = 1;
1796.     }
1797. #endif
1798. }
1799. 
1800. #ifndef SFCTOOL
1801. staticfn void
1802. set_wportal(void)
1803. {
1804.     /* there better be only one magic portal on water level... */
1805.     for (gw.wportal = gf.ftrap; gw.wportal; gw.wportal = gw.wportal->ntrap)
1806.         if (gw.wportal->ttyp == MAGIC_PORTAL)
1807.             return;
1808.     impossible("set_wportal(): no portal!");
1809. }
1810. 
1811. staticfn void
1812. setup_waterlevel(void)
1813. {
1814.     int typ, glyph;
1815.     coordxy x, y, xskip, yskip;
1816. 
1817.     if (!Is_waterlevel(&u.uz) && !Is_airlevel(&u.uz))
1818.         panic("setup_waterlevel(): [%d:%d] neither 'Water' nor 'Air'",
1819.               (int) u.uz.dnum, (int) u.uz.dlevel);
1820. 
1821.     /* ouch, hardcoded... (file scope statics and used in bxmin,bymax,&c) */
1822.     svx.xmin = 3;
1823.     svy.ymin = 1;
1824.     /* use separate statements so that compiler won't complain about min()
1825.        comparing two constants; the alternative is to do this in the
1826.        preprocessor: #if (20 > ROWNO-1) ymax=ROWNO-1 #else ymax=20 #endif */
1827.     svx.xmax = 78;
1828.     svx.xmax = min(svx.xmax, (COLNO - 1) - 1);
1829.     svy.ymax = 20;
1830.     svy.ymax = min(svy.ymax, (ROWNO - 1));
1831. 
1832.     /* entire level is remembered as one glyph and any unspecified portion
1833.        should default to level's base element rather than to usual stone */
1834.     glyph = cmap_to_glyph(Is_waterlevel(&u.uz) ? S_water : S_air);
1835.     typ = Is_waterlevel(&u.uz) ? WATER : AIR;
1836. 
1837.     /* set unspecified terrain (stone) and hero's memory to water or air */
1838.     for (x = 1; x <= COLNO - 1; x++)
1839.         for (y = 0; y <= ROWNO - 1; y++) {
1840.             levl[x][y].glyph = glyph;
1841.             if (levl[x][y].typ == STONE)
1842.                 levl[x][y].typ = typ;
1843.         }
1844. 
1845.     /* make bubbles */
1846.     if (Is_waterlevel(&u.uz)) {
1847.         xskip = 10 + rn2(10);
1848.         yskip = 4 + rn2(4);
1849.     } else {
1850.         xskip = 6 + rn2(4);
1851.         yskip = 3 + rn2(3);
1852.     }
1853. 
1854.     for (x = gbxmin; x <= gbxmax; x += xskip)
1855.         for (y = gbymin; y <= gbymax; y += yskip)
1856.             mk_bubble(x, y, rn2(7));
1857. }
1858. 
1859. staticfn void
1860. unsetup_waterlevel(void)
1861. {
1862.     struct bubble *b, *bb;
1863. 
1864.     /* free bubbles */
1865.     for (b = svb.bbubbles; b; b = bb) {
1866.         bb = b->next;
1867.         free((genericptr_t) b);
1868.     }
1869.     svb.bbubbles = ge.ebubbles = (struct bubble *) 0;
1870. }
1871. 
1872. staticfn void
1873. mk_bubble(coordxy x, coordxy y, int n)
1874. {
1875.     /*
1876.      * These bit masks make visually pleasing bubbles on a normal aspect
1877.      * 25x80 terminal, which naturally results in them being mathematically
1878.      * anything but symmetric.  For this reason they cannot be computed
1879.      * in situ, either.  The first two elements tell the dimensions of
1880.      * the bubble's bounding box.
1881.      */
1882.     static const uchar
1883.         bm2[] = { 2, 1, 0x3 },
1884.         bm3[] = { 3, 2, 0x7, 0x7 },
1885.         bm4[] = { 4, 3, 0x6, 0xf, 0x6 },
1886.         bm5[] = { 5, 3, 0xe, 0x1f, 0xe },
1887.         bm6[] = { 6, 4, 0x1e, 0x3f, 0x3f, 0x1e },
1888.         bm7[] = { 7, 4, 0x3e, 0x7f, 0x7f, 0x3e },
1889.         bm8[] = { 8, 4, 0x7e, 0xff, 0xff, 0x7e },
1890.         *const bmask[] = { bm2, bm3, bm4, bm5, bm6, bm7, bm8 };
1891.     struct bubble *b;
1892. 
1893.     if (x >= gbxmax || y >= gbymax)
1894.         return;
1895.     if (n >= SIZE(bmask)) {
1896.         impossible("n too large (mk_bubble)");
1897.         n = SIZE(bmask) - 1;
1898.     }
1899.     if (bmask[n][1] > MAX_BMASK) {
1900.         panic("bmask size is larger than MAX_BMASK");
1901.     }
1902.     b = (struct bubble *) alloc(sizeof *b);
1903.     if ((x + (int) bmask[n][0] - 1) > gbxmax)
1904.         x = gbxmax - bmask[n][0] + 1;
1905.     if ((y + (int) bmask[n][1] - 1) > gbymax)
1906.         y = gbymax - bmask[n][1] + 1;
1907.     b->x = x;
1908.     b->y = y;
1909.     b->dx = 1 - rn2(3);
1910.     b->dy = 1 - rn2(3);
1911.     /* y dimension is the length of bitmap data - see bmask above */
1912.     (void) memcpy((genericptr_t) b->bm, (genericptr_t) bmask[n],
1913.                   (bmask[n][1] + 2) * sizeof (b->bm[0]));
1914.     b->cons = 0;
1915.     if (!svb.bbubbles)
1916.         svb.bbubbles = b;
1917.     if (ge.ebubbles) {
1918.         ge.ebubbles->next = b;
1919.         b->prev = ge.ebubbles;
1920.     } else
1921.         b->prev = (struct bubble *) 0;
1922.     b->next = (struct bubble *) 0;
1923.     ge.ebubbles = b;
1924.     mv_bubble(b, 0, 0, TRUE);
1925. }
1926. 
1927. /* maybe change the movement direction of the bubble hero is in */
1928. void
1929. maybe_adjust_hero_bubble(void)
1930. {
1931.     if (!Is_waterlevel(&u.uz))
1932.         return;
1933. 
1934.     if (!u.dx && !u.dy)
1935.         return;
1936. 
1937.     if (hero_bubble && !rn2(2)) {
1938.         hero_bubble->dx = u.dx;
1939.         hero_bubble->dy = u.dy;
1940.     }
1941. }
1942. 
1943. /*
1944.  * The player, the portal and all other objects and monsters
1945.  * float along with their associated bubbles.  Bubbles may overlap
1946.  * freely, and the contents may get associated with other bubbles in
1947.  * the process.  Bubbles are "sticky", meaning that if the player is
1948.  * in the immediate neighborhood of one, he/she may get sucked inside.
1949.  * This property also makes leaving a bubble slightly difficult.
1950.  */
1951. staticfn void
1952. mv_bubble(struct bubble *b, coordxy dx, coordxy dy, boolean ini)
1953. {
1954.     int i, j, colli = 0;
1955.     coordxy x, y;
1956.     struct container *cons, *ctemp;
1957. 
1958.     /* clouds move slowly */
1959.     if (!Is_airlevel(&u.uz) || !rn2(6)) {
1960.         /* move bubble */
1961.         if (dx < -1 || dx > 1 || dy < -1 || dy > 1) {
1962.             /* pline("mv_bubble: dx = %d, dy = %d", dx, dy); */
1963.             dx = sgn(dx);
1964.             dy = sgn(dy);
1965.         }
1966. 
1967.         /*
1968.          * collision with level borders?
1969.          *      1 = horizontal border, 2 = vertical, 3 = corner
1970.          */
1971.         if (b->x <= gbxmin)
1972.             colli |= 2;
1973.         if (b->y <= gbymin)
1974.             colli |= 1;
1975.         if ((int) (b->x + b->bm[0] - 1) >= gbxmax)
1976.             colli |= 2;
1977.         if ((int) (b->y + b->bm[1] - 1) >= gbymax)
1978.             colli |= 1;
1979. 
1980.         if (b->x < gbxmin) {
1981.             pline("bubble xmin: x = %d, xmin = %d", b->x, gbxmin);
1982.             b->x = gbxmin;
1983.         }
1984.         if (b->y < gbymin) {
1985.             pline("bubble ymin: y = %d, ymin = %d", b->y, gbymin);
1986.             b->y = gbymin;
1987.         }
1988.         if ((int) (b->x + b->bm[0] - 1) > gbxmax) {
1989.             pline("bubble xmax: x = %d, xmax = %d", b->x + b->bm[0] - 1,
1990.                   gbxmax);
1991.             b->x = gbxmax - b->bm[0] + 1;
1992.         }
1993.         if ((int) (b->y + b->bm[1] - 1) > gbymax) {
1994.             pline("bubble ymax: y = %d, ymax = %d", b->y + b->bm[1] - 1,
1995.                   gbymax);
1996.             b->y = gbymax - b->bm[1] + 1;
1997.         }
1998. 
1999.         /* bounce if we're trying to move off the border */
2000.         if (b->x == gbxmin && dx < 0)
2001.             dx = -dx;
2002.         if (b->x + b->bm[0] - 1 == gbxmax && dx > 0)
2003.             dx = -dx;
2004.         if (b->y == gbymin && dy < 0)
2005.             dy = -dy;
2006.         if (b->y + b->bm[1] - 1 == gbymax && dy > 0)
2007.             dy = -dy;
2008. 
2009.         b->x += dx;
2010.         b->y += dy;
2011.     }
2012. 
2013.     /* draw the bubbles */
2014.     for (i = 0, x = b->x; i < (int) b->bm[0]; i++, x++)
2015.         for (j = 0, y = b->y; j < (int) b->bm[1]; j++, y++)
2016.             if (b->bm[j + 2] & (1 << i)) {
2017.                 if (Is_waterlevel(&u.uz)) {
2018.                     levl[x][y].typ = AIR;
2019.                     levl[x][y].lit = 1;
2020.                     unblock_point(x, y);
2021.                 } else if (Is_airlevel(&u.uz)) {
2022.                     levl[x][y].typ = CLOUD;
2023.                     levl[x][y].lit = 1;
2024.                     block_point(x, y);
2025.                 }
2026.             }
2027. 
2028.     if (Is_waterlevel(&u.uz)) {
2029.         /* replace contents of bubble */
2030.         for (cons = b->cons; cons; cons = ctemp) {
2031.             ctemp = cons->next;
2032.             cons->x += dx;
2033.             cons->y += dy;
2034. 
2035.             switch (cons->what) {
2036.             case CONS_OBJ: {
2037.                 struct obj *olist, *otmp;
2038. 
2039.                 for (olist = (struct obj *) cons->list; olist; olist = otmp) {
2040.                     otmp = olist->nexthere;
2041.                     place_object(olist, cons->x, cons->y);
2042.                     stackobj(olist);
2043.                 }
2044.                 break;
2045.             }
2046. 
2047.             case CONS_MON: {
2048.                 struct monst *mon = (struct monst *) cons->list;
2049. 
2050.                 /* mnearto() might fail. We can jump right to elemental_clog
2051.                    from here rather than deal_with_overcrowding() */
2052.                 if (!mnearto(mon, cons->x, cons->y, TRUE, RLOC_NOMSG))
2053.                     elemental_clog(mon);
2054.                 break;
2055.             }
2056. 
2057.             case CONS_HERO: {
2058.                 struct monst *mtmp = m_at(cons->x, cons->y);
2059.                 int ux0 = u.ux, uy0 = u.uy;
2060. 
2061.                 u_on_newpos(cons->x, cons->y);
2062.                 newsym(ux0, uy0); /* clean up old position */
2063. 
2064.                 if (mtmp) {
2065.                     mnexto(mtmp, RLOC_NOMSG);
2066.                 }
2067.                 break;
2068.             }
2069. 
2070.             case CONS_TRAP: {
2071.                 struct trap *btrap = (struct trap *) cons->list;
2072. 
2073.                 btrap->tx = cons->x;
2074.                 btrap->ty = cons->y;
2075.                 break;
2076.             }
2077. 
2078.             default:
2079.                 impossible("mv_bubble: unknown bubble contents");
2080.                 break;
2081.             }
2082.             free((genericptr_t) cons);
2083.         }
2084.         b->cons = 0;
2085.     }
2086. 
2087.     /* boing? */
2088.     switch (colli) {
2089.     case 1:
2090.         b->dy = -b->dy;
2091.         break;
2092.     case 3:
2093.         b->dy = -b->dy;
2094.         FALLTHROUGH;
2095.         /*FALLTHRU*/
2096.     case 2:
2097.         b->dx = -b->dx;
2098.         break;
2099.     default:
2100.         /* sometimes alter direction for fun anyway
2101.            (higher probability for stationary bubbles) */
2102.         if (!ini && ((b->dx || b->dy) ? !rn2(20) : !rn2(5))) {
2103.             b->dx = 1 - rn2(3);
2104.             b->dy = 1 - rn2(3);
2105.         }
2106.     }
2107. }
2108. #endif /* !SFCTOOL */
2109. 
2110. /*mkmaze.c*/