Source:NetHack 5.0.0/src/artifact.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to artifact.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/artifact.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	artifact.c	$NHDT-Date: 1715889721 2024/05/16 20:02:01 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.236 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Robert Patrick Rankin, 2013. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. #include "artifact.h"
8. #include "artilist.h"
9. 
10. #ifndef SFCTOOL
11. 
12. /*
13.  * Note:  both artilist[] and artiexist[] have a dummy element #0,
14.  *        so loops over them should normally start at #1.  The primary
15.  *        exception is the save & restore code, which doesn't care about
16.  *        the contents, just the total size.
17.  */
18. 
19. staticfn struct artifact *get_artifact(struct obj *) NONNULL;
20. 
21. /* #define get_artifact(o) \
22.     (((o) && ((o)->artifact > 0 && (o)->artifact < AFTER_LAST_ARTIFACT)) \
23.                              ? &artilist[(int) (o)->oartifact] \
24.                              : &artilist[ART_NONARTIFACT]) */
25. 
26. staticfn boolean bane_applies(const struct artifact *, struct monst *)
27.                                                                  NONNULLARG12;
28. staticfn int spec_applies(const struct artifact *, struct monst *)
29.                                                                  NONNULLARG12;
30. staticfn int invoke_ok(struct obj *);
31. staticfn void nothing_special(struct obj *) NONNULLARG1;
32. staticfn int invoke_taming(struct obj *) NONNULLARG1;
33. staticfn int invoke_healing(struct obj *) NONNULLARG1;
34. staticfn int invoke_energy_boost(struct obj *) NONNULLARG1;
35. staticfn int invoke_untrap(struct obj *) NONNULLARG1;
36. staticfn int invoke_charge_obj(struct obj *) NONNULLARG1;
37. staticfn int invoke_create_portal(struct obj *) NONNULLARG1;
38. staticfn int invoke_create_ammo(struct obj *) NONNULLARG1;
39. staticfn int invoke_banish(struct obj *) NONNULLARG1;
40. staticfn int invoke_fling_poison(struct obj *) NONNULLARG1;
41. staticfn int invoke_storm_spell(struct obj *) NONNULLARG1;
42. staticfn int invoke_blinding_ray(struct obj *) NONNULLARG1;
43. staticfn int arti_invoke_cost_pw(struct obj *) NONNULLARG1;
44. staticfn boolean arti_invoke_cost(struct obj *) NONNULLARG1;
45. staticfn int arti_invoke(struct obj *);
46. staticfn boolean Mb_hit(struct monst * magr, struct monst *mdef,
47.                       struct obj *, int *, int, boolean, char *);
48. staticfn unsigned long abil_to_spfx(long *) NONNULLARG1;
49. staticfn uchar abil_to_adtyp(long *) NONNULLARG1;
50. staticfn int glow_strength(int);
51. staticfn boolean untouchable(struct obj *, boolean);
52. staticfn int count_surround_traps(coordxy, coordxy);
53. staticfn void dispose_of_orig_obj(struct obj *);
54. 
55. /* The amount added to the victim's total hit points to insure that the
56.    victim will be killed even after damage bonus/penalty adjustments.
57.    Most such penalties are small, and 200 is plenty; the exception is
58.    half physical damage.  3.3.1 and previous versions tried to use a very
59.    large number to account for this case; now, we just compute the fatal
60.    damage by adding it to 2 times the total hit points instead of 1 time.
61.    Note: this will still break if they have more than about half the number
62.    of hit points that will fit in a 15 bit integer. */
63. #define FATAL_DAMAGE_MODIFIER 200
64. #endif /* SFCTOOL */
65. 
66. /* arti_info struct definition moved to artifact.h */
67. 
68. /* array of flags tracking which artifacts exist, indexed by ART_xx;
69.    ART_xx values are 1..N, element [0] isn't used; no terminator needed */
70. static struct arti_info artiexist[1 + NROFARTIFACTS];
71. /* discovery list; for N discovered artifacts, the first N entries are ART_xx
72.    values in discovery order, the remaining (NROFARTIFACTS-N) slots are 0 */
73. static xint16 artidisco[NROFARTIFACTS];
74. /* note: artiexist[] and artidisco[] don't need to be in struct ga; they
75.  * get explicitly initialized at game start so don't need to be part of
76.  * bulk re-init if game restart ever gets implemented.  They are saved
77.  * and restored but that is done through this file so they can be local.
78.  */
79. 
80. #ifndef SFCTOOL
81. static const struct arti_info zero_artiexist = {0}; /* all bits zero */
82. 
83. staticfn void hack_artifacts(void);
84. 
85. /* handle some special cases; must be called after u_init() */
86. staticfn void
87. hack_artifacts(void)
88. {
89.     struct artifact *art;
90.     int alignmnt = aligns[flags.initalign].value;
91. 
92.     /* Fix up the alignments of "gift" artifacts */
93.     for (art = artilist + 1; art->otyp; art++)
94.         if (art->role == Role_switch && art->alignment != A_NONE)
95.             art->alignment = alignmnt;
96. 
97.     /* Excalibur can be used by any lawful character, not just knights */
98.     if (!Role_if(PM_KNIGHT))
99.         artilist[ART_EXCALIBUR].role = NON_PM;
100. 
101.     /* Fix up the quest artifact */
102.     if (gu.urole.questarti) {
103.         artilist[gu.urole.questarti].alignment = alignmnt;
104.         artilist[gu.urole.questarti].role = Role_switch;
105.     }
106.     return;
107. }
108. 
109. /* zero out the artifact existence list */
110. void
111. init_artifacts(void)
112. {
113.     (void) memset((genericptr_t) artiexist, 0, sizeof artiexist);
114.     (void) memset((genericptr_t) artidisco, 0, sizeof artidisco);
115.     hack_artifacts();
116. }
117. 
118. void
119. save_artifacts(NHFILE *nhfp)
120. {
121.     int i;
122. 
123.     for (i = 0; i < (NROFARTIFACTS + 1); ++i)
124.         Sfo_arti_info(nhfp, &artiexist[i], "artiexist");
125. 
126.     for (i = 0; i < NROFARTIFACTS; ++i)
127.         Sfo_xint16(nhfp, &artidisco[i], "artidisco");
128. }
129. 
130. #endif /* SFCTOOL */
131. 
132. void
133. restore_artifacts(NHFILE *nhfp)
134. {
135.     int i;
136. 
137.     for (i = 0; i < (NROFARTIFACTS + 1); ++i)
138.         Sfi_arti_info(nhfp, &artiexist[i], "artiexist");
139.     for (i = 0; i < NROFARTIFACTS; ++i)
140.         Sfi_short(nhfp, &artidisco[i], "artidisco");
141. #ifndef SFCTOOL
142.     hack_artifacts();   /* redo non-saved special cases */
143. #else
144.     nhUse(artilist);
145. #endif
146. }
147. 
148. #ifndef SFCTOOL
149. 
150. const char *
151. artiname(int artinum)
152. {
153.     if (artinum <= 0 || artinum > NROFARTIFACTS)
154.         return "";
155.     return artilist[artinum].name;
156. }
157. 
158. /*
159.    Make an artifact.  If a specific alignment is specified, then an object of
160.    the appropriate alignment is created from scratch, or 0 is returned if
161.    none is available.  (If at least one aligned artifact has already been
162.    given, then unaligned ones also become eligible for this.)
163.    If no alignment is given, then 'otmp' is converted
164.    into an artifact of matching type, or returned as-is if that's not
165.    possible.
166.    For the 2nd case, caller should use ``obj = mk_artifact(obj, A_NONE, 99);
167.    For the 1st, ``obj = mk_artifact((struct obj *) 0, some_alignment, ...);.
168.    The max_giftvalue is the value of the sacrifice, for an artifact obtained
169.    by sacrificing, or 99 otherwise.
170.  */
171. struct obj *
172. mk_artifact(
173.     struct obj *otmp,    /* existing object; ignored and disposed of
174.                           * if alignment specified */
175.     aligntyp alignment,  /* target alignment, or A_NONE */
176.     uchar max_giftvalue, /* cap on generated giftvalue */
177.     boolean adjust_spe)  /* whether to add spe to situational artifacts */
178. {
179.     const struct artifact *a;
180.     int m, n, altn;
181.     boolean by_align = (alignment != A_NONE);
182.     short o_typ = (by_align || !otmp) ? 0 : otmp->otyp;
183.     boolean unique = !by_align && otmp && objects[o_typ].oc_unique;
184.     short eligible[NROFARTIFACTS];
185.     xint16 skill_compatibility;
186. 
187.     n = altn = 0;    /* no candidates found yet */
188.     eligible[0] = 0; /* lint suppression */
189.     /* gather eligible artifacts */
190.     for (m = 1, a = &artilist[m]; a->otyp; a++, m++) {
191.         if (artiexist[m].exists)
192.             continue;
193.         if ((a->spfx & SPFX_NOGEN) || unique)
194.             continue;
195.         if (a->gift_value > max_giftvalue && !Role_if(a->role))
196.             continue;
197. 
198.         if (!by_align) {
199.             /* looking for a particular type of item; not producing a
200.                divine gift so we don't care about role's first choice */
201.             if (a->otyp == o_typ)
202.                 eligible[n++] = m;
203.             continue; /* move on to next possibility */
204.         }
205. 
206.         /* we're looking for an alignment-specific item
207.            suitable for hero's role+race */
208.         if ((a->alignment == alignment || a->alignment == A_NONE)
209.             /* avoid enemies' equipment */
210.             && (a->race == NON_PM || !race_hostile(&mons[a->race]))) {
211.             /* when a role-specific first choice is available, use it */
212.             if (Role_if(a->role)) {
213.                 /* make this be the only possibility in the list */
214.                 eligible[0] = m;
215.                 n = 1;
216.                 break; /* skip all other candidates */
217.             }
218. 
219.             /* check if this is skill-compatible */
220.             skill_compatibility = P_SKILLED;
221.             if (objects[a->otyp].oc_class == WEAPON_CLASS) {
222.                 schar skill = objects[a->otyp].oc_skill;
223.                 if (skill < 0)
224.                     skill_compatibility = P_MAX_SKILL(-skill);
225.                 else
226.                     skill_compatibility = P_MAX_SKILL(skill);
227.             }
228. 
229.             /* found something to consider for random selection */
230.             if ((a->alignment != A_NONE || u.ugifts > 0 || !rn2(3)) &&
231.                 (!rn2(4) || skill_compatibility >= P_SKILLED ||
232.                  (skill_compatibility >= P_BASIC && rn2(2)))) {
233.                 /* right alignment, or non-aligned with at least 1
234.                    previous gift bestowed, makes this one viable;
235.                    unaligned artifacts are possible even as the first
236.                    gift, but less likely; if it's a bad weapon type
237.                    for the role that also makes it less likely */
238.                 eligible[n++] = m;
239.             } else {
240.                 /* if no candidates have been found yet, record
241.                    this one as a[nother] fallback possibility in
242.                    case all aligned candidates have been used up
243.                    (via wishing, naming, bones, random generation)
244.                    or failed the randomized compatibility checks */
245.                 if (!n)
246.                     eligible[altn++] = m;
247.                 /* [once a regular candidate is found, the list
248.                    is overwritten and `altn' becomes irrelevant] */
249.             }
250.         }
251.     }
252. 
253.     /* resort to fallback list if main list was empty */
254.     if (!n)
255.         n = altn;
256. 
257.     if (n) {
258.         /* found at least one candidate; pick one at random */
259.         m = eligible[rn2(n)]; /* [0..n-1] */
260.         a = &artilist[m];
261. 
262.         /* make an appropriate object if necessary, then christen it */
263.         if (by_align) {
264.             /* 'by_align' indicates that an alignment was passed as
265.              * an argument, but also that the 'otmp' argument is not
266.              * relevant */
267.             struct obj *artiobj = mksobj((int) a->otyp, TRUE, FALSE);
268. 
269.             /* nonnull value of 'otmp' is unexpected. Cope. */
270.             if (otmp) /* just in case; avoid orphaning */
271.                 dispose_of_orig_obj(otmp);
272.             otmp = artiobj;
273.         }
274.         /*
275.          * otmp should be nonnull at this point:
276.          * either the passed argument (if !by_align == A_NONE), or
277.          * the result of mksobj() just above if by_align is an alignment. */
278.         assert(otmp != 0);
279.         /* prevent erosion from generating */
280.         otmp->oeroded = otmp->oeroded2 = 0;
281.         otmp = oname(otmp, a->name, ONAME_NO_FLAGS);
282.         otmp->oartifact = m;  /* probably already set by this point, but */
283.         /* set existence and reason for creation bits */
284.         artifact_origin(otmp, ONAME_RANDOM); /* 'random' is default */
285.         if (adjust_spe) {
286.             int new_spe;
287. 
288.             /* Adjust artiobj->spe by a->gen_spe. (This is a no-op for
289.                non-weapons, which always have a gen_spe of 0, and for many
290.                weapons, too.) The result is clamped into the "normal" range to
291.                prevent an outside chance of +12 artifacts generating. */
292.             new_spe = (int) otmp->spe + a->gen_spe;
293.             if (new_spe >= -10 && new_spe < 10)
294.                 otmp->spe = new_spe;
295.         }
296.     } else {
297.         /* nothing appropriate could be found; return original object */
298.         if (by_align && otmp) {
299.             /* (there shouldn't have been an original object). Deal with it.
300.              * The callers that passed an alignment and a NULL otmp are
301.              * prepared to get a potential NULL return value, so this is okay */
302.             dispose_of_orig_obj(otmp);
303.             otmp = 0;
304.         } /* otherwise, otmp has not changed; just fallthrough to return it */
305.     }
306.     if (otmp && permapoisoned(otmp))
307.         otmp->opoisoned = 1;
308.     return otmp;
309. }
310. 
311. staticfn void
312. dispose_of_orig_obj(struct obj *obj)
313. {
314.     if (!obj)
315.         return;
316. 
317.     obj_extract_self(obj);
318.     obfree(obj, (struct obj *) 0);
319. }
320. 
321. /*
322.  * Returns the full name (with articles and correct capitalization) of an
323.  * artifact named "name" if one exists, or NULL, it not.
324.  * The given name must be rather close to the real name for it to match.
325.  * The object type of the artifact is returned in otyp if the return value
326.  * is non-NULL.
327.  */
328. const char *
329. artifact_name(
330.     const char *name, /* string from player that might be an artifact name */
331.     short *otyp_p,    /* secondary output */
332.     boolean fuzzy)    /* whether to allow extra or omitted spaces or dashes */
333. {
334.     const struct artifact *a;
335.     const char *aname;
336. 
337.     if (!strncmpi(name, "the ", 4))
338.         name += 4;
339. 
340.     for (a = artilist + 1; a->otyp; a++) {
341.         aname = a->name;
342.         if (!strncmpi(aname, "the ", 4))
343.             aname += 4;
344.         if (!fuzzy ? !strcmpi(name, aname)
345.                    : fuzzymatch(name, aname, " -", TRUE)) {
346.             if (otyp_p)
347.                 *otyp_p = a->otyp;
348.             return a->name;
349.         }
350.     }
351. 
352.     return (char *) 0;
353. }
354. 
355. boolean
356. exist_artifact(int otyp, const char *name)
357. {
358.     const struct artifact *a;
359.     struct arti_info *arex;
360. 
361.     if (otyp && *name)
362.         for (a = artilist + 1, arex = artiexist + 1; a->otyp; a++, arex++)
363.             if ((int) a->otyp == otyp && !strcmp(a->name, name))
364.                 return arex->exists ? TRUE : FALSE;
365.     return FALSE;
366. }
367. 
368. /* an artifact has just been created or is being "un-created" for a chance
369.    to be created again later */
370. void
371. artifact_exists(
372.     struct obj *otmp,
373.     const char *name,
374.     boolean mod,      /* True: exists, False: being un-created */
375.     unsigned flgs)    /* ONAME_xyz flags; not relevant if !mod */
376. {
377.     const struct artifact *a;
378. 
379.     if (otmp && *name)
380.         for (a = artilist + 1; a->otyp; a++)
381.             if (a->otyp == otmp->otyp && !strcmp(a->name, name)) {
382.                 int m = (int) (a - artilist);
383. 
384.                 otmp->oartifact = (char) (mod ? m : 0);
385.                 otmp->age = 0;
386.                 if (otmp->otyp == RIN_INCREASE_DAMAGE)
387.                     otmp->spe = 0;
388.                 if (mod) { /* means being created rather than un-created */
389.                     /* one--and only one--of these should always be set */
390.                     if ((flgs & (ONAME_VIA_NAMING | ONAME_WISH | ONAME_GIFT
391.                                  | ONAME_VIA_DIP | ONAME_LEVEL_DEF
392.                                  | ONAME_BONES | ONAME_RANDOM)) == 0)
393.                         flgs |= ONAME_RANDOM; /* the default origin */
394.                     /* 'exists' bit will become set (in artifact_origin();
395.                        there's no ONAME_ flag) and flgs might also contain
396.                        the know_arti bit (hero knows that artifact exists) */
397.                     artifact_origin(otmp, flgs);
398.                 } else { /* uncreate */
399.                     /* clear all the flag bits */
400.                     artiexist[m] = zero_artiexist;
401.                 }
402.                 break;
403.             }
404.     return;
405. }
406. 
407. /* mark an artifact as 'found' */
408. void
409. found_artifact(int a)
410. {
411.     if (a < 1 || a > NROFARTIFACTS)
412.         impossible("found_artifact: invalid artifact index! (%d)", a);
413.     else if (!artiexist[a].exists)
414.         impossible("found_artifact: artifact doesn't exist yet? (%d)", a);
415.     else
416.         artiexist[a].found = 1;
417. }
418. 
419. /* if an artifact hasn't already been designated 'found', do that now
420.    and generate a livelog event about finding it */
421. void
422. find_artifact(struct obj *otmp)
423. {
424.     int a = otmp->oartifact;
425. 
426.     if (a && !artiexist[a].found) {
427.         const char *where;
428. 
429.         found_artifact(a); /* artiexist[a].found = 1 */
430.         /*
431.          * Unlike costly_spot(), inside_shop() includes the "free spot"
432.          * in front of the door.  And it doesn't care whether or not
433.          * there is a shopkeeper present.
434.          *
435.          * If hero sees a monster pick up a not-yet-found artifact, it
436.          * will have its dknown flag set even if far away and will be
437.          * described as 'found on the floor'.  Similarly for dropping
438.          * (possibly upon monster's death), dknown will be set and the
439.          * artifact will be described as 'carried by a monster'.
440.          * That's handled by caller:  dog_invent(), mpickstuff(), or
441.          * mdrop_obj() so that we get called before obj->where changes.
442.          */
443.         where = ((otmp->where == OBJ_FLOOR)
444.                  ?  ((inside_shop(otmp->ox, otmp->oy) != NO_ROOM)
445.                      ? " in a shop"
446.                      : " on the floor")
447.                  /* artifacts aren't created in containers but could be
448.                     inside one if it comes from a bones level */
449.                  : (otmp->where == OBJ_CONTAINED) ? " in a container"
450.                    /* perhaps probing, or seeing monster wield artifact */
451.                    : (otmp->where == OBJ_MINVENT) ? " carried by a monster"
452.                      /* catchall: probably in inventory, picked up while
453.                         blind but now seen; there's no previous_where to
454.                         figure out how it got here */
455.                      : "");
456.         livelog_printf(LL_ARTIFACT, "found %s%s",
457.                        bare_artifactname(otmp), where);
458.     }
459. }
460. 
461. int
462. nartifact_exist(void)
463. {
464.     int i, a = 0;
465. 
466.     for (i = 1; i <= NROFARTIFACTS; ++i)
467.         if (artiexist[i].exists)
468.             ++a;
469. 
470.     return a;
471. }
472. 
473. /* set artifact tracking flags;
474.    calling sequence: oname() -> artifact_exists() -> artifact_origin() or
475.    mksobj(),others -> mk_artifact() -> artifact_origin(random) possibly
476.    followed by mksobj(),others -> artifact_origin(non-random origin) */
477. void
478. artifact_origin(
479.     struct obj *arti, /* new artifact */
480.     unsigned aflags)  /* ONAME_xxx flags, shared by artifact_exists() */
481. {
482.     int ct, a = arti->oartifact;
483. 
484.     if (a) {
485.         /* start by clearing all bits; most are mutually exclusive */
486.         artiexist[a] = zero_artiexist;
487.         /* set 'exists' bit back on; not specified via flag bit in aflags */
488.         artiexist[a].exists = 1;
489.         /* 'hero knows it exists' is expected for wish, gift, viadip, or
490.            named and could eventually become set for any of the others */
491.         if ((aflags & ONAME_KNOW_ARTI) != 0)
492.             artiexist[a].found = 1;
493.         /* should be exactly one of wish, gift, via_dip, via_naming,
494.            level_def (quest), bones, and random (floor or monst's minvent) */
495.         ct = 0;
496.         if ((aflags & ONAME_WISH) != 0)
497.             artiexist[a].wish = 1, ++ct;
498.         if ((aflags & ONAME_GIFT) != 0)
499.             artiexist[a].gift = 1, ++ct;
500.         if ((aflags & ONAME_VIA_DIP) != 0)
501.             artiexist[a].viadip = 1, ++ct;
502.         if ((aflags & ONAME_VIA_NAMING) != 0)
503.             artiexist[a].named = 1, ++ct;
504.         if ((aflags & ONAME_LEVEL_DEF) != 0)
505.             artiexist[a].lvldef = 1, ++ct;
506.         if ((aflags & ONAME_BONES) != 0)
507.             artiexist[a].bones = 1, ++ct;
508.         if ((aflags & ONAME_RANDOM) != 0)
509.             artiexist[a].rndm = 1, ++ct;
510.         if (ct != 1)
511.             impossible("invalid artifact origin: %4o", aflags);
512.     }
513. }
514. 
515. boolean
516. spec_ability(struct obj *otmp, unsigned long abil)
517. {
518.     const struct artifact *arti = get_artifact(otmp);
519. 
520.     return (boolean) (arti != &artilist[ART_NONARTIFACT]
521.                       && (arti->spfx & abil) != 0L);
522. }
523. 
524. /* used so that callers don't need to known about SPFX_ codes */
525. boolean
526. confers_luck(struct obj *obj)
527. {
528.     /* might as well check for this too */
529.     if (obj->otyp == LUCKSTONE)
530.         return TRUE;
531. 
532.     return (boolean) (obj->oartifact && spec_ability(obj, SPFX_LUCK));
533. }
534. 
535. /* used to check whether a monster is getting reflection from an artifact */
536. boolean
537. arti_reflects(struct obj *obj)
538. {
539.     const struct artifact *arti = get_artifact(obj);
540. 
541.     if (arti != &artilist[ART_NONARTIFACT]) {
542.         /* while being worn */
543.         if ((obj->owornmask & ~W_ART) && (arti->spfx & SPFX_REFLECT))
544.             return TRUE;
545.         /* just being carried */
546.         if (arti->cspfx & SPFX_REFLECT)
547.             return TRUE;
548.     }
549.     return FALSE;
550. }
551. 
552. /* decide whether this obj is effective when attacking against shades;
553.    does not consider the bonus for blessed objects versus undead */
554. boolean
555. shade_glare(struct obj *obj)
556. {
557.     const struct artifact *arti;
558. 
559.     /* any silver object is effective */
560.     if (objects[obj->otyp].oc_material == SILVER)
561.         return TRUE;
562.     /* non-silver artifacts with bonus against undead also are effective */
563.     arti = get_artifact(obj);
564.     if (arti != &artilist[ART_NONARTIFACT] && (arti->spfx & SPFX_DFLAG2)
565.                              && arti->mtype == M2_UNDEAD)
566.         return TRUE;
567.     /* [if there was anything with special bonus against noncorporeals,
568.        it would be effective too] */
569.     /* otherwise, harmless to shades */
570.     return FALSE;
571. }
572. 
573. /* returns 1 if name is restricted for otmp->otyp */
574. boolean
575. restrict_name(struct obj *otmp, const char *name)
576. {
577.     const struct artifact *a;
578.     const char *aname, *odesc, *other;
579.     boolean sametype[NUM_OBJECTS];
580.     int i, lo, hi, otyp = otmp->otyp, ocls = objects[otyp].oc_class;
581. 
582.     if (!*name)
583.         return FALSE;
584.     if (!strncmpi(name, "the ", 4))
585.         name += 4;
586. 
587.     /* decide what types of objects are the same as otyp;
588.        if it's been discovered, then only itself matches;
589.        otherwise, include all other undiscovered objects
590.        of the same class which have the same description
591.        or share the same pool of shuffled descriptions */
592.     (void) memset((genericptr_t) sametype, 0, sizeof sametype); /* FALSE */
593.     sametype[otyp] = TRUE;
594.     if (!objects[otyp].oc_name_known
595.         && (odesc = OBJ_DESCR(objects[otyp])) != 0) {
596.         obj_shuffle_range(otyp, &lo, &hi);
597.         for (i = svb.bases[ocls]; i < NUM_OBJECTS; i++) {
598.             if (objects[i].oc_class != ocls)
599.                 break;
600.             if (!objects[i].oc_name_known
601.                 && (other = OBJ_DESCR(objects[i])) != 0
602.                 && (!strcmp(odesc, other) || (i >= lo && i <= hi)))
603.                 sametype[i] = TRUE;
604.         }
605.     }
606. 
607.     /* Since almost every artifact is SPFX_RESTR, it doesn't cost
608.        us much to do the string comparison before the spfx check.
609.        Bug fix:  don't name multiple elven daggers "Sting".
610.      */
611.     for (a = artilist + 1; a->otyp; a++) {
612.         if (!sametype[a->otyp])
613.             continue;
614.         aname = a->name;
615.         if (!strncmpi(aname, "the ", 4))
616.             aname += 4;
617.         if (!strcmp(aname, name))
618.             return (boolean) ((a->spfx & (SPFX_NOGEN | SPFX_RESTR)) != 0
619.                               || otmp->quan > 1L);
620.     }
621. 
622.     return FALSE;
623. }
624. 
625. boolean
626. attacks(int adtyp, struct obj *otmp)
627. {
628.     const struct artifact *weap;
629. 
630.     if ((weap = get_artifact(otmp)) != &artilist[ART_NONARTIFACT])
631.         return (boolean) (weap->attk.adtyp == adtyp);
632.     return FALSE;
633. }
634. 
635. boolean
636. defends(int adtyp, struct obj *otmp)
637. {
638.     const struct artifact *weap;
639. 
640.     if (!otmp)
641.         return FALSE;
642.     if ((weap = get_artifact(otmp)) != &artilist[ART_NONARTIFACT])
643.         return (boolean) (weap->defn.adtyp == adtyp);
644.     if (Is_dragon_armor(otmp)) {
645.         int otyp = otmp->otyp;
646. 
647.         /* convert mail to scales to simplify testing */
648.         if (Is_dragon_mail(otmp))
649.             otyp += GRAY_DRAGON_SCALES - GRAY_DRAGON_SCALE_MAIL;
650. 
651.         switch (adtyp) {
652.         case AD_MAGM: /* magic missiles => general magic resistance */
653.             return (otyp == GRAY_DRAGON_SCALES);
654.         case AD_HALU: /* confers hallucination resistance */
655.             return (otyp == GOLD_DRAGON_SCALES);
656.         case AD_FIRE:
657.       /*case AD_BLND: -- gives infravision but does not prevent blindness */
658.             return (otyp == RED_DRAGON_SCALES); /* red but not gold */
659.         case AD_COLD:
660.       /*case AD_FAMN: -- slows digestion but does not override Famine */
661.             return (otyp == WHITE_DRAGON_SCALES); /* white but not silver */
662.         case AD_DRST: /* drain strength => poison */
663.         case AD_DISE: /* blocks disease but not slime */
664.             return (otyp == GREEN_DRAGON_SCALES);
665.         case AD_SLEE: /* sleep */
666.         case AD_PLYS: /* paralysis => free action */
667.             return (otyp == ORANGE_DRAGON_SCALES);
668.         case AD_DISN: /* disintegration */
669.         case AD_DRLI: /* level drain resistance */
670.             return (otyp == BLACK_DRAGON_SCALES);
671.         case AD_ELEC: /* electricity == lightning */
672.         case AD_SLOW: /* confers speed so blocks speed removal */
673.             return (otyp == BLUE_DRAGON_SCALES);
674.         case AD_ACID:
675.         case AD_STON: /* petrification resistance */
676.             return (otyp == YELLOW_DRAGON_SCALES);
677.         default:
678.             /* SILVER_DRAGON_SCALES don't resist any particular attack type */
679.             break;
680.         }
681.     }
682.     return FALSE;
683. }
684. 
685. /* used for monsters */
686. boolean
687. defends_when_carried(int adtyp, struct obj *otmp)
688. {
689.     const struct artifact *weap;
690. 
691.     if ((weap = get_artifact(otmp)) != &artilist[ART_NONARTIFACT])
692.         return (boolean) (weap->cary.adtyp == adtyp);
693.     return FALSE;
694. }
695. 
696. /* determine whether an item confers Protection */
697. boolean
698. protects(struct obj *otmp, boolean being_worn)
699. {
700.     const struct artifact *arti;
701. 
702.     if (being_worn && objects[otmp->otyp].oc_oprop == PROTECTION)
703.         return TRUE;
704.     arti = get_artifact(otmp);
705.     if (arti == &artilist[ART_NONARTIFACT])
706.         return FALSE;
707.     return (boolean) ((arti->cspfx & SPFX_PROTECT) != 0
708.                       || (being_worn && (arti->spfx & SPFX_PROTECT) != 0));
709. }
710. 
711. /*
712.  * a potential artifact has just been worn/wielded/picked-up or
713.  * unworn/unwielded/dropped.  Pickup/drop only set/reset the W_ART mask.
714.  */
715. void
716. set_artifact_intrinsic(
717.     struct obj *otmp,
718.     boolean on,
719.     long wp_mask)
720. {
721.     long *mask = 0;
722.     const struct artifact *art, *oart = get_artifact(otmp);
723.     struct obj *obj;
724.     uchar dtyp;
725.     long spfx;
726. 
727.     if (oart == &artilist[ART_NONARTIFACT])
728.         return;
729. 
730.     /* effects from the defn field */
731.     dtyp = (wp_mask != W_ART) ? oart->defn.adtyp : oart->cary.adtyp;
732. 
733.     if (dtyp == AD_FIRE)
734.         mask = &EFire_resistance;
735.     else if (dtyp == AD_COLD)
736.         mask = &ECold_resistance;
737.     else if (dtyp == AD_ELEC)
738.         mask = &EShock_resistance;
739.     else if (dtyp == AD_MAGM)
740.         mask = &EAntimagic;
741.     else if (dtyp == AD_DISN)
742.         mask = &EDisint_resistance;
743.     else if (dtyp == AD_DRST)
744.         mask = &EPoison_resistance;
745.     else if (dtyp == AD_DRLI)
746.         mask = &EDrain_resistance;
747. 
748.     if (mask && wp_mask == W_ART && !on) {
749.         /* find out if some other artifact also confers this intrinsic;
750.            if so, leave the mask alone */
751.         for (obj = gi.invent; obj; obj = obj->nobj) {
752.             if (obj != otmp && obj->oartifact) {
753.                 art = get_artifact(obj);
754.                 if (art != &artilist[ART_NONARTIFACT]
755.                         && art->cary.adtyp == dtyp) {
756.                     mask = (long *) 0;
757.                     break;
758.                 }
759.             }
760.         }
761.     }
762.     if (mask) {
763.         if (on)
764.             *mask |= wp_mask;
765.         else
766.             *mask &= ~wp_mask;
767.     }
768. 
769.     /* intrinsics from the spfx field; there could be more than one */
770.     spfx = (wp_mask != W_ART) ? oart->spfx : oart->cspfx;
771.     if (spfx && wp_mask == W_ART && !on) {
772.         /* don't change any spfx also conferred by other artifacts */
773.         for (obj = gi.invent; obj; obj = obj->nobj)
774.             if (obj != otmp && obj->oartifact) {
775.                 art = get_artifact(obj);
776.                 if (art != &artilist[ART_NONARTIFACT])
777.                     spfx &= ~art->cspfx;
778.             }
779.     }
780. 
781.     if (spfx & SPFX_SEARCH) {
782.         if (on)
783.             ESearching |= wp_mask;
784.         else
785.             ESearching &= ~wp_mask;
786.     }
787.     if (spfx & SPFX_HALRES) {
788.         /* make_hallucinated must (re)set the mask itself to get
789.          * the display right */
790.         /* restoring needed because this is the only artifact intrinsic
791.          * that can print a message--need to guard against being printed
792.          * when restoring a game
793.          */
794.         (void) make_hallucinated((long) !on,
795.                                  program_state.restoring ? FALSE : TRUE,
796.                                  wp_mask);
797.     }
798.     if (spfx & SPFX_ESP) {
799.         if (on)
800.             ETelepat |= wp_mask;
801.         else
802.             ETelepat &= ~wp_mask;
803.         recalc_telepat_range();
804.         see_monsters();
805.     }
806.     if (spfx & SPFX_STLTH) {
807.         if (on)
808.             EStealth |= wp_mask;
809.         else
810.             EStealth &= ~wp_mask;
811.     }
812.     if (spfx & SPFX_REGEN) {
813.         if (on)
814.             ERegeneration |= wp_mask;
815.         else
816.             ERegeneration &= ~wp_mask;
817.     }
818.     if (spfx & SPFX_TCTRL) {
819.         if (on)
820.             ETeleport_control |= wp_mask;
821.         else
822.             ETeleport_control &= ~wp_mask;
823.     }
824.     if (spfx & SPFX_WARN) {
825.         if (spec_m2(otmp)) {
826.             if (on) {
827.                 EWarn_of_mon |= wp_mask;
828.                 svc.context.warntype.obj |= spec_m2(otmp);
829.             } else {
830.                 EWarn_of_mon &= ~wp_mask;
831.                 svc.context.warntype.obj &= ~spec_m2(otmp);
832.             }
833.             see_monsters();
834.         } else {
835.             if (on)
836.                 EWarning |= wp_mask;
837.             else
838.                 EWarning &= ~wp_mask;
839.         }
840.     }
841.     if (spfx & SPFX_EREGEN) {
842.         if (on)
843.             EEnergy_regeneration |= wp_mask;
844.         else
845.             EEnergy_regeneration &= ~wp_mask;
846.     }
847.     if (spfx & SPFX_HSPDAM) {
848.         if (on)
849.             EHalf_spell_damage |= wp_mask;
850.         else
851.             EHalf_spell_damage &= ~wp_mask;
852.     }
853.     if (spfx & SPFX_HPHDAM) {
854.         if (on)
855.             EHalf_physical_damage |= wp_mask;
856.         else
857.             EHalf_physical_damage &= ~wp_mask;
858.     }
859.     if (spfx & SPFX_XRAY) {
860.         /* this assumes that no one else is using xray_range */
861.         if (on)
862.             u.xray_range = 3;
863.         else
864.             u.xray_range = -1;
865.         gv.vision_full_recalc = 1;
866.     }
867.     if ((spfx & SPFX_REFLECT) && (wp_mask & W_WEP)) {
868.         if (on)
869.             EReflecting |= wp_mask;
870.         else
871.             EReflecting &= ~wp_mask;
872.     }
873.     if (spfx & SPFX_PROTECT) {
874.         if (on)
875.             EProtection |= wp_mask;
876.         else
877.             EProtection &= ~wp_mask;
878.     }
879. 
880.     if (wp_mask == W_ART && !on && oart->inv_prop) {
881.         /* might have to turn off invoked power too */
882.         if (oart->inv_prop <= LAST_PROP
883.             && (u.uprops[oart->inv_prop].extrinsic & W_ARTI))
884.             (void) arti_invoke(otmp);
885.     }
886. 
887.     if (wp_mask == W_WEP && is_art(otmp, ART_SUNSWORD)) {
888.         if (on)
889.             EBlnd_resist |= wp_mask;
890.         else
891.             EBlnd_resist &= ~wp_mask;
892.     }
893. }
894. 
895. /* touch_artifact()'s return value isn't sufficient to tell whether it
896.    dished out damage, and tracking changes to u.uhp, u.mh, Lifesaved
897.    when trying to avoid second wounding is too cumbersome */
898. static boolean touch_blasted; /* for retouch_object() */
899. 
900. /*
901.  * creature (usually hero) tries to touch (pick up or wield) an artifact obj.
902.  * Returns 0 if the object refuses to be touched.
903.  * This routine does not change any object chains.
904.  * Ignores such things as gauntlets, assuming the artifact is not
905.  * fooled by such trappings.
906.  */
907. int
908. touch_artifact(struct obj *obj, struct monst *mon)
909. {
910.     const struct artifact *oart = get_artifact(obj);
911.     boolean badclass, badalign, self_willed, yours;
912. 
913.     touch_blasted = FALSE;
914.     if (oart == &artilist[ART_NONARTIFACT])
915.         return 1;
916. 
917.     yours = (mon == &gy.youmonst);
918.     /* all quest artifacts are self-willed; if this ever changes, `badclass'
919.        will have to be extended to explicitly include quest artifacts */
920.     self_willed = ((oart->spfx & SPFX_INTEL) != 0);
921.     if (yours) {
922.         badclass = self_willed
923.                    && ((oart->role != NON_PM && !Role_if(oart->role))
924.                        || (oart->race != NON_PM && !Race_if(oart->race)));
925.         badalign = ((oart->spfx & SPFX_RESTR) != 0
926.                     && oart->alignment != A_NONE
927.                     && (oart->alignment != u.ualign.type
928.                         || u.ualign.record < 0));
929.     } else if (!is_covetous(mon->data) && !is_mplayer(mon->data)) {
930.         badclass = self_willed && oart->role != NON_PM
931.                    && oart != &artilist[ART_EXCALIBUR];
932.         badalign = (oart->spfx & SPFX_RESTR) && oart->alignment != A_NONE
933.                    && (oart->alignment != mon_aligntyp(mon));
934.     } else { /* an M3_WANTSxxx monster or a fake player */
935.         /* special monsters trying to take the Amulet, invocation tools or
936.            quest item can touch anything except `spec_applies' artifacts */
937.         badclass = badalign = FALSE;
938.     }
939.     /* weapons which attack specific categories of monsters are
940.        bad for them even if their alignments happen to match */
941.     if (!badalign)
942.         badalign = bane_applies(oart, mon);
943. 
944.     if (((badclass || badalign) && self_willed)
945.         || (badalign && (!yours || !rn2(4)))) {
946.         int dmg, tmp;
947.         char buf[BUFSZ];
948. 
949.         if (!yours)
950.             return 0;
951.         You("are blasted by %s power!", s_suffix(the(xname(obj))));
952.         touch_blasted = TRUE;
953.         dmg = d((Antimagic ? 2 : 4), (self_willed ? 10 : 4));
954.         /* add half (maybe quarter) of the usual silver damage bonus */
955.         if (objects[obj->otyp].oc_material == SILVER && Hate_silver)
956.             tmp = rnd(10), dmg += Maybe_Half_Phys(tmp);
957.         Sprintf(buf, "touching %s", oart->name);
958.         losehp(dmg, buf, KILLED_BY); /* magic damage, not physical */
959.         exercise(A_WIS, FALSE);
960.     }
961. 
962.     /* can pick it up unless you're totally non-synch'd with the artifact */
963.     if (badclass && badalign && self_willed) {
964.         if (yours) {
965.             if (!carried(obj))
966.                 pline("%s your grasp!", Tobjnam(obj, "evade"));
967.             else
968.                 pline("%s beyond your control!", Tobjnam(obj, "are"));
969.         }
970.         return 0;
971.     }
972. 
973.     return 1;
974. }
975. 
976. /* decide whether an artifact itself is vulnerable to a particular type
977.    of erosion damage, independent of the properties of its bearer */
978. boolean
979. arti_immune(struct obj *obj, int dtyp)
980. {
981.     const struct artifact *weap = get_artifact(obj);
982. 
983.     if (weap == &artilist[ART_NONARTIFACT])
984.         return FALSE;
985.     if (dtyp == AD_PHYS)
986.         return FALSE; /* nothing is immune to phys dmg */
987.     return (boolean) (weap->attk.adtyp == dtyp
988.                       || weap->defn.adtyp == dtyp
989.                       || weap->cary.adtyp == dtyp);
990. }
991. 
992. staticfn boolean
993. bane_applies(const struct artifact *oart, struct monst *mon)
994. {
995.     struct artifact atmp;
996. 
997.     if (oart != &artilist[ART_NONARTIFACT]
998.             && (oart->spfx & SPFX_DBONUS) != 0) {
999.         atmp = *oart;
1000.         atmp.spfx &= SPFX_DBONUS; /* clear other spfx fields */
1001.         if (spec_applies(&atmp, mon))
1002.             return TRUE;
1003.     }
1004.     return FALSE;
1005. }
1006. 
1007. /* decide whether an artifact's special attacks apply against mtmp */
1008. staticfn int
1009. spec_applies(const struct artifact *weap, struct monst *mtmp)
1010. {
1011.     struct permonst *ptr;
1012.     boolean yours;
1013. 
1014.     if (!(weap->spfx & (SPFX_DBONUS | SPFX_ATTK)))
1015.         return (weap->attk.adtyp == AD_PHYS);
1016. 
1017.     yours = (mtmp == &gy.youmonst);
1018.     ptr = mtmp->data;
1019. 
1020.     if (weap->spfx & SPFX_DMONS) {
1021.         return (ptr == &mons[(int) weap->mtype]);
1022.     } else if (weap->spfx & SPFX_DCLAS) {
1023.         return (weap->mtype == (unsigned long) ptr->mlet);
1024.     } else if (weap->spfx & SPFX_DFLAG1) {
1025.         return ((ptr->mflags1 & weap->mtype) != 0L);
1026.     } else if (weap->spfx & SPFX_DFLAG2) {
1027.         return ((ptr->mflags2 & weap->mtype)
1028.                 || (yours
1029.                     && ((!Upolyd && (gu.urace.selfmask & weap->mtype))
1030.                         || ((weap->mtype & M2_WERE) && ismnum(u.ulycn)))));
1031.     } else if (weap->spfx & SPFX_DALIGN) {
1032.         return yours ? (u.ualign.type != weap->alignment)
1033.                      : (ptr->maligntyp == A_NONE
1034.                         || sgn(ptr->maligntyp) != weap->alignment);
1035.     } else if (weap->spfx & SPFX_ATTK) {
1036.         if (defended(mtmp, (int) weap->attk.adtyp))
1037.             return FALSE;
1038. 
1039.         switch (weap->attk.adtyp) {
1040.         case AD_FIRE:
1041.             return !(yours ? Fire_resistance : resists_fire(mtmp));
1042.         case AD_COLD:
1043.             return !(yours ? Cold_resistance : resists_cold(mtmp));
1044.         case AD_ELEC:
1045.             return !(yours ? Shock_resistance : resists_elec(mtmp));
1046.         case AD_MAGM:
1047.         case AD_STUN:
1048.             return !(yours ? Antimagic : (rn2(100) < ptr->mr));
1049.         case AD_DRST:
1050.             return !(yours ? Poison_resistance : resists_poison(mtmp));
1051.         case AD_DRLI:
1052.             return !(yours ? Drain_resistance : resists_drli(mtmp));
1053.         case AD_STON:
1054.             return !(yours ? Stone_resistance : resists_ston(mtmp));
1055.         default:
1056.             impossible("Weird weapon special attack.");
1057.         }
1058.     }
1059.     return 0;
1060. }
1061. 
1062. /* return the M2 flags of monster that an artifact's special attacks apply
1063.  * against */
1064. long
1065. spec_m2(struct obj *otmp)
1066. {
1067.     const struct artifact *artifact = get_artifact(otmp);
1068. 
1069.     if (artifact != &artilist[ART_NONARTIFACT])
1070.         return artifact->mtype;
1071.     return 0L;
1072. }
1073. 
1074. /* special attack bonus */
1075. int
1076. spec_abon(struct obj *otmp, struct monst *mon)
1077. {
1078.     const struct artifact *weap = get_artifact(otmp);
1079. 
1080.     /* no need for an extra check for `NO_ATTK' because this will
1081.        always return 0 for any artifact which has that attribute */
1082. 
1083.     if (weap != &artilist[ART_NONARTIFACT]
1084.             && weap->attk.damn && spec_applies(weap, mon))
1085.         return rnd((int) weap->attk.damn);
1086.     return 0;
1087. }
1088. 
1089. /* special damage bonus */
1090. int
1091. spec_dbon(struct obj *otmp, struct monst *mon, int tmp)
1092. {
1093.     const struct artifact *weap = get_artifact(otmp);
1094. 
1095.     if ((weap == &artilist[ART_NONARTIFACT])
1096.         || (weap->attk.adtyp == AD_PHYS /* check for `NO_ATTK' */
1097.                   && weap->attk.damn == 0 && weap->attk.damd == 0))
1098.         gs.spec_dbon_applies = FALSE;
1099.     else if (is_art(otmp, ART_GRIMTOOTH))
1100.         /* Grimtooth has SPFX settings to warn against elves but we want its
1101.            damage bonus to apply to all targets, so bypass spec_applies() */
1102.         gs.spec_dbon_applies = TRUE;
1103.     else
1104.         gs.spec_dbon_applies = spec_applies(weap, mon);
1105. 
1106.     if (gs.spec_dbon_applies)
1107.         return weap->attk.damd ? rnd((int) weap->attk.damd) : max(tmp, 1);
1108.     return 0;
1109. }
1110. 
1111. /* add identified artifact to discoveries list */
1112. void
1113. discover_artifact(xint16 m)
1114. {
1115.     int i;
1116. 
1117.     /* look for this artifact in the discoveries list;
1118.        if we hit an empty slot then it's not present, so add it */
1119.     for (i = 0; i < NROFARTIFACTS; i++)
1120.         if (artidisco[i] == 0 || artidisco[i] == m) {
1121.             artidisco[i] = m;
1122.             return;
1123.         }
1124.     /* there is one slot per artifact, so we should never reach the
1125.        end without either finding the artifact or an empty slot... */
1126.     impossible("couldn't discover artifact (%d)", (int) m);
1127. }
1128. 
1129. /* used to decide whether an artifact has been fully identified */
1130. boolean
1131. undiscovered_artifact(xint16 m)
1132. {
1133.     int i;
1134. 
1135.     /* look for this artifact in the discoveries list;
1136.        if we hit an empty slot then it's undiscovered */
1137.     for (i = 0; i < NROFARTIFACTS; i++)
1138.         if (artidisco[i] == m)
1139.             return FALSE;
1140.         else if (artidisco[i] == 0)
1141.             break;
1142.     return TRUE;
1143. }
1144. 
1145. /* display a list of discovered artifacts; return their count */
1146. int
1147. disp_artifact_discoveries(
1148.     winid tmpwin) /* supplied by dodiscover(); type is NHW_TEXT */
1149. {
1150.     int i, m, otyp;
1151.     const char *algnstr;
1152.     char buf[BUFSZ];
1153. 
1154.     for (i = 0; i < NROFARTIFACTS; i++) {
1155.         if (artidisco[i] == 0)
1156.             break; /* empty slot implies end of list */
1157.         if (tmpwin == WIN_ERR)
1158.             continue; /* for WIN_ERR, we just count */
1159. 
1160.         if (i == 0)
1161.             putstr(tmpwin, iflags.menu_headings.attr, "Artifacts");
1162.         m = artidisco[i];
1163.         otyp = artilist[m].otyp;
1164.         algnstr = align_str(artilist[m].alignment);
1165.         if (!strcmp(algnstr, "unaligned"))
1166.             algnstr = "non-aligned";
1167. 
1168.         Sprintf(buf, "  %s [%s %s]", artiname(m),
1169.                 algnstr, simple_typename(otyp));
1170.         putstr(tmpwin, 0, buf);
1171.     }
1172.     return i;
1173. }
1174. 
1175. /* (wizard mode only) show all artifacts and their flags */
1176. void
1177. dump_artifact_info(winid tmpwin)
1178. {
1179.     int m;
1180.     char buf[BUFSZ], buf2[BUFSZ];
1181. 
1182.     /* not a menu, but header uses same bold or whatever attribute as such */
1183.     putstr(tmpwin, iflags.menu_headings.attr, "Artifacts");
1184.     for (m = 1; m <= NROFARTIFACTS; ++m) {
1185.         Snprintf(buf2, sizeof buf2,
1186.                 "[%s%s%s%s%s%s%s%s%s]", /* 9 bits overall */
1187.                 artiexist[m].exists ? "exists;" : "",
1188.                 artiexist[m].found  ? " hero knows;" : "",
1189.                 /* .exists and .found have different punctuation because
1190.                    they're expected to be combined with one of these */
1191.                 artiexist[m].gift   ? " gift"   : "",
1192.                 artiexist[m].wish   ? " wish"   : "",
1193.                 artiexist[m].named  ? " named"  : "",
1194.                 artiexist[m].viadip ? " viadip" : "",
1195.                 artiexist[m].lvldef ? " lvldef" : "",
1196.                 artiexist[m].bones  ? " bones"  : "",
1197.                 artiexist[m].rndm   ? " random" : "");
1198. #if 0   /* 'tmpwin' here is a text window, not a menu */
1199.         if (iflags.menu_tab_sep)
1200.             Sprintf(buf, "  %s\t%s", artiname(m), buf2);
1201.         else
1202. #else
1203.             /* "The Platinum Yendorian Express Card" is 35 characters */
1204.             Snprintf(buf, sizeof buf, "  %-36.36s%s", artiname(m), buf2);
1205. #endif
1206.         putstr(tmpwin, 0, buf);
1207.     }
1208.     return;
1209. }
1210. 
1211. /*
1212.  * Magicbane's intrinsic magic is incompatible with normal
1213.  * enchantment magic.  Thus, its effects have a negative
1214.  * dependence on spe.  Against low mr victims, it typically
1215.  * does "double athame" damage, 2d4.  Occasionally, it will
1216.  * cast unbalancing magic which effectively averages out to
1217.  * 4d4 damage (3d4 against high mr victims), for spe = 0.
1218.  *
1219.  * Prior to 3.4.1, the cancel (aka purge) effect always
1220.  * included the scare effect too; now it's one or the other.
1221.  * Likewise, the stun effect won't be combined with either
1222.  * of those two; it will be chosen separately or possibly
1223.  * used as a fallback when scare or cancel fails.
1224.  *
1225.  * [Historical note: a change to artifact_hit() for 3.4.0
1226.  * unintentionally made all of Magicbane's special effects
1227.  * be blocked if the defender successfully saved against a
1228.  * stun attack.  As of 3.4.1, those effects can occur but
1229.  * will be slightly less likely than they were in 3.3.x.]
1230.  */
1231. 
1232. enum mb_effect_indices {
1233.     MB_INDEX_PROBE = 0,
1234.     MB_INDEX_STUN,
1235.     MB_INDEX_SCARE,
1236.     MB_INDEX_CANCEL,
1237. 
1238.     NUM_MB_INDICES
1239. };
1240. 
1241. #define MB_MAX_DIEROLL 8 /* rolls above this aren't magical */
1242. static const char *const mb_verb[2][NUM_MB_INDICES] = {
1243.     { "probe", "stun", "scare", "cancel" },
1244.     { "prod", "amaze", "tickle", "purge" },
1245. };
1246. 
1247. /* called when someone is being hit by Magicbane */
1248. staticfn boolean
1249. Mb_hit(struct monst *magr, /* attacker */
1250.        struct monst *mdef, /* defender */
1251.        struct obj *mb,     /* Magicbane */
1252.        int *dmgptr,        /* extra damage target will suffer */
1253.        int dieroll,        /* d20 that has already scored a hit */
1254.        boolean vis,        /* whether the action can be seen */
1255.        char *hittee)       /* target's name: "you" or mon_nam(mdef) */
1256. {
1257.     struct permonst *old_mdat;
1258.     const char *verb;
1259.     boolean youattack = (magr == &gy.youmonst),
1260.             youdefend = (mdef == &gy.youmonst),
1261.             resisted = FALSE, do_stun, do_confuse, result;
1262.     int attack_indx, fakeidx, scare_dieroll = MB_MAX_DIEROLL / 2;
1263. 
1264.     result = FALSE; /* no message given yet */
1265.     /* the most severe effects are less likely at higher enchantment */
1266.     if (mb->spe >= 3)
1267.         scare_dieroll /= (1 << (mb->spe / 3));
1268.     /* if target successfully resisted the artifact damage bonus,
1269.        reduce overall likelihood of the assorted special effects */
1270.     if (!gs.spec_dbon_applies)
1271.         dieroll += 1;
1272. 
1273.     /* might stun even when attempting a more severe effect, but
1274.        in that case it will only happen if the other effect fails;
1275.        extra damage will apply regardless; 3.4.1: sometimes might
1276.        just probe even when it hasn't been enchanted */
1277.     do_stun = (max(mb->spe, 0) < rn2(gs.spec_dbon_applies ? 11 : 7));
1278. 
1279.     /* the special effects also boost physical damage; increments are
1280.        generally cumulative, but since the stun effect is based on a
1281.        different criterium its damage might not be included; the base
1282.        damage is either 1d4 (athame) or 2d4 (athame+spec_dbon) depending
1283.        on target's resistance check against AD_STUN (handled by caller)
1284.        [note that a successful save against AD_STUN doesn't actually
1285.        prevent the target from ending up stunned] */
1286.     attack_indx = MB_INDEX_PROBE;
1287.     *dmgptr += rnd(4); /* (2..3)d4 */
1288.     if (do_stun) {
1289.         attack_indx = MB_INDEX_STUN;
1290.         *dmgptr += rnd(4); /* (3..4)d4 */
1291.     }
1292.     if (dieroll <= scare_dieroll) {
1293.         attack_indx = MB_INDEX_SCARE;
1294.         *dmgptr += rnd(4); /* (3..5)d4 */
1295.     }
1296.     if (dieroll <= (scare_dieroll / 2)) {
1297.         attack_indx = MB_INDEX_CANCEL;
1298.         *dmgptr += rnd(4); /* (4..6)d4 */
1299.     }
1300. 
1301.     /* give the hit message prior to inflicting the effects */
1302.     verb = mb_verb[!!Hallucination][attack_indx];
1303.     if (youattack || youdefend || vis) {
1304.         result = TRUE;
1305.         pline_The("magic-absorbing blade %s %s!",
1306.                   vtense((const char *) 0, verb), hittee);
1307.         /* assume probing has some sort of noticeable feedback
1308.            even if it is being done by one monster to another */
1309.         if (attack_indx == MB_INDEX_PROBE && !canspotmon(mdef))
1310.             map_invisible(mdef->mx, mdef->my);
1311.     }
1312. 
1313.     /* now perform special effects */
1314.     switch (attack_indx) {
1315.     case MB_INDEX_CANCEL:
1316.         old_mdat = youdefend ? gy.youmonst.data : mdef->data;
1317.         /* No mdef->mcan check: even a cancelled monster can be polymorphed
1318.          * into a golem, and the "cancel" effect acts as if some magical
1319.          * energy remains in spellcasting defenders to be absorbed later.
1320.          */
1321.         if (!cancel_monst(mdef, mb, youattack, FALSE, FALSE)) {
1322.             resisted = TRUE;
1323.         } else {
1324.             do_stun = FALSE;
1325.             if (youdefend) {
1326.                 if (gy.youmonst.data != old_mdat)
1327.                     *dmgptr = 0; /* rehumanized, so no more damage */
1328.                 if (u.uenmax > 0) {
1329.                     u.uenmax--;
1330.                     if (u.uen > 0)
1331.                         u.uen--;
1332.                     disp.botl = TRUE;
1333.                     You("lose magical energy!");
1334.                 }
1335.             } else {
1336.                 /* canceled shapeshifter/vamp may have changed forms, so
1337.                    update its name if necessary */
1338.                 if (mdef->data != old_mdat)
1339.                     Strcpy(hittee, mon_nam(mdef));
1340.                 if (mdef->data == &mons[PM_CLAY_GOLEM])
1341.                     mdef->mhp = 1; /* cancelled clay golems will die */
1342.                 if (youattack && attacktype(mdef->data, AT_MAGC)) {
1343.                     u.uenmax++;
1344.                     if (u.uenmax > u.uenpeak)
1345.                         u.uenpeak = u.uenmax;
1346.                     u.uen++;
1347.                     disp.botl = TRUE;
1348.                     You("absorb magical energy!");
1349.                 }
1350.             }
1351.         }
1352.         break;
1353. 
1354.     case MB_INDEX_SCARE:
1355.         if (youdefend) {
1356.             if (Antimagic) {
1357.                 resisted = TRUE;
1358.             } else {
1359.                 nomul(-3);
1360.                 gm.multi_reason = "being scared stiff";
1361.                 gn.nomovemsg = "";
1362.                 if (magr && magr == u.ustuck && sticks(gy.youmonst.data)) {
1363.                     set_ustuck((struct monst *) 0);
1364.                     You("release %s!", mon_nam(magr));
1365.                 }
1366.             }
1367.         } else {
1368.             if (rn2(2) && resist(mdef, WEAPON_CLASS, 0, NOTELL))
1369.                 resisted = TRUE;
1370.             else
1371.                 monflee(mdef, 3, FALSE, (mdef->mhp > *dmgptr));
1372.         }
1373.         if (!resisted)
1374.             do_stun = FALSE;
1375.         break;
1376. 
1377.     case MB_INDEX_STUN:
1378.         do_stun = TRUE; /* (this is redundant...) */
1379.         break;
1380. 
1381.     case MB_INDEX_PROBE:
1382.         if (youattack && (mb->spe == 0 || !rn2(3 * abs(mb->spe)))) {
1383.             pline_The("%s is insightful.", verb);
1384.             /* pre-damage status */
1385.             probe_monster(mdef);
1386.         }
1387.         break;
1388.     }
1389.     /* stun if that was selected and a worse effect didn't occur */
1390.     if (do_stun) {
1391.         if (youdefend)
1392.             make_stunned(((HStun & TIMEOUT) + 3L), FALSE);
1393.         else
1394.             mdef->mstun = 1;
1395.         /* avoid extra stun message below if we used mb_verb["stun"] above */
1396.         if (attack_indx == MB_INDEX_STUN)
1397.             do_stun = FALSE;
1398.     }
1399.     /* lastly, all this magic can be confusing... */
1400.     do_confuse = !rn2(12);
1401.     if (do_confuse) {
1402.         if (youdefend)
1403.             make_confused((HConfusion & TIMEOUT) + 4L, FALSE);
1404.         else
1405.             mdef->mconf = 1;
1406.     }
1407. 
1408.     /* now give message(s) describing side-effects; Use fakename
1409.        so vtense() won't be fooled by assigned name ending in 's' */
1410.     fakeidx = youdefend ? 1 : 0;
1411.     if (youattack || youdefend || vis) {
1412.         (void) upstart(hittee); /* capitalize */
1413.         if (resisted) {
1414.             pline("%s %s!", hittee, vtense(fakename[fakeidx], "resist"));
1415.             shieldeff(youdefend ? u.ux : mdef->mx,
1416.                       youdefend ? u.uy : mdef->my);
1417.         }
1418.         if ((do_stun || do_confuse) && flags.verbose) {
1419.             char buf[BUFSZ];
1420. 
1421.             buf[0] = '\0';
1422.             if (do_stun)
1423.                 Strcat(buf, "stunned");
1424.             if (do_stun && do_confuse)
1425.                 Strcat(buf, " and ");
1426.             if (do_confuse)
1427.                 Strcat(buf, "confused");
1428.             pline("%s %s %s%c", hittee, vtense(fakename[fakeidx], "are"), buf,
1429.                   (do_stun && do_confuse) ? '!' : '.');
1430.         }
1431.     }
1432. 
1433.     return result;
1434. }
1435. 
1436. DISABLE_WARNING_FORMAT_NONLITERAL
1437. 
1438. /* Function used when someone attacks someone else with an artifact
1439.  * weapon.  Only adds the special (artifact) damage, and returns a 1 if it
1440.  * did something special (in which case the caller won't print the normal
1441.  * hit message).  This should be called once upon every artifact attack;
1442.  * dmgval() no longer takes artifact bonuses into account.  Possible
1443.  * extension: change the killer so that when an orc kills you with
1444.  * Stormbringer it's "killed by Stormbringer" instead of "killed by an orc".
1445.  */
1446. boolean
1447. artifact_hit(
1448.     struct monst *magr, /* attacker; might be Null if 'mdef' is youmonst */
1449.     struct monst *mdef, /* defender */
1450.     struct obj *otmp,   /* artifact weapon */
1451.     int *dmgptr,        /* output */
1452.     int dieroll)        /* needed for Magicbane and vorpal blades */
1453. {
1454.     boolean youattack = (magr == &gy.youmonst);
1455.     boolean youdefend = (mdef == &gy.youmonst);
1456.     boolean vis = (!youattack && magr && cansee(magr->mx, magr->my))
1457.                   || (!youdefend && cansee(mdef->mx, mdef->my))
1458.                   || (youattack && engulfing_u(mdef) && !Blind);
1459.     boolean realizes_damage;
1460.     const char *wepdesc;
1461.     static const char you[] = "you";
1462.     char hittee[BUFSZ];
1463. 
1464.     Strcpy(hittee, youdefend ? you : mon_nam(mdef));
1465. 
1466.     /* The following takes care of most of the damage, but not all--
1467.      * the exception being for level draining, which is specially
1468.      * handled.  Messages are done in this function, however.
1469.      */
1470.     *dmgptr += spec_dbon(otmp, mdef, *dmgptr);
1471. 
1472.     if (youattack && youdefend) {
1473.         impossible("attacking yourself with weapon?");
1474.         return FALSE;
1475.     }
1476. 
1477.     realizes_damage = (youdefend || vis
1478.                        /* feel the effect even if not seen */
1479.                        || (youattack && mdef == u.ustuck));
1480. 
1481.     /* the four basic attacks: fire, cold, shock and missiles */
1482.     if (attacks(AD_FIRE, otmp)) {
1483.         if (realizes_damage)
1484.             pline_The("fiery blade %s %s%c",
1485.                       !gs.spec_dbon_applies
1486.                           ? "hits"
1487.                           : (mdef->data == &mons[PM_WATER_ELEMENTAL])
1488.                                 ? "vaporizes part of"
1489.                                 : "burns",
1490.                       hittee, !gs.spec_dbon_applies ? '.' : '!');
1491.         if (!rn2(4)) {
1492.             int itemdmg = destroy_items(mdef, AD_FIRE, *dmgptr);
1493.             if (!youdefend)
1494.                 *dmgptr += itemdmg; /* item destruction dmg */
1495.             ignite_items(mdef->minvent);
1496.         }
1497.         if (youdefend && Slimed)
1498.             burn_away_slime();
1499.         return realizes_damage;
1500.     }
1501.     if (attacks(AD_COLD, otmp)) {
1502.         if (realizes_damage)
1503.             pline_The("ice-cold blade %s %s%c",
1504.                       !gs.spec_dbon_applies ? "hits" : "freezes", hittee,
1505.                       !gs.spec_dbon_applies ? '.' : '!');
1506.         if (!rn2(4)) {
1507.             int itemdmg = destroy_items(mdef, AD_COLD, *dmgptr);
1508.             if (!youdefend)
1509.                 *dmgptr += itemdmg; /* item destruction dmg */
1510.         }
1511.         return realizes_damage;
1512.     }
1513.     if (attacks(AD_ELEC, otmp)) {
1514.         if (realizes_damage)
1515.             pline_The("massive hammer hits%s %s%c",
1516.                       !gs.spec_dbon_applies ? "" : "!  Lightning strikes",
1517.                       hittee, !gs.spec_dbon_applies ? '.' : '!');
1518.         if (gs.spec_dbon_applies)
1519.             wake_nearto(mdef->mx, mdef->my, 4 * 4);
1520.         if (!rn2(5)) {
1521.             int itemdmg = destroy_items(mdef, AD_ELEC, *dmgptr);
1522.             if (!youdefend)
1523.                 *dmgptr += itemdmg; /* item destruction dmg */
1524.         }
1525.         return realizes_damage;
1526.     }
1527.     if (attacks(AD_MAGM, otmp)) {
1528.         if (realizes_damage)
1529.             pline_The("imaginary widget hits%s %s%c",
1530.                       !gs.spec_dbon_applies
1531.                           ? ""
1532.                           : "!  A hail of magic missiles strikes",
1533.                       hittee, !gs.spec_dbon_applies ? '.' : '!');
1534.         return realizes_damage;
1535.     }
1536. 
1537.     if (attacks(AD_STUN, otmp) && dieroll <= MB_MAX_DIEROLL) {
1538.         /* Magicbane's special attacks (possibly modifies hittee[]) */
1539.         return Mb_hit(magr, mdef, otmp, dmgptr, dieroll, vis, hittee);
1540.     }
1541. 
1542.     if (!gs.spec_dbon_applies) {
1543.         /* since damage bonus didn't apply, nothing more to do;
1544.            no further attacks have side-effects on inventory */
1545.         return FALSE;
1546.     }
1547. 
1548.     /* We really want "on a natural 20" but Nethack does it in */
1549.     /* reverse from AD&D. */
1550.     if (spec_ability(otmp, SPFX_BEHEAD)) {
1551.         if (is_art(otmp, ART_TSURUGI_OF_MURAMASA) && dieroll == 1) {
1552.             wepdesc = "The razor-sharp blade";
1553.             /* not really beheading, but so close, why add another SPFX */
1554.             if (youattack && engulfing_u(mdef)) {
1555.                 You("slice %s wide open!", mon_nam(mdef));
1556.                 *dmgptr = 2 * mdef->mhp + FATAL_DAMAGE_MODIFIER;
1557.                 return TRUE;
1558.             }
1559.             if (!youdefend) {
1560.                 /* allow normal cutworm() call to add extra damage */
1561.                 if (gn.notonhead)
1562.                     return FALSE;
1563. 
1564.                 if (bigmonst(mdef->data)) {
1565.                     if (youattack)
1566.                         You("slice deeply into %s!", mon_nam(mdef));
1567.                     else if (vis)
1568.                         pline("%s cuts deeply into %s!", Monnam(magr),
1569.                               hittee);
1570.                     *dmgptr *= 2;
1571.                     return TRUE;
1572.                 }
1573.                 *dmgptr = 2 * mdef->mhp + FATAL_DAMAGE_MODIFIER;
1574.                 pline("%s cuts %s in half!", wepdesc, mon_nam(mdef));
1575.                 observe_object(otmp);
1576.                 return TRUE;
1577.             } else {
1578.                 if (bigmonst(gy.youmonst.data)) {
1579.                     pline("%s cuts deeply into you!",
1580.                           magr ? Monnam(magr) : wepdesc);
1581.                     *dmgptr *= 2;
1582.                     return TRUE;
1583.                 }
1584. 
1585.                 /* Players with negative AC's take less damage instead
1586.                  * of just not getting hit.  We must add a large enough
1587.                  * value to the damage so that this reduction in
1588.                  * damage does not prevent death.
1589.                  */
1590.                 *dmgptr = 2 * (Upolyd ? u.mh : u.uhp) + FATAL_DAMAGE_MODIFIER;
1591.                 pline("%s cuts you in half!", wepdesc);
1592.                 observe_object(otmp);
1593.                 return TRUE;
1594.             }
1595.         } else if (is_art(otmp, ART_VORPAL_BLADE)
1596.                    && (dieroll == 1 || mdef->data == &mons[PM_JABBERWOCK])) {
1597.             static const char *const behead_msg[2] = { "%s beheads %s!",
1598.                                                        "%s decapitates %s!" };
1599. 
1600.             if (youattack && engulfing_u(mdef))
1601.                 return FALSE;
1602.             wepdesc = artilist[ART_VORPAL_BLADE].name;
1603.             if (!youdefend) {
1604.                 if (!has_head(mdef->data) || gn.notonhead || u.uswallow) {
1605.                     if (youattack)
1606.                         pline("Somehow, you miss %s wildly.", mon_nam(mdef));
1607.                     else if (vis)
1608.                         pline("Somehow, %s misses wildly.", mon_nam(magr));
1609.                     *dmgptr = 0;
1610.                     return (boolean) (youattack || vis);
1611.                 }
1612.                 if (noncorporeal(mdef->data) || amorphous(mdef->data)) {
1613.                     pline("%s slices through %s %s.", wepdesc,
1614.                           s_suffix(mon_nam(mdef)), mbodypart(mdef, NECK));
1615.                     return TRUE;
1616.                 }
1617.                 *dmgptr = 2 * mdef->mhp + FATAL_DAMAGE_MODIFIER;
1618.                 pline(ROLL_FROM(behead_msg), wepdesc,
1619.                       mon_nam(mdef));
1620.                 if (Hallucination && !flags.female)
1621.                     pline("Good job Henry, but that wasn't Anne.");
1622.                 observe_object(otmp);
1623.                 return TRUE;
1624.             } else {
1625.                 if (!has_head(gy.youmonst.data)) {
1626.                     pline("Somehow, %s misses you wildly.",
1627.                           magr ? mon_nam(magr) : wepdesc);
1628.                     *dmgptr = 0;
1629.                     return TRUE;
1630.                 }
1631.                 if (noncorporeal(gy.youmonst.data)
1632.                     || amorphous(gy.youmonst.data)) {
1633.                     pline("%s slices through your %s.", wepdesc,
1634.                           body_part(NECK));
1635.                     return TRUE;
1636.                 }
1637.                 *dmgptr = 2 * (Upolyd ? u.mh : u.uhp) + FATAL_DAMAGE_MODIFIER;
1638.                 pline(ROLL_FROM(behead_msg), wepdesc, "you");
1639.                 observe_object(otmp);
1640.                 /* Should amulets fall off? */
1641.                 return TRUE;
1642.             }
1643.         }
1644.     }
1645.     if (spec_ability(otmp, SPFX_DRLI)) {
1646.         /* some non-living creatures (golems, vortices) are vulnerable to
1647.            life drain effects so can get "<Arti> draws the <life>" feedback */
1648.         const char *life = nonliving(mdef->data) ? "animating force" : "life";
1649. 
1650.         if (!youdefend) {
1651.             int m_lev = (int) mdef->m_lev, /* will be 0 for 1d4 mon */
1652.                 mhpmax = mdef->mhpmax,
1653.                 drain = monhp_per_lvl(mdef); /* usually 1d8 */
1654.                 /* note: DRLI attack uses 2d6, attacker doesn't get healed */
1655. 
1656.             /* stop draining HP if it drops too low (still drains level;
1657.                also caller still inflicts regular weapon damage) */
1658.             if (mhpmax - drain <= m_lev)
1659.                 drain = (mhpmax > m_lev) ? (mhpmax - (m_lev + 1)) : 0;
1660. 
1661.             if (vis) {
1662.                 /* call distant_name() for possible side-effects even if
1663.                    the result won't be printed */
1664.                 char *otmpname = distant_name(otmp, xname);
1665. 
1666.                 if (is_art(otmp, ART_STORMBRINGER))
1667.                     pline_The("%s blade draws the %s from %s!",
1668.                               hcolor(NH_BLACK), life, mon_nam(mdef));
1669.                 else
1670.                     pline("%s draws the %s from %s!",
1671.                           The(otmpname), life, mon_nam(mdef));
1672.             }
1673.             if (mdef->m_lev == 0) {
1674.                 /* losing a level when at 0 is fatal */
1675.                 *dmgptr = 2 * mdef->mhp + FATAL_DAMAGE_MODIFIER;
1676.             } else {
1677.                 *dmgptr += drain;
1678.                 mdef->mhpmax -= drain;
1679.                 mdef->m_lev--;
1680.             }
1681. 
1682.             if (drain > 0) {
1683.                 /* drain: was target's damage, now heal attacker by half */
1684.                 drain = (drain + 1) / 2; /* drain/2 rounded up */
1685.                 if (youattack) {
1686.                     healup(drain, 0, FALSE, FALSE);
1687.                 } else {
1688.                     assert(magr != 0);
1689.                     healmon(magr, drain, 0);
1690.                 }
1691.             }
1692.             return vis;
1693.         } else { /* youdefend */
1694.             int oldhpmax = u.uhpmax;
1695. 
1696.             if (Blind) {
1697.                 You_feel("an %s drain your %s!",
1698.                          is_art(otmp, ART_STORMBRINGER)
1699.                             ? "unholy blade"
1700.                             : "object",
1701.                          life);
1702.             } else {
1703.                 /* call distant_name() for possible side-effects even if
1704.                    the result won't be printed */
1705.                 char *otmpname = distant_name(otmp, xname);
1706. 
1707.                 if (is_art(otmp, ART_STORMBRINGER))
1708.                     pline_The("%s blade drains your %s!",
1709.                               hcolor(NH_BLACK), life);
1710.                 else
1711.                     pline("%s drains your %s!", The(otmpname), life);
1712.             }
1713.             losexp("life drainage");
1714.             if (magr && magr->mhp < magr->mhpmax) {
1715.                 healmon(magr, (abs(oldhpmax - u.uhpmax) + 1) / 2, 0);
1716.             }
1717.             return TRUE;
1718.         }
1719.     }
1720.     return FALSE;
1721. }
1722. 
1723. RESTORE_WARNING_FORMAT_NONLITERAL
1724. 
1725. /* getobj callback for object to be invoked */
1726. staticfn int
1727. invoke_ok(struct obj *obj)
1728. {
1729.     if (!obj)
1730.         return GETOBJ_EXCLUDE;
1731. 
1732.     /* artifacts and other special items */
1733.     if (obj->oartifact || objects[obj->otyp].oc_unique
1734.         || (obj->otyp == FAKE_AMULET_OF_YENDOR && !obj->known))
1735.         return GETOBJ_SUGGEST;
1736. 
1737.     /* synonym for apply, though actually invoking it will do different things
1738.      * depending if it's a regular crystal ball, an artifact one that has an
1739.      * invoke power, and a (theoretical) artifact one that doesn't have an
1740.      * invoke power */
1741.     if (obj->otyp == CRYSTAL_BALL)
1742.         return GETOBJ_SUGGEST;
1743. 
1744.     return GETOBJ_EXCLUDE;
1745. }
1746. 
1747. /* the #invoke command */
1748. int
1749. doinvoke(void)
1750. {
1751.     struct obj *obj;
1752. 
1753.     obj = getobj("invoke", invoke_ok, GETOBJ_PROMPT);
1754.     if (!obj)
1755.         return ECMD_CANCEL;
1756.     if (!retouch_object(&obj, FALSE))
1757.         return ECMD_TIME;
1758.     return arti_invoke(obj);
1759. }
1760. 
1761. staticfn void
1762. nothing_special(struct obj *obj)
1763. {
1764.     if (carried(obj))
1765.         You_feel("a surge of power, but nothing seems to happen.");
1766. }
1767. 
1768. staticfn int
1769. invoke_taming(struct obj *obj UNUSED)
1770. {
1771.     struct obj pseudo;
1772. 
1773.     pseudo = cg.zeroobj; /* neither cursed nor blessed, zero oextra too */
1774.     pseudo.otyp = SCR_TAMING;
1775.     (void) seffects(&pseudo);
1776.     return ECMD_TIME;
1777. }
1778. 
1779. staticfn int
1780. invoke_healing(struct obj *obj)
1781. {
1782.     int healamt = (u.uhpmax + 1 - u.uhp) / 2;
1783.     long creamed = (long) u.ucreamed;
1784. 
1785.     if (Upolyd)
1786.         healamt = (u.mhmax + 1 - u.mh) / 2;
1787.     if (healamt || Sick || Slimed || Blinded > creamed)
1788.         You_feel("better.");
1789.     if (healamt || Sick || Slimed || BlindedTimeout > creamed)
1790.         You_feel("%sbetter.",
1791.                  (!healamt && !Sick && !Slimed
1792.                   /* when healing temporary blindness (aside from
1793.                      goop covering face), might still be blind
1794.                      due to PermaBlind or eyeless polymorph;
1795.                      vary the message in that situation */
1796.                   && (HBlinded & ~TIMEOUT) != 0L) ? "slightly " : "");
1797.     else {
1798.         nothing_special(obj);
1799.         return ECMD_TIME;
1800.     }
1801.     if (healamt > 0) {
1802.         if (Upolyd)
1803.             u.mh += healamt;
1804.         else
1805.             u.uhp += healamt;
1806.     }
1807.     if (Sick)
1808.         make_sick(0L, (char *) 0, FALSE, SICK_ALL);
1809.     if (Slimed)
1810.         make_slimed(0L, (char *) 0);
1811.     if (BlindedTimeout > creamed)
1812.         make_blinded(creamed, FALSE);
1813.     disp.botl = TRUE;
1814.     return ECMD_TIME;
1815. }
1816. 
1817. staticfn int
1818. invoke_energy_boost(struct obj *obj)
1819. {
1820.     int epboost = (u.uenmax + 1 - u.uen) / 2;
1821. 
1822.     if (epboost > 120)
1823.         epboost = 120; /* arbitrary */
1824.     else if (epboost < 12)
1825.         epboost = u.uenmax - u.uen;
1826.     if (epboost) {
1827.         u.uen += epboost;
1828.         disp.botl = TRUE;
1829.         You_feel("re-energized.");
1830.     } else {
1831.         nothing_special(obj);
1832.         return ECMD_TIME;
1833.     }
1834.     return ECMD_TIME;
1835. }
1836. 
1837. staticfn int
1838. invoke_untrap(struct obj *obj)
1839. {
1840.     if (!untrap(TRUE, 0, 0, (struct obj *) 0)) {
1841.         obj->age = 0; /* don't charge for changing their mind */
1842.         return ECMD_CANCEL;
1843.     }
1844.     return ECMD_TIME;
1845. }
1846. 
1847. staticfn int
1848. invoke_charge_obj(struct obj *obj)
1849. {
1850.     const struct artifact *oart = get_artifact(obj);
1851.     struct obj *otmp = getobj("charge", charge_ok,
1852.                               GETOBJ_PROMPT | GETOBJ_ALLOWCNT);
1853.     boolean b_effect;
1854. 
1855.     if (!otmp) {
1856.         obj->age = 0;
1857.         return ECMD_CANCEL;
1858.     }
1859.     b_effect = (obj->blessed && (oart->role == Role_switch
1860.                                  || oart->role == NON_PM));
1861.     recharge(otmp, b_effect ? 1 : obj->cursed ? -1 : 0);
1862.     update_inventory();
1863.     return ECMD_TIME;
1864. }
1865. 
1866. staticfn int
1867. invoke_create_portal(struct obj *obj)
1868. {
1869.     int i, num_ok_dungeons, last_ok_dungeon = 0;
1870.     d_level newlev;
1871.     winid tmpwin = create_nhwindow(NHW_MENU);
1872.     anything any;
1873.     int clr = NO_COLOR;
1874. 
1875.     any = cg.zeroany; /* set all bits to zero */
1876.     start_menu(tmpwin, MENU_BEHAVE_STANDARD);
1877.     /* use index+1 (can't use 0) as identifier */
1878.     for (i = num_ok_dungeons = 0; i < svn.n_dgns; i++) {
1879.         if (!svd.dungeons[i].dunlev_ureached)
1880.             continue;
1881.         if (i == tutorial_dnum) /* can't portal into tutorial */
1882.             continue;
1883.         any.a_int = i + 1;
1884.         add_menu(tmpwin, &nul_glyphinfo, &any, 0, 0,
1885.                  ATR_NONE, clr,
1886.                  svd.dungeons[i].dname, MENU_ITEMFLAGS_NONE);
1887.         num_ok_dungeons++;
1888.         last_ok_dungeon = i;
1889.     }
1890.     end_menu(tmpwin, "Open a portal to which dungeon?");
1891.     if (num_ok_dungeons > 1) {
1892.         /* more than one entry; display menu for choices */
1893.         menu_item *selected;
1894.         int n;
1895. 
1896.         n = select_menu(tmpwin, PICK_ONE, &selected);
1897.         if (n <= 0) {
1898.             destroy_nhwindow(tmpwin);
1899.             nothing_special(obj);
1900.             return ECMD_TIME;
1901.         }
1902.         i = selected[0].item.a_int - 1;
1903.         free((genericptr_t) selected);
1904.     } else
1905.         i = last_ok_dungeon; /* also first & only OK dungeon */
1906.     destroy_nhwindow(tmpwin);
1907. 
1908.     /*
1909.      * i is now index into dungeon structure for the new dungeon.
1910.      * Find the closest level in the given dungeon, open
1911.      * a use-once portal to that dungeon and go there.
1912.      * The closest level is either the entry or dunlev_ureached.
1913.      */
1914.     newlev.dnum = i;
1915.     if (svd.dungeons[i].depth_start >= depth(&u.uz))
1916.         newlev.dlevel = svd.dungeons[i].entry_lev;
1917.     else
1918.         newlev.dlevel = svd.dungeons[i].dunlev_ureached;
1919. 
1920.     if (u.uhave.amulet || In_endgame(&u.uz) || In_endgame(&newlev)
1921.         || newlev.dnum == u.uz.dnum || !next_to_u()) {
1922.         You_feel("very disoriented for a moment.");
1923.     } else {
1924.         if (!Blind)
1925.             You("are surrounded by a shimmering sphere!");
1926.         else
1927.             You_feel("weightless for a moment.");
1928.         goto_level(&newlev, FALSE, FALSE, FALSE);
1929.     }
1930.     return ECMD_TIME;
1931. }
1932. 
1933. staticfn int
1934. invoke_create_ammo(struct obj *obj)
1935. {
1936.     struct obj *otmp = mksobj(ARROW, TRUE, FALSE);
1937. 
1938.     if (!otmp) {
1939.         nothing_special(obj);
1940.         return ECMD_TIME;
1941.     }
1942.     otmp->blessed = obj->blessed;
1943.     otmp->cursed = obj->cursed;
1944.     otmp->bknown = obj->bknown;
1945.     otmp->oeroded = otmp->oeroded2 = 0;
1946.     if (obj->blessed) {
1947.         if (otmp->spe < 0)
1948.             otmp->spe = 0;
1949.         otmp->quan += rnd(10);
1950.     } else if (obj->cursed) {
1951.         if (otmp->spe > 0)
1952.             otmp->spe = 0;
1953.     } else
1954.         otmp->quan += rnd(5);
1955.     otmp->owt = weight(otmp);
1956.     otmp = hold_another_object(otmp, "Suddenly %s out.",
1957.                                aobjnam(otmp, "fall"), (char *) 0);
1958.     nhUse(otmp);
1959.     return ECMD_TIME;
1960. }
1961. 
1962. staticfn int
1963. invoke_banish(struct obj *obj UNUSED)
1964. {
1965.     int nvanished = 0, nstayed = 0;
1966.     struct monst *mtmp, *mtmp2;
1967.     d_level dest;
1968. 
1969.     find_hell(&dest);
1970. 
1971.     for (mtmp = fmon; mtmp; mtmp = mtmp2) {
1972.         int chance = 1;
1973. 
1974.         mtmp2 = mtmp->nmon;
1975.         if (DEADMONSTER(mtmp) || !isok(mtmp->mx, mtmp->my))
1976.             continue;
1977.         if (!is_demon(mtmp->data) && mtmp->data->mlet != S_IMP)
1978.             continue;
1979.         if (!couldsee(mtmp->mx, mtmp->my))
1980.             continue;
1981.         if (mtmp->data->msound == MS_NEMESIS)
1982.             continue;
1983. 
1984.         if (In_quest(&u.uz) && !svq.quest_status.killed_nemesis)
1985.             chance += 10;
1986.         if (is_dprince(mtmp->data))
1987.             chance += 2;
1988.         if (is_dlord(mtmp->data))
1989.             chance++;
1990. 
1991.         mtmp->msleeping = mtmp->mtame = mtmp->mpeaceful = 0;
1992.         if (chance <= 1 || !rn2(chance)) {
1993.             if (!Inhell) {
1994.                 nvanished++;
1995.                 /* banish to a random level in Gehennom */
1996.                 dest.dlevel = rn2(dunlevs_in_dungeon(&dest));
1997.                 migrate_mon(mtmp, ledger_no(&dest), MIGR_RANDOM);
1998.             } else {
1999.                 u_teleport_mon(mtmp, FALSE);
2000.             }
2001.         } else {
2002.             nstayed++;
2003.         }
2004.     }
2005. 
2006.     if (nvanished) {
2007.         char subject[] = "demons";
2008. 
2009.         if (nvanished == 1)
2010.             *(eos(subject) - 1) = '\0'; /* remove 's' */
2011.         pline("%s %s %s in a cloud of brimstone!",
2012.               nstayed ? ((nvanished > nstayed)
2013.                          ? "Most of the"
2014.                          : "Some of the")
2015.               : "The",
2016.               subject, vtense(subject, "disappear"));
2017.     }
2018.     return ECMD_TIME;
2019. }
2020. 
2021. staticfn int
2022. invoke_fling_poison(struct obj *obj)
2023. {
2024.     if (getdir((char *) 0)) {
2025.         int venom = rn2(2) ? BLINDING_VENOM : ACID_VENOM;
2026.         struct obj *otmp = mksobj(venom, TRUE, FALSE);
2027. 
2028.         otmp->spe = 1; /* the poison is yours */
2029.         throwit(otmp, 0L, FALSE, (struct obj *) 0);
2030.     } else {
2031.         /* no direction picked */
2032.         pline("%s", Never_mind);
2033.         obj->age = svm.moves;
2034.         return ECMD_CANCEL;
2035.     }
2036.     return ECMD_TIME;
2037. }
2038. 
2039. staticfn int
2040. invoke_storm_spell(struct obj *obj)
2041. {
2042.     const struct artifact *oart = get_artifact(obj);
2043.     int storm = oart->inv_prop == SNOWSTORM ? SPE_CONE_OF_COLD : SPE_FIREBALL;
2044.     int skill = spell_skilltype(storm);
2045.     int expertise = P_SKILL(skill);
2046. 
2047.     P_SKILL(skill) = P_EXPERT;
2048.     (void) spelleffects(storm, FALSE, TRUE);
2049.     P_SKILL(skill) = expertise;
2050.     return ECMD_TIME;
2051. }
2052. 
2053. staticfn int
2054. invoke_blinding_ray(struct obj *obj)
2055. {
2056.     if (getdir((char *) 0)) {
2057.         if (u.dx || u.dy) {
2058.             do_blinding_ray(obj);
2059.         } else if (u.dz) {
2060.             /* up or down => light this map spot; litroom() uses
2061.                radius 0 for Sunsword, except on Rogue level where
2062.                whole room gets lit and corridor spots remain unlit */
2063.             litroom(TRUE, obj);
2064.             pline("%s", ((!Blind && levl[u.ux][u.uy].lit
2065.                           && !levl[u.ux][u.uy].waslit)
2066.                          ? "It is lit here now."
2067.                          : nothing_seems_to_happen));
2068.         } else { /* zapyourself() */
2069.             boolean vulnerable = (u.umonnum == PM_GREMLIN);
2070.             int damg = obj->blessed ? 15 : !obj->cursed ? 10 : 5;
2071. 
2072.             if (vulnerable) /* could be fatal if Unchanging */
2073.                 (void) lightdamage(obj, TRUE, 2 * damg);
2074. 
2075.             if (!flashburn((long) (damg + rnd(damg)), FALSE)
2076.                 && !vulnerable)
2077.                 pline("%s", nothing_seems_to_happen);
2078.         }
2079.     } else {
2080.         /* no direction picked */
2081.         pline("%s", Never_mind);
2082.         obj->age = svm.moves;
2083.         return ECMD_CANCEL;
2084.     }
2085.     return ECMD_TIME;
2086. }
2087. 
2088. /* return the amount of Pw invoking an object costs.
2089.    return a negative value, if obj invoking cannot be paid with Pw */
2090. staticfn int
2091. arti_invoke_cost_pw(struct obj *obj)
2092. {
2093.     const struct artifact *oart = get_artifact(obj);
2094. 
2095.     if (oart->inv_prop == FLING_POISON
2096.         || oart->inv_prop == BLINDING_RAY) {
2097.         /* pretend it's a level 5 spell */
2098.         return SPELL_LEV_PW(5);
2099.     }
2100. 
2101.     return -1;
2102. }
2103. 
2104. /* return TRUE if artifact object's invoke cost can be paid (and pay it) */
2105. staticfn boolean
2106. arti_invoke_cost(struct obj *obj)
2107. {
2108.     if (obj->age > svm.moves) {
2109.         int pw_cost = arti_invoke_cost_pw(obj);
2110. 
2111.         if (pw_cost < 0 || u.uen < pw_cost) {
2112.             /* the artifact is tired :-) */
2113.             You_feel("that %s %s ignoring you.", the(xname(obj)),
2114.                      otense(obj, "are"));
2115.             /* and just got more so; patience is essential... */
2116.             obj->age += (long) d(3, 10);
2117.             return FALSE;
2118.         } else {
2119.             /* you pay invoke cost with your own magic */
2120.             You_feel("drained...");
2121.             u.uen -= pw_cost;
2122.             disp.botl = TRUE;
2123.         }
2124.     } else {
2125.         obj->age = svm.moves + rnz(100);
2126.     }
2127.     return TRUE;
2128. }
2129. 
2130. staticfn int
2131. arti_invoke(struct obj *obj)
2132. {
2133.     const struct artifact *oart;
2134.     int res = ECMD_OK;
2135. 
2136.     if (!obj) {
2137.         impossible("arti_invoke without obj");
2138.         return ECMD_OK;
2139.     }
2140.     oart = get_artifact(obj);
2141.     if (oart == &artilist[ART_NONARTIFACT] || !oart->inv_prop) {
2142.         if (obj->otyp == CRYSTAL_BALL)
2143.             use_crystal_ball(&obj);
2144.         else
2145.             pline1(nothing_happens);
2146.         return ECMD_TIME;
2147.     }
2148. 
2149.     /* It's a special power, not "just" a property */
2150.     if (oart->inv_prop > LAST_PROP) {
2151.         if (!arti_invoke_cost(obj))
2152.             return ECMD_TIME;
2153. 
2154.         switch (oart->inv_prop) {
2155.         case TAMING: res = invoke_taming(obj); break;
2156.         case HEALING: res = invoke_healing(obj); break;
2157.         case ENERGY_BOOST: res = invoke_energy_boost(obj); break;
2158.         case UNTRAP: res = invoke_untrap(obj); break;
2159.         case CHARGE_OBJ: res = invoke_charge_obj(obj); break;
2160.         case LEV_TELE: level_tele(); res = ECMD_TIME; break;
2161.         case CREATE_PORTAL: res = invoke_create_portal(obj); break;
2162.         case ENLIGHTENING:
2163.             enlightenment(MAGICENLIGHTENMENT, ENL_GAMEINPROGRESS);
2164.             res = ECMD_TIME;
2165.             break;
2166.         case CREATE_AMMO: res = invoke_create_ammo(obj); break;
2167.         case BANISH: res = invoke_banish(obj); break;
2168.         case FLING_POISON: res = invoke_fling_poison(obj); break;
2169.         case SNOWSTORM:
2170.             /*FALLTHRU*/
2171.         case FIRESTORM: res = invoke_storm_spell(obj); break;
2172.         case BLINDING_RAY: res = invoke_blinding_ray(obj); break;
2173.         default:
2174.             impossible("Unknown invoke power %d.", oart->inv_prop);
2175.             break;
2176.         }
2177.         return res;
2178.     } else {
2179.         long eprop = (u.uprops[oart->inv_prop].extrinsic ^= W_ARTI),
2180.              iprop = u.uprops[oart->inv_prop].intrinsic;
2181.         boolean on = (eprop & W_ARTI) != 0; /* true if prop just set */
2182. 
2183.         if (on && obj->age > svm.moves) {
2184.             /* the artifact is tired :-) */
2185.             u.uprops[oart->inv_prop].extrinsic ^= W_ARTI;
2186.             You_feel("that %s %s ignoring you.", the(xname(obj)),
2187.                      otense(obj, "are"));
2188.             /* can't just keep repeatedly trying */
2189.             obj->age += (long) d(3, 10);
2190.             return ECMD_TIME;
2191.         } else if (!on) {
2192.             /* when turning off property, determine downtime */
2193.             /* arbitrary for now until we can tune this -dlc */
2194.             obj->age = svm.moves + rnz(100);
2195.         }
2196. 
2197.         if ((eprop & ~W_ARTI) || iprop) {
2198.             /* you had the property from some other source too */
2199.             nothing_special(obj);
2200.             return ECMD_TIME;
2201.         }
2202.         switch (oart->inv_prop) {
2203.         case CONFLICT:
2204.             if (on)
2205.                 You_feel("like a rabble-rouser.");
2206.             else
2207.                 You_feel("the tension decrease around you.");
2208.             break;
2209.         case LEVITATION:
2210.             if (on) {
2211.                 float_up();
2212.                 spoteffects(FALSE);
2213.             } else
2214.                 (void) float_down(I_SPECIAL | TIMEOUT, W_ARTI);
2215.             break;
2216.         case INVIS:
2217.             if (BInvis || Blind) {
2218.                 nothing_special(obj);
2219.                 return ECMD_TIME;
2220.             }
2221.             newsym(u.ux, u.uy);
2222.             if (on)
2223.                 Your("body takes on a %s transparency...",
2224.                      Hallucination ? "normal" : "strange");
2225.             else
2226.                 Your("body seems to unfade...");
2227.             break;
2228.         }
2229.     }
2230. 
2231.     return ECMD_TIME;
2232. }
2233. 
2234. /* will freeing this object from inventory cause levitation to end? */
2235. boolean
2236. finesse_ahriman(struct obj *obj)
2237. {
2238.     const struct artifact *oart;
2239.     struct prop save_Lev;
2240.     boolean result;
2241. 
2242.     /* if we aren't levitating or this isn't an artifact which confers
2243.        levitation via #invoke then freeinv() won't toggle levitation */
2244.     if (!Levitation
2245.         || (oart = get_artifact(obj)) == &artilist[ART_NONARTIFACT]
2246.         || oart->inv_prop != LEVITATION || !(ELevitation & W_ARTI))
2247.         return FALSE;
2248. 
2249.     /* arti_invoke(off) -> float_down() clears I_SPECIAL|TIMEOUT & W_ARTI;
2250.        probe ahead to see whether that actually results in floating down;
2251.        (this assumes that there aren't two simultaneously invoked artifacts
2252.        both conferring levitation--safe, since if there were two of them,
2253.        invoking the 2nd would negate the 1st rather than stack with it) */
2254.     save_Lev = u.uprops[LEVITATION];
2255.     HLevitation &= ~(I_SPECIAL | TIMEOUT);
2256.     ELevitation &= ~W_ARTI;
2257.     result = (boolean) !Levitation;
2258.     u.uprops[LEVITATION] = save_Lev;
2259.     return result;
2260. }
2261. 
2262. /* WAC return TRUE if artifact is always lit */
2263. boolean
2264. artifact_light(struct obj *obj)
2265. {
2266.     /* not artifacts but treat them as if they were because they emit
2267.        light without burning */
2268.     if (obj && (obj->otyp == GOLD_DRAGON_SCALE_MAIL
2269.                 || obj->otyp == GOLD_DRAGON_SCALES)
2270.         && (obj->owornmask & W_ARM) != 0L)
2271.         return TRUE;
2272. 
2273.     return (boolean) ((get_artifact(obj) != &artilist[ART_NONARTIFACT])
2274.                       && is_art(obj, ART_SUNSWORD));
2275. }
2276. 
2277. /* KMH -- Talking artifacts are finally implemented */
2278. int
2279. arti_speak(struct obj *obj)
2280. {
2281.     const struct artifact *oart = get_artifact(obj);
2282.     const char *line;
2283.     char buf[BUFSZ];
2284. 
2285.     /* Is this a speaking artifact? */
2286.     if (oart == &artilist[ART_NONARTIFACT] || !(oart->spfx & SPFX_SPEAK))
2287.         return ECMD_OK; /* nothing happened */
2288. 
2289.     line = getrumor(bcsign(obj), buf, TRUE);
2290.     if (!*line)
2291.         line = "NetHack rumors file closed for renovation.";
2292.     pline("%s:", Tobjnam(obj, "whisper"));
2293.     SetVoice((struct monst *) 0, 0, 80, voice_talking_artifact);
2294.     verbalize1(line);
2295.     return ECMD_TIME;
2296. }
2297. 
2298. boolean
2299. artifact_has_invprop(struct obj *otmp, uchar inv_prop)
2300. {
2301.     const struct artifact *arti = get_artifact(otmp);
2302. 
2303.     return (boolean) ((arti != &artilist[ART_NONARTIFACT])
2304.                       && (arti->inv_prop == inv_prop));
2305. }
2306. 
2307. /* Return the price sold to the hero of a given artifact or unique item */
2308. long
2309. arti_cost(struct obj *otmp)
2310. {
2311.     if (!otmp->oartifact)
2312.         return (long) objects[otmp->otyp].oc_cost;
2313.     else if (artilist[(int) otmp->oartifact].cost)
2314.         return artilist[(int) otmp->oartifact].cost;
2315.     else
2316.         return (100L * (long) objects[otmp->otyp].oc_cost);
2317. }
2318. 
2319. staticfn uchar
2320. abil_to_adtyp(long *abil)
2321. {
2322.     struct abil2adtyp_tag {
2323.         long *abil;
2324.         uchar adtyp;
2325.     } abil2adtyp[] = {
2326.         { &EFire_resistance, AD_FIRE },
2327.         { &ECold_resistance, AD_COLD },
2328.         { &EShock_resistance, AD_ELEC },
2329.         { &EAntimagic, AD_MAGM },
2330.         { &EDisint_resistance, AD_DISN },
2331.         { &EPoison_resistance, AD_DRST },
2332.         { &EDrain_resistance, AD_DRLI },
2333.     };
2334.     int k;
2335. 
2336.     for (k = 0; k < SIZE(abil2adtyp); k++) {
2337.         if (abil2adtyp[k].abil == abil)
2338.             return abil2adtyp[k].adtyp;
2339.     }
2340.     return 0;
2341. }
2342. 
2343. staticfn unsigned long
2344. abil_to_spfx(long *abil)
2345. {
2346.     static const struct abil2spfx_tag {
2347.         long *abil;
2348.         unsigned long spfx;
2349.     } abil2spfx[] = {
2350.         { &ESearching, SPFX_SEARCH },
2351.         { &EHalluc_resistance, SPFX_HALRES },
2352.         { &ETelepat, SPFX_ESP },
2353.         { &EStealth, SPFX_STLTH },
2354.         { &ERegeneration, SPFX_REGEN },
2355.         { &ETeleport_control, SPFX_TCTRL },
2356.         { &EWarn_of_mon, SPFX_WARN },
2357.         { &EWarning, SPFX_WARN },
2358.         { &EEnergy_regeneration, SPFX_EREGEN },
2359.         { &EHalf_spell_damage, SPFX_HSPDAM },
2360.         { &EHalf_physical_damage, SPFX_HPHDAM },
2361.         { &EReflecting, SPFX_REFLECT },
2362.     };
2363.     int k;
2364. 
2365.     for (k = 0; k < SIZE(abil2spfx); k++) {
2366.         if (abil2spfx[k].abil == abil)
2367.             return abil2spfx[k].spfx;
2368.     }
2369.     return 0L;
2370. }
2371. 
2372. /*
2373.  * Return the first item that is conveying a particular intrinsic.
2374.  */
2375. struct obj *
2376. what_gives(long *abil)
2377. {
2378.     struct obj *obj;
2379.     uchar dtyp;
2380.     unsigned long spfx;
2381.     long wornbits;
2382.     long wornmask = (W_ARM | W_ARMC | W_ARMH | W_ARMS
2383.                      | W_ARMG | W_ARMF | W_ARMU
2384.                      | W_AMUL | W_RINGL | W_RINGR | W_TOOL
2385.                      | W_ART | W_ARTI);
2386. 
2387.     if (u.twoweap)
2388.         wornmask |= W_SWAPWEP;
2389.     dtyp = abil_to_adtyp(abil);
2390.     spfx = abil_to_spfx(abil);
2391.     wornbits = (wornmask & *abil);
2392. 
2393.     for (obj = gi.invent; obj; obj = obj->nobj) {
2394.         if (obj->oartifact
2395.             && (abil != &EWarn_of_mon || svc.context.warntype.obj)) {
2396.             const struct artifact *art = get_artifact(obj);
2397. 
2398.             if (art != &artilist[ART_NONARTIFACT]) {
2399.                 if (dtyp) {
2400.                     if (art->cary.adtyp == dtyp /* carried */
2401.                         || (art->defn.adtyp == dtyp /* defends while worn */
2402.                             && (obj->owornmask & ~(W_ART | W_ARTI))))
2403.                         return obj;
2404.                 }
2405.                 if (spfx) {
2406.                     /* property conferred when carried */
2407.                     if ((art->cspfx & spfx) == spfx)
2408.                         return obj;
2409.                     /* property conferred when wielded or worn */
2410.                     if ((art->spfx & spfx) == spfx && obj->owornmask)
2411.                         return obj;
2412.                 }
2413.                 if (obj == uwep && abil == &EBlnd_resist
2414.                     && (*abil & W_WEP) != 0L) {
2415.                     return obj; /* Sunsword */
2416.                 }
2417.             }
2418.         } else {
2419.             if (wornbits && wornbits == (wornmask & obj->owornmask))
2420.                 return obj;
2421.         }
2422.     }
2423.     return (struct obj *) 0;
2424. }
2425. 
2426. const char *
2427. glow_color(int arti_indx)
2428. {
2429.     int colornum = artilist[arti_indx].acolor;
2430.     const char *colorstr = clr2colorname(colornum);
2431. 
2432.     return hcolor(colorstr);
2433. }
2434. 
2435. /* glow verb; [0] holds the value used when blind */
2436. static const char *const glow_verbs[] = {
2437.     "quiver", "flicker", "glimmer", "gleam"
2438. };
2439. 
2440. /* relative strength that Sting is glowing (0..3), to select verb */
2441. staticfn int
2442. glow_strength(int count)
2443. {
2444.     /* glow strength should also be proportional to proximity and
2445.        probably difficulty, but we don't have that information and
2446.        gathering it is more trouble than this would be worth */
2447.     return (count > 12) ? 3 : (count > 4) ? 2 : (count > 0);
2448. }
2449. 
2450. const char *
2451. glow_verb(int count, /* 0 means blind rather than no applicable creatures */
2452.           boolean ingsfx)
2453. {
2454.     static char resbuf[20];
2455. 
2456.     Strcpy(resbuf, glow_verbs[glow_strength(count)]);
2457.     /* ing_suffix() will double the last consonant for all the words
2458.        we're using and none of them should have that, so bypass it */
2459.     if (ingsfx)
2460.         Strcat(resbuf, "ing");
2461.     return resbuf;
2462. }
2463. 
2464. /* use for warning "glow" for Sting, Orcrist, and Grimtooth */
2465. void
2466. Sting_effects(
2467.     int orc_count) /* new count (warn_obj_cnt is old count);
2468.                     * -1 is a flag value */
2469. {
2470.     if (u_wield_art(ART_STING)
2471.         || u_wield_art(ART_ORCRIST)
2472.         || u_wield_art(ART_GRIMTOOTH)) {
2473.         int oldstr = glow_strength(gw.warn_obj_cnt),
2474.             newstr = glow_strength(orc_count);
2475. 
2476.         if (orc_count == -1 && gw.warn_obj_cnt > 0) {
2477.             /* -1 means that blindness has just been toggled; give a
2478.                'continue' message that eventual 'stop' message will match */
2479.             pline("%s is %s.", bare_artifactname(uwep),
2480.                   glow_verb(Blind ? 0 : gw.warn_obj_cnt, TRUE));
2481.         } else if (newstr > 0 && newstr != oldstr) {
2482.             /* goto_level() -> docrt() -> see_monsters() -> Sting_effects();
2483.                if "you materialize on a different level" is pending, give
2484.                it now so that start-glowing message comes after it */
2485.             maybe_lvltport_feedback(); /* usually called by goto_level() */
2486. 
2487.             /* 'start' message */
2488.             if (!Blind)
2489.                 pline("%s %s %s%c", bare_artifactname(uwep),
2490.                       otense(uwep, glow_verb(orc_count, FALSE)),
2491.                       glow_color(uwep->oartifact),
2492.                       (newstr > oldstr) ? '!' : '.');
2493.             else if (oldstr == 0) /* quivers */
2494.                 pline("%s %s slightly.", bare_artifactname(uwep),
2495.                       otense(uwep, glow_verb(0, FALSE)));
2496.         } else if (orc_count == 0 && gw.warn_obj_cnt > 0) {
2497.             /* 'stop' message */
2498.             pline("%s stops %s.", bare_artifactname(uwep),
2499.                   glow_verb(Blind ? 0 : gw.warn_obj_cnt, TRUE));
2500.         }
2501.     }
2502. }
2503. 
2504. /* called when hero is wielding/applying/invoking a carried item, or
2505.    after undergoing a transformation (alignment change, lycanthropy,
2506.    polymorph) which might affect item access */
2507. int
2508. retouch_object(
2509.     struct obj **objp, /* might be destroyed or unintentionally dropped */
2510.     boolean loseit)    /* whether to drop it if hero can longer touch it */
2511. {
2512.     struct obj *obj = *objp;
2513. 
2514.     /* allow hero in silver-hating form to try to perform invocation ritual */
2515.     if (obj->otyp == BELL_OF_OPENING
2516.         && invocation_pos(u.ux, u.uy) && !On_stairs(u.ux, u.uy)) {
2517.         return 1;
2518.     }
2519. 
2520.     if (touch_artifact(obj, &gy.youmonst)) {
2521.         char buf[BUFSZ];
2522.         int dmg = 0, tmp;
2523.         boolean ag = (objects[obj->otyp].oc_material == SILVER && Hate_silver),
2524.                 bane = bane_applies(get_artifact(obj), &gy.youmonst);
2525. 
2526.         /* nothing else to do if hero can successfully handle this object */
2527.         if (!ag && !bane)
2528.             return 1;
2529. 
2530.         /* hero can't handle this object, but didn't get touch_artifact()'s
2531.            "<obj> evades your grasp|control" message; give an alternate one */
2532.         You_cant("handle %s%s!", yname(obj),
2533.                  obj->owornmask ? " anymore" : "");
2534.         /* also inflict damage unless touch_artifact() already did so */
2535.         if (!touch_blasted) {
2536.             const char *what = killer_xname(obj);
2537. 
2538.             if (ag && !obj->oartifact && !bane) {
2539.                 /* 'obj' is silver; for rings and wands it ended up that
2540.                    way due to randomization at start of game; showing this
2541.                    game's silver item without stating that it is silver
2542.                    potentially leads to confusion about cause of death */
2543.                 if (obj->oclass == RING_CLASS)
2544.                     what = "a silver ring";
2545.                 else if (obj->oclass == WAND_CLASS)
2546.                     what = "a silver wand";
2547.                 /* for anything else, stick with killer_xname() */
2548.             }
2549.             /* damage is somewhat arbitrary; half the usual 1d20 physical
2550.                for silver, 1d10 magical for <foo>bane, potentially both */
2551.             if (ag)
2552.                 tmp = rnd(10), dmg += Maybe_Half_Phys(tmp);
2553.             if (bane)
2554.                 dmg += rnd(10);
2555.             Sprintf(buf, "handling %s", what);
2556.             losehp(dmg, buf, KILLED_BY);
2557.             exercise(A_CON, FALSE);
2558.         }
2559.     }
2560. 
2561.     /* removing a worn item might result in loss of levitation,
2562.        dropping the hero onto a polymorph trap or into water or
2563.        lava and potentially dropping or destroying the item */
2564.     if (obj->owornmask) {
2565.         struct obj *otmp;
2566. 
2567.         remove_worn_item(obj, FALSE);
2568.         for (otmp = gi.invent; otmp; otmp = otmp->nobj)
2569.             if (otmp == obj)
2570.                 break;
2571.         if (!otmp)
2572.             *objp = obj = 0;
2573.     }
2574. 
2575.     /* if we still have it and caller wants us to drop it, do so now */
2576.     if (loseit && obj) {
2577.         if (Levitation) {
2578.             freeinv(obj);
2579.             hitfloor(obj, TRUE);
2580.         } else {
2581.             /* dropx gives a message if a dropped item lands on an altar;
2582.                we provide one for other terrain */
2583.             if (!IS_ALTAR(levl[u.ux][u.uy].typ))
2584.                 pline("%s to the %s.", Tobjnam(obj, "fall"),
2585.                       surface(u.ux, u.uy));
2586.             dropx(obj);
2587.         }
2588.         *objp = obj = 0; /* no longer in inventory */
2589.     }
2590.     return 0;
2591. }
2592. 
2593. /* hero has changed form or alignment; an item which is worn/wielded
2594.    or an artifact which conveys something via being carried or which
2595.    has an #invoke effect currently in operation undergoes a touch test;
2596.    if it fails, it will be unworn/unwielded and maybe dropped */
2597. staticfn boolean
2598. untouchable(
2599.     struct obj *obj, /* object to test; in invent or is steed's saddle */
2600.     boolean drop_untouchable) /* whether to drop it if it can't be touched */
2601. {
2602.     struct artifact *art;
2603.     boolean beingworn, carryeffect, invoked;
2604.     long wearmask = ~(W_QUIVER | (u.twoweap ? 0L : W_SWAPWEP) | W_BALL);
2605. 
2606.     beingworn = (obj /* never Null; this pacifies static analysis when
2607.                       * the get_artifact() macro tests 'obj' for Null */
2608.                  && ((obj->owornmask & wearmask) != 0L
2609.                      /* some items in use don't have any wornmask setting */
2610.                      || (obj->oclass == TOOL_CLASS
2611.                          && (obj->lamplit
2612.                              || (obj->otyp == LEASH && obj->leashmon)
2613.                              || (Is_container(obj) && Has_contents(obj))))));
2614. 
2615.     if ((art = get_artifact(obj)) != &artilist[ART_NONARTIFACT]) {
2616.         carryeffect = (art->cary.adtyp || art->cspfx);
2617.         invoked = (art->inv_prop > 0 && art->inv_prop <= LAST_PROP
2618.                    && (u.uprops[art->inv_prop].extrinsic & W_ARTI) != 0L);
2619.     } else {
2620.         carryeffect = invoked = FALSE;
2621.     }
2622. 
2623.     if (beingworn || carryeffect || invoked) {
2624.         if (!retouch_object(&obj, drop_untouchable)) {
2625.             /* "<artifact> is beyond your control" or "you can't handle
2626.                <object>" has been given and it is now unworn/unwielded
2627.                and possibly dropped (depending upon caller); if dropped,
2628.                carried effect was turned off, else we leave that alone;
2629.                we turn off invocation property here if still carried */
2630.             if (invoked && obj)
2631.                 (void) arti_invoke(obj); /* reverse #invoke */
2632.             return TRUE;
2633.         }
2634.     }
2635.     return FALSE;
2636. }
2637. 
2638. /* check all items currently in use (mostly worn) for touchability */
2639. void
2640. retouch_equipment(
2641.     int dropflag) /* 0==don't drop, 1==drop all, 2==drop weapon */
2642. {
2643.     static int nesting = 0; /* recursion control */
2644.     struct obj *obj;
2645.     boolean dropit, had_gloves = (uarmg != 0);
2646.     int had_rings = (!!uleft + !!uright);
2647. 
2648.     /*
2649.      * We can potentially be called recursively if losing/unwearing
2650.      * an item causes worn helm of opposite alignment to come off or
2651.      * be destroyed.
2652.      *
2653.      * BUG: if the initial call was due to putting on a helm of
2654.      * opposite alignment and it does come off to trigger recursion,
2655.      * after the inner call executes, the outer call will finish
2656.      * using the non-helm alignment rather than the helm alignment
2657.      * which triggered this in the first place.
2658.      */
2659.     if (!nesting++)
2660.         clear_bypasses(); /* init upon initial entry */
2661. 
2662.     dropit = (dropflag > 0); /* drop all or drop weapon */
2663.     /* check secondary weapon first, before possibly unwielding primary */
2664.     if (u.twoweap) {
2665.         bypass_obj(uswapwep); /* so loop below won't process it again */
2666.         (void) untouchable(uswapwep, dropit);
2667.     }
2668.     /* check primary weapon next so that they're handled together */
2669.     if (uwep) {
2670.         bypass_obj(uwep); /* so loop below won't process it again */
2671.         (void) untouchable(uwep, dropit);
2672.     }
2673. 
2674.     /* in case someone is daft enough to add artifact or silver saddle */
2675.     if (u.usteed && (obj = which_armor(u.usteed, W_SADDLE)) != 0) {
2676.         /* untouchable() calls retouch_object() which expects an object in
2677.            hero's inventory, but remove_worn_item() will be harmless for
2678.            saddle and we're suppressing drop, so this works as intended */
2679.         if (untouchable(obj, FALSE))
2680.             dismount_steed(DISMOUNT_THROWN);
2681.     }
2682.     /*
2683.      * TODO?  Force off gloves if either or both rings are going to
2684.      * become unworn; force off cloak [suit] before suit [shirt].
2685.      * The torso handling is hypothetical; the case for gloves is
2686.      * not, due to the possibility of unwearing silver rings.
2687.      */
2688. 
2689.     dropit = (dropflag == 1); /* all untouchable items */
2690.     /* loss of levitation (silver ring, or Heart of Ahriman invocation)
2691.        might cause hero to lose inventory items (by dropping into lava,
2692.        for instance), so inventory traversal needs to rescan the whole
2693.        gi.invent chain each time it moves on to another object; we use bypass
2694.        handling to keep track of which items have already been processed */
2695.     while ((obj = nxt_unbypassed_obj(gi.invent)) != 0)
2696.         (void) untouchable(obj, dropit);
2697. 
2698.     if (had_rings != (!!uleft + !!uright) && uarmg && uarmg->cursed)
2699.         uncurse(uarmg); /* temporary? hack for ring removal plausibility */
2700.     if (had_gloves && !uarmg)
2701.         selftouch("After losing your gloves, you");
2702. 
2703.     if (!--nesting)
2704.         clear_bypasses(); /* reset upon final exit */
2705. }
2706. 
2707. staticfn int
2708. count_surround_traps(coordxy x, coordxy y)
2709. {
2710.     struct rm *levp;
2711.     struct obj *o;
2712.     coordxy dx, dy;
2713.     int glyph, ret = 0;
2714. 
2715.     for (dx = x - 1; dx < x + 2; ++dx)
2716.         for (dy = y - 1; dy < y + 2; ++dy) {
2717.             if (!isok(dx, dy))
2718.                 continue;
2719.             /* If a trap is shown here, don't count it; the hero
2720.              * should be expecting it.  But if there is a trap here
2721.              * that's not shown, either undiscovered or covered by
2722.              * something, do count it.
2723.              */
2724.             glyph = glyph_at(dx, dy);
2725.             if (glyph_is_trap(glyph))
2726.                 continue;
2727.             if (t_at(dx, dy)) {
2728.                 ++ret;
2729.                 continue;
2730.             }
2731.             levp = &levl[dx][dy];
2732.             if (IS_DOOR(levp->typ) && (levp->doormask & D_TRAPPED) != 0) {
2733.                 ++ret;
2734.                 continue;
2735.             }
2736.             for (o = svl.level.objects[dx][dy]; o; o = o->nexthere)
2737.                 if (Is_container(o) && o->otrapped) {
2738.                     ++ret; /* we're counting locations, so just */
2739.                     break; /* count the first one in a pile     */
2740.                 }
2741.         }
2742.     /*
2743.      * [Shouldn't we also check inventory for a trapped container?
2744.      * Even if its trap has already been found, there's no 'tknown'
2745.      * flag to help hero remember that so we have nothing comparable
2746.      * to a shown glyph to justify skipping it.]
2747.      */
2748.     return ret;
2749. }
2750. 
2751. /* sense adjacent traps if wielding MKoT without wearing gloves */
2752. void
2753. mkot_trap_warn(void)
2754. {
2755.     static const char *const heat[7] = {
2756.         "cool", "slightly warm", "warm", "very warm",
2757.         "hot", "very hot", "like fire"
2758.     };
2759. 
2760.     if (!uarmg && u_wield_art(ART_MASTER_KEY_OF_THIEVERY)) {
2761.         int idx, ntraps = count_surround_traps(u.ux, u.uy);
2762. 
2763.         if (ntraps != gm.mkot_trap_warn_count) {
2764.             idx = min(ntraps, SIZE(heat) - 1);
2765.             pline_The("Key feels %s%c", heat[idx], (ntraps > 3) ? '!' : '.');
2766.         }
2767.         gm.mkot_trap_warn_count = ntraps;
2768.     } else
2769.         gm.mkot_trap_warn_count = 0;
2770. }
2771. 
2772. /* Master Key is magic key if its bless/curse state meets our criteria:
2773.    not cursed for rogues or blessed for non-rogues */
2774. boolean
2775. is_magic_key(struct monst *mon, /* if null, non-rogue is assumed */
2776.              struct obj *obj)
2777. {
2778.     if (is_art(obj, ART_MASTER_KEY_OF_THIEVERY)) {
2779.         if ((mon == &gy.youmonst) ? Role_if(PM_ROGUE)
2780.                                  : (mon && mon->data == &mons[PM_ROGUE]))
2781.             return !obj->cursed; /* a rogue; non-cursed suffices for magic */
2782.         /* not a rogue; key must be blessed to behave as a magic one */
2783.         return obj->blessed;
2784.     }
2785.     return FALSE;
2786. }
2787. 
2788. /* figure out whether 'mon' (usually youmonst) is carrying the magic key */
2789. struct obj *
2790. has_magic_key(struct monst *mon) /* if null, hero assumed */
2791. {
2792.     struct obj *o;
2793.     short key = artilist[ART_MASTER_KEY_OF_THIEVERY].otyp;
2794. 
2795.     if (!mon)
2796.         mon = &gy.youmonst;
2797.     for (o = ((mon == &gy.youmonst) ? gi.invent : mon->minvent); o;
2798.          o = nxtobj(o, key, FALSE)) {
2799.         if (is_magic_key(mon, o))
2800.             return o;
2801.     }
2802.     return (struct obj *) 0;
2803. }
2804. 
2805. /* #define is_art(o,art) ((o) && (o)->oartifact == (art)) */
2806. 
2807. boolean
2808. is_art(struct obj *obj, int art)
2809. {
2810.     if (obj && obj->oartifact == art)
2811.         return TRUE;
2812.     return FALSE;
2813. }
2814. 
2815. /* #define get_artifact(o) \
2816.     (((o) && ((o)->artifact > 0 && (o)->artifact < AFTER_LAST_ARTIFACT)) \
2817.                              ? &artilist[(int) (o)->oartifact] \
2818.                              : &artilist[ART_NONARTIFACT]) */
2819. 
2820. staticfn struct artifact *
2821. get_artifact(struct obj *obj)
2822. {
2823.     if (obj) {
2824.         int artidx = (int) obj->oartifact;
2825. 
2826.         /* skip 0, 1st artifact at 1 */
2827.         /* SIZE(artilist) would include the terminator,
2828.            so use AFTER_LAST_ARTIFACT instead */
2829.         if (artidx > 0 && artidx < AFTER_LAST_ARTIFACT)
2830.             return &artilist[artidx];
2831.     }
2832.     return &artilist[ART_NONARTIFACT];
2833. }
2834. 
2835. /* is object permanently poisoned? (currently only Grimtooth) */
2836. boolean
2837. permapoisoned(struct obj *obj)
2838. {
2839.     return (obj && is_art(obj, ART_GRIMTOOTH));
2840. }
2841. #endif /* SFCTOOL */
2842. 
2843. /*artifact.c*/