Source:NetHack 5.0.0/src/sp lev.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to sp_lev.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/sp_lev.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	sp_lev.c	$NHDT-Date: 1737610109 2025/01/22 21:28:29 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.373 $ */
2. /*      Copyright (c) 1989 by Jean-Christophe Collet */
3. /* NetHack may be freely redistributed.  See license for details. */
4. 
5. /*
6.  * This file contains the various functions that are related to the special
7.  * levels.
8.  *
9.  * It contains also the special level loader.
10.  */
11. 
12. #define IN_SP_LEV_C
13. 
14. #include "hack.h"
15. #include "sp_lev.h"
16. 
17. extern void mkmap(lev_init *);
18. 
19. staticfn void solidify_map(void);
20. staticfn void map_cleanup(void);
21. staticfn void lvlfill_maze_grid(int, int, int, int, schar);
22. staticfn void lvlfill_solid(schar, schar);
23. staticfn void lvlfill_swamp(schar, schar, schar);
24. staticfn void flip_dbridge_horizontal(struct rm *);
25. staticfn void flip_dbridge_vertical(struct rm *);
26. staticfn void flip_visuals(int, int, int, int, int);
27. staticfn int flip_encoded_dir_bits(int, int);
28. staticfn void flip_vault_guard(int, struct monst *,
29.                              coordxy, coordxy, coordxy, coordxy);
30. staticfn void sel_set_wall_property(coordxy, coordxy, genericptr_t);
31. staticfn void set_wall_property(coordxy, coordxy, coordxy, coordxy, int);
32. staticfn void remove_boundary_syms(void);
33. staticfn void set_door_orientation(int, int);
34. staticfn boolean shared_with_room(int, int, struct mkroom *);
35. staticfn void maybe_add_door(int, int, struct mkroom *);
36. staticfn void link_doors_rooms(void);
37. staticfn int rnddoor(void);
38. staticfn int rndtrap(void);
39. staticfn void get_location(coordxy *, coordxy *, getloc_flags_t,
40.                          struct mkroom *);
41. staticfn void set_ok_location_func(boolean (*)(coordxy, coordxy));
42. staticfn boolean is_ok_location(coordxy, coordxy, getloc_flags_t);
43. staticfn unpacked_coord get_unpacked_coord(long, int);
44. staticfn void get_room_loc(coordxy *, coordxy *, struct mkroom *);
45. staticfn void get_free_room_loc(coordxy *, coordxy *, struct mkroom *,
46.                               packed_coord);
47. staticfn boolean create_subroom(struct mkroom *, coordxy, coordxy, coordxy,
48.                               coordxy, xint16, xint16);
49. staticfn void create_door(room_door *, struct mkroom *);
50. staticfn void create_trap(spltrap *, struct mkroom *);
51. staticfn int noncoalignment(aligntyp);
52. staticfn boolean m_bad_boulder_spot(coordxy, coordxy);
53. staticfn int pm_to_humidity(struct permonst *);
54. staticfn unsigned int sp_amask_to_amask(unsigned int sp_amask);
55. staticfn void create_monster(monster *, struct mkroom *);
56. staticfn struct obj *create_object(object *, struct mkroom *);
57. staticfn void create_altar(altar *, struct mkroom *);
58. staticfn boolean search_door(struct mkroom *, coordxy *, coordxy *, xint16,
59.                              int) NONNULLPTRS;
60. staticfn void create_corridor(corridor *);
61. staticfn struct mkroom *build_room(room *, struct mkroom *);
62. staticfn void light_region(region *);
63. staticfn void maze1xy(coord *, int);
64. staticfn void fill_empty_maze(void);
65. staticfn void splev_initlev(lev_init *);
66. staticfn boolean generate_way_out_method(coordxy nx, coordxy ny,
67.                                        struct selectionvar *ov);
68. staticfn void l_push_wid_hei_table(lua_State *, int, int);
69. staticfn boolean good_stair_loc(coordxy, coordxy);
70. staticfn void ensure_way_out(void);
71. 
72. #if 0
73. /* macosx complains that these are unused */
74. staticfn long sp_code_jmpaddr(long, long);
75. staticfn void spo_room(struct sp_coder *);
76. staticfn void spo_trap(struct sp_coder *);
77. staticfn void spo_gold(struct sp_coder *);
78. staticfn void spo_corridor(struct sp_coder *);
79. staticfn void spo_feature(struct sp_coder *);
80. staticfn void spo_terrain(struct sp_coder *);
81. staticfn void spo_replace_terrain(struct sp_coder *);
82. staticfn void spo_levregion(struct sp_coder *);
83. staticfn void spo_region(struct sp_coder *);
84. staticfn void spo_drawbridge(struct sp_coder *);
85. staticfn void spo_mazewalk(struct sp_coder *);
86. staticfn void spo_wall_property(struct sp_coder *);
87. staticfn void spo_room_door(struct sp_coder *);
88. staticfn void spo_wallify(struct sp_coder *);
89. staticfn void sel_set_wallify(coordxy, coordxy, genericptr_t);
90. #endif
91. staticfn void spo_end_moninvent(void);
92. staticfn void spo_pop_container(void);
93. staticfn int l_create_stairway(lua_State *, boolean);
94. staticfn void spo_endroom(struct sp_coder *);
95. staticfn void l_table_getset_feature_flag(lua_State *, int, int, const char *,
96.                                         int);
97. staticfn void l_get_lregion(lua_State *, lev_region *);
98. staticfn void sel_set_lit(coordxy, coordxy, genericptr_t);
99. staticfn void add_doors_to_room(struct mkroom *);
100. staticfn void get_table_coords_or_region(lua_State *,
101.                              coordxy *, coordxy *, coordxy *, coordxy *);
102. staticfn void sel_set_ter(coordxy, coordxy, genericptr_t);
103. staticfn void sel_set_door(coordxy, coordxy, genericptr_t);
104. staticfn void sel_set_feature(coordxy, coordxy, genericptr_t);
105. staticfn void levregion_add(lev_region *);
106. staticfn void get_table_xy_or_coord(lua_State *, lua_Integer *,
107.                                     lua_Integer *) NONNULLPTRS;
108. staticfn int get_table_region(lua_State *, const char *, lua_Integer *,
109.                         lua_Integer *, lua_Integer *, lua_Integer *, boolean);
110. staticfn void set_wallprop_in_selection(lua_State *, int);
111. staticfn int floodfillchk_match_under(coordxy, coordxy);
112. staticfn int floodfillchk_match_accessible(coordxy, coordxy);
113. staticfn void l_push_mkroom_table(lua_State *, struct mkroom *);
114. staticfn int get_table_align(lua_State *);
115. staticfn int get_table_monclass(lua_State *);
116. staticfn int find_montype(lua_State *, const char *, int *);
117. staticfn int get_table_montype(lua_State *, int *);
118. staticfn lua_Integer get_table_int_or_random(lua_State *, const char *, int);
119. staticfn int get_table_buc(lua_State *);
120. staticfn int find_objtype(lua_State *, const char *, char);
121. staticfn const char *get_mkroom_name(int) NONNULL;
122. staticfn int get_table_roomtype_opt(lua_State *, const char *, int);
123. staticfn int get_table_traptype_opt(lua_State *, const char *, int);
124. staticfn int get_traptype_byname(const char *);
125. staticfn lua_Integer get_table_intarray_entry(lua_State *, int, int);
126. staticfn struct sp_coder *sp_level_coder_init(void);
127. 
128. /* lua_CFunction prototypes */
129. int lspo_altar(lua_State *);
130. int lspo_branch(lua_State *);
131. int lspo_corridor(lua_State *);
132. int lspo_door(lua_State *);
133. int lspo_drawbridge(lua_State *);
134. int lspo_engraving(lua_State *);
135. int lspo_feature(lua_State *);
136. int lspo_gold(lua_State *);
137. int lspo_grave(lua_State *);
138. int lspo_ladder(lua_State *);
139. int lspo_level_flags(lua_State *);
140. int lspo_level_init(lua_State *);
141. int lspo_levregion(lua_State *);
142. int lspo_exclusion(lua_State *);
143. int lspo_map(lua_State *);
144. int lspo_mazewalk(lua_State *);
145. int lspo_message(lua_State *);
146. int lspo_mineralize(lua_State *);
147. int lspo_monster(lua_State *);
148. int lspo_non_diggable(lua_State *);
149. int lspo_non_passwall(lua_State *);
150. int lspo_object(lua_State *);
151. int lspo_portal(lua_State *);
152. int lspo_random_corridors(lua_State *);
153. int lspo_region(lua_State *);
154. int lspo_replace_terrain(lua_State *);
155. int lspo_reset_level(lua_State *);
156. int lspo_finalize_level(lua_State *);
157. int lspo_room(lua_State *);
158. int lspo_stair(lua_State *);
159. int lspo_teleport_region(lua_State *);
160. int lspo_gas_cloud(lua_State *);
161. int lspo_terrain(lua_State *);
162. int lspo_trap(lua_State *);
163. int lspo_wall_property(lua_State *);
164. int lspo_wallify(lua_State *);
165. 
166. #define SPLEV_LEFT 1
167. #define SPLEV_H_LEFT 2
168. #define SPLEV_CENTER 3
169. #define SPLEV_H_RIGHT 4
170. #define SPLEV_RIGHT 5
171. 
172. #define TOP 1
173. #define BOTTOM 5
174. 
175. #define sq(x) ((x) * (x))
176. 
177. #define XLIM 4
178. #define YLIM 3
179. 
180. #define New(type) (type *) alloc(sizeof (type))
181. #define NewTab(type, size) (type **) alloc(sizeof (type *) * (unsigned) size)
182. #define Free(ptr) \
183.     do {                                        \
184.         if (ptr)                                \
185.             free((genericptr_t) (ptr));         \
186.     } while (0)
187. 
188.     /*
189.      * No need for 'struct instance_globals g' to contain these.
190.      * sp_level_coder_init() always re-initializes them prior to use.
191.      */
192. static boolean splev_init_present, icedpools;
193. /* positions touched by level elements explicitly defined in the level */
194. static char SpLev_Map[COLNO][ROWNO];
195. #define MAX_CONTAINMENT 10
196. static int container_idx = 0; /* next slot in container_obj[] to use */
197. static struct obj *container_obj[MAX_CONTAINMENT];
198. static struct monst *invent_carrying_monster = (struct monst *) 0;
199.     /*
200.      * end of no 'g.'
201.      */
202. 
203. #define TYP_CANNOT_MATCH(typ) ((typ) == MAX_TYPE || (typ) == INVALID_TYPE)
204. 
205. void
206. reset_xystart_size(void)
207. {
208.     gx.xstart = 1; /* column [0] is off limits */
209.     gy.ystart = 0;
210.     gx.xsize = COLNO - 1; /* 1..COLNO-1 */
211.     gy.ysize = ROWNO; /* 0..ROWNO-1 */
212. }
213. 
214. /* Does typ match with levl[][].typ, considering special types
215.    MATCH_WALL and MAX_TYPE (aka transparency)? */
216. boolean
217. match_maptyps(xint16 typ, xint16 levltyp)
218. {
219.     if ((typ == MATCH_WALL) && !IS_STWALL(levltyp))
220.         return FALSE;
221.     if ((typ < MAX_TYPE) && (typ != levltyp))
222.         return FALSE;
223.     return TRUE;
224. }
225. 
226. struct mapfragment *
227. mapfrag_fromstr(char *str)
228. {
229.     struct mapfragment *mf = (struct mapfragment *) alloc(sizeof *mf);
230. 
231.     char *tmps;
232. 
233.     mf->data = dupstr(str);
234. 
235.     (void) stripdigits(mf->data);
236.     mf->wid = str_lines_maxlen(mf->data);
237.     mf->hei = 0;
238.     tmps = mf->data;
239.     while (tmps && *tmps) {
240.         char *s1 = strchr(tmps, '\n');
241. 
242.         if (mf->hei > MAP_Y_LIM) {
243.             free(mf->data);
244.             free(mf);
245.             return NULL;
246.         }
247.         if (s1)
248.             s1++;
249.         tmps = s1;
250.         mf->hei++;
251.     }
252.     return mf;
253. }
254. 
255. void
256. mapfrag_free(struct mapfragment **mf)
257. {
258.     if (mf && *mf) {
259.         free((*mf)->data);
260.         free(*mf);
261.         *mf = NULL;
262.     }
263. }
264. 
265. schar
266. mapfrag_get(struct mapfragment *mf, int x, int y)
267. {
268.     if (y < 0 || x < 0 || y > mf->hei - 1 || x > mf->wid - 1)
269.         panic("outside mapfrag (%i,%i), wanted (%i,%i)",
270.               mf->wid, mf->hei, x, y);
271.     return splev_chr2typ(mf->data[y * (mf->wid + 1) + x]);
272. }
273. 
274. boolean
275. mapfrag_canmatch(struct mapfragment *mf)
276. {
277.     return ((mf->wid % 2) && (mf->hei % 2));
278. }
279. 
280. const char *
281. mapfrag_error(struct mapfragment *mf)
282. {
283.     const char *res = NULL;
284. 
285.     if (!mf) {
286.         res = "mapfragment error";
287.     } else if (!mapfrag_canmatch(mf)) {
288.         mapfrag_free(&mf);
289.         res = "mapfragment needs to have odd height and width";
290.     } else if (TYP_CANNOT_MATCH(mapfrag_get(mf, mf->wid / 2, mf->hei / 2))) {
291.         mapfrag_free(&mf);
292.         res = "mapfragment center must be valid terrain";
293.     }
294.     return res;
295. }
296. 
297. boolean
298. mapfrag_match(struct mapfragment *mf,  int x, int y)
299. {
300.     int rx, ry;
301. 
302.     for (rx = -(mf->wid / 2); rx <= (mf->wid / 2); rx++)
303.         for (ry = -(mf->hei / 2); ry <= (mf->hei / 2); ry++) {
304.             schar mapc = mapfrag_get(mf, rx + (mf->wid / 2),
305.                                      ry + (mf->hei / 2));
306.             schar levc = isok(x+rx, y+ry) ? levl[x+rx][y+ry].typ : STONE;
307. 
308.             if (!match_maptyps(mapc, levc))
309.                 return FALSE;
310.         }
311.     return TRUE;
312. }
313. 
314. staticfn void
315. solidify_map(void)
316. {
317.     coordxy x, y;
318. 
319.     for (x = 0; x < COLNO; x++)
320.         for (y = 0; y < ROWNO; y++)
321.             if (IS_STWALL(levl[x][y].typ) && !SpLev_Map[x][y])
322.                 levl[x][y].wall_info |= (W_NONDIGGABLE | W_NONPASSWALL);
323. }
324. 
325. /* do a post-level-creation cleanup of map, such as
326.    removing boulders and traps from lava */
327. staticfn void
328. map_cleanup(void)
329. {
330.     struct obj *otmp;
331.     struct trap *ttmp;
332.     struct engr *etmp;
333.     coordxy x, y;
334. 
335.     for (x = 0; x < COLNO; x++)
336.         for (y = 0; y < ROWNO; y++) {
337.             schar typ = levl[x][y].typ;
338. 
339.             if (IS_LAVA(typ) || IS_POOL(typ)) {
340.                 /* in case any boulders are on liquid, delete them */
341.                 while ((otmp = sobj_at(BOULDER, x, y)) != 0) {
342.                     obj_extract_self(otmp);
343.                     obfree(otmp, (struct obj *) 0);
344.                 }
345. 
346.                 /* traps on liquid? */
347.                 if (((ttmp = t_at(x, y)) != 0)
348.                     && !undestroyable_trap(ttmp->ttyp))
349.                     deltrap(ttmp);
350. 
351.                 /* engravings? */
352.                 if ((etmp = engr_at(x, y)) != 0)
353.                   del_engr(etmp);
354.             }
355.         }
356. }
357. 
358. staticfn void
359. lvlfill_maze_grid(int x1, int y1, int x2, int y2, schar filling)
360. {
361.     int x, y;
362. 
363.     for (x = x1; x <= x2; x++)
364.         for (y = y1; y <= y2; y++) {
365.             if (svl.level.flags.corrmaze)
366.                 levl[x][y].typ = STONE;
367.             else
368.                 levl[x][y].typ = (y < 2 || ((x % 2) && (y % 2))) ? STONE
369.                                                                  : filling;
370.         }
371. }
372. 
373. staticfn void
374. lvlfill_solid(schar filling, schar lit)
375. {
376.     int x, y;
377. 
378.     for (x = 2; x <= gx.x_maze_max; x++)
379.         for (y = 0; y <= gy.y_maze_max; y++) {
380.             if (!set_levltyp_lit(x, y, filling, lit))
381.                 continue;
382.             /* TODO: consolidate this w lspo_map ? */
383.             levl[x][y].flags = 0;
384.             levl[x][y].horizontal = 0;
385.             levl[x][y].roomno = 0;
386.             levl[x][y].edge = 0;
387.         }
388. }
389. 
390. staticfn void
391. lvlfill_swamp(schar fg, schar bg, schar lit)
392. {
393.     int x, y;
394. 
395.     lvlfill_solid(bg, lit);
396. 
397.     /* "relaxed blockwise maze" algorithm, Jamis Buck */
398.     for (x = 2; x <= min(gx.x_maze_max, COLNO-2); x += 2)
399.         for (y = 0; y <= min(gy.y_maze_max, ROWNO-2); y += 2) {
400.             int c = 0;
401. 
402.             (void) set_levltyp_lit(x, y, fg, lit);
403.             if (levl[x + 1][y].typ == bg)
404.                 ++c;
405.             if (levl[x][y + 1].typ == bg)
406.                 ++c;
407.             if (levl[x + 1][y + 1].typ == bg)
408.                 ++c;
409.             if (c == 3) {
410.                 switch (rn2(3)) {
411.                 case 0:
412.                     (void) set_levltyp_lit(x + 1,y, fg, lit);
413.                     break;
414.                 case 1:
415.                     (void) set_levltyp_lit(x, y + 1, fg, lit);
416.                     break;
417.                 case 2:
418.                     (void) set_levltyp_lit(x + 1, y + 1, fg, lit);
419.                     break;
420.                 default:
421.                     break;
422.                 }
423.             }
424.         }
425. }
426. 
427. staticfn void
428. flip_dbridge_horizontal(struct rm *lev)
429. {
430.     if (IS_DRAWBRIDGE(lev->typ)) {
431.         if ((lev->drawbridgemask & DB_DIR) == DB_WEST) {
432.             lev->drawbridgemask &= ~DB_WEST;
433.             lev->drawbridgemask |=  DB_EAST;
434.         } else if ((lev->drawbridgemask & DB_DIR) == DB_EAST) {
435.             lev->drawbridgemask &= ~DB_EAST;
436.             lev->drawbridgemask |=  DB_WEST;
437.         }
438.     }
439. }
440. 
441. staticfn void
442. flip_dbridge_vertical(struct rm *lev)
443. {
444.     if (IS_DRAWBRIDGE(lev->typ)) {
445.         if ((lev->drawbridgemask & DB_DIR) == DB_NORTH) {
446.             lev->drawbridgemask &= ~DB_NORTH;
447.             lev->drawbridgemask |=  DB_SOUTH;
448.         } else if ((lev->drawbridgemask & DB_DIR) == DB_SOUTH) {
449.             lev->drawbridgemask &= ~DB_SOUTH;
450.             lev->drawbridgemask |=  DB_NORTH;
451.         }
452.     }
453. }
454. 
455. /* for #wizfliplevel; not needed when flipping during level creation;
456.    update seen vector for whole flip area and glyph for known walls */
457. staticfn void
458. flip_visuals(int flp, int minx, int miny, int maxx, int maxy)
459. {
460.     struct rm *lev;
461.     int x, y, seenv;
462. 
463.     for (y = miny; y <= maxy; ++y) {
464.         for (x = minx; x <= maxx; ++x) {
465.             lev = &levl[x][y];
466.             seenv = lev->seenv & 0xff;
467.             /* locations which haven't been seen can be skipped */
468.             if (seenv == 0)
469.                 continue;
470.             /* flip <x,y>'s seen vector; not necessary for locations seen
471.                from all directions (the whole level after magic mapping) */
472.             if (seenv != SVALL) {
473.                 /* SV2 SV1 SV0 *
474.                  * SV3 -+- SV7 *
475.                  * SV4 SV5 SV6 */
476.                 if (flp & 1) { /* swap top and bottom */
477.                     seenv = swapbits(seenv, 2, 4);
478.                     seenv = swapbits(seenv, 1, 5);
479.                     seenv = swapbits(seenv, 0, 6);
480.                 }
481.                 if (flp & 2) { /* swap left and right */
482.                     seenv = swapbits(seenv, 2, 0);
483.                     seenv = swapbits(seenv, 3, 7);
484.                     seenv = swapbits(seenv, 4, 6);
485.                 }
486.                 lev->seenv = (uchar) seenv;
487.             }
488.             /* if <x,y> is displayed as a wall, reset its display glyph so
489.                that remembered, out of view T's and corners get flipped */
490.             if ((IS_WALL(lev->typ) || lev->typ == SDOOR)
491.                 && glyph_is_cmap(lev->glyph))
492.                 lev->glyph = back_to_glyph(x, y);
493.         }
494.     }
495. }
496. 
497. /* transpose an encoded direction */
498. staticfn int
499. flip_encoded_dir_bits(int flp, int val)
500. {
501.     /* these depend on xdir[] and ydir[] order */
502.     if (flp & 1) {
503.         val = swapbits(val, 1, 7);
504.         val = swapbits(val, 2, 6);
505.         val = swapbits(val, 3, 5);
506.     }
507.     if (flp & 2) {
508.         val = swapbits(val, 1, 3);
509.         val = swapbits(val, 0, 4);
510.         val = swapbits(val, 7, 5);
511.     }
512. 
513.     return val;
514. }
515. 
516. #define FlipX(val) ((maxx - (val)) + minx)
517. #define FlipY(val) ((maxy - (val)) + miny)
518. #define inFlipArea(x,y) \
519.     ((x) >= minx && (x) <= maxx && (y) >= miny && (y) <= maxy)
520. #define Flip_coord(cc) \
521.     do {                                            \
522.         if ((cc).x && inFlipArea((cc).x, (cc).y)) { \
523.             if (flp & 1)                            \
524.                 (cc).y = FlipY((cc).y);             \
525.             if (flp & 2)                            \
526.                 (cc).x = FlipX((cc).x);             \
527.         }                                           \
528.     } while (0)
529. 
530. /* transpose top with bottom or left with right or both; sometimes called
531.    for new special levels, or for any level via the #wizfliplevel command */
532. void
533. flip_level(
534.     int flp,        /* mask for orientation(s) to transpose */
535.     boolean extras) /* False: level creation; True: #wizfliplevel is
536.                      * altering an active level so more needs to be done */
537. {
538.     int x, y, i, itmp;
539.     coordxy minx, miny, maxx, maxy;
540.     struct rm trm;
541.     struct trap *ttmp;
542.     struct obj *otmp;
543.     struct monst *mtmp;
544.     struct engr *etmp;
545.     struct mkroom *sroom;
546.     timer_element *timer;
547.     boolean ball_active = FALSE, ball_fliparea = FALSE;
548.     stairway *stway;
549.     struct exclusion_zone *ez;
550. 
551.     /* nothing to do unless (flp & 1) or (flp & 2) or both */
552.     if ((flp & 3) == 0)
553.         return;
554. 
555.     get_level_extends(&minx, &miny, &maxx, &maxy);
556.     /* get_level_extends() returns -1,-1 to COLNO,ROWNO at max */
557.     if (miny < 0)
558.         miny = 0;
559.     if (minx < 1)
560.         minx = 1;
561.     if (maxx >= COLNO)
562.         maxx = (COLNO - 1);
563.     if (maxy >= ROWNO)
564.         maxy = (ROWNO - 1);
565. 
566.     if (extras) {
567.         if (Punished && uball->where != OBJ_FREE) {
568.             ball_active = TRUE;
569.             /* if hero and ball and chain are all inside flip area,
570.                flip b&c coordinates along with other objects; if they
571.                are all outside, leave them to be rejected when flipping
572.                so that they stay as is; if some are inside and some are
573.                outside, un-place here and subsequently re-place them on
574.                hero's [possibly new] spot below */
575.             if (carried(uball))
576.                 uball->ox = u.ux, uball->oy = u.uy;
577.             ball_fliparea = ((inFlipArea(uball->ox, uball->oy)
578.                               == inFlipArea(uchain->ox, uchain->oy))
579.                              && (inFlipArea(uball->ox, uball->oy)
580.                                  == inFlipArea(u.ux, u.uy)));
581.             if (!ball_fliparea)
582.                 unplacebc();
583.         }
584.     }
585. 
586.     /* stairs and ladders */
587.     for (stway = gs.stairs; stway; stway = stway->next) {
588.         if (flp & 1)
589.             stway->sy = FlipY(stway->sy);
590.         if (flp & 2)
591.             stway->sx = FlipX(stway->sx);
592.     }
593. 
594.     /* traps */
595.     for (ttmp = gf.ftrap; ttmp; ttmp = ttmp->ntrap) {
596.         if (!inFlipArea(ttmp->tx, ttmp->ty))
597.             continue;
598.         if (flp & 1) {
599.             ttmp->ty = FlipY(ttmp->ty);
600.             if (ttmp->ttyp == ROLLING_BOULDER_TRAP) {
601.                 ttmp->launch.y = FlipY(ttmp->launch.y);
602.                 ttmp->launch2.y = FlipY(ttmp->launch2.y);
603.             } else if (is_pit(ttmp->ttyp) && ttmp->conjoined) {
604.                 ttmp->conjoined = flip_encoded_dir_bits(flp, ttmp->conjoined);
605.             }
606.         }
607.         if (flp & 2) {
608.             ttmp->tx = FlipX(ttmp->tx);
609.             if (ttmp->ttyp == ROLLING_BOULDER_TRAP) {
610.                 ttmp->launch.x = FlipX(ttmp->launch.x);
611.                 ttmp->launch2.x = FlipX(ttmp->launch2.x);
612.             } else if (is_pit(ttmp->ttyp) && ttmp->conjoined) {
613.                 ttmp->conjoined = flip_encoded_dir_bits(flp, ttmp->conjoined);
614.             }
615.         }
616.     }
617. 
618.     /* objects */
619.     for (otmp = fobj; otmp; otmp = otmp->nobj) {
620.         if (!inFlipArea(otmp->ox, otmp->oy))
621.             continue;
622.         if (flp & 1)
623.             otmp->oy = FlipY(otmp->oy);
624.         if (flp & 2)
625.             otmp->ox = FlipX(otmp->ox);
626.     }
627. 
628.     /* buried objects */
629.     for (otmp = svl.level.buriedobjlist; otmp; otmp = otmp->nobj) {
630.         if (!inFlipArea(otmp->ox, otmp->oy))
631.             continue;
632.         if (flp & 1)
633.             otmp->oy = FlipY(otmp->oy);
634.         if (flp & 2)
635.             otmp->ox = FlipX(otmp->ox);
636.     }
637. 
638.     /* monsters */
639.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
640.         if (mtmp->isgd) {
641.             if (extras) /* flip mtmp->mextra->egd */
642.                 flip_vault_guard(flp, mtmp, minx, miny, maxx, maxy);
643.             if (mtmp->mx == 0) /* not on map so don't flip guard->mx,my */
644.                 continue;
645.         }
646.         /* skip the occasional earth elemental outside the flip area */
647.         if (!inFlipArea(mtmp->mx, mtmp->my))
648.             continue;
649.         if (flp & 1)
650.             mtmp->my = FlipY(mtmp->my);
651.         if (flp & 2)
652.             mtmp->mx = FlipX(mtmp->mx);
653. 
654.         Flip_coord(mtmp->mgoal);
655. 
656.         if (mtmp->ispriest) {
657.             Flip_coord(EPRI(mtmp)->shrpos);
658.         } else if (mtmp->isshk) {
659.             Flip_coord(ESHK(mtmp)->shk); /* shk's preferred spot */
660.             Flip_coord(ESHK(mtmp)->shd); /* shop door */
661.         } else if (mtmp->wormno) {
662.             if (flp & 1)
663.                 flip_worm_segs_vertical(mtmp, miny, maxy);
664.             if (flp & 2)
665.                 flip_worm_segs_horizontal(mtmp, minx, maxx);
666.         }
667. #if 0   /* not useful unless tracking also gets flipped */
668.         if (extras) {
669.             if (mtmp->tame && has_edog(mtmp))
670.                 Flip_coord(EDOG(mtmp)->ogoal);
671.         }
672. #endif
673.     }
674.     if (extras) { /* #wizfliplevel rather than level creation */
675.         for (mtmp = gm.migrating_mons; mtmp; mtmp = mtmp->nmon) {
676.             if (mtmp->isgd && on_level(&u.uz, &EGD(mtmp)->gdlevel)) {
677.                 flip_vault_guard(flp, mtmp, minx, miny, maxx, maxy); /* egd */
678.             } else if (mtmp->ispriest
679.                        && on_level(&u.uz, &EPRI(mtmp)->shrlevel)) {
680.                 Flip_coord(EPRI(mtmp)->shrpos); /* priest's altar */
681.             } else if (mtmp->isshk
682.                        && on_level(&u.uz, &ESHK(mtmp)->shoplevel)) {
683.                 Flip_coord(ESHK(mtmp)->shk); /* shk's preferred spot */
684.                 Flip_coord(ESHK(mtmp)->shd); /* shop door */
685.             }
686.         }
687.     }
688. 
689.     /* engravings */
690.     for (etmp = head_engr; etmp; etmp = etmp->nxt_engr) {
691.         if (flp & 1)
692.             etmp->engr_y = FlipY(etmp->engr_y);
693.         if (flp & 2)
694.             etmp->engr_x = FlipX(etmp->engr_x);
695.     }
696. 
697.     /* level (teleport) regions */
698.     for (i = 0; i < gn.num_lregions; i++) {
699.         if (flp & 1) {
700.             gl.lregions[i].inarea.y1 = FlipY(gl.lregions[i].inarea.y1);
701.             gl.lregions[i].inarea.y2 = FlipY(gl.lregions[i].inarea.y2);
702.             if (gl.lregions[i].inarea.y1 > gl.lregions[i].inarea.y2) {
703.                 itmp = gl.lregions[i].inarea.y1;
704.                 gl.lregions[i].inarea.y1 = gl.lregions[i].inarea.y2;
705.                 gl.lregions[i].inarea.y2 = itmp;
706.             }
707. 
708.             gl.lregions[i].delarea.y1 = FlipY(gl.lregions[i].delarea.y1);
709.             gl.lregions[i].delarea.y2 = FlipY(gl.lregions[i].delarea.y2);
710.             if (gl.lregions[i].delarea.y1 > gl.lregions[i].delarea.y2) {
711.                 itmp = gl.lregions[i].delarea.y1;
712.                 gl.lregions[i].delarea.y1 = gl.lregions[i].delarea.y2;
713.                 gl.lregions[i].delarea.y2 = itmp;
714.             }
715.         }
716.         if (flp & 2) {
717.             gl.lregions[i].inarea.x1 = FlipX(gl.lregions[i].inarea.x1);
718.             gl.lregions[i].inarea.x2 = FlipX(gl.lregions[i].inarea.x2);
719.             if (gl.lregions[i].inarea.x1 > gl.lregions[i].inarea.x2) {
720.                 itmp = gl.lregions[i].inarea.x1;
721.                 gl.lregions[i].inarea.x1 = gl.lregions[i].inarea.x2;
722.                 gl.lregions[i].inarea.x2 = itmp;
723.             }
724. 
725.             gl.lregions[i].delarea.x1 = FlipX(gl.lregions[i].delarea.x1);
726.             gl.lregions[i].delarea.x2 = FlipX(gl.lregions[i].delarea.x2);
727.             if (gl.lregions[i].delarea.x1 > gl.lregions[i].delarea.x2) {
728.                 itmp = gl.lregions[i].delarea.x1;
729.                 gl.lregions[i].delarea.x1 = gl.lregions[i].delarea.x2;
730.                 gl.lregions[i].delarea.x2 = itmp;
731.             }
732.         }
733.     }
734. 
735.     /* regions (poison clouds, etc) */
736.     for (i = 0; i < svn.n_regions; i++) {
737.         int j, tmp1, tmp2;
738.         if (flp & 1) {
739.             tmp1 = FlipY(gr.regions[i]->bounding_box.ly);
740.             tmp2 = FlipY(gr.regions[i]->bounding_box.hy);
741.             gr.regions[i]->bounding_box.ly = min(tmp1, tmp2);
742.             gr.regions[i]->bounding_box.hy = max(tmp1, tmp2);
743.             for (j = 0; j < gr.regions[i]->nrects; j++) {
744.                 tmp1 = FlipY(gr.regions[i]->rects[j].ly);
745.                 tmp2 = FlipY(gr.regions[i]->rects[j].hy);
746.                 gr.regions[i]->rects[j].ly = min(tmp1, tmp2);
747.                 gr.regions[i]->rects[j].hy = max(tmp1, tmp2);
748.             }
749.         }
750.         if (flp & 2) {
751.             tmp1 = FlipX(gr.regions[i]->bounding_box.lx);
752.             tmp2 = FlipX(gr.regions[i]->bounding_box.hx);
753.             gr.regions[i]->bounding_box.lx = min(tmp1, tmp2);
754.             gr.regions[i]->bounding_box.hx = max(tmp1, tmp2);
755.             for (j = 0; j < gr.regions[i]->nrects; j++) {
756.                 tmp1 = FlipX(gr.regions[i]->rects[j].lx);
757.                 tmp2 = FlipX(gr.regions[i]->rects[j].hx);
758.                 gr.regions[i]->rects[j].lx = min(tmp1, tmp2);
759.                 gr.regions[i]->rects[j].hx = max(tmp1, tmp2);
760.             }
761.         }
762.     }
763. 
764.     /* rooms */
765.     for (sroom = &svr.rooms[0]; ; sroom++) {
766.         if (sroom->hx < 0)
767.             break;
768. 
769.         if (flp & 1) {
770.             sroom->ly = FlipY(sroom->ly);
771.             sroom->hy = FlipY(sroom->hy);
772.             if (sroom->ly > sroom->hy) {
773.                 itmp = sroom->ly;
774.                 sroom->ly = sroom->hy;
775.                 sroom->hy = itmp;
776.             }
777.         }
778.         if (flp & 2) {
779.             sroom->lx = FlipX(sroom->lx);
780.             sroom->hx = FlipX(sroom->hx);
781.             if (sroom->lx > sroom->hx) {
782.                 itmp = sroom->lx;
783.                 sroom->lx = sroom->hx;
784.                 sroom->hx = itmp;
785.             }
786.         }
787. 
788.         if (sroom->nsubrooms)
789.             for (i = 0; i < sroom->nsubrooms; i++) {
790.                 struct mkroom *rroom = sroom->sbrooms[i];
791. 
792.                 if (flp & 1) {
793.                     rroom->ly = FlipY(rroom->ly);
794.                     rroom->hy = FlipY(rroom->hy);
795.                     if (rroom->ly > rroom->hy) {
796.                         itmp = rroom->ly;
797.                         rroom->ly = rroom->hy;
798.                         rroom->hy = itmp;
799.                     }
800.                 }
801.                 if (flp & 2) {
802.                     rroom->lx = FlipX(rroom->lx);
803.                     rroom->hx = FlipX(rroom->hx);
804.                     if (rroom->lx > rroom->hx) {
805.                         itmp = rroom->lx;
806.                         rroom->lx = rroom->hx;
807.                         rroom->hx = itmp;
808.                     }
809.                 }
810.             }
811.     }
812. 
813.     /* doors */
814.     for (i = 0; i < gd.doorindex; i++) {
815.         Flip_coord(svd.doors[i]);
816.     }
817. 
818.     /* the map */
819.     if (flp & 1) {
820.         for (x = minx; x <= maxx; x++)
821.             for (y = miny; y < (miny + ((maxy - miny + 1) / 2)); y++) {
822.                 int ny = FlipY(y);
823. 
824.                 flip_dbridge_vertical(&levl[x][y]);
825.                 flip_dbridge_vertical(&levl[x][ny]);
826. 
827.                 trm = levl[x][y];
828.                 levl[x][y] = levl[x][ny];
829.                 levl[x][ny] = trm;
830. 
831.                 otmp = svl.level.objects[x][y];
832.                 svl.level.objects[x][y] = svl.level.objects[x][ny];
833.                 svl.level.objects[x][ny] = otmp;
834. 
835.                 mtmp = svl.level.monsters[x][y];
836.                 svl.level.monsters[x][y] = svl.level.monsters[x][ny];
837.                 svl.level.monsters[x][ny] = mtmp;
838.             }
839.     }
840.     if (flp & 2) {
841.         for (x = minx; x < (minx + ((maxx - minx + 1) / 2)); x++)
842.             for (y = miny; y <= maxy; y++) {
843.                 int nx = FlipX(x);
844. 
845.                 flip_dbridge_horizontal(&levl[x][y]);
846.                 flip_dbridge_horizontal(&levl[nx][y]);
847. 
848.                 trm = levl[x][y];
849.                 levl[x][y] = levl[nx][y];
850.                 levl[nx][y] = trm;
851. 
852.                 otmp = svl.level.objects[x][y];
853.                 svl.level.objects[x][y] = svl.level.objects[nx][y];
854.                 svl.level.objects[nx][y] = otmp;
855. 
856.                 mtmp = svl.level.monsters[x][y];
857.                 svl.level.monsters[x][y] = svl.level.monsters[nx][y];
858.                 svl.level.monsters[nx][y] = mtmp;
859.             }
860.     }
861. 
862.     /* timed effects */
863.     for (timer = gt.timer_base; timer; timer = timer->next) {
864.         if (timer->func_index == MELT_ICE_AWAY) {
865.             long ty = timer->arg.a_long & 0xffff;
866.             long tx = (timer->arg.a_long >> 16) & 0xffff;
867. 
868.             if (flp & 1)
869.                 ty = FlipY(ty);
870.             if (flp & 2)
871.                 tx = FlipX(tx);
872.             timer->arg.a_long = ((tx << 16) | ty);
873.         }
874.     }
875. 
876.     /* exclusion zones */
877.     for (ez = sve.exclusion_zones; ez; ez = ez->next) {
878.         if (flp & 1) {
879.             ez->ly = FlipY(ez->ly);
880.             ez->hy = FlipY(ez->hy);
881.             if (ez->ly > ez->hy) {
882.                 itmp = ez->ly;
883.                 ez->ly = ez->hy;
884.                 ez->hy = itmp;
885.             }
886.         }
887.         if (flp & 2) {
888.             ez->lx = FlipX(ez->lx);
889.             ez->hx = FlipX(ez->hx);
890.             if (ez->lx > ez->hx) {
891.                 itmp = ez->lx;
892.                 ez->lx = ez->hx;
893.                 ez->hx = itmp;
894.             }
895.         }
896.     }
897. 
898.     if (extras) { /* for #wizfliplevel rather than during level creation */
899.         /* flip hero location only if inside the flippable area */
900.         if (inFlipArea(u.ux, u.uy)) {
901.             if (flp & 1)
902.                 u.uy = FlipY(u.uy);
903.             if (flp & 2)
904.                 u.ux = FlipX(u.ux);
905.             /* we could flip <ux0,uy0> too if it's inside the flip area,
906.                but have to resort to this if outside, so just do this */
907.             u.ux0 = u.ux, u.uy0 = u.uy;
908.         }
909.         if (ball_active && !ball_fliparea)
910.             placebc();
911.         Flip_coord(iflags.travelcc);
912.         Flip_coord(svc.context.digging.pos);
913.     }
914. 
915.     fix_wall_spines(1, 0, COLNO - 1, ROWNO - 1);
916.     if (extras && flp) {
917.         set_wall_state();
918.         /* after wall_spines; flips seenv and wall joins */
919.         flip_visuals(flp, minx, miny, maxx, maxy);
920.     }
921.     vision_reset();
922. }
923. 
924. /* for #wizfliplevel, flip guard's egd data; not needed for level creation */
925. staticfn void
926. flip_vault_guard(
927.     int flp, /* 1: transpose vertically, 2: transpose horizontally, 3: both */
928.     struct monst *grd, /* the vault guard, has monst->mextra->egd data */
929.     coordxy minx, coordxy miny, /* needed by FlipX(), FlipY(), */
930.     coordxy maxx, coordxy maxy) /* and inFlipArea() macros     */
931. {
932.     int i;
933.     struct egd *egd = EGD(grd);
934. 
935.     if (inFlipArea(egd->gdx, egd->gdy)) {
936.         if (flp & 1)
937.             egd->gdy = FlipY(egd->gdy);
938.         if (flp & 2)
939.             egd->gdx = FlipX(egd->gdx);
940.     }
941.     if (inFlipArea(egd->ogx, egd->ogy)) {
942.         if (flp & 1)
943.             egd->ogy = FlipY(egd->ogy);
944.         if (flp & 2)
945.             egd->ogx = FlipX(egd->ogx);
946.     }
947.     for (i = egd->fcbeg; i < egd->fcend; ++i) {
948.         coordxy fx = egd->fakecorr[i].fx, fy = egd->fakecorr[i].fy;
949. 
950.         if (inFlipArea(fx, fy)) {
951.             if (flp & 1)
952.                 egd->fakecorr[i].fy = FlipY(fy);
953.             if (flp & 2)
954.                 egd->fakecorr[i].fx = FlipX(fx);
955.         }
956.     }
957.     return;
958. }
959. 
960. #undef FlipX
961. #undef FlipY
962. #undef inFlipArea
963. 
964. /* randomly transpose top with bottom or left with right or both;
965.    caller controls which transpositions are allowed */
966. void
967. flip_level_rnd(int flp, boolean extras)
968. {
969.     int c = 0;
970. 
971.     /* TODO?
972.      *  Might change rn2(2) to !rn2(3) or (rn2(5) < 2) in order to bias
973.      *  the outcome towards the traditional orientation.
974.      */
975.     if ((flp & 1) && rn2(2))
976.         c |= 1;
977.     if ((flp & 2) && rn2(2))
978.         c |= 2;
979. 
980.     if (c)
981.         flip_level(c, extras);
982. }
983. 
984. 
985. staticfn void
986. sel_set_wall_property(coordxy x, coordxy y, genericptr_t arg)
987. {
988.     int prop = *(int *) arg;
989. 
990.     if (IS_STWALL(levl[x][y].typ) || IS_TREE(levl[x][y].typ)
991.         /* 3.6.2: made iron bars eligible to be flagged nondiggable
992.            (checked by chewing(hack.c) and zap_over_floor(zap.c)) */
993.         || levl[x][y].typ == IRONBARS)
994.         levl[x][y].wall_info |= prop;
995. }
996. 
997. /*
998.  * Make walls of the area (x1, y1, x2, y2) non diggable/non passwall-able
999.  */
1000. staticfn void
1001. set_wall_property(coordxy x1, coordxy y1, coordxy x2, coordxy y2, int prop)
1002. {
1003.     coordxy x, y;
1004. 
1005.     x1 = max(x1, 1);
1006.     x2 = min(x2, COLNO - 1);
1007.     y1 = max(y1, 0);
1008.     y2 = min(y2, ROWNO - 1);
1009.     for (y = y1; y <= y2; y++)
1010.         for (x = x1; x <= x2; x++) {
1011.             sel_set_wall_property(x, y, (genericptr_t) &prop);
1012.         }
1013. }
1014. 
1015. staticfn void
1016. remove_boundary_syms(void)
1017. {
1018.     /*
1019.      * If any CROSSWALLs are found, must change to ROOM after REGION's
1020.      * are laid out.  CROSSWALLS are used to specify "invisible"
1021.      * boundaries where DOOR syms look bad or aren't desirable.
1022.      */
1023.     coordxy x, y;
1024.     boolean has_bounds = FALSE;
1025. 
1026.     for (x = 0; x < COLNO - 1; x++)
1027.         for (y = 0; y < ROWNO - 1; y++)
1028.             if (levl[x][y].typ == CROSSWALL) {
1029.                 has_bounds = TRUE;
1030.                 break;
1031.             }
1032.     if (has_bounds) {
1033.         for (x = 0; x < gx.x_maze_max; x++)
1034.             for (y = 0; y < gy.y_maze_max; y++)
1035.                 if ((levl[x][y].typ == CROSSWALL) && SpLev_Map[x][y])
1036.                     levl[x][y].typ = ROOM;
1037.     }
1038. }
1039. 
1040. /* used by sel_set_door() and link_doors_rooms() */
1041. staticfn void
1042. set_door_orientation(int x, int y)
1043. {
1044.     boolean wleft, wright, wup, wdown;
1045. 
1046.     /* If there's a wall or door on either the left side or right
1047.      * side (or both) of this secret door, make it be horizontal.
1048.      *
1049.      * It is feasible to put SDOOR in a corner, tee, or crosswall
1050.      * position, although once the door is found and opened it won't
1051.      * make a lot sense (diagonal access required).  Still, we try to
1052.      * handle that as best as possible.  For top or bottom tee, using
1053.      * horizontal is the best we can do.  For corner or crosswall,
1054.      * either horizontal or vertical are just as good as each other;
1055.      * we produce horizontal for corners and vertical for crosswalls.
1056.      * For left or right tee, using vertical is best.
1057.      *
1058.      * A secret door with no adjacent walls is also feasible and makes
1059.      * even less sense.  It will be displayed as a vertical wall while
1060.      * hidden and become a vertical door when found.  Before resorting
1061.      * to that, we check for solid rock which hasn't been wallified
1062.      * yet (cf lower leftside of leader's room in Cav quest).
1063.      */
1064.     wleft  = (isok(x - 1, y) && (IS_WALL(levl[x - 1][y].typ)
1065.                                  || IS_DOOR(levl[x - 1][y].typ)
1066.                                  || levl[x - 1][y].typ == SDOOR));
1067.     wright = (isok(x + 1, y) && (IS_WALL(levl[x + 1][y].typ)
1068.                                  || IS_DOOR(levl[x + 1][y].typ)
1069.                                  || levl[x + 1][y].typ == SDOOR));
1070.     wup    = (isok(x, y - 1) && (IS_WALL(levl[x][y - 1].typ)
1071.                                  || IS_DOOR(levl[x][y - 1].typ)
1072.                                  || levl[x][y - 1].typ == SDOOR));
1073.     wdown  = (isok(x, y + 1) && (IS_WALL(levl[x][y + 1].typ)
1074.                                  || IS_DOOR(levl[x][y + 1].typ)
1075.                                  || levl[x][y + 1].typ == SDOOR));
1076.     if (!wleft && !wright && !wup && !wdown) {
1077.         /* out of bounds is treated as implicit wall; should be academic
1078.            because we don't expect to have doors so near the level's edge */
1079.         wleft  = (!isok(x - 1, y) || IS_DOORJOIN(levl[x - 1][y].typ));
1080.         wright = (!isok(x + 1, y) || IS_DOORJOIN(levl[x + 1][y].typ));
1081.         wup    = (!isok(x, y - 1) || IS_DOORJOIN(levl[x][y - 1].typ));
1082.         wdown  = (!isok(x, y + 1) || IS_DOORJOIN(levl[x][y + 1].typ));
1083.     }
1084.     levl[x][y].horizontal = ((wleft || wright) && !(wup && wdown)) ? 1 : 0;
1085. }
1086. 
1087. /* is x,y right next to room droom? */
1088. staticfn boolean
1089. shared_with_room(int x, int y, struct mkroom *droom)
1090. {
1091.     int rmno = (droom - svr.rooms) + ROOMOFFSET;
1092. 
1093.     if (!isok(x,y))
1094.         return FALSE;
1095.     if ((int) levl[x][y].roomno == rmno && !levl[x][y].edge)
1096.         return FALSE;
1097.     if (isok(x-1, y) && (int) levl[x-1][y].roomno == rmno && x-1 <= droom->hx)
1098.         return TRUE;
1099.     if (isok(x+1, y) && (int) levl[x+1][y].roomno == rmno && x+1 >= droom->lx)
1100.         return TRUE;
1101.     if (isok(x, y-1) && (int) levl[x][y-1].roomno == rmno && y-1 <= droom->hy)
1102.         return TRUE;
1103.     if (isok(x, y+1) && (int) levl[x][y+1].roomno == rmno && y+1 >= droom->ly)
1104.         return TRUE;
1105.     return FALSE;
1106. }
1107. 
1108. /* maybe add door at x,y to room droom */
1109. staticfn void
1110. maybe_add_door(int x, int y, struct mkroom *droom)
1111. {
1112.     if (droom->hx >= 0
1113.         && ((!droom->irregular && inside_room(droom, x, y))
1114.             || (int) levl[x][y].roomno == (droom - svr.rooms) + ROOMOFFSET
1115.             || shared_with_room(x, y, droom))) {
1116.         add_door(x, y, droom);
1117.     }
1118. }
1119. 
1120. /* link all doors in the map to their corresponding rooms */
1121. staticfn void
1122. link_doors_rooms(void)
1123. {
1124.     int x, y;
1125.     int tmpi, m;
1126. 
1127.     for (y = 0; y < ROWNO; y++)
1128.         for (x = 0; x < COLNO; x++)
1129.             if (IS_DOOR(levl[x][y].typ) || levl[x][y].typ == SDOOR) {
1130.                 /* in case this door was a '+' or 'S' from the
1131.                    MAP...ENDMAP section without an explicit DOOR
1132.                    directive, set/clear levl[][].horizontal for it */
1133.                 set_door_orientation(x, y);
1134. 
1135.                 for (tmpi = 0; tmpi < svn.nroom; tmpi++) {
1136.                     maybe_add_door(x, y, &svr.rooms[tmpi]);
1137.                     for (m = 0; m < svr.rooms[tmpi].nsubrooms; m++) {
1138.                         maybe_add_door(x, y, svr.rooms[tmpi].sbrooms[m]);
1139.                     }
1140.                 }
1141.             }
1142. }
1143. 
1144. /*
1145.  * Choose randomly the state (nodoor, open, closed or locked) for a door
1146.  */
1147. staticfn int
1148. rnddoor(void)
1149. {
1150.     static int state[] = { D_NODOOR, D_BROKEN, D_ISOPEN, D_CLOSED, D_LOCKED };
1151. 
1152.     return ROLL_FROM(state);
1153. }
1154. 
1155. /*
1156.  * Select a random trap
1157.  */
1158. staticfn int
1159. rndtrap(void)
1160. {
1161.     int rtrap;
1162. 
1163.     do {
1164.         rtrap = rnd(TRAPNUM - 1);
1165.         switch (rtrap) {
1166.         case HOLE: /* no random holes on special levels */
1167.         case VIBRATING_SQUARE:
1168.         case MAGIC_PORTAL:
1169.             rtrap = NO_TRAP;
1170.             break;
1171.         case TRAPDOOR:
1172.             if (!Can_dig_down(&u.uz))
1173.                 rtrap = NO_TRAP;
1174.             break;
1175.         case LEVEL_TELEP:
1176.         case TELEP_TRAP:
1177.             if (svl.level.flags.noteleport)
1178.                 rtrap = NO_TRAP;
1179.             break;
1180.         case ROLLING_BOULDER_TRAP:
1181.         case ROCKTRAP:
1182.             if (In_endgame(&u.uz))
1183.                 rtrap = NO_TRAP;
1184.             break;
1185.         }
1186.     } while (rtrap == NO_TRAP);
1187.     return rtrap;
1188. }
1189. 
1190. /*
1191.  * Translate a given coordinate from a special level definition into an actual
1192.  * location on the map.
1193.  *
1194.  * If x or y is negative, we generate a random coordinate within the area. If
1195.  * not negative, they are interpreted as relative to the last defined map or
1196.  * room, and are output as absolute svl.level.locations coordinates.
1197.  *
1198.  * The "humidity" flag is used to ensure that engravings aren't created
1199.  * underwater, or eels on dry land.
1200.  */
1201. staticfn void
1202. get_location(
1203.     coordxy *x, coordxy *y,
1204.     getloc_flags_t humidity,
1205.     struct mkroom *croom)
1206. {
1207.     int cpt = 0;
1208.     int mx, my, sx, sy;
1209. 
1210.     if (croom) {
1211.         mx = croom->lx;
1212.         my = croom->ly;
1213.         sx = croom->hx - mx + 1;
1214.         sy = croom->hy - my + 1;
1215.     } else {
1216.         mx = gx.xstart;
1217.         my = gy.ystart;
1218.         sx = gx.xsize;
1219.         sy = gy.ysize;
1220.     }
1221. 
1222.     if (*x >= 0) { /* normal locations */
1223.         *x += mx;
1224.         *y += my;
1225.     } else { /* random location */
1226.         do {
1227.             if (croom) { /* handle irregular areas */
1228.                 coord tmpc;
1229.                 (void) somexy(croom, &tmpc);
1230.                 *x = tmpc.x;
1231.                 *y = tmpc.y;
1232.             } else {
1233.                 *x = mx + rn2((int) sx);
1234.                 *y = my + rn2((int) sy);
1235.             }
1236.             if (is_ok_location(*x, *y, humidity))
1237.                 break;
1238.         } while (++cpt < 100);
1239.         if (cpt >= 100) {
1240.             int xx, yy;
1241. 
1242.             /* last try */
1243.             for (xx = 0; xx < sx; xx++)
1244.                 for (yy = 0; yy < sy; yy++) {
1245.                     *x = mx + xx;
1246.                     *y = my + yy;
1247.                     if (is_ok_location(*x, *y, humidity))
1248.                         goto found_it;
1249.                 }
1250.             if (!(humidity & NO_LOC_WARN)) {
1251.                 impossible("get_location:  can't find a place!");
1252.             } else {
1253.                 *x = *y = -1;
1254.             }
1255.         }
1256.     }
1257.  found_it:
1258.     ;
1259. 
1260.     if (!(humidity & ANY_LOC) && !isok(*x, *y)) {
1261.         if (!(humidity & NO_LOC_WARN)) {
1262.             /*warning("get_location:  (%d,%d) out of bounds", *x, *y);*/
1263.             *x = gx.x_maze_max;
1264.             *y = gy.y_maze_max;
1265.         } else {
1266.             *x = *y = -1;
1267.         }
1268.     }
1269. }
1270. 
1271. static boolean (*is_ok_location_func)(coordxy, coordxy) = NULL;
1272. 
1273. staticfn void
1274. set_ok_location_func(boolean (*func)(coordxy, coordxy))
1275. {
1276.     is_ok_location_func = func;
1277. }
1278. 
1279. staticfn boolean
1280. is_ok_location(coordxy x, coordxy y, getloc_flags_t humidity)
1281. {
1282.     int typ = levl[x][y].typ;
1283. 
1284.     if (Is_waterlevel(&u.uz))
1285.         return TRUE; /* accept any spot */
1286. 
1287.     if (is_ok_location_func)
1288.         return is_ok_location_func(x, y);
1289. 
1290.     /* TODO: Should perhaps check if wall is diggable/passwall? */
1291.     if (humidity & ANY_LOC)
1292.         return TRUE;
1293. 
1294.     if ((humidity & SOLID) && IS_OBSTRUCTED(typ))
1295.         return TRUE;
1296. 
1297.     if ((humidity & (DRY|SPACELOC)) && SPACE_POS(typ)) {
1298.         boolean bould = (sobj_at(BOULDER, x, y) != NULL);
1299. 
1300.         if (!bould || (bould && (humidity & SOLID)))
1301.             return TRUE;
1302.     }
1303.     if ((humidity & WET) && is_pool(x, y))
1304.         return TRUE;
1305.     if ((humidity & HOT) && is_lava(x, y))
1306.         return TRUE;
1307.     return FALSE;
1308. }
1309. 
1310. boolean
1311. pm_good_location(coordxy x, coordxy y, struct permonst *pm)
1312. {
1313.     return is_ok_location(x, y, pm_to_humidity(pm));
1314. }
1315. 
1316. staticfn unpacked_coord
1317. get_unpacked_coord(long loc, int defhumidity)
1318. {
1319.     static unpacked_coord c;
1320. 
1321.     if (loc & SP_COORD_IS_RANDOM) {
1322.         c.x = c.y = -1;
1323.         c.is_random = 1;
1324.         c.getloc_flags = (getloc_flags_t)(loc & ~SP_COORD_IS_RANDOM);
1325.         if (!c.getloc_flags)
1326.             c.getloc_flags = defhumidity;
1327.     } else {
1328.         c.is_random = 0;
1329.         c.getloc_flags = defhumidity;
1330.         c.x = SP_COORD_X(loc);
1331.         c.y = SP_COORD_Y(loc);
1332.     }
1333.     return c;
1334. }
1335. 
1336. void
1337. get_location_coord(
1338.     coordxy *x, coordxy *y,
1339.     int humidity,
1340.     struct mkroom *croom,
1341.     long crd)
1342. {
1343.     unpacked_coord c;
1344. 
1345.     c = get_unpacked_coord(crd, humidity);
1346.     *x = c.x;
1347.     *y = c.y;
1348.     get_location(x, y, c.getloc_flags | (c.is_random ? NO_LOC_WARN : 0),
1349.                  croom);
1350. 
1351.     if (*x == -1 && *y == -1 && c.is_random)
1352.         get_location(x, y, humidity, croom);
1353. }
1354. 
1355. /*
1356.  * Get a relative position inside a room.
1357.  * negative values for x or y means RANDOM!
1358.  */
1359. staticfn void
1360. get_room_loc(coordxy *x, coordxy *y, struct mkroom *croom)
1361. {
1362.     coord c;
1363. 
1364.     if (*x < 0 && *y < 0) {
1365.         if (somexy(croom, &c)) {
1366.             *x = c.x;
1367.             *y = c.y;
1368.         } else
1369.             panic("get_room_loc : can't find a place!");
1370.     } else {
1371.         if (*x < 0)
1372.             *x = rn2(croom->hx - croom->lx + 1);
1373.         if (*y < 0)
1374.             *y = rn2(croom->hy - croom->ly + 1);
1375.         *x += croom->lx;
1376.         *y += croom->ly;
1377.     }
1378. }
1379. 
1380. /*
1381.  * Get a relative position inside a room.
1382.  * negative values for x or y means RANDOM!
1383.  */
1384. staticfn void
1385. get_free_room_loc(
1386.     coordxy *x, coordxy *y,
1387.     struct mkroom *croom,
1388.     packed_coord pos)
1389. {
1390.     coordxy try_x, try_y;
1391.     int trycnt = 0;
1392. 
1393.     get_location_coord(&try_x, &try_y, DRY, croom, pos);
1394.     if (levl[try_x][try_y].typ != ROOM) {
1395.         do {
1396.             try_x = *x, try_y = *y;
1397.             get_room_loc(&try_x, &try_y, croom);
1398.         } while (levl[try_x][try_y].typ != ROOM && ++trycnt <= 100);
1399. 
1400.         if (trycnt > 100)
1401.             panic("get_free_room_loc:  can't find a place!");
1402.     }
1403.     *x = try_x, *y = try_y;
1404. }
1405. 
1406. boolean
1407. check_room(
1408.     coordxy *lowx, coordxy *ddx,
1409.     coordxy *lowy, coordxy *ddy,
1410.     boolean vault)
1411. {
1412.     int x, y, hix = *lowx + *ddx, hiy = *lowy + *ddy;
1413.     struct rm *lev;
1414.     int xlim, ylim, ymax;
1415.     coordxy s_lowx, s_ddx, s_lowy, s_ddy;
1416. 
1417.     s_lowx = *lowx; s_ddx = *ddx;
1418.     s_lowy = *lowy; s_ddy = *ddy;
1419. 
1420.     xlim = XLIM + (vault ? 1 : 0);
1421.     ylim = YLIM + (vault ? 1 : 0);
1422. 
1423.     if (*lowx < 3)
1424.         *lowx = 3;
1425.     if (*lowy < 2)
1426.         *lowy = 2;
1427.     if (hix > COLNO - 3)
1428.         hix = COLNO - 3;
1429.     if (hiy > ROWNO - 3)
1430.         hiy = ROWNO - 3;
1431.  chk:
1432.     if (hix <= *lowx || hiy <= *lowy)
1433.         return FALSE;
1434. 
1435.     if (gi.in_mk_themerooms && (s_lowx != *lowx) && (s_ddx != *ddx)
1436.         && (s_lowy != *lowy) && (s_ddy != *ddy))
1437.         return FALSE;
1438. 
1439.     /* check area around room (and make room smaller if necessary) */
1440.     for (x = *lowx - xlim; x <= hix + xlim; x++) {
1441.         if (x <= 0 || x >= COLNO)
1442.             continue;
1443.         y = *lowy - ylim;
1444.         ymax = hiy + ylim;
1445.         if (y < 0)
1446.             y = 0;
1447.         if (ymax >= ROWNO)
1448.             ymax = (ROWNO - 1);
1449.         lev = &levl[x][y];
1450.         for (; y <= ymax; y++) {
1451.             if (lev++->typ != STONE) {
1452.                 if (!vault) {
1453.                     debugpline2("strange area [%d,%d] in check_room.", x, y);
1454.                 }
1455.                 if (!rn2(3))
1456.                     return FALSE;
1457.                 if (gi.in_mk_themerooms)
1458.                     return FALSE;
1459.                 if (x < *lowx)
1460.                     *lowx = x + xlim + 1;
1461.                 else
1462.                     hix = x - xlim - 1;
1463.                 if (y < *lowy)
1464.                     *lowy = y + ylim + 1;
1465.                 else
1466.                     hiy = y - ylim - 1;
1467.                 goto chk;
1468.             }
1469.         }
1470.     }
1471.     *ddx = hix - *lowx;
1472.     *ddy = hiy - *lowy;
1473. 
1474.     if (gi.in_mk_themerooms && (s_lowx != *lowx) && (s_ddx != *ddx)
1475.         && (s_lowy != *lowy) && (s_ddy != *ddy))
1476.         return FALSE;
1477. 
1478.     return TRUE;
1479. }
1480. 
1481. /*
1482.  * Create a new room.
1483.  * This is still very incomplete...
1484.  */
1485. boolean
1486. create_room(
1487.     coordxy x, coordxy y,
1488.     coordxy w, coordxy h,
1489.     coordxy xal, coordxy yal,
1490.     xint16 rtype, xint16 rlit)
1491. {
1492.     coordxy xabs = 0, yabs = 0;
1493.     int wtmp, htmp, xaltmp, yaltmp, xtmp, ytmp;
1494.     NhRect *r1 = 0, r2;
1495.     int trycnt = 0;
1496.     boolean vault = FALSE;
1497.     int xlim = XLIM, ylim = YLIM;
1498. 
1499.     if (rtype == -1) /* Is the type random ? */
1500.         rtype = OROOM;
1501. 
1502.     if (rtype == VAULT) {
1503.         vault = TRUE;
1504.         xlim++;
1505.         ylim++;
1506.     }
1507. 
1508.     /* on low levels the room is lit (usually) */
1509.     /* some other rooms may require lighting */
1510. 
1511.     /* is light state random ? */
1512.     rlit = litstate_rnd(rlit);
1513. 
1514.     /*
1515.      * Here we will try to create a room. If some parameters are
1516.      * random we are willing to make several try before we give
1517.      * it up.
1518.      */
1519.     do {
1520.         coordxy xborder, yborder;
1521. 
1522.         wtmp = w;
1523.         htmp = h;
1524.         xtmp = x;
1525.         ytmp = y;
1526.         xaltmp = xal;
1527.         yaltmp = yal;
1528. 
1529.         /* First case : a totally random room */
1530. 
1531.         if ((xtmp < 0 && ytmp < 0 && wtmp < 0 && xaltmp < 0 && yaltmp < 0)
1532.             || vault) {
1533.             coordxy hx, hy, lx, ly, dx, dy;
1534. 
1535.             r1 = rnd_rect(); /* Get a random rectangle */
1536. 
1537.             if (!r1) { /* No more free rectangles ! */
1538.                 debugpline0("No more rects...");
1539.                 return FALSE;
1540.             }
1541.             hx = r1->hx;
1542.             hy = r1->hy;
1543.             lx = r1->lx;
1544.             ly = r1->ly;
1545.             if (vault) {
1546.                 dx = dy = 1;
1547.             } else {
1548.                 dx = 2 + rn2((hx - lx > 28) ? 12 : 8);
1549.                 dy = 2 + rn2(4);
1550.                 if (dx * dy > 50)
1551.                     dy = 50 / dx;
1552.             }
1553.             xborder = (lx > 0 && hx < COLNO - 1) ? 2 * xlim : xlim + 1;
1554.             yborder = (ly > 0 && hy < ROWNO - 1) ? 2 * ylim : ylim + 1;
1555.             if (hx - lx < dx + 3 + xborder || hy - ly < dy + 3 + yborder) {
1556.                 r1 = 0;
1557.                 continue;
1558.             }
1559.             xabs = lx + (lx > 0 ? xlim : 3)
1560.                    + rn2(hx - (lx > 0 ? lx : 3) - dx - xborder + 1);
1561.             yabs = ly + (ly > 0 ? ylim : 2)
1562.                    + rn2(hy - (ly > 0 ? ly : 2) - dy - yborder + 1);
1563.             if (ly == 0 && hy >= ROWNO - 1
1564.                 && (!svn.nroom || !rn2(svn.nroom))
1565.                 && (yabs + dy > ROWNO / 2)) {
1566.                 yabs = rn1(3, 2);
1567.                 if (svn.nroom < 4 && dy > 1)
1568.                     dy--;
1569.             }
1570.             if (!check_room(&xabs, &dx, &yabs, &dy, vault)) {
1571.                 r1 = 0;
1572.                 continue;
1573.             }
1574.             wtmp = dx + 1;
1575.             htmp = dy + 1;
1576.             r2.lx = xabs - 1;
1577.             r2.ly = yabs - 1;
1578.             r2.hx = xabs + wtmp;
1579.             r2.hy = yabs + htmp;
1580.         } else { /* Only some parameters are random */
1581.             int rndpos = 0;
1582.             coordxy dx, dy;
1583. 
1584.             if (xtmp < 0 && ytmp < 0) { /* Position is RANDOM */
1585.                 xtmp = rnd(5);
1586.                 ytmp = rnd(5);
1587.                 rndpos = 1;
1588.             }
1589.             if (wtmp < 0 || htmp < 0) { /* Size is RANDOM */
1590.                 wtmp = rn1(15, 3);
1591.                 htmp = rn1(8, 2);
1592.             }
1593.             if (xaltmp == -1) /* Horizontal alignment is RANDOM */
1594.                 xaltmp = rnd(3);
1595.             if (yaltmp == -1) /* Vertical alignment is RANDOM */
1596.                 yaltmp = rnd(3);
1597. 
1598.             /* Try to generate real (absolute) coordinates here! */
1599. 
1600.             xabs = (((xtmp - 1) * COLNO) / 5) + 1;
1601.             yabs = (((ytmp - 1) * ROWNO) / 5) + 1;
1602.             switch (xaltmp) {
1603.             case SPLEV_LEFT:
1604.                 break;
1605.             case SPLEV_RIGHT:
1606.                 xabs += (COLNO / 5) - wtmp;
1607.                 break;
1608.             case SPLEV_CENTER:
1609.                 xabs += ((COLNO / 5) - wtmp) / 2;
1610.                 break;
1611.             }
1612.             switch (yaltmp) {
1613.             case TOP:
1614.                 break;
1615.             case BOTTOM:
1616.                 yabs += (ROWNO / 5) - htmp;
1617.                 break;
1618.             case SPLEV_CENTER:
1619.                 yabs += ((ROWNO / 5) - htmp) / 2;
1620.                 break;
1621.             }
1622. 
1623.             if (xabs + wtmp - 1 > COLNO - 2)
1624.                 xabs = COLNO - wtmp - 3;
1625.             if (xabs < 2)
1626.                 xabs = 2;
1627.             if (yabs + htmp - 1 > ROWNO - 2)
1628.                 yabs = ROWNO - htmp - 3;
1629.             if (yabs < 2)
1630.                 yabs = 2;
1631. 
1632.             /* Try to find a rectangle that fit our room ! */
1633. 
1634.             r2.lx = xabs - 1;
1635.             r2.ly = yabs - 1;
1636.             r2.hx = xabs + wtmp + rndpos;
1637.             r2.hy = yabs + htmp + rndpos;
1638.             r1 = get_rect(&r2);
1639.             dx = wtmp;
1640.             dy = htmp;
1641. 
1642.             if (r1 && !check_room(&xabs, &dx, &yabs, &dy, vault)) {
1643.                 r1 = 0;
1644.             }
1645.         }
1646.     } while (++trycnt <= 100 && !r1);
1647.     if (!r1) { /* creation of room failed ? */
1648.         return FALSE;
1649.     }
1650.     split_rects(r1, &r2);
1651. 
1652.     if (!vault) {
1653.         gs.smeq[svn.nroom] = svn.nroom;
1654.         add_room(xabs, yabs, xabs + wtmp - 1, yabs + htmp - 1, rlit, rtype,
1655.                  FALSE);
1656.     } else {
1657.         svr.rooms[svn.nroom].lx = xabs;
1658.         svr.rooms[svn.nroom].ly = yabs;
1659.     }
1660.     return TRUE;
1661. }
1662. 
1663. /*
1664.  * Create a subroom in room proom at pos x,y with width w & height h.
1665.  * x & y are relative to the parent room.
1666.  */
1667. staticfn boolean
1668. create_subroom(
1669.     struct mkroom *proom,
1670.     coordxy x, coordxy y,
1671.     coordxy w, coordxy h,
1672.     xint16 rtype, xint16 rlit)
1673. {
1674.     coordxy width, height;
1675. 
1676.     width = proom->hx - proom->lx + 1;
1677.     height = proom->hy - proom->ly + 1;
1678. 
1679.     /* There is a minimum size for the parent room */
1680.     if (width < 4 || height < 4)
1681.         return FALSE;
1682. 
1683.     /* Check for random position, size, etc... */
1684. 
1685.     if (w == -1)
1686.         w = rnd(width - 3);
1687.     if (h == -1)
1688.         h = rnd(height - 3);
1689.     if (x == -1)
1690.         x = rnd(width - w);
1691.     if (y == -1)
1692.         y = rnd(height - h);
1693.     if (x == 1)
1694.         x = 0;
1695.     if (y == 1)
1696.         y = 0;
1697.     if ((x + w + 1) == width)
1698.         x++;
1699.     if ((y + h + 1) == height)
1700.         y++;
1701.     if (rtype == -1)
1702.         rtype = OROOM;
1703.     rlit = litstate_rnd(rlit);
1704.     add_subroom(proom, proom->lx + x, proom->ly + y, proom->lx + x + w - 1,
1705.                 proom->ly + y + h - 1, rlit, rtype, FALSE);
1706.     return TRUE;
1707. }
1708. 
1709. /*
1710.  * Create a new door in a room.
1711.  * It's placed on a wall (north, south, east or west).
1712.  */
1713. staticfn void
1714. create_door(room_door *dd, struct mkroom *broom)
1715. {
1716.     int x = 0, y = 0;
1717.     int trycnt;
1718. 
1719.     if (dd->secret == -1)
1720.         dd->secret = rn2(2);
1721. 
1722.     if (dd->wall == W_RANDOM)
1723.         dd->wall = W_ANY; /* speeds things up in the below loop */
1724. 
1725.     if (dd->mask == -1) {
1726.         /* is it a locked door, closed, or a doorway? */
1727.         if (!dd->secret) {
1728.             if (!rn2(3)) {
1729.                 if (!rn2(5))
1730.                     dd->mask = D_ISOPEN;
1731.                 else if (!rn2(6))
1732.                     dd->mask = D_LOCKED;
1733.                 else
1734.                     dd->mask = D_CLOSED;
1735.                 if (dd->mask != D_ISOPEN && !rn2(25))
1736.                     dd->mask |= D_TRAPPED;
1737.             } else
1738.                 dd->mask = D_NODOOR;
1739.         } else {
1740.             if (!rn2(5))
1741.                 dd->mask = D_LOCKED;
1742.             else
1743.                 dd->mask = D_CLOSED;
1744. 
1745.             if (!rn2(20))
1746.                 dd->mask |= D_TRAPPED;
1747.         }
1748.     }
1749. 
1750.     for (trycnt = 0; trycnt < 100; ++trycnt) {
1751.         int dwall = dd->wall, dpos = dd->pos;
1752. 
1753.         /* Convert wall and pos into an absolute coordinate! */
1754.         switch (rn2(4)) {
1755.         case 0:
1756.             if (!(dwall & W_NORTH))
1757.                 continue;
1758.             y = broom->ly - 1;
1759.             x = broom->lx + ((dpos == -1) ? rn2(1 + broom->hx - broom->lx)
1760.                                           : dpos);
1761.             if (!isok(x, y - 1) || IS_OBSTRUCTED(levl[x][y - 1].typ))
1762.                 continue;
1763.             break;
1764.         case 1:
1765.             if (!(dwall & W_SOUTH))
1766.                 continue;
1767.             y = broom->hy + 1;
1768.             x = broom->lx + ((dpos == -1) ? rn2(1 + broom->hx - broom->lx)
1769.                                           : dpos);
1770.             if (!isok(x, y + 1) || IS_OBSTRUCTED(levl[x][y + 1].typ))
1771.                 continue;
1772.             break;
1773.         case 2:
1774.             if (!(dwall & W_WEST))
1775.                 continue;
1776.             x = broom->lx - 1;
1777.             y = broom->ly + ((dpos == -1) ? rn2(1 + broom->hy - broom->ly)
1778.                                           : dpos);
1779.             if (!isok(x - 1, y) || IS_OBSTRUCTED(levl[x - 1][y].typ))
1780.                 continue;
1781.             break;
1782.         case 3:
1783.             if (!(dwall & W_EAST))
1784.                 continue;
1785.             x = broom->hx + 1;
1786.             y = broom->ly + ((dpos == -1) ? rn2(1 + broom->hy - broom->ly)
1787.                                           : dpos);
1788.             if (!isok(x + 1, y) || IS_OBSTRUCTED(levl[x + 1][y].typ))
1789.                 continue;
1790.             break;
1791.         default:
1792.             /*NOTREACHED*/
1793.             break;
1794.         }
1795. 
1796.         if (okdoor(x, y))
1797.             break;
1798.     }
1799.     if (trycnt >= 100) {
1800.         impossible("create_door: Can't find a proper place!");
1801.         return;
1802.     }
1803.     if (!set_levltyp(x, y, (dd->secret ? SDOOR : DOOR)))
1804.         return;
1805.     levl[x][y].doormask = dd->mask;
1806. }
1807. 
1808. /*
1809.  * Create a trap in a room.
1810.  */
1811. staticfn void
1812. create_trap(spltrap *t, struct mkroom *croom)
1813. {
1814.     coordxy x = -1, y = -1;
1815.     coord tm;
1816.     unsigned mktrap_flags = MKTRAP_MAZEFLAG;
1817. 
1818.     if (t->type == VIBRATING_SQUARE) {
1819.         pick_vibrasquare_location();
1820.         maketrap(svi.inv_pos.x, svi.inv_pos.y, VIBRATING_SQUARE);
1821.         return;
1822.     } else if (croom) {
1823.         get_free_room_loc(&x, &y, croom, t->coord);
1824.     } else {
1825.         int trycnt = 0;
1826. 
1827.         do {
1828.             get_location_coord(&x, &y, DRY, croom, t->coord);
1829.         } while ((levl[x][y].typ == STAIRS || levl[x][y].typ == LADDER)
1830.                  && ++trycnt <= 100);
1831.         if (trycnt > 100)
1832.             return;
1833.     }
1834. 
1835.     if (!t->spider_on_web)
1836.         mktrap_flags |= MKTRAP_NOSPIDERONWEB;
1837.     if (t->seen)
1838.         mktrap_flags |= MKTRAP_SEEN;
1839.     if (t->novictim)
1840.         mktrap_flags |= MKTRAP_NOVICTIM;
1841. 
1842.     tm.x = x;
1843.     tm.y = y;
1844. 
1845.     mktrap(t->type, mktrap_flags, (struct mkroom *) 0, &tm);
1846. }
1847. 
1848. /*
1849.  * Create a monster in a room.
1850.  */
1851. staticfn int
1852. noncoalignment(aligntyp alignment)
1853. {
1854.     int k;
1855. 
1856.     k = rn2(2);
1857.     if (!alignment)
1858.         return (k ? -1 : 1);
1859.     return (k ? -alignment : 0);
1860. }
1861. 
1862. /* attempt to screen out locations where a mimic-as-boulder shouldn't occur */
1863. staticfn boolean
1864. m_bad_boulder_spot(coordxy x, coordxy y)
1865. {
1866.     struct rm *lev;
1867. 
1868.     /* avoid trap locations */
1869.     if (t_at(x, y))
1870.         return TRUE;
1871.     /* try to avoid locations which already have a boulder (this won't
1872.        actually work; we get called before objects have been placed...) */
1873.     if (sobj_at(BOULDER, x, y))
1874.         return TRUE;
1875.     /* avoid closed doors */
1876.     lev = &levl[x][y];
1877.     if (IS_DOOR(lev->typ) && (lev->doormask & (D_CLOSED | D_LOCKED)) != 0)
1878.         return TRUE;
1879.     /* spot is ok */
1880.     return FALSE;
1881. }
1882. 
1883. staticfn int
1884. pm_to_humidity(struct permonst *pm)
1885. {
1886.     int loc = DRY;
1887. 
1888.     if (!pm)
1889.         return loc;
1890.     if (pm->mlet == S_EEL || amphibious(pm) || is_swimmer(pm))
1891.         loc = WET;
1892.     if (is_flyer(pm) || is_floater(pm))
1893.         loc |= (HOT | WET);
1894.     if (passes_walls(pm) || noncorporeal(pm))
1895.         loc |= SOLID;
1896.     if (likes_fire(pm))
1897.         loc |= HOT;
1898.     return loc;
1899. }
1900. 
1901. /*
1902.  * Convert a special level alignment mask (an alignment mask with possible
1903.  * extra values/flags) to a "normal" alignment mask (no extra flags).
1904.  *
1905.  * When random: there is an 80% chance that the altar will be co-aligned.
1906.  */
1907. staticfn unsigned int
1908. sp_amask_to_amask(unsigned int sp_amask)
1909. {
1910.     unsigned int amask;
1911. 
1912.     if (sp_amask == AM_SPLEV_CO)
1913.         amask = Align2amask(u.ualignbase[A_ORIGINAL]);
1914.     else if (sp_amask == AM_SPLEV_NONCO)
1915.         amask = Align2amask(noncoalignment(u.ualignbase[A_ORIGINAL]));
1916.     else if (sp_amask == AM_SPLEV_RANDOM)
1917.         amask = induced_align(80);
1918.     else
1919.         amask = sp_amask & AM_MASK;
1920. 
1921.     return amask;
1922. }
1923. 
1924. staticfn void
1925. create_monster(monster *m, struct mkroom *croom)
1926. {
1927.     struct monst *mtmp;
1928.     coordxy x, y;
1929.     char class;
1930.     unsigned int amask;
1931.     coord cc;
1932.     struct permonst *pm;
1933.     unsigned g_mvflags;
1934. 
1935.     if (m->class >= 0)
1936.         class = (char) def_char_to_monclass((char) m->class);
1937.     else
1938.         class = 0;
1939. 
1940.     if (class == MAXMCLASSES)
1941.         panic("create_monster: unknown monster class '%c'", m->class);
1942. 
1943.     amask = sp_amask_to_amask(m->sp_amask);
1944. 
1945.     if (!class) {
1946.         pm = (struct permonst *) 0;
1947.     } else if (m->id != NON_PM) {
1948.         pm = &mons[m->id];
1949.         g_mvflags = (unsigned) svm.mvitals[monsndx(pm)].mvflags;
1950.         if ((pm->geno & G_UNIQ) && (g_mvflags & G_EXTINCT))
1951.             return;
1952.         if (g_mvflags & G_GONE) /* genocided or extinct */
1953.             pm = (struct permonst *) 0; /* make random monster */
1954.     } else {
1955.         pm = mkclass(class, G_NOGEN);
1956.         /* if we can't get a specific monster type (pm == 0) then the
1957.            class has been genocided, so settle for a random monster */
1958.     }
1959.     if (In_mines(&u.uz) && pm && your_race(pm)
1960.         && (Race_if(PM_DWARF) || Race_if(PM_GNOME)) && rn2(3))
1961.         pm = (struct permonst *) 0;
1962. 
1963.     if (pm) {
1964.         int loc = pm_to_humidity(pm);
1965. 
1966.         /* If water-liking monster, first try is without DRY */
1967.         get_location_coord(&x, &y, loc | NO_LOC_WARN, croom, m->coord);
1968.         if (x == -1 && y == -1) {
1969.             loc |= DRY;
1970.             get_location_coord(&x, &y, loc, croom, m->coord);
1971.         }
1972.     } else {
1973.         get_location_coord(&x, &y, DRY, croom, m->coord);
1974.     }
1975. 
1976.     /* try to find a close place if someone else is already there */
1977.     if (MON_AT(x, y) && enexto(&cc, x, y, pm))
1978.         x = cc.x, y = cc.y;
1979. 
1980.     if (croom && !inside_room(croom, x, y))
1981.         return;
1982. 
1983.     if (m->sp_amask != AM_SPLEV_RANDOM)
1984.         mtmp = mk_roamer(pm, Amask2align(amask), x, y, m->peaceful);
1985.     else if (PM_ARCHEOLOGIST <= m->id && m->id <= PM_WIZARD)
1986.         mtmp = mk_mplayer(pm, x, y, FALSE);
1987.     else
1988.         mtmp = makemon(pm, x, y, m->mm_flags);
1989. 
1990.     if (mtmp) {
1991.         x = mtmp->mx, y = mtmp->my; /* sanity precaution */
1992.         m->x = x, m->y = y;
1993.         /* handle specific attributes for some special monsters */
1994.         if (m->name.str)
1995.             mtmp = christen_monst(mtmp, m->name.str);
1996. 
1997.         /*
1998.          * This doesn't complain if an attempt is made to give a
1999.          * non-mimic/non-shapechanger an appearance or to give a
2000.          * shapechanger a non-monster shape, it just refuses to comply.
2001.          */
2002.         if (m->appear_as.str
2003.             && ((mtmp->data->mlet == S_MIMIC)
2004.                 /* shapechanger (chameleons, et al, and vampires) */
2005.                 || (ismnum(mtmp->cham) && m->appear == M_AP_MONSTER))
2006.             && !Protection_from_shape_changers) {
2007.             int i;
2008. 
2009.             switch (m->appear) {
2010.             case M_AP_NOTHING:
2011.                 impossible(
2012.                  "create_monster: mon has an appearance, \"%s\", but no type",
2013.                            m->appear_as.str);
2014.                 break;
2015. 
2016.             case M_AP_FURNITURE:
2017.                 for (i = 0; i < MAXPCHARS; i++)
2018.                     if (!strcmp(defsyms[i].explanation, m->appear_as.str))
2019.                         break;
2020.                 if (i == MAXPCHARS) {
2021.                     impossible("create_monster: can't find feature \"%s\"",
2022.                                m->appear_as.str);
2023.                 } else {
2024.                     mtmp->m_ap_type = M_AP_FURNITURE;
2025.                     mtmp->mappearance = i;
2026.                 }
2027.                 break;
2028. 
2029.             case M_AP_OBJECT:
2030.                 for (i = 0; i < NUM_OBJECTS; i++)
2031.                     if (OBJ_NAME(objects[i])
2032.                         && !strcmp(OBJ_NAME(objects[i]), m->appear_as.str))
2033.                         break;
2034.                 if (i == NUM_OBJECTS) {
2035.                     impossible("create_monster: can't find object \"%s\"",
2036.                                m->appear_as.str);
2037.                 } else {
2038.                     mtmp->m_ap_type = M_AP_OBJECT;
2039.                     mtmp->mappearance = i;
2040.                     /* try to avoid placing mimic boulder on a trap */
2041.                     if (i == BOULDER && m->x < 0
2042.                         && m_bad_boulder_spot(x, y)) {
2043.                         int retrylimit = 10;
2044. 
2045.                         remove_monster(x, y);
2046.                         do {
2047.                             x = m->x;
2048.                             y = m->y;
2049.                             get_location(&x, &y, DRY, croom);
2050.                             if (MON_AT(x, y) && enexto(&cc, x, y, pm))
2051.                                 x = cc.x, y = cc.y;
2052.                         } while (m_bad_boulder_spot(x, y)
2053.                                  && --retrylimit > 0);
2054.                         place_monster(mtmp, x, y);
2055.                         /* if we didn't find a good spot
2056.                            then mimic something else */
2057.                         if (!retrylimit)
2058.                             set_mimic_sym(mtmp);
2059.                     }
2060.                 }
2061.                 break;
2062. 
2063.             case M_AP_MONSTER: {
2064.                 int mndx, gender_name_var = NEUTRAL;
2065. 
2066.                 if (!strcmpi(m->appear_as.str, "random"))
2067.                     mndx = select_newcham_form(mtmp);
2068.                 else
2069.                     mndx = name_to_mon(m->appear_as.str, &gender_name_var);
2070. 
2071.                 if (mndx == NON_PM || (is_vampshifter(mtmp)
2072.                                        && !validvamp(mtmp, &mndx, S_HUMAN))) {
2073.                     impossible("create_monster: invalid %s (\"%s\")",
2074.                                (mtmp->data->mlet == S_MIMIC)
2075.                                  ? "mimic appearance"
2076.                                  : (mtmp->data == &mons[PM_WIZARD_OF_YENDOR])
2077.                                      ? "Wizard appearance"
2078.                                      : is_vampshifter(mtmp)
2079.                                          ? "vampire shape"
2080.                                          : "chameleon shape",
2081.                                m->appear_as.str);
2082.                 } else if (&mons[mndx] == mtmp->data) {
2083.                     /* explicitly forcing a mimic to appear as itself */
2084.                     mtmp->m_ap_type = M_AP_NOTHING;
2085.                     mtmp->mappearance = 0;
2086.                 } else if (mtmp->data->mlet == S_MIMIC
2087.                            || mtmp->data == &mons[PM_WIZARD_OF_YENDOR]) {
2088.                     /* this is ordinarily only used for Wizard clones
2089.                        and hasn't been exhaustively tested for mimics */
2090.                     mtmp->m_ap_type = M_AP_MONSTER;
2091.                     mtmp->mappearance = mndx;
2092.                 } else { /* chameleon or vampire */
2093.                     struct permonst *mdat = &mons[mndx];
2094.                     struct permonst *olddata = mtmp->data;
2095. 
2096.                     mgender_from_permonst(mtmp, mdat);
2097.                     if (gender_name_var != NEUTRAL)
2098.                         mtmp->female = gender_name_var;
2099.                     set_mon_data(mtmp, mdat);
2100.                     if (emits_light(olddata) != emits_light(mtmp->data)) {
2101.                         /* used to give light, now doesn't, or vice versa,
2102.                            or light's range has changed */
2103.                         if (emits_light(olddata))
2104.                             del_light_source(LS_MONSTER, monst_to_any(mtmp));
2105.                         if (emits_light(mtmp->data))
2106.                             new_light_source(mtmp->mx, mtmp->my,
2107.                                              emits_light(mtmp->data),
2108.                                              LS_MONSTER, monst_to_any(mtmp));
2109.                     }
2110.                     if (!mtmp->perminvis || pm_invisible(olddata))
2111.                         mtmp->perminvis = pm_invisible(mdat);
2112.                 }
2113.                 break;
2114.             }
2115.             default:
2116.                 impossible(
2117.                   "create_monster: unimplemented mon appear type [%d,\"%s\"]",
2118.                            m->appear, m->appear_as.str);
2119.                 break;
2120.             }
2121.             if (does_block(x, y, &levl[x][y]))
2122.                 block_point(x, y);
2123.         }
2124. 
2125.         mtmp->female = m->female;
2126.         if (m->peaceful > BOOL_RANDOM) {
2127.             mtmp->mpeaceful = m->peaceful;
2128.             /* changed mpeaceful again; have to reset malign */
2129.             set_malign(mtmp);
2130.         }
2131.         if (m->asleep > BOOL_RANDOM)
2132.             mtmp->msleeping = m->asleep;
2133.         if (m->seentraps)
2134.             mtmp->mtrapseen = m->seentraps;
2135.         if (m->cancelled)
2136.             mtmp->mcan = 1;
2137.         if (m->revived)
2138.             mtmp->mrevived = 1;
2139.         if (m->avenge)
2140.             mtmp->mavenge = 1;
2141.         if (m->stunned)
2142.             mtmp->mstun = 1;
2143.         if (m->confused)
2144.             mtmp->mconf = 1;
2145.         if (m->invis) {
2146.             mtmp->minvis = mtmp->perminvis = 1;
2147.         }
2148.         if (m->blinded) {
2149.             mtmp->mcansee = 0;
2150.             mtmp->mblinded = (m->blinded % 127);
2151.         }
2152.         if (m->paralyzed) {
2153.             mtmp->mcanmove = 0;
2154.             mtmp->mfrozen = (m->paralyzed % 127);
2155.         }
2156.         if (m->fleeing) {
2157.             mtmp->mflee = 1;
2158.             mtmp->mfleetim = (m->fleeing % 127);
2159.         }
2160.         if (m->waiting) {
2161.             mtmp->mstrategy |= STRAT_WAITFORU;
2162.             /* if this is a vampire that got created already shifted into
2163.                bat/fog/wolf form and the special level or theme room didn't
2164.                explicitly request that, shift back to vampire */
2165.             if (vampshifted(mtmp) && m->appear != M_AP_MONSTER)
2166.                 (void) newcham(mtmp, &mons[mtmp->cham], NO_NC_FLAGS);
2167.         }
2168.         if (m->m_lev_adj) {
2169.             if (mtmp->m_lev + m->m_lev_adj > 49)
2170.                 mtmp->m_lev = 49;
2171.             else if (mtmp->m_lev + m->m_lev_adj < 0)
2172.                 mtmp->m_lev = 0;
2173.             else
2174.                 mtmp->m_lev += m->m_lev_adj;
2175.         }
2176.         if (!(m->has_invent & DEFAULT_INVENT)) {
2177.             /* guard against someone accidentally specifying e.g. quest nemesis
2178.              * with custom inventory that lacks Bell or quest artifact but
2179.              * forgetting to flag them as receiving their default inventory */
2180.             mdrop_special_objs(mtmp);
2181.             discard_minvent(mtmp, TRUE);
2182.         }
2183.         if (m->has_invent & CUSTOM_INVENT) {
2184.             invent_carrying_monster = mtmp;
2185.         }
2186.     }
2187. }
2188. 
2189. /*
2190.  * Create an object in a room.
2191.  */
2192. staticfn struct obj *
2193. create_object(object *o, struct mkroom *croom)
2194. {
2195.     struct obj *otmp;
2196.     coordxy x, y;
2197.     char c;
2198.     boolean named; /* has a name been supplied in level description? */
2199. 
2200.     named = o->name.str ? TRUE : FALSE;
2201. 
2202.     get_location_coord(&x, &y, DRY, croom, o->coord);
2203. 
2204.     if (o->class >= 0)
2205.         c = o->class;
2206.     else
2207.         c = 0;
2208. 
2209.     if (!c) {
2210.         otmp = mkobj_at(RANDOM_CLASS, x, y, !named);
2211.     } else if (o->id != -1) {
2212.         otmp = mksobj_at(o->id, x, y, TRUE, !named);
2213.     } else {
2214.         /*
2215.          * The special levels are compiled with the default "text" object
2216.          * class characters.  We must convert them to the internal format.
2217.          */
2218.         char oclass = (char) def_char_to_objclass(c);
2219. 
2220.         if (oclass == MAXOCLASSES)
2221.             panic("create_object:  unexpected object class '%c'", c);
2222. 
2223.         /* KMH -- Create piles of gold properly */
2224.         if (oclass == COIN_CLASS)
2225.             otmp = mkgold(0L, x, y);
2226.         else
2227.             otmp = mkobj_at(oclass, x, y, !named);
2228.     }
2229. 
2230.     if (o->spe != -127) /* That means NOT RANDOM! */
2231.         otmp->spe = (schar) o->spe;
2232. 
2233.     switch (o->curse_state) {
2234.     case 1: /* blessed */
2235.         bless(otmp);
2236.         break;
2237.     case 2: /* uncursed */
2238.         unbless(otmp);
2239.         uncurse(otmp);
2240.         break;
2241.     case 3: /* cursed */
2242.         curse(otmp);
2243.         break;
2244.     case 4: /* not cursed */
2245.         uncurse(otmp);
2246.         break;
2247.     case 5: /* not uncursed */
2248.         blessorcurse(otmp, 1);
2249.         break;
2250.     case 6: /* not blessed */
2251.         unbless(otmp);
2252.         break;
2253.     default: /* random */
2254.         break; /* keep what mkobj gave us */
2255.     }
2256. 
2257.     /* corpsenm is "empty" if -1, random if -2, otherwise specific */
2258.     if (o->corpsenm != NON_PM) {
2259.         if (o->corpsenm == NON_PM - 1)
2260.             set_corpsenm(otmp, rndmonnum());
2261.         else
2262.             set_corpsenm(otmp, o->corpsenm);
2263.     }
2264.     /* set_corpsenm() took care of egg hatch and corpse timers */
2265. 
2266.     if (named) {
2267.         otmp = oname(otmp, o->name.str, ONAME_LEVEL_DEF);
2268.         if (otmp->otyp == SPE_NOVEL) {
2269.             /* needs to be an existing title */
2270.             (void) lookup_novel(o->name.str, &otmp->novelidx);
2271.         }
2272.     }
2273.     if (o->eroded) {
2274.         if (o->eroded < 0) {
2275.             otmp->oerodeproof = 1;
2276.         } else {
2277.             otmp->oeroded = (o->eroded % 4);
2278.             otmp->oeroded2 = ((o->eroded >> 2) % 4);
2279.         }
2280.     } else {
2281.         otmp->oeroded = otmp->oeroded2 = 0;
2282.         otmp->oerodeproof = 0;
2283.     }
2284.     if (o->recharged)
2285.         otmp->recharged = (o->recharged % 8);
2286.     if (o->locked == 0 || o->locked == 1) {
2287.         otmp->olocked = o->locked;
2288.     } else if (o->broken) {
2289.         otmp->obroken = 1;
2290.         otmp->olocked = 0; /* obj generation may set */
2291.     }
2292.     if (o->trapped == 0 || o->trapped == 1)
2293.         otmp->otrapped = o->trapped;
2294.     if (o->trapped && (o->tknown == 0 || o->tknown == 1))
2295.         otmp->tknown = o->tknown;
2296.     otmp->greased = o->greased ? 1 : 0;
2297. 
2298.     if (o->quan > 0 && objects[otmp->otyp].oc_merge) {
2299.         otmp->quan = o->quan;
2300.         otmp->owt = weight(otmp);
2301.     }
2302. 
2303.     /* contents (of a container or monster's inventory) */
2304.     if (o->containment & SP_OBJ_CONTENT || invent_carrying_monster) {
2305.         if (!container_idx) {
2306.             if (!invent_carrying_monster) {
2307.                 /*impossible("create_object: no container");*/
2308.                 /* don't complain, the monster may be gone legally
2309.                    (eg. unique demon already generated)
2310.                    TODO: In the case of unique demon lords, they should
2311.                    get their inventories even when they get generated
2312.                    outside the des-file.  Maybe another data file that
2313.                    determines what inventories monsters get by default?
2314.                  */
2315.                 ; /* ['otmp' remains on floor] */
2316.             } else {
2317.                 remove_object(otmp);
2318.                 if (otmp->otyp == SADDLE && can_saddle(invent_carrying_monster))
2319.                     put_saddle_on_mon(otmp, invent_carrying_monster);
2320.                 else
2321.                     (void) mpickobj(invent_carrying_monster, otmp);
2322.             }
2323.         } else {
2324.             struct obj *cobj = container_obj[container_idx - 1];
2325. 
2326.             remove_object(otmp);
2327.             if (cobj) {
2328.                 otmp = add_to_container(cobj, otmp);
2329.                 cobj->owt = weight(cobj);
2330.             } else {
2331.                 obj_extract_self(otmp);
2332.                 /* uncreate a random artifact created in a container */
2333.                 /* FIXME: it could be intentional rather than random */
2334.                 if (otmp->oartifact)
2335.                     artifact_exists(otmp, safe_oname(otmp), FALSE,
2336.                                     ONAME_NO_FLAGS); /* flags don't matter */
2337.                 obfree(otmp, NULL);
2338.                 return NULL;
2339.             }
2340.         }
2341.     }
2342.     /* container */
2343.     if (o->containment & SP_OBJ_CONTAINER) {
2344.         delete_contents(otmp);
2345.         if (container_idx < MAX_CONTAINMENT) {
2346.             container_obj[container_idx] = otmp;
2347.             container_idx++;
2348.         } else
2349.             impossible("create_object: too deeply nested containers.");
2350.     }
2351. 
2352.     /* Medusa level special case: statues are petrified monsters, so they
2353.      * are not stone-resistant and have monster inventory.  They also lack
2354.      * other contents, but that can be specified as an empty container.
2355.      */
2356.     if (o->id == STATUE && Is_medusa_level(&u.uz) && o->corpsenm == NON_PM) {
2357.         struct monst *was = NULL;
2358.         struct obj *obj;
2359.         int wastyp;
2360.         int i = 0; /* prevent endless loop in case makemon always fails */
2361. 
2362.         /* Named random statues are of player types, and aren't stone-
2363.          * resistant (if they were, we'd have to reset the name as well as
2364.          * setting corpsenm).
2365.          */
2366.         for (wastyp = otmp->corpsenm; i < 1000; i++, wastyp = rndmonnum()) {
2367.             /* makemon without rndmonst() might create a group */
2368.             was = makemon(&mons[wastyp], 0, 0, MM_NOCOUNTBIRTH|MM_NOMSG);
2369.             if (was) {
2370.                 if (!resists_ston(was) && !poly_when_stoned(&mons[wastyp])) {
2371.                     (void) propagate(wastyp, TRUE, FALSE);
2372.                     break;
2373.                 }
2374.                 mongone(was);
2375.                 was = NULL;
2376.             }
2377.         }
2378.         if (was) {
2379.             set_corpsenm(otmp, wastyp);
2380.             while (was->minvent) {
2381.                 obj = was->minvent;
2382.                 obj->owornmask = 0;
2383.                 obj_extract_self(obj);
2384.                 (void) add_to_container(otmp, obj);
2385.             }
2386.             otmp->owt = weight(otmp);
2387.             mongone(was);
2388.         }
2389.     }
2390. 
2391.     if (o->achievement) {
2392.         static const char prize_warning[] = "multiple prizes on %s level";
2393. 
2394.         if (Is_mineend_level(&u.uz)) {
2395.             if (!svc.context.achieveo.mines_prize_oid) {
2396.                 svc.context.achieveo.mines_prize_oid = otmp->o_id;
2397.                 svc.context.achieveo.mines_prize_otyp = otmp->otyp;
2398.                 /* prevent stacking; cleared when achievement is recorded;
2399.                    will be reset in addinv_core1() */
2400.                 otmp->nomerge = 1;
2401.             } else {
2402.                 impossible(prize_warning, "mines end");
2403.             }
2404.         } else if (Is_sokoend_level(&u.uz)) {
2405.             if (!svc.context.achieveo.soko_prize_oid) {
2406.                 svc.context.achieveo.soko_prize_oid = otmp->o_id;
2407.                 svc.context.achieveo.soko_prize_otyp = otmp->otyp;
2408.                 otmp->nomerge = 1; /* redundant; Sokoban prizes don't stack;
2409.                                     * will be reset in addinv_core1() */
2410.             } else {
2411.                 impossible(prize_warning, "sokoban end");
2412.             }
2413.         } else if (!iflags.lua_testing) {
2414.             char lbuf[QBUFSZ];
2415. 
2416.             (void) describe_level(lbuf, 1 | 2);
2417.             impossible("create_object: unknown achievement (%s\"%s\")",
2418.                        lbuf, simpleonames(otmp));
2419.         }
2420.     }
2421. 
2422.     if (!(o->containment & SP_OBJ_CONTENT)) {
2423.         stackobj(otmp);
2424. 
2425.         if (o->lit)
2426.             begin_burn(otmp, FALSE);
2427. 
2428.         if (o->buried) {
2429.             boolean dealloced;
2430. 
2431.             (void) bury_an_obj(otmp, &dealloced);
2432.             if (dealloced) {
2433.                 if (container_idx)
2434.                     container_obj[container_idx - 1] = NULL;
2435.                 otmp = NULL;
2436.             }
2437.         }
2438.     }
2439.     return otmp;
2440. }
2441. 
2442. /*
2443.  * Create an altar in a room.
2444.  */
2445. staticfn void
2446. create_altar(altar *a, struct mkroom *croom)
2447. {
2448.     schar sproom;
2449.     coordxy x = -1, y = -1;
2450.     unsigned int amask;
2451.     boolean croom_is_temple = TRUE;
2452. 
2453.     if (croom) {
2454.         get_free_room_loc(&x, &y, croom, a->coord);
2455.         if (croom->rtype != TEMPLE)
2456.             croom_is_temple = FALSE;
2457.     } else {
2458.         get_location_coord(&x, &y, DRY, croom, a->coord);
2459.         if ((sproom = (schar) *in_rooms(x, y, TEMPLE)) != 0)
2460.             croom = &svr.rooms[sproom - ROOMOFFSET];
2461.         else
2462.             croom_is_temple = FALSE;
2463.     }
2464. 
2465.     /* check for existing features */
2466.     if (!set_levltyp(x, y, ALTAR))
2467.         return;
2468. 
2469.     amask = sp_amask_to_amask(a->sp_amask);
2470. 
2471.     levl[x][y].altarmask = amask;
2472. 
2473.     if (a->shrine < 0)
2474.         a->shrine = rn2(2); /* handle random case */
2475. 
2476.     if (!croom_is_temple || !a->shrine)
2477.         return;
2478. 
2479.     if (a->shrine) { /* Is it a shrine  or sanctum? */
2480.         priestini(&u.uz, croom, x, y, (a->shrine > 1));
2481.         levl[x][y].altarmask |= AM_SHRINE;
2482.         if (a->shrine == 2) /* high altar or sanctum */
2483.             levl[x][y].altarmask |= AM_SANCTUM;
2484.         svl.level.flags.has_temple = TRUE;
2485.     }
2486. }
2487. 
2488. /*
2489.  * Search for a door in a room on a specified wall.
2490.  */
2491. staticfn boolean
2492. search_door(
2493.     struct mkroom *croom,
2494.     coordxy *x, coordxy *y,
2495.     xint16 wall, int cnt)
2496. {
2497.     int dx, dy;
2498.     int xx, yy;
2499. 
2500.     switch (wall) {
2501.     case W_SOUTH:
2502.         dy = 0;
2503.         dx = 1;
2504.         xx = croom->lx;
2505.         yy = croom->hy + 1;
2506.         break;
2507.     case W_NORTH:
2508.         dy = 0;
2509.         dx = 1;
2510.         xx = croom->lx;
2511.         yy = croom->ly - 1;
2512.         break;
2513.     case W_EAST:
2514.         dy = 1;
2515.         dx = 0;
2516.         xx = croom->hx + 1;
2517.         yy = croom->ly;
2518.         break;
2519.     case W_WEST:
2520.         dy = 1;
2521.         dx = 0;
2522.         xx = croom->lx - 1;
2523.         yy = croom->ly;
2524.         break;
2525.     default:
2526.         panic("search_door: Bad wall!");
2527.         /*NOTREACHED*/
2528.     }
2529.     while (xx <= croom->hx + 1 && yy <= croom->hy + 1) {
2530.         if (IS_DOOR(levl[xx][yy].typ) || levl[xx][yy].typ == SDOOR) {
2531.             *x = xx;
2532.             *y = yy;
2533.             if (cnt-- <= 0)
2534.                 return TRUE;
2535.         }
2536.         xx += dx;
2537.         yy += dy;
2538.     }
2539.     return FALSE;
2540. }
2541. 
2542. /*
2543.  * Dig a corridor between two points, using terrain ftyp.
2544.  * if nxcor is TRUE, he corridor may be blocked by a boulder,
2545.  * or just end without reaching the destination.
2546.  * if not null, npoints has the number of map locations used
2547.  */
2548. boolean
2549. dig_corridor(
2550.     coord *org, coord *dest,
2551.     int *npoints,
2552.     boolean nxcor,
2553.     schar ftyp, schar btyp)
2554. {
2555.     int dx = 0, dy = 0, dix, diy, cct;
2556.     struct rm *crm;
2557.     int tx, ty, xx, yy;
2558. 
2559.     if (npoints)
2560.         *npoints = 0;
2561.     xx = org->x;
2562.     yy = org->y;
2563.     tx = dest->x;
2564.     ty = dest->y;
2565.     if (xx <= 0 || yy <= 0 || tx <= 0 || ty <= 0 || xx > COLNO - 1
2566.         || tx > COLNO - 1 || yy > ROWNO - 1 || ty > ROWNO - 1) {
2567.         debugpline4("dig_corridor: bad coords <%d,%d> <%d,%d>.",
2568.                     xx, yy, tx, ty);
2569.         return FALSE;
2570.     }
2571.     if (tx > xx)
2572.         dx = 1;
2573.     else if (ty > yy)
2574.         dy = 1;
2575.     else if (tx < xx)
2576.         dx = -1;
2577.     else
2578.         dy = -1;
2579. 
2580.     xx -= dx;
2581.     yy -= dy;
2582.     cct = 0;
2583.     while (xx != tx || yy != ty) {
2584.         /* loop: dig corridor at [xx,yy] and find new [xx,yy] */
2585.         if (cct++ > 500 || (nxcor && !rn2(35)))
2586.             return FALSE;
2587. 
2588.         xx += dx;
2589.         yy += dy;
2590. 
2591.         if (xx >= COLNO - 1 || xx <= 0 || yy <= 0 || yy >= ROWNO - 1)
2592.             return FALSE; /* impossible */
2593. 
2594.         crm = &levl[xx][yy];
2595.         if (crm->typ == btyp) {
2596.             if (ftyp == CORR && maybe_sdoor(100)) {
2597.                 if (npoints)
2598.                     (*npoints)++;
2599.                 crm->typ = SCORR;
2600.             } else {
2601.                 if (npoints)
2602.                     (*npoints)++;
2603.                 crm->typ = ftyp;
2604.                 if (nxcor && !rn2(50))
2605.                     (void) mksobj_at(BOULDER, xx, yy, TRUE, FALSE);
2606.             }
2607.         } else if (crm->typ != ftyp && crm->typ != SCORR) {
2608.             /* strange ... */
2609.             return FALSE;
2610.         }
2611. 
2612.         /* find next corridor position */
2613.         dix = abs(xx - tx);
2614.         diy = abs(yy - ty);
2615. 
2616.         if ((dix > diy) && diy && !rn2(dix - diy + 1)) {
2617.             dix = 0;
2618.         } else if ((diy > dix) && dix && !rn2(diy - dix + 1)) {
2619.             diy = 0;
2620.         }
2621. 
2622.         /* do we have to change direction ? */
2623.         if (dy && dix > diy) {
2624.             int ddx = (xx > tx) ? -1 : 1;
2625. 
2626.             crm = &levl[xx + ddx][yy];
2627.             if (crm->typ == btyp || crm->typ == ftyp || crm->typ == SCORR) {
2628.                 dx = ddx;
2629.                 dy = 0;
2630.                 continue;
2631.             }
2632.         } else if (dx && diy > dix) {
2633.             int ddy = (yy > ty) ? -1 : 1;
2634. 
2635.             crm = &levl[xx][yy + ddy];
2636.             if (crm->typ == btyp || crm->typ == ftyp || crm->typ == SCORR) {
2637.                 dy = ddy;
2638.                 dx = 0;
2639.                 continue;
2640.             }
2641.         }
2642. 
2643.         /* continue straight on? */
2644.         crm = &levl[xx + dx][yy + dy];
2645.         if (crm->typ == btyp || crm->typ == ftyp || crm->typ == SCORR)
2646.             continue;
2647. 
2648.         /* no, what must we do now?? */
2649.         if (dx) {
2650.             dx = 0;
2651.             dy = (ty < yy) ? -1 : 1;
2652.         } else {
2653.             dy = 0;
2654.             dx = (tx < xx) ? -1 : 1;
2655.         }
2656.         crm = &levl[xx + dx][yy + dy];
2657.         if (crm->typ == btyp || crm->typ == ftyp || crm->typ == SCORR)
2658.             continue;
2659.         dy = -dy;
2660.         dx = -dx;
2661.     }
2662.     return TRUE;
2663. }
2664. 
2665. /*
2666.  * Corridors always start from a door. But it can end anywhere...
2667.  * Basically we search for door coordinates or for endpoints coordinates
2668.  * (from a distance).
2669.  */
2670. staticfn void
2671. create_corridor(corridor *c)
2672. {
2673.     coord org, dest;
2674. 
2675.     if (c->src.room == -1) {
2676.         makecorridors(); /*makecorridors(c->src.door);*/
2677.         return;
2678.     }
2679. 
2680.     /* Safety railings - if there's ever a case where des.corridor() needs
2681.      * to be called with src/destwall="random", that logic first needs to be
2682.      * implemented in search_door. */
2683.     if (c->src.wall == W_ANY || c->src.wall == W_RANDOM
2684.         || c->dest.wall == W_ANY || c->dest.wall == W_RANDOM) {
2685.         impossible("create_corridor to/from a random wall");
2686.         return;
2687.     }
2688.     if (!search_door(&svr.rooms[c->src.room], &org.x, &org.y, c->src.wall,
2689.                      c->src.door))
2690.         return;
2691.     if (c->dest.room != -1) {
2692.         if (!search_door(&svr.rooms[c->dest.room],
2693.                          &dest.x, &dest.y, c->dest.wall, c->dest.door))
2694.             return;
2695.         switch (c->src.wall) {
2696.         case W_NORTH:
2697.             org.y--;
2698.             break;
2699.         case W_SOUTH:
2700.             org.y++;
2701.             break;
2702.         case W_WEST:
2703.             org.x--;
2704.             break;
2705.         case W_EAST:
2706.             org.x++;
2707.             break;
2708.         }
2709.         switch (c->dest.wall) {
2710.         case W_NORTH:
2711.             dest.y--;
2712.             break;
2713.         case W_SOUTH:
2714.             dest.y++;
2715.             break;
2716.         case W_WEST:
2717.             dest.x--;
2718.             break;
2719.         case W_EAST:
2720.             dest.x++;
2721.             break;
2722.         }
2723.         (void) dig_corridor(&org, &dest, NULL, FALSE, CORR, STONE);
2724.     }
2725. }
2726. 
2727. /*
2728.  * Fill a room (shop, zoo, etc...) with appropriate stuff.
2729.  */
2730. void
2731. fill_special_room(struct mkroom *croom)
2732. {
2733.     int i;
2734. 
2735.     if (!croom)
2736.         return;
2737. 
2738.     /* First recurse into subrooms. We don't want to block an ordinary room
2739.      * with a special subroom from having the subroom filled, or an unfilled
2740.      * outer room preventing a special subroom from being filled. */
2741.     for (i = 0; i < croom->nsubrooms; ++i) {
2742.         fill_special_room(croom->sbrooms[i]);
2743.     }
2744. 
2745.     if (croom->rtype == OROOM || croom->rtype == THEMEROOM
2746.         || croom->needfill == FILL_NONE)
2747.         return;
2748. 
2749.     if (croom->needfill == FILL_NORMAL) {
2750.         int x, y;
2751. 
2752.         /* Shop ? */
2753.         if (croom->rtype >= SHOPBASE) {
2754.             stock_room(croom->rtype - SHOPBASE, croom);
2755.             svl.level.flags.has_shop = TRUE;
2756.             return;
2757.         }
2758. 
2759.         switch (croom->rtype) {
2760.         case VAULT:
2761.             for (x = croom->lx; x <= croom->hx; x++)
2762.                 for (y = croom->ly; y <= croom->hy; y++)
2763.                     (void) mkgold((long) rn1(abs(depth(&u.uz)) * 100, 51),
2764.                                   x, y);
2765.             break;
2766.         case COURT:
2767.         case ZOO:
2768.         case BEEHIVE:
2769.         case ANTHOLE:
2770.         case COCKNEST:
2771.         case LEPREHALL:
2772.         case MORGUE:
2773.         case BARRACKS:
2774.             fill_zoo(croom);
2775.             break;
2776.         }
2777.     }
2778.     switch (croom->rtype) {
2779.     case VAULT:
2780.         svl.level.flags.has_vault = TRUE;
2781.         break;
2782.     case ZOO:
2783.         svl.level.flags.has_zoo = TRUE;
2784.         break;
2785.     case COURT:
2786.         svl.level.flags.has_court = TRUE;
2787.         break;
2788.     case MORGUE:
2789.         svl.level.flags.has_morgue = TRUE;
2790.         break;
2791.     case BEEHIVE:
2792.         svl.level.flags.has_beehive = TRUE;
2793.         break;
2794.     case BARRACKS:
2795.         svl.level.flags.has_barracks = TRUE;
2796.         break;
2797.     case TEMPLE:
2798.         svl.level.flags.has_temple = TRUE;
2799.         break;
2800.     case SWAMP:
2801.         svl.level.flags.has_swamp = TRUE;
2802.         break;
2803.     }
2804. }
2805. 
2806. staticfn struct mkroom *
2807. build_room(room *r, struct mkroom *mkr)
2808. {
2809.     boolean okroom;
2810.     struct mkroom *aroom;
2811.     xint16 rtype = (!r->chance || rn2(100) < r->chance) ? r->rtype : OROOM;
2812. 
2813.     if (mkr) {
2814.         aroom = &gs.subrooms[gn.nsubroom];
2815.         okroom = create_subroom(mkr, r->x, r->y, r->w, r->h, rtype, r->rlit);
2816.     } else {
2817.         aroom = &svr.rooms[svn.nroom];
2818.         okroom = create_room(r->x, r->y, r->w, r->h, r->xalign, r->yalign,
2819.                              rtype, r->rlit);
2820.     }
2821. 
2822.     if (okroom) {
2823. #ifdef SPECIALIZATION
2824.         topologize(aroom, FALSE); /* set roomno */
2825. #else
2826.         topologize(aroom); /* set roomno */
2827. #endif
2828.         aroom->needfill = r->needfill;
2829.         aroom->needjoining = r->joined;
2830.         return aroom;
2831.     }
2832.     return (struct mkroom *) 0;
2833. }
2834. 
2835. /*
2836.  * set lighting in a region that will not become a room.
2837.  */
2838. staticfn void
2839. light_region(region *tmpregion)
2840. {
2841.     boolean litstate = tmpregion->rlit ? 1 : 0;
2842.     int hiy = tmpregion->y2;
2843.     int x, y;
2844.     struct rm *lev;
2845.     int lowy = tmpregion->y1;
2846.     int lowx = tmpregion->x1, hix = tmpregion->x2;
2847. 
2848.     if (litstate) {
2849.         /* adjust region size for walls, but only if lighted */
2850.         lowx = max(lowx - 1, 1);
2851.         hix = min(hix + 1, COLNO - 1);
2852.         lowy = max(lowy - 1, 0);
2853.         hiy = min(hiy + 1, ROWNO - 1);
2854.     }
2855.     for (x = lowx; x <= hix; x++) {
2856.         lev = &levl[x][lowy];
2857.         for (y = lowy; y <= hiy; y++) {
2858.             lev->lit = IS_LAVA(lev->typ) ? 1 : litstate;
2859.             lev++;
2860.         }
2861.     }
2862. }
2863. 
2864. void
2865. wallify_map(coordxy x1, coordxy y1, coordxy x2, coordxy y2)
2866. {
2867.     coordxy x, y, xx, yy, lo_xx, lo_yy, hi_xx, hi_yy;
2868. 
2869.     y1 = max(y1, 0);
2870.     x1 = max(x1, 1);
2871.     y2 = min(y2, ROWNO - 1);
2872.     x2 = min(x2, COLNO - 1);
2873.     for (y = y1; y <= y2; y++) {
2874.         lo_yy = (y > 0) ? y - 1 : 0;
2875.         hi_yy = (y < y2) ? y + 1 : y2;
2876.         for (x = x1; x <= x2; x++) {
2877.             if (levl[x][y].typ != STONE)
2878.                 continue;
2879.             lo_xx = (x > 1) ? x - 1 : 1;
2880.             hi_xx = (x < x2) ? x + 1 : x2;
2881.             for (yy = lo_yy; yy <= hi_yy; yy++)
2882.                 for (xx = lo_xx; xx <= hi_xx; xx++)
2883.                     if (IS_ROOM(levl[xx][yy].typ)
2884.                         || levl[xx][yy].typ == CROSSWALL) {
2885.                         levl[x][y].typ = (yy != y) ? HWALL : VWALL;
2886.                         yy = hi_yy; /* end `yy' loop */
2887.                         break;      /* end `xx' loop */
2888.                     }
2889.         }
2890.     }
2891. }
2892. 
2893. /*
2894.  * Select a random coordinate in the maze.
2895.  *
2896.  * We want a place not 'touched' by the loader.  That is, a place in
2897.  * the maze outside every part of the special level.
2898.  */
2899. staticfn void
2900. maze1xy(coord *m, int humidity)
2901. {
2902.     int x, y, tryct = 2000;
2903.     /* tryct:  normally it won't take more than ten or so tries due
2904.        to the circumstances under which we'll be called, but the
2905.        `humidity' screening might drastically change the chances */
2906. 
2907.     do {
2908.         x = rn1(gx.x_maze_max - 3, 3);
2909.         y = rn1(gy.y_maze_max - 3, 3);
2910.         if (--tryct < 0)
2911.             break; /* give up */
2912.     } while (!(x % 2) || !(y % 2) || SpLev_Map[x][y]
2913.              || !is_ok_location((coordxy) x, (coordxy) y, humidity));
2914. 
2915.     m->x = (coordxy) x, m->y = (coordxy) y;
2916. }
2917. 
2918. /*
2919.  * If there's a significant portion of maze unused by the special level,
2920.  * we don't want it empty.
2921.  *
2922.  * Makes the number of traps, monsters, etc. proportional
2923.  * to the size of the maze.
2924.  */
2925. staticfn void
2926. fill_empty_maze(void)
2927. {
2928.     int mapcountmax, mapcount, mapfact;
2929.     coordxy x, y;
2930.     coord mm;
2931. 
2932.     mapcountmax = mapcount = (gx.x_maze_max - 2) * (gy.y_maze_max - 2);
2933.     mapcountmax = mapcountmax / 2;
2934. 
2935.     for (x = 2; x < gx.x_maze_max; x++)
2936.         for (y = 0; y < gy.y_maze_max; y++)
2937.             if (SpLev_Map[x][y])
2938.                 mapcount--;
2939. 
2940.     if ((mapcount > (int) (mapcountmax / 10))) {
2941.         mapfact = (int) ((mapcount * 100L) / mapcountmax);
2942.         for (x = rnd((int) (20 * mapfact) / 100); x; x--) {
2943.             maze1xy(&mm, DRY);
2944.             (void) mkobj_at(rn2(2) ? GEM_CLASS : RANDOM_CLASS, mm.x, mm.y,
2945.                             TRUE);
2946.         }
2947.         for (x = rnd((int) (12 * mapfact) / 100); x; x--) {
2948.             struct trap *ttmp;
2949. 
2950.             maze1xy(&mm, DRY);
2951.             if ((ttmp = t_at(mm.x, mm.y)) != 0
2952.                 && (is_pit(ttmp->ttyp) || is_hole(ttmp->ttyp)))
2953.                 continue;
2954.             (void) mksobj_at(BOULDER, mm.x, mm.y, TRUE, FALSE);
2955.         }
2956.         for (x = rn2(2); x; x--) {
2957.             maze1xy(&mm, DRY);
2958.             (void) makemon(&mons[PM_MINOTAUR], mm.x, mm.y, NO_MM_FLAGS);
2959.         }
2960.         for (x = rnd((int) (12 * mapfact) / 100); x; x--) {
2961.             maze1xy(&mm, DRY);
2962.             (void) makemon((struct permonst *) 0, mm.x, mm.y, NO_MM_FLAGS);
2963.         }
2964.         for (x = rn2((int) (15 * mapfact) / 100); x; x--) {
2965.             maze1xy(&mm, DRY);
2966.             (void) mkgold(0L, mm.x, mm.y);
2967.         }
2968.         for (x = rn2((int) (15 * mapfact) / 100); x; x--) {
2969.             int trytrap;
2970. 
2971.             maze1xy(&mm, DRY);
2972.             trytrap = rndtrap();
2973.             if (sobj_at(BOULDER, mm.x, mm.y))
2974.                 while (is_pit(trytrap) || is_hole(trytrap))
2975.                     trytrap = rndtrap();
2976.             (void) maketrap(mm.x, mm.y, trytrap);
2977.         }
2978.     }
2979. }
2980. 
2981. staticfn void
2982. splev_initlev(lev_init *linit)
2983. {
2984.     switch (linit->init_style) {
2985.     default:
2986.         impossible("Unrecognized level init style.");
2987.         break;
2988.     case LVLINIT_NONE:
2989.         break;
2990.     case LVLINIT_SOLIDFILL:
2991.         if (linit->lit == BOOL_RANDOM)
2992.             linit->lit = rn2(2);
2993.         lvlfill_solid(linit->filling, linit->lit);
2994.         break;
2995.     case LVLINIT_MAZEGRID:
2996.         lvlfill_maze_grid(2, 0, gx.x_maze_max, gy.y_maze_max, linit->bg);
2997.         break;
2998.     case LVLINIT_MAZE:
2999.         create_maze(linit->corrwid, linit->wallthick, linit->rm_deadends);
3000.         break;
3001.     case LVLINIT_ROGUE:
3002.         makeroguerooms();
3003.         break;
3004.     case LVLINIT_MINES:
3005.         if (linit->lit == BOOL_RANDOM)
3006.             linit->lit = rn2(2);
3007.         if (linit->filling > -1)
3008.             lvlfill_solid(linit->filling, 0);
3009.         linit->icedpools = icedpools;
3010.         mkmap(linit);
3011.         break;
3012.     case LVLINIT_SWAMP:
3013.         if (linit->lit == BOOL_RANDOM)
3014.             linit->lit = rn2(2);
3015.         lvlfill_swamp(linit->fg, linit->bg, linit->lit);
3016.         break;
3017.     }
3018. }
3019. 
3020. #if 0
3021. staticfn long
3022. sp_code_jmpaddr(long curpos, long jmpaddr)
3023. {
3024.     return (curpos + jmpaddr);
3025. }
3026. #endif
3027. 
3028. 
3029. /*ARGUSED*/
3030. staticfn void
3031. spo_end_moninvent(void)
3032. {
3033.     if (invent_carrying_monster)
3034.         m_dowear(invent_carrying_monster, TRUE);
3035.     invent_carrying_monster = NULL;
3036. }
3037. 
3038. /*ARGUSED*/
3039. staticfn void
3040. spo_pop_container(void)
3041. {
3042.     if (container_idx > 0) {
3043.         container_idx--;
3044.         container_obj[container_idx] = NULL;
3045.     }
3046. }
3047. 
3048. /* push a table on lua stack: {width=wid, height=hei} */
3049. staticfn void
3050. l_push_wid_hei_table(lua_State *L, int wid, int hei)
3051. {
3052.     lua_newtable(L);
3053.     nhl_add_table_entry_int(L, "width", wid);
3054.     nhl_add_table_entry_int(L, "height", hei);
3055. }
3056. 
3057. /* push a table on lua stack containing room data */
3058. staticfn void
3059. l_push_mkroom_table(lua_State *L, struct mkroom *tmpr)
3060. {
3061.     lua_newtable(L);
3062.     nhl_add_table_entry_int(L, "width", 1 + (tmpr->hx - tmpr->lx));
3063.     nhl_add_table_entry_int(L, "height", 1 + (tmpr->hy - tmpr->ly));
3064.     nhl_add_table_entry_region(L, "region", tmpr->lx, tmpr->ly,
3065.                                tmpr->hx, tmpr->hy);
3066.     nhl_add_table_entry_bool(L, "lit", (boolean) tmpr->rlit);
3067.     nhl_add_table_entry_bool(L, "irregular", tmpr->irregular);
3068.     nhl_add_table_entry_bool(L, "needjoining", tmpr->needjoining);
3069.     nhl_add_table_entry_str(L, "type", get_mkroom_name(tmpr->rtype));
3070. }
3071. 
3072. DISABLE_WARNING_UNREACHABLE_CODE
3073. 
3074. /* message("What a strange feeling!"); */
3075. int
3076. lspo_message(lua_State *L)
3077. {
3078.     char *levmsg;
3079.     int old_n, n;
3080.     const char *msg;
3081. 
3082.     int argc = lua_gettop(L);
3083. 
3084.     if (argc < 1) {
3085.         nhl_error(L, "Wrong parameters");
3086.         /*NOTREACHED*/
3087.         return 0;
3088.     }
3089. 
3090.     create_des_coder();
3091. 
3092.     msg = luaL_checkstring(L, 1);
3093. 
3094.     old_n = gl.lev_message ? (Strlen(gl.lev_message) + 1) : 0;
3095.     n = Strlen(msg);
3096. 
3097.     levmsg = (char *) alloc(old_n + n + 1);
3098.     if (old_n)
3099.         levmsg[old_n - 1] = '\n';
3100.     if (gl.lev_message)
3101.         (void) memcpy((genericptr_t) levmsg, (genericptr_t) gl.lev_message,
3102.                       old_n - 1);
3103.     (void) memcpy((genericptr_t) &levmsg[old_n], msg, n);
3104.     levmsg[old_n + n] = '\0';
3105.     Free(gl.lev_message);
3106.     gl.lev_message = levmsg;
3107. 
3108.     return 0;  /* number of results */
3109. }
3110. 
3111. RESTORE_WARNING_UNREACHABLE_CODE
3112. 
3113. staticfn int
3114. get_table_align(lua_State *L)
3115. {
3116.     static const char *const gtaligns[] = {
3117.         "noalign", "law", "neutral", "chaos",
3118.         "coaligned", "noncoaligned", "random", NULL
3119.     };
3120.     static const int aligns2i[] = {
3121.         AM_NONE, AM_LAWFUL, AM_NEUTRAL, AM_CHAOTIC,
3122.         AM_SPLEV_CO, AM_SPLEV_NONCO, AM_SPLEV_RANDOM, 0
3123.     };
3124. 
3125.     int a = aligns2i[get_table_option(L, "align", "random", gtaligns)];
3126. 
3127.     return a;
3128. }
3129. 
3130. staticfn int
3131. get_table_monclass(lua_State *L)
3132. {
3133.     char *s = get_table_str_opt(L, "class", NULL);
3134.     int ret = -1;
3135. 
3136.     if (s && strlen(s) == 1)
3137.         ret = (int) *s;
3138.     Free(s);
3139.     return ret;
3140. }
3141. 
3142. staticfn int
3143. find_montype(
3144.     lua_State *L UNUSED,
3145.     const char *s,
3146.     int *mgender)
3147. {
3148.     int i, mgend = NEUTRAL;
3149. 
3150.     i = name_to_monplus(s, (const char **) 0, &mgend);
3151.     if (i >= LOW_PM && i < NUMMONS) {
3152.         if (is_male(&mons[i]) || is_female(&mons[i]))
3153.             mgend = is_female(&mons[i]) ? FEMALE : MALE;
3154.         else
3155.             mgend = (mgend == FEMALE) ? FEMALE
3156.                         : (mgend == MALE) ? MALE : rn2(2);
3157.         if (mgender)
3158.             *mgender = mgend;
3159.         return i;
3160.     }
3161.     if (mgender)
3162.         *mgender = NEUTRAL;
3163.     return NON_PM;
3164. }
3165. 
3166. staticfn int
3167. get_table_montype(lua_State *L, int *mgender)
3168. {
3169.     char *s = get_table_str_opt(L, "id", NULL);
3170.     int ret = NON_PM;
3171. 
3172.     if (s) {
3173.         ret = find_montype(L, s, mgender);
3174.         Free(s);
3175.         if (ret == NON_PM)
3176.             nhl_error(L, "Unknown monster id");
3177.     }
3178.     return ret;
3179. }
3180. 
3181. /* Get x and y values from a table (which the caller has already checked for
3182.  * the existence of), handling both a table with x= and y= specified and a
3183.  * table with coord= specified.
3184.  * Returns absolute rather than map-relative coordinates; the caller of this
3185.  * function must decide if it wants to interpret the coordinates as
3186.  * map-relative and adjust accordingly. */
3187. staticfn void
3188. get_table_xy_or_coord(
3189.     lua_State *L,
3190.     lua_Integer *x,
3191.     lua_Integer *y)
3192. {
3193.     lua_Integer mx = get_table_int_opt(L, "x", -1);
3194.     lua_Integer my = get_table_int_opt(L, "y", -1);
3195. 
3196.     if (mx == -1 && my == -1) {
3197.         lua_getfield(L, 1, "coord");
3198.         (void) get_coord(L, -1, &mx, &my);
3199.         lua_pop(L, 1);
3200.     }
3201. 
3202.     *x = mx;
3203.     *y = my;
3204. }
3205. 
3206. /* monster(); */
3207. /* monster("wood nymph"); */
3208. /* monster("D"); */
3209. /* monster("giant eel",11,06); */
3210. /* monster("hill giant", {08,06}); */
3211. /* monster({ id = "giant mimic", appear_as = "obj:boulder" }); */
3212. /* monster({ class = "H", peaceful = 0 }); */
3213. int
3214. lspo_monster(lua_State *L)
3215. {
3216.     int argc = lua_gettop(L);
3217.     monster tmpmons;
3218.     lua_Integer mx = -1, my = -1;
3219.     int mgend = NEUTRAL;
3220.     char *mappear = NULL;
3221. 
3222.     create_des_coder();
3223. 
3224.     tmpmons.peaceful = -1;
3225.     tmpmons.asleep = -1;
3226.     tmpmons.name.str = NULL;
3227.     tmpmons.appear = 0;
3228.     tmpmons.appear_as.str = (char *) 0;
3229.     tmpmons.sp_amask = AM_SPLEV_RANDOM;
3230.     tmpmons.female = 0;
3231.     tmpmons.invis = 0;
3232.     tmpmons.cancelled = 0;
3233.     tmpmons.revived = 0;
3234.     tmpmons.avenge = 0;
3235.     tmpmons.fleeing = 0;
3236.     tmpmons.blinded = 0;
3237.     tmpmons.paralyzed = 0;
3238.     tmpmons.stunned = 0;
3239.     tmpmons.confused = 0;
3240.     tmpmons.seentraps = 0;
3241.     tmpmons.has_invent = DEFAULT_INVENT;
3242.     tmpmons.waiting = 0;
3243.     tmpmons.mm_flags = NO_MM_FLAGS;
3244.     tmpmons.m_lev_adj = 0;
3245. 
3246.     if (argc == 1 && lua_type(L, 1) == LUA_TSTRING) {
3247.         const char *paramstr = luaL_checkstring(L, 1);
3248. 
3249.         if (strlen(paramstr) == 1) {
3250.             tmpmons.class = *paramstr;
3251.             tmpmons.id = NON_PM;
3252.         } else {
3253.             tmpmons.class = -1;
3254.             tmpmons.id = find_montype(L, paramstr, &mgend);
3255.             tmpmons.female = (mgend == FEMALE) ? FEMALE
3256.                                 : (mgend == MALE) ? MALE : rn2(2);
3257.         }
3258.     } else if (argc == 2 && lua_type(L, 1) == LUA_TSTRING
3259.                && lua_type(L, 2) == LUA_TTABLE) {
3260.         const char *paramstr = luaL_checkstring(L, 1);
3261. 
3262.         (void) get_coord(L, 2, &mx, &my);
3263. 
3264.         if (strlen(paramstr) == 1) {
3265.             tmpmons.class = *paramstr;
3266.             tmpmons.id = NON_PM;
3267.         } else {
3268.             tmpmons.class = -1;
3269.             tmpmons.id = find_montype(L, paramstr, &mgend);
3270.             tmpmons.female = (mgend == FEMALE) ? FEMALE
3271.                                 : (mgend == MALE) ? MALE : rn2(2);
3272.         }
3273. 
3274.     } else if (argc == 3) {
3275.         const char *paramstr = luaL_checkstring(L, 1);
3276. 
3277.         mx = luaL_checkinteger(L, 2);
3278.         my = luaL_checkinteger(L, 3);
3279. 
3280.         if (strlen(paramstr) == 1) {
3281.             tmpmons.class = *paramstr;
3282.             tmpmons.id = NON_PM;
3283.         } else {
3284.             tmpmons.class = -1;
3285.             tmpmons.id = find_montype(L, paramstr, &mgend);
3286.             tmpmons.female = (mgend == FEMALE) ? FEMALE
3287.                                 : (mgend == MALE) ? MALE : rn2(2);
3288.         }
3289.     } else {
3290.         int keep_default_invent = -1; /* -1 = unspecified */
3291.         lcheck_param_table(L);
3292. 
3293.         tmpmons.peaceful = get_table_boolean_opt(L, "peaceful", BOOL_RANDOM);
3294.         tmpmons.asleep = get_table_boolean_opt(L, "asleep", BOOL_RANDOM);
3295.         tmpmons.name.str = get_table_str_opt(L, "name", NULL);
3296.         tmpmons.appear = 0;
3297.         tmpmons.appear_as.str = (char *) 0;
3298.         tmpmons.sp_amask = get_table_align(L);
3299.         tmpmons.female = get_table_boolean_opt(L, "female", BOOL_RANDOM);
3300.         tmpmons.invis = get_table_boolean_opt(L, "invisible", FALSE);
3301.         tmpmons.cancelled = get_table_boolean_opt(L, "cancelled", FALSE);
3302.         tmpmons.revived = get_table_boolean_opt(L, "revived", FALSE);
3303.         tmpmons.avenge = get_table_boolean_opt(L, "avenge", FALSE);
3304.         tmpmons.fleeing = get_table_int_opt(L, "fleeing", 0);
3305.         tmpmons.blinded = get_table_int_opt(L, "blinded", 0);
3306.         tmpmons.paralyzed = get_table_int_opt(L, "paralyzed", 0);
3307.         tmpmons.stunned = get_table_boolean_opt(L, "stunned", FALSE);
3308.         tmpmons.confused = get_table_boolean_opt(L, "confused", FALSE);
3309.         tmpmons.waiting = get_table_boolean_opt(L, "waiting", FALSE);
3310.         tmpmons.m_lev_adj = get_table_int_opt(L, "m_lev_adj", 0);
3311.         tmpmons.seentraps = 0; /* TODO: list of trap names to bitfield */
3312.         keep_default_invent =
3313.             get_table_boolean_opt(L, "keep_default_invent", -1);
3314. 
3315.         if (!get_table_boolean_opt(L, "tail", TRUE))
3316.             tmpmons.mm_flags |= MM_NOTAIL;
3317.         if (!get_table_boolean_opt(L, "group", TRUE))
3318.             tmpmons.mm_flags |= MM_NOGRP;
3319.         if (get_table_boolean_opt(L, "adjacentok", FALSE))
3320.             tmpmons.mm_flags |= MM_ADJACENTOK;
3321.         if (get_table_boolean_opt(L, "ignorewater", FALSE))
3322.             tmpmons.mm_flags |= MM_IGNOREWATER;
3323.         if (!get_table_boolean_opt(L, "countbirth", TRUE))
3324.             tmpmons.mm_flags |= MM_NOCOUNTBIRTH;
3325. 
3326.         mappear = get_table_str_opt(L, "appear_as", NULL);
3327.         if (mappear) {
3328.             if (!strncmp("obj:", mappear, 4)) {
3329.                 tmpmons.appear = M_AP_OBJECT;
3330.             } else if (!strncmp("mon:", mappear, 4)) {
3331.                 tmpmons.appear = M_AP_MONSTER;
3332.             } else if (!strncmp("ter:", mappear, 4)) {
3333.                 tmpmons.appear = M_AP_FURNITURE;
3334.             } else {
3335.                 nhl_error(L, "Unknown appear_as type");
3336.             }
3337.             tmpmons.appear_as.str = dupstr(&mappear[4]);
3338.             Free(mappear);
3339.         }
3340. 
3341.         get_table_xy_or_coord(L, &mx, &my);
3342. 
3343.         tmpmons.id = get_table_montype(L, &mgend);
3344.         /* get_table_montype will return a random gender if the species isn't
3345.          * all-male or all-female; if the level designer specified a certain
3346.          * gender, override that random one now, unless it *is* a one-gender
3347.          * species, in which case don't override (don't permit creation of a
3348.          * male nymph or female Nazgul, etc.) */
3349.         if (mgend != NEUTRAL
3350.             && (tmpmons.female == BOOL_RANDOM || is_female(&mons[tmpmons.id])
3351.                 || is_male(&mons[tmpmons.id])))
3352.             tmpmons.female = mgend;
3353.         /* safety net - if find_montype did not find a gender for this species
3354.          * (should cause a lua error anyway) */
3355.         if (tmpmons.female == BOOL_RANDOM)
3356.             tmpmons.female = 0;
3357. 
3358.         tmpmons.class = get_table_monclass(L);
3359. 
3360.         lua_getfield(L, 1, "inventory");
3361.         if (!lua_isnil(L, -1)) {
3362.             /* overwrite DEFAULT_INVENT - most times inventory is specified,
3363.              * the monster should not get its species' default inventory. Only
3364.              * provide it if explicitly requested. */
3365.             tmpmons.has_invent = CUSTOM_INVENT;
3366.             if (keep_default_invent == TRUE)
3367.                 tmpmons.has_invent |= DEFAULT_INVENT;
3368.         }
3369.         else {
3370.             /* if keep_default_invent was not specified (-1), keep has_invent as
3371.              * DEFAULT_INVENT and provide the species' default inventory.
3372.              * But if it was explicitly set to false, provide *no* inventory. */
3373.             if (keep_default_invent == FALSE)
3374.                 tmpmons.has_invent = NO_INVENT;
3375.         }
3376.     }
3377. 
3378.     if (mx == -1 && my == -1)
3379.         tmpmons.coord = SP_COORD_PACK_RANDOM(0);
3380.     else
3381.         tmpmons.coord = SP_COORD_PACK(mx, my);
3382. 
3383.     if (tmpmons.id != NON_PM && tmpmons.class == -1)
3384.         tmpmons.class = monsym(&mons[tmpmons.id]);
3385. 
3386.     create_monster(&tmpmons, gc.coder->croom);
3387. 
3388.     if ((tmpmons.has_invent & CUSTOM_INVENT)
3389.         && lua_type(L, -1) == LUA_TFUNCTION) {
3390.         lua_remove(L, -2);
3391.         nhl_pcall_handle(L, 0, 0, "lspo_monster", NHLpa_panic);
3392.         spo_end_moninvent();
3393.     } else
3394.         lua_pop(L, 1);
3395. 
3396.     Free(tmpmons.name.str);
3397.     Free(tmpmons.appear_as.str);
3398. 
3399.     return 0;
3400. }
3401. 
3402. DISABLE_WARNING_UNREACHABLE_CODE
3403. 
3404. /* the hash key 'name' is an integer or "random",
3405.    or if not existent, also return rndval */
3406. staticfn lua_Integer
3407. get_table_int_or_random(lua_State *L, const char *name, int rndval)
3408. {
3409.     lua_Integer ret;
3410.     char buf[BUFSZ];
3411. 
3412.     lua_getfield(L, 1, name);
3413.     if (lua_type(L, -1) == LUA_TNIL) {
3414.         lua_pop(L, 1);
3415.         return rndval;
3416.     }
3417.     if (!lua_isnumber(L, -1)) {
3418.         const char *tmp = lua_tostring(L, -1);
3419. 
3420.         if (tmp && !strcmpi("random", tmp)) {
3421.             lua_pop(L, 1);
3422.             return rndval;
3423.         }
3424.         Sprintf(buf, "Expected integer or \"random\" for \"%s\", got ", name);
3425.         if (tmp)
3426.             Sprintf(eos(buf), "\"%s\"", tmp);
3427.         else
3428.             Strcat(buf, "<Null>");
3429.         nhl_error(L, buf);
3430.         /*NOTREACHED*/
3431.         lua_pop(L, 1);
3432.         return 0;
3433.     }
3434.     ret = luaL_optinteger(L, -1, rndval);
3435.     lua_pop(L, 1);
3436.     return ret;
3437. }
3438. 
3439. RESTORE_WARNING_UNREACHABLE_CODE
3440. 
3441. staticfn int
3442. get_table_buc(lua_State *L)
3443. {
3444.     static const char *const bucs[] = {
3445.         "random", "blessed", "uncursed", "cursed",
3446.         "not-cursed", "not-uncursed", "not-blessed", NULL,
3447.     };
3448.     static const int bucs2i[] = { 0, 1, 2, 3, 4, 5, 6, 0 };
3449.     int curse_state = bucs2i[get_table_option(L, "buc", "random", bucs)];
3450. 
3451.     return curse_state;
3452. }
3453. 
3454. int
3455. get_table_objclass(lua_State *L)
3456. {
3457.     char *s = get_table_str_opt(L, "class", NULL);
3458.     int ret = -1;
3459. 
3460.     if (s && strlen(s) == 1)
3461.         ret = (int) *s;
3462.     Free(s);
3463.     return ret;
3464. }
3465. 
3466. /* find object otyp by text s (optionally considering oclass) */
3467. staticfn int
3468. find_objtype(lua_State *L, const char *s, char oclass)
3469. {
3470.     if (s && *s) {
3471.         int i;
3472.         const char *objname;
3473.         char class = def_char_to_objclass(oclass);
3474. 
3475.         /* In objects.h, some item classes are defined without prefixes
3476.            (such as "scroll of ") in their names, making some names (such
3477.            as "teleportation") ambiguous.  Get the object class if it is
3478.            specified, and only return an object of the matching class. */
3479.         static struct objclasspfx {
3480.             const char *prefix;
3481.             char class;
3482.         } class_prefixes[] = {
3483.             { "ring of ", RING_CLASS },
3484.             { "potion of ", POTION_CLASS },
3485.             { "scroll of ", SCROLL_CLASS },
3486.             { "spellbook of ", SPBOOK_CLASS },
3487.             { "wand of ", WAND_CLASS },
3488.             { NULL, 0 }
3489.         };
3490. 
3491.         if (class == MAXOCLASSES)
3492.             class = 0;
3493. 
3494.         if (strstri(s, " of ")) {
3495.             for (i = 0; class_prefixes[i].prefix; i++) {
3496.                 const char *p = class_prefixes[i].prefix;
3497. 
3498.                 if (!strncmpi(s, p, strlen(p))) {
3499.                     class = class_prefixes[i].class;
3500.                     s = s + strlen(p);
3501.                     break;
3502.                 }
3503.             }
3504.         }
3505. 
3506.         /* find by object name */
3507.         for (i = 0; i < NUM_OBJECTS; i++) {
3508.             objname = OBJ_NAME(objects[i]);
3509.             if ((!class || class == objects[i].oc_class)
3510.                 && objname && !strcmpi(s, objname))
3511.                 return i;
3512.         }
3513. 
3514.         /*
3515.          * FIXME:
3516.          *  If the file specifies "orange potion", the actual object
3517.          *  description is just "orange" and won't match.  [There's a
3518.          *  reason that wish handling is insanely complicated.]  And
3519.          *  even if that gets fixed, if the file specifies "gray stone"
3520.          *  it will start matching but would always pick the first one.
3521.          *
3522.          *  "orange potion" is an unlikely thing to have in a special
3523.          *  level description but "gray stone" is not....
3524.          */
3525. 
3526.         /* find by object description */
3527.         for (i = 0; i < NUM_OBJECTS; i++) {
3528.             objname = OBJ_DESCR(objects[i]);
3529.             if (objname && !strcmpi(s, objname))
3530.                 return i;
3531.         }
3532. 
3533.         nhl_error(L, "Unknown object id");
3534.     }
3535.     return STRANGE_OBJECT;
3536. }
3537. 
3538. int
3539. get_table_objtype(lua_State *L)
3540. {
3541.     char *s = get_table_str_opt(L, "id", NULL);
3542.     char oclass = get_table_objclass(L);
3543.     int ret = find_objtype(L, s, oclass);
3544. 
3545.     Free(s);
3546.     return ret;
3547. }
3548. 
3549. /* object(); */
3550. /* object("sack"); */
3551. /* object("scimitar", 6,7); */
3552. /* object("scimitar", {6,7}); */
3553. /* object({ class = "%" }); */
3554. /* object({ id = "boulder", x = 03, y = 12}); */
3555. /* object({ id = "boulder", coord = {03,12} }); */
3556. int
3557. lspo_object(lua_State *L)
3558. {
3559.     static object zeroobject = {
3560.             { 0 },   /* Str_or_len name */
3561.             0,       /* corpsenm */
3562.             0, 0,    /* id, spe */
3563.             0,       /* coord */
3564.             0, 0,    /* coordxy x,y */
3565.             0, 0,    /* class, containment */
3566.             0,       /* curse_state */
3567.             0,       /* quan */
3568.             0,       /* buried */
3569.             0,       /* lit */
3570.             0, 0, 0, 0, 0, /* eroded, locked, trapped, tknown, recharged */
3571.             0, 0, 0, 0, /* invis, greased, broken, achievement */
3572.     };
3573. #if 0
3574.     int nparams = 0;
3575. #endif
3576.     long quancnt;
3577.     object tmpobj;
3578.     lua_Integer ox = -1, oy = -1;
3579.     int argc = lua_gettop(L);
3580.     int maybe_contents = 0;
3581.     struct obj *otmp = NULL;
3582. 
3583.     create_des_coder();
3584. 
3585.     tmpobj = zeroobject;
3586.     tmpobj.name.str = (char *) 0;
3587.     tmpobj.spe = -127;
3588.     tmpobj.quan = -1;
3589.     tmpobj.trapped = -1;
3590.     tmpobj.tknown = -1;
3591.     tmpobj.locked = -1;
3592.     tmpobj.corpsenm = NON_PM;
3593. 
3594.     if (argc == 1 && lua_type(L, 1) == LUA_TSTRING) {
3595.         const char *paramstr = luaL_checkstring(L, 1);
3596. 
3597.         if (strlen(paramstr) == 1) {
3598.             tmpobj.class = *paramstr;
3599.             tmpobj.id = STRANGE_OBJECT;
3600.         } else {
3601.             tmpobj.class = -1;
3602.             tmpobj.id = find_objtype(L, paramstr, -1);
3603.         }
3604.     } else if (argc == 2 && lua_type(L, 1) == LUA_TSTRING
3605.                && lua_type(L, 2) == LUA_TTABLE) {
3606.         const char *paramstr = luaL_checkstring(L, 1);
3607. 
3608.         (void) get_coord(L, 2, &ox, &oy);
3609. 
3610.         if (strlen(paramstr) == 1) {
3611.             tmpobj.class = *paramstr;
3612.             tmpobj.id = STRANGE_OBJECT;
3613.         } else {
3614.             tmpobj.class = -1;
3615.             tmpobj.id = find_objtype(L, paramstr, -1);
3616.         }
3617.     } else if (argc == 3 && lua_type(L, 2) == LUA_TNUMBER
3618.                && lua_type(L, 3) == LUA_TNUMBER) {
3619.         const char *paramstr = luaL_checkstring(L, 1);
3620. 
3621.         ox = luaL_checkinteger(L, 2);
3622.         oy = luaL_checkinteger(L, 3);
3623. 
3624.         if (strlen(paramstr) == 1) {
3625.             tmpobj.class = *paramstr;
3626.             tmpobj.id = STRANGE_OBJECT;
3627.         } else {
3628.             tmpobj.class = -1;
3629.             tmpobj.id = find_objtype(L, paramstr, -1);
3630.         }
3631.     } else {
3632.         lcheck_param_table(L);
3633. 
3634.         tmpobj.spe = get_table_int_or_random(L, "spe", -127);
3635.         tmpobj.curse_state = get_table_buc(L);
3636.         tmpobj.corpsenm = NON_PM;
3637.         tmpobj.name.str = get_table_str_opt(L, "name", (char *) 0);
3638.         tmpobj.quan = get_table_int_or_random(L, "quantity", -1);
3639.         tmpobj.buried = get_table_boolean_opt(L, "buried", 0);
3640.         tmpobj.lit = get_table_boolean_opt(L, "lit", 0);
3641.         tmpobj.eroded = get_table_int_opt(L, "eroded", 0);
3642.         tmpobj.locked = get_table_boolean_opt(L, "locked", -1);
3643.         tmpobj.trapped = get_table_boolean_opt(L, "trapped", -1);
3644.         tmpobj.tknown = get_table_boolean_opt(L, "trap_known", -1);
3645.         tmpobj.recharged = get_table_int_opt(L, "recharged", 0);
3646.         tmpobj.greased = get_table_boolean_opt(L, "greased", 0);
3647.         tmpobj.broken = get_table_boolean_opt(L, "broken", 0);
3648.         tmpobj.achievement = get_table_boolean_opt(L, "achievement", 0);
3649. 
3650.         get_table_xy_or_coord(L, &ox, &oy);
3651. 
3652.         tmpobj.id = get_table_objtype(L);
3653.         tmpobj.class = get_table_objclass(L);
3654.         maybe_contents = 1;
3655.     }
3656. 
3657.     if (ox == -1 && oy == -1)
3658.         tmpobj.coord = SP_COORD_PACK_RANDOM(0);
3659.     else
3660.         tmpobj.coord = SP_COORD_PACK(ox, oy);
3661. 
3662.     if (tmpobj.class == -1 && tmpobj.id > STRANGE_OBJECT)
3663.         tmpobj.class = objects[tmpobj.id].oc_class;
3664.     else if (tmpobj.class > -1 && tmpobj.id == STRANGE_OBJECT)
3665.         tmpobj.id = -1;
3666. 
3667.     if (tmpobj.id == STATUE || tmpobj.id == EGG
3668.         || tmpobj.id == CORPSE || tmpobj.id == TIN
3669.         || tmpobj.id == FIGURINE) {
3670.         struct permonst *pm = NULL;
3671.         boolean nonpmobj = FALSE;
3672.         int i;
3673.         char *montype = get_table_str_opt(L, "montype", NULL);
3674. 
3675.         if (montype) {
3676.             if ((tmpobj.id == TIN && (!strcmpi(montype, "spinach")
3677.                 /* id="tin",montype="empty" produces an empty tin */
3678.                                       || !strcmpi(montype, "empty")))
3679.                 /* id="egg",montype="empty" produces a generic, unhatchable
3680.                    egg rather than an "empty egg" */
3681.                 || (tmpobj.id == EGG && !strcmpi(montype, "empty"))) {
3682.                 tmpobj.corpsenm = NON_PM;
3683.                 tmpobj.spe = !strcmpi(montype, "spinach") ? 1 : 0;
3684.                 nonpmobj = TRUE;
3685.             } else if (strlen(montype) == 1
3686.                        && def_char_to_monclass(*montype) != MAXMCLASSES) {
3687.                 pm = mkclass(def_char_to_monclass(*montype),
3688.                              G_NOGEN | G_IGNORE);
3689.             } else {
3690.                 for (i = LOW_PM; i < NUMMONS; i++)
3691.                     if (!strcmpi(mons[i].pmnames[NEUTRAL], montype)
3692.                         || (mons[i].pmnames[MALE] != 0
3693.                             && !strcmpi(mons[i].pmnames[MALE], montype))
3694.                         || (mons[i].pmnames[FEMALE] != 0
3695.                             && !strcmpi(mons[i].pmnames[FEMALE], montype))) {
3696.                         pm = &mons[i];
3697.                         break;
3698.                     }
3699.             }
3700.             free((genericptr_t) montype);
3701.             if (pm)
3702.                 tmpobj.corpsenm = monsndx(pm);
3703.             else if (!nonpmobj)
3704.                 nhl_error(L, "Unknown montype");
3705.         }
3706.         if (tmpobj.id == STATUE || tmpobj.id == CORPSE) {
3707.             int lflags = 0;
3708. 
3709.             if (get_table_boolean_opt(L, "historic", 0))
3710.                 lflags |= CORPSTAT_HISTORIC;
3711.             if (get_table_boolean_opt(L, "male", 0))
3712.                 lflags |= CORPSTAT_MALE;
3713.             if (get_table_boolean_opt(L, "female", 0))
3714.                 lflags |= CORPSTAT_FEMALE;
3715.             tmpobj.spe = lflags;
3716.         } else if (tmpobj.id == EGG) {
3717.             tmpobj.spe = get_table_boolean_opt(L, "laid_by_you", 0) ? 1 : 0;
3718.         } else if (!nonpmobj) { /* tmpobj.spe is already set for nonpmobj */
3719.             tmpobj.spe = 0;
3720.         }
3721.     }
3722. 
3723.     quancnt = (tmpobj.id > STRANGE_OBJECT) ? tmpobj.quan : 0;
3724. 
3725.     if (container_idx)
3726.         tmpobj.containment |= SP_OBJ_CONTENT;
3727. 
3728.     if (maybe_contents) {
3729.         lua_getfield(L, 1, "contents");
3730.         if (!lua_isnil(L, -1))
3731.             tmpobj.containment |= SP_OBJ_CONTAINER;
3732.     }
3733. 
3734.     do {
3735.         otmp = create_object(&tmpobj, gc.coder->croom);
3736.         quancnt--;
3737.     } while ((quancnt > 0) && ((tmpobj.id > STRANGE_OBJECT)
3738.                                && !objects[tmpobj.id].oc_merge));
3739. 
3740.     if (lua_type(L, -1) == LUA_TFUNCTION) {
3741.         lua_remove(L, -2);
3742.         nhl_push_obj(L, otmp);
3743.         nhl_pcall_handle(L, 1, 0, "lspo_object", NHLpa_panic);
3744.     } else
3745.         lua_pop(L, 1);
3746. 
3747.     if ((tmpobj.containment & SP_OBJ_CONTAINER) != 0)
3748.         spo_pop_container();
3749. 
3750.     Free(tmpobj.name.str);
3751. 
3752.     nhl_push_obj(L, otmp);
3753. 
3754.     return 1;
3755. }
3756. 
3757. /* level_flags("noteleport", "mazelevel", ... ); */
3758. int
3759. lspo_level_flags(lua_State *L)
3760. {
3761.     int argc = lua_gettop(L);
3762.     int i;
3763. 
3764.     create_des_coder();
3765. 
3766.     if (argc < 1)
3767.         nhl_error(L, "expected string params");
3768. 
3769.     for (i = 1; i <= argc; i++) {
3770.         const char *s = luaL_checkstring(L, i);
3771. 
3772.         if (!strcmpi(s, "noteleport"))
3773.             svl.level.flags.noteleport = 1;
3774.         else if (!strcmpi(s, "hardfloor"))
3775.             svl.level.flags.hardfloor = 1;
3776.         else if (!strcmpi(s, "nommap"))
3777.             svl.level.flags.nommap = 1;
3778.         else if (!strcmpi(s, "shortsighted"))
3779.             svl.level.flags.shortsighted = 1;
3780.         else if (!strcmpi(s, "arboreal"))
3781.             svl.level.flags.arboreal = 1;
3782.         else if (!strcmpi(s, "mazelevel"))
3783.             svl.level.flags.is_maze_lev = 1;
3784.         else if (!strcmpi(s, "shroud"))
3785.             svl.level.flags.hero_memory = 1;
3786.         else if (!strcmpi(s, "graveyard"))
3787.             svl.level.flags.graveyard = 1;
3788.         else if (!strcmpi(s, "icedpools"))
3789.             icedpools = 1;
3790.         else if (!strcmpi(s, "corrmaze"))
3791.             svl.level.flags.corrmaze = 1;
3792.         else if (!strcmpi(s, "premapped"))
3793.             gc.coder->premapped = 1;
3794.         else if (!strcmpi(s, "solidify"))
3795.             gc.coder->solidify = 1;
3796.         else if (!strcmpi(s, "sokoban"))
3797.             Sokoban = 1; /* svl.level.flags.sokoban_rules */
3798.         else if (!strcmpi(s, "inaccessibles"))
3799.             gc.coder->check_inaccessibles = 1;
3800.         else if (!strcmpi(s, "noflipx"))
3801.             gc.coder->allow_flips &= ~2;
3802.         else if (!strcmpi(s, "noflipy"))
3803.             gc.coder->allow_flips &= ~1;
3804.         else if (!strcmpi(s, "noflip"))
3805.             gc.coder->allow_flips = 0;
3806.         else if (!strcmpi(s, "temperate"))
3807.             svl.level.flags.temperature = 0;
3808.         else if (!strcmpi(s, "hot"))
3809.             svl.level.flags.temperature = 1;
3810.         else if (!strcmpi(s, "cold"))
3811.             svl.level.flags.temperature = -1;
3812.         else if (!strcmpi(s, "nomongen"))
3813.             svl.level.flags.rndmongen = 0;
3814.         else if (!strcmpi(s, "nodeathdrops"))
3815.             svl.level.flags.deathdrops = 0;
3816.         else if (!strcmpi(s, "noautosearch"))
3817.             svl.level.flags.noautosearch = 1;
3818.         else if (!strcmpi(s, "fumaroles"))
3819.             svl.level.flags.fumaroles = 1;
3820.         else if (!strcmpi(s, "stormy"))
3821.             svl.level.flags.stormy = 1;
3822.         else {
3823.             char buf[BUFSZ];
3824. 
3825.             Sprintf(buf, "Unknown level flag %s", s);
3826.             nhl_error(L, buf);
3827.         }
3828.     }
3829. 
3830.     return 0;
3831. }
3832. 
3833. /* level_init({ style = "solidfill", fg = " " }); */
3834. /* level_init({ style = "mines", fg = ".", bg = "}",
3835.                 smoothed=true, joined=true, lit=0 }) */
3836. int
3837. lspo_level_init(lua_State *L)
3838. {
3839.     static const char *const initstyles[] = {
3840.         "solidfill", "mazegrid", "maze", "rogue", "mines", "swamp", NULL
3841.     };
3842.     static const int initstyles2i[] = {
3843.         LVLINIT_SOLIDFILL, LVLINIT_MAZEGRID, LVLINIT_MAZE, LVLINIT_ROGUE,
3844.         LVLINIT_MINES, LVLINIT_SWAMP, 0
3845.     };
3846.     lev_init init_lev;
3847. 
3848.     create_des_coder();
3849. 
3850.     lcheck_param_table(L);
3851. 
3852.     splev_init_present = TRUE;
3853. 
3854.     init_lev.init_style
3855.         = initstyles2i[get_table_option(L, "style", "solidfill", initstyles)];
3856.     init_lev.fg = get_table_mapchr_opt(L, "fg", ROOM);
3857.     init_lev.bg = get_table_mapchr_opt(L, "bg", INVALID_TYPE);
3858.     init_lev.smoothed = get_table_boolean_opt(L, "smoothed", FALSE);
3859.     init_lev.joined = get_table_boolean_opt(L, "joined", FALSE);
3860.     init_lev.lit = get_table_boolean_opt(L, "lit", BOOL_RANDOM);
3861.     init_lev.walled = get_table_boolean_opt(L, "walled", FALSE);
3862.     init_lev.filling = get_table_mapchr_opt(L, "filling", init_lev.fg);
3863.     init_lev.corrwid = get_table_int_opt(L, "corrwid", -1);
3864.     init_lev.wallthick = get_table_int_opt(L, "wallthick", -1);
3865.     init_lev.rm_deadends = !get_table_boolean_opt(L, "deadends", TRUE);
3866. 
3867.     gc.coder->lvl_is_joined = init_lev.joined;
3868. 
3869.     if (init_lev.bg == INVALID_TYPE)
3870.         init_lev.bg = (init_lev.init_style == LVLINIT_SWAMP) ? MOAT : STONE;
3871. 
3872.     splev_initlev(&init_lev);
3873. 
3874.     return 0;
3875. }
3876. 
3877. /* engraving({ x = 1, y = 1, type="burn", text="Foo" }); */
3878. /* engraving({ coord={1, 1}, type="burn", text="Foo" }); */
3879. /* engraving({x,y}, "engrave", "Foo"); */
3880. int
3881. lspo_engraving(lua_State *L)
3882. {
3883.     static const char *const engrtypes[] = {
3884.         "dust", "engrave", "burn", "mark", "blood", NULL
3885.     };
3886.     static const int engrtypes2i[] = {
3887.         DUST, ENGRAVE, BURN, MARK, ENGR_BLOOD, 0
3888.     };
3889.     int etyp = DUST;
3890.     char *txt = (char *) 0;
3891.     long ecoord;
3892.     coordxy x = -1, y = -1;
3893.     int argc = lua_gettop(L);
3894.     boolean guardobjs = FALSE;
3895.     boolean wipeout = TRUE;
3896.     struct engr *ep;
3897. 
3898.     create_des_coder();
3899. 
3900.     if (argc == 1) {
3901.         lua_Integer ex, ey;
3902.         lcheck_param_table(L);
3903. 
3904.         get_table_xy_or_coord(L, &ex, &ey);
3905.         x = ex;
3906.         y = ey;
3907.         etyp = engrtypes2i[get_table_option(L, "type", "engrave", engrtypes)];
3908.         txt = get_table_str(L, "text");
3909.         wipeout = get_table_boolean_opt(L, "degrade", TRUE);
3910.         guardobjs = get_table_boolean_opt(L, "guardobjects", FALSE);
3911.     } else if (argc == 3) {
3912.         lua_Integer ex, ey;
3913.         (void) get_coord(L, 1, &ex, &ey);
3914.         x = ex;
3915.         y = ey;
3916.         etyp = engrtypes2i[luaL_checkoption(L, 2, "engrave", engrtypes)];
3917.         txt = dupstr(luaL_checkstring(L, 3));
3918.     } else {
3919.         nhl_error(L, "Wrong parameters");
3920.     }
3921. 
3922.     if (x == -1 && y == -1)
3923.         ecoord = SP_COORD_PACK_RANDOM(0);
3924.     else
3925.         ecoord = SP_COORD_PACK(x, y);
3926. 
3927.     get_location_coord(&x, &y, DRY, gc.coder->croom, ecoord);
3928.     make_engr_at(x, y, txt, NULL, 0L, etyp);
3929.     Free(txt);
3930.     ep = engr_at(x, y);
3931.     if (ep) {
3932.         ep->guardobjects = guardobjs;
3933.         ep->nowipeout = !wipeout;
3934.     }
3935.     return 0;
3936. }
3937. 
3938. int
3939. lspo_mineralize(lua_State *L)
3940. {
3941.     int gem_prob, gold_prob, kelp_moat, kelp_pool;
3942. 
3943.     create_des_coder();
3944. 
3945.     lcheck_param_table(L);
3946.     /* -1 produces default mineralize behavior */
3947.     gem_prob = get_table_int_opt(L, "gem_prob", -1);
3948.     gold_prob = get_table_int_opt(L, "gold_prob", -1);
3949.     kelp_moat = get_table_int_opt(L, "kelp_moat", -1);
3950.     kelp_pool = get_table_int_opt(L, "kelp_pool", -1);
3951. 
3952.     mineralize(kelp_pool, kelp_moat, gold_prob, gem_prob, TRUE);
3953. 
3954.     return 0;
3955. }
3956. 
3957. static const struct {
3958.     const char *name;
3959.     int type;
3960. } room_types[] = {
3961.     { "ordinary", OROOM },
3962.     { "themed", THEMEROOM },
3963.     { "throne", COURT },
3964.     { "swamp", SWAMP },
3965.     { "vault", VAULT },
3966.     { "beehive", BEEHIVE },
3967.     { "morgue", MORGUE },
3968.     { "barracks", BARRACKS },
3969.     { "zoo", ZOO },
3970.     { "delphi", DELPHI },
3971.     { "temple", TEMPLE },
3972.     { "anthole", ANTHOLE },
3973.     { "cocknest", COCKNEST },
3974.     { "leprehall", LEPREHALL },
3975.     { "shop", SHOPBASE },
3976.     { "armor shop", ARMORSHOP },
3977.     { "scroll shop", SCROLLSHOP },
3978.     { "potion shop", POTIONSHOP },
3979.     { "weapon shop", WEAPONSHOP },
3980.     { "food shop", FOODSHOP },
3981.     { "ring shop", RINGSHOP },
3982.     { "wand shop", WANDSHOP },
3983.     { "tool shop", TOOLSHOP },
3984.     { "book shop", BOOKSHOP },
3985.     { "health food shop", FODDERSHOP },
3986.     { "candle shop", CANDLESHOP },
3987.     { 0, 0 }
3988. };
3989. 
3990. staticfn const char *
3991. get_mkroom_name(int rtype)
3992. {
3993.     int i;
3994. 
3995.     for (i = 0; room_types[i].name; i++)
3996.         if (room_types[i].type == rtype)
3997.             return room_types[i].name;
3998. 
3999.     impossible("get_mkroom_name unknown rtype %d", rtype);
4000.     return "unknown"; /* not NULL */
4001. }
4002. 
4003. staticfn int
4004. get_table_roomtype_opt(lua_State *L, const char *name, int defval)
4005. {
4006.     char *roomstr = get_table_str_opt(L, name, emptystr);
4007.     int i, res = defval;
4008. 
4009.     if (roomstr && *roomstr) {
4010.         for (i = 0; room_types[i].name; i++)
4011.             if (!strcmpi(roomstr, room_types[i].name)) {
4012.                 res = room_types[i].type;
4013.                 break;
4014.             }
4015.         if (!room_types[i].name)
4016.             impossible("Unknown room type '%s'", roomstr);
4017.     }
4018.     Free(roomstr);
4019.     return res;
4020. }
4021. 
4022. /* room({ type="ordinary", lit=1, x=3,y=3, xalign="center",yalign="center",
4023.  *        w=11,h=9 }); */
4024. /* room({ lit=1, coord={3,3}, xalign="center",yalign="center", w=11,h=9 }); */
4025. /* room({ coord={3,3}, xalign="center",yalign="center", w=11,h=9,
4026.  *        contents=function(room) ... end }); */
4027. int
4028. lspo_room(lua_State *L)
4029. {
4030.     create_des_coder();
4031. 
4032.     if (gi.in_mk_themerooms && gt.themeroom_failed)
4033.         return 0;
4034. 
4035.     lcheck_param_table(L);
4036. 
4037.     if (gc.coder->n_subroom > MAX_NESTED_ROOMS) {
4038.         panic("Too deeply nested rooms?!");
4039.     } else {
4040.         static const char *const left_or_right[] = {
4041.             "left", "half-left", "center", "half-right", "right",
4042.             "none", "random", NULL
4043.         };
4044.         static const int l_or_r2i[] = {
4045.             SPLEV_LEFT, SPLEV_H_LEFT, SPLEV_CENTER, SPLEV_H_RIGHT,
4046.             SPLEV_RIGHT, -1, -1, -1
4047.         };
4048.         static const char *const top_or_bot[] = {
4049.             "top", "center", "bottom", "none", "random", NULL
4050.         };
4051.         static const int t_or_b2i[] = { TOP, SPLEV_CENTER, BOTTOM,
4052.                                         -1, -1, -1 };
4053.         room tmproom;
4054.         struct mkroom *tmpcr;
4055.         lua_Integer rx, ry;
4056. 
4057.         get_table_xy_or_coord(L, &rx, &ry);
4058.         tmproom.x = rx, tmproom.y = ry;
4059.         if ((tmproom.x == -1 || tmproom.y == -1) && tmproom.x != tmproom.y)
4060.             nhl_error(L, "Room must have both x and y");
4061. 
4062.         tmproom.w = get_table_int_opt(L, "w", -1);
4063.         tmproom.h = get_table_int_opt(L, "h", -1);
4064. 
4065.         if ((tmproom.w == -1 || tmproom.h == -1) && tmproom.w != tmproom.h)
4066.             nhl_error(L, "Room must have both w and h");
4067. 
4068.         tmproom.xalign = l_or_r2i[get_table_option(L, "xalign", "random",
4069.                                                    left_or_right)];
4070.         tmproom.yalign = t_or_b2i[get_table_option(L, "yalign", "random",
4071.                                                    top_or_bot)];
4072.         tmproom.rtype = get_table_roomtype_opt(L, "type", OROOM);
4073.         tmproom.chance = get_table_int_opt(L, "chance", 100);
4074.         tmproom.rlit = get_table_int_opt(L, "lit", -1);
4075.         /* theme rooms default to unfilled */
4076.         tmproom.needfill = get_table_int_opt(L, "filled",
4077.                                              gi.in_mk_themerooms ? 0 : 1);
4078.         tmproom.joined = get_table_boolean_opt(L, "joined", TRUE);
4079. 
4080.         if (!gc.coder->failed_room[gc.coder->n_subroom - 1]) {
4081.             tmpcr = build_room(&tmproom, gc.coder->croom);
4082.             if (tmpcr) {
4083.                 int n = gc.coder->n_subroom;
4084. 
4085.                 gc.coder->tmproomlist[n] = tmpcr; /* TRUE to get here... */
4086.                 gc.coder->failed_room[n] = FALSE;
4087.                 /* added a subroom, make parent room irregular */
4088.                 if (gc.coder->tmproomlist[n - 1])
4089.                     gc.coder->tmproomlist[n - 1]->irregular = TRUE;
4090.                 gc.coder->n_subroom++;
4091.                 update_croom();
4092.                 lua_getfield(L, 1, "contents");
4093.                 if (lua_type(L, -1) == LUA_TFUNCTION) {
4094.                     lua_remove(L, -2);
4095.                     l_push_mkroom_table(L, tmpcr);
4096.                     nhl_pcall_handle(L, 1, 0, "lspo_room", NHLpa_panic);
4097.                 } else
4098.                     lua_pop(L, 1);
4099.                 spo_endroom(gc.coder);
4100.                 add_doors_to_room(tmpcr);
4101.                 return 0;
4102.             }
4103.             if (gi.in_mk_themerooms)
4104.                 gt.themeroom_failed = TRUE;
4105.         } /* failed to create parent room, so fail this too */
4106.     }
4107.     gc.coder->tmproomlist[gc.coder->n_subroom] = (struct mkroom *) 0;
4108.     gc.coder->failed_room[gc.coder->n_subroom] = TRUE;
4109.     gc.coder->n_subroom++;
4110.     update_croom();
4111.     spo_endroom(gc.coder);
4112.     if (gi.in_mk_themerooms)
4113.         gt.themeroom_failed = TRUE;
4114. 
4115.     return 0;
4116. }
4117. 
4118. staticfn void
4119. spo_endroom(struct sp_coder *coder UNUSED)
4120. {
4121.     if (gc.coder->n_subroom > 1) {
4122.         gc.coder->n_subroom--;
4123.         gc.coder->tmproomlist[gc.coder->n_subroom] = NULL;
4124.         gc.coder->failed_room[gc.coder->n_subroom] = TRUE;
4125.     } else {
4126.         /* no subroom, get out of top-level room */
4127.         /* Need to ensure xstart/ystart/xsize/ysize have something sensible,
4128.            in case there's some stuff to be created outside the outermost
4129.            room, and there's no MAP. */
4130.         if (gx.xsize <= 1 && gy.ysize <= 1)
4131.             reset_xystart_size();
4132.     }
4133.     update_croom();
4134. }
4135. 
4136. /* callback for is_ok_location.
4137.    stairs generated at random location shouldn't overwrite special terrain */
4138. staticfn boolean
4139. good_stair_loc(coordxy x, coordxy y)
4140. {
4141.     schar typ = levl[x][y].typ;
4142. 
4143.     return (typ == ROOM || typ == CORR || typ == ICE);
4144. }
4145. 
4146. staticfn int
4147. l_create_stairway(lua_State *L, boolean using_ladder)
4148. {
4149.     static const char *const stairdirs[] = { "down", "up", NULL };
4150.     static const int stairdirs2i[] = { 0, 1 };
4151.     int argc = lua_gettop(L);
4152.     coordxy x = -1, y = -1;
4153.     struct trap *badtrap;
4154. 
4155.     long scoord;
4156.     int up = 0; /* default is down */
4157.     int ltype = lua_type(L, 1);
4158. 
4159.     create_des_coder();
4160. 
4161.     if (argc == 1 && ltype == LUA_TTABLE) {
4162.         lua_Integer ax = -1, ay = -1;
4163.         lcheck_param_table(L);
4164.         get_table_xy_or_coord(L, &ax, &ay);
4165.         up = stairdirs2i[get_table_option(L, "dir", "down", stairdirs)];
4166.         x = (coordxy) ax;
4167.         y = (coordxy) ay;
4168.     } else {
4169.         lua_Integer ix = -1, iy = -1;
4170.         if (argc > 0 && ltype == LUA_TSTRING) {
4171.             up = stairdirs2i[luaL_checkoption(L, 1, "down", stairdirs)];
4172.             lua_remove(L, 1);
4173.         }
4174.         nhl_get_xy_params(L, &ix, &iy);
4175.         x = (coordxy) ix;
4176.         y = (coordxy) iy;
4177.     }
4178. 
4179.     if (x == -1 && y == -1) {
4180.         set_ok_location_func(good_stair_loc);
4181.         scoord = SP_COORD_PACK_RANDOM(0);
4182.     } else
4183.         scoord = SP_COORD_PACK(x, y);
4184. 
4185.     get_location_coord(&x, &y, DRY, gc.coder->croom, scoord);
4186.     set_ok_location_func(NULL);
4187.     if ((badtrap = t_at(x, y)) != 0)
4188.         deltrap(badtrap);
4189.     SpLev_Map[x][y] = 1;
4190. 
4191.     if (using_ladder) {
4192.         levl[x][y].typ = LADDER;
4193.         if (up) {
4194.             d_level dest;
4195. 
4196.             dest.dnum = u.uz.dnum;
4197.             dest.dlevel = u.uz.dlevel - 1;
4198.             stairway_add(x, y, TRUE, TRUE, &dest);
4199.             levl[x][y].ladder = LA_UP;
4200.         } else {
4201.             d_level dest;
4202. 
4203.             dest.dnum = u.uz.dnum;
4204.             dest.dlevel = u.uz.dlevel + 1;
4205.             stairway_add(x, y, FALSE, TRUE, &dest);
4206.             levl[x][y].ladder = LA_DOWN;
4207.         }
4208.     } else {
4209.         mkstairs(x, y, (char) up, gc.coder->croom,
4210.                  !(scoord & SP_COORD_IS_RANDOM));
4211.     }
4212.     return 0;
4213. }
4214. 
4215. /* stair("up"); */
4216. /* stair({ dir = "down" }); */
4217. /* stair({ dir = "down", x = 4, y = 7 }); */
4218. /* stair({ dir = "down", coord = {x,y} }); */
4219. /* stair("down", 4, 7); */
4220. /* TODO: stair(selection, "down"); */
4221. /* TODO: stair("up", {x,y}); */
4222. int
4223. lspo_stair(lua_State *L)
4224. {
4225.     return l_create_stairway(L, FALSE);
4226. }
4227. 
4228. /* ladder("down"); */
4229. /* ladder("up", 6,10); */
4230. /* ladder({ x=11, y=05, dir="down" }); */
4231. int
4232. lspo_ladder(lua_State *L)
4233. {
4234.     return l_create_stairway(L, TRUE);
4235. }
4236. 
4237. /* grave(); */
4238. /* grave(x,y, "text"); */
4239. /* grave({ x = 1, y = 1 }); */
4240. /* grave({ x = 1, y = 1, text = "Foo" }); */
4241. /* grave({ coord = {1, 1}, text = "Foo" }); */
4242. int
4243. lspo_grave(lua_State *L)
4244. {
4245.     int argc = lua_gettop(L);
4246.     coordxy x, y;
4247.     long scoord;
4248.     lua_Integer ax,ay;
4249.     char *txt;
4250. 
4251.     create_des_coder();
4252. 
4253.     if (argc == 3) {
4254.         x = ax = luaL_checkinteger(L, 1);
4255.         y = ay = luaL_checkinteger(L, 2);
4256.         txt = dupstr(luaL_checkstring(L, 3));
4257.     } else {
4258.         lcheck_param_table(L);
4259. 
4260.         get_table_xy_or_coord(L, &ax, &ay);
4261.         x = ax, y = ay;
4262.         txt = get_table_str_opt(L, "text", NULL);
4263.     }
4264. 
4265.     if (x == -1 && y == -1)
4266.         scoord = SP_COORD_PACK_RANDOM(0);
4267.     else
4268.         scoord = SP_COORD_PACK(ax, ay);
4269. 
4270.     get_location_coord(&x, &y, DRY, gc.coder->croom, scoord);
4271. 
4272.     if (isok(x, y) && !t_at(x, y)) {
4273.         levl[x][y].typ = GRAVE;
4274.         make_grave(x, y, txt); /* note: 'txt' might be Null */
4275.     }
4276.     Free(txt);
4277.     return 0;
4278. }
4279. 
4280. /* altar({ x=NN, y=NN, align=ALIGNMENT, type=SHRINE }); */
4281. /* des.altar({ coord = {5, 10}, align="noalign", type="altar" }); */
4282. int
4283. lspo_altar(lua_State *L)
4284. {
4285.     static const char *const shrines[] = {
4286.         "altar", "shrine", "sanctum", NULL
4287.     };
4288.     static const int shrines2i[] = { 0, 1, 2, 0 };
4289. 
4290.     altar tmpaltar;
4291. 
4292.     lua_Integer x, y;
4293.     long acoord;
4294.     int shrine;
4295.     int al;
4296. 
4297.     create_des_coder();
4298. 
4299.     lcheck_param_table(L);
4300. 
4301.     get_table_xy_or_coord(L, &x, &y);
4302. 
4303.     al = get_table_align(L);
4304.     shrine = shrines2i[get_table_option(L, "type", "altar", shrines)];
4305. 
4306.     if (x == -1 && y == -1)
4307.         acoord = SP_COORD_PACK_RANDOM(0);
4308.     else
4309.         acoord = SP_COORD_PACK(x, y);
4310. 
4311.     tmpaltar.coord = acoord;
4312.     tmpaltar.sp_amask = al;
4313.     tmpaltar.shrine = shrine;
4314. 
4315.     create_altar(&tmpaltar, gc.coder->croom);
4316. 
4317.     return 0;
4318. }
4319. 
4320. static const struct {
4321.     const char *name;
4322.     int type;
4323. } trap_types[] = { { "arrow", ARROW_TRAP },
4324.                    { "dart", DART_TRAP },
4325.                    { "falling rock", ROCKTRAP },
4326.                    { "board", SQKY_BOARD },
4327.                    { "bear", BEAR_TRAP },
4328.                    { "land mine", LANDMINE },
4329.                    { "rolling boulder", ROLLING_BOULDER_TRAP },
4330.                    { "sleep gas", SLP_GAS_TRAP },
4331.                    { "rust", RUST_TRAP },
4332.                    { "fire", FIRE_TRAP },
4333.                    { "pit", PIT },
4334.                    { "spiked pit", SPIKED_PIT },
4335.                    { "hole", HOLE },
4336.                    { "trap door", TRAPDOOR },
4337.                    { "teleport", TELEP_TRAP },
4338.                    { "level teleport", LEVEL_TELEP },
4339.                    { "magic portal", MAGIC_PORTAL },
4340.                    { "web", WEB },
4341.                    { "statue", STATUE_TRAP },
4342.                    { "magic", MAGIC_TRAP },
4343.                    { "anti magic", ANTI_MAGIC },
4344.                    { "polymorph", POLY_TRAP },
4345.                    { "vibrating square", VIBRATING_SQUARE },
4346.                    { "random", -1 },
4347.                    { 0, NO_TRAP } };
4348. 
4349. staticfn int
4350. get_table_traptype_opt(lua_State *L, const char *name, int defval)
4351. {
4352.     char *trapstr = get_table_str_opt(L, name, emptystr);
4353.     int i, res = defval;
4354. 
4355.     if (trapstr && *trapstr) {
4356.         for (i = 0; trap_types[i].name; i++)
4357.             if (!strcmpi(trapstr, trap_types[i].name)) {
4358.                 res = trap_types[i].type;
4359.                 break;
4360.             }
4361.     }
4362.     Free(trapstr);
4363.     return res;
4364. }
4365. 
4366. const char *
4367. get_trapname_bytype(int ttyp)
4368. {
4369.     int i;
4370. 
4371.     for (i = 0; trap_types[i].name; i++)
4372.         if (ttyp == trap_types[i].type)
4373.             return trap_types[i].name;
4374. 
4375.     return NULL;
4376. }
4377. 
4378. staticfn int
4379. get_traptype_byname(const char *trapname)
4380. {
4381.     int i;
4382. 
4383.     for (i = 0; trap_types[i].name; i++)
4384.         if (!strcmpi(trapname, trap_types[i].name))
4385.             return trap_types[i].type;
4386. 
4387.     return NO_TRAP;
4388. }
4389. 
4390. /* trap({ type = "hole", x = 1, y = 1 }); */
4391. /* trap({ type = "web", spider_on_web = 0 }); */
4392. /* trap("hole", 3, 4); */
4393. /* trap("level teleport", {5, 8}); */
4394. /* trap("rust") */
4395. /* trap(); */
4396. int
4397. lspo_trap(lua_State *L)
4398. {
4399.     spltrap tmptrap;
4400.     lua_Integer x, y;
4401.     int argc = lua_gettop(L);
4402. 
4403.     create_des_coder();
4404. 
4405.     tmptrap.spider_on_web = TRUE;
4406.     tmptrap.seen = FALSE;
4407.     tmptrap.novictim = FALSE;
4408. 
4409.     if (argc == 1 && lua_type(L, 1) == LUA_TSTRING) {
4410.         const char *trapstr = luaL_checkstring(L, 1);
4411. 
4412.         tmptrap.type = get_traptype_byname(trapstr);
4413.         x = y = -1;
4414.     } else if (argc == 2 && lua_type(L, 1) == LUA_TSTRING
4415.                && lua_type(L, 2) == LUA_TTABLE) {
4416.         const char *trapstr = luaL_checkstring(L, 1);
4417. 
4418.         tmptrap.type = get_traptype_byname(trapstr);
4419.         (void) get_coord(L, 2, &x, &y);
4420.     } else if (argc == 3) {
4421.         const char *trapstr = luaL_checkstring(L, 1);
4422. 
4423.         tmptrap.type = get_traptype_byname(trapstr);
4424.         x = luaL_checkinteger(L, 2);
4425.         y = luaL_checkinteger(L, 3);
4426.     } else {
4427.         lcheck_param_table(L);
4428. 
4429.         get_table_xy_or_coord(L, &x, &y);
4430.         tmptrap.type = get_table_traptype_opt(L, "type", -1);
4431.         tmptrap.spider_on_web = get_table_boolean_opt(L, "spider_on_web", 1);
4432.         tmptrap.seen = get_table_boolean_opt(L, "seen", FALSE);
4433.         tmptrap.novictim = !get_table_boolean_opt(L, "victim", TRUE);
4434. 
4435.         lua_getfield(L, -1, "launchfrom");
4436.         if (lua_type(L, -1) == LUA_TTABLE) {
4437.             lua_Integer lx = -1, ly = -1;
4438. 
4439.             (void) get_coord(L, -1, &lx, &ly);
4440.             lua_pop(L, 1);
4441.             gl.launchplace.x = lx;
4442.             gl.launchplace.y = ly;
4443.         } else
4444.             lua_pop(L, 1);
4445. 
4446.         lua_getfield(L, -1, "teledest");
4447.         if (lua_type(L, -1) == LUA_TTABLE) {
4448.             lua_Integer lx = -1, ly = -1;
4449. 
4450.             (void) get_coord(L, -1, &lx, &ly);
4451.             lua_pop(L, 1);
4452.             gl.launchplace.x = lx;
4453.             gl.launchplace.y = ly;
4454.         } else
4455.             lua_pop(L, 1);
4456.     }
4457. 
4458.     if (tmptrap.type == NO_TRAP)
4459.         nhl_error(L, "Unknown trap type");
4460. 
4461.     if (x == -1 && y == -1)
4462.         tmptrap.coord = SP_COORD_PACK_RANDOM(0);
4463.     else
4464.         tmptrap.coord = SP_COORD_PACK(x, y);
4465. 
4466.     create_trap(&tmptrap, gc.coder->croom);
4467.     gl.launchplace.x = gl.launchplace.y = 0;
4468. 
4469.     return 0;
4470. }
4471. 
4472. DISABLE_WARNING_UNREACHABLE_CODE
4473. 
4474. /* gold(500, 3,5); */
4475. /* gold(500, {5, 6}); */
4476. /* gold({ amount = 500, x = 2, y = 5 });*/
4477. /* gold({ amount = 500, coord = {2, 5} });*/
4478. /* gold(); */
4479. int
4480. lspo_gold(lua_State *L)
4481. {
4482.     int argc = lua_gettop(L);
4483.     coordxy x, y;
4484.     long amount;
4485.     long gcoord;
4486.     lua_Integer gldx, gldy;
4487. 
4488.     create_des_coder();
4489. 
4490.     if (argc == 3) {
4491.         amount = luaL_checkinteger(L, 1);
4492.         x = gldx = luaL_checkinteger(L, 2);
4493.         y = gldy = luaL_checkinteger(L, 3);
4494.     } else if (argc == 2 && lua_type(L, 2) == LUA_TTABLE) {
4495.         amount = luaL_checkinteger(L, 1);
4496.         (void) get_coord(L, 2, &gldx, &gldy);
4497.         x = gldx;
4498.         y = gldy;
4499.     } else if (argc == 0 || (argc == 1 && lua_type(L, 1) == LUA_TTABLE)) {
4500.         lcheck_param_table(L);
4501. 
4502.         amount = get_table_int_opt(L, "amount", -1);
4503.         get_table_xy_or_coord(L, &gldx, &gldy);
4504.         x = gldx, y = gldy;
4505.     } else {
4506.         nhl_error(L, "Wrong parameters");
4507.         /*NOTREACHED*/
4508.         return 0;
4509.     }
4510. 
4511.     if (x == -1 && y == -1)
4512.         gcoord = SP_COORD_PACK_RANDOM(0);
4513.     else
4514.         gcoord = SP_COORD_PACK(gldx, gldy);
4515. 
4516.     get_location_coord(&x, &y, DRY, gc.coder->croom, gcoord);
4517.     if (amount < 0)
4518.         amount = rnd(200);
4519.     mkgold(amount, x, y);
4520. 
4521.     return 0;
4522. }
4523. 
4524. RESTORE_WARNING_UNREACHABLE_CODE
4525. 
4526. /* corridor({ srcroom=1, srcdoor=2, srcwall="north",
4527.  *            destroom=2, destdoor=1, destwall="west" }); */
4528. int
4529. lspo_corridor(lua_State *L)
4530. {
4531.     static const char *const walldirs[] = {
4532.         "all", "random", "north", "west", "east", "south", NULL
4533.     };
4534.     static const int walldirs2i[] = {
4535.         W_ANY, W_RANDOM, W_NORTH, W_WEST, W_EAST, W_SOUTH, 0
4536.     };
4537.     corridor tc;
4538. 
4539.     create_des_coder();
4540. 
4541.     lcheck_param_table(L);
4542. 
4543.     tc.src.room = get_table_int(L, "srcroom");
4544.     tc.src.door = get_table_int(L, "srcdoor");
4545.     tc.src.wall = walldirs2i[get_table_option(L, "srcwall", "all", walldirs)];
4546.     tc.dest.room = get_table_int(L, "destroom");
4547.     tc.dest.door = get_table_int(L, "destdoor");
4548.     tc.dest.wall = walldirs2i[get_table_option(L, "destwall", "all",
4549.                                                walldirs)];
4550. 
4551.     create_corridor(&tc);
4552. 
4553.     return 0;
4554. }
4555. 
4556. /* random_corridors(); */
4557. int
4558. lspo_random_corridors(lua_State *L UNUSED)
4559. {
4560.     corridor tc;
4561. 
4562.     create_des_coder();
4563. 
4564.     tc.src.room = -1;
4565.     tc.src.door = -1;
4566.     tc.src.wall = -1;
4567.     tc.dest.room = -1;
4568.     tc.dest.door = -1;
4569.     tc.dest.wall = -1;
4570. 
4571.     create_corridor(&tc);
4572. 
4573.     return 0;
4574. }
4575. 
4576. /* Choose a single random W_* direction. */
4577. coordxy
4578. random_wdir(void)
4579. {
4580.     static const coordxy wdirs[4] = { W_NORTH, W_SOUTH, W_EAST, W_WEST };
4581.     return wdirs[rn2(4)];
4582. }
4583. 
4584. static schar floodfillchk_match_under_typ;
4585. 
4586. staticfn int
4587. floodfillchk_match_under(coordxy x, coordxy y)
4588. {
4589.     return (floodfillchk_match_under_typ == levl[x][y].typ);
4590. }
4591. 
4592. void
4593. set_floodfillchk_match_under(coordxy typ)
4594. {
4595.     floodfillchk_match_under_typ = typ;
4596.     set_selection_floodfillchk(floodfillchk_match_under);
4597. }
4598. 
4599. staticfn int
4600. floodfillchk_match_accessible(coordxy x, coordxy y)
4601. {
4602.     return (ACCESSIBLE(levl[x][y].typ)
4603.             || levl[x][y].typ == SDOOR
4604.             || levl[x][y].typ == SCORR);
4605. }
4606. 
4607. /* change map location terrain type during level creation */
4608. staticfn void
4609. sel_set_ter(coordxy x, coordxy y, genericptr_t arg)
4610. {
4611.     terrain terr;
4612. 
4613.     terr = *(terrain *) arg;
4614.     if (!set_levltyp_lit(x, y, terr.ter, terr.tlit))
4615.         return;
4616.     /* TODO: move this below into set_levltyp? */
4617.     /* handle doors and secret doors */
4618.     if (levl[x][y].typ == SDOOR || IS_DOOR(levl[x][y].typ)) {
4619.         if (levl[x][y].typ == SDOOR)
4620.             levl[x][y].doormask = D_CLOSED;
4621.         if (x && (IS_WALL(levl[x - 1][y].typ) || levl[x - 1][y].horizontal))
4622.             levl[x][y].horizontal = 1;
4623.     } else if (levl[x][y].typ == HWALL || levl[x][y].typ == IRONBARS) {
4624.         levl[x][y].horizontal = 1;
4625.     } else if (splev_init_present && levl[x][y].typ == ICE) {
4626.         levl[x][y].icedpool = icedpools ? ICED_POOL : ICED_MOAT;
4627.     } else if (levl[x][y].typ == CLOUD) {
4628.         del_engr_at(x, y); /* clouds cannot have engravings */
4629.     }
4630. }
4631. 
4632. staticfn void
4633. sel_set_feature(coordxy x, coordxy y, genericptr_t arg)
4634. {
4635.     if (!isok(x, y)) {
4636. #ifdef EXTRA_SANITY_CHECKS
4637.         impossible("sel_set_feature(%i,%i,%i) !isok", x, y, (*(int *) arg));
4638. #endif /*EXTRA_SANITY_CHECKS*/
4639.         return;
4640.     }
4641.     if (IS_FURNITURE(levl[x][y].typ))
4642.         return;
4643.     levl[x][y].typ = (*(int *) arg);
4644. }
4645. 
4646. staticfn void
4647. sel_set_door(coordxy dx, coordxy dy, genericptr_t arg)
4648. {
4649.     coordxy typ = *(coordxy *) arg;
4650.     coordxy x = dx, y = dy;
4651. 
4652.     if (!IS_DOOR(levl[x][y].typ) && levl[x][y].typ != SDOOR)
4653.         levl[x][y].typ = (typ & D_SECRET) ? SDOOR : DOOR;
4654.     if (typ & D_SECRET) {
4655.         typ &= ~D_SECRET;
4656.         if (typ < D_CLOSED)
4657.             typ = D_CLOSED;
4658.     }
4659.     set_door_orientation(x, y); /* set/clear levl[x][y].horizontal */
4660.     levl[x][y].doormask = typ;
4661.     SpLev_Map[x][y] = 1;
4662. }
4663. 
4664. DISABLE_WARNING_UNREACHABLE_CODE
4665. 
4666. /* door({ x = 1, y = 1, state = "nodoor" }); */
4667. /* door({ coord = {1, 1}, state = "nodoor" }); */
4668. /* door({ wall = "north", pos = 3, state="secret" }); */
4669. /* door("nodoor", 1, 2); */
4670. int
4671. lspo_door(lua_State *L)
4672. {
4673.     static const char *const doorstates[] = {
4674.         "random", "open", "closed", "locked", "nodoor", "broken",
4675.         "secret", NULL
4676.     };
4677.     static const int doorstates2i[] = {
4678.         -1, D_ISOPEN, D_CLOSED, D_LOCKED, D_NODOOR, D_BROKEN, D_SECRET
4679.     };
4680.     int msk;
4681.     coordxy x, y;
4682.     coordxy typ;
4683.     int argc = lua_gettop(L);
4684. 
4685.     create_des_coder();
4686. 
4687.     if (argc == 3) {
4688.         msk = doorstates2i[luaL_checkoption(L, 1, "random", doorstates)];
4689.         x = luaL_checkinteger(L, 2);
4690.         y = luaL_checkinteger(L, 3);
4691. 
4692.     } else {
4693.         lua_Integer dx, dy;
4694.         lcheck_param_table(L);
4695. 
4696.         get_table_xy_or_coord(L, &dx, &dy);
4697.         x = dx, y = dy;
4698.         msk = doorstates2i[get_table_option(L, "state", "random",
4699.                                             doorstates)];
4700.     }
4701. 
4702.     typ = (msk == -1) ? rnddoor() : (coordxy) msk;
4703. 
4704.     if (x == -1 && y == -1) {
4705.         static const char *const walldirs[] = {
4706.             "all", "random", "north", "west", "east", "south", NULL
4707.         };
4708.         /* Note that "random" is also W_ANY, because create_door just wants a
4709.          * mask of acceptable walls */
4710.         static const int walldirs2i[] = {
4711.             W_ANY, W_ANY, W_NORTH, W_WEST, W_EAST, W_SOUTH, 0
4712.         };
4713.         room_door tmpd;
4714. 
4715.         tmpd.secret = (typ == D_SECRET) ? 1 : 0;
4716.         tmpd.mask = msk;
4717.         tmpd.pos = get_table_int_opt(L, "pos", -1);
4718.         tmpd.wall = walldirs2i[get_table_option(L, "wall", "all", walldirs)];
4719. 
4720.         create_door(&tmpd, gc.coder->croom);
4721.     } else {
4722.         /*selection_iterate(sel, sel_set_door, (genericptr_t) &typ);*/
4723.         get_location_coord(&x, &y, ANY_LOC, gc.coder->croom,
4724.                            SP_COORD_PACK(x, y));
4725.         if (!isok(x, y)) {
4726.             nhl_error(L, "door coord not ok");
4727.             /*NOTREACHED*/
4728.             return 0;
4729.         }
4730.         sel_set_door(x, y, (genericptr_t) &typ);
4731.     }
4732. 
4733.     return 0;
4734. }
4735. 
4736. RESTORE_WARNING_UNREACHABLE_CODE
4737. 
4738. staticfn void
4739. l_table_getset_feature_flag(
4740.     lua_State *L,
4741.     int x, int y,
4742.     const char *name,
4743.     int flag)
4744. {
4745.     int val = get_table_boolean_opt(L, name, -2);
4746. 
4747.     if (val != -2) {
4748.         if (val == -1)
4749.             val = rn2(2);
4750.         if (val)
4751.             levl[x][y].flags |= flag;
4752.         else
4753.             levl[x][y].flags &= ~flag;
4754.     }
4755. }
4756. 
4757. /* guts of nhl_abs_coord; convert a coordinate relative to a map or room
4758.  * into an absolute coordinate in svl.level.locations.
4759.  *
4760.  * If there is no enclosing map or room, the coordinates are assumed to be
4761.  * absolute already.
4762.  *
4763.  * Part of the reason this is a function is to make it clearer in the calling
4764.  * code that this conversion is what is intended.
4765.  *
4766.  * NOTE: if the coordinates are going to get passed to one of the get_location
4767.  * family of functions, this should NOT be called; get_location already makes
4768.  * an adjustment like this. (What this function supports which get_location
4769.  * doesn't is the input coordinates being negative. get_location will treat
4770.  * that as "level designer wants a random coordinate".) */
4771. void
4772. cvt_to_abscoord(coordxy *x, coordxy *y)
4773. {
4774.     /* since commit 99715e0, xstart and ystart are only relevant in mklev when
4775.      * maps are being used, and 0 otherwise. It is possible in the future that
4776.      * map positions and dimensions can be saved and retrieved outside of
4777.      * mklev which would reintroduce nonzero xstart/ystart/xsiz/ysiz, but
4778.      * this is not currently implemented, so this function can be assumed to
4779.      * have no effect outside of mklev.
4780.      */
4781.     if (gc.coder && gc.coder->croom) {
4782.         *x += gc.coder->croom->lx;
4783.         *y += gc.coder->croom->ly;
4784.     } else {
4785.         *x += gx.xstart;
4786.         *y += gy.ystart;
4787.     }
4788. }
4789. 
4790. /* inverse of cvt_to_abscoord; turn an absolute svl.level.locations coordinate
4791.  * into one relative to the current map or room. */
4792. void
4793. cvt_to_relcoord(coordxy *x, coordxy *y)
4794. {
4795.     if (gc.coder && gc.coder->croom) {
4796.         *x -= gc.coder->croom->lx;
4797.         *y -= gc.coder->croom->ly;
4798.     } else {
4799.         *x -= gx.xstart;
4800.         *y -= gy.ystart;
4801.     }
4802. }
4803. 
4804. DISABLE_WARNING_UNREACHABLE_CODE
4805. 
4806. /* convert map-relative coordinate to absolute.
4807.   local ax,ay = nh.abscoord(rx, ry);
4808.   local pt = nh.abscoord({ x = 10, y = 5 });
4809.  */
4810. int
4811. nhl_abs_coord(lua_State *L)
4812. {
4813.     int argc = lua_gettop(L);
4814.     coordxy x = -1, y = -1;
4815. 
4816.     if (argc == 2) {
4817.         x = (coordxy) lua_tointeger(L, 1);
4818.         y = (coordxy) lua_tointeger(L, 2);
4819.         cvt_to_abscoord(&x, &y);
4820.         lua_pushinteger(L, x);
4821.         lua_pushinteger(L, y);
4822.         return 2;
4823.     } else if (argc == 1 && lua_type(L, 1) == LUA_TTABLE) {
4824.         x = (coordxy) get_table_int(L, "x");
4825.         y = (coordxy) get_table_int(L, "y");
4826.         cvt_to_abscoord(&x, &y);
4827.         lua_newtable(L);
4828.         nhl_add_table_entry_int(L, "x", x);
4829.         nhl_add_table_entry_int(L, "y", y);
4830.         return 1;
4831.     } else {
4832.         nhl_error(L, "nhl_abs_coord: Wrong args");
4833.         /*NOTREACHED*/
4834.         return 0;
4835.     }
4836. }
4837. 
4838. /* feature("fountain", x, y); */
4839. /* feature("fountain", {x,y}); */
4840. /* feature({ type="fountain", x=NN, y=NN }); */
4841. /* feature({ type="fountain", coord={NN, NN} }); */
4842. /* feature({ type="tree", coord={NN, NN}, swarm=true, looted=false }); */
4843. int
4844. lspo_feature(lua_State *L)
4845. {
4846.     static const char *const features[] = { "fountain", "sink", "pool",
4847.                                             "throne", "tree", NULL };
4848.     static const int features2i[] = { FOUNTAIN, SINK, POOL,
4849.                                       THRONE, TREE, STONE };
4850.     coordxy x, y;
4851.     int typ;
4852.     int argc = lua_gettop(L);
4853.     boolean can_have_flags = FALSE;
4854.     long fcoord;
4855.     int humidity;
4856. 
4857.     create_des_coder();
4858. 
4859.     if (argc == 1 && lua_type(L, 1) == LUA_TSTRING) {
4860.         typ = features2i[luaL_checkoption(L, 1, NULL, features)];
4861.         x = y = -1;
4862.     } else if (argc == 2 && lua_type(L, 1) == LUA_TSTRING
4863.         && lua_type(L, 2) == LUA_TTABLE) {
4864.         lua_Integer fx, fy;
4865.         typ = features2i[luaL_checkoption(L, 1, NULL, features)];
4866.         (void) get_coord(L, 2, &fx, &fy);
4867.         x = fx;
4868.         y = fy;
4869.     } else if (argc == 3) {
4870.         typ = features2i[luaL_checkoption(L, 1, NULL, features)];
4871.         x = luaL_checkinteger(L, 2);
4872.         y = luaL_checkinteger(L, 3);
4873.     } else {
4874.         lua_Integer fx, fy;
4875.         lcheck_param_table(L);
4876. 
4877.         get_table_xy_or_coord(L, &fx, &fy);
4878.         x = fx, y = fy;
4879.         typ = features2i[get_table_option(L, "type", NULL, features)];
4880.         can_have_flags = TRUE;
4881.     }
4882. 
4883.     if (x == -1 && y == -1) {
4884.         fcoord = SP_COORD_PACK_RANDOM(0);
4885.         humidity = DRY; /* pick a regular space, no rock or other furniture */
4886.     }
4887.     else {
4888.         fcoord = SP_COORD_PACK(x, y);
4889.         humidity = ANY_LOC; /* assume the author knows what they're doing */
4890.     }
4891.     get_location_coord(&x, &y, humidity, gc.coder->croom, fcoord);
4892. 
4893.     if (typ == STONE)
4894.         impossible("feature has unknown type param.");
4895.     else
4896.         sel_set_feature(x, y, (genericptr_t) &typ);
4897. 
4898.     if (levl[x][y].typ != typ || !can_have_flags)
4899.         return 0;
4900. 
4901.     switch (typ) {
4902.     default:
4903.         break;
4904.     case FOUNTAIN:
4905.         l_table_getset_feature_flag(L, x, y, "looted", F_LOOTED);
4906.         l_table_getset_feature_flag(L, x, y, "warned", F_WARNED);
4907.         break;
4908.     case SINK:
4909.         l_table_getset_feature_flag(L, x, y, "pudding", S_LPUDDING);
4910.         l_table_getset_feature_flag(L, x, y, "dishwasher", S_LDWASHER);
4911.         l_table_getset_feature_flag(L, x, y, "ring", S_LRING);
4912.         break;
4913.     case THRONE:
4914.         l_table_getset_feature_flag(L, x, y, "looted", T_LOOTED);
4915.         break;
4916.     case TREE:
4917.         l_table_getset_feature_flag(L, x, y, "looted", TREE_LOOTED);
4918.         l_table_getset_feature_flag(L, x, y, "swarm", TREE_SWARM);
4919.         break;
4920.     }
4921. 
4922.     return 0;
4923. }
4924. 
4925. /* gas_cloud({ selection=SELECTION }); */
4926. /* gas_cloud({ selection=SELECTION, damage=N }); */
4927. /* gas_cloud({ selection=SELECTION, damage=N, ttl=N }); */
4928. int
4929. lspo_gas_cloud(lua_State *L)
4930. {
4931.     coordxy x = 0, y = 0;
4932.     struct selectionvar *sel = NULL;
4933.     int argc = lua_gettop(L);
4934.     int damage = 0;
4935.     int ttl = -2;
4936. 
4937.     create_des_coder();
4938. 
4939.     if (argc == 1 && lua_type(L, 1) == LUA_TTABLE) {
4940.         lua_Integer tx, ty;
4941.         NhRegion *reg;
4942. 
4943.         lcheck_param_table(L);
4944. 
4945.         get_table_xy_or_coord(L, &tx, &ty);
4946.         x = tx, y = ty;
4947.         if (tx == -1 && ty == -1) {
4948.             lua_getfield(L, 1, "selection");
4949.             sel = l_selection_check(L, -1);
4950.             lua_pop(L, 1);
4951.         }
4952.         damage = get_table_int_opt(L, "damage", 0);
4953.         ttl = get_table_int_opt(L, "ttl", -2);
4954.         if (!sel) {
4955.             reg = create_gas_cloud(x, y, 1, damage);
4956.         } else
4957.             reg = create_gas_cloud_selection(sel, damage);
4958.         if (ttl > -2)
4959.             reg->ttl = ttl;
4960.     } else {
4961.         nhl_error(L, "wrong parameters");
4962.     }
4963. 
4964.     return 0;
4965. }
4966. 
4967. 
4968. /*
4969.  * [lit_state: 1 On, 0 Off, -1 random, -2 leave as-is]
4970.  * terrain({ x=NN, y=NN, typ=MAPCHAR, lit=lit_state });
4971.  * terrain({ coord={X, Y}, typ=MAPCHAR, lit=lit_state });
4972.  * terrain({ selection=SELECTION, typ=MAPCHAR, lit=lit_state });
4973.  * terrain( SELECTION, MAPCHAR [, lit_state ] );
4974.  * terrain({x,y}, MAPCHAR);
4975.  * terrain(x,y, MAPCHAR);
4976.  */
4977. int
4978. lspo_terrain(lua_State *L)
4979. {
4980.     terrain tmpterrain;
4981.     coordxy x = 0, y = 0;
4982.     struct selectionvar *sel = NULL;
4983.     int argc = lua_gettop(L);
4984. 
4985.     create_des_coder();
4986.     tmpterrain.tlit = SET_LIT_NOCHANGE;
4987.     tmpterrain.ter = INVALID_TYPE;
4988. 
4989.     if (argc == 1) {
4990.         lua_Integer tx, ty;
4991.         lcheck_param_table(L);
4992. 
4993.         get_table_xy_or_coord(L, &tx, &ty);
4994.         x = tx, y = ty;
4995.         if (tx == -1 && ty == -1) {
4996.             lua_getfield(L, 1, "selection");
4997.             sel = l_selection_check(L, -1);
4998.             lua_pop(L, 1);
4999.         }
5000.         tmpterrain.ter = get_table_mapchr(L, "typ");
5001.         tmpterrain.tlit = get_table_int_opt(L, "lit", SET_LIT_NOCHANGE);
5002.     } else if (argc == 2 && lua_type(L, 1) == LUA_TTABLE
5003.                && lua_type(L, 2) == LUA_TSTRING) {
5004.         lua_Integer tx, ty;
5005.         tmpterrain.ter = check_mapchr(luaL_checkstring(L, 2));
5006.         lua_pop(L, 1);
5007.         (void) get_coord(L, 1, &tx, &ty);
5008.         x = tx;
5009.         y = ty;
5010.     } else if (argc == 2) {
5011.         sel = l_selection_check(L, 1);
5012.         tmpterrain.ter = check_mapchr(luaL_checkstring(L, 2));
5013.     } else if (argc == 3) {
5014.         x = luaL_checkinteger(L, 1);
5015.         y = luaL_checkinteger(L, 2);
5016.         tmpterrain.ter = check_mapchr(luaL_checkstring(L, 3));
5017.     } else {
5018.         nhl_error(L, "wrong parameters");
5019.     }
5020. 
5021.     if (tmpterrain.ter == INVALID_TYPE)
5022.         nhl_error(L, "Erroneous map char");
5023. 
5024.     if (sel) {
5025.         selection_iterate(sel, sel_set_ter, (genericptr_t) &tmpterrain);
5026.     } else {
5027.         get_location_coord(&x, &y, ANY_LOC, gc.coder->croom,
5028.                            SP_COORD_PACK(x, y));
5029.         if (!isok(x, y)) {
5030.             nhl_error(L, "terrain coord not ok");
5031.             /*NOTREACHED*/
5032.             return 0;
5033.         }
5034.         sel_set_ter(x, y, (genericptr_t) &tmpterrain);
5035.     }
5036. 
5037.     return 0;
5038. }
5039. 
5040. /*
5041.  * replace_terrain({ x1=NN,y1=NN, x2=NN,y2=NN, fromterrain=MAPCHAR,
5042.  *                   toterrain=MAPCHAR, lit=N, chance=NN });
5043.  * replace_terrain({ region={x1,y1, x2,y2}, fromterrain=MAPCHAR,
5044.  *                   toterrain=MAPCHAR, lit=N, chance=NN });
5045.  * replace_terrain({ selection=selection.area(2,5, 40,10),
5046.  *                   fromterrain=MAPCHAR, toterrain=MAPCHAR });
5047.  * replace_terrain({ selection=SEL, mapfragment=...,
5048.  *                   toterrain=MAPCHAR });
5049.  */
5050. int
5051. lspo_replace_terrain(lua_State *L)
5052. {
5053.     coordxy totyp, fromtyp;
5054.     struct mapfragment *mf = NULL;
5055.     struct selectionvar *sel = NULL;
5056.     boolean freesel = FALSE;
5057.     coordxy x, y;
5058.     lua_Integer x1, y1, x2, y2;
5059.     int chance;
5060.     int tolit;
5061.     NhRect rect = cg.zeroNhRect;
5062. 
5063.     create_des_coder();
5064. 
5065.     lcheck_param_table(L);
5066. 
5067.     totyp = get_table_mapchr(L, "toterrain");
5068. 
5069.     if (totyp >= MAX_TYPE)
5070.         return 0;
5071. 
5072.     fromtyp = get_table_mapchr_opt(L, "fromterrain", INVALID_TYPE);
5073. 
5074.     if (fromtyp == INVALID_TYPE) {
5075.         const char *err;
5076.         char *tmpstr = get_table_str(L, "mapfragment");
5077.         mf = mapfrag_fromstr(tmpstr);
5078.         free(tmpstr);
5079. 
5080.         if ((err = mapfrag_error(mf)) != NULL) {
5081.             nhl_error(L, err);
5082.             /*NOTREACHED*/
5083.         }
5084.     }
5085. 
5086.     chance = get_table_int_opt(L, "chance", 100);
5087.     tolit = get_table_int_opt(L, "lit", SET_LIT_NOCHANGE);
5088.     x1 = get_table_int_opt(L, "x1", -1);
5089.     y1 = get_table_int_opt(L, "y1", -1);
5090.     x2 = get_table_int_opt(L, "x2", -1);
5091.     y2 = get_table_int_opt(L, "y2", -1);
5092. 
5093.     if (x1 == -1 && y1 == -1 && x2 == -1 && y2 == -1) {
5094.         get_table_region(L, "region", &x1, &y1, &x2, &y2, TRUE);
5095.     }
5096. 
5097.     if (x1 == -1 && y1 == -1 && x2 == -1 && y2 == -1) {
5098.         lua_getfield(L, 1, "selection");
5099.         if (lua_type(L, -1) != LUA_TNIL)
5100.             sel = l_selection_check(L, -1);
5101.         lua_pop(L, 1);
5102.     }
5103. 
5104.     if (!sel) {
5105.         sel = selection_new();
5106.         freesel = TRUE;
5107. 
5108.         if (x1 == -1 && y1 == -1 && x2 == -1 && y2 == -1) {
5109.             (void) selection_clear(sel, 1);
5110.         } else {
5111.             coordxy rx1, ry1, rx2, ry2;
5112.             rx1 = x1, ry1 = y1, rx2 = x2, ry2 = y2;
5113.             get_location(&rx1, &ry1, ANY_LOC, gc.coder->croom);
5114.             get_location(&rx2, &ry2, ANY_LOC, gc.coder->croom);
5115.             for (x = max(rx1, 0); x <= min(rx2, COLNO - 1); x++)
5116.                 for (y = max(ry1, 0); y <= min(ry2, ROWNO - 1); y++)
5117.                     selection_setpoint(x, y, sel, 1);
5118.         }
5119.     }
5120. 
5121.     selection_getbounds(sel, &rect);
5122. 
5123.     for (x = max(1, rect.lx); x <= rect.hx; x++)
5124.         for (y = rect.ly; y <= rect.hy; y++)
5125.             if (selection_getpoint(x, y,sel)) {
5126.                 if (mf) {
5127.                     if (mapfrag_match(mf, x, y) && (rn2(100)) < chance)
5128.                         (void) set_levltyp_lit(x, y, totyp, tolit);
5129.                 } else {
5130.                     if (((fromtyp == MATCH_WALL && IS_STWALL(levl[x][y].typ))
5131.                          || levl[x][y].typ == fromtyp)
5132.                         && rn2(100) < chance)
5133.                         (void) set_levltyp_lit(x, y, totyp, tolit);
5134.                 }
5135.             }
5136. 
5137.     if (freesel)
5138.         selection_free(sel, TRUE);
5139. 
5140.     mapfrag_free(&mf);
5141. 
5142.     return 0;
5143. }
5144. 
5145. staticfn boolean
5146. generate_way_out_method(
5147.     coordxy nx, coordxy ny,
5148.     struct selectionvar *ov)
5149. {
5150.     static const int escapeitems[] = {
5151.         PICK_AXE, DWARVISH_MATTOCK, WAN_DIGGING,
5152.         WAN_TELEPORTATION, SCR_TELEPORTATION, RIN_TELEPORTATION
5153.     };
5154.     struct selectionvar *ov2 = selection_new(), *ov3;
5155.     coordxy x, y;
5156.     boolean res = TRUE;
5157. 
5158.     selection_floodfill(ov2, nx, ny, TRUE);
5159.     ov3 = selection_clone(ov2);
5160. 
5161.     /* try to make a secret door */
5162.     while (selection_rndcoord(ov3, &x, &y, TRUE)) {
5163.         if (isok(x + 1, y) && !selection_getpoint(x + 1, y, ov)
5164.             && IS_WALL(levl[x + 1][y].typ)
5165.             && isok(x + 2, y) &&  selection_getpoint(x + 2, y, ov)
5166.             && ACCESSIBLE(levl[x + 2][y].typ)) {
5167.             levl[x + 1][y].typ = SDOOR;
5168.             goto gotitdone;
5169.         }
5170.         if (isok(x - 1, y) && !selection_getpoint(x - 1, y, ov)
5171.             && IS_WALL(levl[x - 1][y].typ)
5172.             && isok(x - 2, y) && selection_getpoint(x - 2, y, ov)
5173.             && ACCESSIBLE(levl[x - 2][y].typ)) {
5174.             levl[x - 1][y].typ = SDOOR;
5175.             goto gotitdone;
5176.         }
5177.         if (isok(x, y + 1) && !selection_getpoint(x, y + 1, ov)
5178.             && IS_WALL(levl[x][y + 1].typ)
5179.             && isok(x, y + 2) && selection_getpoint(x, y + 2, ov)
5180.             && ACCESSIBLE(levl[x][y + 2].typ)) {
5181.             levl[x][y + 1].typ = SDOOR;
5182.             goto gotitdone;
5183.         }
5184.         if (isok(x, y - 1) && !selection_getpoint(x, y - 1, ov)
5185.             && IS_WALL(levl[x][y - 1].typ)
5186.             && isok(x, y - 2) && selection_getpoint(x, y - 2, ov)
5187.             && ACCESSIBLE(levl[x][y - 2].typ)) {
5188.             levl[x][y - 1].typ = SDOOR;
5189.             goto gotitdone;
5190.         }
5191.     }
5192. 
5193.     /* try to make a hole or a trapdoor */
5194.     if (Can_fall_thru(&u.uz)) {
5195.         selection_free(ov3, TRUE);
5196.         ov3 = selection_clone(ov2);
5197.         while (selection_rndcoord(ov3, &x, &y, TRUE)) {
5198.             if (maketrap(x, y, rn2(2) ? HOLE : TRAPDOOR))
5199.                 goto gotitdone;
5200.         }
5201.     }
5202. 
5203.     /* generate one of the escape items */
5204.     if (selection_rndcoord(ov2, &x, &y, FALSE)) {
5205.         mksobj_at(ROLL_FROM(escapeitems), x, y, TRUE, FALSE);
5206.         goto gotitdone;
5207.     }
5208. 
5209.     res = FALSE;
5210.  gotitdone:
5211.     selection_free(ov2, TRUE);
5212.     selection_free(ov3, TRUE);
5213.     return res;
5214. }
5215. 
5216. staticfn void
5217. ensure_way_out(void)
5218. {
5219.     struct selectionvar *ov = selection_new();
5220.     struct trap *ttmp = gf.ftrap;
5221.     coordxy x, y;
5222.     boolean ret = TRUE;
5223.     stairway *stway = gs.stairs;
5224. 
5225.     set_selection_floodfillchk(floodfillchk_match_accessible);
5226. 
5227.     while (stway) {
5228.         if (stway->tolev.dnum == u.uz.dnum)
5229.             selection_floodfill(ov, stway->sx, stway->sy, TRUE);
5230.         stway = stway->next;
5231.     }
5232. 
5233.     while (ttmp) {
5234.         if ((undestroyable_trap(ttmp->ttyp) || is_hole(ttmp->ttyp))
5235.             && !selection_getpoint(ttmp->tx, ttmp->ty, ov))
5236.             selection_floodfill(ov, ttmp->tx, ttmp->ty, TRUE);
5237.         ttmp = ttmp->ntrap;
5238.     }
5239. 
5240.     do {
5241.         ret = TRUE;
5242.         for (x = 1; x < COLNO; x++)
5243.             for (y = 0; y < ROWNO; y++)
5244.                 if (ACCESSIBLE(levl[x][y].typ)
5245.                     && !selection_getpoint(x, y, ov)) {
5246.                     if (generate_way_out_method(x, y, ov))
5247.                         selection_floodfill(ov, x, y, TRUE);
5248.                     ret = FALSE;
5249.                     goto outhere;
5250.                 }
5251.  outhere:
5252.         ;
5253.     } while (!ret);
5254.     selection_free(ov, TRUE);
5255. }
5256. 
5257. DISABLE_WARNING_UNREACHABLE_CODE
5258. 
5259. staticfn lua_Integer
5260. get_table_intarray_entry(lua_State *L, int tableidx, int entrynum)
5261. {
5262.     lua_Integer ret = 0;
5263.     if (tableidx < 0)
5264.         tableidx--;
5265. 
5266.     lua_pushinteger(L, entrynum);
5267.     lua_gettable(L, tableidx);
5268.     if (lua_isnumber(L, -1)) {
5269.         ret = lua_tointeger(L, -1);
5270.     } else {
5271.         char buf[BUFSZ];
5272. 
5273.         Sprintf(buf, "Array entry #%i is %s, expected number",
5274.                 1, luaL_typename(L, -1));
5275.         nhl_error(L, buf);
5276.     }
5277.     lua_pop(L, 1);
5278.     return ret;
5279. }
5280. 
5281. staticfn int
5282. get_table_region(
5283.     lua_State *L,
5284.     const char *name,
5285.     lua_Integer *x1, lua_Integer *y1,
5286.     lua_Integer *x2, lua_Integer *y2,
5287.     boolean optional)
5288. {
5289.     lua_Integer arrlen;
5290. 
5291.     lua_getfield(L, 1, name);
5292.     if (optional && lua_type(L, -1) == LUA_TNIL) {
5293.         lua_pop(L, 1);
5294.         return 1;
5295.     }
5296. 
5297.     luaL_checktype(L, -1, LUA_TTABLE);
5298. 
5299.     lua_len(L, -1);
5300.     arrlen = lua_tointeger(L, -1);
5301.     lua_pop(L, 1);
5302.     if (arrlen != 4) {
5303.         nhl_error(L, "Not a region");
5304.         /*NOTREACHED*/
5305.         lua_pop(L, 1);
5306.         return 0;
5307.     }
5308. 
5309.     *x1 = get_table_intarray_entry(L, -1, 1);
5310.     *y1 = get_table_intarray_entry(L, -1, 2);
5311.     *x2 = get_table_intarray_entry(L, -1, 3);
5312.     *y2 = get_table_intarray_entry(L, -1, 4);
5313. 
5314.     lua_pop(L, 1);
5315.     return 1;
5316. }
5317. 
5318. boolean
5319. get_coord(lua_State *L, int i, lua_Integer *x, lua_Integer *y)
5320. {
5321.     boolean ret = FALSE;
5322.     int ltyp = lua_type(L, i);
5323. 
5324.     if (ltyp == LUA_TTABLE) {
5325.         int arrlen;
5326.         boolean gotx = FALSE;
5327. 
5328.         lua_getfield(L, i, "x");
5329.         if (!lua_isnil(L, -1)) {
5330.             *x = luaL_checkinteger(L, -1);
5331.             gotx = TRUE;
5332.         }
5333.         lua_pop(L, 1);
5334. 
5335.         if (gotx) {
5336.             lua_getfield(L, i, "y");
5337.             if (!lua_isnil(L, -1)) {
5338.                 *y = luaL_checkinteger(L, -1);
5339.                 lua_pop(L, 1);
5340.                 ret = TRUE;
5341.             } else {
5342.                 nhl_error(L, "Not a coordinate");
5343.                 /*NOTREACHED*/
5344.                 return FALSE;
5345.             }
5346.         } else {
5347.             lua_len(L, i);
5348.             arrlen = lua_tointeger(L, -1);
5349.             lua_pop(L, 1);
5350.             if (arrlen != 2) {
5351.                 nhl_error(L, "Not a coordinate");
5352.                 /*NOTREACHED*/
5353.                 return FALSE;
5354.             }
5355. 
5356.             *x = get_table_intarray_entry(L, i, 1);
5357.             *y = get_table_intarray_entry(L, i, 2);
5358. 
5359.             return TRUE;
5360.         }
5361.     } else if (ltyp != LUA_TNIL) {
5362.         /* non-existent coord is ok */
5363.         nhl_error(L, "non-table coord specified");
5364.     }
5365.     return ret;
5366. }
5367. 
5368. RESTORE_WARNING_UNREACHABLE_CODE
5369. 
5370. staticfn void
5371. levregion_add(lev_region *lregion)
5372. {
5373.     if (!lregion->in_islev) {
5374.         get_location(&lregion->inarea.x1, &lregion->inarea.y1, ANY_LOC,
5375.                      (struct mkroom *) 0);
5376.         get_location(&lregion->inarea.x2, &lregion->inarea.y2, ANY_LOC,
5377.                      (struct mkroom *) 0);
5378.     }
5379. 
5380.     if (!lregion->del_islev) {
5381.         get_location(&lregion->delarea.x1, &lregion->delarea.y1,
5382.                      ANY_LOC, (struct mkroom *) 0);
5383.         get_location(&lregion->delarea.x2, &lregion->delarea.y2,
5384.                      ANY_LOC, (struct mkroom *) 0);
5385.     }
5386.     if (gn.num_lregions) {
5387.         /* realloc the lregion space to add the new one */
5388.         lev_region *newl = (lev_region *) alloc(
5389.             sizeof (lev_region) * (unsigned) (1 + gn.num_lregions));
5390. 
5391.         (void) memcpy((genericptr_t) (newl), (genericptr_t) gl.lregions,
5392.                       sizeof (lev_region) * gn.num_lregions);
5393.         Free(gl.lregions);
5394.         gn.num_lregions++;
5395.         gl.lregions = newl;
5396.     } else {
5397.         gn.num_lregions = 1;
5398.         gl.lregions = (lev_region *) alloc(sizeof (lev_region));
5399.     }
5400.     (void) memcpy(&gl.lregions[gn.num_lregions - 1], lregion,
5401.                   sizeof (lev_region));
5402. }
5403. 
5404. /* get params from topmost lua hash:
5405.    - region = {x1,y1,x2,y2}
5406.    - exclude = {x1,y1,x2,y2} (optional)
5407.    - region_islev=true, exclude_islev=true (optional)
5408.    - negative x and y are invalid */
5409. staticfn void
5410. l_get_lregion(lua_State *L, lev_region *tmplregion)
5411. {
5412.     lua_Integer x1,y1,x2,y2;
5413. 
5414.     get_table_region(L, "region", &x1, &y1, &x2, &y2, FALSE);
5415.     tmplregion->inarea.x1 = x1;
5416.     tmplregion->inarea.y1 = y1;
5417.     tmplregion->inarea.x2 = x2;
5418.     tmplregion->inarea.y2 = y2;
5419. 
5420.     x1 = y1 = x2 = y2 = -1;
5421.     get_table_region(L, "exclude", &x1, &y1, &x2, &y2, TRUE);
5422.     tmplregion->delarea.x1 = x1;
5423.     tmplregion->delarea.y1 = y1;
5424.     tmplregion->delarea.x2 = x2;
5425.     tmplregion->delarea.y2 = y2;
5426. 
5427.     tmplregion->in_islev = get_table_boolean_opt(L, "region_islev", 0);
5428.     tmplregion->del_islev = get_table_boolean_opt(L, "exclude_islev", 0);
5429. 
5430.     /* if x1 is still negative, exclude wasn't specified, so we should treat
5431.      * it as if there is no exclude region at all. Force exclude_islev to
5432.      * true so the -1,-1,-1,-1 region is safely off the map and won't
5433.      * interfere with branch or portal placement. */
5434.     if (x1 < 0)
5435.         tmplregion->del_islev = TRUE;
5436. }
5437. 
5438. /* teleport_region({ region = { x1,y1, x2,y2 } }); */
5439. /* teleport_region({ region = { x1,y1, x2,y2 }, [ region_islev = 1, ]
5440.  *   exclude = { x1,y1, x2,y2 }, [ exclude_islen = 1, ] [ dir = "up" ] }); */
5441. /* TODO: maybe allow using selection, with a new method "getextents()"? */
5442. int
5443. lspo_teleport_region(lua_State *L)
5444. {
5445.     static const char *const teledirs[] = { "both", "down", "up", NULL };
5446.     static const int teledirs2i[] = { LR_TELE, LR_DOWNTELE, LR_UPTELE, -1 };
5447.     lev_region tmplregion;
5448. 
5449.     create_des_coder();
5450.     lcheck_param_table(L);
5451.     l_get_lregion(L, &tmplregion);
5452.     tmplregion.rtype = teledirs2i[get_table_option(L, "dir", "both",
5453.                                                    teledirs)];
5454.     tmplregion.padding = 0;
5455.     tmplregion.rname.str = NULL;
5456. 
5457.     levregion_add(&tmplregion);
5458. 
5459.     return 0;
5460. }
5461. 
5462. /* TODO: FIXME
5463.    from lev_comp SPO_LEVREGION was called as:
5464.    - STAIR:(x1,y1,x2,y2),(x1,y1,x2,y2),dir
5465.    - PORTAL:(x1,y1,x2,y2),(x1,y1,x2,y2),string
5466.    - BRANCH:(x1,y1,x2,y2),(x1,y1,x2,y2),dir
5467. */
5468. /* levregion({ region = { x1,y1, x2,y2 }, exclude = { x1,y1, x2,y2 },
5469.  *             type = "portal", name="air" }); */
5470. /* TODO: allow region to be optional, defaulting to whole level */
5471. int
5472. lspo_levregion(lua_State *L)
5473. {
5474.     static const char *const regiontypes[] = {
5475.         "stair-down", "stair-up", "portal", "branch",
5476.         "teleport", "teleport-up", "teleport-down", NULL
5477.     };
5478.     static const int regiontypes2i[] = {
5479.         LR_DOWNSTAIR, LR_UPSTAIR, LR_PORTAL, LR_BRANCH,
5480.         LR_TELE, LR_UPTELE, LR_DOWNTELE, 0
5481.     };
5482.     lev_region tmplregion;
5483. 
5484.     create_des_coder();
5485.     lcheck_param_table(L);
5486.     l_get_lregion(L, &tmplregion);
5487.     tmplregion.rtype = regiontypes2i[get_table_option(L, "type", "stair-down",
5488.                                                       regiontypes)];
5489.     tmplregion.padding = get_table_int_opt(L, "padding", 0);
5490.     tmplregion.rname.str = get_table_str_opt(L, "name", NULL);
5491. 
5492.     levregion_add(&tmplregion);
5493.     return 0;
5494. }
5495. 
5496. /* exclusion({ type = "teleport", region = { x1,y1, x2,y2 } }); */
5497. int
5498. lspo_exclusion(lua_State *L)
5499. {
5500.     static const char *const ez_types[] = {
5501.         "teleport", "teleport-up", "teleport-down", "monster-generation", NULL
5502.     };
5503.     static const int ez_types2i[] = {
5504.         LR_TELE, LR_UPTELE, LR_DOWNTELE, LR_MONGEN, 0
5505.     };
5506.     struct exclusion_zone *ez = (struct exclusion_zone *) alloc(sizeof *ez);
5507.     lua_Integer x1,y1,x2,y2;
5508.     coordxy a1,b1,a2,b2;
5509. 
5510.     create_des_coder();
5511.     lcheck_param_table(L);
5512.     ez->zonetype = ez_types2i[get_table_option(L, "type", "teleport",
5513.                                                       ez_types)];
5514.     get_table_region(L, "region", &x1, &y1, &x2, &y2, FALSE);
5515. 
5516.     a1 = x1, b1 = y1;
5517.     a2 = x2, b2 = y2;
5518. 
5519.     get_location_coord(&a1, &b1, ANY_LOC|NO_LOC_WARN, gc.coder->croom,
5520.                        SP_COORD_PACK(a1, b1));
5521.     get_location_coord(&a2, &b2, ANY_LOC|NO_LOC_WARN, gc.coder->croom,
5522.                        SP_COORD_PACK(a2, b2));
5523. 
5524.     ez->lx = a1;
5525.     ez->ly = b1;
5526.     ez->hx = a2;
5527.     ez->hy = b2;
5528. 
5529.     ez->next = sve.exclusion_zones;
5530.     sve.exclusion_zones = ez;
5531.     return 0;
5532. }
5533. 
5534. staticfn void
5535. sel_set_lit(coordxy x, coordxy y, genericptr_t arg)
5536. {
5537.      int lit = *(int *) arg;
5538. 
5539.      levl[x][y].lit = (IS_LAVA(levl[x][y].typ) || lit) ? 1 : 0;
5540. }
5541. 
5542. /* Add to the room any doors within/bordering it */
5543. staticfn void
5544. add_doors_to_room(struct mkroom *croom)
5545. {
5546.     coordxy x, y;
5547.     int i;
5548. 
5549.     for (x = croom->lx - 1; x <= croom->hx + 1; x++)
5550.         for (y = croom->ly - 1; y <= croom->hy + 1; y++)
5551.             if (IS_DOOR(levl[x][y].typ) || levl[x][y].typ == SDOOR)
5552.                 maybe_add_door(x, y, croom);
5553.     for (i = 0; i < croom->nsubrooms; i++)
5554.         add_doors_to_room(croom->sbrooms[i]);
5555. }
5556. 
5557. DISABLE_WARNING_UNREACHABLE_CODE
5558. 
5559. /* inside a lua table, get fields x1,y1,x2,y2 or region table */
5560. staticfn void
5561. get_table_coords_or_region(lua_State *L,
5562.                            coordxy *dx1, coordxy *dy1,
5563.                            coordxy *dx2, coordxy *dy2)
5564. {
5565.     *dx1 = get_table_int_opt(L, "x1", -1);
5566.     *dy1 = get_table_int_opt(L, "y1", -1);
5567.     *dx2 = get_table_int_opt(L, "x2", -1);
5568.     *dy2 = get_table_int_opt(L, "y2", -1);
5569. 
5570.     if (*dx1 == -1 && *dy1 == -1 && *dx2 == -1 && *dy2 == -1) {
5571.         lua_Integer rx1, ry1, rx2, ry2;
5572. 
5573.         get_table_region(L, "region", &rx1, &ry1, &rx2, &ry2, FALSE);
5574.         *dx1 = rx1; *dy1 = ry1;
5575.         *dx2 = rx2; *dy2 = ry2;
5576.     }
5577. }
5578. 
5579. /* region(selection, lit); */
5580. /* region({ x1=NN, y1=NN, x2=NN, y2=NN, lit=BOOL, type=ROOMTYPE, joined=BOOL,
5581.  *          irregular=BOOL, filled=NN [ , contents = FUNCTION ] }); */
5582. /* region({ region={x1,y1, x2,y2}, type="ordinary" }); */
5583. int
5584. lspo_region(lua_State *L)
5585. {
5586.     coordxy dx1, dy1, dx2, dy2;
5587.     struct mkroom *troom;
5588.     boolean do_arrival_room = FALSE, room_not_needed,
5589.             irregular = FALSE, joined = TRUE;
5590.     int rtype = OROOM, rlit = 1, needfill = 0;
5591.     int argc = lua_gettop(L);
5592. 
5593.     create_des_coder();
5594. 
5595.     if (argc <= 1) {
5596.         lcheck_param_table(L);
5597. 
5598.         /* TODO: "unfilled" => filled=0, "filled" => filled=1, and
5599.          * "lvflags_only" => filled=2, probably in a get_table_needfill_opt */
5600.         needfill = get_table_int_opt(L, "filled", 0);
5601.         irregular = get_table_boolean_opt(L, "irregular", 0);
5602.         joined = get_table_boolean_opt(L, "joined", TRUE);
5603.         do_arrival_room = get_table_boolean_opt(L, "arrival_room", 0);
5604.         rtype = get_table_roomtype_opt(L, "type", OROOM);
5605.         rlit = get_table_int_opt(L, "lit", -1);
5606. 
5607.         get_table_coords_or_region(L, &dx1, &dy1, &dx2, &dy2);
5608. 
5609.         if (dx1 == -1 && dy1 == -1 && dx2 == -1 && dy2 == -1) {
5610.             nhl_error(L, "region needs region");
5611.         }
5612. 
5613.     } else if (argc == 2) {
5614.         /* region(selection, "lit"); */
5615.         static const char *const lits[] = { "unlit", "lit", NULL };
5616.         struct selectionvar *orig = l_selection_check(L, 1),
5617.                             *sel = selection_clone(orig);
5618. 
5619.         rlit = luaL_checkoption(L, 2, "lit", lits);
5620. 
5621.         /*
5622.     TODO: lit=random
5623.         */
5624.         if (rlit)
5625.             selection_do_grow(sel, W_ANY);
5626.         selection_iterate(sel, sel_set_lit, (genericptr_t) &rlit);
5627. 
5628.         selection_free(sel, TRUE);
5629. 
5630.         /* TODO: skip the rest of this function? */
5631.         return 0;
5632.     } else {
5633.         nhl_error(L, "Wrong parameters");
5634.         /*NOTREACHED*/
5635.         return 0;
5636.     }
5637. 
5638.     rlit = litstate_rnd(rlit);
5639. 
5640.     get_location(&dx1, &dy1, ANY_LOC, (struct mkroom *) 0);
5641.     get_location(&dx2, &dy2, ANY_LOC, (struct mkroom *) 0);
5642. 
5643.     /* Many regions are simple, rectangular areas that just need to set
5644.      * lighting in an area. In that case, we don't need to do anything
5645.      * complicated by creating a room. The exceptions are:
5646.      *  - Special rooms (which usually need to be filled).
5647.      *  - Irregular regions (more convenient to use the room-making code).
5648.      *  - Themed room regions (which often have contents).
5649.      *  - When a room is desired to constrain the arrival of migrating
5650.      *    monsters (see the mon_arrive function for details).
5651.      */
5652.     room_not_needed = (rtype == OROOM && !irregular
5653.                        && !do_arrival_room && !gi.in_mk_themerooms);
5654.     if (room_not_needed || svn.nroom >= MAXNROFROOMS) {
5655.         region tmpregion;
5656.         if (!room_not_needed)
5657.             impossible("Too many rooms on new level!");
5658.         tmpregion.rlit = rlit;
5659.         tmpregion.x1 = dx1;
5660.         tmpregion.y1 = dy1;
5661.         tmpregion.x2 = dx2;
5662.         tmpregion.y2 = dy2;
5663.         light_region(&tmpregion);
5664. 
5665.         return 0;
5666.     }
5667. 
5668.     troom = &svr.rooms[svn.nroom];
5669. 
5670.     /* mark rooms that must be filled, but do it later */
5671.     troom->needfill = needfill;
5672. 
5673.     troom->needjoining = joined;
5674. 
5675.     if (irregular) {
5676.         gm.min_rx = gm.max_rx = dx1;
5677.         gm.min_ry = gm.max_ry = dy1;
5678.         gs.smeq[svn.nroom] = svn.nroom;
5679.         flood_fill_rm(dx1, dy1, svn.nroom + ROOMOFFSET, rlit, TRUE);
5680.         add_room(gm.min_rx, gm.min_ry, gm.max_rx, gm.max_ry, FALSE, rtype,
5681.                  TRUE);
5682.         troom->rlit = rlit;
5683.         troom->irregular = TRUE;
5684.     } else {
5685.         add_room(dx1, dy1, dx2, dy2, rlit, rtype, TRUE);
5686. #ifdef SPECIALIZATION
5687.         topologize(troom, FALSE); /* set roomno */
5688. #else
5689.         topologize(troom); /* set roomno */
5690. #endif
5691.     }
5692. 
5693.     if (!room_not_needed) {
5694.         if (gc.coder->n_subroom > 1) {
5695.             impossible("region as subroom");
5696.         } else {
5697.             gc.coder->tmproomlist[gc.coder->n_subroom] = troom;
5698.             gc.coder->failed_room[gc.coder->n_subroom] = FALSE;
5699.             gc.coder->n_subroom++;
5700.             update_croom();
5701.             lua_getfield(L, 1, "contents");
5702.             if (lua_type(L, -1) == LUA_TFUNCTION) {
5703.                 lua_remove(L, -2);
5704.                 l_push_mkroom_table(L, troom);
5705.                 nhl_pcall_handle(L, 1, 0, "lspo_region", NHLpa_panic);
5706.             } else {
5707.                 lua_pop(L, 1);
5708.             }
5709.             spo_endroom(gc.coder);
5710.             add_doors_to_room(troom);
5711.         }
5712.     }
5713. 
5714.     return 0;
5715. }
5716. 
5717. /* drawbridge({ dir="east", state="closed", x=05,y=08 }); */
5718. /* drawbridge({ dir="east", state="closed", coord={05,08} }); */
5719. int
5720. lspo_drawbridge(lua_State *L)
5721. {
5722.     static const char *const mwdirs[] = {
5723.         "north", "south", "west", "east", "random", NULL
5724.     };
5725.     static const int mwdirs2i[] = {
5726.         DB_NORTH, DB_SOUTH, DB_WEST, DB_EAST, -1, -2
5727.     };
5728.     static const char *const dbopens[] = {
5729.         "open", "closed", "random", NULL
5730.     };
5731.     static const int dbopens2i[] = { 1, 0, -1, -2 };
5732.     coordxy x, y;
5733.     lua_Integer mx, my;
5734.     int dir;
5735.     int db_open;
5736.     long dcoord;
5737. 
5738.     create_des_coder();
5739. 
5740.     lcheck_param_table(L);
5741. 
5742.     get_table_xy_or_coord(L, &mx, &my);
5743. 
5744.     dir = mwdirs2i[get_table_option(L, "dir", "random", mwdirs)];
5745.     dcoord = SP_COORD_PACK(mx, my);
5746.     db_open = dbopens2i[get_table_option(L, "state", "random", dbopens)];
5747.     x = mx;
5748.     y = my;
5749. 
5750.     get_location_coord(&x, &y, DRY | WET | HOT, gc.coder->croom, dcoord);
5751.     if (!isok(mx, my)) {
5752.         nhl_error(L, "drawbridge coord not ok");
5753.         /*NOTREACHED*/
5754.         return 0;
5755.     }
5756.     if (db_open == -1)
5757.         db_open = !rn2(2);
5758.     if (!create_drawbridge(x, y, dir, db_open ? TRUE : FALSE))
5759.         impossible("Cannot create drawbridge.");
5760.     SpLev_Map[x][y] = 1;
5761. 
5762.     return 0;
5763. }
5764. 
5765. /* mazewalk({ x = NN, y = NN, typ = ".", dir = "north", stocked = 0 }); */
5766. /* mazewalk({ coord = {XX, YY}, typ = ".", dir = "north", stocked = 0 }); */
5767. /* mazewalk(x,y,dir); */
5768. int
5769. lspo_mazewalk(lua_State *L)
5770. {
5771.     static const char *const mwdirs[] = {
5772.         "north", "south", "east", "west", "random", NULL
5773.     };
5774.     static const int mwdirs2i[] = {
5775.         W_NORTH, W_SOUTH, W_EAST, W_WEST, W_RANDOM, -2
5776.     };
5777.     coordxy x, y;
5778.     lua_Integer mx, my;
5779.     coordxy ftyp = ROOM;
5780.     int fstocked = 1, dir = -1;
5781.     long mcoord;
5782.     int argc = lua_gettop(L);
5783. 
5784.     create_des_coder();
5785. 
5786.     if (argc == 3) {
5787.         mx = luaL_checkinteger(L, 1);
5788.         my = luaL_checkinteger(L, 2);
5789.         dir = mwdirs2i[luaL_checkoption(L, 3, "random", mwdirs)];
5790.     } else {
5791.         lcheck_param_table(L);
5792. 
5793.         get_table_xy_or_coord(L, &mx, &my);
5794.         ftyp = get_table_mapchr_opt(L, "typ", ROOM);
5795.         fstocked = get_table_boolean_opt(L, "stocked", 1);
5796.         dir = mwdirs2i[get_table_option(L, "dir", "random", mwdirs)];
5797.     }
5798. 
5799.     mcoord = SP_COORD_PACK(mx, my);
5800.     x = mx;
5801.     y = my;
5802. 
5803.     get_location_coord(&x, &y, ANY_LOC, gc.coder->croom, mcoord);
5804. 
5805.     if (!isok(x, y)) {
5806.         nhl_error(L, "mazewalk coord not ok");
5807.         /*NOTREACHED*/
5808.         return 0;
5809.     }
5810. 
5811.     if (ftyp < 1) {
5812.         ftyp = svl.level.flags.corrmaze ? CORR : ROOM;
5813.     }
5814. 
5815.     if (dir == W_RANDOM)
5816.         dir = random_wdir();
5817. 
5818.     /* don't use move() - it doesn't use W_NORTH, etc. */
5819.     switch (dir) {
5820.     case W_NORTH:
5821.         --y;
5822.         break;
5823.     case W_SOUTH:
5824.         y++;
5825.         break;
5826.     case W_EAST:
5827.         x++;
5828.         break;
5829.     case W_WEST:
5830.         --x;
5831.         break;
5832.     default:
5833.         impossible("mazewalk: Bad direction");
5834.     }
5835. 
5836.     if (!IS_DOOR(levl[x][y].typ)) {
5837.         levl[x][y].typ = ftyp;
5838.         levl[x][y].flags = 0;
5839.     }
5840. 
5841.     /*
5842.      * We must be sure that the parity of the coordinates for
5843.      * walkfrom() is odd.  But we must also take into account
5844.      * what direction was chosen.
5845.      */
5846.     if (!(x % 2)) {
5847.         if (dir == W_EAST)
5848.             x++;
5849.         else
5850.             x--;
5851. 
5852.         /* no need for IS_DOOR check; out of map bounds */
5853.         levl[x][y].typ = ftyp;
5854.         levl[x][y].flags = 0;
5855.     }
5856. 
5857.     if (!(y % 2)) {
5858.         if (dir == W_SOUTH)
5859.             y++;
5860.         else
5861.             y--;
5862.     }
5863. 
5864.     walkfrom(x, y, ftyp);
5865.     if (fstocked)
5866.         fill_empty_maze();
5867. 
5868.     return 0;
5869. }
5870. 
5871. RESTORE_WARNING_UNREACHABLE_CODE
5872. 
5873. /* wall_property({ x1=0, y1=0, x2=78, y2=20, property="nondiggable" }); */
5874. /* wall_property({ region = {1,0, 78,20}, property="nonpasswall" }); */
5875. int
5876. lspo_wall_property(lua_State *L)
5877. {
5878.     static const char *const wprops[] = {
5879.         "nondiggable", "nonpasswall", NULL
5880.     };
5881.     static const int wprop2i[] = { W_NONDIGGABLE, W_NONPASSWALL, -1 };
5882.     coordxy dx1 = -1, dy1 = -1, dx2 = -1, dy2 = -1;
5883.     int wprop;
5884. 
5885.     create_des_coder();
5886. 
5887.     lcheck_param_table(L);
5888. 
5889.     get_table_coords_or_region(L, &dx1, &dy1, &dx2, &dy2);
5890. 
5891.     wprop = wprop2i[get_table_option(L, "property", "nondiggable", wprops)];
5892. 
5893.     if (dx1 == -1)
5894.         dx1 = gx.xstart - 1;
5895.     if (dy1 == -1)
5896.         dy1 = gy.ystart - 1;
5897.     if (dx2 == -1)
5898.         dx2 = gx.xstart + gx.xsize + 1;
5899.     if (dy2 == -1)
5900.         dy2 = gy.ystart + gy.ysize + 1;
5901. 
5902.     get_location(&dx1, &dy1, ANY_LOC, (struct mkroom *) 0);
5903.     get_location(&dx2, &dy2, ANY_LOC, (struct mkroom *) 0);
5904. 
5905.     set_wall_property(dx1, dy1, dx2, dy2, wprop);
5906. 
5907.     return 0;
5908. }
5909. 
5910. staticfn void
5911. set_wallprop_in_selection(lua_State *L, int prop)
5912. {
5913.     int argc = lua_gettop(L);
5914.     boolean freesel = FALSE;
5915.     struct selectionvar *sel = (struct selectionvar *) 0;
5916. 
5917.     create_des_coder();
5918. 
5919.     if (argc == 1) {
5920.         sel = l_selection_check(L, -1);
5921.     } else if (argc == 0) {
5922.         freesel = TRUE;
5923.         sel = selection_new();
5924.         selection_clear(sel, 1);
5925.     }
5926. 
5927.     if (sel) {
5928.         selection_iterate(sel, sel_set_wall_property, (genericptr_t) &prop);
5929.         if (freesel)
5930.             selection_free(sel, TRUE);
5931.     }
5932. }
5933. 
5934. /* non_diggable(selection); */
5935. /* non_diggable(); */
5936. int
5937. lspo_non_diggable(lua_State *L)
5938. {
5939.     set_wallprop_in_selection(L, W_NONDIGGABLE);
5940.     return 0;
5941. }
5942. 
5943. /* non_passwall(selection); */
5944. /* non_passwall(); */
5945. int
5946. lspo_non_passwall(lua_State *L)
5947. {
5948.     set_wallprop_in_selection(L, W_NONPASSWALL);
5949.     return 0;
5950. }
5951. 
5952. #if 0
5953. /*ARGSUSED*/
5954. staticfn void
5955. sel_set_wallify(coordxy x, coordxy y, genericptr_t arg UNUSED)
5956. {
5957.     wallify_map(x, y, x, y);
5958. }
5959. #endif
5960. 
5961. /* TODO: wallify(selection) */
5962. /* wallify({ x1=NN,y1=NN, x2=NN,y2=NN }); */
5963. /* wallify(); */
5964. int
5965. lspo_wallify(lua_State *L)
5966. {
5967.     int dx1 = -1, dy1 = -1, dx2 = -1, dy2 = -1;
5968. 
5969.     /* TODO: clamp coord values */
5970.     /* TODO: maybe allow wallify({x1,y1}, {x2,y2}) */
5971.     /* TODO: is_table_coord(), is_table_area(),
5972.              get_table_coord(), get_table_area() */
5973. 
5974.     create_des_coder();
5975. 
5976.     if (lua_gettop(L) == 1) {
5977.         dx1 = get_table_int(L, "x1");
5978.         dy1 = get_table_int(L, "y1");
5979.         dx2 = get_table_int(L, "x2");
5980.         dy2 = get_table_int(L, "y2");
5981.     }
5982. 
5983.     wallify_map(dx1 < 0 ? (gx.xstart - 1) : dx1,
5984.                 dy1 < 0 ? (gy.ystart - 1) : dy1,
5985.                 dx2 < 0 ? (gx.xstart + gx.xsize + 1) : dx2,
5986.                 dy2 < 0 ? (gy.ystart + gy.ysize + 1) : dy2);
5987. 
5988.     return 0;
5989. }
5990. 
5991. /* reset_level is only needed for testing purposes */
5992. int
5993. lspo_reset_level(lua_State *L)
5994. {
5995.     boolean wtower = In_W_tower(u.ux, u.uy, &u.uz);
5996. 
5997.     iflags.lua_testing = TRUE;
5998.     if (L) {
5999.         if (gc.coder) {
6000.             Free(gc.coder);
6001.             gc.coder = NULL;
6002.         }
6003.         create_des_coder();
6004.     }
6005.     makemap_prepost(TRUE, wtower);
6006.     gi.in_mklev = TRUE;
6007.     oinit(); /* assign level dependent obj probabilities */
6008.     clear_level_structures();
6009.     return 0;
6010. }
6011. 
6012. /* finalize_level is only needed for testing purposes */
6013. int
6014. lspo_finalize_level(lua_State *L)
6015. {
6016.     boolean wtower = In_W_tower(u.ux, u.uy, &u.uz);
6017.     int i;
6018. 
6019.     if (L)
6020.         create_des_coder();
6021. 
6022.     link_doors_rooms();
6023.     remove_boundary_syms();
6024. 
6025.     /* TODO: ensure_way_out() needs rewrite */
6026.     if (L && gc.coder->check_inaccessibles)
6027.         ensure_way_out();
6028. 
6029.     map_cleanup();
6030. 
6031.     /* FIXME: Ideally, we want this call to only cover areas of the map
6032.      * which were not inserted directly by the special level file (see
6033.      * the insect legs on Baalzebub's level, for instance). Since that
6034.      * is currently not possible, we overload the corrmaze flag for this
6035.      * purpose.
6036.      */
6037.     if (!svl.level.flags.corrmaze)
6038.         wallification(1, 0, COLNO - 1, ROWNO - 1);
6039. 
6040.     if (L)
6041.         flip_level_rnd(gc.coder->allow_flips, FALSE);
6042. 
6043.     count_level_features();
6044. 
6045.     if (L && gc.coder->solidify)
6046.         solidify_map();
6047. 
6048.     /* This must be done before premap_detect(),
6049.      * otherwise branch stairs won't be premapped. */
6050.     fixup_special();
6051. 
6052.     if (L && gc.coder->premapped)
6053.         premap_detect();
6054. 
6055.     level_finalize_topology();
6056. 
6057.     for (i = 0; i < svn.nroom; ++i) {
6058.         fill_special_room(&svr.rooms[i]);
6059.     }
6060. 
6061.     makemap_prepost(FALSE, wtower);
6062.     iflags.lua_testing = FALSE;
6063.     return 0;
6064. }
6065. 
6066. DISABLE_WARNING_UNREACHABLE_CODE
6067. 
6068. /* map({ x = 10, y = 10, map = ... }); */
6069. /* map({ coord = {10, 10}, map = ... }); */
6070. /* map({ halign = "center", valign = "center", map = ... }); */
6071. /* map({ map = ..., contents = function(map) ... end }); */
6072. /* map(...) */
6073. /* local selection = map( ... ); */
6074. int
6075. lspo_map(lua_State *L)
6076. {
6077.     /*
6078. TODO: allow passing an array of strings as map data
6079. TODO: handle if map lines aren't same length
6080. TODO: gc.coder->croom needs to be updated
6081.      */
6082. 
6083.     static const char *const left_or_right[] = {
6084.         "left", "half-left", "center", "half-right", "right", "none", NULL
6085.     };
6086.     static const int l_or_r2i[] = {
6087.         SPLEV_LEFT, SPLEV_H_LEFT, SPLEV_CENTER, SPLEV_H_RIGHT,
6088.         SPLEV_RIGHT, -1, -1
6089.     };
6090.     static const char *const top_or_bot[] = {
6091.         "top", "center", "bottom", "none", NULL
6092.     };
6093.     static const int t_or_b2i[] = { TOP, SPLEV_CENTER, BOTTOM, -1, -1 };
6094.     int lr, tb;
6095.     lua_Integer x = -1, y = -1;
6096.     struct mapfragment *mf;
6097.     char *tmpstr;
6098.     int argc = lua_gettop(L);
6099.     boolean has_contents = FALSE;
6100.     int tryct = 0;
6101.     int ox, oy;
6102.     boolean lit = FALSE;
6103.     struct selectionvar *sel;
6104. 
6105.     create_des_coder();
6106. 
6107.     if (gi.in_mk_themerooms && gt.themeroom_failed)
6108.         return 0;
6109. 
6110.     if (argc == 1 && lua_type(L, 1) == LUA_TSTRING) {
6111.         tmpstr = dupstr(luaL_checkstring(L, 1));
6112.         lr = tb = SPLEV_CENTER;
6113.         mf = mapfrag_fromstr(tmpstr);
6114.         free(tmpstr);
6115.     } else {
6116.         lcheck_param_table(L);
6117.         lr = l_or_r2i[get_table_option(L, "halign", "none", left_or_right)];
6118.         tb = t_or_b2i[get_table_option(L, "valign", "none", top_or_bot)];
6119.         get_table_xy_or_coord(L, &x, &y);
6120.         tmpstr = get_table_str(L, "map");
6121.         lit = (boolean) get_table_boolean_opt(L, "lit", FALSE);
6122.         lua_getfield(L, 1, "contents");
6123.         if (lua_type(L, -1) == LUA_TFUNCTION) {
6124.             lua_remove(L, -2);
6125.             has_contents = TRUE;
6126.         } else {
6127.             lua_pop(L, 1);
6128.         }
6129.         mf = mapfrag_fromstr(tmpstr);
6130.         free(tmpstr);
6131.     }
6132. 
6133.     if (!mf) {
6134.         nhl_error(L, "Map data error");
6135.         /*NOTREACHED*/
6136.         return 0;
6137.     }
6138. 
6139.     sel = selection_new();
6140.     ox = x;
6141.     oy = y;
6142.  redo_maploc:
6143.     gx.xsize = mf->wid;
6144.     gy.ysize = mf->hei;
6145. 
6146.     if (lr == -1 && tb == -1) {
6147.         if (gi.in_mk_themerooms && (ox == -1 || oy == -1)) {
6148.             if (ox == -1) {
6149.                 if (gc.coder->croom) {
6150.                     x = somex(gc.coder->croom) - mf->wid;
6151.                     if (x < 1)
6152.                         x = 1;
6153.                 } else {
6154.                     x = 1 + rn2(COLNO - 1 - mf->wid);
6155.                 }
6156.             }
6157. 
6158.             if (oy == -1) {
6159.                 if (gc.coder->croom) {
6160.                     y = somey(gc.coder->croom) - mf->hei;
6161.                     if (y < 1)
6162.                         y = 1;
6163.                 } else {
6164.                     y = rn2(ROWNO - mf->hei);
6165.                 }
6166.             }
6167.         }
6168. 
6169.         if (isok(x, y)) {
6170.             /* x,y is given, place map starting at x,y */
6171.             if (gc.coder->croom) {
6172.                 /* in a room? adjust to room relative coords */
6173.                 gx.xstart = x + gc.coder->croom->lx;
6174.                 gy.ystart = y + gc.coder->croom->ly;
6175.                 gx.xsize = min(mf->wid,
6176.                               (gc.coder->croom->hx - gc.coder->croom->lx));
6177.                 gy.ysize = min(mf->hei,
6178.                               (gc.coder->croom->hy - gc.coder->croom->ly));
6179.             } else {
6180.                 gx.xsize = mf->wid;
6181.                 gy.ysize = mf->hei;
6182.                 gx.xstart = x;
6183.                 gy.ystart = y;
6184.             }
6185.         } else {
6186.             mapfrag_free(&mf);
6187.             nhl_error(L, "Map requires either x,y or halign,valign params");
6188.             selection_free(sel, TRUE);
6189.             return 0;
6190.         }
6191.     } else {
6192.         /* place map starting at halign,valign */
6193.         switch (lr) {
6194.         case SPLEV_LEFT:
6195.             gx.xstart = splev_init_present ? 1 : 3;
6196.             break;
6197.         case SPLEV_H_LEFT:
6198.             gx.xstart = 2 + ((gx.x_maze_max - 2 - gx.xsize) / 4);
6199.             break;
6200.         case SPLEV_CENTER:
6201.             gx.xstart = 2 + ((gx.x_maze_max - 2 - gx.xsize) / 2);
6202.             break;
6203.         case SPLEV_H_RIGHT:
6204.             gx.xstart = 2 + ((gx.x_maze_max - 2 - gx.xsize) * 3 / 4);
6205.             break;
6206.         case SPLEV_RIGHT:
6207.             gx.xstart = gx.x_maze_max - gx.xsize - 1;
6208.             break;
6209.         }
6210.         switch (tb) {
6211.         case TOP:
6212.             gy.ystart = 3;
6213.             break;
6214.         case SPLEV_CENTER:
6215.             gy.ystart = 2 + ((gy.y_maze_max - 2 - gy.ysize) / 2);
6216.             break;
6217.         case BOTTOM:
6218.             gy.ystart = gy.y_maze_max - gy.ysize - 1;
6219.             break;
6220.         }
6221.         if (!(gx.xstart % 2))
6222.             gx.xstart++;
6223.         if (!(gy.ystart % 2))
6224.             gy.ystart++;
6225.     }
6226. 
6227.     if (gy.ystart < 0 || gy.ystart + gy.ysize > ROWNO) {
6228.         if (gi.in_mk_themerooms) {
6229.             gt.themeroom_failed = TRUE;
6230.             goto skipmap;
6231.         }
6232.         /* try to move the start a bit */
6233.         gy.ystart += (gy.ystart > 0) ? -2 : 2;
6234.         if (gy.ysize == ROWNO)
6235.             gy.ystart = 0;
6236.         if (gy.ystart < 0 || gy.ystart + gy.ysize > ROWNO)
6237.             gy.ystart = 0;
6238.     }
6239.     if (gx.xsize <= 1 && gy.ysize <= 1) {
6240.         reset_xystart_size();
6241.     } else {
6242.         coordxy mptyp;
6243.         terrain terr;
6244. 
6245.         /* Themed rooms should never overwrite anything */
6246.         if (gi.in_mk_themerooms) {
6247.             boolean isokp = TRUE;
6248.             for (y = gy.ystart - 1;
6249.                  y < min(ROWNO, gy.ystart + gy.ysize) + 1; y++)
6250.                 for (x = gx.xstart - 1;
6251.                      x < min(COLNO, gx.xstart + gx.xsize) + 1; x++) {
6252.                     if (!isok(x, y)) {
6253.                         isokp = FALSE;
6254.                     } else if (y < gy.ystart || y >= (gy.ystart + gy.ysize)
6255.                             || x < gx.xstart || x >= (gx.xstart + gx.xsize)) {
6256.                         if (levl[x][y].typ != STONE
6257.                             || levl[x][y].roomno != NO_ROOM)
6258.                             isokp = FALSE;
6259.                     } else {
6260.                         mptyp = mapfrag_get(mf, x - gx.xstart, y - gy.ystart);
6261.                         if (mptyp >= MAX_TYPE)
6262.                             continue;
6263.                         if ((levl[x][y].typ != STONE
6264.                              && levl[x][y].typ != mptyp)
6265.                             || levl[x][y].roomno != NO_ROOM)
6266.                             isokp = FALSE;
6267.                     }
6268.                     if (!isokp) {
6269.                         if (tryct++ < 100 && (lr == -1 || tb == -1))
6270.                             goto redo_maploc;
6271.                         gt.themeroom_failed = TRUE;
6272.                         goto skipmap;
6273.                     }
6274.                 }
6275.         }
6276. 
6277.         /* Load the map */
6278.         for (y = gy.ystart; y < min(ROWNO, gy.ystart + gy.ysize); y++)
6279.             for (x = gx.xstart; x < min(COLNO, gx.xstart + gx.xsize); x++) {
6280.                 mptyp = mapfrag_get(mf, (x - gx.xstart), (y - gy.ystart));
6281.                 if (mptyp == INVALID_TYPE) {
6282.                     /* TODO: warn about illegal map char */
6283.                     continue;
6284.                 }
6285.                 if (mptyp >= MAX_TYPE)
6286.                     continue;
6287.                 /* clear out levl: load_common_data may set them */
6288.                 levl[x][y].flags = 0;
6289.                 levl[x][y].horizontal = 0;
6290.                 levl[x][y].roomno = 0;
6291.                 levl[x][y].edge = 0;
6292.                 SpLev_Map[x][y] = 1;
6293.                 selection_setpoint(x, y, sel, 1);
6294.                 terr.ter = mptyp;
6295.                 terr.tlit = lit;
6296.                 sel_set_ter(x, y, &terr);
6297.             }
6298.     }
6299. 
6300.  skipmap:
6301.     mapfrag_free(&mf);
6302. 
6303.     if (gi.in_mk_themerooms && gt.themeroom_failed) {
6304.         /* this mutated xstart and ystart in the process of trying to make a
6305.          * themed room, so undo them */
6306.         reset_xystart_size();
6307.     }
6308.     else if (has_contents) {
6309.         l_push_wid_hei_table(L, gx.xsize, gy.ysize);
6310.         nhl_pcall_handle(L, 1, 0, "lspo_map", NHLpa_panic);
6311.         reset_xystart_size();
6312.     }
6313. 
6314.     /* return selection where map locations were put */
6315.     l_selection_push_copy(L, sel);
6316.     selection_free(sel, TRUE);
6317. 
6318.     return 1;
6319. }
6320. 
6321. RESTORE_WARNING_UNREACHABLE_CODE
6322. 
6323. void
6324. update_croom(void)
6325. {
6326.     if (!gc.coder)
6327.         return;
6328. 
6329.     if (gc.coder->n_subroom)
6330.         gc.coder->croom = gc.coder->tmproomlist[gc.coder->n_subroom - 1];
6331.     else
6332.         gc.coder->croom = NULL;
6333. }
6334. 
6335. staticfn struct sp_coder *
6336. sp_level_coder_init(void)
6337. {
6338.     int tmpi;
6339.     struct sp_coder *coder = (struct sp_coder *) alloc(sizeof *coder);
6340. 
6341.     coder->premapped = FALSE;
6342.     coder->solidify = FALSE;
6343.     coder->check_inaccessibles = FALSE;
6344.     coder->allow_flips = 3; /* allow flipping level horiz/vert */
6345.     coder->croom = NULL;
6346.     coder->n_subroom = 1;
6347.     coder->lvl_is_joined = FALSE;
6348.     coder->room_stack = 0;
6349. 
6350.     splev_init_present = FALSE;
6351.     icedpools = FALSE;
6352. 
6353.     for (tmpi = 0; tmpi <= MAX_NESTED_ROOMS; tmpi++) {
6354.         coder->tmproomlist[tmpi] = (struct mkroom *) 0;
6355.         coder->failed_room[tmpi] = FALSE;
6356.     }
6357. 
6358.     update_croom();
6359. 
6360.     for (tmpi = 0; tmpi < MAX_CONTAINMENT; tmpi++)
6361.         container_obj[tmpi] = NULL;
6362.     container_idx = 0;
6363. 
6364.     invent_carrying_monster = NULL;
6365. 
6366.     (void) memset((genericptr_t) SpLev_Map, 0, sizeof SpLev_Map);
6367. 
6368.     svl.level.flags.is_maze_lev = 0;
6369.     svl.level.flags.temperature = In_hell(&u.uz) ? 1 : 0;
6370.     svl.level.flags.rndmongen = 1;
6371.     svl.level.flags.deathdrops = 1;
6372. 
6373.     reset_xystart_size();
6374. 
6375.     return coder;
6376. }
6377. 
6378. 
6379. static const struct luaL_Reg nhl_functions[] = {
6380.     { "message", lspo_message },
6381.     { "monster", lspo_monster },
6382.     { "object", lspo_object },
6383.     { "level_flags", lspo_level_flags },
6384.     { "level_init", lspo_level_init },
6385.     { "engraving", lspo_engraving },
6386.     { "mineralize", lspo_mineralize },
6387.     { "door", lspo_door },
6388.     { "stair", lspo_stair },
6389.     { "ladder", lspo_ladder },
6390.     { "grave", lspo_grave },
6391.     { "altar", lspo_altar },
6392.     { "map", lspo_map },
6393.     { "feature", lspo_feature },
6394.     { "terrain", lspo_terrain },
6395.     { "replace_terrain", lspo_replace_terrain },
6396.     { "room", lspo_room },
6397.     { "corridor", lspo_corridor },
6398.     { "random_corridors", lspo_random_corridors },
6399.     { "gold", lspo_gold },
6400.     { "trap", lspo_trap },
6401.     { "mazewalk", lspo_mazewalk },
6402.     { "drawbridge", lspo_drawbridge },
6403.     { "region", lspo_region },
6404.     { "levregion", lspo_levregion },
6405.     { "exclusion", lspo_exclusion },
6406.     { "wallify", lspo_wallify },
6407.     { "wall_property", lspo_wall_property },
6408.     { "non_diggable", lspo_non_diggable },
6409.     { "non_passwall", lspo_non_passwall },
6410.     { "teleport_region", lspo_teleport_region },
6411.     { "reset_level", lspo_reset_level },
6412.     { "finalize_level", lspo_finalize_level },
6413.     { "gas_cloud", lspo_gas_cloud },
6414.     /* TODO: { "branch", lspo_branch }, */
6415.     /* TODO: { "portal", lspo_portal }, */
6416.     { NULL, NULL }
6417. };
6418. 
6419. /* TODO:
6420. 
6421.  - if des-file used MAZE_ID to start a level, the level needs
6422.    des.level_flags("mazelevel")
6423.  - expose gc.coder->croom or gx.xstart gy.ystart and gx.xsize gy.ysize to lua.
6424.  - detect a "subroom" automatically.
6425.  - new function get_mapchar(x,y) to return the mapchar on map
6426.  - many params should accept their normal type (eg, int or bool), AND "random"
6427.  - automatically add shuffle(array)
6428.  - automatically add align = { "law", "neutral", "chaos" } and shuffle it.
6429.    (remove from lua files)
6430.  - grab the header comments from des-files and add them to the lua files
6431. 
6432. */
6433. 
6434. void
6435. l_register_des(lua_State *L)
6436. {
6437.     /* register des -table, and functions for it */
6438.     lua_newtable(L);
6439.     luaL_setfuncs(L, nhl_functions, 0);
6440.     lua_setglobal(L, "des");
6441. }
6442. 
6443. void
6444. create_des_coder(void)
6445. {
6446.     if (!gc.coder)
6447.         gc.coder = sp_level_coder_init();
6448. }
6449. 
6450. /*
6451.  * General loader
6452.  */
6453. boolean
6454. load_special(const char *name)
6455. {
6456.     boolean result = FALSE;
6457.     nhl_sandbox_info sbi = {NHL_SB_SAFE, 1*1024*1024, 0, 1*1024*1024};
6458. 
6459.     create_des_coder();
6460. 
6461.     if (!load_lua(name, &sbi))
6462.         goto give_up;
6463. 
6464.     link_doors_rooms();
6465.     remove_boundary_syms();
6466. 
6467.     /* TODO: ensure_way_out() needs rewrite */
6468.     if (gc.coder->check_inaccessibles)
6469.         ensure_way_out();
6470. 
6471.     map_cleanup();
6472. 
6473.     /* FIXME: Ideally, we want this call to only cover areas of the map
6474.      * which were not inserted directly by the special level file (see
6475.      * the insect legs on Baalzebub's level, for instance). Since that
6476.      * is currently not possible, we overload the corrmaze flag for this
6477.      * purpose.
6478.      */
6479.     if (!svl.level.flags.corrmaze)
6480.         wallification(1, 0, COLNO - 1, ROWNO - 1);
6481. 
6482.     flip_level_rnd(gc.coder->allow_flips, FALSE);
6483. 
6484.     count_level_features();
6485. 
6486.     if (gc.coder->solidify)
6487.         solidify_map();
6488. 
6489.     /* This must be done before premap_detect(),
6490.      * otherwise branch stairs won't be premapped. */
6491.     fixup_special();
6492. 
6493.     if (gc.coder->premapped)
6494.         premap_detect();
6495. 
6496.     result = TRUE;
6497.  give_up:
6498.     Free(gc.coder);
6499.     gc.coder = NULL;
6500. 
6501.     return result;
6502. }
6503. 
6504. /*sp_lev.c*/