1 /**
2  * \file obj-util.c
3  * \brief Object utilities
4  *
5  * Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke
6  *
7  * This work is free software; you can redistribute it and/or modify it
8  * under the terms of either:
9  *
10  * a) the GNU General Public License as published by the Free Software
11  *    Foundation, version 2, or
12  *
13  * b) the "Angband licence":
14  *    This software may be copied and distributed for educational, research,
15  *    and not for profit purposes provided that this copyright and statement
16  *    are included in all such copies.  Other copyrights may also apply.
17  */
18 
19 #include "angband.h"
20 #include "cave.h"
21 #include "cmd-core.h"
22 #include "effects.h"
23 #include "game-input.h"
24 #include "game-world.h"
25 #include "generate.h"
26 #include "grafmode.h"
27 #include "init.h"
28 #include "mon-make.h"
29 #include "monster.h"
30 #include "obj-curse.h"
31 #include "obj-desc.h"
32 #include "obj-gear.h"
33 #include "obj-ignore.h"
34 #include "obj-knowledge.h"
35 #include "obj-make.h"
36 #include "obj-pile.h"
37 #include "obj-slays.h"
38 #include "obj-tval.h"
39 #include "obj-util.h"
40 #include "player-history.h"
41 #include "player-spell.h"
42 #include "player-util.h"
43 #include "randname.h"
44 #include "z-queue.h"
45 
46 struct object_base *kb_info;
47 struct object_kind *k_info;
48 struct artifact *a_info;
49 struct ego_item *e_info;
50 struct flavor *flavors;
51 
52 /**
53  * Hold the titles of scrolls, 6 to 14 characters each, plus quotes.
54  */
55 static char scroll_adj[MAX_TITLES][18];
56 
flavor_assign_fixed(void)57 static void flavor_assign_fixed(void)
58 {
59 	int i;
60 	struct flavor *f;
61 
62 	for (f = flavors; f; f = f->next) {
63 		if (f->sval == SV_UNKNOWN)
64 			continue;
65 
66 		for (i = 0; i < z_info->k_max; i++) {
67 			struct object_kind *k = &k_info[i];
68 			if (k->tval == f->tval && k->sval == f->sval)
69 				k->flavor = f;
70 		}
71 	}
72 }
73 
74 
flavor_assign_random(byte tval)75 static void flavor_assign_random(byte tval)
76 {
77 	int i;
78 	int flavor_count = 0;
79 	int choice;
80 	struct flavor *f;
81 
82 	/* Count the random flavors for the given tval */
83 	for (f = flavors; f; f = f->next)
84 		if (f->tval == tval && f->sval == SV_UNKNOWN)
85 			flavor_count++;
86 
87 	for (i = 0; i < z_info->k_max; i++) {
88 		if (k_info[i].tval != tval || k_info[i].flavor)
89 			continue;
90 
91 		if (!flavor_count)
92 			quit_fmt("Not enough flavors for tval %d.", tval);
93 
94 		choice = randint0(flavor_count);
95 
96 		for (f = flavors; f; f = f->next) {
97 			if (f->tval != tval || f->sval != SV_UNKNOWN)
98 				continue;
99 
100 			if (choice == 0) {
101 				k_info[i].flavor = f;
102 				f->sval = k_info[i].sval;
103 				if (tval == TV_SCROLL)
104 					f->text = scroll_adj[k_info[i].sval];
105 				flavor_count--;
106 				break;
107 			}
108 
109 			choice--;
110 		}
111 	}
112 }
113 
114 /**
115  * Reset svals on flavors, effectively removing any fixed flavors.
116  *
117  * Mainly useful for randarts so that fixed flavors for standards aren't
118  * predictable. The One Ring is kept as fixed, since it lives through randarts.
119  */
flavor_reset_fixed(void)120 void flavor_reset_fixed(void)
121 {
122 	struct flavor *f;
123 
124 	for (f = flavors; f; f = f->next) {
125 		if (f->tval == TV_RING && strstr(f->text, "Plain Gold"))
126 			continue;
127 
128 		f->sval = SV_UNKNOWN;
129 	}
130 }
131 
132 /**
133  * Prepare the "variable" part of the "k_info" array.
134  *
135  * The "color"/"metal"/"type" of an item is its "flavor".
136  * For the most part, flavors are assigned randomly each game.
137  *
138  * Initialize descriptions for the "colored" objects, including:
139  * Rings, Amulets, Staffs, Wands, Rods, Mushrooms, Potions, Scrolls.
140  *
141  * Scroll titles are always between 6 and 14 letters long.  This is
142  * ensured because every title is composed of whole words, where every
143  * word is from 2 to 8 letters long, and that no scroll is finished
144  * until it attempts to grow beyond 15 letters.  The first time this
145  * can happen is when the current title has 6 letters and the new word
146  * has 8 letters, which would result in a 6 letter scroll title.
147  *
148  * Hack -- make sure everything stays the same for each saved game
149  * This is accomplished by the use of a saved "random seed", as in
150  * "town_gen()".  Since no other functions are called while the special
151  * seed is in effect, so this function is pretty "safe".
152  */
flavor_init(void)153 void flavor_init(void)
154 {
155 	int i, j;
156 
157 	/* Hack -- Use the "simple" RNG */
158 	Rand_quick = true;
159 
160 	/* Hack -- Induce consistant flavors */
161 	Rand_value = seed_flavor;
162 
163 	/* Scrub all flavors and re-parse for new players */
164 	if (turn == 1) {
165 		struct flavor *f;
166 
167 		for (i = 0; i < z_info->k_max; i++) {
168 			k_info[i].flavor = NULL;
169 		}
170 		for (f = flavors; f; f = f->next) {
171 			f->sval = SV_UNKNOWN;
172 		}
173 		cleanup_parser(&flavor_parser);
174 		run_parser(&flavor_parser);
175 	}
176 
177 	if (OPT(player, birth_randarts))
178 		flavor_reset_fixed();
179 
180 	flavor_assign_fixed();
181 
182 	flavor_assign_random(TV_RING);
183 	flavor_assign_random(TV_AMULET);
184 	flavor_assign_random(TV_STAFF);
185 	flavor_assign_random(TV_WAND);
186 	flavor_assign_random(TV_ROD);
187 	flavor_assign_random(TV_MUSHROOM);
188 	flavor_assign_random(TV_POTION);
189 
190 	/* Scrolls (random titles, always white) */
191 	for (i = 0; i < MAX_TITLES; i++) {
192 		char buf[26];
193 		char *end = buf + 1;
194 		int titlelen = 0;
195 		int wordlen;
196 		bool okay = true;
197 
198 		my_strcpy(buf, "\"", 2);
199 		wordlen = randname_make(RANDNAME_SCROLL, 2, 8, end, 24, name_sections);
200 		while (titlelen + wordlen < (int)(sizeof(scroll_adj[0]) - 3)) {
201 			end[wordlen] = ' ';
202 			titlelen += wordlen + 1;
203 			end += wordlen + 1;
204 			wordlen = randname_make(RANDNAME_SCROLL, 2, 8, end, 24 - titlelen,
205 									name_sections);
206 		}
207 		buf[titlelen] = '"';
208 		buf[titlelen+1] = '\0';
209 
210 		/* Check the scroll name hasn't already been generated */
211 		for (j = 0; j < i; j++) {
212 			if (streq(buf, scroll_adj[j])) {
213 				okay = false;
214 				break;
215 			}
216 		}
217 
218 		if (okay)
219 			my_strcpy(scroll_adj[i], buf, sizeof(scroll_adj[0]));
220 		else
221 			/* Have another go at making a name */
222 			i--;
223 	}
224 	flavor_assign_random(TV_SCROLL);
225 
226 	/* Hack -- Use the "complex" RNG */
227 	Rand_quick = false;
228 
229 	/* Analyze every object */
230 	for (i = 0; i < z_info->k_max; i++) {
231 		struct object_kind *kind = &k_info[i];
232 
233 		/* Skip "empty" objects */
234 		if (!kind->name) continue;
235 
236 		/* No flavor yields aware */
237 		if (!kind->flavor) kind->aware = true;
238 	}
239 }
240 
241 /**
242  * Set all flavors as aware
243  */
flavor_set_all_aware(void)244 void flavor_set_all_aware(void)
245 {
246 	int i;
247 
248 	/* Analyze every object */
249 	for (i = 0; i < z_info->k_max; i++) {
250 		struct object_kind *kind = &k_info[i];
251 
252 		/* Skip empty objects */
253 		if (!kind->name) continue;
254 
255 		/* Flavor yields aware */
256 		if (kind->flavor) kind->aware = true;
257 	}
258 }
259 
260 /**
261  * Obtain the flags for an item
262  */
object_flags(const struct object * obj,bitflag flags[OF_SIZE])263 void object_flags(const struct object *obj, bitflag flags[OF_SIZE])
264 {
265 	of_wipe(flags);
266 	if (!obj) return;
267 	of_copy(flags, obj->flags);
268 }
269 
270 
271 /**
272  * Obtain the flags for an item which are known to the player
273  */
object_flags_known(const struct object * obj,bitflag flags[OF_SIZE])274 void object_flags_known(const struct object *obj, bitflag flags[OF_SIZE])
275 {
276 	object_flags(obj, flags);
277 	of_inter(flags, obj->known->flags);
278 
279 	if (!obj->kind) {
280 		return;
281 	}
282 
283 	if (object_flavor_is_aware(obj)) {
284 		of_union(flags, obj->kind->flags);
285 	}
286 
287 	if (obj->ego && easy_know(obj)) {
288 		of_union(flags, obj->ego->flags);
289 		of_diff(flags, obj->ego->flags_off);
290 	}
291 }
292 
293 /**
294  * Apply a tester function, skipping all non-objects and gold
295  */
object_test(item_tester tester,const struct object * obj)296 bool object_test(item_tester tester, const struct object *obj)
297 {
298 	/* Require object */
299 	if (!obj) return false;
300 
301 	/* Ignore gold */
302 	if (tval_is_money(obj)) return false;
303 
304 	/* Pass without a tester, or tail-call the tester if it exists */
305 	return !tester || tester(obj);
306 }
307 
308 
309 /**
310  * Return true if the item is unknown (has yet to be seen by the player).
311  */
is_unknown(const struct object * obj)312 bool is_unknown(const struct object *obj)
313 {
314 	struct grid_data gd = {
315 		.m_idx = 0,
316 		.f_idx = 0,
317 		.first_kind = NULL,
318 		.trap = NULL,
319 		.multiple_objects = false,
320 		.unseen_object = false,
321 		.unseen_money = false,
322 		.lighting = LIGHTING_LOS,
323 		.in_view = false,
324 		.is_player = false,
325 		.hallucinate = false,
326 	};
327 	map_info(obj->grid, &gd);
328 	return gd.unseen_object;
329 }
330 
331 
332 /**
333  * Looks if "inscrip" is present on the given object.
334  */
check_for_inscrip(const struct object * obj,const char * inscrip)335 unsigned check_for_inscrip(const struct object *obj, const char *inscrip)
336 {
337 	unsigned i = 0;
338 	const char *s;
339 
340 	if (!obj->note) return 0;
341 
342 	s = quark_str(obj->note);
343 
344 	/* Needing this implies there are bad instances of obj->note around,
345 	 * but I haven't been able to track down their origins - NRM */
346 	if (!s) return 0;
347 
348 	do {
349 		s = strstr(s, inscrip);
350 		if (!s) break;
351 
352 		i++;
353 		s++;
354 	} while (s);
355 
356 	return i;
357 }
358 
359 /**
360  * Looks if "inscrip" immediately followed by a decimal integer without a
361  * leading sign character is present on the given object.  Returns the number
362  * of times such an inscription occurs and, if that value is at least one,
363  * sets *ival to the value of the integer that followed the first such
364  * inscription.
365  */
check_for_inscrip_with_int(const struct object * obj,const char * inscrip,int * ival)366 unsigned check_for_inscrip_with_int(const struct object *obj, const char *inscrip, int* ival)
367 {
368 	unsigned i = 0;
369 	size_t inlen = strlen(inscrip);
370 	const char *s;
371 
372 	if (!obj->note) return 0;
373 
374 	s = quark_str(obj->note);
375 
376 	/* Needing this implies there are bad instances of obj->note around,
377 	 * but I haven't been able to track down their origins - NRM */
378 	if (!s) return 0;
379 
380 	do {
381 		s = strstr(s, inscrip);
382 		if (!s) break;
383 		if (isdigit(s[inlen])) {
384 			if (i == 0) {
385 				long inarg = strtol(s + inlen, 0, 10);
386 
387 				*ival = (inarg < INT_MAX) ? (int) inarg : INT_MAX;
388 			}
389 			i++;
390 		}
391 		s++;
392 	} while (s);
393 
394 	return i;
395 }
396 
397 /*** Object kind lookup functions ***/
398 
399 /**
400  * Return the object kind with the given `tval` and `sval`, or NULL.
401  */
lookup_kind(int tval,int sval)402 struct object_kind *lookup_kind(int tval, int sval)
403 {
404 	int k;
405 
406 	/* Look for it */
407 	for (k = 0; k < z_info->k_max; k++) {
408 		struct object_kind *kind = &k_info[k];
409 		if (kind->tval == tval && kind->sval == sval)
410 			return kind;
411 	}
412 
413 	/* Failure */
414 	msg("No object: %d:%d (%s)", tval, sval, tval_find_name(tval));
415 	return NULL;
416 }
417 
objkind_byid(int kidx)418 struct object_kind *objkind_byid(int kidx) {
419 	if (kidx < 0 || kidx >= z_info->k_max)
420 		return NULL;
421 	return &k_info[kidx];
422 }
423 
424 
425 /*** Textual<->numeric conversion ***/
426 
427 /**
428  * Return the a_idx of the artifact with the given name
429  */
lookup_artifact_name(const char * name)430 struct artifact *lookup_artifact_name(const char *name)
431 {
432 	int i;
433 	int a_idx = -1;
434 
435 	/* Look for it */
436 	for (i = 0; i < z_info->a_max; i++) {
437 		struct artifact *art = &a_info[i];
438 
439 		/* Test for equality */
440 		if (art->name && streq(name, art->name))
441 			return art;
442 
443 		/* Test for close matches */
444 		if (strlen(name) >= 3 && art->name && my_stristr(art->name, name)
445 			&& a_idx == -1)
446 			a_idx = i;
447 	}
448 
449 	/* Return our best match */
450 	return a_idx > 0 ? &a_info[a_idx] : NULL;
451 }
452 
453 /**
454  * \param name ego type name
455  * \param tval object tval
456  * \param sval object sval
457  * \return eidx of the ego item type
458  */
lookup_ego_item(const char * name,int tval,int sval)459 struct ego_item *lookup_ego_item(const char *name, int tval, int sval)
460 {
461 	int i;
462 
463 	/* Look for it */
464 	for (i = 0; i < z_info->e_max; i++) {
465 		struct ego_item *ego = &e_info[i];
466 		struct poss_item *poss_item = ego->poss_items;
467 
468 		/* Reject nameless and wrong names */
469 		if (!ego->name) continue;
470 		if (!streq(name, ego->name)) continue;
471 
472 		/* Check tval and sval */
473 		while (poss_item) {
474 			struct object_kind *kind = lookup_kind(tval, sval);
475 			if (kind->kidx == poss_item->kidx) {
476 				return ego;
477 			}
478 			poss_item = poss_item->next;
479 		}
480 	}
481 
482 	return NULL;
483 }
484 
485 /**
486  * Return the numeric sval of the object kind with the given `tval` and
487  * name `name`.
488  */
lookup_sval(int tval,const char * name)489 int lookup_sval(int tval, const char *name)
490 {
491 	int k;
492 	unsigned int r;
493 
494 	if (sscanf(name, "%u", &r) == 1)
495 		return r;
496 
497 	/* Look for it */
498 	for (k = 0; k < z_info->k_max; k++) {
499 		struct object_kind *kind = &k_info[k];
500 		char cmp_name[1024];
501 
502 		if (!kind || !kind->name) continue;
503 
504 		obj_desc_name_format(cmp_name, sizeof cmp_name, 0, kind->name, 0,
505 							 false);
506 
507 		/* Found a match */
508 		if (kind->tval == tval && !my_stricmp(cmp_name, name))
509 			return kind->sval;
510 	}
511 
512 	return -1;
513 }
514 
object_short_name(char * buf,size_t max,const char * name)515 void object_short_name(char *buf, size_t max, const char *name)
516 {
517 	size_t j, k;
518 	/* Copy across the name, stripping modifiers & and ~) */
519 	size_t len = strlen(name);
520 	for (j = 0, k = 0; j < len && k < max - 1; j++) {
521 		if (j == 0 && name[0] == '&' && name[1] == ' ')
522 			j += 2;
523 		if (name[j] == '~')
524 			continue;
525 
526 		buf[k++] = name[j];
527 	}
528 	buf[k] = 0;
529 }
530 
531 /**
532  * Sort comparator for objects using only tval and sval.
533  * -1 if o1 should be first
534  *  1 if o2 should be first
535  *  0 if it doesn't matter
536  */
compare_types(const struct object * o1,const struct object * o2)537 static int compare_types(const struct object *o1, const struct object *o2)
538 {
539 	if (o1->tval == o2->tval)
540 		return CMP(o1->sval, o2->sval);
541 	else
542 		return CMP(o1->tval, o2->tval);
543 }
544 
545 
546 /**
547  * Sort comparator for objects
548  * -1 if o1 should be first
549  *  1 if o2 should be first
550  *  0 if it doesn't matter
551  *
552  * The sort order is designed with the "list items" command in mind.
553  */
compare_items(const struct object * o1,const struct object * o2)554 int compare_items(const struct object *o1, const struct object *o2)
555 {
556 	/* unknown objects go at the end, order doesn't matter */
557 	if (is_unknown(o1) || is_unknown(o2)) {
558 		if (!is_unknown(o1)) return -1;
559 		return 1;
560 	}
561 
562 	/* known artifacts will sort first */
563 	if (object_is_known_artifact(o1) && object_is_known_artifact(o2))
564 		return compare_types(o1, o2);
565 	if (object_is_known_artifact(o1)) return -1;
566 	if (object_is_known_artifact(o2)) return 1;
567 
568 	/* unknown objects will sort next */
569 	if (!object_flavor_is_aware(o1) && !object_flavor_is_aware(o2))
570 		return compare_types(o1, o2);
571 	if (!object_flavor_is_aware(o1)) return -1;
572 	if (!object_flavor_is_aware(o2)) return 1;
573 
574 	/* if only one of them is worthless, the other comes first */
575 	if (o1->kind->cost == 0 && o2->kind->cost != 0) return 1;
576 	if (o1->kind->cost != 0 && o2->kind->cost == 0) return -1;
577 
578 	/* otherwise, just compare tvals and svals */
579 	/* NOTE: arguably there could be a better order than this */
580 	return compare_types(o1, o2);
581 }
582 
583 
584 /**
585  * Determine if an object has charges
586  */
obj_has_charges(const struct object * obj)587 bool obj_has_charges(const struct object *obj)
588 {
589 	if (!tval_can_have_charges(obj)) return false;
590 
591 	if (obj->pval <= 0) return false;
592 
593 	return true;
594 }
595 
596 /**
597  * Determine if an object is zappable
598  */
obj_can_zap(const struct object * obj)599 bool obj_can_zap(const struct object *obj)
600 {
601 	/* Any rods not charging? */
602 	if (tval_can_have_timeout(obj) && number_charging(obj) < obj->number)
603 		return true;
604 
605 	return false;
606 }
607 
608 /**
609  * Determine if an object is activatable
610  */
obj_is_activatable(const struct object * obj)611 bool obj_is_activatable(const struct object *obj)
612 {
613 	if (!tval_is_wearable(obj)) return false;
614 	return object_effect(obj) ? true : false;
615 }
616 
617 /**
618  * Determine if an object can be activated now
619  */
obj_can_activate(const struct object * obj)620 bool obj_can_activate(const struct object *obj)
621 {
622 	if (obj_is_activatable(obj)) {
623 		/* Check the recharge */
624 		if (!obj->timeout) return true;
625 	}
626 
627 	return false;
628 }
629 
630 /**
631  * Check if an object can be used to refuel other objects.
632  */
obj_can_refill(const struct object * obj)633 bool obj_can_refill(const struct object *obj)
634 {
635 	const struct object *light = equipped_item_by_slot_name(player, "light");
636 
637 	/* Need fuel? */
638 	if (of_has(obj->flags, OF_NO_FUEL)) return false;
639 
640 	/* A lantern can be refueled from a flask or another lantern */
641 	if (light && of_has(light->flags, OF_TAKES_FUEL)) {
642 		if (tval_is_fuel(obj))
643 			return true;
644 		else if (tval_is_light(obj) && of_has(obj->flags, OF_TAKES_FUEL) &&
645 				 obj->timeout > 0)
646 			return true;
647 	}
648 
649 	return false;
650 }
651 
obj_kind_can_browse(const struct object_kind * kind)652 bool obj_kind_can_browse(const struct object_kind *kind)
653 {
654 	int i;
655 
656 	for (i = 0; i < player->class->magic.num_books; i++) {
657 		struct class_book book = player->class->magic.books[i];
658 		if (kind == lookup_kind(book.tval, book.sval))
659 			return true;
660 	}
661 
662 	return false;
663 }
664 
obj_can_browse(const struct object * obj)665 bool obj_can_browse(const struct object *obj)
666 {
667 	return obj_kind_can_browse(obj->kind);
668 }
669 
obj_can_cast_from(const struct object * obj)670 bool obj_can_cast_from(const struct object *obj)
671 {
672 	return obj_can_browse(obj) &&
673 			spell_book_count_spells(obj, spell_okay_to_cast) > 0;
674 }
675 
obj_can_study(const struct object * obj)676 bool obj_can_study(const struct object *obj)
677 {
678 	return obj_can_browse(obj) &&
679 		spell_book_count_spells(obj, spell_okay_to_study) > 0;
680 }
681 
682 
683 /* Can only take off non-cursed items */
obj_can_takeoff(const struct object * obj)684 bool obj_can_takeoff(const struct object *obj)
685 {
686 	return !obj_has_flag(obj, OF_STICKY);
687 }
688 
689 /* Can only put on wieldable items */
obj_can_wear(const struct object * obj)690 bool obj_can_wear(const struct object *obj)
691 {
692 	return (wield_slot(obj) >= 0);
693 }
694 
695 /* Can only fire an item with the right tval */
obj_can_fire(const struct object * obj)696 bool obj_can_fire(const struct object *obj)
697 {
698 	return obj->tval == player->state.ammo_tval;
699 }
700 
701 /**
702  * Determine if an object is designed for throwing
703  */
obj_is_throwing(const struct object * obj)704 bool obj_is_throwing(const struct object *obj)
705 {
706 	return of_has(obj->flags, OF_THROWING);
707 }
708 
709 /**
710  * Determine if an object is a known artifact
711  */
obj_is_known_artifact(const struct object * obj)712 bool obj_is_known_artifact(const struct object *obj)
713 {
714 	if (!obj->artifact) return false;
715 	if (!obj->known) return false;
716 	if (!obj->known->artifact) return false;
717 	return true;
718 }
719 
720 /* Can has inscrip pls */
obj_has_inscrip(const struct object * obj)721 bool obj_has_inscrip(const struct object *obj)
722 {
723 	return (obj->note ? true : false);
724 }
725 
obj_has_flag(const struct object * obj,int flag)726 bool obj_has_flag(const struct object *obj, int flag)
727 {
728 	struct curse_data *c = obj->curses;
729 
730 	/* Check the object's own flags */
731 	if (of_has(obj->flags, flag)) {
732 		return true;
733 	}
734 
735 	/* Check any curse object flags */
736 	if (c) {
737 		int i;
738 		for (i = 1; i < z_info->curse_max; i++) {
739 			if (c[i].power && of_has(curses[i].obj->flags, flag)) {
740 				return true;
741 			}
742 		}
743 	}
744 	return false;
745 }
746 
obj_is_useable(const struct object * obj)747 bool obj_is_useable(const struct object *obj)
748 {
749 	if (tval_is_useable(obj))
750 		return true;
751 
752 	if (object_effect(obj))
753 		return true;
754 
755 	if (tval_is_ammo(obj))
756 		return obj->tval == player->state.ammo_tval;
757 
758 	return false;
759 }
760 
761 /*** Generic utility functions ***/
762 
763 /**
764  * Return an object's effect.
765  */
object_effect(const struct object * obj)766 struct effect *object_effect(const struct object *obj)
767 {
768 	if (obj->activation)
769 		return obj->activation->effect;
770 	else if (obj->effect)
771 		return obj->effect;
772 	else
773 		return NULL;
774 }
775 
776 /**
777  * Does the given object need to be aimed?
778  */
obj_needs_aim(struct object * obj)779 bool obj_needs_aim(struct object *obj)
780 {
781 	struct effect *effect = object_effect(obj);
782 
783 	/* If the effect needs aiming, or if the object type needs
784 	   aiming, this object needs aiming. */
785 	return effect_aim(effect) || tval_is_ammo(obj) ||
786 			tval_is_wand(obj) ||
787 			(tval_is_rod(obj) && !object_flavor_is_aware(obj));
788 }
789 
790 /**
791  * Can the object fail if used?
792  */
obj_can_fail(const struct object * o)793 bool obj_can_fail(const struct object *o)
794 {
795 	if (tval_can_have_failure(o))
796 		return true;
797 
798 	return wield_slot(o) == -1 ? false : true;
799 }
800 
801 
802 /**
803  * Returns the number of times in 1000 that @ will FAIL
804  * - thanks to Ed Graham for the formula
805  */
get_use_device_chance(const struct object * obj)806 int get_use_device_chance(const struct object *obj)
807 {
808 	int lev, fail, numerator, denominator;
809 
810 	int skill = player->state.skills[SKILL_DEVICE];
811 
812 	int skill_min = 10;
813 	int skill_max = 141;
814 	int diff_min  = 1;
815 	int diff_max  = 100;
816 
817 	/* Extract the item level, which is the difficulty rating */
818 	if (obj->artifact)
819 		lev = obj->artifact->level;
820 	else
821 		lev = obj->kind->level;
822 
823 	/* TODO: maybe use something a little less convoluted? */
824 	numerator   = (skill - lev) - (skill_max - diff_min);
825 	denominator = (lev - skill) - (diff_max - skill_min);
826 
827 	/* Make sure that we don't divide by zero */
828 	if (denominator == 0) denominator = numerator > 0 ? 1 : -1;
829 
830 	fail = (100 * numerator) / denominator;
831 
832 	/* Ensure failure rate is between 1% and 75% */
833 	if (fail > 750) fail = 750;
834 	if (fail < 10) fail = 10;
835 
836 	return fail;
837 }
838 
839 
840 /**
841  * Distribute charges of rods, staves, or wands.
842  *
843  * \param source is the source item
844  * \param dest is the target item, must be of the same type as source
845  * \param amt is the number of items that are transfered
846  */
distribute_charges(struct object * source,struct object * dest,int amt)847 void distribute_charges(struct object *source, struct object *dest, int amt)
848 {
849 	int charge_time = randcalc(source->time, 0, AVERAGE), max_time;
850 
851 	/*
852 	 * Hack -- If rods, staves, or wands are dropped, the total maximum
853 	 * timeout or charges need to be allocated between the two stacks.
854 	 * If all the items are being dropped, it makes for a neater message
855 	 * to leave the original stack's pval alone. -LM-
856 	 */
857 	if (tval_can_have_charges(source)) {
858 		dest->pval = source->pval * amt / source->number;
859 
860 		if (amt < source->number)
861 			source->pval -= dest->pval;
862 	}
863 
864 	/*
865 	 * Hack -- Rods also need to have their timeouts distributed.
866 	 *
867 	 * The dropped stack will accept all time remaining to charge up to
868 	 * its maximum.
869 	 */
870 	if (tval_can_have_timeout(source)) {
871 		max_time = charge_time * amt;
872 
873 		if (source->timeout > max_time)
874 			dest->timeout = max_time;
875 		else
876 			dest->timeout = source->timeout;
877 
878 		if (amt < source->number)
879 			source->timeout -= dest->timeout;
880 	}
881 }
882 
883 
884 /**
885  * Number of items (usually rods) charging
886  */
number_charging(const struct object * obj)887 int number_charging(const struct object *obj)
888 {
889 	int charge_time, num_charging;
890 
891 	charge_time = randcalc(obj->time, 0, AVERAGE);
892 
893 	/* Item has no timeout */
894 	if (charge_time <= 0) return 0;
895 
896 	/* No items are charging */
897 	if (obj->timeout <= 0) return 0;
898 
899 	/* Calculate number charging based on timeout */
900 	num_charging = (obj->timeout + charge_time - 1) / charge_time;
901 
902 	/* Number charging cannot exceed stack size */
903 	if (num_charging > obj->number) num_charging = obj->number;
904 
905 	return num_charging;
906 }
907 
908 /**
909  * Allow a stack of charging objects to charge by one unit per charging object
910  * Return true if something recharged
911  */
recharge_timeout(struct object * obj)912 bool recharge_timeout(struct object *obj)
913 {
914 	int charging_before, charging_after;
915 
916 	/* Find the number of charging items */
917 	charging_before = number_charging(obj);
918 
919 	/* Nothing to charge */
920 	if (charging_before == 0)
921 		return false;
922 
923 	/* Decrease the timeout */
924 	obj->timeout -= MIN(charging_before, obj->timeout);
925 
926 	/* Find the new number of charging items */
927 	charging_after = number_charging(obj);
928 
929 	/* Return true if at least 1 item obtained a charge */
930 	if (charging_after < charging_before)
931 		return true;
932 	else
933 		return false;
934 }
935 
936 /**
937  * Verify the choice of an item.
938  *
939  * The item can be negative to mean "item on floor".
940  */
verify_object(const char * prompt,struct object * obj)941 bool verify_object(const char *prompt, struct object *obj)
942 {
943 	char o_name[80];
944 
945 	char out_val[160];
946 
947 	/* Describe */
948 	object_desc(o_name, sizeof(o_name), obj, ODESC_PREFIX | ODESC_FULL);
949 
950 	/* Prompt */
951 	strnfmt(out_val, sizeof(out_val), "%s %s? ", prompt, o_name);
952 
953 	/* Query */
954 	return (get_check(out_val));
955 }
956 
957 
958 typedef enum {
959 	MSG_TAG_NONE,
960 	MSG_TAG_NAME,
961 	MSG_TAG_KIND,
962 	MSG_TAG_VERB,
963 	MSG_TAG_VERB_IS
964 } msg_tag_t;
965 
msg_tag_lookup(const char * tag)966 static msg_tag_t msg_tag_lookup(const char *tag)
967 {
968 	if (strncmp(tag, "name", 4) == 0) {
969 		return MSG_TAG_NAME;
970 	} else if (strncmp(tag, "kind", 4) == 0) {
971 		return MSG_TAG_KIND;
972 	} else if (strncmp(tag, "s", 1) == 0) {
973 		return MSG_TAG_VERB;
974 	} else if (strncmp(tag, "is", 2) == 0) {
975 		return MSG_TAG_VERB_IS;
976 	} else {
977 		return MSG_TAG_NONE;
978 	}
979 }
980 
981 /**
982  * Print a message from a string, customised to include details about an object
983  */
print_custom_message(struct object * obj,const char * string,int msg_type)984 void print_custom_message(struct object *obj, const char *string, int msg_type)
985 {
986 	char buf[1024] = "\0";
987 	const char *next;
988 	const char *s;
989 	const char *tag;
990 	size_t end = 0;
991 
992 	/* Not always a string */
993 	if (!string) return;
994 
995 	next = strchr(string, '{');
996 	while (next) {
997 		/* Copy the text leading up to this { */
998 		strnfcat(buf, 1024, &end, "%.*s", next - string, string);
999 
1000 		s = next + 1;
1001 		while (*s && isalpha((unsigned char) *s)) s++;
1002 
1003 		/* Valid tag */
1004 		if (*s == '}') {
1005 			/* Start the tag after the { */
1006 			tag = next + 1;
1007 			string = s + 1;
1008 
1009 			switch(msg_tag_lookup(tag)) {
1010 			case MSG_TAG_NAME:
1011 				if (obj) {
1012 					end += object_desc(buf, 1024, obj,
1013 									   ODESC_PREFIX | ODESC_BASE);
1014 				} else {
1015 					strnfcat(buf, 1024, &end, "hands");
1016 				}
1017 				break;
1018 			case MSG_TAG_KIND:
1019 				if (obj) {
1020 					object_kind_name(&buf[end], 1024 - end, obj->kind, true);
1021 					end += strlen(&buf[end]);
1022 				} else {
1023 					strnfcat(buf, 1024, &end, "hands");
1024 				}
1025 				break;
1026 			case MSG_TAG_VERB:
1027 				if (obj && obj->number == 1) {
1028 					strnfcat(buf, 1024, &end, "s");
1029 				}
1030 				break;
1031 			case MSG_TAG_VERB_IS:
1032 				if ((!obj) || (obj->number > 1)) {
1033 					strnfcat(buf, 1024, &end, "are");
1034 				} else {
1035 					strnfcat(buf, 1024, &end, "is");
1036 				}
1037 			default:
1038 				break;
1039 			}
1040 		} else
1041 			/* An invalid tag, skip it */
1042 			string = next + 1;
1043 
1044 		next = strchr(string, '{');
1045 	}
1046 	strnfcat(buf, 1024, &end, string);
1047 
1048 	msgt(msg_type, "%s", buf);
1049 }
1050