1 /* The main simulation-running code in Xconq.
2    Copyright (C) 1986-1989, 1991-2000 Stanley T. Shebs.
3 
4 Xconq is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.  See the file COPYING.  */
8 
9 /* This is the main simulation-running code. */
10 
11 #include "conq.h"
12 #include "kernel.h"
13 #include "kpublic.h"
14 
15 /* This is for storing the most recently executed action. */
16 
17 Action *latest_action = NULL;
18 
19 /* The last known position of the latest actor. */
20 
21 int latest_action_x;
22 int latest_action_y;
23 
24 static void compose_actionvectors(void);
25 static void init_movement(void);
26 static void clear_aicontrolled_outcomes(void);
27 static int move_some_units(int lim);
28 static int side_move_some_units(Side *side, int lim);
29 static int unit_still_acting(Unit *unit);
30 static int unit_still_acting_no_plan(Unit *unit);
31 static int move_one_unit_multiple(Unit *unit, int lim);
32 static int action_reaction_needed(int type, int rslt);
33 static int all_human_only_sides_finished(void);
34 
35 static void test_for_game_start(void);
36 static void test_for_game_end(void);
37 static int all_sides_finished(void);
38 static void check_realtime(void);
39 static int exceeded_rt_for_game(void);
40 static int exceeded_rt_per_turn(void);
41 static int units_still_acting(Side *side);
42 static int unit_priority(Unit *unit);
43 static void auto_pick_new_plan(Unit *unit);
44 
45 /* Advanced unit support. */
46 
47 extern void allocate_used_cells(Unit *unit);	/* Used in move.c */
48 
49 static void run_side_research(void);
50 static void run_population(Unit *unit);
51 static void run_research(Unit *unit);
52 static int auto_pick_new_build_task(Unit *unit);
53 
54 static void take_all_from_treasury(Unit *unit);
55 static void give_all_to_treasury(Unit *unit);
56 
57 /* Priority of sides that are now moving. */
58 
59 int curpriority;
60 
61 /* Priority of units that are now moving. */
62 
63 int cur_unit_priority;
64 
65 /* Highest and lowest possible priority of unit (smallest and largest
66    number). */
67 
68 int highest_unit_priority;
69 int lowest_unit_priority;
70 
71 int maintimeout = -1;
72 
73 int paused = FALSE;
74 
75 /* State variables. */
76 /* (I don't think all of these are strictly necessary) */
77 
78 /* This becomes TRUE the first time run_game is executed. */
79 
80 int gameinited = FALSE;
81 
82 /* This is true only before the game actually starts. */
83 
84 int beforestart = TRUE;
85 
86 /* This is true only at the beginning of a turn. */
87 
88 int at_turn_start = FALSE;
89 
90 /* This is true after the game is over. */
91 
92 int endofgame = FALSE;
93 
94 /* This is true when the program may actually exit. */
95 
96 int ok_to_exit;
97 
98 /* This is set FALSE whenever the game state changes, and TRUE whenever
99    the game has been saved. */
100 
101 int gamestatesafe = TRUE;
102 
103 /* This is TRUE after the designer has been mucking around, or if
104    networked versions are found to be inconsistent. */
105 
106 int compromised = FALSE;
107 
108 int in_run_game = FALSE;
109 
110 /* The time at which the game actually starts. */
111 
112 time_t game_start_in_real_time;
113 
114 /* The point in the turn at which players can actually do things. */
115 
116 time_t turn_play_start_in_real_time;
117 
118 int planexecs;
119 
120 /* The count of task executions during a call to run_game. */
121 
122 int taskexecs;
123 
124 /* The rate at which AIs play when acting more slowly (so as
125    not to overwhelm human players), expressed as plan executions
126    per minute.  0 means "as fast as possible". */
127 
128 int slow_play_rate = 240;
129 
130 /* The rate at which AIs play when acting more quickly (such
131    as when all humans are done with their moves). */
132 
133 int fast_play_rate = 0;
134 
135 /* The current rate at which AIs are playing. */
136 
137 int current_play_rate;
138 
139 /* Debugging counts for when run_game does nothing many times. */
140 
141 static int nothing_count;
142 
143 /* True when an event occurs and we need to check scorekeepers. */
144 
145 int need_post_event_scores;
146 
147 /* Flags that other code uses to signal the AI code that it ought
148    to consider running something. */
149 
150 int need_ai_init_turn;
151 
152 int need_ai_planning;
153 
154 int need_ai_action_reaction;
155 
156 int need_ai_for_new_side;
157 
158 int need_ai_finish_movement;
159 
160 int debugging_state_sync;
161 
162 void
init_run(void)163 init_run(void)
164 {
165     int u;
166     Unit *unit;
167     Side *side;
168 
169     highest_unit_priority = 9999;
170     lowest_unit_priority = -1;
171     for_all_unit_types(u) {
172         highest_unit_priority =
173 	  min(highest_unit_priority, u_action_priority(u));
174         lowest_unit_priority =
175 	  max(lowest_unit_priority, u_action_priority(u));
176         for_all_sides(side) {
177 	    if (side->action_priorities) {
178 		highest_unit_priority =
179 		  min(highest_unit_priority, side->action_priorities[u]);
180 		lowest_unit_priority =
181 		  max(lowest_unit_priority, side->action_priorities[u]);
182 	    }
183         }
184     }
185     for_all_units(unit) {
186         if (unit->extras) {
187 	    highest_unit_priority =
188 	      min(highest_unit_priority, unit_extra_priority(unit));
189 	    lowest_unit_priority =
190 	      max(lowest_unit_priority, unit_extra_priority(unit));
191         }
192     }
193 }
194 
195 /* This function does a (small, usually) amount of simulation, then
196    returns.  It can be run multiple times at any time, will not go
197    "too far".  It returns the number of actions that were actually
198    performed. Other important state changes (such a side finishing its
199    turn or the turn ending) are also counted as actions, so that this
200    function's callers will know that something was done. */
201 
202 static void save_run_state(char *suffix);
203 
204 int
run_game(int maxactions)205 run_game(int maxactions)
206 {
207     int numacted, numother, runtime, numdone, bump;
208     int last_taskexecs = taskexecs;
209     long saved_randstate;
210     time_t rungamestart, rungameend;
211     Side *side;
212     extern long randstate;
213     char *activity = "run_game";
214 
215     in_run_game = TRUE;
216     record_activity_start(activity, maxactions);
217     if (Debug)
218       save_run_state("a");
219     gameinited = TRUE;
220     saved_randstate = randstate;
221     time(&rungamestart);
222     numacted = numother = planexecs = taskexecs = 0;
223     need_ai_planning = FALSE;
224     /* Make sure the action record is allocated. */
225     if (latest_action == NULL)
226       latest_action = (Action *) xmalloc(sizeof(Action));
227     if (beforestart) {
228 	/* If we haven't started yet, see if it's time. */
229 	test_for_game_start();
230 	Dprintf("run_game: tested for game start.\n");
231     }
232     if (endofgame) {
233 	/* Nothing to do except wait for users to do exit commands. */
234     	Dprintf("run_game: at end of game.\n");
235     } else if (paused) {
236 	/* Don't do anything if we're paused. */
237     	Dprintf("run_game: paused.\n");
238     } else if (numdesigners > 0) {
239 	/* Don't try to run the game if any designers are around. */
240     	Dprintf("run_game: designing.\n");
241     } else if (!beforestart) {
242 	if (at_turn_start) {
243 	    if (midturnrestore)
244 	      run_restored_turn_start();
245 	    else
246 	      run_turn_start();
247 	    check_all_units();
248 	    init_movement();
249 	    cur_unit_priority = highest_unit_priority;
250 	    compose_actionvectors();
251 	    update_all_progress_displays("", -1);
252 	    /* Make sure the research window is popped up for sides
253 	    without a research task. */
254 	    for_all_sides(side) {
255 		    if (side_has_display(side)) {
256 			update_research_display(side);
257 		    }
258 	    }
259 	    /* Game might have been ended by new turn init. */
260 	    test_for_game_end();
261 	    if (endofgame) {
262 	    	Dprintf("run_game: game ended by new turn init.\n");
263 	    	goto run_game_return;
264 	    }
265 	    /* (should adjust this by recorded elapsed turn time) */
266 	    time(&turn_play_start_in_real_time);
267 	    at_turn_start = FALSE;
268 	    ++numother;
269 	    /* Might have local AIs that need to run, so give them a chance
270 	       now rather than after units start moving. */
271 	    need_ai_init_turn = TRUE;
272 	    need_ai_planning = TRUE;
273 	    goto run_game_return;
274 	}
275 	/* If this game is running in realtime, update all clock displays. */
276 	if (realtime_game()) {
277 	    for_all_sides(side) {
278 		if (side->ingame && side_has_display(side)) {
279 		    update_clock_display(side, TRUE);
280 		}
281 	    }
282 	}
283 	/* If all sides are done acting, end the turn.  This will never be true
284 	   right at the start of a turn. */
285 	if (all_sides_finished() || exceeded_rt_per_turn()) {
286 	    run_turn_end();
287 	    Dprintf("run_game: at turn end.\n");
288 	    at_turn_start = TRUE;
289 	    ++numother;
290 	    need_ai_finish_movement = TRUE;
291 	} else {
292 	    /* First do some side research. Note: we have to do this
293 	       here rather than during run_turn_start since we must
294 	       give human players and ais a chance to pick a new
295 	       research task if the current one is
296 	       completed. Otherwise, no side can ever finish more than
297 	       one advance each turn. */
298 	    run_side_research();
299 	    if (last_taskexecs > 0)
300 	      clear_aicontrolled_outcomes();
301 	    /* Move some units around. */
302 	    numacted += move_some_units(maxactions);
303 	    if (cur_unit_priority < lowest_unit_priority) {
304 		/* Handle prioritized movement. */
305 		bump = TRUE;
306 		for_all_sides(side) {
307 		    if (!side->finishedturn
308 			&& units_still_acting(side)) {
309 			bump = FALSE;
310 		    }
311 		}
312 		if (bump) {
313 		    Dprintf("run_game: increment unit priority to %d\n",
314 			    cur_unit_priority + 1);
315 		    ++cur_unit_priority;
316 		    compose_actionvectors();
317 		    ++numother;
318 		}
319 	    } else {
320 		/* Possibly finish some sides' turns. */
321 		for_all_sides(side) {
322 		    if (!side->finishedturn
323 			&& ((!units_still_acting(side)
324 			     && side->autofinish
325 			     && !is_designer(side))
326 			    /* Sides with no display or AI finish
327                                automatically. */
328 			    || (!side_has_display(side)
329 				&& !side_has_ai(side)))) {
330 			Dprintf("run_game: %s auto-finishes.\n",
331 				side_desig(side));
332 			finish_turn(side);
333 			++numother;
334 		    }
335 		}
336 	    }
337 	}
338 	check_realtime();
339 	test_for_game_end();
340     }
341  run_game_return:
342     if (need_post_event_scores)
343       check_post_event_scores();
344     numdone = numacted + planexecs + taskexecs + numother;
345     if (Debug) {
346 	if (numdone > 0) {
347 	    if (nothing_count > 0) {
348 		Dprintf("run_game: Did nothing %d times\n", nothing_count);
349 		nothing_count = 0;
350 	    }
351 	    Dprintf("run_game #%d: %d/%d actions", g_run_serial_number(),
352 		    numacted, maxactions);
353 	    if (planexecs > 0)
354 	      Dprintf(", %d plan execs", planexecs);
355 	    if (taskexecs > 0)
356 	      Dprintf(", %d task execs", taskexecs);
357 	    if (numother > 0)
358 	      Dprintf(", %d other", numother);
359 	    /* (also number of units considered?) */
360 	    Dprintf("\n");
361 	    if (numremotes > 0)
362 	      Dprintf("run_game: Randstate started at %ld, is now %ld\n",
363 		      saved_randstate, randstate);
364 	    save_run_state("");
365 	} else {
366 	    if (nothing_count >= 1000) {
367 		Dprintf("run_game: Did nothing %d times\n", nothing_count);
368 		nothing_count = 0;
369 	    } else {
370 		++nothing_count;
371 	    }
372 	}
373     }
374     time(&rungameend);
375     runtime = idifftime(rungameend, rungamestart);
376     if (runtime > 0)
377       Dprintf("run_game: runtime seconds = %d\n", runtime);
378     if (Debug)
379       save_run_state("b");
380     in_run_game = FALSE;
381     set_g_run_serial_number(g_run_serial_number() + 1);
382     record_activity_end(activity, numdone);
383     return numdone;
384 }
385 
386 /* The following routine saves a copy of the game's state in a
387    specially-named file, for the purposes of debugging networking sync
388    problems.  This generates massive amounts of saved data very
389    quickly, be careful using it! */
390 
391 static int save_run_states = 0;
392 
393 void
save_run_state(char * suffix)394 save_run_state(char *suffix)
395 {
396     if (numremotes > 0 && save_run_states) {
397 	sprintf(spbuf, "states/%dstate%06d%s",
398 		my_rid, g_run_serial_number(), suffix);
399 	debugging_state_sync = TRUE;
400 	write_entire_game_state(spbuf);
401 	debugging_state_sync = FALSE;
402     }
403 }
404 
405 /* See if game is ready to get underway for real.  Note that displays will
406    work before the game has started, but game time doesn't move. */
407 
408 static void
test_for_game_start(void)409 test_for_game_start(void)
410 {
411     int anydisplays = FALSE;
412     Side *side;
413 
414     /* We must have at least one unit on a side that is being displayed
415        before the game can start for real. */
416     for_all_sides(side) {
417 	if (side_has_display(side)) {
418 	    anydisplays = TRUE;
419 	}
420 	if (side_has_units(side) && side_has_display(side)) {
421 	    /* Now we're really ready to roll. */
422 	    beforestart = FALSE;
423 	    at_turn_start = TRUE;
424 	    if (midturnrestore) {
425 		record_event(H_GAME_RESTARTED, ALLSIDES);
426 	    } else {
427 		record_event(H_GAME_STARTED, ALLSIDES);
428 		set_g_elapsed_time(0);
429 	    }
430 	    /* Record the game as starting NOW in real time. */
431 	    time(&game_start_in_real_time);
432 	    /* Adjust by any recorded elapsed time. */
433 	    game_start_in_real_time -= g_elapsed_time();
434 	    /* No need to look at any more sides, just get on with the game. */
435 	    return;
436 	}
437     }
438     if (!anydisplays) {
439 	init_warning("No sides have a display");
440     }
441 }
442 
443 /* This routine looks to see if the game is completely over. */
444 
445 static void
test_for_game_end(void)446 test_for_game_end(void)
447 {
448     Side *side;
449 
450     /* Declare a draw if everybody is amenable. */
451     if (all_others_willing_to_quit(NULL)) {
452     	notify_all("All sides have agreed to declare a draw.");
453     	all_sides_draw();
454 	end_the_game();
455 	return;
456     }
457     for_all_sides(side) {
458     	/* If we have an active side being displayed, we're not done yet. */
459 	if (side->ingame && side_has_display(side))
460 	  return;
461 	/* (If no displayed sides have units, turns will whiz by) */
462     }
463     notify_all("All sides with displays are out of the game.");
464     end_the_game();
465 }
466 
467 /* This is true when all participating sides have finished their turn. */
468 
469 static int
all_sides_finished(void)470 all_sides_finished(void)
471 {
472     Side *side;
473 
474     for_all_sides(side) {
475 	if (side->ingame
476 	    && !side->finishedturn) {
477 	    return FALSE;
478 	}
479     }
480     return TRUE;
481 }
482 
483 /* This is true when AIs should move more quickly. */
484 
485 int
all_human_only_sides_finished(void)486 all_human_only_sides_finished(void)
487 {
488     Side *side;
489 
490     for_all_sides(side) {
491 	if (side->ingame
492 	    && side_has_display(side)
493 	    && !side_has_ai(side)
494 	    && !side->finishedturn) {
495 	    return FALSE;
496 	}
497     }
498     return TRUE;
499 }
500 
501 /* Call this from interfaces to check on realtime details without actually
502    going into run_game.  Will call back to interface if necessary. */
503 
504 void
check_realtime(void)505 check_realtime(void)
506 {
507     Side *side;
508 
509     if (!realtime_game())
510       return;
511     if (exceeded_rt_for_game()) {
512 	notify_all("Time has run out!");
513 	end_the_game();
514     }
515     if (g_rt_per_side() > 0) {
516 	for_all_sides(side) {
517 	    if (side->ingame && side->totaltimeused > g_rt_per_side()) {
518 		remove_side_from_game(side);
519 	    }
520 	}
521     }
522 }
523 
524 int
exceeded_rt_for_game(void)525 exceeded_rt_for_game(void)
526 {
527     time_t now;
528 
529     if (g_rt_for_game() <= 0)
530       return FALSE;
531     time(&now);
532     /* Note that the game start time is already adjusted for any
533        elapsed time recorded when the game was last saved. */
534     return (idifftime(now, game_start_in_real_time) > g_rt_for_game());
535 }
536 
537 int
exceeded_rt_per_turn(void)538 exceeded_rt_per_turn(void)
539 {
540     time_t now;
541 
542     if (g_rt_per_turn() <= 0)
543       return FALSE;
544     time(&now);
545     return (idifftime(now, turn_play_start_in_real_time) > g_rt_per_turn());
546 }
547 
548 /* This returns true if the given side is still wanting to do stuff. */
549 
550 int
units_still_acting(Side * side)551 units_still_acting(Side *side)
552 {
553     int curactor, a;
554     Unit *unit;
555     UnitVector *av = side->actionvector;
556 
557     if (!side->ingame)
558       return FALSE;
559     /* Test current actor first, most likely to be still acting. */
560     if (side->curactor_pos < av->numunits) {
561 	unit = unit_in_vector(av, side->curactor_pos);
562 	if (unit_still_acting(unit) && side_controls_unit(side, unit))
563 	  return TRUE;
564     }
565     /* Now scan the whole action vector.  It's expected that all
566        active units will be in this vector. */
567     for (curactor = 0; curactor < av->numunits; ++curactor) {
568 	unit = unit_in_vector(av, curactor);
569 	if (unit_still_acting(unit) && side_controls_unit(side, unit))
570 	  return TRUE;
571     }
572     /* Try not to let a side not be researching something. */
573     if (numatypes > 0
574 	&& g_side_can_research()
575 	&& side->research_topic == NOADVANCE) {
576 	/* Check that the side can research something. */
577 	for_all_advance_types(a) {
578 	    if (side_can_research(side, a)) {
579 		/* Popup the research dialog if the side has a
580 		   display. */
581 		if (side_has_display(side)) {
582 		    update_research_display(side);
583 		}
584 		return TRUE;
585 	    }
586 	}
587     }
588     return FALSE;
589 }
590 
591 /* Handle movement priorities and various flags. */
592 
593 static void
init_movement(void)594 init_movement(void)
595 {
596     int i;
597     Side *side;
598 
599     i = 1;
600     curpriority = 9999;
601     /* If the indepside has no AI and cannot build or research, it's
602        done. */
603     if (!g_indepside_can_research()
604 	&& !g_indepside_can_build()
605 	&& !g_indepside_has_ai())
606       indepside->finishedturn = TRUE;
607     for_all_sides(side) {
608 	if (side->ingame) {
609 	    /* Record that this side was active during at least one turn. */
610 	    side->everingame = TRUE;
611 	    /* No units are waiting for orders initially. */
612 	    side->numwaiting = 0;
613 	}
614 	side->turnstarttime = time(0);
615 	/* Didn't really do input, but useful to pretend so. */
616 	side->lasttime = time(0);
617 	/* Calculate side priorities; do here so future versions can
618 	   set priorities dynamically. */
619 	if (g_use_side_priority()) {
620 	    if (side->priority < 0) {
621 		side->priority = i++;
622 	    }
623 	}
624 	side->busy = FALSE;
625 	if (side_has_display(side))
626 	  update_action_display(side, TRUE);
627     }
628     /* Set independent units to move after units on sides. */
629     if (g_use_side_priority()) {
630 	if (indepside->priority < 0) {
631 	    indepside->priority = i;
632 	}
633 	for_all_sides(side) {
634 	    if (!side->finishedturn && side->priority < curpriority)
635 	      curpriority = side->priority;
636 	}
637     }
638 }
639 
640 /* Create (if necessary) and fill in the action vectors, which are the
641    arrays of units that will be moving during the turn. */
642 
643 static void
compose_actionvectors(void)644 compose_actionvectors(void)
645 {
646     int priority;
647     Unit *unit;
648     Side *side, *side2;
649 
650     for_all_sides(side) {
651 	if (side->actionvector == NULL)
652 	  side->actionvector = make_unit_vector(max(numunits, 100));
653 	clear_unit_vector(side->actionvector);
654 	for_all_side_units(side, unit) {
655 	    if (unit->act
656 	        && ((unit->act->initacp > 0)
657 	            || acp_indep(unit))) {
658 		priority = unit_priority(unit);
659 		if (priority == cur_unit_priority) {
660 		    side->actionvector =
661 		      add_unit_to_vector(side->actionvector, unit, 0);
662 		    /* Clear any delay flags. */
663 		    if (unit->plan)
664 		      unit->plan->delayed = FALSE;
665 		    /* Clear any busy flags. */
666 		    if (unit->busy) {
667 		    	/* The busy flag should have been cleared when the unit
668 			   moved. If it is still set, it could mean that a
669 			   broadcasted action was never received by the host
670 		    	   and rebroadcasted. */
671 			Dprintf(
672 "Busy flag still set for %s at start of turn.\n",
673 				unit_desig(unit));
674 			unit->busy = FALSE;
675 		    }
676 		}
677 	    }
678 	    if (unit->plan) {
679 		unit->plan->execs_this_turn = 0;
680 	    }
681 	}
682 	Dprintf("Action vector for %s has %d units, at priority %d\n",
683 		side_desig(side), side->actionvector->numunits,
684 		cur_unit_priority);
685     }
686     /* Inform sides with displays of how many units are ready to act. */
687     for_all_sides(side) {
688 	if (side_has_display(side)) {
689 	    for_all_sides(side2) {
690 		update_side_display(side, side2, TRUE);
691 	    }
692 	}
693     }
694 }
695 
696 int
unit_priority(Unit * unit)697 unit_priority(Unit *unit)
698 {
699     int pri;
700     Side *side = unit->side;
701 
702     pri = unit_extra_priority(unit);
703     if (pri >= 0)
704       return pri;
705     if (side->action_priorities != NULL) {
706 	pri = side->action_priorities[unit->type];
707 	if (pri >= 0)
708 	  return pri;
709     }
710     return u_action_priority(unit->type);
711 }
712 
713 static void
clear_aicontrolled_outcomes(void)714 clear_aicontrolled_outcomes(void)
715 {
716     Unit *unit;
717 
718     /* The human side is not always able to react between two
719        runs. Premature loss of task outcomes causes interface
720        problems. Since the only purpose of clearing outcomes is to
721        send a signal to run_local_ai, we only clear them for
722        ai-controlled units. */
723     for_all_units(unit) {
724 	if (ai_controlled(unit))
725 	  clear_task_outcome(unit);
726     }
727 }
728 
729 /* Do some number of actions, up to a total of LIM per side.  Return
730    the total number of actions performed.  If sides are moving in
731    priority order (aka sequentially), only allow the side matching the
732    current priority to do anything. */
733 
734 static int
move_some_units(int lim)735 move_some_units(int lim)
736 {
737     int num = 0, sidenum;
738     Side *side;
739 
740     for_all_sides(side) {
741 	if ((g_use_side_priority() ?
742 	     curpriority == side->priority :
743 	     TRUE)) {
744 	    sidenum = side_move_some_units(side, lim);
745 	    num += sidenum;
746 	}
747     }
748     return num;
749 }
750 
751 /* Do some number of actions. */
752 
753 static int
side_move_some_units(Side * side,int lim)754 side_move_some_units(Side *side, int lim)
755 {
756     int num, foundanytomove, curactor0, curactor, numcouldact = 0, numfollowing;
757     int numdelayed = 0;
758     Unit *unit;
759     UnitVector *av = side->actionvector;
760 
761     num = 0;
762     curactor0 = 0;
763     /* If we were here last while working on moving a particular unit,
764        and it's still around, start with it. */
765     if (side->curactor_pos < av->numunits
766         && side->curactor == unit_in_vector(av, side->curactor_pos)
767         && side->curactor != NULL
768         && side->curactor_id == unit_in_vector(av, side->curactor_pos)->id)
769       curactor0 = side->curactor_pos;
770     /* (is this needed to maintain sync, or what??) */
771     if (numremotes > 0)
772       curactor0 = 0;
773   try_again:
774     foundanytomove = FALSE;
775     numcouldact = 0;
776     numdelayed = 0;
777     numfollowing = 0;
778     /* Iterate through all units in the action vector, starting with
779        the "current" (most recently moved) unit. */
780     /* Note that the action vector may get resized/reallocated as
781        units act (such as when a unit is captured), so we can't cache
782        it into a local var here. */
783     for (curactor = curactor0; curactor < side->actionvector->numunits;
784 	 ++curactor) {
785 	unit = unit_in_vector(side->actionvector, curactor);
786 #if 0 /* use this for more intense debugging */
787 	Dprintf("Considering moving %s with plan %s\n",
788 		unit_desig(unit), plan_desig(unit->plan));
789 #endif
790 	/* If the unit cannot act anymore, then skip it forthwith. */
791 	if (!has_acp_left(unit))
792 	  continue;
793 	/* Count and skip over deliberately delayed units. */
794 	if (unit->plan && unit->plan->delayed) {
795 	    ++numcouldact;
796 	    ++numdelayed;
797 	    continue;
798 	}
799 	/* Count the units which are in formations and can still act. */
800 	if (unit->plan && unit->plan->formation && unit_still_acting(unit))
801 	  ++numfollowing;
802 	/* Default AIs to the slow play rate. */
803 	current_play_rate = slow_play_rate;
804 	/* AIs should play as fast as possible if turns are sequential,
805 	   or if the human players are all done moving for this turn. */
806 	if (g_use_side_priority() || all_human_only_sides_finished())
807 	  current_play_rate = fast_play_rate;
808 	/* If the unit is keeping formation, then give it a chance to
809 	   adjust its position, even if it's not "still acting". */
810 	if (is_active(unit)
811 	    && unit->side->ingame
812 	    && !unit->side->finishedturn
813 	    && has_acp_left(unit)
814 	    && (unit->plan && unit->plan->formation
815 		&& !is_in_formation(unit))) {
816 	    num += move_one_unit_multiple(unit, lim - num);
817 	    foundanytomove = TRUE;
818 	}
819 	/* Execute standing orders. */
820 	if (unit->side->orders
821 	    && unit->plan
822 	    && unit->plan->tasks == NULL
823 	    && execute_standing_order(unit, FALSE)) {
824 	    /* We're not waiting because standing order execution will
825 	       shortly be allowed to fill in a task for real. */
826 	    set_waiting_for_tasks(unit, FALSE);
827 	    num += move_one_unit_multiple(unit, lim - num);
828 	    foundanytomove = TRUE;
829 	}
830 	/* Execute any tasks or pending actions that the unit has. */
831 	if (unit_still_acting(unit)
832 	    && (unit->plan && !unit->plan->waitingfortasks)) {
833 	    num += move_one_unit_multiple(unit, lim - num);
834 	    foundanytomove = TRUE;
835 	} else if (unit_still_acting_no_plan(unit)) {
836 	    if (has_pending_action(unit) || (unit->plan && unit->plan->tasks)) {
837 		num += move_one_unit_multiple(unit, lim - num);
838 		foundanytomove = TRUE;
839 	    }
840 	}
841 	/* See if we exceeded the limit on the number of moves that
842 	   we're allowed to do this time.  If so, memorize the unit
843 	   that we were working on and return. */
844 	if (num >= lim) {
845 	    if (foundanytomove && unit != NULL) {
846 		side->curactor_pos = curactor;
847 		side->curactor = unit;
848 		/* Important to remember the id, in case the unit dies
849 		   or changes side, invalidating the raw pointer. */
850 		side->curactor_id = unit->id;
851 	    } else {
852 		side->curactor_pos = 0;
853 		side->curactor = NULL;
854 		side->curactor_id = 0;
855 	    }
856 	    return num;
857 	}
858 	/* Increment the count of units that could act. */
859 	++numcouldact;
860     }
861     /* If started in middle of list, and didn't find anything to do,
862        rescan from beginning. */
863     if (!foundanytomove && curactor0 > 0) {
864 	curactor0 = 0;
865 	goto try_again;
866     }
867     /* See if any at all could act, and let the 'run_game' logic deal
868        with it. */
869     if (!numcouldact)
870       return 0;
871     /* Clear all the delay flags and rescan the action vector, if no other
872        non-delayed actors left. */
873     if (!foundanytomove && (0 >= (numcouldact - numdelayed))) {
874 	av = side->actionvector;
875 	for (curactor = 0; curactor < av->numunits; ++curactor) {
876 	    unit = unit_in_vector(av, curactor);
877 	    if (unit->plan)
878 	      unit->plan->delayed = FALSE;
879 	}
880 	curactor0 = 0;
881 	goto try_again;
882     }
883     if (!foundanytomove && 0 /* not at max priority */) {
884 	/* (should recompose action vector for new unit priority?) */
885     }
886     /* Set waiting-for-tasks to true for any units in a formation, which
887        still are acting (have ACP, are not skipped, etc...). */
888     if (numfollowing > 0) {
889 	for (curactor = 0; curactor < av->numunits; ++curactor) {
890 	    unit = unit_in_vector(av, curactor);
891 	    if (unit->plan && unit->plan->formation
892 		&& unit_still_acting(unit) && !(unit->plan->tasks))
893 	      set_waiting_for_tasks(unit, TRUE);
894 	}
895     }
896     side->curactor_pos = 0;
897     side->curactor = NULL;
898     side->curactor_id = 0;
899     return num;
900 }
901 
902 /* Return true if a unit is not yet finished moving. */
903 
904 static int
unit_still_acting(Unit * unit)905 unit_still_acting(Unit *unit)
906 {
907     /* Conditions that always rule out further action. */
908     if (!is_active(unit))
909       return FALSE;
910     if (!unit->side->ingame)
911       return FALSE;
912     if (unit->side->finishedturn)
913       return FALSE;
914     if (!has_acp_left(unit))
915       return FALSE;
916     if (unit->plan
917 	 && (unit->plan->asleep
918 	    || unit->plan->reserve))
919       return FALSE;
920     /* Conditions that require further action provided
921        that it was not ruled out above. */
922     // HACK: We need to check action allowance flags rather than doing this.
923     if (acp_indep(unit))
924       return TRUE;
925     if (has_pending_action(unit))
926       return TRUE;
927     if (unit->plan)
928       return TRUE;
929     return FALSE;
930 }
931 
932 static int
unit_still_acting_no_plan(Unit * unit)933 unit_still_acting_no_plan(Unit *unit)
934 {
935     /* Conditions that always rule out further action. */
936     if (!is_active(unit))
937       return FALSE;
938     if (!unit->side->ingame)
939       return FALSE;
940     if (unit->side->finishedturn)
941       return FALSE;
942     if (!has_acp_left(unit))
943       return FALSE;
944     /* Conditions that require further action provided that it was not
945        ruled out above. */
946     // HACK: We need to check action allowance flags rather than doing this.
947     if (acp_indep(unit))
948       return TRUE;
949     if (has_pending_action(unit))
950       return TRUE;
951     return FALSE;
952 }
953 
954 /* Do a single unit's actions, up to the given limit or until it runs
955    out of things it wants to do (or something happens to it). */
956 
957 static int
move_one_unit_multiple(Unit * unit,int lim)958 move_one_unit_multiple(Unit *unit, int lim)
959 {
960     int num = 0, buzz = 0, acp1, i;
961     int rslt;
962 
963     /* If unit is incapable of acting right now, get out of here. */
964     if (unit->act == NULL
965         || (unit->act->initacp < 1
966             && !acp_indep(unit)))
967       return 0;
968     acp1 = unit->act->acp;
969     while (is_active(unit) && has_acp_left(unit)
970 	   && ((unit->plan && !unit->plan->asleep
971 		&& !unit->plan->reserve && !unit->plan->delayed)
972 	       || has_pending_action(unit))
973 	   && num < lim
974 	   && buzz < lim) {
975 #if (1) /* enable for more intense debugging */
976 	Dprintf("  Moving %s (%d/%d, buzz %d) with plan %s\n",
977 		unit_desig(unit), num, lim, buzz, plan_desig(unit->plan));
978 #endif
979         /* Unit may be dead, and thus cannot complete the rest of its actions.
980            Although kill_unit removes the unit from action vector, we may
981            not have had a chance to go back up to side_move_some_units to
982            discover this.
983            Tell side_move_some_units to go find another unit to move.
984            (Note that execute_action does check whether the unit is alive
985            or not, but why check in each called function when we can
986            nip things in the bud right here, right now? None of the
987            called functions can reasonably do anything with a dead unit.)
988         */
989         if (!alive(unit)) {
990             Dprintf("Tried to act with dead unit, %s!\n", unit_desig(unit));
991             break;
992         }
993 #if (0)
994 	/* Skip over AI-run units that have executed a task during
995 	   this run step, so that the AI gets a chance to react to the
996 	   result. */
997 	if (ai_controlled(unit)
998 	    && unit->plan->last_task_outcome != TASK_UNKNOWN
999 	    && unit->plan->last_task_outcome != TASK_PREPPED_ACTION)
1000 	  break;
1001 #endif
1002 	if (has_pending_action(unit)) {
1003 	    /* Save the action now in case the actor dies or wrecks. */
1004 	    latest_action->type = unit->act->nextaction.type;
1005 	    for (i = 0; i < MAXACTIONARGS; ++i) {
1006 	    	latest_action->args[i] = unit->act->nextaction.args[i];
1007 	    }
1008 	    latest_action->actee = unit->act->nextaction.actee;
1009 	    latest_action->next = unit->act->nextaction.next;
1010 
1011 	    /* Also save the latest known position of the actor. */
1012 	    latest_action_x = unit->x;
1013 	    latest_action_y = unit->y;
1014 	    /* Execute the action directly. */
1015 	    rslt = execute_action(unit, &(unit->act->nextaction));
1016 	    /* Trigger ai reaction for certain actions. */
1017 	    need_ai_action_reaction =
1018 		action_reaction_needed(latest_action->type, rslt);
1019 	    /* Clear the action.  Note that the unit might have changed
1020 	       to a non-acting type, so we have to check for act struct. */
1021 	    if (unit->act)
1022 	      unit->act->nextaction.type = ACTION_NONE;
1023 	    /* Also clear the busy flag. */
1024 	    unit->busy = FALSE;
1025 	    /* In any case, the game state is irrevocably altered. */
1026 	    gamestatesafe = FALSE;
1027 	    ++num;
1028 	} else if (unit->plan != NULL) {
1029 	    /* Even units that are asleep, in reserve, etc must execute
1030 	       any standing orders that apply. */
1031 	    if (unit->side
1032 		&& unit->side->orders
1033 		&& unit->plan->tasks == NULL
1034 		&& execute_standing_order(unit, TRUE)) {
1035 		planexecs += execute_plan(unit);
1036 		gamestatesafe = FALSE;
1037 		++buzz;
1038 	    }
1039 	    /* Similarly for formations. */
1040 	    if (unit->plan->formation && move_into_formation(unit)) {
1041 		planexecs += execute_plan(unit);
1042 		gamestatesafe = FALSE;
1043 		++buzz;
1044 	    }
1045 #if 0
1046 	    /* This replanning caused buzzing. It is sufficient to call
1047                ai_decide_plan at the start of each turn and after
1048                force_replan. Possibly, we should test for an empty task queue
1049                here, and replan in that case only. However, the AI works fine
1050                without any replanning. */
1051 
1052 	    /* Flag so that we run AI code in the near future (after
1053 	       run_game exits). */
1054 	    if (side_has_ai(unit->side))
1055 	      need_ai_planning = TRUE;
1056 #endif
1057 	    /* Get out of here if unit is set not to do anything on
1058 	       its own. */
1059 	    if (unit->plan->waitingfortasks
1060 		|| unit->plan->asleep
1061 		|| unit->plan->reserve
1062 		|| unit->plan->delayed)
1063 	      break;
1064 	    /* Normal plan execution. */
1065 	    planexecs += execute_plan(unit);
1066 	    record_ms();
1067 	    gamestatesafe = FALSE;
1068 	    ++buzz;
1069 	} else {
1070 	    run_warning("Planless \"%s\" was asked to act", unit_desig(unit));
1071 	    ++buzz;
1072 	}
1073 	/* If the unit is trying to do actions several times in this
1074 	   loop and and none of them are succeeding, something is
1075 	   wrong; blast the plan and eventually put the unit to
1076 	   sleep, if the problem persists. */
1077 	if (unit->act && unit->act->acp == acp1 && num > 1) {
1078 	    /* Blast the action. */
1079 	    unit->act->nextaction.type = ACTION_NONE;
1080 	    /* Blast the plan. */
1081 	    if (unit->plan)
1082 	      unit->plan->type = PLAN_PASSIVE;
1083 	    run_warning("\"%s\" trying multiple bad actions, clearing its plan",
1084 			unit_desig(unit));
1085 	}
1086     }
1087     return num;
1088 }
1089 
1090 /* Returns true if ais may need to react on a given action and result. */
1091 
1092 int
action_reaction_needed(int type,int rslt)1093 action_reaction_needed(int type, int rslt)
1094 {
1095     /* Special success flags for captures, overruns and builds that
1096        just completed a unit. */
1097     if (rslt == A_CAPTURE_SUCCEEDED
1098 	|| rslt == A_OVERRUN_SUCCEEDED
1099 	|| rslt == A_BUILD_COMPLETED) {
1100 	return TRUE;
1101 	/* Any other action returns A_ANY_DONE on success. */
1102     } else if (rslt == A_ANY_DONE
1103 	       /* These actions may change the tactical situation. */
1104 	       && ((type == ACTION_MOVE
1105 		    || type == ACTION_ENTER
1106 		    || type == ACTION_DISBAND
1107 		    || type == ACTION_CHANGE_TYPE
1108 		    || type == ACTION_CHANGE_SIDE)
1109 		   /* Also worry about offensive actions that kill or
1110 		      capture a unit. */
1111 		   ||((type == ACTION_ATTACK
1112 		       || type == ACTION_FIRE_AT
1113 		       || type == ACTION_FIRE_INTO
1114 		       || type == ACTION_DETONATE)
1115 		      && (history->prev->type == H_UNIT_KILLED
1116 			  || history->prev->type == H_UNIT_CAPTURED)))) {
1117 	return TRUE;
1118     }
1119     return FALSE;
1120 }
1121 
1122 /* This explicitly finishes out a side's activity for the turn. */
1123 
1124 void
finish_turn(Side * side)1125 finish_turn(Side *side)
1126 {
1127     int nextpriority;
1128     Side *side2, *side3;
1129 
1130     /* Flag the side as being done for this turn. */
1131     side->finishedturn = TRUE;
1132     /* Stop counting down our time consumption. */
1133     side->totaltimeused += (time(0) - side->turnstarttime);
1134     if (g_use_side_priority()) {
1135 	nextpriority = 9999;
1136 	for_all_sides(side2) {
1137 	    if (!side2->finishedturn
1138 		/* && side2->priority > curpriority */
1139 		&& side2->priority < nextpriority) {
1140 		nextpriority = side2->priority;
1141 	    }
1142 	    if (!side2->finishedturn && side2->priority < curpriority)
1143 	      run_warning(
1144 "%s not finished, but priority is %d, less than current %d",
1145 			  side_desig(side2), side2->priority, curpriority);
1146 	}
1147 	if (nextpriority > curpriority)
1148 	  curpriority = nextpriority;
1149     }
1150     /* Clue everybody in. */
1151     if (g_use_side_priority()) {
1152 	/* Several sides may change, if current priority changes. */
1153 	for_all_sides(side2) {
1154 	    for_all_sides(side3) {
1155 		update_side_display(side2, side3, TRUE);
1156 	    }
1157 	}
1158     } else {
1159 	/* Only the turn-finishing side changes. */
1160 	for_all_sides(side2) {
1161 	    update_side_display(side2, side, TRUE);
1162 	}
1163     }
1164     Dprintf("%s finished its turn.\n", side_desig(side));
1165 }
1166 
1167 void
set_play_rate(int slow,int fast)1168 set_play_rate(int slow, int fast)
1169 {
1170     if (slow < 0 || fast < 0 || fast < slow) {
1171 	run_warning("Bad play rates slow=%d fast=%d, ignoring", slow, fast);
1172 	return;
1173     }
1174     slow_play_rate = slow;
1175     fast_play_rate = fast;
1176 }
1177 
1178 /* Resignation, possibly giving away any remaining units. */
1179 
1180 void
resign_game(Side * side,Side * side2)1181 resign_game(Side *side, Side *side2)
1182 {
1183     /* Nothing to do if we're not in the game. */
1184     if (!side->ingame)
1185       return;
1186     notify_all_of_resignation(side, side2);
1187     side_loses(side, side2, -1);
1188 }
1189 
1190 /* This is true if there is any kind of realtime limit on the game. */
1191 
1192 int
realtime_game(void)1193 realtime_game(void)
1194 {
1195     return (g_rt_for_game() > 0
1196     	    || g_rt_per_side() > 0
1197     	    || g_rt_per_turn() > 0);
1198 }
1199 
1200 /* Pass NULL to see if all sides are now willing to save the game. */
1201 
1202 int
all_others_willing_to_save(Side * side)1203 all_others_willing_to_save(Side *side)
1204 {
1205     Side *side2;
1206 
1207     for_all_sides(side2) {
1208 	if (side != side2 && !side2->willingtosave)
1209 	  return FALSE;
1210     }
1211     return TRUE;
1212 }
1213 
1214 /* Pass NULL to see if all sides are now willing to declare a draw. */
1215 
1216 int
all_others_willing_to_quit(Side * side)1217 all_others_willing_to_quit(Side *side)
1218 {
1219     Side *side2;
1220 
1221     for_all_sides(side2) {
1222 	if (side != side2 && !side2->willingtodraw)
1223 	  return FALSE;
1224     }
1225     return TRUE;
1226 }
1227 
1228 /* This forces an end to the game directly. */
1229 
1230 void
end_the_game(void)1231 end_the_game(void)
1232 {
1233     Side *side;
1234 
1235     Dprintf("The game is over.\n");
1236     /* Make sure everybody sees this. */
1237     notify_all("END OF THE GAME!");
1238     record_event(H_GAME_ENDED, ALLSIDES);
1239     /* Set the global that indicates the game is over for everybody. */
1240     endofgame = TRUE;
1241     end_history();
1242     /* (should compute final scoring) */
1243     record_into_scorefile();
1244     /* Done with internal state change, now echo onto displays. */
1245     for_all_sides(side) {
1246 	/* Enable the display of everything in the world. */
1247 	if (!side->see_all)
1248 	  side->may_set_show_all = TRUE;
1249 	/* ...by default display it all. */
1250 	side->show_all = TRUE;
1251     	if (side_has_display(side)) {
1252     	    update_turn_display(side, TRUE);
1253     	    /* (should update side's view of all sides?) */
1254     	    update_side_display(side, side, TRUE);
1255 	    /* Update legends and their positions as new terrain comes into view. */
1256 	    place_legends(side);
1257 	    /* Redraw legends in new positions. */
1258 	    update_area_display(side);
1259     	}
1260     }
1261     dump_statistics();
1262     /* We've done everything the kernel needs to have done; it's now up to
1263        the interface to decide when to exit. */
1264     ok_to_exit = TRUE;
1265 }
1266 
1267 /* Run any per-side research activities. */
1268 
1269 void
run_side_research(void)1270 run_side_research(void)
1271 {
1272     int a, m, consump, amt, totalweight = 0;
1273     long maxrp, rp;
1274     Side *side;
1275     Obj *choice = NULL, *nextgoal = NULL;
1276 
1277     /* No research if there are no advances. */
1278     if (numatypes == 0)
1279       return;
1280     if (!g_side_can_research())
1281       return;
1282     for_all_sides(side) {
1283 	/* The indepside might just be done here. */
1284 	if (side == indepside
1285 	    && (g_indepside_can_research() != TRUE
1286  	        || g_indepside_has_treasury() != TRUE)) {
1287  	    continue;
1288  	}
1289 	/* Our wise men are resting. Don't disturb them. */
1290     	if (side->research_topic == NONATYPE)
1291 	  continue;
1292 	/* Our wise men are waiting for something to do. */
1293 	if (side->research_topic == NOADVANCE) {
1294 	    if (side_has_ai(side)) {
1295 		/* Do nothing. ai_plan_research will pick a new advance. */
1296 	    } else if (side->autoresearch) {
1297 		auto_pick_side_research(side);
1298 	    }
1299 	    /* We are not ready to proceed until the human player or
1300 	       the computer has picked a new research topic. */
1301 	    continue;
1302 	}
1303 	a = side->research_topic;
1304 	/* Compute the maximum number of rps that our material limits
1305 	   allow us to add. */
1306 	maxrp = VARHI;
1307 	for_all_material_types(m) {
1308 	    consump = am_consumption_per_rp(a, m);
1309 	    if (consump > 0) {
1310 		/* Check that all required materials have a treasury. */
1311 	    	if (!side_has_treasury(side, m))
1312 		  return;
1313 		rp = side->treasury[m] / consump;
1314 		maxrp = min(maxrp, rp);
1315 	    }
1316 	}
1317 	/* If research is not limited by materials something is wrong. */
1318 	if (maxrp == VARHI) {
1319 	    run_error("research is not limited by materials");
1320 	}
1321 	/* Don't spend more than needed to complete the advance! */
1322 	maxrp = min(maxrp, a_rp(a) - side->advance[a]);
1323 	/* Only proceed if we are still doing some research. */
1324 	if (maxrp > 0) {
1325 	    side->advance[a] += maxrp;
1326 	    /* Make sure the research window is updated. */
1327 	    if (side_has_display(side)) {
1328 		update_research_display(side);
1329 	    }
1330 	    if (side->advance[a] >= a_rp(a)) {
1331 		side->advance[a] = DONE;
1332 		/* Update research and build vectors. */
1333 		update_canresearch_vector(side);
1334 		update_canbuild_vector(side);
1335 		/* (TODO: Replace "Your wise men discover" with a custom
1336 		    string.) */
1337 		notify(side, "Your wise men discover %s!", a_type_name(a));
1338 		side->research_topic = NOADVANCE;
1339 		nextgoal = lispnil;
1340 		choice = lispnil;
1341 		if (a == side->research_goal) {
1342 		    side->research_goal = NONATYPE;
1343 		    nextgoal = a_ai_next_goal(a);
1344 		}
1345 		if (nextgoal != lispnil) {
1346 		    if (consp(nextgoal)) {
1347 			choice = choose_side_research_goal_from_weighted_list(
1348 				    nextgoal, &totalweight, side);
1349 		    }
1350 		    else {
1351 			choice = eval(nextgoal);
1352 		    }
1353 		}
1354 		if (choice != lispnil) {
1355 		    if (symbolp(choice))
1356 		      choice = eval_symbol(choice);
1357 		    if (atypep(choice)) {
1358 			if (is_advance_type(c_number(choice)))
1359 			  side->research_goal = c_number(choice);
1360 			else
1361 			  run_warning(
1362 "Invalid research goal provided by advance, %s, upon reserach completion",
1363 				      a_type_name(a));
1364 		    }
1365 		    else
1366 		      run_warning(
1367 "Invalid research goal provided by advance, %s, upon reserach completion",
1368 				  a_type_name(a));
1369 		}
1370 		if (side_has_ai(side)) {
1371 		    /* Do nothing. ai_plan_research will pick a new advance. */
1372 		} else if (side->autoresearch) {
1373 		    auto_pick_side_research(side);
1374 		}
1375 		/* Make sure the research window is updated. */
1376 		if (side_has_display(side)) {
1377 		    update_research_display(side);
1378 		}
1379 	    }
1380 	    /* Consume the materials. */
1381 	    for_all_material_types(m) {
1382 		consump = am_consumption_per_rp(a, m);
1383 		if (consump > 0) {
1384 		    amt = maxrp * consump;
1385 		    side->treasury[m] -= amt;
1386 		}
1387 	    }
1388 	}
1389     }
1390 }
1391 
1392 /* 	Advanced unit and advance code for Xconq.
1393      	Copyright (C) 1998 Hans Ronne.
1394 	Copyright (C) 2004 Eric A. McDonald.
1395 */
1396 
1397 void
update_canresearch_vector(Side * side)1398 update_canresearch_vector(Side *side)
1399 {
1400     int a, a2;
1401 
1402     update_side_research_goal_availability(side);
1403     for_all_advance_types(a) {
1404 	/* We can't research advances that are already done. */
1405 	if (has_advance(side, a)) {
1406 	    side->canresearch[a] = FALSE;
1407 	    continue;
1408 	}
1409 	side->canresearch[a] = TRUE;
1410 	/* Test for required advances. */
1411 	for_all_advance_types(a2) {
1412 	    if (aa_needed_to_research(a, a2) && !has_advance(side, a2)) {
1413 		side->canresearch[a] = FALSE;
1414 		break;
1415 	    }
1416 	    if (aa_precludes(a2, a) && has_advance(side, a2)) {
1417 		side->canresearch[a] = FALSE;
1418 		break;
1419 	    }
1420 	}
1421     }
1422 }
1423 
1424 void
update_side_research_goal_availability(Side * side)1425 update_side_research_goal_availability(Side *side)
1426 {
1427     int updated = TRUE;
1428     int a = NONATYPE, a2 = NONATYPE;
1429 
1430     assert_error(side, "Attempted to access a NULL side");
1431     while (updated) {
1432 	updated = FALSE;
1433 	for_all_advance_types(a) {
1434 	    if (side->research_precluded[a])
1435 	      continue;
1436 	    for_all_advance_types(a2) {
1437 		if ((aa_precludes(a2, a) && has_advance(side, a2))
1438 		    || (side->research_precluded[a2]
1439 			&& aa_needed_to_research(a, a2))) {
1440 			side->research_precluded[a] = TRUE;
1441 			updated = TRUE;
1442 			break;
1443 		    }
1444 	    } /* a2 */
1445 	    if (updated)
1446 	      break;
1447 	} /* a */
1448     } /* while updated */
1449 }
1450 
1451 /* Call this whenever the list of buildable/developable types changes. */
1452 
1453 void
update_canbuild_vector(Side * side)1454 update_canbuild_vector(Side *side)
1455 {
1456     int a, u;
1457 
1458     for_all_unit_types(u) {
1459 	/* Start out optimistic, then following code may disallow some
1460            types. */
1461 	side->canbuild[u] = TRUE;
1462 	side->candevelop[u] = TRUE;
1463 	/* Units with zero cp are unbuildable by definition. */
1464 	if (u_cp(u) == 0) {
1465 	    side->canbuild[u] = FALSE;
1466 	    side->candevelop[u] = FALSE;
1467 	    continue;
1468 	}
1469 	/* First test if this unit type is at all allowed on our side. */
1470 	if (!type_allowed_on_side(u, side)) {
1471 	    side->canbuild[u] = FALSE;
1472 	    side->candevelop[u] = FALSE;
1473 	    continue;
1474 	}
1475 	/* Then test if we have the required tech to both build and own
1476 	   this type. */
1477 	if (u_tech_to_build(u) > 0) {
1478 	    /* Don't "continue" in this group, because we need to set
1479 	       both build and develop cases correctly. */
1480 	    if (side->tech[u] < u_tech_to_own(u)
1481 		|| side->tech[u] < u_tech_to_build(u))
1482 	      side->canbuild[u] = FALSE;
1483 	    if (side->tech[u] >= u_tech_max(u))
1484 	      side->candevelop[u] = FALSE;
1485 	}
1486 	/* Consider the effect of advances on ability to build/develop. */
1487 	if (numatypes > 0) {
1488 	    /* Test for an obsoleting advance. */
1489 	    a = u_obsolete(u);
1490 	    if (a != NONATYPE && has_advance(side, a)) {
1491 		side->canbuild[u] = FALSE;
1492 		side->candevelop[u] = FALSE;
1493 		continue;
1494 	    }
1495 	    /* Then test for required advances. */
1496 	    for_all_advance_types(a) {
1497 		if (ua_needed_to_build(u, a) && !has_advance(side, a)) {
1498 		    side->canbuild[u] = FALSE;
1499 		    side->candevelop[u] = FALSE;
1500 		    break;
1501 		}
1502 	    }
1503 	}
1504     }
1505 }
1506 
1507 void
update_cancarry_vector(Side * side)1508 update_cancarry_vector(Side *side)
1509 {
1510     Unit *unit;
1511     int u;
1512 
1513     for_all_unit_types(u) {
1514     	side->cancarry[u] = FALSE;
1515     	for_all_side_units(side, unit) {
1516 	    if (mobile(unit->type)
1517 		&& could_carry(unit->type, u)) {
1518 		side->cancarry[u] = TRUE;
1519 		break;
1520 	    }
1521     	}
1522     }
1523 }
1524 
1525 static void
take_all_from_treasury(Unit * unit)1526 take_all_from_treasury(Unit *unit)
1527 {
1528     int m, amount;
1529 
1530     /* Borrow materials from treasury if it exists. */
1531     for_all_material_types(m) {
1532 	if (side_has_treasury(unit->side, m)
1533 	    && um_takes_from_treasury(unit->type, m)) {
1534 	    /* Don't exceed the unit's storage capacity unless there is no
1535 	        capacity, in which case take the lot. */
1536 	    if (um_storage_x(unit->type, m) <= 0)
1537 	        amount = unit->side->treasury[m];
1538 	    else
1539 	        amount = min(unit->side->treasury[m],
1540 			     um_storage_x(unit->type, m) - unit->supply[m]);
1541 	    unit->supply[m] += amount;
1542 	    unit->side->treasury[m] -= amount;
1543 	}
1544     }
1545 }
1546 
1547 static void
give_all_to_treasury(Unit * unit)1548 give_all_to_treasury(Unit *unit)
1549 {
1550     int m, amount;
1551 
1552     /* Return all unused materials to treasury. */
1553     for_all_material_types(m) {
1554 	if (side_has_treasury(unit->side, m)
1555 	    && um_gives_to_treasury(unit->type, m)) {
1556 	    amount = min(unit->supply[m],
1557 			 g_treasury_size() - unit->side->treasury[m]);
1558 	    unit->side->treasury[m] += amount;
1559 	    unit->supply[m] -= amount;
1560 	}
1561     }
1562 }
1563 
1564 /* Called from run_turn_start. */
1565 
1566 void
run_people()1567 run_people()
1568 {
1569 }
1570 
1571 /* Main city emulating routine. Called by run_turn_start in run2.c. */
1572 
1573 static int *rau_incrs;
1574 
1575 void
run_advanced_units()1576 run_advanced_units()
1577 {
1578     Unit *unit, *unit2;
1579 
1580     for_all_units(unit) {
1581 	Side	*side;
1582 	int	a, m, x, y, oldsize;
1583 
1584 	/* Only do this for cities. */
1585 	if (!u_advanced(unit->type))
1586 	  continue;
1587 
1588 	/* Skip if this is an indep which cannot produce or consume materials. */
1589 	if (indep(unit) &! g_indepside_has_economy())
1590 	  continue;
1591 
1592 	/* Units still under construction or off-area can't do anything. */
1593 	if (!completed(unit) || !in_play(unit))
1594 	  continue;
1595 
1596 	/* Set size to 1 if not defined. */
1597 	if (!unit->size)
1598 	  unit->size = 1;
1599 	oldsize = unit->size;
1600 
1601 	/* Break here if no material types exist. */
1602 	if (!nummtypes)
1603 	  continue;
1604 
1605 	/* Make sure landuse is optimize before collecting materials. */
1606 	allocate_used_cells(unit);
1607 
1608 	/* Zero the production cache. */
1609 	for_all_material_types (m)
1610 	    unit->production[m] = 0;
1611 	/* Collect materials from cells controlled by the city. */
1612 	for_all_cells_within_reach(unit, x, y) {
1613 	    int m;
1614 
1615 	    if (!inside_area(x, y))
1616 	  	continue;
1617 	    if (user_at(x, y) == unit->id)
1618 	      for_all_material_types(m)
1619 		unit->production[m] += production_at(x, y, m);
1620 	}
1621 	/* Support for city improvements. */
1622 
1623 	/* Note: an occupant or facility will typically have either an
1624 	   additive or a multiplicative effect on material
1625 	   production. However, it is possible for it to have
1626 	   both. The default additive effect is zero, and the default
1627 	   multiplicative effect is 1 (100 %). If the multiplicative
1628 	   effect is set to zero, the occupant will prevent all
1629 	   production of the specified material. A negative additive
1630 	   effect means that the occupant is consuming some material
1631 	   each turn. */
1632 
1633 	for_all_material_types(m) {
1634 
1635 	    /* First compute additive effect of each occupant/facility. */
1636 	    for_all_occupants(unit, unit2) {
1637 	    	if (is_active(unit2)) {
1638 	    	    unit->production[m] += um_occ_add_production(unit2->type, m);
1639 	    	}
1640 	    }
1641 	    /* Then compute additive effect of each completed advance. */
1642 	    if (unit->side) {
1643 		for_all_advance_types(a)
1644 		  if (unit->side->advance[a] == DONE)
1645 		    unit->production[m] += am_adv_add_production(a, m);
1646 	    }
1647 
1648 	    /* Then factor in multiplicative effect (in %) of each
1649                occupant/facility. */
1650 	    for_all_occupants(unit, unit2) {
1651 	    	if (is_active(unit2)) {
1652 		      unit->production[m] =
1653 		        (unit->production[m] * um_occ_mult_production(unit2->type, m)) / 100;
1654 	    	}
1655 	    }
1656 	    /* Then factor in multiplicative effect (in %) of each
1657                completed advance. */
1658 	    if (unit->side) {
1659 		for_all_advance_types(a)
1660 		  if (unit->side->advance[a] == DONE)
1661 		    unit->production[m] =
1662 		      (unit->production[m] * am_adv_mult_production(a, m))
1663 		      / 100;
1664 	    }
1665 
1666 	    {
1667 		int m2, anyconversion = FALSE, tot = 0;
1668 
1669 		for_all_material_types(m2) {
1670 		    if (rau_incrs == NULL)
1671 		      rau_incrs = (int *) xmalloc(nummtypes * sizeof(int));
1672 		    rau_incrs[m2] = 0;
1673 		    if (mm_conversion(m, m2) > 0
1674 			&& unit->side->c_rates != NULL
1675 			&& unit->side->c_rates[m2] > 0) {
1676 			anyconversion = TRUE;
1677 			tot += unit->side->c_rates[m2];
1678 		    }
1679 		}
1680 		while (anyconversion && unit->production[m] > 0) {
1681 		    for_all_material_types(m2) {
1682 			if (mm_conversion(m, m2) > 0
1683 			    && unit->side->c_rates != NULL
1684 			    && unit->side->c_rates[m2] > 0) {
1685 			    rau_incrs[m2] += unit->side->c_rates[m2];
1686 			}
1687 		    }
1688 		    for_all_material_types(m2) {
1689 			if (rau_incrs[m2] >= tot
1690 			    && unit->production[m] > 0) {
1691 			    rau_incrs[m2] -= tot;
1692 			    unit->production[m2] += 1;
1693 			    unit->production[m] -= 1;
1694 			}
1695 		    }
1696 		}
1697 	    }
1698 	}
1699 	    /* Finally add production to unit supply. Check that we have room and
1700 	    transfer any excess materials to the treasury if possible. */
1701 	for_all_material_types(m) {
1702 	    int space, amount;
1703 
1704 	    space = um_storage_x(unit->type, m) - unit->supply[m];
1705 	    if (unit->production[m] <= space) {
1706 		unit->supply[m] += unit->production[m];
1707 	    } else {
1708 	    	unit->supply[m] = um_storage_x(unit->type, m);
1709 	    	amount = unit->production[m] - space;
1710 		if (side_has_treasury(unit->side, m)
1711 		    && um_gives_to_treasury(unit->type, m)) {
1712 			amount = min(amount, g_treasury_size() - unit->side->treasury[m]);
1713 			unit->side->treasury[m] += amount;
1714 		}
1715 	    }
1716 	}
1717 	/* Growth or starvation. */
1718 	run_population(unit);
1719 	/* Fixes crashes when the unit starved to death. */
1720 	if (!in_play(unit))
1721 	  continue;
1722 	/* Optimize landuse again in case city size changed. */
1723 	if (unit->size != oldsize) {
1724 	    allocate_used_cells(unit);
1725 	    /* Also reflect any changes of the city size text. */
1726 	    for_all_sides(side) {
1727 		if (side->see_all) {
1728 		    update_cell_display(side, unit->x, unit->y,
1729 					UPDATE_ALWAYS);
1730 		} else if (side_sees_unit(side, unit)
1731 		    || side_tracking_unit(side, unit)
1732 		    || cover(side, unit->x, unit->y) > 0) {
1733 			see_cell(side, unit->x, unit->y);
1734 		}
1735 	    }
1736 	}
1737     }
1738 }
1739 
1740 /* Compute the total production of the given material at the given
1741    location within a city radius. */
1742 
1743 int
production_at(int x,int y,int m)1744 production_at(int x, int y, int m)
1745 {
1746     int prod = 0, t2 = NONTTYPE;
1747 
1748     prod = tm_prod_from_terrain(terrain_at(x, y), m);
1749     /* Add bonuses for all aux terrain types. */
1750     for_all_aux_terrain_types(t2) {
1751 	if (aux_terrain_defined(t2)
1752 	    && aux_terrain_at(x, y, t2)
1753 	    && (tm_prod_from_terrain(t2, m) > 0)) {
1754 	    prod += tm_prod_from_terrain(t2, m);
1755 	}
1756     }
1757     return prod;
1758 }
1759 
1760 /* Starve or grow city population depending on food supply. */
1761 
1762 void
run_population(Unit * unit)1763 run_population(Unit *unit)
1764 {
1765     int starved = FALSE;
1766     int u = unit->type;
1767     int a, m, u2;
1768     Side *side = unit->side;
1769 
1770     /* If we have no people we are done. */
1771     if (!g_people())
1772         return;
1773     /* Loot the treasury. */
1774     take_all_from_treasury(unit);
1775     /* Consume necessary materials (food) in proportion to unit size. */
1776     for_all_material_types(m) {
1777 	unit->supply[m] -= unit->size * um_consumption_per_size(u, m);
1778 	if (unit->supply[m] < 0) {
1779 	    /* Don't allow negative supply. */
1780 	    unit->supply[m] = 0;
1781 	    /* Trigger starvation. */
1782 	    starved = TRUE;
1783 	}
1784     }
1785     /* Return remaining materials to treasury. */
1786     give_all_to_treasury(unit);
1787     /* Starvation! (Size Loss) */
1788     if (starved && (unit->size > u_size_min(u))) {
1789 	/* Shrink size by one. */
1790 	unit->size -= 1;
1791 	/* Run warning. */
1792 	if (unit->size > 0) {
1793 	    notify(side, "The people in %s are starving!",
1794 		   unit_handle(side, unit));
1795 	} else {
1796 	    notify(side, "%s is no more. The people starved to death.",
1797 		   unit_handle(side, unit));
1798 	    kill_unit(unit, H_UNIT_STARVED);
1799 	}
1800 	/* Done with handling starvation. */
1801 	return;
1802     }
1803     /* Growth (Size Gain) */
1804     /* First check if we have reached our max size. */
1805     if (unit->size >= u_size_max(u))
1806       return;
1807     /* Then check if we have the required advances for the next size. */
1808     for_all_advance_types(a) {
1809 	if (side->advance[a] != DONE
1810 	    && ua_size_limit_without_adv(u, a) <= unit->size) {
1811 	    notify(side, "%s needs %s advance to grow in size.",
1812 		   unit_handle(side, unit), a_type_name(a));
1813 	    return;
1814 	}
1815     }
1816     /* Then check if we have the required facilities for the next size. */
1817     for_all_unit_types(u2) {
1818 	if (uu_size_limit_without_occ(u, u2) <= unit->size) {
1819 	    int	hasocc = FALSE;
1820 	    Unit *unit2;
1821 
1822 	    for_all_occupants(unit, unit2) {
1823 		if (is_active(unit2) && unit2->type == u2) {
1824 		    hasocc = TRUE;
1825 		    break;
1826 		}
1827 	    }
1828 	    if (!hasocc) {
1829 		notify(side, "%s needs a %s to grow in size.",
1830 		       unit_handle(side, unit), u_type_name(u2));
1831 		return;
1832 	    }
1833 	}
1834     }
1835     /* Loot the treasury again, in case storage space was limiting before
1836 	consumption. */
1837     take_all_from_treasury(unit);
1838     /* Now check if we have enough supplies left to grow in size. */
1839     /*! \todo Consider occupant effects on growth consumption. */
1840     for_all_material_types(m) {
1841 	if (unit->supply[m] < unit->size * um_consumption_to_grow(u, m)) {
1842 	    /* Return borrowed stuff to treasury. */
1843 	    give_all_to_treasury(unit);
1844 	    return;
1845 	}
1846     }
1847     /* If we got this far we are ready for a size increase! */
1848     for_all_material_types(m) {
1849 	int consump = unit->size * um_consumption_to_grow(u, m);
1850 	/*! \todo Consider occupant effects on growth consumption. */
1851 	/* Use up more supplies as required to prepare growth. */
1852 	unit->supply[m] -= consump;
1853     }
1854     /* Then increase the size. */
1855     unit->size += 1;
1856     /* And brag about it. */
1857     notify(side, "%s prospers and reaches size %d.",
1858 	   unit_handle(side, unit), unit->size);
1859     /* Return borrowed stuff to treasury. */
1860     give_all_to_treasury(unit);
1861 }
1862 
1863 #if (0) // A few leftover snippets worth considering.
1864 void
run_construction(Unit * unit)1865 run_construction(Unit *unit)
1866 {
1867 
1868     /* Skip if this is an indep which cannot build. */
1869     if (indep(unit) && !g_indepside_can_build())
1870       return;
1871 
1872     update_unit_acp_display(unit->side, unit, TRUE);
1873     /* Things have changed. */
1874     gamestatesafe = FALSE;
1875 }
1876 #endif
1877 
1878 /* Do research until supply of its limiting material is gone. */
1879 
1880 void
run_research(Unit * unit)1881 run_research(Unit *unit)
1882 {
1883     int m, a, lim = PROPHI;
1884 
1885     /* Check if independent units are allowed to do research. */
1886     if (indep(unit) && !g_indepside_can_research())
1887 	return;
1888     /* First test if we are already done, and select new research in
1889        that case. */
1890     if (has_advance(unit->side, unit->curadvance)
1891 	|| unit->curadvance == NOADVANCE) {
1892 	/* Set current advance to NOADVANCE to signal that we are idle. */
1893 	unit->curadvance = NOADVANCE;
1894 	/* Pick new research manually for human players. */
1895 	if (side_has_display(unit->side)
1896 	    && !side_has_ai(unit->side))
1897 	  unit_research_dialog(unit);
1898 	/* Pick new research automatically for AIs. */
1899 	else
1900 	  auto_pick_unit_research(unit);
1901     }
1902     /* Only proceed if we now have a new advance. */
1903     a = unit->curadvance;
1904     if (a == DONE)
1905       return;
1906     /* Loot the treasury. */
1907     take_all_from_treasury(unit);
1908     /* Loop until break. */
1909     while (1) {
1910 	/* Find the material whose supply limits current research. */
1911 	for_all_material_types(m) {
1912 	    if (am_consumption_per_rp(a, m) > 0) {
1913 		lim = min(lim, (int)((float) unit->supply[m] /
1914 			       am_consumption_per_rp(a, m)));
1915 	    }
1916 	}
1917 	/* Don't do more research than needed to complete the advance though. */
1918 	lim = min(lim,  a_rp(a) - unit->side->advance[a]);
1919 	/* Then do research to the limit. */
1920 	unit->side->advance[a] += lim;
1921 	/* Reduce all supplies accordingly. */
1922 	for_all_material_types(m) {
1923 	    if (am_consumption_per_rp(a, m) > 0) {
1924 		unit->supply[m] -= lim * am_consumption_per_rp(a, m);
1925 	    }
1926 	}
1927 	/* Check if research has been completed. */
1928 	if (unit->side->advance[a] >= a_rp(a)) {
1929 	    Unit *unit2;
1930 
1931 	    /* Set current advance to done. */
1932 	    unit->side->advance[a] = DONE;
1933 	    /* Update research and build vectors. */
1934 	    update_canresearch_vector(unit->side);
1935 	    update_canbuild_vector(unit->side);
1936 	    /* Notify the units side about it. */
1937 	    /* (TODO: Change "wise men in" to be a customizable string.) */
1938 	    /* (TODO: Change "discover" to be a customizable string.) */
1939 	    notify(unit->side, "Your wise men in %s discover %s!",
1940 		   unit->name, a_type_name(a));
1941 	    /* Pick new research for all involved units. */
1942 	    if (side_has_display(unit->side)
1943 	          && !side_has_ai(unit->side)) {
1944 		for_all_side_units(unit->side, unit2) {
1945 		    if (!u_advanced(unit2->type))
1946 			continue;
1947 		    /* Reallocate units on auto that took part in this
1948 		       advance. */
1949 		    if (unit2->curadvance == a) {
1950 			auto_pick_unit_research(unit2);
1951 		    /* Detect idle units on non-auto. */
1952 		    } else if (unit2->curadvance == a) {
1953 			unit2->curadvance = 0;
1954 			unit_research_dialog(unit2);
1955 		    }
1956     		}
1957 	    } else {
1958 		for_all_side_units(unit->side, unit2) {
1959 		    if (!u_advanced(unit2->type))
1960 		      continue;
1961 		    if (unit2->curadvance == a)
1962 		      auto_pick_unit_research(unit2);
1963 		}
1964 	    }
1965 	/* Research ended because we ran out of materials. */
1966 	} else {
1967 	    unit->researchdone = TRUE;
1968 	    break;
1969     	}
1970     }
1971     /* Return all materials to treasury. */
1972     give_all_to_treasury(unit);
1973 }
1974 
1975 /* Free all used cells and redistribute them for optimal limiting
1976    material production (usually food) if the city belongs to an AI or
1977    is independent. If it belongs to a human player, only allocate new
1978    used cells automatically. Don't change old allocations that may
1979    differ from automatic ones intentionally.  */
1980 
1981 void
allocate_used_cells(Unit * unit)1982 allocate_used_cells(Unit *unit)
1983 {
1984 	int	x, y, a, i, m, mlim = 0, lim = 0;
1985 	int u = unit->type;
1986 	Unit *unit2;
1987 
1988 	/* Set max used cells to unit size. */
1989 	unit->maxcells = unit->size;
1990 	if (u_use_own_cell(u))
1991 	    ++(unit->maxcells);
1992 	/* First compute additive effect of each occupant/facility. */
1993 	for_all_occupants(unit, unit2) {
1994 		if (is_active(unit2)) {
1995 			unit->maxcells += uu_occ_add_maxcells(u, unit2->type);
1996 		}
1997 	}
1998 	/* Then compute additive effect of completed advances. */
1999 	for_all_advance_types(a) {
2000 		if (has_advance(unit->side, a)) {
2001 			unit->maxcells += ua_adv_add_maxcells(u, a);
2002 		}
2003 	}
2004 	/* Then factor in multiplicative effect (in %) of each
2005 	occupant/facility. */
2006 	for_all_occupants(unit, unit2) {
2007 		if (is_active(unit2)) {
2008 			unit->maxcells = (unit->maxcells * uu_occ_mult_maxcells(u, unit2->type)) / 100;
2009 		}
2010 	}
2011 	/* Then factor in multiplicative effect (in %) of completed advances. */
2012 	for_all_advance_types(a) {
2013 		if (has_advance(unit->side, a)) {
2014 			unit->maxcells = (unit->maxcells * ua_adv_mult_maxcells(u, a)) / 100;
2015 		}
2016 	}
2017 	/* Check the number of used cells. */
2018 	unit->usedcells = 0;
2019 	for_all_cells_within_reach(unit, x, y) {
2020 		if (!inside_area(x, y))
2021 	    	    continue;
2022 		if (user_at(x, y) == unit->id)
2023 		    unit->usedcells += 1;
2024 	}
2025 	/* Find the limiting material for population maintenance. */
2026 	for_all_material_types(m) {
2027 		if (um_consumption_per_size(u, m) > lim) {
2028 			lim = um_consumption_per_size(u, m);
2029 			mlim = m;
2030 		}
2031 	}
2032 
2033 	/* Free all of this unit's doubtful cells within reach. */
2034 	for_all_cells_within_reach(unit, x, y) {
2035 		/* Skip if not inside area */
2036 		if (!inside_area(x, y))
2037 		    continue;
2038 		/* Free cells used by the unit itself if it is independent or
2039 		played by an AI. */
2040 		if (user_at(x, y) == unit->id
2041 		    && (indep(unit) || side_has_ai(unit->side))) {
2042 			set_user_at(x, y, NOUSER);
2043 			unit->usedcells -= 1;
2044 		} else if (user_at(x, y) != NOUSER && unit_at(x, y) != NULL) {
2045 			/* Also free cells used by enemy side if we have a unit in
2046 			the cell. */
2047 			for_all_stack(x, y, unit2) {
2048 				if (unit2->side && unit2->side == unit->side) {
2049 					kick_out_enemy_users(unit->side, x, y);
2050 					break;
2051 				}
2052 			}
2053 		}
2054 	}
2055 	/* May want to use own cell automatically. */
2056 	if (u_use_own_cell(u) && user_at(unit->x, unit->y) == NOUSER) {
2057 		set_user_at(unit->x, unit->y, unit->id);
2058 		unit->usedcells += 1;
2059 	}
2060 	/* Then select new cells up to unit size */
2061 	for (i = unit->usedcells + 1; i <= unit->maxcells; i++) {
2062 		int prod, tmpprod = 0, tmpx = unit->x, tmpy = unit->y;
2063 
2064 		for_all_cells_within_reach(unit, x, y) {
2065 			/* Skip if not inside area */
2066 			if (!inside_area(x, y))
2067 			    continue;
2068 			/* Skip if cell already is in use */
2069 			if (user_at(x, y) != NOUSER)
2070 			    continue;
2071 			/* Skip if cell is invisible to unit */
2072 			if (!terrain_visible(unit->side, x, y))
2073 			    continue;
2074 			/* Skip if untrusted side has a unit in the cell */
2075 			if (unit_at(x, y) != NULL) {
2076 				int enemy = FALSE;
2077 				for_all_stack(x, y, unit2) {
2078 					if (!trusted_side(unit->side, unit2->side)) {
2079 						enemy = TRUE;
2080 						break;
2081 					}
2082 				}
2083 				if (enemy)
2084 				    continue;
2085 			}
2086 			/* Make this tmp used cell if it produces more limiting
2087 			material than previous tmp used cell or if the previous
2088 			tmp cell is already in use. */
2089 			prod = production_at(x, y, mlim);
2090 			if ((prod > tmpprod) || (user_at(tmpx, tmpy) != NOUSER)) {
2091 				tmpprod = prod;
2092 				tmpx = x;  tmpy = y;
2093 			}
2094 		}
2095 		/* Make tmp used cell permanently used if it is unused. */
2096 		if (user_at(tmpx, tmpy) == NOUSER) {
2097 			set_user_at(tmpx, tmpy, unit->id);
2098 			unit->usedcells += 1;
2099 		}
2100 	}
2101 }
2102 
2103 /* Can't use a cell occupied by an enemy unit. */
2104 
2105 void
kick_out_enemy_users(Side * side,int x,int y)2106 kick_out_enemy_users(Side *side, int x, int y)
2107 {
2108     Unit *unit;
2109 
2110     /* Nothing to do if no user layer. */
2111     if (!user_defined())
2112       return;
2113     /* Return if nobody is using the cell. */
2114     if (user_at(x, y) == NOUSER)
2115       return;
2116     /* Else find the user. */
2117     unit = find_unit(user_at(x, y));
2118     /* Return if the user belongs to the same or a friendly side. */
2119     if (in_play(unit) && trusted_side(unit->side, side))
2120       return;
2121 
2122     /* Mark the cell as unused. */
2123     set_user_at(x, y, NOUSER);
2124     /* Reduce the former user's cells. */
2125     if (in_play(unit))
2126       unit->usedcells -= 1;
2127 }
2128 
2129 /* Now picks new advance at random rather than by number. */
2130 
2131 static int *apr_type;
2132 
2133 void
auto_pick_unit_research(Unit * unit)2134 auto_pick_unit_research(Unit *unit)
2135 {
2136     int a;
2137     int numtypes = 0;
2138 
2139     if (apr_type == NULL)
2140       apr_type = (int *) xmalloc(numutypes * sizeof(int));
2141 
2142     /* Get researchable advance types. */
2143     for_all_advance_types(a) {
2144 	if (side_can_research(unit->side, a)) {
2145 	    /* Add to list of researchable advances. */
2146 	    apr_type[numtypes++] = a;
2147 	}
2148     }
2149     if (numtypes)
2150       /* Pick one of them at random. */
2151       unit->curadvance = apr_type[xrandom(numtypes)];
2152     else
2153       unit->curadvance = NOADVANCE;
2154 }
2155 
2156 /* Try to pick a good advance to research. */
2157 
2158 void
auto_pick_side_research(Side * side)2159 auto_pick_side_research(Side *side)
2160 {
2161     ai_pick_side_research(side);
2162 }
2163 
2164 #if (0)
2165 static int *apnbt_types;
2166 
2167 int
auto_pick_new_build_task(Unit * unit)2168 auto_pick_new_build_task(Unit *unit)
2169 {
2170     int enemy_city_near = FALSE;
2171     int x, y, x1, y1, u;
2172     int city_has_shore = FALSE;
2173     int numtypes = 0;
2174     Side *side = unit->side;
2175     Unit *unit2;
2176 
2177     if (apnbt_types == NULL)
2178       apnbt_types = (int *) xmalloc(numutypes * sizeof(int));
2179     /* Zero the apnbt vector! */
2180     for_all_unit_types(u) {
2181 	apnbt_types[u] = 0;
2182     }
2183     /* Reevaluate the current plan every time. */
2184     auto_pick_new_plan(unit);
2185     /* Check if the unit borders on a water cell. */
2186     for_all_cells_within_range(unit->x, unit->y, 1, x, y) {
2187     	if (!inside_area(x, y))
2188     	    continue;
2189 	if (t_liquid(terrain_at(x, y))) {
2190 	    /* Also check if that water cell borders on another water cell.
2191 	       (we don't want to build battleships in the city pond) */
2192 	    for_all_cells_within_range(x, y, 1, x1, y1) {
2193 	    	if (!inside_area(x1, y1))
2194 	    	    continue;
2195 		if (t_liquid(terrain_at(x1, y1))
2196 		    /* Don't count the first water cell. */
2197 		    && (x != x1 || y != y1)) {
2198 		    city_has_shore = TRUE;
2199 		    break;
2200 		}
2201 	    }
2202 	    if (city_has_shore)
2203 	      break;
2204 	}
2205     }
2206     /* Check if we have an enemy city within our tactical range. */
2207     for_all_units(unit2) {
2208 	if (u_advanced(unit2->type)
2209 	    && distance(unit->x, unit->y, unit2->x, unit2->y)
2210 	    <= u_ai_enemy_alert_range(unit->type)
2211 	    && enemy_side(side, unit2->side)
2212 	    /* Only count cities that we can actually see. */
2213 	    && side_sees_image(side, unit2)) {
2214 	    enemy_city_near = TRUE;
2215 	    break;
2216 	}
2217     }
2218     /* Calculate unit values. */
2219     for_all_unit_types(u) {
2220 	if (side_can_build(side, u)
2221 	    && could_create(unit->type, u)) {
2222 	    /* Don't build immobile units for which there is no room. */
2223 	    if (!mobile(u)
2224 	        && !type_can_occupy(u, unit)) {
2225 		continue;
2226 	    }
2227 	    /* Don't build ships (naval-only movers)
2228 		if we don't have a shore. */
2229 	   if (u_naval_mobile(u)
2230 	       && !city_has_shore
2231 	       && !u_air_mobile(u)
2232 	       && !u_ground_mobile(u)) {
2233 		continue;
2234 	    }
2235 	    switch (unit->plan->type) {
2236 	      case PLAN_IMPROVING:
2237 		apnbt_types[u] = u_facility_worth(u);
2238 		break;
2239 	      case PLAN_EXPLORATORY:
2240 		apnbt_types[u] = u_ai_explorer_worth(u);
2241 		break;
2242 	      case PLAN_OFFENSIVE:
2243 		if (enemy_city_near) {
2244 		    /* Build 50% siege units. */
2245 		    if (probability(50))
2246 		    	apnbt_types[u] = u_siege_worth(u);
2247 		    else
2248 		    	apnbt_types[u] = u_siege_worth(u);
2249 		} else	{
2250 		    /* Build only attack units. */
2251 		    apnbt_types[u] = u_offensive_worth(u);
2252 		}
2253 		break;
2254 	      case PLAN_DEFENSIVE:
2255 		apnbt_types[u] = occ_can_defend_transport(u, unit->type)
2256 		  * u_defensive_worth(u);
2257 		break;
2258 	      case PLAN_NONE:
2259 	      case PLAN_PASSIVE:
2260 	      case NUMPLANTYPES:
2261 		apnbt_types[u] = 0;
2262 		break;
2263 	    }
2264 	}
2265 	if (apnbt_types[u] <= 0)
2266 	  apnbt_types[u] = 0;
2267 	else ++numtypes;
2268     }
2269     /* Try again with random choice if we found nothing to build. */
2270     if (numtypes == 0) {
2271 	for_all_unit_types(u) {
2272 	    if (side_can_build(side, u)
2273 		&& could_create(unit->type, u)) {
2274 	         /* Don't build immobile units for which there is no room. */
2275 	         if (!mobile(u)
2276 	             && !type_can_occupy(u, unit)) {
2277 		     continue;
2278 	         }
2279 	         /* Don't build ships (naval-only movers)
2280 		    if we don't have a shore. */
2281 	         if (u_naval_mobile(u)
2282 	            && !city_has_shore
2283 	            && !u_air_mobile(u)
2284 	            && !u_ground_mobile(u)) {
2285 		     continue;
2286 	         }
2287 		apnbt_types[u] = u_random_worth(u);
2288 		if (apnbt_types[u] <= 0)
2289 		  apnbt_types[u] = 0;
2290 		else ++numtypes;
2291 	    }
2292 	}
2293     }
2294     if (numtypes > 0) {
2295 	/* Use prefs weight to pick unit type to build. */
2296 	u = select_by_weight(apnbt_types, numutypes);
2297 	if (is_unit_type(u))
2298 	  set_construct_task(unit, u, 1, -1, unit->x, unit->y);
2299 	else
2300 	  u = NONUTYPE;
2301     } else
2302       u = NONUTYPE;
2303     if (u == NONUTYPE) {
2304     	set_unit_reserve(side, unit, TRUE, FALSE);
2305     	notify(side, "%s unable to pick build task, waiting one turn.",
2306 	       unit_handle(side, unit));
2307     }
2308     return u;
2309 }
2310 
2311 /* This is a rudimentary AI for advanced units. Lots of room for
2312    improvement! */
2313 
2314 void
auto_pick_new_plan(Unit * unit)2315 auto_pick_new_plan(Unit *unit)
2316 {
2317     int my_advanced = 0, my_colonizers = 0, my_total = 0;
2318     int enemy_advanced = 0, enemy_colonizers = 0, enemy_total = 0;
2319     int defenders = 0, facilities = 0, mobiles = 0, invisible_cells = 0;
2320     int u = unit->type;
2321     int x, y, u2;
2322     Unit *unit2;
2323 
2324     /* Init plan if necessary. */
2325     if (!unit->plan)
2326       init_unit_plan(unit);
2327     /* First count our facilities, defenders and mobile types. */
2328     for_all_occs_with_occs(unit, unit2) {
2329 	if (u_facility(unit2->type))
2330 	  facilities += 1;
2331 	if (is_active(unit2)
2332 	    && occ_can_defend_transport(unit2->type, unit->type))
2333 	  defenders += 1;
2334 	if (mobile(unit2->type))
2335 	  mobiles += 1;
2336     }
2337     /* Always build defenders if we are undefended. */
2338     if (!defended_by_occupants(unit)
2339 	&& can_build_defenders(unit->side, unit->type)) {
2340 	set_unit_plan_type(unit->side, unit, PLAN_DEFENSIVE);
2341 	return;
2342     }
2343     /* Check out the tactical neighbourhood. */
2344     for_all_cells_within_range(unit->x, unit->y,
2345 			       u_ai_tactical_range(unit->type), x, y) {
2346 	if (!inside_area(x, y))
2347 	  continue;
2348 	if (!terrain_visible(unit->side, x, y))
2349 	  invisible_cells +=1;
2350 	unit2 = NULL;
2351 	/* Important to count also occupants here. */
2352 	for_all_stack_with_occs(x, y, unit2) {
2353 	    /* Only count real units. */
2354 	    if (!is_active(unit2))
2355 	      continue;
2356 	    /* Only count units that we can see. */
2357 	    if (!side_sees_image(unit->side, unit2))
2358 	      continue;
2359 	    u2 = unit2->type;
2360 	    /* First count own units. */
2361 	    if (unit->side == unit2->side) {
2362 		if (u_advanced(u2))
2363 		  my_advanced += 1;
2364 		else if (u_colonizer_worth(u2))
2365 		  my_colonizers += 1;
2366 		my_total += 1;
2367 		/* Then count hostile units. */
2368 	    } else if (enemy_side(unit->side, unit2->side)){
2369 		if (u_advanced(u2))
2370 		  enemy_advanced += 1;
2371 		else if (u_colonizer_worth(u2))
2372 		  enemy_colonizers += 1;
2373 		enemy_total += 1;
2374 	    }
2375 	}
2376     }
2377     if (enemy_total > 0
2378 	&& can_build_attackers(unit->side, unit->type)) {
2379 	/* Always build attackers if any enemy unit is near. */
2380 	set_unit_plan_type(unit->side, unit, PLAN_OFFENSIVE);
2381     } else if (invisible_cells
2382 	       && can_build_explorers(unit->side, unit->type)) {
2383 	/* Then build explorers if we have any invisible cells nearby. */
2384 	set_unit_plan_type(unit->side, unit, PLAN_EXPLORATORY);
2385     } else if (flip_coin() && facilities < u_facility_total_max(u)
2386 	       && can_build_facilities(unit->side, unit->type)) {
2387 	/* Build 50% facilities if there is room left. */
2388 	set_unit_plan_type(unit->side, unit, PLAN_IMPROVING);
2389     } else if (can_build_attackers(unit->side, unit->type)) {
2390 	/* Else build offensive units. */
2391 	set_unit_plan_type(unit->side, unit, PLAN_OFFENSIVE);
2392     } else {
2393 	set_unit_plan_type(unit->side, unit, PLAN_PASSIVE);
2394 	set_unit_reserve(unit->side, unit, TRUE, FALSE);
2395     }
2396 }
2397 #endif
2398