Source:NetHack 5.0.0/src/mkobj.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to mkobj.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/mkobj.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	mkobj.c	$NHDT-Date: 1764044196 2025/11/24 20:16:36 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.326 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Derek S. Ray, 2015. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. 
8. staticfn boolean may_generate_eroded(struct obj *);
9. staticfn void mkobj_erosions(struct obj *);
10. staticfn void mkbox_cnts(struct obj *);
11. staticfn unsigned nextoid(struct obj *, struct obj *);
12. staticfn void mksobj_init(struct obj **, boolean);
13. staticfn int item_on_ice(struct obj *);
14. staticfn void shrinking_glob_gone(struct obj *);
15. staticfn void obj_timer_checks(struct obj *, coordxy, coordxy, int);
16. staticfn void dealloc_obj_real(struct obj *);
17. staticfn struct obj *save_mtraits(struct obj *, struct monst *);
18. staticfn void objlist_sanity(struct obj *, int, const char *);
19. staticfn void shop_obj_sanity(struct obj *, const char *);
20. staticfn void mon_obj_sanity(struct monst *, const char *);
21. staticfn void insane_obj_bits(struct obj *, struct monst *);
22. staticfn boolean nomerge_exception(struct obj *);
23. staticfn const char *where_name(struct obj *);
24. staticfn void insane_object(struct obj *, const char *, const char *,
25.                           struct monst *);
26. staticfn void check_contained(struct obj *, const char *);
27. staticfn void check_glob(struct obj *, const char *);
28. staticfn void sanity_check_worn(struct obj *);
29. staticfn void init_oextra(struct oextra *);
30. 
31. struct icp {
32.     int iprob;   /* probability of an item type */
33.     char iclass; /* item class */
34. };
35. 
36. static const struct icp mkobjprobs[] = { { 10, WEAPON_CLASS },
37.                                          { 11, ARMOR_CLASS },
38.                                          { 20, FOOD_CLASS },
39.                                          { 8, TOOL_CLASS },
40.                                          { 7, GEM_CLASS },
41.                                          { 16, POTION_CLASS },
42.                                          { 16, SCROLL_CLASS },
43.                                          { 4, SPBOOK_CLASS },
44.                                          { 4, WAND_CLASS },
45.                                          { 3, RING_CLASS },
46.                                          { 1, AMULET_CLASS } };
47. 
48. static const struct icp boxiprobs[] = { { 18, GEM_CLASS },
49.                                         { 15, FOOD_CLASS },
50.                                         { 18, POTION_CLASS },
51.                                         { 18, SCROLL_CLASS },
52.                                         { 12, SPBOOK_CLASS },
53.                                         { 7, COIN_CLASS },
54.                                         { 6, WAND_CLASS },
55.                                         { 5, RING_CLASS },
56.                                         { 1, AMULET_CLASS } };
57. 
58. static const struct icp rogueprobs[] = { { 12, WEAPON_CLASS },
59.                                          { 12, ARMOR_CLASS },
60.                                          { 22, FOOD_CLASS },
61.                                          { 22, POTION_CLASS },
62.                                          { 22, SCROLL_CLASS },
63.                                          { 5, WAND_CLASS },
64.                                          { 5, RING_CLASS } };
65. 
66. static const struct icp hellprobs[] = { { 20, WEAPON_CLASS },
67.                                         { 20, ARMOR_CLASS },
68.                                         { 16, FOOD_CLASS },
69.                                         { 12, TOOL_CLASS },
70.                                         { 10, GEM_CLASS },
71.                                         { 1, POTION_CLASS },
72.                                         { 1, SCROLL_CLASS },
73.                                         { 8, WAND_CLASS },
74.                                         { 8, RING_CLASS },
75.                                         { 4, AMULET_CLASS } };
76. 
77. static const struct oextra zerooextra = DUMMY;
78. 
79. staticfn void
80. init_oextra(struct oextra *oex)
81. {
82.     *oex = zerooextra;
83. }
84. 
85. struct oextra *
86. newoextra(void)
87. {
88.     struct oextra *oextra;
89. 
90.     oextra = (struct oextra *) alloc(sizeof (struct oextra));
91.     init_oextra(oextra);
92.     return oextra;
93. }
94. 
95. void
96. dealloc_oextra(struct obj *o)
97. {
98.     struct oextra *x = o->oextra;
99. 
100.     if (x) {
101.         if (x->oname)
102.             free((genericptr_t) x->oname), x->oname = 0;
103.         if (x->omonst)
104.             free_omonst(o); /* note: pass 'o' rather than 'x' */
105.         if (x->omailcmd)
106.             free((genericptr_t) x->omailcmd), x->omailcmd = 0;
107. 
108.         free((genericptr_t) x);
109.         o->oextra = (struct oextra *) 0;
110.     }
111. }
112. 
113. void
114. newomonst(struct obj *otmp)
115. {
116.     if (!otmp->oextra)
117.         otmp->oextra = newoextra();
118. 
119.     if (!OMONST(otmp)) {
120.         struct monst *m = newmonst();
121. 
122.         *m = cg.zeromonst;
123.         OMONST(otmp) = m;
124.     }
125. }
126. 
127. void
128. free_omonst(struct obj *otmp)
129. {
130.     if (otmp->oextra) {
131.         struct monst *m = OMONST(otmp);
132. 
133.         if (m) {
134.             if (m->mextra)
135.                 dealloc_mextra(m);
136.             free((genericptr_t) m);
137.             OMONST(otmp) = (struct monst *) 0;
138.         }
139.     }
140. }
141. 
142. void
143. newomid(struct obj *otmp)
144. {
145.     if (!otmp->oextra)
146.         otmp->oextra = newoextra();
147.     OMID(otmp) = 0;
148. }
149. 
150. void
151. free_omid(struct obj *otmp)
152. {
153.     OMID(otmp) = 0;
154. }
155. 
156. void
157. new_omailcmd(struct obj *otmp, const char *response_cmd)
158. {
159.     if (!otmp->oextra)
160.         otmp->oextra = newoextra();
161.     if (OMAILCMD(otmp))
162.         free_omailcmd(otmp);
163.     OMAILCMD(otmp) = dupstr(response_cmd);
164. }
165. 
166. void
167. free_omailcmd(struct obj *otmp)
168. {
169.     if (otmp->oextra && OMAILCMD(otmp)) {
170.         free((genericptr_t) OMAILCMD(otmp));
171.         OMAILCMD(otmp) = (char *) 0;
172.     }
173. }
174. 
175. /* can object be generated eroded? */
176. staticfn boolean
177. may_generate_eroded(struct obj *otmp)
178. {
179.     /* initial hero inventory */
180.     if (svm.moves <= 1 && !gi.in_mklev)
181.         return FALSE;
182.     /* already erodeproof or cannot be eroded */
183.     if (otmp->oerodeproof || !erosion_matters(otmp) || !is_damageable(otmp))
184.         return FALSE;
185.     /* part of a monster's body and produced when it dies */
186.     if (otmp->otyp == WORM_TOOTH || otmp->otyp == UNICORN_HORN)
187.         return FALSE;
188.     /* artifacts cannot be generated eroded  */
189.     if (otmp->oartifact)
190.         return FALSE;
191.     return TRUE;
192. }
193. 
194. /* random chance of applying erosions/grease to object */
195. staticfn void
196. mkobj_erosions(struct obj *otmp)
197. {
198.     if (may_generate_eroded(otmp)) {
199.         /* A small fraction of non-artifact items will generate eroded or
200.          * possibly erodeproof. An item that generates eroded will never be
201.          * erodeproof, and vice versa. */
202.         if (!rn2(100)) {
203.             otmp->oerodeproof = 1;
204.         } else {
205.             if (!rn2(80) && (is_flammable(otmp) || is_rustprone(otmp)
206.                              || is_crackable(otmp))) {
207.                 do {
208.                     otmp->oeroded++;
209.                 } while (otmp->oeroded < 3 && !rn2(9));
210.             }
211.             if (!rn2(80) && (is_rottable(otmp) || is_corrodeable(otmp))) {
212.                 do {
213.                     otmp->oeroded2++;
214.                 } while (otmp->oeroded2 < 3 && !rn2(9));
215.             }
216.         }
217.         /* and an extremely small fraction of the time, erodable items
218.          * will generate greased */
219.         if (!rn2(1000))
220.             otmp->greased = 1;
221.     }
222. }
223. 
224. /* make a random object of class 'let' at a specific location;
225.    'let' might be random class; place_object() will validate <x,y> */
226. struct obj *
227. mkobj_at(char let, coordxy x, coordxy y, boolean artif)
228. {
229.     struct obj *otmp;
230. 
231.     otmp = mkobj(let, artif);
232.     place_object(otmp, x, y);
233.     return otmp;
234. }
235. 
236. /* make a specific object at a specific location */
237. struct obj *
238. mksobj_at(
239.     int otyp,
240.     coordxy x, coordxy y,
241.     boolean init, boolean artif)
242. {
243.     struct obj *otmp;
244. 
245.     otmp = mksobj(otyp, init, artif);
246.     place_object(otmp, x, y);
247.     return otmp;
248. }
249. 
250. 
251. /* used for extra orctown loot */
252. struct obj *
253. mksobj_migr_to_species(
254.     int otyp,
255.     unsigned mflags2,
256.     boolean init, boolean artif)
257. {
258.     struct obj *otmp;
259. 
260.     otmp = mksobj(otyp, init, artif);
261.     add_to_migration(otmp);
262.     otmp->owornmask = (long) MIGR_TO_SPECIES;
263.     otmp->migr_species = mflags2;
264.     return otmp;
265. }
266. 
267. /* mkobj(): select a type of item from a class, use mksobj() to create it;
268.    result is always non-Null */
269. struct obj *
270. mkobj(int oclass, boolean artif)
271. {
272.     int tprob, i, prob;
273. 
274.     if (oclass == RANDOM_CLASS) {
275.         const struct icp *iprobs = Is_rogue_level(&u.uz)
276.                                    ? (const struct icp *) rogueprobs
277.                                    : Inhell ? (const struct icp *) hellprobs
278.                                             : (const struct icp *) mkobjprobs;
279. 
280.         for (tprob = rnd(100); (tprob -= iprobs->iprob) > 0; iprobs++)
281.             continue;
282.         oclass = iprobs->iclass;
283.     }
284. 
285.     if (oclass == SPBOOK_no_NOVEL) {
286.         i = rnd_class(svb.bases[SPBOOK_CLASS], SPE_BLANK_PAPER);
287.         oclass = SPBOOK_CLASS; /* for sanity check below */
288.     } else {
289.         prob = rnd(go.oclass_prob_totals[oclass]);
290.         i = svb.bases[oclass];
291.         while ((prob -= objects[i].oc_prob) > 0)
292.             ++i;
293.     }
294. 
295.     if (objects[i].oc_class != oclass || !OBJ_NAME(objects[i])) {
296.         impossible("probtype error, oclass=%d i=%d", (int) oclass, i);
297.         i = svb.bases[oclass];
298.     }
299. 
300.     return mksobj(i, TRUE, artif);
301. }
302. 
303. staticfn void
304. mkbox_cnts(struct obj *box)
305. {
306.     int n;
307.     struct obj *otmp;
308. 
309.     box->cobj = (struct obj *) 0;
310. 
311.     switch (box->otyp) {
312.     case ICE_BOX:
313.         n = 20;
314.         break;
315.     case CHEST:
316.         n = box->olocked ? 7 : 5;
317.         break;
318.     case LARGE_BOX:
319.         n = box->olocked ? 5 : 3;
320.         break;
321.     case SACK:
322.     case OILSKIN_SACK:
323.         /* initial inventory: sack starts out empty */
324.         if (svm.moves <= 1 && !gi.in_mklev) {
325.             n = 0;
326.             break;
327.         }
328.         FALLTHROUGH;
329.         /*FALLTHRU*/
330.     case BAG_OF_HOLDING:
331.         n = 1;
332.         break;
333.     default:
334.         n = 0;
335.         break;
336.     }
337. 
338.     for (n = rn2(n + 1); n > 0; n--) {
339.         if (box->otyp == ICE_BOX) {
340.             otmp = mksobj(CORPSE, TRUE, FALSE);
341.             /* Note: setting age to 0 is correct.  Age has a different
342.              * from usual meaning for objects stored in ice boxes. -KAA
343.              */
344.             otmp->age = 0L;
345.             if (otmp->timed) {
346.                 (void) stop_timer(ROT_CORPSE, obj_to_any(otmp));
347.                 (void) stop_timer(REVIVE_MON, obj_to_any(otmp));
348.                 (void) stop_timer(SHRINK_GLOB, obj_to_any(otmp));
349.             }
350.         } else {
351.             int tprob;
352.             const struct icp *iprobs = boxiprobs;
353. 
354.             for (tprob = rnd(100); (tprob -= iprobs->iprob) > 0; iprobs++)
355.                 ;
356.             if (!(otmp = mkobj(iprobs->iclass, FALSE)))
357.                 continue;
358. 
359.             /* handle a couple of special cases */
360.             if (otmp->oclass == COIN_CLASS) {
361.                 /* 2.5 x level's usual amount; weight adjusted below */
362.                 otmp->quan = (long) (rnd(level_difficulty() + 2) * rnd(75));
363.                 otmp->owt = weight(otmp);
364.             } else
365.                 while (otmp->otyp == ROCK) {
366.                     otmp->otyp = rnd_class(DILITHIUM_CRYSTAL, LOADSTONE);
367.                     if (otmp->quan > 2L)
368.                         otmp->quan = 1L;
369.                     otmp->owt = weight(otmp);
370.                 }
371.             if (box->otyp == BAG_OF_HOLDING) {
372.                 if (Is_mbag(otmp)) {
373.                     otmp->otyp = SACK;
374.                     otmp->spe = 0;
375.                     otmp->owt = weight(otmp);
376.                 } else
377.                     while (otmp->otyp == WAN_CANCELLATION)
378.                         otmp->otyp = rnd_class(WAN_LIGHT, WAN_LIGHTNING);
379.             }
380.         }
381.         (void) add_to_container(box, otmp);
382.     }
383.     /* caller will update box->owt */
384. }
385. 
386. /* select a random, common monster type */
387. int
388. rndmonnum(void)
389. {
390.     return rndmonnum_adj(0, 0);
391. }
392. 
393. /* select a random, common monster type, with adjusted difficulty */
394. int
395. rndmonnum_adj(int minadj, int maxadj)
396. {
397.     struct permonst *ptr;
398.     int i;
399.     unsigned short excludeflags;
400. 
401.     /* Plan A: get a level-appropriate common monster */
402.     ptr = rndmonst_adj(minadj, maxadj);
403.     if (ptr)
404.         return monsndx(ptr);
405. 
406.     /* Plan B: get any common monster */
407.     excludeflags = G_UNIQ | G_NOGEN | (Inhell ? G_NOHELL : G_HELL);
408.     do {
409.         i = rn1(SPECIAL_PM - LOW_PM, LOW_PM);
410.         ptr = &mons[i];
411.     } while ((ptr->geno & excludeflags) != 0);
412. 
413.     return i;
414. }
415. 
416. void
417. copy_oextra(struct obj *obj2, struct obj *obj1)
418. {
419.     if (!obj2 || !obj1 || !obj1->oextra)
420.         return;
421. 
422.     if (!obj2->oextra)
423.         obj2->oextra = newoextra();
424.     if (has_oname(obj1))
425.         oname(obj2, ONAME(obj1), ONAME_SKIP_INVUPD);
426.     if (has_omonst(obj1)) {
427.         if (!OMONST(obj2))
428.             newomonst(obj2);
429.         assert(has_omonst(obj2));
430.         (void) memcpy((genericptr_t) OMONST(obj2),
431.                       (genericptr_t) OMONST(obj1), sizeof (struct monst));
432.         OMONST(obj2)->mextra = (struct mextra *) 0;
433.         OMONST(obj2)->nmon = (struct monst *) 0;
434. #if 0
435.         OMONST(obj2)->m_id = next_ident();
436. #endif
437.         if (OMONST(obj1)->mextra)
438.             copy_mextra(OMONST(obj2), OMONST(obj1));
439.     }
440.     if (has_omailcmd(obj1)) {
441.         new_omailcmd(obj2, OMAILCMD(obj1));
442.     }
443.     if (has_omid(obj1)) {
444.         if (!OMID(obj2))
445.             newomid(obj2);
446.         OMID(obj2) = OMID(obj1);
447.     }
448. }
449. 
450. /*
451.  * Split stack so that its size gets reduced by num.  The quantity num is
452.  * put in the object structure delivered by this call.  The returned object
453.  * has its wornmask cleared and is positioned just following the original
454.  * in the nobj chain (and nexthere chain when on the floor).
455.  */
456. struct obj *
457. splitobj(struct obj *obj, long num)
458. {
459.     struct obj *otmp;
460. 
461.     /* can't split containers */
462.     if (obj->cobj || num <= 0L || obj->quan <= num)
463.         panic("splitobj [cobj=%s num=%ld quan=%ld]",
464.               obj->cobj ? "non-empty container" : "(null)", num, obj->quan);
465. 
466.     otmp = newobj();
467.     *otmp = *obj; /* copies whole structure */
468.     otmp->oextra = (struct oextra *) 0;
469.     otmp->o_id = nextoid(obj, otmp);
470.     otmp->timed = 0;                  /* not timed, yet */
471.     otmp->lamplit = 0;                /* ditto */
472.     otmp->owornmask = 0L;             /* new object isn't worn */
473.     obj->quan -= num;
474.     obj->owt = weight(obj);
475.     otmp->quan = num;
476.     otmp->owt = weight(otmp); /* -= obj->owt ? */
477.     otmp->lua_ref_cnt = 0;
478.     otmp->pickup_prev = 0;
479. 
480.     svc.context.objsplit.parent_oid = obj->o_id;
481.     svc.context.objsplit.child_oid = otmp->o_id;
482.     obj->nobj = otmp;
483.     /* Only set nexthere when on the floor; nexthere is also used
484.        as a back pointer to the container object when contained.
485.        For either case, otmp's nexthere pointer is already pointing
486.        at the right thing. */
487.     if (obj->where == OBJ_FLOOR)
488.         obj->nexthere = otmp; /* insert into chain: obj -> otmp -> next */
489.     /* lua isn't tracking the split off portion even if it happens to
490.        be tracking the original */
491.     if (otmp->where == OBJ_LUAFREE)
492.         otmp->where = OBJ_FREE;
493.     if (obj->unpaid)
494.         splitbill(obj, otmp);
495.     copy_oextra(otmp, obj);
496.     if (has_omid(otmp))
497.         free_omid(otmp); /* only one association with m_id */
498.     if (obj->timed)
499.         obj_split_timers(obj, otmp);
500.     if (obj_sheds_light(obj))
501.         obj_split_light_source(obj, otmp);
502.     return otmp;
503. }
504. 
505. /* return the value of context.ident and then increment it to be ready for
506.    its next use; used to be simple += 1 so that every value from 1 to N got
507.    used but now has a random increase that skips half of potential values */
508. unsigned
509. next_ident(void)
510. {
511.     unsigned res = svc.context.ident;
512. 
513.     /* +rnd(2): originally just +1; changed to rnd() to avoid potential
514.        exploit of player using #adjust to split an object stack in a manner
515.        that makes most recent ident%2 known; since #adjust takes no time,
516.        no intervening activity like random creation of a new monster will
517.        take place before next user command; with former +1, o_id%2 of the
518.        next object to be created was knowable and player could make a wish
519.        under controlled circumstances for an item that is affected by the
520.        low bits of its obj->o_id [particularly helm of opposite alignment] */
521.     svc.context.ident += rnd(2); /* ready for next new object or monster */
522. 
523.     /* if ident has wrapped to 0, force it to be non-zero; if/when it
524.        ever wraps past 0 (unlikely, but possible on a configuration which
525.        uses 16-bit 'int'), just live with that and hope no o_id conflicts
526.        between objects or m_id conflicts between monsters arise */
527.     if (!svc.context.ident)
528.         svc.context.ident = rnd(2) + 1;   /* id 1 is reserved */
529. 
530.     return res;
531. }
532. 
533. /* when splitting a stack that has o_id-based shop prices, pick an
534.    o_id value for the new stack that will maintain the same price */
535. staticfn unsigned
536. nextoid(struct obj *oldobj, struct obj *newobj)
537. {
538.     int olddif, newdif, trylimit = 256; /* limit of 4 suffices at present */
539.     unsigned oid = svc.context.ident - 1; /* loop increment will reverse -1 */
540. 
541.     olddif = oid_price_adjustment(oldobj, oldobj->o_id);
542.     do {
543.         ++oid;
544.         if (!oid) /* avoid using 0 (in case value wrapped) */
545.             ++oid;
546.         newdif = oid_price_adjustment(newobj, oid);
547.     } while (newdif != olddif && --trylimit >= 0);
548.     svc.context.ident = oid; /* update 'last ident used' */
549.     (void) next_ident(); /* increment context.ident for next use */
550.     return oid; /* caller will use this ident */
551. }
552. 
553. /* try to find the stack obj was split from, then merge them back together;
554.    returns the combined object if unsplit is successful, null otherwise */
555. struct obj *
556. unsplitobj(struct obj *obj)
557. {
558.     unsigned target_oid = 0;
559.     struct obj *oparent = 0, *ochild = 0, *list = 0;
560. 
561.     /*
562.      * We don't operate on floor objects (we're following o->nobj rather
563.      * than o->nexthere), on free objects (don't know which list to use when
564.      * looking for obj's parent or child), on bill objects (too complicated,
565.      * not needed), or on buried or migrating objects (not needed).
566.      * [This could be improved, but at present additional generality isn't
567.      * necessary.]
568.      */
569.     switch (obj->where) {
570.     case OBJ_FREE:
571.     case OBJ_FLOOR:
572.     case OBJ_ONBILL:
573.     case OBJ_MIGRATING:
574.     case OBJ_BURIED:
575.     default:
576.         return (struct obj *) 0;
577.     case OBJ_INVENT:
578.         list = gi.invent;
579.         break;
580.     case OBJ_MINVENT:
581.         list = obj->ocarry->minvent;
582.         break;
583.     case OBJ_CONTAINED:
584.         list = obj->ocontainer->cobj;
585.         break;
586.     }
587. 
588.     /* first try the expected case; obj is split from another stack */
589.     if (obj->o_id == svc.context.objsplit.child_oid) {
590.         /* parent probably precedes child and will require list traversal */
591.         ochild = obj;
592.         target_oid = svc.context.objsplit.parent_oid;
593.         if (obj->nobj && obj->nobj->o_id == target_oid)
594.             oparent = obj->nobj;
595.     } else if (obj->o_id == svc.context.objsplit.parent_oid) {
596.         /* alternate scenario: another stack was split from obj;
597.            child probably follows parent and will be found here */
598.         oparent = obj;
599.         target_oid = svc.context.objsplit.child_oid;
600.         if (obj->nobj && obj->nobj->o_id == target_oid)
601.             ochild = obj->nobj;
602.     }
603.     /* if we have only half the split, scan obj's list to find other half */
604.     if (ochild && !oparent) {
605.         /* expected case */
606.         for (obj = list; obj; obj = obj->nobj)
607.             if (obj->o_id == target_oid) {
608.                 oparent = obj;
609.                 break;
610.             }
611.     } else if (oparent && !ochild) {
612.         /* alternate scenario */
613.         for (obj = list; obj; obj = obj->nobj)
614.             if (obj->o_id == target_oid) {
615.                 ochild = obj;
616.                 break;
617.             }
618.     }
619.     /* if we have both parent and child, try to merge them;
620.        if successful, return the combined stack, otherwise return null */
621.     return (oparent && ochild && merged(&oparent, &ochild)) ? oparent : 0;
622. }
623. 
624. /* reset splitobj()/unsplitobj() context */
625. void
626. clear_splitobjs(void)
627. {
628.     svc.context.objsplit.parent_oid = svc.context.objsplit.child_oid = 0;
629. }
630. 
631. /*
632.  * Insert otmp right after obj in whatever chain(s) it is on.  Then extract
633.  * obj from the chain(s).  This function does a literal swap.  It is up to
634.  * the caller to provide a valid context for the swap.  When done, obj will
635.  * still exist, but not on any chain.
636.  *
637.  * Note:  Don't use obj_extract_self() -- we are doing an in-place swap,
638.  * not actually moving something.
639.  */
640. void
641. replace_object(struct obj *obj, struct obj *otmp)
642. {
643.     otmp->where = obj->where;
644.     switch (obj->where) {
645.     case OBJ_FREE:
646.         /* do nothing */
647.         break;
648.     case OBJ_INVENT:
649.         otmp->nobj = obj->nobj;
650.         obj->nobj = otmp;
651.         extract_nobj(obj, &gi.invent);
652.         break;
653.     case OBJ_CONTAINED:
654.         otmp->nobj = obj->nobj;
655.         otmp->ocontainer = obj->ocontainer;
656.         obj->nobj = otmp;
657.         extract_nobj(obj, &obj->ocontainer->cobj);
658.         break;
659.     case OBJ_MINVENT:
660.         otmp->nobj = obj->nobj;
661.         otmp->ocarry = obj->ocarry;
662.         obj->nobj = otmp;
663.         extract_nobj(obj, &obj->ocarry->minvent);
664.         break;
665.     case OBJ_FLOOR:
666.         otmp->nobj = obj->nobj;
667.         otmp->nexthere = obj->nexthere;
668.         otmp->ox = obj->ox;
669.         otmp->oy = obj->oy;
670.         obj->nobj = otmp;
671.         obj->nexthere = otmp;
672.         extract_nobj(obj, &fobj);
673.         extract_nexthere(obj, &svl.level.objects[obj->ox][obj->oy]);
674.         break;
675.     default:
676.         panic("replace_object: obj position");
677.         break;
678.     }
679. }
680. 
681. /* is 'obj' inside a container whose contents aren't known?
682.    if so, return the outermost container meeting that criterium */
683. struct obj *
684. unknwn_contnr_contents(struct obj *obj)
685. {
686.     struct obj *result = 0, *parent;
687. 
688.     while (obj->where == OBJ_CONTAINED) {
689.         parent = obj->ocontainer;
690.         if (!parent->cknown)
691.             result = parent;
692.         obj = parent;
693.     }
694.     return result;
695. }
696. 
697. /*
698.  * Create a dummy duplicate to put on shop bill.  The duplicate exists
699.  * only in the billobjs chain.  This function is used when a shop object
700.  * is being altered, and a copy of the original is needed for billing
701.  * purposes.  For example, when eating, where an interruption will yield
702.  * an object which is different from what it started out as; the "I x"
703.  * command needs to display the original object.
704.  *
705.  * The caller is responsible for checking otmp->unpaid and
706.  * costly_spot(u.ux, u.uy).  This function will make otmp no charge.
707.  *
708.  * Note that check_unpaid_usage() should be used instead for partial
709.  * usage of an object.
710.  */
711. void
712. bill_dummy_object(struct obj *otmp)
713. {
714.     struct obj *dummy;
715.     long cost = 0L;
716. 
717.     if (otmp->unpaid) {
718.         cost = unpaid_cost(otmp, COST_SINGLEOBJ);
719.         subfrombill(otmp, shop_keeper(*u.ushops));
720.     }
721.     dummy = newobj();
722.     *dummy = *otmp;
723.     dummy->oextra = (struct oextra *) 0;
724.     dummy->where = OBJ_FREE;
725.     dummy->o_id = nextoid(otmp, dummy);
726.     dummy->timed = 0;
727.     copy_oextra(dummy, otmp);
728.     if (has_omid(dummy))
729.         free_omid(dummy); /* only one association with m_id */
730.     if (Is_candle(dummy))
731.         dummy->lamplit = 0;
732.     dummy->owornmask = 0L; /* dummy object is not worn */
733.     addtobill(dummy, FALSE, TRUE, TRUE);
734.     if (cost && dummy->where != OBJ_DELETED)
735.         alter_cost(dummy, -cost);
736.     /* no_charge is only valid for some locations */
737.     otmp->no_charge = (otmp->where == OBJ_FLOOR
738.                        || otmp->where == OBJ_CONTAINED) ? 1 : 0;
739.     otmp->unpaid = 0;
740.     return;
741. }
742. 
743. /* alteration types; must match COST_xxx macros in hack.h */
744. static const char *const alteration_verbs[] = {
745.     "cancel", "drain", "uncharge", "unbless", "uncurse", "disenchant",
746.     "degrade", "dilute", "erase", "burn", "neutralize", "destroy", "splatter",
747.     "bite", "open", "break the lock on", "rust", "rot", "tarnish", "crack",
748. };
749. 
750. /* possibly bill for an object which the player has just modified */
751. void
752. costly_alteration(struct obj *obj, int alter_type)
753. {
754.     coordxy ox, oy;
755.     char objroom;
756.     boolean learn_bknown;
757.     const char *those, *them;
758.     struct monst *shkp = 0;
759. 
760.     if (alter_type < 0 || alter_type >= SIZE(alteration_verbs)) {
761.         impossible("invalid alteration type (%d)", alter_type);
762.         alter_type = 0;
763.     }
764. 
765.     ox = oy = 0;    /* lint suppression */
766.     objroom = '\0'; /* ditto */
767.     if (carried(obj) || obj->where == OBJ_FREE) {
768.         /* OBJ_FREE catches obj_no_longer_held()'s transformation
769.            of crysknife back into worm tooth; the object has been
770.            removed from inventory but not necessarily placed at
771.            its new location yet--the unpaid flag will still be set
772.            if this item is owned by a shop */
773.         if (!obj->unpaid)
774.             return;
775.     } else {
776.         /* this get_obj_location shouldn't fail, but if it does,
777.            use hero's location */
778.         if (!get_obj_location(obj, &ox, &oy, CONTAINED_TOO))
779.             ox = u.ux, oy = u.uy;
780.         if (!costly_spot(ox, oy))
781.             return;
782.         objroom = *in_rooms(ox, oy, SHOPBASE);
783.         /* if no shop cares about it, we're done */
784.         if (!billable(&shkp, obj, objroom, FALSE))
785.             return;
786.     }
787. 
788.     if (obj->quan == 1L)
789.         those = "that", them = "it";
790.     else
791.         those = "those", them = "them";
792. 
793.     /* when shopkeeper describes the object as being uncursed or unblessed
794.        hero will know that it is now uncursed; will also make the feedback
795.        from `I x' after bill_dummy_object() be more specific for this item */
796.     learn_bknown = (alter_type == COST_UNCURS || alter_type == COST_UNBLSS);
797. 
798.     switch (obj->where) {
799.     case OBJ_FREE: /* obj_no_longer_held() */
800.     case OBJ_INVENT:
801.         if (learn_bknown)
802.             set_bknown(obj, 1);
803.         if (shkp) {
804.             SetVoice(shkp, 0, 80, 0);
805.         }
806.         verbalize("You %s %s %s, you pay for %s!",
807.                   alteration_verbs[alter_type], those, simpleonames(obj),
808.                   them);
809.         bill_dummy_object(obj);
810.         break;
811.     case OBJ_FLOOR:
812.         if (learn_bknown)
813.             obj->bknown = 1; /* ok to bypass set_bknown() here */
814.         if (costly_spot(u.ux, u.uy) && objroom == *u.ushops) {
815.             if (shkp) {
816.                 SetVoice(shkp, 0, 80, 0);
817.             }
818.             verbalize("You %s %s, you pay for %s!",
819.                       alteration_verbs[alter_type], those, them);
820.             bill_dummy_object(obj);
821.         } else {
822.             (void) stolen_value(obj, ox, oy, FALSE, FALSE);
823.         }
824.         break;
825.     }
826. }
827. 
828. static const char dknowns[] = { WAND_CLASS,   RING_CLASS, POTION_CLASS,
829.                                 SCROLL_CLASS, GEM_CLASS,  SPBOOK_CLASS,
830.                                 WEAPON_CLASS, TOOL_CLASS, VENOM_CLASS, 0 };
831. 
832. /* set obj->dknown to 0 for most types of objects, to 1 otherwise;
833.    split off from unknow_object() */
834. void
835. clear_dknown(struct obj *obj)
836. {
837.     /* note: this is an unobserving not an observing, so don't call
838.        observe_object even if dknown is being set to 1 */
839.     obj->dknown = strchr(dknowns, obj->oclass) ? 0 : 1;
840.     if ((obj->otyp >= ELVEN_SHIELD && obj->otyp <= ORCISH_SHIELD)
841.         || obj->otyp == SHIELD_OF_REFLECTION
842.         || objects[obj->otyp].oc_merge)
843.         obj->dknown = 0;
844.     /* globs always have dknown flag set (to maximize merging) but for new
845.        object, globby flag won't be set yet so isn't available to check */
846.     if (Is_pudding(obj))
847.         obj->dknown = 1;
848. }
849. 
850. /* some init for a brand new object, or partial re-init when hero loses
851.    potentially known info about an object (called when an unseen monster
852.    picks up or uses it); moved from invent.c to here for access to dknowns */
853. void
854. unknow_object(struct obj *obj)
855. {
856.     clear_dknown(obj); /* obj->dknown = 0; */
857. 
858.     obj->bknown = obj->rknown = 0;
859.     obj->cknown = obj->lknown = 0;
860.     obj->tknown = 0;
861.     /* for an existing object, awareness of charges or enchantment has
862.        gone poof...  [object types which don't use the known flag have
863.        it set True for some reason] */
864.     obj->known = objects[obj->otyp].oc_uses_known ? 0 : 1;
865. }
866. 
867. /* do some initialization to newly created object; otyp must already be set */
868. staticfn void
869. mksobj_init(struct obj **obj, boolean artif)
870. {
871.     int mndx, tryct;
872.     struct obj *otmp = *obj;
873.     char let = objects[otmp->otyp].oc_class;
874. 
875.     switch (let) {
876.     case WEAPON_CLASS:
877.         otmp->quan = is_multigen(otmp) ? (long) rn1(6, 6) : 1L;
878.         if (!rn2(11)) {
879.             otmp->spe = rne(3);
880.             otmp->blessed = rn2(2);
881.         } else if (!rn2(10)) {
882.             curse(otmp);
883.             otmp->spe = -rne(3);
884.         } else
885.             blessorcurse(otmp, 10);
886.         if (is_poisonable(otmp) && !rn2(100))
887.             otmp->opoisoned = 1;
888. 
889.         if (artif && !rn2(20 + (10 * nartifact_exist()))) {
890.             /* mk_artifact() with otmp and A_NONE will never return NULL */
891.             otmp = mk_artifact(otmp, (aligntyp) A_NONE, 99, TRUE);
892.             *obj = otmp;
893.         }
894.         break;
895.     case FOOD_CLASS:
896.         otmp->oeaten = 0;
897.         switch (otmp->otyp) {
898.         case CORPSE:
899.             /* possibly overridden by mkcorpstat() */
900.             tryct = 50;
901.             do
902.                 otmp->corpsenm = undead_to_corpse(rndmonnum());
903.             while ((svm.mvitals[otmp->corpsenm].mvflags & G_NOCORPSE)
904.                    && (--tryct > 0));
905.             if (tryct == 0) {
906.                 /* perhaps rndmonnum() only wants to make G_NOCORPSE
907.                    monsters on this svl.level; create an adventurer's
908.                    corpse instead, then */
909.                 otmp->corpsenm = PM_HUMAN;
910.             }
911.             /* timer set below */
912.             break;
913.         case EGG:
914.             otmp->corpsenm = NON_PM; /* generic egg */
915.             if (!rn2(3))
916.                 for (tryct = 200; tryct > 0; --tryct) {
917.                     mndx = can_be_hatched(rndmonnum());
918.                     if (mndx != NON_PM && !dead_species(mndx, TRUE)) {
919.                         otmp->corpsenm = mndx; /* typed egg */
920.                         break;
921.                     }
922.                 }
923.             /* timer set below */
924.             break;
925.         case TIN:
926.             otmp->corpsenm = NON_PM; /* empty (so far) */
927.             if (!rn2(6))
928.                 set_tin_variety(otmp, SPINACH_TIN);
929.             else
930.                 for (tryct = 200; tryct > 0; --tryct) {
931.                     mndx = undead_to_corpse(rndmonnum());
932.                     if (mons[mndx].cnutrit
933.                         && !(svm.mvitals[mndx].mvflags & G_NOCORPSE)) {
934.                         otmp->corpsenm = mndx;
935.                         set_tin_variety(otmp, RANDOM_TIN);
936.                         break;
937.                     }
938.                 }
939.             blessorcurse(otmp, 10);
940.             break;
941.         case SLIME_MOLD:
942.             otmp->spe = svc.context.current_fruit;
943.             flags.made_fruit = TRUE;
944.             break;
945.         case KELP_FROND:
946.             otmp->quan = (long) rnd(2);
947.             break;
948.         case CANDY_BAR:
949.             /* set otmp->spe */
950.             assign_candy_wrapper(otmp);
951.             break;
952.         default:
953.             break;
954.         }
955.         if (Is_pudding(otmp)) {
956.             otmp->globby = 1;
957.             /* for emphasis; glob quantity is always 1 and weight varies
958.                when other globs coalesce with it or this one shrinks */
959.             otmp->quan = 1L;
960.             /* 5.0: globs in 3.6.x left owt as 0 and let weight() fix
961.                that up during 'obj->owt = weight(obj)' below, but now
962.                we initialize glob->owt explicitly so weight() doesn't
963.                need to perform any fix up and returns glob->owt as-is */
964.             otmp->owt = objects[otmp->otyp].oc_weight;
965.             /* dknown, but not observed */
966.             otmp->known = otmp->dknown = 1;
967.             otmp->corpsenm = PM_GRAY_OOZE + (otmp->otyp - GLOB_OF_GRAY_OOZE);
968.             start_glob_timeout(otmp, 0L);
969.         } else {
970.             if (otmp->otyp != CORPSE && otmp->otyp != MEAT_RING
971.                 && otmp->otyp != KELP_FROND && !rn2(6)) {
972.                 otmp->quan = 2L;
973.             }
974.         }
975.         break;
976.     case GEM_CLASS:
977.         otmp->corpsenm = 0; /* LOADSTONE hack */
978.         if (otmp->otyp == LOADSTONE)
979.             curse(otmp);
980.         else if (otmp->otyp == ROCK)
981.             otmp->quan = (long) rn1(6, 6);
982.         else if (otmp->otyp != LUCKSTONE && !rn2(6))
983.             otmp->quan = 2L;
984.         else
985.             otmp->quan = 1L;
986.         break;
987.     case TOOL_CLASS:
988.         switch (otmp->otyp) {
989.         case TALLOW_CANDLE:
990.         case WAX_CANDLE:
991.             otmp->spe = 1;
992.             otmp->age = 20L * /* 400 or 200 */
993.                         (long) objects[otmp->otyp].oc_cost;
994.             otmp->lamplit = 0;
995.             otmp->quan = 1L + (long) (rn2(2) ? rn2(7) : 0);
996.             blessorcurse(otmp, 5);
997.             break;
998.         case BRASS_LANTERN:
999.         case OIL_LAMP:
1000.             otmp->spe = 1;
1001.             otmp->age = (long) rn1(500, 1000);
1002.             otmp->lamplit = 0;
1003.             blessorcurse(otmp, 5);
1004.             break;
1005.         case MAGIC_LAMP:
1006.             otmp->spe = 1;
1007.             otmp->lamplit = 0;
1008.             blessorcurse(otmp, 2);
1009.             break;
1010.         case CHEST:
1011.         case LARGE_BOX:
1012.             otmp->olocked = !!(rn2(5));
1013.             otmp->otrapped = !(rn2(10));
1014.             otmp->tknown = otmp->otrapped && !rn2(100); /* obvious trap */
1015.             FALLTHROUGH;
1016.             /*FALLTHRU*/
1017.         case ICE_BOX:
1018.         case SACK:
1019.         case OILSKIN_SACK:
1020.         case BAG_OF_HOLDING:
1021.             mkbox_cnts(otmp);
1022.             break;
1023.         case EXPENSIVE_CAMERA:
1024.         case TINNING_KIT:
1025.         case MAGIC_MARKER:
1026.             otmp->spe = rn1(70, 30);
1027.             break;
1028.         case CAN_OF_GREASE:
1029.             otmp->spe = rn1(21, 5); /* 0..20 + 5 => 5..25 */
1030.             blessorcurse(otmp, 10);
1031.             break;
1032.         case CRYSTAL_BALL:
1033.             otmp->spe = rn1(5, 3); /* 0..4 + 3 => 3..7 */
1034.             blessorcurse(otmp, 2);
1035.             break;
1036.         case HORN_OF_PLENTY:
1037.         case BAG_OF_TRICKS:
1038.             otmp->spe = rn1(18, 3); /* 0..17 + 3 => 3..20 */
1039.             break;
1040.         case FIGURINE:
1041.             tryct = 0;
1042.             /* figurines are slightly harder monsters */
1043.             do
1044.                 otmp->corpsenm = rndmonnum_adj(5, 10);
1045.             while (is_human(&mons[otmp->corpsenm]) && tryct++ < 30);
1046.             blessorcurse(otmp, 4);
1047.             break;
1048.         case BELL_OF_OPENING:
1049.             otmp->spe = 3;
1050.             break;
1051.         case MAGIC_FLUTE:
1052.         case MAGIC_HARP:
1053.         case FROST_HORN:
1054.         case FIRE_HORN:
1055.         case DRUM_OF_EARTHQUAKE:
1056.             otmp->spe = rn1(5, 4);
1057.             break;
1058.         }
1059.         break;
1060.     case AMULET_CLASS:
1061.         if (otmp->otyp == AMULET_OF_YENDOR)
1062.             svc.context.made_amulet = TRUE;
1063.         if (rn2(10) && (otmp->otyp == AMULET_OF_STRANGULATION
1064.                         || otmp->otyp == AMULET_OF_CHANGE
1065.                         || otmp->otyp == AMULET_OF_RESTFUL_SLEEP)) {
1066.             curse(otmp);
1067.         } else
1068.             blessorcurse(otmp, 10);
1069.         break;
1070.     case VENOM_CLASS:
1071.     case CHAIN_CLASS:
1072.     case BALL_CLASS:
1073.         break;
1074.     case POTION_CLASS: /* note: potions get some additional init below */
1075.     case SCROLL_CLASS:
1076. #ifdef MAIL_STRUCTURES
1077.         if (otmp->otyp != SCR_MAIL)
1078. #endif
1079.             blessorcurse(otmp, 4);
1080.         break;
1081.     case SPBOOK_CLASS:
1082.         otmp->spestudied = 0;
1083.         blessorcurse(otmp, 17);
1084.         break;
1085.     case ARMOR_CLASS:
1086.         if (rn2(10)
1087.             && (otmp->otyp == FUMBLE_BOOTS
1088.                 || otmp->otyp == LEVITATION_BOOTS
1089.                 || otmp->otyp == HELM_OF_OPPOSITE_ALIGNMENT
1090.                 || otmp->otyp == GAUNTLETS_OF_FUMBLING || !rn2(11))) {
1091.             curse(otmp);
1092.             otmp->spe = -rne(3);
1093.         } else if (!rn2(10)) {
1094.             otmp->blessed = rn2(2);
1095.             otmp->spe = rne(3);
1096.         } else
1097.             blessorcurse(otmp, 10);
1098.         if (artif && !rn2(40 + (10 * nartifact_exist()))) {
1099.             /* mk_artifact() with otmp and A_NONE will never return NULL */
1100.             otmp = mk_artifact(otmp, (aligntyp) A_NONE, 99, TRUE);
1101.             *obj = otmp;
1102.         }
1103.         /* simulate lacquered armor for samurai */
1104.         if (Role_if(PM_SAMURAI) && otmp->otyp == SPLINT_MAIL
1105.             && (svm.moves <= 1 || In_quest(&u.uz))) {
1106. #ifdef UNIXPC
1107.             /* optimizer bitfield bug */
1108.             otmp->oerodeproof = 1;
1109.             otmp->rknown = 1;
1110. #else
1111.             otmp->oerodeproof = otmp->rknown = 1;
1112. #endif
1113.         }
1114.         break;
1115.     case WAND_CLASS:
1116.         if (otmp->otyp == WAN_WISHING)
1117.             otmp->spe = 1;
1118.         else if (otmp->otyp == WAN_STASIS)
1119.             /* just as easy to recharge as other NODIR wands, but starts with
1120.                fewer charges */
1121.             otmp->spe = rn1(4, 3);
1122.         else
1123.             otmp->spe = rn1(5,
1124.                             (objects[otmp->otyp].oc_dir == NODIR) ? 11 : 4);
1125.         blessorcurse(otmp, 17);
1126.         otmp->recharged = 0; /* used to control recharging */
1127.         break;
1128.     case RING_CLASS:
1129.         if (objects[otmp->otyp].oc_charged) {
1130.             blessorcurse(otmp, 3);
1131.             if (rn2(10)) {
1132.                 if (rn2(10) && bcsign(otmp))
1133.                     otmp->spe = bcsign(otmp) * rne(3);
1134.                 else
1135.                     otmp->spe = rn2(2) ? rne(3) : -rne(3);
1136.             }
1137.             /* make useless +0 rings much less common */
1138.             if (otmp->spe == 0)
1139.                 otmp->spe = rn2(4) - rn2(3);
1140.             /* negative rings are usually cursed */
1141.             if (otmp->spe < 0 && rn2(5))
1142.                 curse(otmp);
1143.         } else if (rn2(10) && (otmp->otyp == RIN_TELEPORTATION
1144.                                || otmp->otyp == RIN_POLYMORPH
1145.                                || otmp->otyp == RIN_AGGRAVATE_MONSTER
1146.                                || otmp->otyp == RIN_HUNGER || !rn2(9))) {
1147.             curse(otmp);
1148.         }
1149.         break;
1150.     case ROCK_CLASS:
1151.         if (otmp->otyp == STATUE) {
1152.             /* possibly overridden by mkcorpstat() */
1153.             otmp->corpsenm = rndmonnum();
1154.             if (!verysmall(&mons[otmp->corpsenm])
1155.                 && rn2(level_difficulty() / 2 + 10) > 10)
1156.                 (void) add_to_container(otmp, /* caller will update owt */
1157.                                         mkobj(SPBOOK_no_NOVEL, FALSE));
1158.         }
1159.         /* boulder init'd below in the 'regardless of !init' code */
1160.         break;
1161.     case COIN_CLASS:
1162.         break; /* do nothing */
1163.     default:
1164.         /* 3.6.3: this used to be impossible() followed by return 0
1165.            but most callers aren't prepared to deal with Null result
1166.            and cluttering them up to do so is pointless */
1167.         panic("mksobj tried to make type %d, class %d.",
1168.               (int) otmp->otyp, (int) objects[otmp->otyp].oc_class);
1169.         /*NOTREACHED*/
1170.     }
1171. 
1172.     mkobj_erosions(otmp);
1173.     if (permapoisoned(otmp))
1174.         otmp->opoisoned = 1;
1175. }
1176. 
1177. /* mksobj(): create a specific type of object; result is always non-Null */
1178. struct obj *
1179. mksobj(int otyp, boolean init, boolean artif)
1180. {
1181.     struct obj *otmp;
1182.     char let = objects[otyp].oc_class;
1183. 
1184.     otmp = newobj();
1185.     *otmp = cg.zeroobj;
1186.     otmp->age = max(svm.moves, 1L);
1187.     otmp->o_id = next_ident();
1188.     otmp->quan = 1L;
1189.     otmp->oclass = let;
1190.     otmp->otyp = otyp;
1191.     otmp->where = OBJ_FREE;
1192.     unknow_object(otmp); /* set up dknown and known: non-0 for some things */
1193.     otmp->corpsenm = NON_PM;
1194.     otmp->lua_ref_cnt = 0;
1195.     otmp->pickup_prev = 0;
1196. 
1197.     if (init)
1198.         mksobj_init(&otmp, artif);
1199. 
1200.     /* some things must get done (corpsenm, timers) even if init = 0 */
1201.     switch ((otmp->oclass == POTION_CLASS && otmp->otyp != POT_OIL)
1202.             ? POT_WATER
1203.             : otmp->otyp) {
1204.     case CORPSE:
1205.         if (otmp->corpsenm == NON_PM) {
1206.             otmp->corpsenm = undead_to_corpse(rndmonnum());
1207.             if (svm.mvitals[otmp->corpsenm].mvflags & (G_NOCORPSE | G_GONE))
1208.                 otmp->corpsenm = gu.urole.mnum;
1209.         }
1210.         FALLTHROUGH;
1211.         /*FALLTHRU*/
1212.     case STATUE:
1213.     case FIGURINE:
1214.         if (otmp->corpsenm == NON_PM)
1215.             otmp->corpsenm = rndmonnum();
1216.         if (otmp->corpsenm != NON_PM) {
1217.             struct permonst *ptr = &mons[otmp->corpsenm];
1218. 
1219.             otmp->spe = (is_neuter(ptr) ? CORPSTAT_NEUTER
1220.                          : is_female(ptr) ? CORPSTAT_FEMALE
1221.                            : is_male(ptr) ? CORPSTAT_MALE
1222.                              : rn2(2) ? CORPSTAT_FEMALE : CORPSTAT_MALE);
1223.         }
1224.         FALLTHROUGH;
1225.         /*FALLTHRU*/
1226.     case EGG:
1227.     /* case TIN: */
1228.         set_corpsenm(otmp, otmp->corpsenm);
1229.         break;
1230.     case BOULDER:
1231.         /* next_boulder overloads corpsenm so the default value is NON_PM;
1232.            since that is non-zero, the "next boulder" case in xname() would
1233.            happen when it shouldn't; explicitly set it to 0 */
1234.         otmp->next_boulder = 0;
1235.         break;
1236.     case POT_OIL:
1237.         otmp->age = MAX_OIL_IN_FLASK; /* amount of oil */
1238.         FALLTHROUGH;
1239.         /*FALLTHRU*/
1240.     case POT_WATER: /* POTION_CLASS */
1241.         otmp->fromsink = 0; /* overloads corpsenm, which was set to NON_PM */
1242.         break;
1243.     case LEASH:
1244.         otmp->leashmon = 0; /* overloads corpsenm, which was set to NON_PM */
1245.         break;
1246.     case SPE_NOVEL:
1247.         otmp->novelidx = -1; /* "none of the above"; will be changed */
1248.         otmp = oname(otmp, noveltitle(&otmp->novelidx), ONAME_NO_FLAGS);
1249.         break;
1250.     }
1251. 
1252.     /* unique objects may have an associated artifact entry */
1253.     if (objects[otyp].oc_unique && !otmp->oartifact) {
1254.         /* mk_artifact() with otmp and A_NONE will never return NULL */
1255.         otmp = mk_artifact(otmp, (aligntyp) A_NONE, 99, FALSE);
1256.     }
1257.     otmp->owt = weight(otmp);
1258.     return otmp;
1259. }
1260. 
1261. /* potential mimic shapes that should be undone by stone-to-flesh;
1262.    not used for objects that will be transformed when hit by stone-to-flesh */
1263. boolean
1264. stone_object_type(unsigned mappearance)
1265. {
1266.     int otyp = (int) mappearance;
1267. 
1268.     /* we exclude wands, rings, and gems even though some qualify as stone;
1269.        there aren't any weapons or armor classified as made out of stone */
1270.     return (otyp == BOULDER || otyp == STATUE || otyp == FIGURINE);
1271. }
1272. 
1273. /* possible mimic shapes that are affected by stone-to-flesh;
1274.    mappearance for furniture is a display symbol rather than a terrain type */
1275. boolean
1276. stone_furniture_type(unsigned mappearance)
1277. {
1278.     int sym = (int) mappearance;
1279. 
1280.     switch (sym) {
1281.     case S_upstair:
1282.     case S_dnstair:
1283.     case S_brupstair:
1284.     case S_brdnstair:
1285.     case S_altar:
1286.     case S_throne:
1287.     case S_sink: /* stone sink is iffy; metal might be more appropriate */
1288.         return TRUE;
1289.     default:
1290.         if (sym >= S_vwall && sym <= S_trwall)
1291.             return TRUE;
1292.         break;
1293.     }
1294.     return FALSE;
1295. }
1296. 
1297. /*
1298.  * Several areas of the code made direct reassignments
1299.  * to obj->corpsenm.  Because some special handling is
1300.  * required in certain cases, place that handling here
1301.  * and call this routine in place of the direct assignment.
1302.  *
1303.  * If the object was a lizard or lichen corpse:
1304.  *     - ensure that you don't end up with some
1305.  *       other corpse type which has no rot-away timer.
1306.  *
1307.  * If the object was a troll corpse:
1308.  *     - ensure that you don't end up with some other
1309.  *       corpse type which resurrects from the dead.
1310.  *
1311.  * Re-calculates the weight of figurines and corpses to suit the
1312.  * new species.
1313.  *
1314.  * Existing timeout value for egg hatch is preserved.
1315.  *
1316.  */
1317. void
1318. set_corpsenm(struct obj *obj, int id)
1319. {
1320.     int old_id = obj->corpsenm;
1321.     long when = 0L;
1322. 
1323.     if (obj->timed) {
1324.         if (obj->otyp == EGG) {
1325.             when = stop_timer(HATCH_EGG, obj_to_any(obj));
1326.         } else {
1327.             when = 0L;
1328.             obj_stop_timers(obj); /* corpse or figurine */
1329.         }
1330.     }
1331.     /* oeaten is used to determine how much nutrition is left in
1332.        multiple-bite food and also used to derive how many hit points
1333.        a creature resurrected from a partly eaten corpse gets; latter
1334.        is of interest when a <foo> corpse revives as a <foo> zombie
1335.        in case they are defined with different mons[].cnutrit values */
1336.     if (obj->otyp == CORPSE && obj->oeaten != 0
1337.         /* when oeaten is non-zero, index old_id can't be NON_PM
1338.            and divisor mons[old_id].cnutrit can't be zero */
1339.         && mons[old_id].cnutrit != mons[id].cnutrit) {
1340.         /* oeaten and cnutrit are unsigned; theoretically that could
1341.            be 16 bits and the calculation might overflow, so force long */
1342.         obj->oeaten = (unsigned) ((long) obj->oeaten
1343.                                   * (long) mons[id].cnutrit
1344.                                   / (long) mons[old_id].cnutrit);
1345.     }
1346. 
1347.     obj->corpsenm = id;
1348.     switch (obj->otyp) {
1349.     case CORPSE:
1350.         start_corpse_timeout(obj);
1351.         obj->owt = weight(obj);
1352.         break;
1353.     case FIGURINE:
1354.         if (obj->corpsenm != NON_PM && !dead_species(obj->corpsenm, TRUE)
1355.             && (carried(obj) || mcarried(obj)))
1356.             attach_fig_transform_timeout(obj);
1357.         obj->owt = weight(obj);
1358.         break;
1359.     case EGG:
1360.         if (obj->corpsenm != NON_PM && !dead_species(obj->corpsenm, TRUE))
1361.             attach_egg_hatch_timeout(obj, when);
1362.         break;
1363.     default: /* tin, etc. */
1364.         obj->owt = weight(obj);
1365.         break;
1366.     }
1367. }
1368. 
1369. /* Return the number of turns after which a Rider corpse revives */
1370. long
1371. rider_revival_time(struct obj *body, boolean retry)
1372. {
1373.     long when;
1374.     long minturn = retry ? 3L : (body->corpsenm == PM_DEATH) ? 6L : 12L;
1375. 
1376.     /* Riders have a 1/3 chance per turn of reviving after 12, 6, or 3 turns.
1377.        Always revive by 67. */
1378.     for (when = minturn; when < 67L; when++)
1379.         if (!rn2(3))
1380.             break;
1381.     return when;
1382. }
1383. 
1384. /*
1385.  * Start a corpse decay or revive timer.
1386.  * This takes the age of the corpse into consideration as of 3.4.0.
1387.  */
1388. void
1389. start_corpse_timeout(struct obj *body)
1390. {
1391.     long when;       /* rot away when this old */
1392.     long age;        /* age of corpse          */
1393.     int rot_adjust;
1394.     short action;
1395. 
1396.     /*
1397.      * Note:
1398.      *      if body->norevive is set, the corpse will rot away instead
1399.      *      of revive when its REVIVE_MON timer finishes.
1400.      */
1401. 
1402.     /* lizards and lichen don't rot or revive */
1403.     if (body->corpsenm == PM_LIZARD || body->corpsenm == PM_LICHEN)
1404.         return;
1405. 
1406.     action = ROT_CORPSE;               /* default action: rot away */
1407.     rot_adjust = gi.in_mklev ? 25 : 10; /* give some variation */
1408.     age = max(svm.moves, 1) - body->age;
1409.     if (age > ROT_AGE)
1410.         when = rot_adjust;
1411.     else
1412.         when = ROT_AGE - age;
1413.     when += (long) (rnz(rot_adjust) - rot_adjust);
1414. 
1415.     if (is_rider(&mons[body->corpsenm])) {
1416.         action = REVIVE_MON;
1417.         when = rider_revival_time(body, FALSE);
1418.     } else if (mons[body->corpsenm].mlet == S_TROLL) {
1419.         for (age = 2; age <= TAINT_AGE; age++)
1420.             if (!rn2(TROLL_REVIVE_CHANCE)) { /* troll revives */
1421.                 action = REVIVE_MON;
1422.                 when = age;
1423.                 break;
1424.             }
1425.     } else if (gz.zombify && zombie_form(&mons[body->corpsenm]) != NON_PM
1426.                && !body->norevive) {
1427.         action = ZOMBIFY_MON;
1428.         when = rn1(15, 5); /* 5..19 */
1429.     }
1430. 
1431.     (void) start_timer(when, TIMER_OBJECT, action, obj_to_any(body));
1432. }
1433. 
1434. /* used by item_on_ice() and shrink_glob() */
1435. enum obj_on_ice {
1436.     NOT_ON_ICE = 0,
1437.     SET_ON_ICE = 1,
1438.     BURIED_UNDER_ICE = 2
1439. };
1440. 
1441. /* used by shrink_glob(); is 'item' or enclosing container on or under ice? */
1442. staticfn int
1443. item_on_ice(struct obj *item)
1444. {
1445.     struct obj *otmp;
1446.     coordxy ox, oy;
1447. 
1448.     otmp = item;
1449.     /* if in a container, it might be nested so find outermost one since
1450.        that's the item whose location needs to be checked */
1451.     while (otmp->where == OBJ_CONTAINED)
1452.         otmp = otmp->ocontainer;
1453. 
1454.     if (get_obj_location(otmp, &ox, &oy, BURIED_TOO)) {
1455.         switch (otmp->where) {
1456.         case OBJ_FLOOR:
1457.             if (is_ice(ox, oy))
1458.                 return SET_ON_ICE;
1459.             break;
1460.         case OBJ_BURIED:
1461.             if (is_ice(ox, oy))
1462.                 return BURIED_UNDER_ICE;
1463.             break;
1464.         default:
1465.             break;
1466.         }
1467.     }
1468.     return NOT_ON_ICE;
1469. }
1470. 
1471. /* schedule a timer that will shrink the target glob by 1 unit of weight */
1472. void
1473. start_glob_timeout(
1474.     struct obj *obj, /* glob */
1475.     long when)       /* when to shrink; if 0L, use random value close to 25 */
1476. {
1477.     if (!obj->globby) {
1478.         impossible("start_glob_timeout for non-glob [%d: %s]?",
1479.                    obj->otyp, simpleonames(obj));
1480.         return; /* skip timer creation */
1481.     }
1482.     /* sanity precaution */
1483.     if (obj->timed)
1484.         (void) stop_timer(SHRINK_GLOB, obj_to_any(obj));
1485. 
1486.     if (when < 1L) /* caller usually passes 0L; should never be negative */
1487.         when = 25L + (long) rn2(5) - 2L; /* 25+[0..4]-2 => 23..27, avg 25 */
1488.     /* 1 new glob weighs 20 units and loses 1 unit every 25 turns,
1489.        so lasts for 500 turns, twice as long as the average corpse */
1490.     (void) start_timer(when, TIMER_OBJECT, SHRINK_GLOB, obj_to_any(obj));
1491. }
1492. 
1493. /* globs have quantity 1 and size which varies by multiples of 20 in owt;
1494.    they don't become tainted with age, but every 25 turns this timer runs
1495.    and reduces owt by 1; when it hits 0, destroy the glob (if some other
1496.    part of the program destroys it, the timer will be cancelled);
1497.    note: timer keeps going if an object gets buried or scheduled to
1498.    migrate to another level and can delete the glob in those states */
1499. void
1500. shrink_glob(
1501.     anything *arg,    /* glob (in arg->a_obj) */
1502.     long expire_time) /* turn the timer should have gone off; if less than
1503.                        * current 'moves', we're making up for lost time
1504.                        * after leaving and then returning to this level */
1505. {
1506.     char globnambuf[BUFSZ];
1507.     struct obj *obj = arg->a_obj;
1508.     int globloc = item_on_ice(obj);
1509.     boolean ininv = (obj->where == OBJ_INVENT),
1510.             shrink = FALSE, gone = FALSE, updinv = FALSE;
1511.     struct obj *contnr = (obj->where == OBJ_CONTAINED) ? obj->ocontainer : 0,
1512.                *topcontnr = 0;
1513.     unsigned old_top_owt = 0;
1514. 
1515.     if (!obj->globby) {
1516.         impossible("shrink_glob for non-glob [%d: %s]?",
1517.                    obj->otyp, simpleonames(obj));
1518.         return; /* old timer is gone, don't start a new one */
1519.     }
1520.     /* note: if check_glob() complains about a problem, the " obj " here
1521.        will be replaced in the feedback with info about this glob */
1522.     check_glob(obj, "shrink obj ");
1523. 
1524.     /*
1525.      * If shrinkage occurred while we were on another level, catch up now.
1526.      */
1527.     if (expire_time < svm.moves && globloc != BURIED_UNDER_ICE) {
1528.         /* number of units of weight to remove */
1529.         long delta = (svm.moves - expire_time + 24L) / 25L,
1530.              /* leftover amount to use for new timer */
1531.              moddelta = 25L - (delta % 25L);
1532. 
1533.         if (globloc == SET_ON_ICE)
1534.             delta = (delta + 2L) / 3L;
1535. 
1536.         if (delta >= (long) obj->owt) {
1537.             /* gone; no newsym() or message here--forthcoming map update for
1538.                level arrival is all that's needed */
1539.             obj->owt = 0; /* not required; accurately reflects obj's state */
1540.             shrinking_glob_gone(obj);
1541.         } else {
1542.             /* shrank but not gone; reduce remaining weight */
1543.             obj->owt -= (unsigned) delta;
1544.             /* when contained, update container's weight (recursively if
1545.                nested); won't be in a container carried by hero (since
1546.                catching up for lost time never applies in that situation)
1547.                but might be in one on floor or one carried by a monster */
1548.             if (contnr)
1549.                 container_weight(contnr);
1550.             /* resume regular shrinking */
1551.             start_glob_timeout(obj, moddelta);
1552.         }
1553.         return;
1554.     }
1555. 
1556.     /*
1557.      * When on ice, only shrink every third try.  If buried under ice,
1558.      * don't shrink at all, similar to being contained in an ice box
1559.      * except that the timer remains active.  [FIXME:  stop the timer
1560.      * for obj in pool that becomes frozen, restart it if/when unburied.]
1561.      *
1562.      * If the glob is actively being eaten by hero, skip weight reduction
1563.      * to avoid messing up the context.victual data (if/when eaten by a
1564.      * monster, timer won't have a chance to run before meal is finished).
1565.      */
1566.     if (eating_glob(obj)
1567.         || globloc == BURIED_UNDER_ICE
1568.         || (globloc == SET_ON_ICE && (svm.moves % 3L) == 1L)) {
1569.         /* schedule next shrink attempt; for the being eaten case, the
1570.            glob and its timer might be deleted before this kicks in */
1571.         start_glob_timeout(obj, 0L);
1572.         return;
1573.     }
1574. 
1575.     /* format "Your/Shk's/The [partly eaten] glob of <goo>" into
1576.        globnambuf[] before shrinking the glob; Yname2() calls yname()
1577.        which calls xname() which ordinarily leaves "partly eaten" to
1578.        doname() rather than inserting that itself; ask xname() to add
1579.        that when appropriate */
1580.     iflags.partly_eaten_hack = TRUE;
1581.     Strcpy(globnambuf, Yname2(obj));
1582.     iflags.partly_eaten_hack = FALSE;
1583. 
1584.     if (obj->owt > 0) { /* sanity precaution */
1585.         /* globs start out weighing 20 units; give two messages per glob,
1586.            when going from 20 to 19 and from 10 to 9; a different message
1587.            is given for going from 1 to 0 (gone) */
1588.         unsigned basewt = objects[obj->otyp].oc_weight, /* 20 */
1589.                  msgwt = (max(basewt, 1U) + 1U) / 2U; /* 10 */
1590. 
1591.         shrink = (obj->owt % msgwt) == 0;
1592.         obj->owt -= 1;
1593.         /* if glob is partly eaten, reduce the amount still available (but
1594.            not all the way to 0 which would change it back to untouched) */
1595.         if (obj->oeaten > 1)
1596.             obj->oeaten -= 1;
1597.     }
1598.     gone = !obj->owt;
1599. 
1600.     /* timer might go off when the glob is migrating to another level and
1601.        possibly delete it; messages are only given for in-open-inventory,
1602.        inside-container-in-invent, and going away when can-see-on-floor */
1603.     if (ininv) {
1604.         if (shrink || gone)
1605.             pline("%s %s.", globnambuf,
1606.                   /* globs always have quantity 1 so we don't need otense()
1607.                      because the verb always references a singular item */
1608.                   gone ? "dissolves completely" : "shrinks");
1609.         updinv = TRUE;
1610.     } else if (contnr) {
1611.         /* when in a container, it might be nested so find outermost one */
1612.         topcontnr = contnr;
1613.         while (topcontnr->where == OBJ_CONTAINED)
1614.             topcontnr = topcontnr->ocontainer;
1615.         /* obj's weight has been reduced, but weight(s) of enclosing
1616.            container(s) haven't been adjusted for that yet */
1617.         old_top_owt = topcontnr->owt;
1618.         /* update those weights now; recursively updates nested containers */
1619.         container_weight(contnr);
1620. 
1621.         if (topcontnr->where == OBJ_INVENT) {
1622.             /* for regular containers, the weight will always be reduced
1623.                when glob's weight has been reduced but we only say so
1624.                when shrinking beneath a particular threshold (N*20 to
1625.                (N-1)*20 + 19 or (N-1)*20 + 10 to (N-1)*20 + 9), or
1626.                if we're going to report a change in carrying capacity;
1627.                for a non-cursed bag of holding the total weight might not
1628.                change because only a fraction of glob's weight is counted;
1629.                however, always say the bag is lighter for the 'gone' case */
1630.             if (gone || (shrink && topcontnr->owt != old_top_owt)
1631.                 || near_capacity() != go.oldcap)
1632.                 pline("%s %s%s lighter.", Yname2(topcontnr),
1633.                       /* containers also always have quantity 1 */
1634.                       (topcontnr->owt != old_top_owt) ? "becomes" : "seems",
1635.                       /* TODO?  maybe also skip "slightly" if description
1636.                          is changing (from "very large" to "large",
1637.                          "large" to "medium", or "medium to "small") */
1638.                       !gone ? " slightly" : "");
1639.             updinv = TRUE;
1640.         }
1641.     }
1642. 
1643.     if (gone) {
1644.         coordxy ox = 0, oy = 0;
1645.         /* check location for visibility before destroying obj */
1646.         boolean seeit = (obj->where == OBJ_FLOOR
1647.                          && get_obj_location(obj, &ox, &oy, 0)
1648.                          && cansee(ox, oy));
1649. 
1650.         /* weight has been reduced to 0 so destroy the glob */
1651.         shrinking_glob_gone(obj);
1652. 
1653.         if (seeit) {
1654.             newsym(ox, oy);
1655.             if ((ox != u.ux || oy != u.uy) && !strncmp(globnambuf, "The ", 4))
1656.                 /* fortunately none of the glob adjectives warrant "An " */
1657.                 (void) strsubst(globnambuf, "The ", "A ");
1658.             /* again, quantity is always 1 so no need for otense()/vtense() */
1659.             pline("%s fades away.", globnambuf);
1660.         }
1661.     } else {
1662.         /* schedule next shrink ~25 turns from now */
1663.         start_glob_timeout(obj, 0L);
1664.     }
1665.     if (updinv) {
1666.         update_inventory();
1667.         encumber_msg();
1668.     }
1669. }
1670. 
1671. /* a glob has shrunk away to nothing; handle owornmask, then delete glob */
1672. staticfn void
1673. shrinking_glob_gone(struct obj *obj)
1674. {
1675.     xint16 owhere = obj->where;
1676. 
1677.     if (owhere == OBJ_INVENT) {
1678.         if (obj->owornmask) {
1679.             remove_worn_item(obj, FALSE);
1680.             stop_occupation();
1681.         }
1682.         useupall(obj); /* freeinv()+obfree() */
1683.     } else {
1684.         if (owhere == OBJ_MIGRATING) {
1685.             /* destination flag overloads owornmask; clear it so obfree()'s
1686.                check for freeing a worn object doesn't get a false hit */
1687.             obj->owornmask = 0L;
1688.         } else if (owhere == OBJ_MINVENT) {
1689.             /* monsters don't wield globs so this isn't strictly needed */
1690.             if (obj->owornmask && obj == MON_WEP(obj->ocarry))
1691.                 setmnotwielded(obj->ocarry, obj); /* clears owornmask */
1692.         }
1693.         /* remove the glob from whatever list it's on and then delete it;
1694.            if it's contained, obj_extract_self() will update the container's
1695.            weight and if nested, the enclosing containers' weights too */
1696.         obj_extract_self(obj);
1697.         if (owhere == OBJ_FLOOR)
1698.             maybe_unhide_at(obj->ox, obj->oy);
1699.         obfree(obj, (struct obj *) 0);
1700.     }
1701. }
1702. 
1703. void
1704. maybe_adjust_light(struct obj *obj, int old_range)
1705. {
1706.     char buf[BUFSZ];
1707.     coordxy ox, oy;
1708.     int new_range = arti_light_radius(obj), delta = new_range - old_range;
1709. 
1710.     /* radius of light emitting artifact varies by curse/bless state
1711.        so will change after blessing or cursing */
1712.     if (delta) {
1713.         obj_adjust_light_radius(obj, new_range);
1714.         /* simplifying assumptions:  hero is wielding or wearing this object;
1715.            artifacts have to be in use to emit light and monsters' gear won't
1716.            change bless or curse state */
1717.         if (!Blind && get_obj_location(obj, &ox, &oy, 0)) {
1718.             *buf = '\0';
1719.             if (iflags.last_msg == PLNMSG_OBJ_GLOWS)
1720.                 /* we just saw "The <obj> glows <color>." from dipping */
1721.                 Strcpy(buf, (obj->quan == 1L) ? "It" : "They");
1722.             else if (carried(obj) || cansee(ox, oy))
1723.                 Strcpy(buf, Yname2(obj));
1724.             if (*buf) {
1725.                 /* initial activation says "dimly" if cursed,
1726.                    "brightly" if uncursed, and "brilliantly" if blessed;
1727.                    when changing intensity, using "less brightly" is
1728.                    straightforward for dimming, but we need "brighter"
1729.                    rather than "more brightly" for brightening; ugh */
1730.                 pline("%s %s %s%s.", buf, otense(obj, "shine"),
1731.                       (abs(delta) > 1) ? "much " : "",
1732.                       (delta > 0) ? "brighter" : "less brightly");
1733.             }
1734.         }
1735.     }
1736. }
1737. 
1738. /*
1739.  *      bless(), curse(), unbless(), uncurse() -- any relevant message
1740.  *      about glowing amber/black/&c should be delivered prior to calling
1741.  *      these routines to make the actual curse/bless state change.
1742.  */
1743. 
1744. void
1745. bless(struct obj *otmp)
1746. {
1747.     int old_light = 0;
1748. 
1749.     if (otmp->oclass == COIN_CLASS)
1750.         return;
1751.     if (otmp->lamplit)
1752.         old_light = arti_light_radius(otmp);
1753.     otmp->cursed = 0;
1754.     otmp->blessed = 1;
1755.     if (carried(otmp) && confers_luck(otmp))
1756.         set_moreluck();
1757.     else if (otmp->otyp == BAG_OF_HOLDING)
1758.         otmp->owt = weight(otmp);
1759.     else if (otmp->otyp == FIGURINE && otmp->timed)
1760.         (void) stop_timer(FIG_TRANSFORM, obj_to_any(otmp));
1761.     if (otmp->lamplit)
1762.         maybe_adjust_light(otmp, old_light);
1763.     return;
1764. }
1765. 
1766. void
1767. unbless(struct obj *otmp)
1768. {
1769.     int old_light = 0;
1770. 
1771.     if (otmp->lamplit)
1772.         old_light = arti_light_radius(otmp);
1773.     otmp->blessed = 0;
1774.     if (carried(otmp) && confers_luck(otmp))
1775.         set_moreluck();
1776.     else if (otmp->otyp == BAG_OF_HOLDING)
1777.         otmp->owt = weight(otmp);
1778.     if (otmp->lamplit)
1779.         maybe_adjust_light(otmp, old_light);
1780. }
1781. 
1782. void
1783. curse(struct obj *otmp)
1784. {
1785.     unsigned already_cursed;
1786.     int old_light = 0;
1787. 
1788.     if (otmp->oclass == COIN_CLASS)
1789.         return;
1790.     if (otmp->lamplit)
1791.         old_light = arti_light_radius(otmp);
1792.     already_cursed = otmp->cursed;
1793.     otmp->blessed = 0;
1794.     otmp->cursed = 1;
1795.     /* welded two-handed weapon interferes with some armor removal */
1796.     if (otmp == uwep && bimanual(uwep))
1797.         reset_remarm();
1798.     /* rules at top of wield.c state that twoweapon cannot be done
1799.        with cursed alternate weapon */
1800.     if (otmp == uswapwep && u.twoweap)
1801.         drop_uswapwep();
1802.     /* some cursed items need immediate updating */
1803.     if (carried(otmp) && confers_luck(otmp)) {
1804.         set_moreluck();
1805.     } else if (otmp->otyp == BAG_OF_HOLDING) {
1806.         otmp->owt = weight(otmp);
1807.     } else if (otmp->otyp == FIGURINE) {
1808.         if (otmp->corpsenm != NON_PM && !dead_species(otmp->corpsenm, TRUE)
1809.             && (carried(otmp) || mcarried(otmp)))
1810.             attach_fig_transform_timeout(otmp);
1811.     } else if (otmp->oclass == SPBOOK_CLASS) {
1812.         /* if book hero is reading becomes cursed, interrupt */
1813.         if (!already_cursed)
1814.             book_cursed(otmp);
1815.     }
1816.     if (otmp->lamplit)
1817.         maybe_adjust_light(otmp, old_light);
1818.     return;
1819. }
1820. 
1821. void
1822. uncurse(struct obj *otmp)
1823. {
1824.     int old_light = 0;
1825. 
1826.     if (otmp->lamplit)
1827.         old_light = arti_light_radius(otmp);
1828.     otmp->cursed = 0;
1829.     if (carried(otmp) && confers_luck(otmp))
1830.         set_moreluck();
1831.     else if (otmp->otyp == BAG_OF_HOLDING)
1832.         otmp->owt = weight(otmp);
1833.     else if (otmp->otyp == FIGURINE && otmp->timed)
1834.         (void) stop_timer(FIG_TRANSFORM, obj_to_any(otmp));
1835.     if (otmp->lamplit)
1836.         maybe_adjust_light(otmp, old_light);
1837.     return;
1838. }
1839. 
1840. void
1841. blessorcurse(struct obj *otmp, int chance)
1842. {
1843.     if (otmp->blessed || otmp->cursed)
1844.         return;
1845. 
1846.     if (!rn2(chance)) {
1847.         if (!rn2(2)) {
1848.             curse(otmp);
1849.         } else {
1850.             bless(otmp);
1851.         }
1852.     }
1853.     return;
1854. }
1855. 
1856. int
1857. bcsign(struct obj *otmp)
1858. {
1859.     return (!!otmp->blessed - !!otmp->cursed);
1860. }
1861. 
1862. /* set the object's bless/curse-state known flag */
1863. void
1864. set_bknown(
1865.     struct obj *obj,
1866.     unsigned int onoff) /* 1 or 0 */
1867. {
1868.     if (obj->bknown != onoff) {
1869.         obj->bknown = onoff;
1870.         if (obj->where == OBJ_INVENT && svm.moves > 1L)
1871.             update_inventory();
1872.     }
1873. }
1874. 
1875. /*
1876.  *  Calculate the weight of the given object.  This will recursively follow
1877.  *  and calculate the weight of any containers.
1878.  *
1879.  *  Note:  It is possible to end up with an incorrect weight if some part
1880.  *         of the code messes with a contained object and doesn't update the
1881.  *         container's weight.
1882.  *
1883.  *  Note too: obj->owt is an unsigned int and objects[].oc_weight an
1884.  *         unsigned short int, so weight() should probably be changed to
1885.  *         use and return unsigned int instead of signed int.
1886.  */
1887. int
1888. weight(struct obj *obj)
1889. {
1890.     int wt = (int) objects[obj->otyp].oc_weight; /* weight of 1 'otyp' */
1891. 
1892.     if (obj->quan < 1L) {
1893.         impossible("Calculating weight of %ld %s?",
1894.                    obj->quan, simpleonames(obj));
1895.         return 0;
1896.     }
1897.     /* glob absorption means that merging globs combines their weight
1898.        while quantity stays 1; mksobj(), obj_absorb(), and shrink_glob()
1899.        manage glob->owt and there is nothing for weight() to do except
1900.        return the current value as-is */
1901.     if (obj->globby) {
1902.         /* 5.0: in 3.6.x this checked for owt==0 and then used
1903.            owt as-is when non-zero or objects[].oc_weight if zero;
1904.            we don't do that anymore because it confused calculating
1905.            the weight of a container when a glob inside shrank down
1906.            to 0 and was about to be deleted [mksobj() now initializes
1907.            owt for globs sooner and the subsequent o->owt = weight(o)
1908.            general initialization is benignly redundant for globs] */
1909.         return (int) obj->owt;
1910.     }
1911.     if (Is_container(obj) || obj->otyp == STATUE) {
1912.         struct obj *contents;
1913.         int cwt;
1914. 
1915.         if (obj->otyp == STATUE && ismnum(obj->corpsenm)) {
1916.             int msize = (int) mons[obj->corpsenm].msize, /* 0..7 */
1917.                 minwt = (msize + msize + 1) * 100;
1918. 
1919.             /* default statue weight is 1.5 times corpse weight */
1920.             wt = 3 * (int) mons[obj->corpsenm].cwt / 2;
1921.             /* some monsters that never leave a corpse when they die have
1922.                corpse weight defined as 0; statues resembling them need to
1923.                have non-zero weight; others are so tiny (killer bee) that
1924.                they weigh barely more than nothing or so insubstantial
1925.                (wraith) that they actually weigh nothing; statues of such
1926.                need more heft */
1927.             if (wt < minwt)
1928.                 wt = minwt;
1929.             /* this has no effect because statues don't stack */
1930.             wt *= (int) obj->quan;
1931.         }
1932. 
1933.         cwt = 0; /* contents weight */
1934.         for (contents = obj->cobj; contents; contents = contents->nobj)
1935.             cwt += weight(contents);
1936.         /*
1937.          *  The weight of bags of holding is calculated as the weight
1938.          *  of the bag plus the weight of the bag's contents modified
1939.          *  as follows:
1940.          *
1941.          *      Bag status      Weight of contents
1942.          *      ----------      ------------------
1943.          *      cursed                  2x
1944.          *      blessed                 x/4 [rounded up: (x+3)/4]
1945.          *      otherwise               x/2 [rounded up: (x+1)/2]
1946.          *
1947.          *  The macro DELTA_CWT in pickup.c also implements these
1948.          *  weight equations.
1949.          */
1950.         if (obj->otyp == BAG_OF_HOLDING)
1951.             cwt = obj->cursed ? (cwt * 2)
1952.                   : obj->blessed ? ((cwt + 3) / 4)
1953.                     : ((cwt + 1) / 2); /* uncursed */
1954. 
1955.         return wt + cwt;
1956.     }
1957.     if (obj->otyp == CORPSE && ismnum(obj->corpsenm)) {
1958.         long long_wt = obj->quan * (long) mons[obj->corpsenm].cwt;
1959. 
1960.         wt = (long_wt > LARGEST_INT) ? LARGEST_INT : (int) long_wt;
1961.         if (obj->oeaten)
1962.             wt = eaten_stat(wt, obj);
1963.         return wt;
1964.     } else if (obj->oclass == FOOD_CLASS && obj->oeaten) {
1965.         return eaten_stat((int) obj->quan * wt, obj);
1966.     } else if (obj->oclass == COIN_CLASS) {
1967.         /* 5.0: always weigh at least 1 unit; used to yield 0 for 1..49 */
1968.         wt = (int) ((obj->quan + 50L) / 100L);
1969.         return max(wt, 1);
1970.     } else if (obj->otyp == HEAVY_IRON_BALL && obj->owt != 0) {
1971.         return (int) obj->owt; /* kludge for "very" heavy iron ball */
1972.     } else if (obj->otyp == CANDELABRUM_OF_INVOCATION && obj->spe) {
1973.         return wt + obj->spe * (int) objects[TALLOW_CANDLE].oc_weight;
1974.     }
1975.     return (wt ? wt * (int) obj->quan : ((int) obj->quan + 1) >> 1);
1976. }
1977. 
1978. static const int treefruits[] = {
1979.     APPLE, ORANGE, PEAR, BANANA, EUCALYPTUS_LEAF
1980. };
1981. 
1982. /* called when a tree is kicked; never returns Null */
1983. struct obj *
1984. rnd_treefruit_at(coordxy x, coordxy y)
1985. {
1986.     return mksobj_at(ROLL_FROM(treefruits), x, y, TRUE, FALSE);
1987. }
1988. 
1989. /* for describing objects embedded in trees */
1990. boolean
1991. is_treefruit(struct obj *otmp)
1992. {
1993.     int fruitidx;
1994. 
1995.     for (fruitidx = 0; fruitidx < SIZE(treefruits); ++fruitidx)
1996.         if (treefruits[fruitidx] == otmp->otyp)
1997.             return TRUE;
1998.     return FALSE;
1999. }
2000. 
2001. /* create a stack of N gold pieces; never returns Null */
2002. struct obj *
2003. mkgold(long amount, coordxy x, coordxy y)
2004. {
2005.     struct obj *gold = g_at(x, y);
2006. 
2007.     if (amount <= 0L) {
2008.         long mul = rnd(30 / max(12-depth(&u.uz), 2));
2009. 
2010.         amount = (long) (1 + rnd(level_difficulty() + 2) * mul);
2011.     }
2012.     if (gold) {
2013.         gold->quan += amount;
2014.     } else {
2015.         gold = mksobj_at(GOLD_PIECE, x, y, TRUE, FALSE);
2016.         gold->quan = amount;
2017.     }
2018.     gold->owt = weight(gold);
2019.     return gold;
2020. }
2021. 
2022. /* potions of oil use their obj->age field differently from other potions
2023.    so changing potion type to or from oil needs to have that fixed up */
2024. void
2025. fixup_oil(
2026.     struct obj *potion, /* potion that just had its otyp changed */
2027.     struct obj *source) /* item used to create potion; might be Null */
2028. {
2029.     if (potion->otyp == POT_OIL) {
2030.         if (source && source->otyp == POT_OIL) {
2031.             /* potion of oil being used to set potion's otyp to oil;
2032.                source might be partly used */
2033.             potion->age = source->age;
2034.         } else {
2035.             /* non-oil is being turned into oil; change absolute age
2036.                (turn created) into relative age (amount remaining /
2037.                burn time available) */
2038.             potion->age = MAX_OIL_IN_FLASK;
2039.         }
2040.     } else if (source && source->otyp == POT_OIL) {
2041.         /* potion is no longer oil, being turned into non-oil */
2042.         if (potion->age == source->age)
2043.             potion->age = svm.moves;
2044.         /* when source is a partly used oil, mark potion as diluted */
2045.         if (source->age < MAX_OIL_IN_FLASK)
2046.             potion->odiluted = 1;
2047.     }
2048. }
2049. 
2050. /* return TRUE if the corpse has special timing;
2051.    lizards and lichen don't rot, trolls and Riders auto-revive */
2052. #define special_corpse(num) \
2053.     (((num) == PM_LIZARD || (num) == PM_LICHEN)                 \
2054.      || (mons[num].mlet == S_TROLL || is_rider(&mons[num])))
2055. 
2056. /* mkcorpstat: make a corpse or statue; never returns Null.
2057.  *
2058.  * OEXTRA note: Passing mtmp causes mtraits to be saved
2059.  * even if ptr passed as well, but ptr is always used for
2060.  * the corpse type (corpsenm). That allows the corpse type
2061.  * to be different from the original monster,
2062.  *      i.e.  vampire -> human corpse
2063.  * yet still allow restoration of the original monster upon
2064.  * resurrection.
2065.  */
2066. struct obj *
2067. mkcorpstat(
2068.     int objtype,          /* CORPSE or STATUE */
2069.     struct monst *mtmp,   /* dead monster, might be Null */
2070.     struct permonst *ptr, /* if non-Null, overrides mtmp->mndx */
2071.     coordxy x, coordxy y,         /* where to place corpse; <0,0> => random */
2072.     unsigned corpstatflags)
2073. {
2074.     struct obj *otmp;
2075.     boolean init = ((corpstatflags & CORPSTAT_INIT) != 0);
2076. 
2077.     if (objtype != CORPSE && objtype != STATUE)
2078.         impossible("making corpstat type %d", objtype);
2079.     if (x == 0 && y == 0) { /* special case - random placement */
2080.         otmp = mksobj(objtype, init, FALSE);
2081.         (void) rloco(otmp);
2082.     } else {
2083.         otmp = mksobj_at(objtype, x, y, init, FALSE);
2084.     }
2085.     /* record gender and 'historic statue' in overloaded enchantment field */
2086.     otmp->spe = (corpstatflags & CORPSTAT_SPE_VAL);
2087.     otmp->norevive = gm.mkcorpstat_norevive; /* via envrmt rather than flags */
2088. 
2089.     /* when 'mtmp' is non-null save the monster's details with the
2090.        corpse or statue; it will also force the 'ptr' override below */
2091.     if (mtmp) {
2092.         /* save_mtraits updates otmp->oextra->omonst in place */
2093.         (void) save_mtraits(otmp, mtmp);
2094. 
2095.         if (!ptr)
2096.             ptr = mtmp->data;
2097. 
2098.         /* don't give a revive timer to a cancelled troll's corpse */
2099.         if (mtmp->mcan && !is_rider(ptr))
2100.             otmp->norevive = 1;
2101.     }
2102. 
2103.     /* when 'ptr' is non-null it comes from our caller or from 'mtmp';
2104.        override mkobjs()'s initialization of a random monster type */
2105.     if (ptr) {
2106.         int old_corpsenm = otmp->corpsenm;
2107. 
2108.         otmp->corpsenm = monsndx(ptr);
2109.         otmp->owt = weight(otmp);
2110.         if (otmp->otyp == CORPSE
2111.             && (gz.zombify || special_corpse(old_corpsenm)
2112.                 || special_corpse(otmp->corpsenm))) {
2113.             obj_stop_timers(otmp);
2114.             start_corpse_timeout(otmp);
2115.         }
2116.     }
2117.     return otmp;
2118. }
2119. 
2120. /*
2121.  * Return the type of monster that this corpse will
2122.  * revive as, even if it has a monster structure
2123.  * attached to it. In that case, you can't just
2124.  * use obj->corpsenm, because the stored monster
2125.  * type can, and often is, different.
2126.  * The return value is an index into mons[].
2127.  */
2128. int
2129. corpse_revive_type(struct obj *obj)
2130. {
2131.     int revivetype = obj->corpsenm;
2132.     struct monst *mtmp;
2133. 
2134.     if (has_omonst(obj) && ((mtmp = get_mtraits(obj, FALSE)) != 0)) {
2135.         /* mtmp is a temporary pointer to a monster's stored
2136.         attributes, not a real monster */
2137.         revivetype = mtmp->mnum;
2138.     }
2139.     return revivetype;
2140. }
2141. 
2142. /*
2143.  * Attach a monster id to an object, to provide
2144.  * a lasting association between the two.
2145.  */
2146. struct obj *
2147. obj_attach_mid(struct obj *obj, unsigned int mid)
2148. {
2149.     if (!mid || !obj)
2150.         return (struct obj *) 0;
2151.     newomid(obj);
2152.     OMID(obj) = mid;
2153.     return obj;
2154. }
2155. 
2156. staticfn struct obj *
2157. save_mtraits(struct obj *obj, struct monst *mtmp)
2158. {
2159.     if (mtmp->ispriest)
2160.         forget_temple_entry(mtmp); /* EPRI() */
2161.     if (!has_omonst(obj))
2162.         newomonst(obj);
2163.     if (has_omonst(obj)) {
2164.         int baselevel = mtmp->data->mlevel; /* mtmp->data is valid ptr */
2165.         struct monst *mtmp2 = OMONST(obj);
2166. 
2167.         *mtmp2 = *mtmp;
2168.         mtmp2->mextra = (struct mextra *) 0;
2169.         mtmp2->mnum = monsndx(mtmp->data);
2170.         /* invalidate pointers */
2171.         /* m_id is needed to know if this is a revived quest leader */
2172.         /* but m_id must be cleared when loading bones */
2173.         mtmp2->nmon = (struct monst *) 0;
2174.         mtmp2->data = (struct permonst *) 0;
2175.         mtmp2->minvent = (struct obj *) 0;
2176.         MON_NOWEP(mtmp2); /* mtmp2->mw = (struct obj *) 0; */
2177.         if (mtmp->mextra)
2178.             copy_mextra(mtmp2, mtmp);
2179.         /* if mtmp is a long worm with segments, its saved traits will
2180.            be one without any segments */
2181.         mtmp2->wormno = 0;
2182.         /* mtmp might have been killed by repeated life draining; make sure
2183.            mtmp2 can survive if revived ('baselevel' will be 0 for 1d4 mon) */
2184.         if (mtmp2->mhpmax <= baselevel)
2185.             mtmp2->mhpmax = baselevel + 1;
2186.         /* mtmp is assumed to be dead but we don't kill it or its saved
2187.            traits, just force those to have a sane value for current HP */
2188.         if (mtmp2->mhp > mtmp2->mhpmax)
2189.             mtmp2->mhp = mtmp2->mhpmax;
2190.         if (mtmp2->mhp < 1)
2191.             mtmp2->mhp = 0;
2192.         mtmp2->mstate &= ~MON_DETACH;
2193.     }
2194.     return obj;
2195. }
2196. 
2197. /* returns a pointer to a new monst structure based on
2198.  * the one contained within the obj.
2199.  */
2200. struct monst *
2201. get_mtraits(struct obj *obj, boolean copyof)
2202. {
2203.     struct monst *mtmp = (struct monst *) 0;
2204.     struct monst *mnew = (struct monst *) 0;
2205. 
2206.     if (has_omonst(obj))
2207.         mtmp = OMONST(obj);
2208.     if (mtmp) {
2209.         if (copyof) {
2210.             mnew = newmonst();
2211.             *mnew = *mtmp;
2212.             mnew->mextra = (struct mextra *) 0;
2213.             if (mtmp->mextra)
2214.                 copy_mextra(mnew, mtmp);
2215.         } else {
2216.             /* Never insert this returned pointer into mon chains! */
2217.             mnew = mtmp;
2218.         }
2219.         mnew->data = &mons[mnew->mnum];
2220.     }
2221.     return mnew;
2222. }
2223. 
2224. /* make an object named after someone listed in the scoreboard file;
2225.    never returns Null */
2226. struct obj *
2227. mk_tt_object(
2228.     int objtype, /* CORPSE or STATUE */
2229.     coordxy x, coordxy y)
2230. {
2231.     struct obj *otmp;
2232.     boolean initialize_it;
2233. 
2234.     /* player statues never contain books */
2235.     initialize_it = (objtype != STATUE);
2236.     otmp = mksobj_at(objtype, x, y, initialize_it, FALSE);
2237. 
2238.     /* tt_oname() will return null if the scoreboard is empty, which in
2239.        turn leaves the random corpsenm value; force it to match a player */
2240.     if (!tt_oname(otmp)) {
2241.         int pm = rn1(PM_WIZARD - PM_ARCHEOLOGIST + 1, PM_ARCHEOLOGIST);
2242. 
2243.         /* update weight for either, force timer sanity for corpses */
2244.         set_corpsenm(otmp, pm);
2245.     }
2246. 
2247.     return otmp;
2248. }
2249. 
2250. /* make a new corpse or statue, uninitialized if a statue (i.e. no books);
2251.    never returns Null */
2252. struct obj *
2253. mk_named_object(
2254.     int objtype, /* CORPSE or STATUE */
2255.     struct permonst *ptr,
2256.     coordxy x, coordxy y,
2257.     const char *nm)
2258. {
2259.     struct obj *otmp;
2260.     unsigned corpstatflags = (objtype != STATUE) ? CORPSTAT_INIT
2261.                                                  : CORPSTAT_NONE;
2262. 
2263.     otmp = mkcorpstat(objtype, (struct monst *) 0, ptr, x, y, corpstatflags);
2264.     if (nm)
2265.         otmp = oname(otmp, nm, ONAME_NO_FLAGS);
2266.     return otmp;
2267. }
2268. 
2269. boolean
2270. is_flammable(struct obj *otmp)
2271. {
2272.     int otyp = otmp->otyp;
2273.     int omat = objects[otyp].oc_material;
2274. 
2275.     /* Candles can be burned, but they're not flammable in the sense that
2276.      * they can't get fire damage and it makes no sense for them to be
2277.      * fireproofed.
2278.      */
2279.     if (Is_candle(otmp))
2280.         return FALSE;
2281. 
2282.     if (objects[otyp].oc_oprop == FIRE_RES || otyp == WAN_FIRE)
2283.         return FALSE;
2284. 
2285.     return (boolean) ((omat <= WOOD && omat != LIQUID) || omat == PLASTIC);
2286. }
2287. 
2288. boolean
2289. is_rottable(struct obj *otmp)
2290. {
2291.     int otyp = otmp->otyp;
2292. 
2293.     return (boolean) ((objects[otyp].oc_material <= WOOD
2294.                        && objects[otyp].oc_material != LIQUID)
2295.                       || objects[otyp].oc_material == DRAGON_HIDE);
2296. }
2297. 
2298. /*
2299.  * These routines maintain the single-linked lists headed in level.objects[][]
2300.  * and threaded through the nexthere fields in the object-instance structure.
2301.  */
2302. 
2303. /* put the object at the given location */
2304. void
2305. place_object(struct obj *otmp, coordxy x, coordxy y)
2306. {
2307.     struct obj *otmp2;
2308. 
2309.     if (!isok(x, y)) { /* validate location */
2310.         void (*func)(const char *, ...) PRINTF_F_PTR(1, 2);
2311. 
2312.         func = (x < 0 || y < 0 || x > COLNO - 1 || y > ROWNO - 1) ? panic
2313.                : impossible;
2314.         (*func)("place_object: \"%s\" [%d] off map <%d,%d>",
2315.                 safe_typename(otmp->otyp), otmp->where, x, y);
2316. 
2317.         /* we'll only get to here if we've issued a warning (and fuzzer
2318.            is not running since it escalates impossible to panic), so
2319.            x,y has failed isok() but is within array bounds for the map;
2320.            in other words, x specifies column 0 which should not happen
2321.            but we let the game keep going */
2322.     }
2323.     if (otmp->where != OBJ_FREE)
2324.         panic("place_object: obj \"%s\" [%d] not free",
2325.               safe_typename(otmp->otyp), otmp->where);
2326. 
2327.     assert(x >= 0 && x < COLNO && y >= 0 && y < ROWNO);
2328.     otmp2 = svl.level.objects[x][y];
2329. 
2330.     obj_no_longer_held(otmp);
2331.     if (otmp->otyp == BOULDER) {
2332.         if (!otmp2 || otmp2->otyp != BOULDER)
2333.             block_point(x, y); /* vision */
2334.     }
2335. 
2336.     /* non-boulder object goes under boulders so that map will show boulder
2337.        here without display code needing to traverse pile chain to find one */
2338.     if (otmp2 && otmp2->otyp == BOULDER && otmp->otyp != BOULDER) {
2339.         /* 3.6.3: put otmp under last consecutive boulder rather than under
2340.            just the first one */
2341.         while (otmp2->nexthere && otmp2->nexthere->otyp == BOULDER)
2342.             otmp2 = otmp2->nexthere;
2343.         otmp->nexthere = otmp2->nexthere;
2344.         otmp2->nexthere = otmp;
2345.     } else {
2346.         /* put on top of current pile */
2347.         otmp->nexthere = otmp2;
2348.         svl.level.objects[x][y] = otmp;
2349.     }
2350. 
2351.     /* set the object's new location */
2352.     otmp->ox = x;
2353.     otmp->oy = y;
2354.     otmp->where = OBJ_FLOOR;
2355. 
2356.     /* if placed outside of shop, no_charge is no longer applicable */
2357.     if (otmp->no_charge && !costly_spot(x, y)
2358.         && !costly_adjacent(find_objowner(otmp, x, y), x, y))
2359.         otmp->no_charge = 0;
2360. 
2361.     /* add to floor chain */
2362.     otmp->nobj = fobj;
2363.     fobj = otmp;
2364.     if (otmp->timed)
2365.         obj_timer_checks(otmp, x, y, 0);
2366. }
2367. 
2368. /* tear down the object pile at <x,y> and create it again, so that any
2369.    boulders which are present get forced to the top */
2370. void
2371. recreate_pile_at(coordxy x, coordxy y)
2372. {
2373.     struct obj *otmp, *next_obj, *reversed = 0;
2374. 
2375.     /* remove all objects at <x,y>, saving a reversed temporary list */
2376.     for (otmp = svl.level.objects[x][y]; otmp; otmp = next_obj) {
2377.         next_obj = otmp->nexthere;
2378.         remove_object(otmp); /* obj_extract_self() for floor */
2379.         otmp->nobj = reversed;
2380.         reversed = otmp;
2381.     }
2382.     /* pile at <tx,ty> is now empty; create new one, re-reversing to restore
2383.        original order; place_object() handles making boulders be on top */
2384.     for (otmp = reversed; otmp; otmp = next_obj) {
2385.         next_obj = otmp->nobj;
2386.         otmp->nobj = 0; /* obj->where is OBJ_FREE */
2387.         place_object(otmp, x, y);
2388.     }
2389. }
2390. 
2391. #define ROT_ICE_ADJUSTMENT 2 /* rotting on ice takes 2 times as long */
2392. 
2393. /* If ice was affecting any objects correct that now
2394.  * Also used for starting ice effects too. [zap.c]
2395.  */
2396. void
2397. obj_ice_effects(coordxy x, coordxy y, boolean do_buried)
2398. {
2399.     struct obj *otmp;
2400. 
2401.     for (otmp = svl.level.objects[x][y]; otmp; otmp = otmp->nexthere) {
2402.         if (otmp->timed)
2403.             obj_timer_checks(otmp, x, y, 0);
2404.     }
2405.     if (do_buried) {
2406.         for (otmp = svl.level.buriedobjlist; otmp; otmp = otmp->nobj) {
2407.             if (otmp->ox == x && otmp->oy == y) {
2408.                 if (otmp->timed)
2409.                     obj_timer_checks(otmp, x, y, 0);
2410.             }
2411.         }
2412.     }
2413. }
2414. 
2415. /*
2416.  * Returns an obj->age for a corpse object on ice, that would be the
2417.  * actual obj->age if the corpse had just been lifted from the ice.
2418.  * This is useful when just using obj->age in a check or calculation because
2419.  * rot timers pertaining to the object don't have to be stopped and
2420.  * restarted etc.
2421.  */
2422. long
2423. peek_at_iced_corpse_age(struct obj *otmp)
2424. {
2425.     long age, retval = otmp->age;
2426. 
2427.     if (otmp->otyp == CORPSE && otmp->on_ice) {
2428.         /* Adjust the age; must be same as obj_timer_checks() for off ice*/
2429.         age = svm.moves - otmp->age;
2430.         retval += age * (ROT_ICE_ADJUSTMENT - 1) / ROT_ICE_ADJUSTMENT;
2431.         debugpline3(
2432.           "The %s age has ice modifications: otmp->age = %ld, returning %ld.",
2433.                     s_suffix(doname(otmp)), otmp->age, retval);
2434.         debugpline1("Effective age of corpse: %ld.", svm.moves - retval);
2435.     }
2436.     return retval;
2437. }
2438. 
2439. staticfn void
2440. obj_timer_checks(
2441.     struct obj *otmp,
2442.     coordxy x, coordxy y,
2443.     int force) /* 0 = no force so do checks, <0 = force off, >0 force on */
2444. {
2445.     long tleft = 0L;
2446.     short action = ROT_CORPSE;
2447.     boolean restart_timer = FALSE;
2448.     boolean on_floor = (otmp->where == OBJ_FLOOR);
2449.     boolean buried = (otmp->where == OBJ_BURIED);
2450. 
2451.     /* Check for corpses just placed on or in ice */
2452.     if (otmp->otyp == CORPSE && (on_floor || buried) && is_ice(x, y)) {
2453.         tleft = stop_timer(action, obj_to_any(otmp));
2454.         if (tleft == 0L) {
2455.             action = REVIVE_MON;
2456.             tleft = stop_timer(action, obj_to_any(otmp));
2457.         }
2458.         if (tleft != 0L) {
2459.             long age;
2460. 
2461.             /* mark the corpse as being on ice */
2462.             otmp->on_ice = 1;
2463.             debugpline3("%s is now on ice at <%d,%d>.",
2464.                         The(xname(otmp)), x, y);
2465.             /* Adjust the time remaining */
2466.             tleft *= ROT_ICE_ADJUSTMENT;
2467.             restart_timer = TRUE;
2468.             /* Adjust the age; time spent off ice needs to be multiplied
2469.                by the ice adjustment and subtracted from the age so that
2470.                later calculations behave as if it had been on ice during
2471.                that time (longwinded way of saying this is the inverse
2472.                of removing it from the ice and of peeking at its age). */
2473.             age = svm.moves - otmp->age;
2474.             otmp->age = svm.moves - (age * ROT_ICE_ADJUSTMENT);
2475.         }
2476. 
2477.     /* Check for corpses coming off ice */
2478.     } else if (force < 0 || (otmp->otyp == CORPSE && otmp->on_ice
2479.                              && !((on_floor || buried) && is_ice(x, y)))) {
2480.         tleft = stop_timer(action, obj_to_any(otmp));
2481.         if (tleft == 0L) {
2482.             action = REVIVE_MON;
2483.             tleft = stop_timer(action, obj_to_any(otmp));
2484.         }
2485.         if (tleft != 0L) {
2486.             long age;
2487. 
2488.             otmp->on_ice = 0;
2489.             debugpline3("%s is no longer on ice at <%d,%d>.",
2490.                         The(xname(otmp)), x, y);
2491.             /* Adjust the remaining time */
2492.             tleft /= ROT_ICE_ADJUSTMENT;
2493.             restart_timer = TRUE;
2494.             /* Adjust the age */
2495.             age = svm.moves - otmp->age;
2496.             otmp->age += age * (ROT_ICE_ADJUSTMENT - 1) / ROT_ICE_ADJUSTMENT;
2497.         }
2498.     }
2499. 
2500.     /* now re-start the timer with the appropriate modifications */
2501.     if (restart_timer)
2502.         (void) start_timer(tleft, TIMER_OBJECT, action, obj_to_any(otmp));
2503. }
2504. 
2505. #undef ROT_ICE_ADJUSTMENT
2506. 
2507. void
2508. remove_object(struct obj *otmp)
2509. {
2510.     coordxy x = otmp->ox;
2511.     coordxy y = otmp->oy;
2512. 
2513.     if (otmp->where != OBJ_FLOOR)
2514.         panic("remove_object: obj where=%d, not on floor", otmp->where);
2515.     extract_nexthere(otmp, &svl.level.objects[x][y]);
2516.     extract_nobj(otmp, &fobj);
2517.     if (otmp->otyp == BOULDER)
2518.         recalc_block_point(x, y); /* vision */
2519.     if (otmp->timed)
2520.         obj_timer_checks(otmp, x, y, 0);
2521. }
2522. 
2523. /* throw away all of a monster's inventory */
2524. void
2525. discard_minvent(struct monst *mtmp, boolean uncreate_artifacts)
2526. {
2527.     struct obj *otmp;
2528. 
2529.     while ((otmp = mtmp->minvent) != 0) {
2530.         /* this has now become very similar to m_useupall()... */
2531.         extract_from_minvent(mtmp, otmp, TRUE, TRUE);
2532.         if (uncreate_artifacts && otmp->oartifact)
2533.             artifact_exists(otmp, safe_oname(otmp), FALSE, ONAME_NO_FLAGS);
2534.         obfree(otmp, (struct obj *) 0); /* dealloc_obj() isn't sufficient */
2535.     }
2536. }
2537. 
2538. /*
2539.  * Free obj from whatever list it is on in preparation for deleting it
2540.  * or moving it elsewhere; obj->where will end up set to OBJ_FREE unless
2541.  * it is already OBJ_LUAFREE or OBJ_DELETED.
2542.  * Doesn't handle unwearing of objects in hero's or monsters' inventories.
2543.  *
2544.  * Object positions:
2545.  *      OBJ_FREE        not on any list
2546.  *      OBJ_FLOOR       fobj, level.locations[][] chains (use remove_object)
2547.  *      OBJ_CONTAINED   cobj chain of container object
2548.  *      OBJ_INVENT      hero's invent chain (use freeinv)
2549.  *      OBJ_MINVENT     monster's invent chain
2550.  *      OBJ_MIGRATING   migrating chain
2551.  *      OBJ_BURIED      level.buriedobjs chain
2552.  *      OBJ_ONBILL      on gb.billobjs chain
2553.  *      OBJ_LUAFREE     obj is dealloc'd from core, but still used by lua
2554.  *      OBJ_DELETED     obj has been deleted from play but not yet deallocated
2555.  */
2556. void
2557. obj_extract_self(struct obj *obj)
2558. {
2559.     switch (obj->where) {
2560.     case OBJ_FREE:
2561.     case OBJ_LUAFREE:
2562.     case OBJ_DELETED:
2563.         break;
2564.     case OBJ_FLOOR:
2565.         remove_object(obj);
2566.         break;
2567.     case OBJ_CONTAINED:
2568.         extract_nobj(obj, &obj->ocontainer->cobj);
2569.         container_weight(obj->ocontainer);
2570.         obj->ocontainer = (struct obj *) 0; /* clear stale back-link */
2571.         break;
2572.     case OBJ_INVENT:
2573.         freeinv(obj);
2574.         break;
2575.     case OBJ_MINVENT:
2576.         extract_nobj(obj, &obj->ocarry->minvent);
2577.         obj->ocarry = (struct monst *) 0; /* clear stale back-link */
2578.         break;
2579.     case OBJ_MIGRATING:
2580.         extract_nobj(obj, &gm.migrating_objs);
2581.         break;
2582.     case OBJ_BURIED:
2583.         extract_nobj(obj, &svl.level.buriedobjlist);
2584.         break;
2585.     case OBJ_ONBILL:
2586.         extract_nobj(obj, &gb.billobjs);
2587.         break;
2588.     default:
2589.         panic("obj_extract_self, where=%d", obj->where);
2590.         break;
2591.     }
2592. }
2593. 
2594. /* Extract the given object from the chain, following nobj chain. */
2595. void
2596. extract_nobj(struct obj *obj, struct obj **head_ptr)
2597. {
2598.     struct obj *curr, *prev;
2599. 
2600.     curr = *head_ptr;
2601.     for (prev = (struct obj *) 0; curr; prev = curr, curr = curr->nobj) {
2602.         if (curr == obj) {
2603.             if (prev)
2604.                 prev->nobj = curr->nobj;
2605.             else
2606.                 *head_ptr = curr->nobj;
2607.             break;
2608.         }
2609.     }
2610.     if (!curr)
2611.         panic("extract_nobj: object lost");
2612.     obj->where = OBJ_FREE;
2613.     obj->nobj = (struct obj *) 0;
2614. }
2615. 
2616. /*
2617.  * Extract the given object from the chain, following nexthere chain.
2618.  *
2619.  * This does not set obj->where, this function is expected to be called
2620.  * in tandem with extract_nobj, which does set it.
2621.  */
2622. void
2623. extract_nexthere(struct obj *obj, struct obj **head_ptr)
2624. {
2625.     struct obj *curr, *prev;
2626. 
2627.     curr = *head_ptr;
2628.     for (prev = (struct obj *) 0; curr; prev = curr, curr = curr->nexthere) {
2629.         if (curr == obj) {
2630.             if (prev)
2631.                 prev->nexthere = curr->nexthere;
2632.             else
2633.                 *head_ptr = curr->nexthere;
2634.             break;
2635.         }
2636.     }
2637.     if (!curr)
2638.         panic("extract_nexthere: object lost");
2639.     obj->nexthere = (struct obj *) 0;
2640. }
2641. 
2642. /*
2643.  * Add obj to mon's inventory.  If obj is able to merge with something already
2644.  * in the inventory, then the passed obj is deleted and 1 is returned.
2645.  * Otherwise 0 is returned.
2646.  */
2647. int
2648. add_to_minv(struct monst *mon, struct obj *obj)
2649. {
2650.     struct obj *otmp;
2651. 
2652.     if (obj->where != OBJ_FREE)
2653.         panic("add_to_minv: obj where=%d, not free", obj->where);
2654. 
2655.     /* merge if possible */
2656.     for (otmp = mon->minvent; otmp; otmp = otmp->nobj)
2657.         if (merged(&otmp, &obj))
2658.             return 1; /* obj merged and then free'd */
2659.     /* else insert; don't bother forcing it to end of chain */
2660.     obj->where = OBJ_MINVENT;
2661.     obj->ocarry = mon;
2662.     obj->nobj = mon->minvent;
2663.     mon->minvent = obj;
2664.     return 0; /* obj on mon's inventory chain */
2665. }
2666. 
2667. /*
2668.  * Add obj to container, make sure obj is "free".  Returns (merged) obj.
2669.  * The input obj may be deleted in the process.
2670.  *
2671.  * Caveat:  this does not update the container's weight [possibly to
2672.  * prevent that from being recalculated repeatedly when adding multiple
2673.  * items].
2674.  */
2675. struct obj *
2676. add_to_container(struct obj *container, struct obj *obj)
2677. {
2678.     struct obj *otmp;
2679. 
2680.     if (obj->where != OBJ_FREE)
2681.         panic("add_to_container: obj where=%d, not free", obj->where);
2682.     if (container->where != OBJ_INVENT && container->where != OBJ_MINVENT)
2683.         obj_no_longer_held(obj);
2684. 
2685.     /* merge if possible */
2686.     for (otmp = container->cobj; otmp; otmp = otmp->nobj)
2687.         if (merged(&otmp, &obj))
2688.             return otmp;
2689. 
2690.     obj->where = OBJ_CONTAINED;
2691.     obj->ocontainer = container;
2692.     obj->nobj = container->cobj;
2693.     container->cobj = obj;
2694.     return obj;
2695. }
2696. 
2697. void
2698. add_to_migration(struct obj *obj)
2699. {
2700.     if (obj->where != OBJ_FREE)
2701.         panic("add_to_migration: obj where=%d, not free", obj->where);
2702. 
2703.     if (obj->unpaid) /* caller should have changed unpaid item to stolen */
2704.         impossible("unpaid object migrating to another level? [%s]",
2705.                    simpleonames(obj));
2706.     obj->no_charge = 0; /* was only relevant while inside a shop */
2707. 
2708.     /* lock picking context becomes stale if it's for this object */
2709.     if (Is_container(obj))
2710.         maybe_reset_pick(obj);
2711. 
2712.     obj->where = OBJ_MIGRATING;
2713.     obj->nobj = gm.migrating_objs;
2714.     obj->omigr_from_dnum = u.uz.dnum;
2715.     obj->omigr_from_dlevel = u.uz.dlevel;
2716.     gm.migrating_objs = obj;
2717. }
2718. 
2719. void
2720. add_to_buried(struct obj *obj)
2721. {
2722.     if (obj->where != OBJ_FREE)
2723.         panic("add_to_buried: obj where=%d, not free", obj->where);
2724. 
2725.     obj->where = OBJ_BURIED;
2726.     obj->nobj = svl.level.buriedobjlist;
2727.     svl.level.buriedobjlist = obj;
2728. }
2729. 
2730. /* recalculate weight of object, which doesn't have to be a container
2731.    itself; if it is contained, recursively handle _its_ container(s) */
2732. void
2733. container_weight(struct obj *object)
2734. {
2735.     object->owt = weight(object);
2736.     if (object->where == OBJ_CONTAINED)
2737.         container_weight(object->ocontainer);
2738. }
2739. 
2740. /*
2741.  * Mark object to be deallocated.  _All_ objects should be run through here
2742.  * for them to be deallocated.
2743.  */
2744. void
2745. dealloc_obj(struct obj *obj)
2746. {
2747.     if (obj->otyp == BOULDER)
2748.         obj->next_boulder = 0;
2749.     if (obj->where == OBJ_DELETED) {
2750.         impossible("dealloc_obj: obj already deleted (type=%d)", obj->otyp);
2751.         return;
2752.     } else if (obj->where != OBJ_FREE && obj->where != OBJ_LUAFREE) {
2753.         panic("dealloc_obj: obj not free (type=%d, where=%d)",
2754.               obj->otyp, obj->where);
2755.     }
2756.     if (obj->nobj)
2757.         panic("dealloc_obj with nobj");
2758.     if (obj->cobj)
2759.         panic("dealloc_obj with cobj");
2760.     if (obj == &hands_obj) {
2761.         impossible("dealloc_obj with hands_obj");
2762.         return;
2763.     }
2764. 
2765.     /* free up any timers attached to the object */
2766.     if (obj->timed)
2767.         obj_stop_timers(obj);
2768. 
2769.     /*
2770.      * Free up any light sources attached to the object.
2771.      *
2772.      * We may want to just call del_light_source() without any
2773.      * checks (requires a code change there).  Otherwise this
2774.      * list must track all objects that can have a light source
2775.      * attached to it (and also requires lamplit to be set).
2776.      */
2777.     if (obj_sheds_light(obj)) {
2778.         del_light_source(LS_OBJECT, obj_to_any(obj));
2779.         obj->lamplit = 0;
2780.     }
2781. 
2782.     if (obj == gt.thrownobj)
2783.         gt.thrownobj = 0;
2784.     if (obj == gk.kickedobj)
2785.         gk.kickedobj = 0;
2786.     if (obj == svc.context.tin.tin) {
2787.         svc.context.tin.tin = (struct obj *) 0;
2788.         svc.context.tin.o_id = 0;
2789.     }
2790. 
2791.     /* if obj came from the most recent splitobj(), it's no longer eligible
2792.        for unsplitobj(); perform inline clear_splitobjs() */
2793.     if (obj->o_id == svc.context.objsplit.parent_oid
2794.         || obj->o_id == svc.context.objsplit.child_oid)
2795.         svc.context.objsplit.parent_oid = svc.context.objsplit.child_oid = 0;
2796. 
2797.     if (obj->lua_ref_cnt) {
2798.         /* obj is referenced from a lua script, let lua gc free it */
2799.         obj->where = OBJ_LUAFREE;
2800.         return;
2801.     }
2802.     if (!program_state.freeingdata) {
2803.         /* mark object as deleted, put it into queue to be freed */
2804.         obj->where = OBJ_DELETED;
2805.         obj->nobj = go.objs_deleted;
2806.         go.objs_deleted = obj;
2807.     } else {
2808.         /* when saving, there's no need to stage deletions on objs_deleted */
2809.         dealloc_obj_real(obj);
2810.     }
2811. }
2812. 
2813. /* actually deallocate the object */
2814. staticfn void
2815. dealloc_obj_real(struct obj *obj)
2816. {
2817.     if (obj->oextra)
2818.         dealloc_oextra(obj);
2819. 
2820.     /* clear out of date information contained in the about-to-become
2821.        stale memory so that potential used-after-freed bugs (should never
2822.        happen) might trigger an object lost panic instead of continuing;
2823.        linking with a debugging malloc library is likely to do something
2824.        similar so this is mainly useful for ordinary malloc/free */
2825.     *obj = cg.zeroobj;
2826.     free((genericptr_t) obj);
2827. }
2828. 
2829. /* free all the objects marked for deletion */
2830. void
2831. dobjsfree(void)
2832. {
2833.     struct obj *otmp;
2834. 
2835.     while (go.objs_deleted) {
2836.         otmp = go.objs_deleted;
2837.         go.objs_deleted = otmp->nobj;
2838.         if (otmp->where != OBJ_DELETED)
2839.             panic("dobjsfree: obj where=%d, not OBJ_DELETED", otmp->where);
2840.         obj_extract_self(otmp);
2841.         dealloc_obj_real(otmp);
2842.     }
2843. }
2844. 
2845. /* create an object from a horn of plenty; mirrors bagotricks(makemon.c) */
2846. int
2847. hornoplenty(
2848.     struct obj *horn,
2849.     boolean tipping, /* caller emptying entire contents; affects shop mesgs */
2850.     struct obj *targetbox) /* if non-Null, container to tip into */
2851. {
2852.     int objcount = 0;
2853. 
2854.     if (!horn || horn->otyp != HORN_OF_PLENTY) {
2855.         impossible("bad horn o' plenty");
2856.     } else if (horn->spe < 1) {
2857.         pline1(nothing_happens);
2858.         if (!horn->cknown) {
2859.             horn->cknown = 1;
2860.             update_inventory();
2861.         }
2862.     } else {
2863.         struct obj *obj;
2864.         const char *what;
2865. 
2866.         consume_obj_charge(horn, !tipping);
2867.         if (!rn2(13)) {
2868.             obj = mkobj(POTION_CLASS, FALSE);
2869.             if (objects[obj->otyp].oc_magic) {
2870.                 do {
2871.                     obj->otyp = rnd_class(POT_BOOZE, POT_WATER);
2872.                 } while (obj->otyp == POT_SICKNESS);
2873.                 /* oil uses obj->age field differently from other potions */
2874.                 if (obj->otyp == POT_OIL)
2875.                     fixup_oil(obj, (struct obj *) NULL);
2876.             }
2877.             what = (obj->quan > 1L) ? "Some potions" : "A potion";
2878.         } else {
2879.             obj = mkobj(FOOD_CLASS, FALSE);
2880.             if (obj->otyp == FOOD_RATION && !rn2(7))
2881.                 obj->otyp = LUMP_OF_ROYAL_JELLY;
2882.             what = "Some food";
2883.         }
2884.         ++objcount;
2885.         pline("%s %s out.", what, vtense(what, "spill"));
2886.         obj->blessed = horn->blessed;
2887.         obj->cursed = horn->cursed;
2888.         obj->owt = weight(obj);
2889.         /* using a shop's horn of plenty entails a usage fee and also
2890.            confers ownership of the created item to the shopkeeper */
2891.         if (horn->unpaid)
2892.             addtobill(obj, FALSE, FALSE, tipping);
2893.         /* if it ended up on bill, we don't want "(unpaid, N zorkmids)"
2894.            being included in its formatted name during next message */
2895.         iflags.suppress_price++;
2896.         if (!tipping) {
2897.             obj = hold_another_object(obj,
2898.                                       u.uswallow
2899.                                         ? "Oops!  %s out of your reach!"
2900.                                         : (Is_airlevel(&u.uz)
2901.                                            || Is_waterlevel(&u.uz)
2902.                                            || levl[u.ux][u.uy].typ < IRONBARS
2903.                                            || levl[u.ux][u.uy].typ >= ICE)
2904.                                           ? "Oops!  %s away from you!"
2905.                                           : "Oops!  %s to the floor!",
2906.                                       The(aobjnam(obj, "slip")), (char *) 0);
2907.             nhUse(obj);
2908.         } else if (targetbox) {
2909.             add_to_container(targetbox, obj);
2910.             /* add to container doesn't update the weight */
2911.             targetbox->owt = weight(targetbox);
2912.             /* item still in magic horn was weightless; when it's now in
2913.                a carried container, hero's encumbrance could change */
2914.             if (carried(targetbox)) {
2915.                 encumber_msg();
2916.                 update_inventory(); /* for contents count or wizweight */
2917.             }
2918.         } else {
2919.             /* assumes this is taking place at hero's location */
2920.             if (!can_reach_floor(TRUE)) {
2921.                 hitfloor(obj, TRUE); /* does altar check, message, drop */
2922.             } else {
2923.                 if (IS_ALTAR(levl[u.ux][u.uy].typ))
2924.                     doaltarobj(obj); /* does its own drop message */
2925.                 else
2926.                     pline("%s %s to the %s.", Doname2(obj),
2927.                           otense(obj, "drop"), surface(u.ux, u.uy));
2928.                 dropy(obj);
2929.             }
2930.         }
2931.         iflags.suppress_price--;
2932.         if (horn->dknown)
2933.             makeknown(HORN_OF_PLENTY);
2934.     }
2935.     return objcount;
2936. }
2937. 
2938. /* support for wizard-mode's `sanity_check' option */
2939. 
2940. static const char NEARDATA /* pline formats for insane_object() */
2941.     ofmt0[] = "%s obj %s %s: %s",
2942.     ofmt3[] = "%s [not null] %s %s: %s",
2943.     /* " held by mon %p (%s)" will be appended, filled by M,mon_nam(M) */
2944.     mfmt1[] = "%s obj %s %s (%s)",
2945.     mfmt2[] = "%s obj %s %s (%s) *not*";
2946. 
2947. /* Check all object lists for consistency. */
2948. void
2949. obj_sanity_check(void)
2950. {
2951.     coordxy x, y;
2952.     struct obj *obj, *otop, *prevo;
2953. 
2954.     objlist_sanity(fobj, OBJ_FLOOR, "floor sanity");
2955. 
2956.     /* check that the map's record of floor objects is consistent;
2957.        those objects should have already been sanity checked via
2958.        the floor list so container contents are skipped here */
2959.     for (x = 0; x < COLNO; x++)
2960.         for (y = 0; y < ROWNO; y++) {
2961.             char at_fmt[BUFSZ];
2962. 
2963.             otop = svl.level.objects[x][y];
2964.             prevo = 0;
2965.             for (obj = otop; obj; prevo = obj, obj = prevo->nexthere) {
2966.                 /* <ox,oy> should match <x,y>; <0,*> should always be empty */
2967.                 if (obj->where != OBJ_FLOOR || x == 0
2968.                     || obj->ox != x || obj->oy != y) {
2969.                     Sprintf(at_fmt, "%%s obj@<%d,%d> %%s %%s: %%s@<%d,%d>",
2970.                             x, y, obj->ox, obj->oy);
2971.                     insane_object(obj, at_fmt, "location sanity",
2972.                                   (struct monst *) 0);
2973. 
2974.                 /* when one or more boulders are present, they should always
2975.                    be at the top of their pile; also never in water or lava */
2976.                 } else if (obj->otyp == BOULDER) {
2977.                     if (prevo && prevo->otyp != BOULDER) {
2978.                         Sprintf(at_fmt,
2979.                                 "%%s boulder@<%d,%d> %%s %%s: not on top",
2980.                                 x, y);
2981.                         insane_object(obj, at_fmt, "boulder sanity",
2982.                                       (struct monst *) 0);
2983.                     }
2984.                     if (is_pool_or_lava(x, y)) {
2985.                         Sprintf(at_fmt,
2986.                                 "%%s boulder@<%d,%d> %%s %%s: on/in %s",
2987.                                 x, y, is_pool(x, y) ? "water" : "lava");
2988.                         insane_object(obj, at_fmt, "boulder sanity",
2989.                                       (struct monst *) 0);
2990.                     }
2991.                 }
2992.             }
2993.         }
2994. 
2995.     objlist_sanity(gi.invent, OBJ_INVENT, "invent sanity");
2996.     objlist_sanity(gm.migrating_objs, OBJ_MIGRATING, "migrating sanity");
2997.     objlist_sanity(svl.level.buriedobjlist, OBJ_BURIED, "buried sanity");
2998.     objlist_sanity(gb.billobjs, OBJ_ONBILL, "bill sanity");
2999.     objlist_sanity(go.objs_deleted, OBJ_DELETED, "deleted object sanity");
3000. 
3001.     mon_obj_sanity(fmon, "minvent sanity");
3002.     mon_obj_sanity(gm.migrating_mons, "migrating minvent sanity");
3003.     /* monsters temporarily in transit;
3004.        they should have arrived with hero by the time we get called */
3005.     if (gm.mydogs) {
3006.         impossible("gm.mydogs sanity [not empty]");
3007.         mon_obj_sanity(gm.mydogs, "mydogs minvent sanity");
3008.     }
3009. 
3010.     /* objects temporarily freed from invent/floor lists;
3011.        they should have arrived somewhere by the time we get called */
3012.     if (gt.thrownobj)
3013.         insane_object(gt.thrownobj, ofmt3, "thrownobj sanity",
3014.                       (struct monst *) 0);
3015.     if (gk.kickedobj)
3016.         insane_object(gk.kickedobj, ofmt3, "kickedobj sanity",
3017.                       (struct monst *) 0);
3018.     /* returning_missile temporarily remembers thrownobj and should be
3019.        Null in between moves */
3020.     if (iflags.returning_missile)
3021.         insane_object(gk.kickedobj, ofmt3, "returning_missile sanity",
3022.                       (struct monst *) 0);
3023.     /* gc.current_wand isn't removed from invent while in use, but should
3024.        be Null between moves when we're called */
3025.     if (gc.current_wand)
3026.         insane_object(gc.current_wand, ofmt3, "current_wand sanity",
3027.                       (struct monst *) 0);
3028. }
3029. 
3030. /* sanity check for objects on specified list (fobj, &c) */
3031. staticfn void
3032. objlist_sanity(struct obj *objlist, int wheretype, const char *mesg)
3033. {
3034.     struct obj *obj;
3035. 
3036.     for (obj = objlist; obj; obj = obj->nobj) {
3037.         if (obj->where != wheretype)
3038.             insane_object(obj, ofmt0, mesg, (struct monst *) 0);
3039.         if (obj->where == OBJ_INVENT && obj->how_lost != LOST_NONE) {
3040.             char lostbuf[40];
3041. 
3042.             /* %d: bitfield is unsigned but narrow, so promotes to int */
3043.             Sprintf(lostbuf, "how_lost=%d obj in inventory!", obj->how_lost);
3044.             insane_object(obj, ofmt0, lostbuf, (struct monst *) 0);
3045.         }
3046.         if (Has_contents(obj)) {
3047.             if (wheretype == OBJ_ONBILL)
3048.                 /* containers on shop bill should always be empty */
3049.                 insane_object(obj, "%s obj contains something! %s %s: %s",
3050.                               mesg, (struct monst *) 0);
3051.             check_contained(obj, mesg);
3052.         }
3053.         if (obj->unpaid || obj->no_charge) {
3054.             shop_obj_sanity(obj, mesg);
3055.         }
3056.         if (obj->owornmask) {
3057.             char maskbuf[40];
3058.             boolean bc_ok = FALSE;
3059. 
3060.             switch (obj->where) {
3061.             case OBJ_INVENT:
3062.             case OBJ_MINVENT:
3063.                 sanity_check_worn(obj);
3064.                 break;
3065.             case OBJ_MIGRATING:
3066.                 /* migrating objects overload the owornmask field
3067.                    with a destination code; skip attempt to check it */
3068.                 break;
3069.             case OBJ_FLOOR:
3070.                 /* note: ball and chain can also be OBJ_FREE, but not across
3071.                    turns so this sanity check shouldn't encounter that */
3072.                 bc_ok = TRUE;
3073.             FALLTHROUGH;
3074.             /*FALLTHRU*/
3075.             default:
3076.                 if ((obj != uchain && obj != uball) || !bc_ok) {
3077.                     /* discovered an object not in inventory which
3078.                        erroneously has worn mask set */
3079.                     Sprintf(maskbuf, "worn mask 0x%08lx", obj->owornmask);
3080.                     insane_object(obj, ofmt0, maskbuf, (struct monst *) 0);
3081.                 }
3082.                 break;
3083.             }
3084.         }
3085.         if (obj->otyp == LEASH && obj->leashmon) {
3086.             char buf[BUFSZ];
3087.             struct monst *mtmp = find_mid(obj->leashmon, FM_FMON);
3088. 
3089.             if (obj->where == OBJ_INVENT) {
3090.                 if (!mtmp) { /* found leash with phantom mon */
3091.                     Sprintf(buf, "leashmon=%u no monst,",
3092.                             (unsigned) obj->leashmon);
3093.                     insane_object(obj, ofmt0, buf, (struct monst *) 0);
3094.                 } else if (!mtmp->mleashed) { /* found leashed mon
3095.                                                * not flagged as leashed */
3096.                     Sprintf(buf, "leashmon=%u %s not leashed,",
3097.                             (unsigned) obj->leashmon, mon_pmname(mtmp));
3098.                     insane_object(obj, ofmt0, buf, (struct monst *) 0);
3099.                 }
3100. 
3101.             /* have to explicitly exclude migrating_objs because the
3102.                obj->migr_species field overlays obj->corpsenm just like
3103.                obj->leashmon does, so obj->leashmon and consequently 'mtmp'
3104.                might be inaccurate for any leash found on migrating_objs */
3105.             } else if (obj->where != OBJ_MIGRATING) {
3106.                 struct monst *mtmp2 = (obj->where == OBJ_MINVENT)
3107.                                       ? obj->ocarry : (struct monst *) 0;
3108. 
3109.                 if (mtmp) { /* found monst leashed by non-invent leash */
3110.                     Sprintf(buf, "leashmon:%u %s leashed by %s leash,",
3111.                             (unsigned) obj->leashmon,
3112.                             mon_pmname(mtmp), where_name(obj));
3113.                     insane_object(obj, ofmt0, buf, mtmp2);
3114.                 } else { /* found non-invent leash with m_id of phantom mon */
3115.                     Sprintf(buf, "leashmon:%u no monst for %s leash,",
3116.                             (unsigned) obj->leashmon, where_name(obj));
3117.                     insane_object(obj, ofmt0, buf, mtmp2);
3118.                 }
3119.             }
3120.         }
3121.         if (obj->globby)
3122.             check_glob(obj, mesg);
3123.         /* temporary flags that might have been set but which should
3124.            be clear by the time this sanity check is taking place */
3125.         if (obj->in_use || obj->bypass || obj->nomerge
3126.             || (obj->otyp == BOULDER && obj->next_boulder))
3127.             insane_obj_bits(obj, (struct monst *) 0);
3128.     }
3129. }
3130. 
3131. /* check obj->unpaid and obj->no_charge for shop sanity; caller has
3132.    verified that at least one of them is set */
3133. staticfn void
3134. shop_obj_sanity(struct obj *obj, const char *mesg)
3135. {
3136.     struct obj *otop;
3137.     struct monst *shkp;
3138.     const char *why;
3139.     boolean costly, costlytoo;
3140.     coordxy x = 0, y = 0;
3141. 
3142.     /* if contained, get top-most container; we needs its location */
3143.     otop = obj;
3144.     while (otop->where == OBJ_CONTAINED)
3145.         otop = otop->ocontainer;
3146.     /* get obj's or its container's location; do not update obj->ox,oy
3147.        or otop->ox,oy because that would cause sanity checking to
3148.        produce side-effects that won't occur when not sanity checking;
3149.        no need for CONTAINED_TOO because we have a top level container */
3150.     (void) get_obj_location(otop, &x, &y, BURIED_TOO);
3151. 
3152.     /* these will always be needed for the normal case, so don't bother
3153.        waiting until we find an insanity to fetch them */
3154.     shkp = find_objowner(obj, x, y);
3155.     if (shkp && obj->where == OBJ_ONBILL)
3156.         x = shkp->mx, y = shkp->my;
3157.     costly = costly_spot(x, y);
3158.     costlytoo = costly_adjacent(shkp, x, y);
3159. 
3160.     why = (const char *) 0;
3161.     if (obj->no_charge && obj->unpaid) {
3162.         why = "%s obj both unpaid and no_charge! %s %s: %s";
3163.     } else if (obj->unpaid) {
3164.         /* unpaid is only applicable for directly carried objects, for
3165.            objects inside carried containers, for used up items on the
3166.            billobjs list, and for floor items outside the shop proper
3167.            but within the shop boundary (walls, door, "free spot") and
3168.            for objects moved from such spots into the shop proper by
3169.            repair of shop walls or items buried while on boundary */
3170.         if (otop->where != OBJ_INVENT
3171.             && obj->where != OBJ_ONBILL /* when on bill, obj==otop */
3172.             && ((otop->where != OBJ_FLOOR && obj->where != OBJ_BURIED)
3173.                 || !(costly || costlytoo)))
3174.             why = "%s unpaid obj not carried! %s %s: %s";
3175.         else if (!costly && !costlytoo)
3176.             why = "%s unpaid obj not inside tended shop! %s %s: %s";
3177.         else if (!shkp)
3178.             why = "%s unpaid obj inside untended shop! %s %s: %s";
3179.         else if (!onshopbill(obj, shkp, TRUE))
3180.             why = "%s unpaid obj not on shop bill! %s %s: %s";
3181.     } else if (obj->no_charge) {
3182.         /* no_charge is only applicable for floor objects in shops, for
3183.            objects inside floor containers in shops, and for objects buried
3184.            beneath the shop floor or carried by a monster (usually pet) */
3185.         if (otop->where != OBJ_FLOOR
3186.             && otop->where != OBJ_BURIED
3187.             && otop->where != OBJ_MINVENT)
3188.             why = "%s no_charge obj not on floor! %s %s: %s";
3189.         else if (!costly && !costlytoo)
3190.             why = "%s no_charge obj not inside tended shop! %s %s: %s";
3191.         else if (!shkp)
3192.             why = "%s no_charge obj inside untended shop! %s %s: %s";
3193.         else if (onshopbill(obj, shkp, TRUE))
3194.             why = "%s no_charge obj on shop bill! %s %s: %s";
3195.     }
3196.     if (why)
3197.         insane_object(obj, why, mesg,
3198.                       mcarried(otop) ? otop->ocarry : (struct monst *) 0);
3199.     return;
3200. }
3201. 
3202. /* sanity check for objects carried by all monsters in specified list */
3203. staticfn void
3204. mon_obj_sanity(struct monst *monlist, const char *mesg)
3205. {
3206.     struct monst *mon;
3207.     struct obj *obj, *mwep;
3208. 
3209.     for (mon = monlist; mon; mon = mon->nmon) {
3210.         if (DEADMONSTER(mon))
3211.             continue;
3212.         mwep = MON_WEP(mon); /* mon->mw */
3213.         if (mwep) {
3214.             if (!mcarried(mwep))
3215.                 insane_object(mwep, mfmt1, mesg, mon);
3216.             if (mwep->ocarry != mon)
3217.                 insane_object(mwep, mfmt2, mesg, mon);
3218.         }
3219.         for (obj = mon->minvent; obj; obj = obj->nobj) {
3220.             if (obj->where != OBJ_MINVENT)
3221.                 insane_object(obj, mfmt1, mesg, mon);
3222.             if (obj->ocarry != mon)
3223.                 insane_object(obj, mfmt2, mesg, mon);
3224.             if (obj->globby)
3225.                 check_glob(obj, mesg);
3226.             check_contained(obj, mesg);
3227.             if (obj->unpaid || obj->no_charge)
3228.                 shop_obj_sanity(obj, mesg);
3229.             if (obj->in_use || obj->bypass || obj->nomerge
3230.                 || (obj->otyp == BOULDER && obj->next_boulder))
3231.                 insane_obj_bits(obj, mon);
3232.             if (obj == mwep)
3233.                 mwep = (struct obj *) 0;
3234.         }
3235.         if (mwep) {
3236.             /* this is a monster check rather than an object check, but doing
3237.                it here avoids making an extra pass through mon's minvent;
3238.                if the full pass through that list hasn't reset mwep to Null,
3239.                then mwep isn't in that list where it should be */
3240.             impossible("monst (%s: %u) wielding %s (%u) not in %s inventory",
3241.                        pmname(mon->data, Mgender(mon)), mon->m_id,
3242.                        safe_typename(mwep->otyp), mwep->o_id, mhis(mon));
3243. 
3244.         }
3245.     }
3246. }
3247. 
3248. staticfn void
3249. insane_obj_bits(struct obj *obj, struct monst *mon)
3250. {
3251.     unsigned o_in_use, o_bypass, o_nomerge, o_boulder;
3252. 
3253.     if (obj->where == OBJ_DELETED)
3254.         return; /* skip bit checking for deleted objects */
3255. 
3256.     o_in_use = obj->in_use;
3257.     o_bypass = obj->bypass;
3258.     /* having obj->nomerge be set might be intentional */
3259.     o_nomerge = (obj->nomerge && !nomerge_exception(obj));
3260.     /* next_boulder is only for object name formatting when pushing
3261.        boulders and should be reset by time of next sanity check */
3262.     o_boulder = (obj->otyp == BOULDER && obj->next_boulder);
3263. 
3264.     if (o_in_use || o_bypass || o_nomerge || o_boulder) {
3265.         char infobuf[QBUFSZ];
3266. 
3267.         Sprintf(infobuf, "flagged%s%s%s%s",
3268.                 o_in_use ? " in_use" : "",
3269.                 o_bypass ? " bypass" : "",
3270.                 o_nomerge ? " nomerge" : "",
3271.                 o_boulder ? " nxtbldr" : "");
3272.         insane_object(obj, ofmt0, infobuf, mon);
3273.     }
3274. }
3275. 
3276. /* does 'obj' use the 'nomerge' flag persistently? */
3277. staticfn boolean
3278. nomerge_exception(struct obj *obj)
3279. {
3280.     /* special prize objects for achievement tracking are set 'nomerge'
3281.        until they get picked up by the hero */
3282.     if (is_mines_prize(obj) || is_soko_prize(obj))
3283.         return TRUE;
3284. 
3285.     return FALSE;
3286. }
3287. 
3288. /* This must stay consistent with the defines in obj.h. */
3289. static const char *const obj_state_names[NOBJ_STATES] = {
3290.     "free", "floor", "contained", "invent",
3291.     "minvent", "migrating", "buried", "onbill",
3292.     "luafree", "deleted",
3293. };
3294. 
3295. staticfn const char *
3296. where_name(struct obj *obj)
3297. {
3298.     static char unknown[32]; /* big enough to handle rogue 64-bit int */
3299.     int where;
3300. 
3301.     if (!obj)
3302.         return "nowhere";
3303.     where = obj->where;
3304.     if (where < 0 || where >= NOBJ_STATES || !obj_state_names[where]) {
3305.         Sprintf(unknown, "unknown[%d]", where);
3306.         return unknown;
3307.     }
3308.     return obj_state_names[where];
3309. }
3310. 
3311. DISABLE_WARNING_FORMAT_NONLITERAL
3312. 
3313. staticfn void
3314. insane_object(
3315.     struct obj *obj,
3316.     const char *fmt,
3317.     const char *mesg,
3318.     struct monst *mon)
3319. {
3320.     const char *objnm, *monnm;
3321.     char altfmt[BUFSZ];
3322. 
3323.     objnm = monnm = "null!";
3324.     if (obj) {
3325.         iflags.override_ID++;
3326.         objnm = doname(obj);
3327.         iflags.override_ID--;
3328.     }
3329.     if (mon || (strstri(mesg, "minvent") && !strstri(mesg, "contained"))) {
3330.         Strcat(strcpy(altfmt, fmt), " held by mon %s (%s)");
3331.         if (mon)
3332.             monnm = x_monnam(mon, ARTICLE_A, (char *) 0, EXACT_NAME, TRUE);
3333.         impossible(altfmt, mesg, fmt_ptr((genericptr_t) obj), where_name(obj),
3334.                    objnm, fmt_ptr((genericptr_t) mon), monnm);
3335.     } else {
3336.         impossible(fmt, mesg, fmt_ptr((genericptr_t) obj), where_name(obj),
3337.                    objnm);
3338.     }
3339. }
3340. 
3341. RESTORE_WARNING_FORMAT_NONLITERAL
3342. 
3343. /* initialize a dummy obj with just enough info to allow some of the tests in
3344.    obj.h that take an obj pointer to work; used when applying a stethoscope
3345.    toward a mimic mimicking an object */
3346. struct obj *
3347. init_dummyobj(struct obj *obj, short otyp, long oquan)
3348. {
3349.      if (obj) {
3350.          *obj = cg.zeroobj;
3351.          obj->otyp = otyp;
3352.          obj->oclass = objects[otyp].oc_class;
3353.          /* obj->dknown = 0; */
3354.          /* suppress known except for amulets (needed for fakes & real AoY) */
3355.          obj->known = (obj->oclass == AMULET_CLASS)
3356.                          ? obj->known
3357.                          /* default is "on" for types which don't use it */
3358.                          : !objects[otyp].oc_uses_known;
3359.          obj->quan = oquan ? oquan : 1L;
3360.          obj->corpsenm = NON_PM; /* suppress statue and figurine details */
3361.          if (obj->otyp == LEASH)
3362.              obj->leashmon = 0; /* overloads corpsenm, avoid NON_PM */
3363.          if (obj->otyp == BOULDER)
3364.              obj->next_boulder = 0; /* overloads corpsenm, avoid NON_PM */
3365.          /* but suppressing fruit details leads to "bad fruit #0" */
3366.          if (obj->otyp == SLIME_MOLD)
3367.              obj->spe = svc.context.current_fruit;
3368.      }
3369.      return obj;
3370. }
3371. 
3372. /* obj sanity check: check objects inside container */
3373. staticfn void
3374. check_contained(struct obj *container, const char *mesg)
3375. {
3376.     struct obj *obj;
3377.     /* big enough to work with, not too big to blow out stack in recursion */
3378.     char mesgbuf[40], nestedmesg[120];
3379. 
3380.     if (!Has_contents(container))
3381.         return;
3382.     /* change "invent sanity" to "contained invent sanity"
3383.        but leave "nested contained invent sanity" as is */
3384.     if (!strstri(mesg, "contained"))
3385.         mesg = strcat(strcpy(mesgbuf, "contained "), mesg);
3386. 
3387.     for (obj = container->cobj; obj; obj = obj->nobj) {
3388.         /* catch direct cycle to avoid unbounded recursion */
3389.         if (obj == container)
3390.             panic("failed sanity check: container holds itself");
3391.         if (obj->where != OBJ_CONTAINED)
3392.             insane_object(obj, "%s obj %s %s: %s", mesg, (struct monst *) 0);
3393.         else if (obj->ocontainer != container)
3394.             impossible("%s obj %s in container %s, not %s", mesg,
3395.                   fmt_ptr((genericptr_t) obj),
3396.                   fmt_ptr((genericptr_t) obj->ocontainer),
3397.                   fmt_ptr((genericptr_t) container));
3398.         if (obj->globby)
3399.             check_glob(obj, mesg);
3400. 
3401.         if (Has_contents(obj)) {
3402.             /* catch most likely indirect cycle; we won't notice if
3403.                parent is present when something comes before it, or
3404.                notice more deeply embedded cycles (grandparent, &c) */
3405.             if (obj->cobj == container)
3406.                 panic("failed sanity check: container holds its parent");
3407.             /* change "contained... sanity" to "nested contained... sanity"
3408.                and "nested contained..." to "nested nested contained..." */
3409.             Strcpy(nestedmesg, "nested ");
3410.             copynchars(eos(nestedmesg), mesg, (int) sizeof nestedmesg
3411.                                               - (int) strlen(nestedmesg) - 1);
3412.             /* recursively check contents */
3413.             check_contained(obj, nestedmesg);
3414.         }
3415.     }
3416. }
3417. 
3418. /* called when 'obj->globby' is set so we don't recheck it here */
3419. staticfn void
3420. check_glob(struct obj *obj, const char *mesg)
3421. {
3422. #define LOWEST_GLOB GLOB_OF_GRAY_OOZE
3423. #define HIGHEST_GLOB GLOB_OF_BLACK_PUDDING
3424.     if (obj->quan != 1L || obj->owt == 0
3425.         || obj->otyp < LOWEST_GLOB || obj->otyp > HIGHEST_GLOB
3426. #if 0   /*
3427.          * This was relevant before the shrink_glob timer was adopted but
3428.          * now any glob could have a weight that isn't a multiple of 20.
3429.          */
3430.         /* a partially eaten glob could have any non-zero weight but an
3431.            intact one should weigh an exact multiple of base weight (20) */
3432.         || ((obj->owt % objects[obj->otyp].oc_weight) != 0 && !obj->oeaten)
3433. #endif
3434.         ) {
3435.         char mesgbuf[BUFSZ], globbuf[QBUFSZ];
3436. 
3437.         Sprintf(globbuf, " glob %d,quan=%ld,owt=%u ",
3438.                 obj->otyp, obj->quan, obj->owt);
3439.         mesg = strsubst(strcpy(mesgbuf, mesg), " obj ", globbuf);
3440.         insane_object(obj, ofmt0, mesg,
3441.                       (obj->where == OBJ_MINVENT) ? obj->ocarry : 0);
3442.     }
3443. }
3444. 
3445. /* check an object in hero's or monster's inventory which has worn mask set */
3446. staticfn void
3447. sanity_check_worn(struct obj *obj)
3448. {
3449. #if (NH_DEVEL_STATUS != NH_STATUS_RELEASED) || defined(DEBUG)
3450.     static unsigned long wearbits[] = {
3451.         W_ARM,    W_ARMC,   W_ARMH,    W_ARMS, W_ARMG,  W_ARMF,  W_ARMU,
3452.         W_WEP,    W_QUIVER, W_SWAPWEP, W_AMUL, W_RINGL, W_RINGR, W_TOOL,
3453.         W_SADDLE, W_BALL,   W_CHAIN,   0
3454.         /* [W_ART,W_ARTI are property bits for items which aren't worn] */
3455.     };
3456.     char maskbuf[60];
3457.     const char *what;
3458.     unsigned long owornmask, allmask = 0L;
3459.     boolean embedded = FALSE;
3460.     int i, n = 0;
3461. 
3462.     /* use owornmask for testing and bit twiddling, but use original
3463.        obj->owornmask for printing */
3464.     owornmask = obj->owornmask;
3465.     /* figure out how many bits are set, and also which are viable */
3466.     for (i = 0; wearbits[i]; ++i) {
3467.         if ((owornmask & wearbits[i]) != 0L)
3468.             ++n;
3469.         allmask |= wearbits[i];
3470.     }
3471.     if (obj == uskin) {
3472.         /* embedded dragon scales have an extra bit set;
3473.            make sure it's set, then suppress it */
3474.         embedded = TRUE;
3475.         if ((owornmask & (W_ARM | I_SPECIAL)) == (W_ARM | I_SPECIAL))
3476.             owornmask &= ~I_SPECIAL;
3477.         else
3478.             n = 0,  owornmask = ~0; /* force insane_object("bogus") below */
3479.     }
3480.     if (n == 2 && carried(obj)
3481.         && obj == uball && (owornmask & W_BALL) != 0L
3482.         && (owornmask & W_WEAPONS) != 0L) {
3483.         /* chained ball can be wielded/alt-wielded/quivered; if so,
3484.           pretend it's not chained in order to check the weapon pointer
3485.           (we've already verified the ball pointer by successfully passing
3486.           the if-condition to get here...) */
3487.         owornmask &= ~W_BALL;
3488.         n = 1;
3489.     }
3490.     if (n > 1) {
3491.         /* multiple bits set */
3492.         Sprintf(maskbuf, "worn mask (multiple) 0x%08lx", obj->owornmask);
3493.         insane_object(obj, ofmt0, maskbuf, (struct monst *) 0);
3494.     }
3495.     if ((owornmask & ~allmask) != 0L
3496.         || (carried(obj) && (owornmask & W_SADDLE) != 0L)) {
3497.         /* non-wearable bit(s) set */
3498.         Sprintf(maskbuf, "worn mask (bogus)) 0x%08lx", obj->owornmask);
3499.         insane_object(obj, ofmt0, maskbuf, (struct monst *) 0);
3500.     }
3501.     if (n == 1 && (carried(obj) || (owornmask & (W_BALL | W_CHAIN)) != 0L)) {
3502.         what = 0;
3503.         /* verify that obj in hero's invent (or ball/chain elsewhere)
3504.            with owornmask of W_foo is the object pointed to by ufoo */
3505.         switch (owornmask) {
3506.         case W_ARM:
3507.             if (obj != (embedded ? uskin : uarm))
3508.                 what = embedded ? "skin" : "suit";
3509.             break;
3510.         case W_ARMC:
3511.             if (obj != uarmc)
3512.                 what = "cloak";
3513.             break;
3514.         case W_ARMH:
3515.             if (obj != uarmh)
3516.                 what = "helm";
3517.             break;
3518.         case W_ARMS:
3519.             if (obj != uarms)
3520.                 what = "shield";
3521.             break;
3522.         case W_ARMG:
3523.             if (obj != uarmg)
3524.                 what = "gloves";
3525.             break;
3526.         case W_ARMF:
3527.             if (obj != uarmf)
3528.                 what = "boots";
3529.             break;
3530.         case W_ARMU:
3531.             if (obj != uarmu)
3532.                 what = "shirt";
3533.             break;
3534.         case W_WEP:
3535.             if (obj != uwep)
3536.                 what = "primary weapon";
3537.             break;
3538.         case W_QUIVER:
3539.             if (obj != uquiver)
3540.                 what = "quiver";
3541.             break;
3542.         case W_SWAPWEP:
3543.             if (obj != uswapwep)
3544.                 what = u.twoweap ? "secondary weapon" : "alternate weapon";
3545.             break;
3546.         case W_AMUL:
3547.             if (obj != uamul)
3548.                 what = "amulet";
3549.             break;
3550.         case W_RINGL:
3551.             if (obj != uleft)
3552.                 what = "left ring";
3553.             break;
3554.         case W_RINGR:
3555.             if (obj != uright)
3556.                 what = "right ring";
3557.             break;
3558.         case W_TOOL:
3559.             if (obj != ublindf)
3560.                 what = "blindfold";
3561.             break;
3562.         /* case W_SADDLE: */
3563.         case W_BALL:
3564.             if (obj != uball)
3565.                 what = "ball";
3566.             break;
3567.         case W_CHAIN:
3568.             if (obj != uchain)
3569.                 what = "chain";
3570.             break;
3571.         default:
3572.             break;
3573.         }
3574.         if (what) {
3575.             Sprintf(maskbuf, "worn mask 0x%08lx != %s", obj->owornmask, what);
3576.             insane_object(obj, ofmt0, maskbuf, (struct monst *) 0);
3577.         }
3578.     }
3579.     if (n == 1 && (carried(obj) || (owornmask & (W_BALL | W_CHAIN)) != 0L
3580.                    || mcarried(obj))) {
3581.         /* check for items worn in invalid slots; practically anything can
3582.            be wielded/alt-wielded/quivered, so tests on those are limited */
3583.         what = 0;
3584.         if (owornmask & W_ARMOR) {
3585.             if (obj->oclass != ARMOR_CLASS)
3586.                 what = "armor";
3587.             /* 3.6: dragon scale mail reverts to dragon scales when
3588.                becoming embedded in poly'd hero's skin */
3589.             if (embedded && !Is_dragon_scales(obj))
3590.                 what = "skin";
3591.         } else if (owornmask & W_WEAPONS) {
3592.             /* monsters don't maintain alternate weapon or quiver */
3593.             if (mcarried(obj) && (owornmask & (W_SWAPWEP | W_QUIVER)) != 0L)
3594.                 what = (owornmask & W_SWAPWEP) != 0L ? "monst alt weapon?"
3595.                                                      : "monst quiver?";
3596.             /* hero can quiver gold but not wield it (hence not alt-wield
3597.                it either); also catches monster wielding gold */
3598.             else if (obj->oclass == COIN_CLASS
3599.                      && (owornmask & (W_WEP | W_SWAPWEP)) != 0L)
3600.                 what = (owornmask & W_WEP) != 0L ? "weapon" : "alt weapon";
3601.         } else if (owornmask & W_AMUL) {
3602.             if (obj->oclass != AMULET_CLASS)
3603.                 what = "amulet";
3604.         } else if (owornmask & W_RING) {
3605.             if (obj->oclass != RING_CLASS && obj->otyp != MEAT_RING)
3606.                 what = "ring";
3607.         } else if (owornmask & W_TOOL) {
3608.             if (obj->otyp != BLINDFOLD && obj->otyp != TOWEL
3609.                 && obj->otyp != LENSES)
3610.                 what = "blindfold";
3611.         } else if (owornmask & W_BALL) {
3612.             if (obj->oclass != BALL_CLASS)
3613.                 what = "chained ball";
3614.         } else if (owornmask & W_CHAIN) {
3615.             if (obj->oclass != CHAIN_CLASS)
3616.                 what = "chain";
3617.         } else if (owornmask & W_SADDLE) {
3618.             if (obj->otyp != SADDLE)
3619.                 what = "saddle";
3620.         }
3621.         if (what) {
3622.             char oclassname[30];
3623.             struct monst *mon = mcarried(obj) ? obj->ocarry : 0;
3624. 
3625.             /* if we've found a potion worn in the amulet slot,
3626.                this yields "worn (potion amulet)" */
3627.             Strcpy(oclassname, def_oc_syms[(uchar) obj->oclass].name);
3628.             Sprintf(maskbuf, "worn (%s %s)", makesingular(oclassname), what);
3629.             insane_object(obj, ofmt0, maskbuf, mon);
3630.         }
3631.     }
3632. #else /* not (NH_DEVEL_STATUS != NH_STATUS_RELEASED) || DEBUG) */
3633.     /* dummy use of obj to avoid "arg not used" complaint */
3634.     if (!obj)
3635.         insane_object(obj, ofmt0, "<null>", (struct monst *) 0);
3636. #endif
3637. }
3638. 
3639. /*
3640.  * wrapper to make "near this object" convenient
3641.  */
3642. struct obj *
3643. obj_nexto(struct obj *otmp)
3644. {
3645.     if (!otmp) {
3646.         impossible("obj_nexto: wasn't given an object to check");
3647.         return (struct obj *) 0;
3648.     }
3649.     return obj_nexto_xy(otmp, otmp->ox, otmp->oy, TRUE);
3650. }
3651. 
3652. /*
3653.  * looks for objects of a particular type next to x, y
3654.  * skips over oid if found (lets us avoid ourselves if
3655.  * we're looking for a second type of an existing object)
3656.  *
3657.  * TODO: return a list of all objects near us so we can more
3658.  * reliably predict which one we want to 'find' first
3659.  */
3660. struct obj *
3661. obj_nexto_xy(struct obj *obj, coordxy x, coordxy y, boolean recurs)
3662. {
3663.     struct obj *otmp;
3664.     int fx, fy, ex, ey, otyp = obj->otyp;
3665.     short dx, dy;
3666. 
3667.     /* check under our "feet" first */
3668.     otmp = sobj_at(otyp, x, y);
3669.     while (otmp) {
3670.         /* don't be clever and find ourselves */
3671.         if (otmp != obj && mergable(otmp, obj))
3672.             return otmp;
3673.         otmp = nxtobj(otmp, otyp, TRUE);
3674.     }
3675. 
3676.     if (!recurs)
3677.         return (struct obj *) 0;
3678. 
3679.     /* search in a random order */
3680.     dx = (rn2(2) ? -1 : 1);
3681.     dy = (rn2(2) ? -1 : 1);
3682.     ex = x - dx;
3683.     ey = y - dy;
3684. 
3685.     for (fx = ex; abs(fx - ex) < 3; fx += dx) {
3686.         for (fy = ey; abs(fy - ey) < 3; fy += dy) {
3687.             /* 0, 0 was checked above */
3688.             if (isok(fx, fy) && (fx != x || fy != y)) {
3689.                 if ((otmp = obj_nexto_xy(obj, fx, fy, FALSE)) != 0)
3690.                     return otmp;
3691.             }
3692.         }
3693.     }
3694.     return (struct obj *) 0;
3695. }
3696. 
3697. /*
3698.  * Causes one object to absorb another, increasing weight
3699.  * accordingly.  Frees obj2; obj1 remains and is returned.
3700.  */
3701. struct obj *
3702. obj_absorb(struct obj **obj1, struct obj **obj2)
3703. {
3704.     struct obj *otmp1, *otmp2;
3705.     int o1wt, o2wt;
3706.     long agetmp;
3707. 
3708.     /* don't let people dumb it up */
3709.     if (obj1 && obj2) {
3710.         otmp1 = *obj1;
3711.         otmp2 = *obj2;
3712.         if (otmp1 && otmp2 && otmp1 != otmp2) {
3713.             globby_bill_fixup(otmp1, otmp2);
3714.             if (otmp1->bknown != otmp2->bknown)
3715.                 otmp1->bknown = otmp2->bknown = 0;
3716.             if (otmp1->rknown != otmp2->rknown)
3717.                 otmp1->rknown = otmp2->rknown = 0;
3718.             if (otmp1->greased != otmp2->greased)
3719.                 otmp1->greased = otmp2->greased = 0;
3720.             if (otmp1->orotten || otmp2->orotten)
3721.                 otmp1->orotten = otmp2->orotten = 1;
3722.             o1wt = otmp1->oeaten ? otmp1->oeaten : otmp1->owt;
3723.             o2wt = otmp2->oeaten ? otmp2->oeaten : otmp2->owt;
3724.             /* averaging the relative ages is less likely to overflow
3725.                than averaging the absolute ages directly */
3726.             agetmp = (((svm.moves - otmp1->age) * o1wt
3727.                        + (svm.moves - otmp2->age) * o2wt)
3728.                       / (o1wt + o2wt));
3729.             /* convert relative age back to absolute age */
3730.             otmp1->age = svm.moves - agetmp;
3731.             otmp1->owt += o2wt;
3732.             if (otmp1->oeaten || otmp2->oeaten)
3733.                 otmp1->oeaten = o1wt + o2wt;
3734.             otmp1->quan = 1L;
3735.             if (otmp1->globby && otmp2->globby) {
3736.                 /* average (not weighted, no pun intended) the two globs'
3737.                    shrink timers and use that to give otmp1 a new timer */
3738.                 long tm1 = stop_timer(SHRINK_GLOB, obj_to_any(otmp1)),
3739.                      tm2 = stop_timer(SHRINK_GLOB, obj_to_any(otmp2));
3740. 
3741.                 tm1 = ((tm1 ? tm1 : 25L) + (tm2 ? tm2 : 25L) + 1L) / 2L;
3742.                 start_glob_timeout(otmp1, tm1);
3743.             }
3744.             /* get rid of second glob, return augmented first one */
3745.             obj_extract_self(otmp2);
3746.             dealloc_obj(otmp2);
3747.             *obj2 = (struct obj *) 0;
3748.             return otmp1;
3749.         }
3750.     }
3751. 
3752.     impossible("obj_absorb: not called with two actual objects");
3753.     return (struct obj *) 0;
3754. }
3755. 
3756. /*
3757.  * Causes the heavier object to absorb the lighter object in
3758.  * most cases, but if one object is OBJ_FREE and the other is
3759.  * on the floor, the floor object goes first.  Note that when
3760.  * a globby monster dies, its corpse (new glob) will be created
3761.  * on the floor; when a glob is dropped, thrown, or kicked it
3762.  * will be free at the time obj_meld() gets called.
3763.  *
3764.  * Wrapper for obj_absorb() so that floor_effects works more
3765.  * cleanly (since we don't know which we want to stay around).
3766.  */
3767. struct obj *
3768. obj_meld(struct obj **obj1, struct obj **obj2)
3769. {
3770.     struct obj *otmp1, *otmp2, *result = 0;
3771.     int ox, oy; /* coordinates for the glob that goes away */
3772. 
3773.     if (obj1 && obj2) {
3774.         otmp1 = *obj1;
3775.         otmp2 = *obj2;
3776.         if (otmp1 && otmp2 && otmp1 != otmp2) {
3777.             ox = oy = 0;
3778.             /*
3779.              * FIXME?
3780.              *  If one of the objects is free because it's being dropped,
3781.              *  we should really finish a full drop and then absorb/meld
3782.              *  if it survives the flooreffects().  Then lighter-melds-into-
3783.              *  heavier will be true even when heavier is the one dropped.
3784.              *
3785.              *  [Also, what about when one of the globs is on the shore
3786.              *  and we drop the other into adjacent pool or vice versa?]
3787.              */
3788.             if (!(otmp2->where == OBJ_FLOOR && otmp1->where == OBJ_FREE)
3789.                 && (otmp1->owt > otmp2->owt
3790.                     || (otmp1->owt == otmp2->owt && rn2(2)))) {
3791.                 if (otmp2->where == OBJ_FLOOR)
3792.                     ox = otmp2->ox, oy = otmp2->oy;
3793.                 result = obj_absorb(obj1, obj2);
3794.             } else {
3795.                 if (otmp1->where == OBJ_FLOOR)
3796.                     ox = otmp1->ox, oy = otmp1->oy;
3797.                 result = obj_absorb(obj2, obj1);
3798.             }
3799.             /* callers really ought to take care of this; glob melding is
3800.                a bookkeeping issue rather than a display one */
3801.             if (ox) {
3802.                 if (cansee(ox, oy))
3803.                     newsym(ox, oy);
3804.                 /* and this; a hides-under monster might be hiding under
3805.                    the glob that went away; if there's nothing else there
3806.                    to hide under, force it out of hiding */
3807.                 maybe_unhide_at(ox, oy);
3808.             }
3809.         }
3810.     } else {
3811.         impossible("obj_meld: not called with two actual objects");
3812.     }
3813.     return result;
3814. }
3815. 
3816. /* give a message if hero notices two globs merging [used to be in pline.c] */
3817. void
3818. pudding_merge_message(struct obj *otmp, struct obj *otmp2)
3819. {
3820.     boolean visible = (cansee(otmp->ox, otmp->oy)
3821.                        || cansee(otmp2->ox, otmp2->oy)),
3822.             onfloor = (otmp->where == OBJ_FLOOR || otmp2->where == OBJ_FLOOR),
3823.             inpack = (carried(otmp) || carried(otmp2));
3824. 
3825.     /* the player will know something happened inside his own inventory */
3826.     if ((!Blind && visible) || inpack) {
3827.         if (Hallucination) {
3828.             if (onfloor) {
3829.                 You_see("parts of the floor melting!");
3830.             } else if (inpack) {
3831.                 Your("pack reaches out and grabs something!");
3832.             }
3833.             /* even though we can see where they should be,
3834.              * they'll be out of our view (minvent or container)
3835.              * so don't actually show anything */
3836.         } else if (onfloor || inpack) {
3837.             boolean adj = ((otmp->ox != u.ux || otmp->oy != u.uy)
3838.                            && (otmp2->ox != u.ux || otmp2->oy != u.uy));
3839. 
3840.             pline("The %s%s coalesce%s.",
3841.                   (onfloor && adj) ? "adjacent " : "",
3842.                   makeplural(obj_typename(otmp->otyp)),
3843.                   inpack ? " inside your pack" : "");
3844.         }
3845.     } else {
3846.         Soundeffect(se_faint_sloshing, 25);
3847.         You_hear("a faint sloshing sound.");
3848.     }
3849. }
3850. 
3851. /*mkobj.c*/