Debian Codegraph @

src/cdogs/ai_coop.c

raw symbols SCIP
1 /*
2 C-Dogs SDL
3 A port of the legendary (and fun) action/arcade cdogs.
4
5 Copyright (c) 2013-2015, 2017-2018, 2020-2023 Cong Xu
6 All rights reserved.
7
8 Redistribution and use in source and binary forms, with or without
9 modification, are permitted provided that the following conditions are met:
10
11 Redistributions of source code must retain the above copyright notice, this
12 list of conditions and the following disclaimer.
13 Redistributions in binary form must reproduce the above copyright notice,
14 this list of conditions and the following disclaimer in the documentation
15 and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 POSSIBILITY OF SUCH DAMAGE.
28 */
29 #include "ai_coop.h"
30
31 #include "ai_utils.h"
32 #include "gamedata.h"
33 #include "pickup.h"
34
35 // How many ticks to stay in one confusion state
36 #define CONFUSION_STATE_TICKS_MIN 25
37 #define CONFUSION_STATE_TICKS_RANGE 25
38
39 #define DISTANCE_TO_KEEP_OUT_OF_WAY SQUARED(4 * 16)
40
41 static int AICoopGetCmdNormal(TActor *actor);
42 int AICoopGetCmd(TActor *actor, const int ticks)
43 {
44 // Create AI context if it isn't there already
45 // This is because co-op AIs don't have the character bot property
46 // TODO: don't require this lazy initialisation
47 if (actor->aiContext == NULL)
48 {
49 actor->aiContext = AIContextNew();
50 }
51
52 int cmd = 0;
53
54 // Special decision tree for confusion
55 // - If confused, randomly:
56 // - Perform the right action (reverse directions)
57 // - Perform a random command (except for switching weapons)
58 // - And never slide
59 if (actor->confused)
60 {
61 AIConfusionState *s = &actor->aiContext->ConfusionState;
62 // Check delay and change state
63 actor->aiContext->Delay = MAX(0, actor->aiContext->Delay - ticks);
64 if (actor->aiContext->Delay == 0)
65 {
66 actor->aiContext->Delay = CONFUSION_STATE_TICKS_MIN +
67 (rand() % CONFUSION_STATE_TICKS_RANGE);
68 if (s->Type == AI_CONFUSION_CONFUSED)
69 {
70 s->Type = AI_CONFUSION_CORRECT;
71 }
72 else
73 {
74 ActorSetAIState(actor, AI_STATE_CONFUSED);
75 s->Type = AI_CONFUSION_CONFUSED;
76 // Generate the confused action
77 s->Cmd = rand() & (CMD_LEFT | CMD_RIGHT | CMD_UP | CMD_DOWN |
78 CMD_BUTTON1 | CMD_BUTTON2);
79 }
80 }
81 // Choose confusion action based on state
82 switch (s->Type)
83 {
84 case AI_CONFUSION_CONFUSED:
85 // Use canned random command
86 // TODO: add state for this action
87 cmd = s->Cmd;
88 break;
89 case AI_CONFUSION_CORRECT:
90 // Reverse directions so they are correct
91 cmd = CmdGetReverse(AICoopGetCmdNormal(actor));
92 break;
93 default:
94 CASSERT(false, "Unknown state");
95 break;
96 }
97 // Don't slide
98 if (Button2(cmd) && CMD_HAS_DIRECTION(cmd))
99 {
100 cmd &= ~CMD_BUTTON2;
101 }
102 }
103 else
104 {
105 // Act normally
106 cmd = AICoopGetCmdNormal(actor);
107 }
108 return cmd;
109 }
110
111 static int SmartGoto(
112 TActor *actor, const struct vec2 pos, const float minDistance2);
113 static bool TryCompleteNearbyObjective(
114 TActor *actor, const TActor *closestPlayer,
115 const float distanceTooFarFromPlayer, int *cmdOut);
116 static int AICoopGetCmdNormal(TActor *actor)
117 {
118 // Use decision tree to command the AI
119 // - Move away from dangerous bullets
120 // - Check weapons and ammo
121 // - If too far away from nearest player
122 // - Go to nearest player
123 // - else if blocking a nearby player
124 // - move out of the way
125 // - else if closest enemy is close enough
126 // - Attack enemy
127 // - else
128 // - Go to nearest player if too far, or away if too close
129 const struct vec2i actorTilePos = Vec2ToTile(actor->Pos);
130
131 // Look for dangerous bullets in a 1-tile radius
132 // These are bullets with the "HurtAlways" property true
133 struct vec2i v;
134 struct vec2 dangerBulletPos = svec2_zero();
135 for (v.x = actorTilePos.x - 1;
136 v.x <= actorTilePos.x + 1 && svec2_is_zero(dangerBulletPos); v.x++)
137 {
138 for (v.y = actorTilePos.y - 1;
139 v.y <= actorTilePos.y + 1 && svec2_is_zero(dangerBulletPos);
140 v.y++)
141 {
142 const Tile *t = MapGetTile(&gMap, v);
143 if (t == NULL)
144 continue;
145 CA_FOREACH(const ThingId, tid, t->things)
146 // Only look for bullets
147 if (tid->Kind != KIND_MOBILEOBJECT)
148 continue;
149 const TMobileObject *mo = CArrayGet(&gMobObjs, tid->Id);
150 if (mo->bulletClass->HurtAlways)
151 {
152 dangerBulletPos = mo->thing.Pos;
153 break;
154 }
155 CA_FOREACH_END()
156 }
157 }
158 // Run away if dangerous bullet found
159 if (!svec2_is_zero(dangerBulletPos))
160 {
161 return AIRetreatFrom(actor, dangerBulletPos);
162 }
163
164 // Check the weapon for ammo
165 int lowAmmoGun = -1;
166 if (gCampaign.Setting.Ammo && actor->aiContext->OnGunId == -1)
167 {
168 // Check all our weapons
169 // Prefer guns using ammo
170 // This is because unlimited ammo guns tend to be worse
171 int mostPreferredWeaponWithAmmo = -1;
172 bool mostPreferredWeaponHasAmmo = false;
173 for (int i = 0; i < MAX_GUNS; i++)
174 {
175 const Weapon *w = &actor->guns[i];
176 // TODO: support multi guns?
177 if (w->Gun == NULL || w->Gun->Type != GUNTYPE_NORMAL)
178 {
179 continue;
180 }
181 const int ammoAmount = ActorWeaponGetAmmo(actor, w->Gun, 0);
182 if ((mostPreferredWeaponWithAmmo == -1 && ammoAmount != 0) ||
183 (!mostPreferredWeaponHasAmmo && ammoAmount > 0))
184 {
185 // Note: -1 means the gun has unlimited ammo
186 mostPreferredWeaponWithAmmo = i;
187 mostPreferredWeaponHasAmmo = ammoAmount > 0;
188 }
189 if (w->Gun->u.Normal.AmmoId != -1)
190 {
191 const Ammo *ammo =
192 AmmoGetById(&gAmmo, w->Gun->u.Normal.AmmoId);
193 if (lowAmmoGun == -1 && ammoAmount < ammo->Amount)
194 {
195 lowAmmoGun = i;
196 }
197 }
198 }
199
200 // If we're out of ammo, switch to one with ammo
201 // Prioritise our selection based on weapon order, i.e.
202 // prefer first weapon over second over third etc.
203 if (mostPreferredWeaponWithAmmo != -1 &&
204 mostPreferredWeaponWithAmmo != actor->gunIndex)
205 {
206 return actor->lastCmd == CMD_BUTTON2 ? 0 : CMD_BUTTON2;
207 }
208 }
209
210 // If we're over a weapon pickup, check if we want to pick it up
211 // Pick up if we have:
212 // - a weapon that is low on ammo and don't yet have the gun, or
213 // - if we have a free slot
214 if (actor->aiContext->OnGunId != -1)
215 {
216 const WeaponClass *wc = IdWeaponClass(actor->aiContext->OnGunId);
217 if ((lowAmmoGun != -1 && ActorFindGun(actor, wc) < 0) ||
218 (wc->Type == GUNTYPE_GRENADE
219 ? ActorGetNumGrenades(actor) < MAX_GRENADES
220 : ActorGetNumGuns(actor) < MAX_GUNS))
221 {
222 actor->aiContext->OnGunId = -1;
223 // Pick it up
224 // TODO: this will not guarantee the new gun will replace
225 // the low ammo gun; weapon management?
226 return actor->lastCmd == CMD_BUTTON2 ? 0 : CMD_BUTTON2;
227 }
228 actor->aiContext->OnGunId = -1;
229 }
230
231 // Find nearby players, and move out of the way if any of them are facing
232 // directly at us
233 // Follow the closest player with a lower UID
234 const TActor *closestPlayer = NULL;
235 float minDistance2 = -1;
236 if (!IsPVP(gCampaign.Entry.Mode))
237 {
238 for (int uid = 0; uid < actor->PlayerUID; uid++)
239 {
240 const PlayerData *pd = PlayerDataGetByUID(uid);
241 if (pd == NULL || !IsPlayerAlive(pd))
242 continue;
243 const TActor *p = ActorGetByUID(pd->ActorUID);
244 const float distance2 = svec2_distance_squared(actor->Pos, p->Pos);
245 if (!closestPlayer || distance2 < minDistance2)
246 {
247 minDistance2 = distance2;
248 closestPlayer = p;
249 }
250 // TODO: AIIsFacing might be too generous?
251 if (distance2 < DISTANCE_TO_KEEP_OUT_OF_WAY &&
252 AIIsFacing(p, actor->Pos, p->direction))
253 {
254 // Move out of the way
255 return AIMoveAwayFromLine(actor->Pos, p->Pos, p->direction);
256 }
257 }
258 }
259
260 // Set distance we want to stay within the lead player
261 float distanceTooFarFromPlayer = 8.0f;
262 // If player is exiting, we want to be very close to the player
263 if (closestPlayer && closestPlayer->action == ACTORACTION_EXITING)
264 {
265 distanceTooFarFromPlayer = 2.0f;
266 }
267 if (closestPlayer && minDistance2 > SQUARED(distanceTooFarFromPlayer * 16))
268 {
269 ActorSetAIState(actor, AI_STATE_FOLLOW);
270 return SmartGoto(actor, closestPlayer->Pos, minDistance2);
271 }
272
273 // Check if closest enemy is close enough, and visible
274 const TActor *closestEnemy = AIGetClosestVisibleEnemy(actor, true);
275 if (closestEnemy)
276 {
277 const float minEnemyDistance = CHEBYSHEV_DISTANCE(
278 actor->Pos.x, actor->Pos.y, closestEnemy->Pos.x,
279 closestEnemy->Pos.y);
280 // Also only engage if there's a clear shot
281 if (minEnemyDistance > 0 && minEnemyDistance < 12 * 16 &&
282 AIHasClearShot(actor->Pos, closestEnemy->Pos))
283 {
284 ActorSetAIState(actor, AI_STATE_HUNT);
285 if (closestEnemy->uid != actor->aiContext->EnemyId)
286 {
287 // Engaging new enemy now
288 actor->aiContext->EnemyId = closestEnemy->uid;
289 actor->aiContext->GunRangeScalar = 1.0;
290 }
291 else
292 {
293 // Still attacking the same enemy; inch closer
294 actor->aiContext->GunRangeScalar *= 0.99;
295 }
296 return AIAttack(actor, closestEnemy->Pos);
297 }
298 }
299
300 // Look for objectives nearby to complete
301 int cmd;
302 if (TryCompleteNearbyObjective(
303 actor, closestPlayer, distanceTooFarFromPlayer, &cmd))
304 {
305 return cmd;
306 }
307
308 // Otherwise, just go towards the closest player as long as we don't
309 // run into them, but keep away if we're too close
310 if (closestPlayer)
311 {
312 if (minDistance2 > SQUARED(2 * 16))
313 {
314 ActorSetAIState(actor, AI_STATE_FOLLOW);
315 return SmartGoto(actor, closestPlayer->Pos, minDistance2);
316 }
317 else if (minDistance2 < SQUARED(4 * 16 / 3))
318 {
319 return CmdGetReverse(AIGotoDirect(actor->Pos, closestPlayer->Pos));
320 }
321 }
322
323 ActorSetAIState(actor, AI_STATE_IDLE);
324 return 0;
325 }
326 // Number of ticks to persist in trying to destroy an obstruction
327 // before giving up and going around
328 #define STUCK_TICKS 70
329 // Goto with extra smarts:
330 // - If clear path, slide
331 // - If non-dangerous object blocking, shoot at it
332 // - If stuck for a long time, pathfind around obstructing object
333 static int SmartGoto(
334 TActor *actor, const struct vec2 pos, const float minDistance2)
335 {
336 int cmd = AIGoto(actor, pos, true);
337 // Try to slide if there is a clear path and we are far enough away
338 if (CMD_HAS_DIRECTION(cmd) &&
339 AIHasClearPath(actor->Pos, pos, !actor->aiContext->IsStuckTooLong) &&
340 minDistance2 > SQUARED(7 * 16))
341 {
342 cmd |= CMD_BUTTON2;
343 }
344 // If running into safe object, and we're being blocked, shoot at it
345 const TObject *o = AIGetObjectRunningInto(actor, cmd);
346 const struct vec2i tilePos = Vec2ToTile(actor->Pos);
347 if (o && ObjIsDangerous(o) &&
348 svec2i_is_equal(tilePos, actor->aiContext->LastTile))
349 {
350 cmd = AIGoto(actor, o->thing.Pos, true);
351 if (ActorGetCanFireBarrel(actor, ACTOR_GET_WEAPON(actor)) >= 0)
352 {
353 cmd |= CMD_BUTTON1;
354 }
355 }
356 // Check if we are stuck
357 if (svec2i_is_equal(tilePos, actor->aiContext->LastTile))
358 {
359 actor->aiContext->Delay++;
360 if (actor->aiContext->Delay >= STUCK_TICKS)
361 {
362 // We've been stuck for too long
363 // Pathfind around it
364 // Make sure to reset the A* path if we are first realising
365 // we are stuck
366 if (!actor->aiContext->IsStuckTooLong)
367 {
368 actor->aiContext->Goto.IsFollowing = false;
369 }
370 actor->aiContext->IsStuckTooLong = true;
371 cmd = AIGoto(actor, pos, !actor->aiContext->IsStuckTooLong);
372 }
373 }
374 else
375 {
376 actor->aiContext->Delay = 0;
377 actor->aiContext->IsStuckTooLong = false;
378 }
379 actor->aiContext->LastTile = tilePos;
380 return cmd;
381 }
382 typedef struct
383 {
384 float Distance2;
385 union {
386 const Objective *Objective;
387 int UID;
388 } u;
389 struct vec2 Pos;
390 bool IsDestructible;
391 AIObjectiveType Type;
392 } ClosestObjective;
393 static void FindObjectivesSortedByDistance(
394 CArray *objectives, const TActor *actor, const TActor *closestPlayer);
395 static bool CanGetObjective(
396 const struct vec2 objPos, const struct vec2 actorPos, const TActor *player,
397 const float distanceTooFarFromPlayer);
398 static int GotoObjective(TActor *actor, const float objDistance2);
399 static bool TryCompleteNearbyObjective(
400 TActor *actor, const TActor *closestPlayer,
401 const float distanceTooFarFromPlayer, int *cmdOut)
402 {
403 AIContext *context = actor->aiContext;
404 AIObjectiveState *objState = &context->ObjectiveState;
405
406 // Check to see if we are already attempting to complete an objective,
407 // and that it hasn't been updated since we last checked.
408 // If so keep following the path
409 if (context->State == AI_STATE_NEXT_OBJECTIVE)
410 {
411 bool hasNoUpdates = true;
412 switch (objState->Type)
413 {
414 case AI_OBJECTIVE_TYPE_KEY:
415 hasNoUpdates =
416 objState->LastDone == KeycardCount(gMission.KeyFlags);
417 break;
418 case AI_OBJECTIVE_TYPE_NORMAL:
419 hasNoUpdates =
420 objState->u.Obj && objState->LastDone == objState->u.Obj->done;
421 break;
422 case AI_OBJECTIVE_TYPE_KILL: {
423 const TActor *target = ActorGetByUID(objState->u.UID);
424 hasNoUpdates = target->health > 0;
425 // Update target position
426 objState->Goal = target->thing.Pos;
427 }
428 break;
429 case AI_OBJECTIVE_TYPE_PICKUP: {
430 const Pickup *p = PickupGetByUID(objState->u.UID);
431 hasNoUpdates = p != NULL && p->isInUse;
432 }
433 break;
434 default:
435 // Do nothing
436 break;
437 }
438 if (hasNoUpdates)
439 {
440 int cmd = GotoObjective(actor, 0);
441 // If we can't go to the objective,
442 // one possibility is that we've reached where the objective was,
443 // but have nothing to do.
444 // Remember that actor objectives can move around!
445 if (CMD_HAS_DIRECTION(cmd))
446 {
447 *cmdOut = cmd;
448 return true;
449 }
450 }
451 }
452
453 // First, check if mission complete;
454 // if so (and there's a path) go to an exit
455 if (CanCompleteMission(&gMission))
456 {
457 for (int i = 0; i < (int)gMap.exits.size; i++)
458 {
459 const struct vec2 exitPos = MapGetExitPos(&gMap, i);
460 if (CanGetObjective(
461 exitPos, actor->Pos, closestPlayer,
462 distanceTooFarFromPlayer))
463 {
464 ActorSetAIState(actor, AI_STATE_NEXT_OBJECTIVE);
465 objState->Type = AI_OBJECTIVE_TYPE_EXIT;
466 objState->Goal = exitPos;
467 *cmdOut = GotoObjective(actor, 0);
468 return true;
469 }
470 }
471 }
472
473 // Find all the objective/key locations, sort according to distance
474 // TODO: reuse this array, don't recreate it
475 CArray objectives;
476 FindObjectivesSortedByDistance(&objectives, actor, closestPlayer);
477
478 // Starting from the closest objectives, find one we can go to
479 CA_FOREACH(ClosestObjective, c, objectives)
480 if (CanGetObjective(
481 c->Pos, actor->Pos, closestPlayer, distanceTooFarFromPlayer))
482 {
483 ActorSetAIState(actor, AI_STATE_NEXT_OBJECTIVE);
484 objState->Type = c->Type;
485 objState->IsDestructible = c->IsDestructible;
486 switch (c->Type)
487 {
488 case AI_OBJECTIVE_TYPE_KEY:
489 objState->LastDone = KeycardCount(gMission.KeyFlags);
490 break;
491 case AI_OBJECTIVE_TYPE_NORMAL:
492 objState->u.Obj = c->u.Objective;
493 objState->LastDone = c->u.Objective->done;
494 break;
495 case AI_OBJECTIVE_TYPE_KILL:
496 objState->u.UID = c->u.UID;
497 break;
498 case AI_OBJECTIVE_TYPE_PICKUP:
499 objState->u.UID = c->u.UID;
500 break;
501 default:
502 // Do nothing
503 break;
504 }
505 objState->Goal = c->Pos;
506 *cmdOut = GotoObjective(actor, c->Distance2);
507 return true;
508 }
509 CA_FOREACH_END()
510 return false;
511 }
512 static bool ShouldPickupGun(
513 const PickupEffect *pe, const TActor *actor, const TActor *closestPlayer);
514 static AIObjectiveType GetPickupObjectiveType(
515 const Pickup *p, int *uid, const TActor *actor,
516 const TActor *closestPlayer)
517 {
518 CA_FOREACH(const PickupEffect, pe, p->class->Effects)
519 switch (pe->Type)
520 {
521 case PICKUP_KEYCARD:
522 return AI_OBJECTIVE_TYPE_KEY;
523 case PICKUP_JEWEL:
524 *uid = p->UID;
525 return AI_OBJECTIVE_TYPE_PICKUP;
526 case PICKUP_HEALTH:
527 // Pick up if we are on low health, and lower than lead player
528 if (actor->health > CampaignGetMaxHP(&gCampaign) / 4 ||
529 (closestPlayer != NULL && actor->health >= closestPlayer->health))
530 {
531 continue;
532 }
533 *uid = p->UID;
534 return AI_OBJECTIVE_TYPE_PICKUP;
535 case PICKUP_AMMO: {
536 // Pick up if we use this ammo, have less ammo than starting,
537 // and lower than lead player, who uses the ammo
538 const int ammoId = pe->u.Ammo.Id;
539 const Ammo *ammo = AmmoGetById(&gAmmo, ammoId);
540 const int ammoAmount = *(int *)CArrayGet(&actor->ammo, ammoId);
541 if (!ActorUsesAmmo(actor, ammoId) || ammoAmount > ammo->Amount ||
542 (closestPlayer != NULL && ActorUsesAmmo(closestPlayer, ammoId) &&
543 ammoAmount > *(int *)CArrayGet(&closestPlayer->ammo, ammoId)))
544 {
545 continue;
546 }
547 *uid = p->UID;
548 return AI_OBJECTIVE_TYPE_PICKUP;
549 }
550 case PICKUP_GUN:
551 if (ShouldPickupGun(pe, actor, closestPlayer))
552 {
553 *uid = p->UID;
554 return AI_OBJECTIVE_TYPE_PICKUP;
555 }
556 break;
557 case PICKUP_SHOW_MAP:
558 *uid = p->UID;
559 return AI_OBJECTIVE_TYPE_PICKUP;
560 case PICKUP_LIVES:
561 // Pick up if we have less lives than lead player
562 if (closestPlayer != NULL &&
563 PlayerDataGetByUID(actor->PlayerUID)->Lives >=
564 PlayerDataGetByUID(closestPlayer->PlayerUID)->Lives)
565 {
566 continue;
567 }
568 *uid = p->UID;
569 return AI_OBJECTIVE_TYPE_PICKUP;
570 default:
571 // Not something we want to pick up
572 continue;
573 }
574 CA_FOREACH_END()
575 return AI_OBJECTIVE_TYPE_NORMAL;
576 }
577 static int CompareClosestObjective(const void *v1, const void *v2);
578 static void FindObjectivesSortedByDistance(
579 CArray *objectives, const TActor *actor, const TActor *closestPlayer)
580 {
581 CArrayInit(objectives, sizeof(ClosestObjective));
582
583 // If PVP, find the closest enemy and go to them
584 if (IsPVP(gCampaign.Entry.Mode))
585 {
586 const TActor *closestEnemy = AIGetClosestVisibleEnemy(actor, true);
587 if (closestEnemy != NULL)
588 {
589 ClosestObjective co;
590 memset(&co, 0, sizeof co);
591 co.Pos = closestEnemy->thing.Pos;
592 co.IsDestructible = false;
593 co.Type = AI_OBJECTIVE_TYPE_KILL;
594 co.Distance2 = svec2_distance_squared(actor->Pos, co.Pos);
595 co.u.UID = closestEnemy->uid;
596 CArrayPushBack(objectives, &co);
597 }
598 }
599
600 // Look for pickups
601 CA_FOREACH(const Pickup, p, gPickups)
602 if (!p->isInUse)
603 {
604 continue;
605 }
606 ClosestObjective co;
607 memset(&co, 0, sizeof co);
608 co.Pos = p->thing.Pos;
609 co.IsDestructible = false;
610 co.Type = GetPickupObjectiveType(p, &co.u.UID, actor, closestPlayer);
611 if (co.Type == AI_OBJECTIVE_TYPE_NORMAL)
612 {
613 continue;
614 }
615 // Check if the pickup is actually accessible
616 // This is because random spawning may cause some pickups to be spawned
617 // in inaccessible areas
618 if (!TileCanWalk(MapGetTile(&gMap, Vec2ToTile(co.Pos))))
619 {
620 continue;
621 }
622 co.Distance2 = svec2_distance_squared(actor->Pos, co.Pos);
623 if (co.Type == AI_OBJECTIVE_TYPE_NORMAL)
624 {
625 const int objective = ObjectiveFromThing(p->thing.flags);
626 co.u.Objective =
627 CArrayGet(&gMission.missionData->Objectives, objective);
628 }
629 CArrayPushBack(objectives, &co);
630 CA_FOREACH_END()
631
632 // Look for destructibles
633 CA_FOREACH(const TObject, o, gObjs)
634 if (!o->isInUse)
635 {
636 continue;
637 }
638 ClosestObjective co;
639 memset(&co, 0, sizeof co);
640 co.Pos = o->thing.Pos;
641 co.IsDestructible = true;
642 co.Type = AI_OBJECTIVE_TYPE_NORMAL;
643 if (!(o->thing.flags & THING_OBJECTIVE))
644 {
645 continue;
646 }
647 // Destructible objective; go towards it and fire
648 co.Distance2 = svec2_distance_squared(actor->Pos, co.Pos);
649 if (co.Type == AI_OBJECTIVE_TYPE_NORMAL)
650 {
651 const int objective = ObjectiveFromThing(o->thing.flags);
652 co.u.Objective =
653 CArrayGet(&gMission.missionData->Objectives, objective);
654 }
655 CArrayPushBack(objectives, &co);
656 CA_FOREACH_END()
657
658 // Look for kill or rescue objectives
659 CA_FOREACH(const TActor, a, gActors)
660 if (!a->isInUse)
661 {
662 continue;
663 }
664 const Thing *ti = &a->thing;
665 if (!(ti->flags & THING_OBJECTIVE))
666 {
667 continue;
668 }
669 const int objective = ObjectiveFromThing(ti->flags);
670 const Objective *o =
671 CArrayGet(&gMission.missionData->Objectives, objective);
672 if (o->Type != OBJECTIVE_KILL && o->Type != OBJECTIVE_RESCUE)
673 {
674 continue;
675 }
676 // Only rescue those that need to be rescued
677 if (o->Type == OBJECTIVE_RESCUE && !(a->flags & FLAGS_PRISONER))
678 {
679 continue;
680 }
681 ClosestObjective co;
682 memset(&co, 0, sizeof co);
683 co.Pos = ti->Pos;
684 co.IsDestructible = false;
685 co.Type = AI_OBJECTIVE_TYPE_NORMAL;
686 co.Distance2 = svec2_distance_squared(actor->Pos, co.Pos);
687 co.u.Objective = o;
688 CArrayPushBack(objectives, &co);
689 CA_FOREACH_END()
690
691 // Look for explore objectives
692 CA_FOREACH(const Objective, o, gMission.missionData->Objectives)
693 if (o->Type != OBJECTIVE_INVESTIGATE)
694 {
695 continue;
696 }
697 if (ObjectiveIsComplete(o) || MapGetExploredPercentage(&gMap) == 100)
698 {
699 continue;
700 }
701 // Find the nearest unexplored tile
702 const struct vec2i actorTile = Vec2ToTile(actor->Pos);
703 const struct vec2i unexploredTile =
704 MapSearchTileAround(&gMap, actorTile, MapTileIsUnexplored);
705 ClosestObjective co;
706 memset(&co, 0, sizeof co);
707 co.Pos = Vec2CenterOfTile(unexploredTile);
708 co.IsDestructible = false;
709 co.Type = AI_OBJECTIVE_TYPE_NORMAL;
710 co.Distance2 = svec2_distance_squared(actor->Pos, co.Pos);
711 co.u.Objective = o;
712 CArrayPushBack(objectives, &co);
713 CA_FOREACH_END()
714
715 // Sort according to distance
716 qsort(
717 objectives->data, objectives->size, objectives->elemSize,
718 CompareClosestObjective);
719 }
720 static bool ShouldPickupGun(
721 const PickupEffect *pe, const TActor *actor, const TActor *closestPlayer)
722 {
723 if (!gCampaign.Setting.Ammo)
724 {
725 return false;
726 }
727 const WeaponClass *pickupGun = IdWeaponClass(pe->u.GunId);
728 const int weaponIndexStart =
729 pickupGun->Type == GUNTYPE_GRENADE ? MAX_GUNS : 0;
730 const int weaponIndexEnd =
731 pickupGun->Type == GUNTYPE_GRENADE ? MAX_WEAPONS : MAX_GUNS;
732 // Pick up if:
733 // - we have a gun with less ammo than starting,
734 // - and lower than lead player, who uses the ammo,
735 // - or if there is a free weapon slot,
736 // - and the gun is the same type (normal, grenade)
737 bool hasGunLowOnAmmo = false;
738 for (int i = weaponIndexStart; i < weaponIndexEnd; i++)
739 {
740 const WeaponClass *wc = actor->guns[i].Gun;
741 if (wc == NULL)
742 {
743 hasGunLowOnAmmo = true;
744 break;
745 }
746 // TODO: support multi guns
747 if (wc->Type != GUNTYPE_NORMAL)
748 {
749 continue;
750 }
751 const int ammoId = wc->u.Normal.AmmoId;
752 if (ammoId < 0)
753 {
754 continue;
755 }
756 const Ammo *ammo = AmmoGetById(&gAmmo, ammoId);
757 const int ammoAmount = *(int *)CArrayGet(&actor->ammo, ammoId);
758 if (ammoAmount >= ammo->Amount ||
759 (closestPlayer != NULL && ActorUsesAmmo(closestPlayer, ammoId) &&
760 ammoAmount > *(int *)CArrayGet(&closestPlayer->ammo, ammoId)))
761 {
762 continue;
763 }
764 hasGunLowOnAmmo = true;
765 }
766
767 if (!hasGunLowOnAmmo)
768 {
769 return false;
770 }
771
772 if (ActorFindGun(actor, IdWeaponClass(pe->u.GunId)) >= 0)
773 {
774 return false;
775 }
776 return true;
777 }
778 static int CompareClosestObjective(const void *v1, const void *v2)
779 {
780 const ClosestObjective *c1 = v1;
781 const ClosestObjective *c2 = v2;
782 if (c1->Distance2 < c2->Distance2)
783 {
784 return -1;
785 }
786 else if (c1->Distance2 > c2->Distance2)
787 {
788 return 1;
789 }
790 return 0;
791 }
792 static bool IsPosCloseEnoughToPlayer(
793 const struct vec2 pos, const TActor *player,
794 const float distanceTooFarFromPlayer);
795 static bool CanGetObjective(
796 const struct vec2 objPos, const struct vec2 actorPos, const TActor *player,
797 const float distanceTooFarFromPlayer)
798 {
799 // Check if we can complete an objective.
800 // If we don't need to follow any player, then only check that we can
801 // pathfind to it.
802 if (!player)
803 {
804 return AIHasPath(actorPos, objPos, true);
805 }
806 // If we need to stick close to a player, then check that it is both:
807 // - Close enough from the lead player
808 // - In line of sight from us
809 if (!IsPosCloseEnoughToPlayer(objPos, player, distanceTooFarFromPlayer))
810 {
811 return false;
812 }
813 return AIHasClearPath(actorPos, objPos, true);
814 }
815 static bool IsPosCloseEnoughToPlayer(
816 const struct vec2 pos, const TActor *player,
817 const float distanceTooFarFromPlayer)
818 {
819 if (!player)
820 {
821 return true;
822 }
823 const float distanceFromPlayer2 = svec2_distance_squared(pos, player->Pos);
824 const float distanceMax2 = SQUARED(distanceTooFarFromPlayer * 16);
825 return distanceFromPlayer2 < distanceMax2;
826 }
827 // Navigate to the current objective
828 // If the objective is destructible and it makes sense to shoot it,
829 // shoot at it as well
830 static int GotoObjective(TActor *actor, const float objDistance2)
831 {
832 const AIObjectiveState *objState = &actor->aiContext->ObjectiveState;
833 const struct vec2 goal = objState->Goal;
834 int cmd = 0;
835 // Check to see if we need to go any closer to the objective
836 const bool isDestruction =
837 objState->Type == AI_OBJECTIVE_TYPE_NORMAL && objState->IsDestructible;
838 if (!isDestruction ||
839 svec2_distance_squared(actor->Pos, goal) > SQUARED(3 * 16) ||
840 !AIHasClearView(actor, goal, 10 * 16))
841 {
842 cmd = SmartGoto(actor, goal, objDistance2);
843 }
844 else if (
845 isDestruction &&
846 ActorGetCanFireBarrel(actor, ACTOR_GET_WEAPON(actor)) >= 0)
847 {
848 cmd = AIHunt(actor, goal);
849 if (AIHasClearShot(actor->Pos, goal))
850 {
851 cmd |= CMD_BUTTON1;
852 }
853 }
854 return cmd;
855 }
856
857 void AICoopSelectWeapons(
858 PlayerData *p, const int player, const CArray *weapons)
859 {
860 // Select two weapons from available ones
861 // Offset the starting index a bit so each AI uses different guns
862 // TODO: select grenades
863 const int startIdx = (player * MAX_GUNS) % weapons->size;
864 int gunCount = 0;
865 for (int i = 0; gunCount < MAX_GUNS; i++)
866 {
867 const int idx = (startIdx + i) % weapons->size;
868 if (idx == startIdx && i > 0)
869 {
870 // Not enough weapons
871 break;
872 }
873 const WeaponClass **wc = CArrayGet(weapons, idx);
874 // TODO: support multi guns
875 if ((*wc)->Type != GUNTYPE_NORMAL)
876 {
877 continue;
878 }
879 p->guns[gunCount] = *wc;
880 gunCount++;
881 }
882
883 if (gCampaign.Setting.Ammo)
884 {
885 // Select pistol as an infinite-ammo backup
886 const WeaponClass *pistol = StrWeaponClass("Pistol");
887 if (!PlayerHasWeapon(p, pistol))
888 {
889 if (gunCount == MAX_GUNS)
890 {
891 // Player has full weapons; replace last gun
892 p->guns[MAX_GUNS - 1] = pistol;
893 }
894 else
895 {
896 // Add the pistol
897 p->guns[gunCount] = pistol;
898 gunCount++;
899 }
900 }
901 }
902 }
903
904 void AICoopOnPickupGun(TActor *a, const int gunId)
905 {
906 // Remember that we are over a gun pickup;
907 // we will act upon it later (during GetCmd)
908 a->aiContext->OnGunId = gunId;
909 }