Debian Codegraph @

src/cdogs/actors.c

raw symbols SCIP
1 /*
2 C-Dogs SDL
3 A port of the legendary (and fun) action/arcade cdogs.
4 Copyright (C) 1995 Ronny Wester
5 Copyright (C) 2003 Jeremy Chin
6 Copyright (C) 2003-2007 Lucas Martin-King
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22 This file incorporates work covered by the following copyright and
23 permission notice:
24
25 Copyright (c) 2013-2025 Cong Xu
26 All rights reserved.
27
28 Redistribution and use in source and binary forms, with or without
29 modification, are permitted provided that the following conditions are met:
30
31 Redistributions of source code must retain the above copyright notice, this
32 list of conditions and the following disclaimer.
33 Redistributions in binary form must reproduce the above copyright notice,
34 this list of conditions and the following disclaimer in the documentation
35 and/or other materials provided with the distribution.
36
37 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
38 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
41 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
42 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
43 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
44 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
45 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
47 POSSIBILITY OF SUCH DAMAGE.
48 */
49 #include "actors.h"
50
51 #include <assert.h>
52 #include <float.h>
53 #include <math.h>
54 #include <stdlib.h>
55 #include <string.h>
56
57 #include "actor_fire.h"
58 #include "actor_pickup.h"
59 #include "actor_placement.h"
60 #include "ai.h"
61 #include "ai_coop.h"
62 #include "ai_utils.h"
63 #include "ammo.h"
64 #include "character.h"
65 #include "collision/collision.h"
66 #include "config.h"
67 #include "damage.h"
68 #include "defs.h"
69 #include "draw/drawtools.h"
70 #include "events.h"
71 #include "game.h"
72 #include "game_events.h"
73 #include "gamedata.h"
74 #include "log.h"
75 #include "material.h"
76 #include "mission.h"
77 #include "pic_manager.h"
78 #include "sounds.h"
79 #include "thing.h"
80 #include "triggers.h"
81 #include "utils.h"
82
83 #define FOOTSTEP_MAX_ANIM_SPEED 2
84 #define REPEL_STRENGTH 0.06f
85 #define SLIDE_LOCK 50
86 #define SLIDE_X (TILE_WIDTH / 3)
87 #define SLIDE_Y (TILE_HEIGHT / 3)
88 #define VEL_DECAY_X (TILE_WIDTH * 2 / 256.0f)
89 #define VEL_DECAY_Y (TILE_WIDTH * 2 / 256.0f) // Note: deliberately tile width
90 #define SOUND_LOCK_WEAPON_CLICK 20
91 #define DRAW_RADIAN_SPEED (MPI / 16)
92 // Percent of health considered low; bleed and flash HUD if low
93 #define LOW_HEALTH_PERCENTAGE 25
94 #define GORE_EMITTER_MAX_SPEED 0.25f
95 #define CHATTER_SHOW_SECONDS 2
96 #define CHATTER_SWITCH_GUN \
97 45 // TODO: based on clock time instead of game ticks
98 #define GRIMACE_PERIOD 20
99 #define GRIMACE_HIT_TICKS 39
100 #define GRIMACE_MELEE_TICKS 19
101 #define DAMAGE_TEXT_DISTANCE_RESET_THRESHOLD (ACTOR_W / 2)
102 #define FOOTPRINT_MAX 8
103
104 CArray gPlayerIds;
105
106 CArray gActors;
107 static unsigned int sActorUIDs = 0;
108
109 void ActorSetState(TActor *actor, const ActorAnimation state)
110 {
111 actor->anim = AnimationGetActorAnimation(state);
112 }
113
114 static void ActorUpdateWeapon(TActor *a, Weapon *w, const int ticks);
115 static void CheckPickups(TActor *actor);
116 static void ActorAddAmmoPickup(const TActor *actor);
117 static void ActorAddGunPickup(const TActor *actor);
118 void UpdateActorState(TActor *actor, int ticks)
119 {
120 ActorUpdateWeapon(actor, ACTOR_GET_GUN(actor), ticks);
121 ActorUpdateWeapon(actor, ACTOR_GET_GRENADE(actor), ticks);
122
123 // If we're ready to pick up, always check the pickups
124 if (actor->PickupAll && !gCampaign.IsClient)
125 {
126 CheckPickups(actor);
127 }
128 // Stop picking up to prevent multiple pickups
129 // (require repeated key presses)
130 actor->PickupAll = false;
131
132 if (actor->health > 0)
133 {
134 actor->flamed = MAX(0, actor->flamed - ticks);
135 if (actor->poisoned)
136 {
137 if ((actor->poisoned & 7) == 0)
138 {
139 InjureActor(actor, 1);
140 }
141 actor->poisoned = MAX(0, actor->poisoned - ticks);
142 }
143 actor->petrified = MAX(0, actor->petrified - ticks);
144 actor->confused = MAX(0, actor->confused - ticks);
145
146 // Reset accumulated damage if FPS_FRAMELIMIT passed since taking
147 // damage
148 actor->damageCooldownTicks += ticks;
149 if (actor->accumulatedDamage)
150 {
151 if (actor->damageCooldownTicks >= FPS_FRAMELIMIT)
152 {
153 actor->accumulatedDamage = 0;
154 actor->damageCooldownTicks = 0;
155 }
156 }
157 }
158
159 actor->slideLock = MAX(0, actor->slideLock - ticks);
160
161 ThingUpdate(&actor->thing, ticks);
162
163 actor->stateCounter = MAX(0, actor->stateCounter - ticks);
164 if (actor->stateCounter > 0)
165 {
166 return;
167 }
168
169 const Character *c = ActorGetCharacter(actor);
170
171 if (actor->health <= 0)
172 {
173 if (actor->dead == 0 && !gCampaign.IsClient)
174 {
175 // Just entered dead state
176 // Drop weapon/ammo
177 if (c->Drop)
178 {
179 GameEvent e = GameEventNew(GAME_EVENT_ADD_PICKUP);
180 strcpy(e.u.AddPickup.PickupClass, c->Drop->Name);
181 e.u.AddPickup.Pos = Vec2ToNet(actor->Pos);
182 GameEventsEnqueue(&gGameEvents, e);
183 }
184 else if (!gCampaign.Setting.BuyAndSell)
185 {
186 // Add an ammo pickup of the actor's gun
187 if (gCampaign.Setting.Ammo)
188 {
189 ActorAddAmmoPickup(actor);
190 }
191
192 ActorAddGunPickup(actor);
193 }
194 }
195 actor->dead++;
196 actor->MoveVel = svec2_zero();
197 actor->stateCounter = 4;
198 actor->thing.flags = 0;
199 return;
200 }
201
202 // Draw rotation interpolation
203 const float targetRadians = (float)dir2radians[actor->direction];
204 if (actor->DrawRadians - targetRadians > MPI)
205 {
206 actor->DrawRadians -= 2 * MPI;
207 }
208 if (actor->DrawRadians - targetRadians < -MPI)
209 {
210 actor->DrawRadians += 2 * MPI;
211 }
212 const float dr = actor->DrawRadians - targetRadians;
213 if (dr < 0)
214 {
215 actor->DrawRadians += (float)MIN(DRAW_RADIAN_SPEED * ticks, -dr);
216 }
217 else if (dr > 0)
218 {
219 actor->DrawRadians -= (float)MIN(DRAW_RADIAN_SPEED * ticks, dr);
220 }
221
222 const struct vec2i tilePos = Vec2ToTile(actor->Pos);
223 const Tile *t = MapGetTile(&gMap, tilePos);
224
225 // Footstep sounds
226 // Step on 2 and 6
227 // TODO: custom animation and footstep frames
228 const int frame = AnimationGetFrame(&actor->anim);
229 const bool isFootstepFrame = actor->anim.Type == ACTORANIMATION_WALKING &&
230 (frame == 2 || frame == 6) &&
231 actor->anim.newFrame;
232 if (isFootstepFrame)
233 {
234
235 if (ConfigGetBool(&gConfig, "Sound.Footsteps"))
236 {
237 GameEvent e = GameEventNew(GAME_EVENT_SOUND_AT);
238 MatGetFootstepSound(c->Class, t, e.u.SoundAt.Sound);
239 e.u.SoundAt.Pos = Vec2ToNet(actor->thing.Pos);
240 e.u.SoundAt.Distance = c->Class->FootstepsDistancePlus;
241 GameEventsEnqueue(&gGameEvents, e);
242 }
243
244 // See if we've stepped on something that leaves footprints
245 const color_t footprintMask = MatGetFootprintMask(t);
246 if (footprintMask.a != 0)
247 {
248 actor->footprintMask = footprintMask;
249 actor->footprintCounter = FOOTPRINT_MAX;
250 }
251
252 // Footprint particle
253 if (actor->footprintCounter > 0)
254 {
255 GameEvent e = GameEventNew(GAME_EVENT_ADD_PARTICLE);
256 e.u.AddParticle.Class =
257 StrParticleClass(&gParticleClasses, "footprint");
258 const struct vec2 footOffset = svec2_scale(
259 Vec2FromRadiansScaled(actor->DrawRadians + MPI_2),
260 frame == 2 ? 3.f : -3.f);
261 e.u.AddParticle.Pos = svec2_subtract(actor->thing.Pos, footOffset);
262 e.u.AddParticle.Angle = actor->DrawRadians;
263 e.u.AddParticle.Mask = actor->footprintMask;
264 // Fade footprint away gradually
265 e.u.AddParticle.Mask.a = (uint8_t)MIN(
266 actor->footprintCounter * e.u.AddParticle.Mask.a /
267 FOOTPRINT_MAX,
268 255);
269 GameEventsEnqueue(&gGameEvents, e);
270 actor->footprintCounter--;
271 }
272 }
273
274 // Damage when on special tiles
275 if (!gCampaign.IsClient && actor->anim.Type == ACTORANIMATION_WALKING
276 ? isFootstepFrame
277 : (gMission.time % FPS_FRAMELIMIT) == 0)
278 {
279 const BulletClass *b = MatGetDamageBullet(t);
280 if (b != NULL)
281 {
282 GameEvent e = GameEventNew(GAME_EVENT_THING_DAMAGE);
283 e.u.ThingDamage.UID = actor->uid;
284 e.u.ThingDamage.Kind = KIND_CHARACTER;
285 BulletToDamageEvent(b, &e);
286 GameEventsEnqueue(&gGameEvents, e);
287 }
288 }
289
290 // Animation
291 float animTicks = 1;
292 if (actor->anim.Type == ACTORANIMATION_WALKING)
293 {
294 // Update walk animation based on actor speed
295 animTicks =
296 MIN(svec2_length(svec2_add(actor->MoveVel, actor->thing.Vel)),
297 FOOTSTEP_MAX_ANIM_SPEED);
298 }
299 animTicks *= ticks;
300 AnimationUpdate(&actor->anim, animTicks);
301
302 // Chatting
303 actor->ChatterCounter = MAX(0, actor->ChatterCounter - ticks);
304 if (actor->ChatterCounter == 0)
305 {
306 // Stop chatting
307 strcpy(actor->Chatter, "");
308 }
309
310 actor->grimaceCounter = MAX(0, actor->grimaceCounter - ticks);
311 }
312 static void ActorUpdateWeapon(TActor *a, Weapon *w, const int ticks)
313 {
314 if (w->Gun == NULL)
315 {
316 return;
317 }
318 WeaponUpdate(w, ticks);
319 ActorFireUpdate(w, a, ticks);
320 for (int i = 0; i < WeaponClassNumBarrels(w->Gun); i++)
321 {
322 if (WeaponBarrelIsOverheating(w, i))
323 {
324 AddParticle ap;
325 memset(&ap, 0, sizeof ap);
326 ap.Pos = svec2_add(a->Pos, ActorGetMuzzleOffset(a, w, i));
327 ap.Z = WeaponClassGetMuzzleHeight(w->Gun, w->barrels[i].state, i) /
328 Z_FACTOR;
329 ap.Mask = colorWhite;
330 EmitterUpdate(&a->barrelSmoke, &ap, ticks);
331 }
332 }
333 }
334
335 static bool CanMeleeTarget(
336 const TActor *a, const Weapon *w, const Thing *target);
337 static struct vec2 GetConstrainedPos(
338 const Map *map, const struct vec2 from, const struct vec2 to,
339 const struct vec2i size);
340 static void OnMove(TActor *a);
341 static bool TryMoveActor(TActor *actor, struct vec2 pos)
342 {
343 CASSERT(
344 !svec2_is_nearly_equal(actor->Pos, pos, EPSILON_POS),
345 "trying to move to same position");
346 actor->CanPickupSpecial = false;
347
348 // Don't check collisions for pilots
349 if (actor->vehicleUID == -1)
350 {
351 actor->hasCollided = true;
352
353 const struct vec2 oldPos = actor->Pos;
354 pos = GetConstrainedPos(&gMap, actor->Pos, pos, actor->thing.size);
355 if (svec2_is_nearly_equal(oldPos, pos, EPSILON_POS))
356 {
357 return false;
358 }
359
360 // Check for object collisions
361 const CollisionParams params = {
362 THING_IMPASSABLE, CalcCollisionTeam(true, actor),
363 IsPVP(gCampaign.Entry.Mode), false};
364 const Thing *target = OverlapGetFirstItem(
365 &actor->thing, pos, actor->thing.size, actor->thing.Vel, params);
366 if (target && actor->health > 0)
367 {
368 // We are running into an object or actor
369 // If we have an auto-melee weapon and aren't shooting, switch to
370 // it
371 const Weapon *meleeW = &actor->guns[MELEE_SLOT];
372 if (actor->gunIndex != MELEE_SLOT && meleeW->Gun &&
373 meleeW->Gun->Type == GUNTYPE_MELEE &&
374 meleeW->Gun->u.Normal.Auto && !actor->hasShot &&
375 CanMeleeTarget(actor, meleeW, target))
376 {
377 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_SWITCH_GUN);
378 e.u.ActorSwitchGun.UID = actor->uid;
379 e.u.ActorSwitchGun.GunIdx = MELEE_SLOT;
380 GameEventsEnqueue(&gGameEvents, e);
381 }
382 else
383 {
384 Weapon *gun = ACTOR_GET_WEAPON(actor);
385 if (CanMeleeTarget(actor, gun, target))
386 {
387 const int barrel = ActorGetCanFireBarrel(actor, gun);
388 if (barrel >= 0)
389 {
390 // TODO: support melee weapons on multi guns
391 const BulletClass *b =
392 WeaponClassGetBullet(gun->Gun, barrel);
393 if (CanHit(b, actor->flags, actor->uid, target))
394 {
395 // Tell the server that we want to melee something
396 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_MELEE);
397 e.u.Melee.UID = actor->uid;
398 strcpy(e.u.Melee.BulletClass, b->Name);
399 e.u.Melee.TargetKind = target->kind;
400 switch (target->kind)
401 {
402 case KIND_CHARACTER:
403 e.u.Melee.TargetUID =
404 ((const TActor *)CArrayGet(
405 &gActors, target->id))
406 ->uid;
407 e.u.Melee.HitType = HIT_FLESH;
408 break;
409 case KIND_OBJECT:
410 e.u.Melee.TargetUID =
411 ((const TObject *)CArrayGet(
412 &gObjs, target->id))
413 ->uid;
414 e.u.Melee.HitType = HIT_OBJECT;
415 break;
416 default:
417 CASSERT(false, "cannot damage target kind");
418 break;
419 }
420 if (gun->barrels[barrel].soundLock > 0)
421 {
422 e.u.Melee.HitType = (int)HIT_NONE;
423 }
424 GameEventsEnqueue(&gGameEvents, e);
425 WeaponBarrelOnFire(gun, barrel);
426
427 // Only set grimace when counter 0 so that the
428 // actor alternates their grimace
429 if (actor->grimaceCounter == 0)
430 {
431 actor->grimaceCounter = GRIMACE_MELEE_TICKS;
432 }
433 }
434 }
435 return false;
436 }
437 }
438
439 const struct vec2 yPos = svec2(actor->Pos.x, pos.y);
440 if (OverlapGetFirstItem(
441 &actor->thing, yPos, actor->thing.size, svec2_zero(),
442 params))
443 {
444 pos.y = actor->Pos.y;
445 }
446 const struct vec2 xPos = svec2(pos.x, actor->Pos.y);
447 if (OverlapGetFirstItem(
448 &actor->thing, xPos, actor->thing.size, svec2_zero(),
449 params))
450 {
451 pos.x = actor->Pos.x;
452 }
453 if (pos.x != actor->Pos.x && pos.y != actor->Pos.y)
454 {
455 // Both x-only or y-only movement are viable,
456 // i.e. we are colliding corner vs corner
457 // Arbitrarily choose x-only movement
458 pos.y = actor->Pos.y;
459 }
460 if ((pos.x == actor->Pos.x && pos.y == actor->Pos.y) ||
461 IsCollisionWithWall(pos, actor->thing.size))
462 {
463 return false;
464 }
465 }
466 }
467
468 actor->Pos = pos;
469 OnMove(actor);
470
471 actor->hasCollided = false;
472 return true;
473 }
474 static bool CanMeleeTarget(
475 const TActor *a, const Weapon *w, const Thing *target)
476 {
477 // Check valid melee weapon
478 if (!w->Gun || WeaponClassCanShoot(w->Gun))
479 return false;
480 // Check for melee damage if we are the owner of the actor
481 // Is client: must be local player
482 // Not client: AI or local player
483 if (!ActorIsLocalPlayer(a->uid) &&
484 (gCampaign.IsClient || a->PlayerUID >= 0))
485 return false;
486 // Check if any barrel can fire and melee
487 for (int barrel = 0; barrel < WeaponClassNumBarrels(w->Gun); barrel++)
488 {
489 const BulletClass *b = WeaponClassGetBullet(w->Gun, barrel);
490 if (b == NULL)
491 continue;
492 if (target->kind == KIND_OBJECT)
493 {
494 if (!b->Hit.Object.Hit)
495 continue;
496 const TObject *object = CArrayGet(&gObjs, target->id);
497 if (object && !ObjIsDangerous(object))
498 return true;
499 }
500 else if (b->Hit.Flesh.Hit && target->kind == KIND_CHARACTER)
501 return true;
502 }
503 return false;
504 }
505 // Get a movement position that is constrained by collisions
506 // May return a position that is the same as the 'from', that is, we cannot
507 // move in the direction specified.
508 static struct vec2 GetConstrainedPos(
509 const Map *map, const struct vec2 from, const struct vec2 to,
510 const struct vec2i size)
511 {
512 // Check collision with wall
513 if (!IsCollisionWithWall(to, size))
514 {
515 // Not in collision; just return where we wanted to go
516 return to;
517 }
518
519 CASSERT(size.x >= size.y, "tall collision not supported");
520 const struct vec2 dv = svec2_subtract(to, from);
521
522 // If moving diagonally, use rectangular bounds and
523 // try to move in only x or y directions
524 if (!nearly_equal(dv.x, 0.0f, EPSILON_POS) &&
525 !nearly_equal(dv.y, 0.0f, EPSILON_POS))
526 {
527 // X-only movement
528 const struct vec2 xVec = svec2(to.x, from.y);
529 if (!IsCollisionWithWall(xVec, size))
530 {
531 return xVec;
532 }
533 // Y-only movement
534 const struct vec2 yVec = svec2(from.x, to.y);
535 if (!IsCollisionWithWall(yVec, size))
536 {
537 return yVec;
538 }
539 // If we're still stuck, we're possibly stuck on a corner which is not
540 // in collision with a diamond but is colliding with the box.
541 // If so try x- or y-only movement, but with the benefit of diamond
542 // slipping.
543 const struct vec2 xPos = GetConstrainedPos(map, from, xVec, size);
544 if (!svec2_is_nearly_equal(xPos, from, EPSILON_POS))
545 {
546 return xPos;
547 }
548 const struct vec2 yPos = GetConstrainedPos(map, from, yVec, size);
549 if (!svec2_is_nearly_equal(yPos, from, EPSILON_POS))
550 {
551 return yPos;
552 }
553 }
554
555 // Now check diagonal movement, if we were moving in an x- or y-
556 // only direction
557 // Note: we're moving at extra speed because dx/dy are only magnitude 1;
558 // if we divide then we get 0 which ruins the logic
559 if (nearly_equal(dv.x, 0.0f, EPSILON_POS))
560 {
561 // Moving up or down; try moving to the left or right diagonally
562 // Scale X movement because our diamond is wider than tall, so we
563 // may need to scale the diamond wider.
564 const int xScale =
565 size.x > size.y ? (int)ceil((double)size.x / size.y) : 1;
566 const struct vec2 diag1Vec =
567 svec2_add(from, svec2(-dv.y * xScale, dv.y));
568 if (!IsCollisionDiamond(map, diag1Vec, size))
569 {
570 return diag1Vec;
571 }
572 const struct vec2 diag2Vec =
573 svec2_add(from, svec2(dv.y * xScale, dv.y));
574 if (!IsCollisionDiamond(map, diag2Vec, size))
575 {
576 return diag2Vec;
577 }
578 }
579 else if (nearly_equal(dv.y, 0.0f, EPSILON_POS))
580 {
581 // Moving left or right; try moving up or down diagonally
582 const struct vec2 diag1Vec = svec2_add(from, svec2(dv.x, -dv.x));
583 if (!IsCollisionDiamond(map, diag1Vec, size))
584 {
585 return diag1Vec;
586 }
587 const struct vec2 diag2Vec = svec2_add(from, svec2(dv.x, dv.x));
588 if (!IsCollisionDiamond(map, diag2Vec, size))
589 {
590 return diag2Vec;
591 }
592 }
593
594 // All alternative movements are in collision; don't move
595 return from;
596 }
597
598 void ActorMove(const NActorMove am)
599 {
600 TActor *a = ActorGetByUID(am.UID);
601 if (a == NULL || !a->isInUse)
602 return;
603 a->Pos = NetToVec2(am.Pos);
604 a->MoveVel = NetToVec2(am.MoveVel);
605 OnMove(a);
606 }
607 static void CheckTrigger(const TActor *a, const Map *map);
608 static void CheckRescue(const TActor *a);
609 static void OnMove(TActor *a)
610 {
611 MapTryMoveThing(&gMap, &a->thing, a->Pos);
612 if (MapIsTileInExit(&gMap, &a->thing, -1) != -1)
613 {
614 a->action = ACTORACTION_EXITING;
615 }
616 else
617 {
618 a->action = ACTORACTION_MOVING;
619 }
620
621 if (!gCampaign.IsClient)
622 {
623 CheckTrigger(a, &gMap);
624
625 CheckPickups(a);
626
627 CheckRescue(a);
628 }
629 }
630 static void CheckTrigger(const TActor *a, const Map *map)
631 {
632 // Don't let sleeping AI actors trigger tiles
633 if (a->PlayerUID < 0 && a->flags & FLAGS_SLEEPING)
634 {
635 return;
636 }
637 const struct vec2i tilePos = Vec2ToTile(a->Pos);
638 const bool showLocked = ActorIsLocalPlayer(a->uid);
639 const Tile *t = MapGetTile(map, tilePos);
640 const int keyFlags =
641 (a->flags & FLAGS_UNLOCK_DOORS) ? -1 : gMission.KeyFlags;
642 CA_FOREACH(Trigger *, tp, t->triggers)
643 if (!TriggerTryActivate(*tp, keyFlags, tilePos) && (*tp)->isActive &&
644 TriggerCannotActivate(*tp) && showLocked)
645 {
646 TriggerSetCannotActivate(*tp);
647 GameEvent s = GameEventNew(GAME_EVENT_ADD_PARTICLE);
648 s.u.AddParticle.Class =
649 StrParticleClass(&gParticleClasses, "locked_text");
650 s.u.AddParticle.Pos = Vec2CenterOfTile(tilePos);
651 s.u.AddParticle.Z = (BULLET_Z * 2) * Z_FACTOR;
652 sprintf(s.u.AddParticle.Text, "locked");
653 GameEventsEnqueue(&gGameEvents, s);
654 }
655 CA_FOREACH_END()
656 }
657 // Check if the player can pickup any item
658 static bool CheckPickupFunc(
659 Thing *ti, void *data, const struct vec2 colA, const struct vec2 colB,
660 const struct vec2 normal);
661 static void CheckPilot(const TActor *a, const CollisionParams params);
662 static void CheckPickups(TActor *actor)
663 {
664 // NPCs can't pickup
665 if (actor->PlayerUID < 0)
666 {
667 return;
668 }
669 const CollisionParams params = {
670 0, CalcCollisionTeam(true, actor), IsPVP(gCampaign.Entry.Mode), false};
671 OverlapThings(
672 &actor->thing, actor->Pos, actor->thing.Vel, actor->thing.size, params,
673 CheckPickupFunc, actor, NULL, NULL, NULL);
674 if (actor->PickupAll)
675 {
676 const CollisionParams paramsPilot = {
677 THING_IMPASSABLE | THING_CAN_BE_SHOT, params.Team, params.IsPVP,
678 true};
679 CheckPilot(actor, paramsPilot);
680 }
681 }
682 static bool CheckPickupFunc(
683 Thing *ti, void *data, const struct vec2 colA, const struct vec2 colB,
684 const struct vec2 normal)
685 {
686 UNUSED(colA);
687 UNUSED(colB);
688 UNUSED(normal);
689 // Always return true, as we can pickup multiple items in one go
690 if (ti->kind != KIND_PICKUP)
691 return true;
692 TActor *a = data;
693 PickupPickup(a, CArrayGet(&gPickups, ti->id), a->PickupAll);
694 return true;
695 }
696 static void CheckPilot(const TActor *a, const CollisionParams params)
697 {
698 const Thing *ti = OverlapGetFirstItem(
699 &a->thing, a->Pos, a->thing.size, a->thing.Vel, params);
700 if (ti == NULL || ti->kind != KIND_CHARACTER)
701 return;
702 const TActor *vehicle = CArrayGet(&gActors, ti->id);
703 if (vehicle->pilotUID >= 0)
704 return;
705
706 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_PILOT);
707 e.u.Pilot.On = true;
708 e.u.Pilot.UID = a->uid;
709 e.u.Pilot.VehicleUID = vehicle->uid;
710 GameEventsEnqueue(&gGameEvents, e);
711 }
712 static void CheckRescue(const TActor *a)
713 {
714 // NPCs can't rescue
715 if (a->PlayerUID < 0)
716 return;
717
718 // Check an area slightly bigger than the actor's size for rescue
719 // objectives
720 #define RESCUE_CHECK_PAD 2
721 const CollisionParams params = {
722 THING_IMPASSABLE, CalcCollisionTeam(true, a),
723 IsPVP(gCampaign.Entry.Mode), false};
724 const Thing *target = OverlapGetFirstItem(
725 &a->thing, a->Pos,
726 svec2i_add(a->thing.size, svec2i(RESCUE_CHECK_PAD, RESCUE_CHECK_PAD)),
727 a->thing.Vel, params);
728 if (target != NULL && target->kind == KIND_CHARACTER)
729 {
730 TActor *other = CArrayGet(&gActors, target->id);
731 CASSERT(other->isInUse, "Cannot find nonexistent player");
732 if (other->flags & FLAGS_PRISONER)
733 {
734 other->flags &= ~FLAGS_PRISONER;
735 GameEvent e = GameEventNew(GAME_EVENT_RESCUE_CHARACTER);
736 e.u.Rescue.UID = other->uid;
737 GameEventsEnqueue(&gGameEvents, e);
738 UpdateMissionObjective(
739 &gMission, other->thing.flags, OBJECTIVE_RESCUE, 1);
740 }
741 }
742 }
743
744 void ActorHeal(TActor *actor, const int amount, const bool exceedMax)
745 {
746 actor->health += amount;
747 const int maxHealth = ActorGetMaxHeal(actor, exceedMax);
748 actor->health = MIN(actor->health, maxHealth);
749 AddParticle ap;
750 memset(&ap, 0, sizeof ap);
751 ap.Pos = actor->Pos;
752 ap.Z = 10;
753 for (int i = 0; i < MAX(amount / 20, 1); i++)
754 {
755 ap.Vel = svec2(RAND_FLOAT(-0.2f, 0.2f), RAND_FLOAT(-0.2f, 0.2f));
756 EmitterStart(&actor->healEffect, &ap);
757 }
758 }
759
760 void InjureActor(TActor *actor, int injury)
761 {
762 const int lastHealth = actor->health;
763 actor->health -= injury;
764 LOG(LM_ACTOR, LL_DEBUG, "actor uid(%d) injured %d -(%d)-> %d", actor->uid,
765 lastHealth, injury, actor->health);
766 if (lastHealth > 0 && actor->health <= 0)
767 {
768 actor->stateCounter = 0;
769 GameEvent es = GameEventNew(GAME_EVENT_SOUND_AT);
770 CharacterClassGetSound(
771 ActorGetCharacter(actor)->Class, es.u.SoundAt.Sound, "die");
772 es.u.SoundAt.Pos = Vec2ToNet(actor->thing.Pos);
773 GameEventsEnqueue(&gGameEvents, es);
774 if (actor->PlayerUID >= 0)
775 {
776 es = GameEventNew(GAME_EVENT_SOUND_AT);
777 strcpy(es.u.SoundAt.Sound, "hahaha");
778 es.u.SoundAt.Pos = Vec2ToNet(actor->thing.Pos);
779 GameEventsEnqueue(&gGameEvents, es);
780 }
781 if (actor->thing.flags & THING_OBJECTIVE)
782 {
783 UpdateMissionObjective(
784 &gMission, actor->thing.flags, OBJECTIVE_KILL, 1);
785 // If we've killed someone we have rescued, deduct from the
786 // rescue objective
787 if (!(actor->flags & FLAGS_PRISONER))
788 {
789 UpdateMissionObjective(
790 &gMission, actor->thing.flags, OBJECTIVE_RESCUE, -1);
791 }
792 }
793 }
794 }
795
796 void ActorAddAmmo(TActor *actor, const int ammoId, const int amount)
797 {
798 int *ammo = CArrayGet(&actor->ammo, ammoId);
799 *ammo += amount;
800 const int ammoMax = AmmoGetById(&gAmmo, ammoId)->Max;
801 if (ammoMax > 0)
802 {
803 *ammo = CLAMP(*ammo, 0, ammoMax);
804 }
805 }
806
807 bool ActorUsesAmmo(const TActor *actor, const int ammoId)
808 {
809 if (!actor)
810 {
811 return false;
812 }
813 for (int i = 0; i < MAX_WEAPONS; i++)
814 {
815 const WeaponClass *wc = actor->guns[i].Gun;
816 if (wc == NULL)
817 {
818 continue;
819 }
820 for (int j = 0; j < WeaponClassNumBarrels(wc); j++)
821 {
822 if (WC_BARREL_ATTR(*wc, AmmoId, j) == ammoId)
823 {
824 return true;
825 }
826 }
827 }
828 return false;
829 }
830
831 static void ActorSetChatter(TActor *a, const char *text, const int count)
832 {
833 strcpy(a->Chatter, text);
834 a->ChatterCounter = count;
835 }
836
837 void ActorReplaceGun(const NActorReplaceGun rg)
838 {
839 TActor *a = ActorGetByUID(rg.UID);
840 if (a == NULL || !a->isInUse)
841 return;
842 const WeaponClass *wc = StrWeaponClass(rg.Gun);
843 CASSERT(wc != NULL, "cannot find gun");
844 // If player already has gun, don't do anything
845 if (ActorFindGun(a, wc) >= 0)
846 {
847 return;
848 }
849 LOG(LM_ACTOR, LL_DEBUG, "actor uid(%d) replacing gun(%s) idx(%d)",
850 (int)rg.UID, rg.Gun, rg.GunIdx);
851 Weapon w = WeaponCreate(wc);
852 memcpy(&a->guns[rg.GunIdx], &w, sizeof w);
853 // Switch immediately to picked up gun
854 if (ActorCanSwitchToWeapon(a, rg.GunIdx))
855 {
856 a->gunIndex = rg.GunIdx;
857 }
858 SoundPlayAt(&gSoundDevice, wc->SwitchSound, a->Pos);
859 // Show gun switch text as chatter, but only for PCs
860 if (a->PlayerUID >= 0)
861 {
862 ActorSetChatter(a, wc->name, CHATTER_SWITCH_GUN);
863 }
864 }
865
866 int ActorFindGun(const TActor *a, const WeaponClass *wc)
867 {
868 for (int i = 0; i < MAX_WEAPONS; i++)
869 {
870 if (a->guns[i].Gun == wc)
871 {
872 return i;
873 }
874 }
875 return -1;
876 }
877
878 int ActorGetNumWeapons(const TActor *a)
879 {
880 int count = 0;
881 for (int i = 0; i < MAX_WEAPONS; i++)
882 {
883 if (a->guns[i].Gun != NULL)
884 {
885 count++;
886 }
887 }
888 return count;
889 }
890 int ActorGetNumGuns(const TActor *a)
891 {
892 int count = 0;
893 for (int i = 0; i < MAX_GUNS; i++)
894 {
895 if (a->guns[i].Gun != NULL)
896 {
897 count++;
898 }
899 }
900 return count;
901 }
902 int ActorGetNumGrenades(const TActor *a)
903 {
904 int count = 0;
905 for (int i = MAX_GUNS; i < MAX_WEAPONS; i++)
906 {
907 if (a->guns[i].Gun != NULL)
908 {
909 count++;
910 }
911 }
912 return count;
913 }
914
915 // Set AI state and possibly say something based on the state
916 void ActorSetAIState(TActor *actor, const AIState s)
917 {
918 if (AIContextSetState(actor->aiContext, s) &&
919 AIContextShowChatter(ConfigGetEnum(&gConfig, "Interface.AIChatter")))
920 {
921 ActorSetChatter(
922 actor, AIStateGetChatterText(actor->aiContext->State),
923 CHATTER_SHOW_SECONDS * ConfigGetInt(&gConfig, "Game.FPS"));
924 }
925 }
926
927 void ActorPilot(const NActorPilot ap)
928 {
929 TActor *pilot = ActorGetByUID(ap.UID);
930 TActor *vehicle = ActorGetByUID(ap.VehicleUID);
931 if (ap.On)
932 {
933 CASSERT(pilot->vehicleUID == -1, "already piloting");
934 pilot->vehicleUID = vehicle->uid;
935 CASSERT(vehicle->pilotUID == -1, "already has pilot");
936 vehicle->pilotUID = pilot->uid;
937 char buf[256];
938 CharacterClassGetSound(
939 ActorGetCharacter(vehicle)->Class, buf, "alert");
940 SoundPlayAt(&gSoundDevice, StrSound(buf), vehicle->Pos);
941 }
942 else
943 {
944 CASSERT(pilot->vehicleUID != -1, "not piloting");
945 pilot->vehicleUID = -1;
946 CASSERT(vehicle->pilotUID != -1, "doesn't have pilot");
947 vehicle->pilotUID = -1;
948 char buf[256];
949 MatGetFootstepSound(ActorGetCharacter(pilot)->Class, NULL, buf);
950 SoundPlayAt(&gSoundDevice, StrSound(buf), vehicle->Pos);
951 }
952 }
953
954 static void FireWeapon(TActor *a, Weapon *w)
955 {
956 if (w->Gun == NULL)
957 {
958 return;
959 }
960 // If currently equipping an auto-melee weapon,
961 // and if possible, switch to the last gun
962 if (w->Gun->Type == GUNTYPE_MELEE && w->Gun->u.Normal.Auto &&
963 a->guns[a->lastGunIdx].Gun != NULL)
964 {
965 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_SWITCH_GUN);
966 e.u.ActorSwitchGun.UID = a->uid;
967 e.u.ActorSwitchGun.GunIdx = a->lastGunIdx;
968 GameEventsEnqueue(&gGameEvents, e);
969 return;
970 }
971 const int barrel = ActorGetCanFireBarrel(a, w);
972 if (barrel == -1)
973 {
974 const int unlockedBarrel = WeaponGetUnlockedBarrel(w);
975 if (unlockedBarrel >= 0 && gCampaign.Setting.Ammo)
976 {
977 CASSERT(
978 ActorWeaponGetAmmo(a, w->Gun, unlockedBarrel) == 0,
979 "should be out of ammo");
980 // Play a clicking sound if this weapon is out of ammo
981 if (w->clickLock <= 0)
982 {
983 GameEvent es = GameEventNew(GAME_EVENT_SOUND_AT);
984 strcpy(es.u.SoundAt.Sound, "click");
985 es.u.SoundAt.Pos = Vec2ToNet(a->Pos);
986 GameEventsEnqueue(&gGameEvents, es);
987 w->clickLock = SOUND_LOCK_WEAPON_CLICK;
988 }
989 }
990 return;
991 }
992 ActorFireBarrel(w, a, barrel);
993 const int ammoId = WC_BARREL_ATTR(*(w->Gun), AmmoId, barrel);
994 if (a->PlayerUID >= 0 && gCampaign.Setting.Ammo && ammoId >= 0)
995 {
996 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_USE_AMMO);
997 e.u.UseAmmo.UID = a->uid;
998 e.u.UseAmmo.PlayerUID = a->PlayerUID;
999 e.u.UseAmmo.Ammo.Id = ammoId;
1000 e.u.UseAmmo.Ammo.Amount = 1;
1001 GameEventsEnqueue(&gGameEvents, e);
1002 }
1003 const TActor *firingActor = ActorGetByUID(a->pilotUID);
1004 const int cost = WC_BARREL_ATTR(*(w->Gun), Cost, barrel);
1005 if (firingActor->PlayerUID >= 0 && cost != 0)
1006 {
1007 // Classic C-Dogs score consumption
1008 GameEvent e = GameEventNew(GAME_EVENT_SCORE);
1009 e.u.Score.PlayerUID = firingActor->PlayerUID;
1010 e.u.Score.Score = -cost;
1011 GameEventsEnqueue(&gGameEvents, e);
1012 }
1013 }
1014
1015 static bool ActorTryChangeDirection(
1016 TActor *actor, const int cmd, const int prevCmd)
1017 {
1018 const bool willChangeDirecton =
1019 !actor->petrified && CMD_HAS_DIRECTION(cmd) &&
1020 (!Button2(cmd) || ConfigGetEnum(&gConfig, "Game.SwitchMoveStyle") !=
1021 SWITCHMOVE_STRAFE) &&
1022 (!Button1(prevCmd) ||
1023 ConfigGetEnum(&gConfig, "Game.FireMoveStyle") != FIREMOVE_STRAFE);
1024 const direction_e dir = CmdToDirection(cmd);
1025 if (willChangeDirecton && dir != actor->direction)
1026 {
1027 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_DIR);
1028 e.u.ActorDir.UID = actor->uid;
1029 e.u.ActorDir.Dir = (int32_t)dir;
1030 GameEventsEnqueue(&gGameEvents, e);
1031 // Change direction immediately because this affects shooting
1032 actor->direction = dir;
1033 }
1034 return willChangeDirecton;
1035 }
1036
1037 static bool ActorTryShoot(TActor *actor, const int cmd)
1038 {
1039 const bool willShoot = !actor->petrified && Button1(cmd);
1040 if (willShoot)
1041 {
1042 FireWeapon(actor, ACTOR_GET_GUN(actor));
1043 }
1044 else
1045 {
1046 // Stop firing barrel and restore ready state
1047 const Weapon *w = ACTOR_GET_GUN(actor);
1048 for (int i = 0; i < WeaponClassNumBarrels(w->Gun); i++)
1049 {
1050 if (w->barrels[i].state == GUNSTATE_FIRING)
1051 {
1052 GameEvent e = GameEventNew(GAME_EVENT_GUN_STATE);
1053 e.u.GunState.ActorUID = actor->uid;
1054 e.u.GunState.Barrel = i;
1055 e.u.GunState.State = GUNSTATE_READY;
1056 GameEventsEnqueue(&gGameEvents, e);
1057 }
1058 }
1059 }
1060 return willShoot;
1061 }
1062
1063 static bool TryGrenade(TActor *a, const int cmd)
1064 {
1065 const bool willGrenade = !a->petrified && (cmd & CMD_GRENADE);
1066 if (willGrenade)
1067 {
1068 FireWeapon(a, ACTOR_GET_GRENADE(a));
1069 }
1070 return willGrenade;
1071 }
1072
1073 static bool ActorTryMove(TActor *actor, int cmd, int ticks);
1074 int CommandActor(TActor *actor, int cmd, int ticks)
1075 {
1076 GameEvent e;
1077 // If the actor is currently using a menu, control the menu instead
1078 if (actor->pickupMenu.pickup)
1079 {
1080 if (Button1(cmd) && !Button1(actor->lastCmd))
1081 {
1082 // Apply effects of pickup menu item and reset
1083 if (actor->pickupMenu.index <
1084 (int)actor->pickupMenu.effect->u.Menu.Items.size)
1085 {
1086 const PickupMenuItem *m = CArrayGet(
1087 &actor->pickupMenu.effect->u.Menu.Items,
1088 actor->pickupMenu.index);
1089 bool canPickup = false;
1090 const char *sound = "menu_enter";
1091 CA_FOREACH(const PickupEffect, pe, m->Effects)
1092 CASSERT(
1093 pe->Type != PICKUP_MENU, "can't have nested menu effects");
1094 canPickup = PickupApplyEffect(
1095 actor, actor->pickupMenu.pickup, pe, true, &sound) || canPickup;
1096 CA_FOREACH_END()
1097 if (canPickup && sound != NULL)
1098 {
1099 e = GameEventNew(GAME_EVENT_SOUND_AT);
1100 strcpy(e.u.SoundAt.Sound, sound);
1101 e.u.SoundAt.Pos = Vec2ToNet(actor->thing.Pos);
1102 GameEventsEnqueue(&gGameEvents, e);
1103 }
1104 }
1105 actor->pickupMenu.pickup = NULL;
1106 actor->pickupMenu.effect = NULL;
1107 actor->pickupMenu.index = 0;
1108 // Reset input
1109 KeyLockKeys(&gEventHandlers.keyboard);
1110 JoyLock(&gEventHandlers.joysticks);
1111 actor->lastCmd = 0;
1112 return 0;
1113 }
1114 else if (Up(cmd) && !Up(actor->lastCmd))
1115 {
1116 actor->pickupMenu.index--;
1117 if (actor->pickupMenu.index < 0)
1118 {
1119 actor->pickupMenu.index =
1120 (int)actor->pickupMenu.effect->u.Menu.Items.size - 1;
1121 }
1122 SoundPlay(&gSoundDevice, StrSound("menu_switch"));
1123 }
1124 else if (Down(cmd) && !Down(actor->lastCmd))
1125 {
1126 actor->pickupMenu.index++;
1127 if (actor->pickupMenu.index ==
1128 (int)actor->pickupMenu.effect->u.Menu.Items.size)
1129 {
1130 actor->pickupMenu.index = 0;
1131 }
1132 SoundPlay(&gSoundDevice, StrSound("menu_switch"));
1133 }
1134 }
1135 else
1136 {
1137 actor->hasShot = false;
1138 // If this is a pilot, command the vehicle instead
1139 if (actor->vehicleUID != -1)
1140 {
1141 TActor *vehicle = ActorGetByUID(actor->vehicleUID);
1142 CommandActor(vehicle, cmd, ticks);
1143 }
1144 else if (actor->pilotUID == -1)
1145 {
1146 // If this is a vehicle and there's no pilot, do nothing
1147 }
1148 else
1149 {
1150
1151 if (actor->confused)
1152 {
1153 cmd = CmdGetReverse(cmd);
1154 }
1155
1156 if (actor->health > 0)
1157 {
1158 const bool hasChangedDirection =
1159 ActorTryChangeDirection(actor, cmd, actor->lastCmd);
1160 actor->hasShot = ActorTryShoot(actor, cmd);
1161 const bool hasGrenaded = TryGrenade(actor, cmd);
1162 const bool hasMoved = ActorTryMove(actor, cmd, ticks);
1163 ActorAnimation anim = actor->anim.Type;
1164 // Idle if player hasn't done anything
1165 if (!(hasChangedDirection || actor->hasShot || hasGrenaded ||
1166 hasMoved))
1167 {
1168 anim = ACTORANIMATION_IDLE;
1169 }
1170 else if (hasMoved)
1171 {
1172 anim = ACTORANIMATION_WALKING;
1173 }
1174 else
1175 {
1176 anim = ACTORANIMATION_STAND;
1177 }
1178 if (actor->anim.Type != anim)
1179 {
1180 e = GameEventNew(GAME_EVENT_ACTOR_STATE);
1181 e.u.ActorState.UID = actor->uid;
1182 e.u.ActorState.State = (int32_t)anim;
1183 GameEventsEnqueue(&gGameEvents, e);
1184 }
1185 }
1186 }
1187
1188 actor->specialCmdDir = CMD_HAS_DIRECTION(cmd);
1189 if (Button2(cmd) && !actor->specialCmdDir)
1190 {
1191 // Special: pick up things that can only be picked up on demand
1192 if (!actor->PickupAll && !Button2(actor->lastCmd) &&
1193 actor->vehicleUID == -1)
1194 {
1195 e = GameEventNew(GAME_EVENT_ACTOR_PICKUP_ALL);
1196 e.u.ActorPickupAll.UID = actor->uid;
1197 e.u.ActorPickupAll.PickupAll = true;
1198 GameEventsEnqueue(&gGameEvents, e);
1199 }
1200 }
1201 }
1202
1203 actor->lastCmd = cmd;
1204 return cmd;
1205 }
1206 static bool ActorTryMove(TActor *actor, int cmd, int ticks)
1207 {
1208 const bool canMoveWhenShooting =
1209 actor->PlayerUID < 0
1210 ? (actor->flags & FLAGS_MOVE_AND_SHOOT)
1211 : (ConfigGetEnum(&gConfig, "Game.FireMoveStyle") !=
1212 FIREMOVE_STOP ||
1213 (ConfigGetEnum(&gConfig, "Game.SwitchMoveStyle") ==
1214 SWITCHMOVE_STRAFE &&
1215 Button2(cmd)));
1216 const bool canMove = !actor->hasShot || canMoveWhenShooting;
1217 const bool willMove =
1218 !actor->petrified && CMD_HAS_DIRECTION(cmd) && canMove;
1219 actor->MoveVel = svec2_zero();
1220 if (willMove)
1221 {
1222 const float moveAmount = ActorGetCharacter(actor)->speed * ticks;
1223 struct vec2 moveVel = svec2_zero();
1224 if (Left(cmd))
1225 moveVel.x--;
1226 else if (Right(cmd))
1227 moveVel.x++;
1228 if (Up(cmd))
1229 moveVel.y--;
1230 else if (Down(cmd))
1231 moveVel.y++;
1232 if (!svec2_is_zero(moveVel))
1233 {
1234 actor->MoveVel = svec2_scale(svec2_normalize(moveVel), moveAmount);
1235 }
1236 }
1237
1238 // If we have changed our move commands, send the move event
1239 if (cmd != actor->lastCmd || actor->hasCollided)
1240 {
1241 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_MOVE);
1242 e.u.ActorMove.UID = actor->uid;
1243 e.u.ActorMove.Pos = Vec2ToNet(actor->Pos);
1244 e.u.ActorMove.MoveVel = Vec2ToNet(actor->MoveVel);
1245 GameEventsEnqueue(&gGameEvents, e);
1246 }
1247
1248 return willMove || !svec2_is_zero(actor->thing.Vel);
1249 }
1250
1251 void SlideActor(TActor *actor, int cmd)
1252 {
1253 // Check that actor can slide
1254 if (actor->slideLock > 0)
1255 {
1256 return;
1257 }
1258
1259 if (actor->petrified)
1260 return;
1261
1262 if (actor->confused)
1263 {
1264 cmd = CmdGetReverse(cmd);
1265 }
1266
1267 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_SLIDE);
1268 e.u.ActorSlide.UID = actor->uid;
1269 struct vec2 vel = svec2_zero();
1270 if (Left(cmd))
1271 vel.x = -SLIDE_X;
1272 else if (Right(cmd))
1273 vel.x = SLIDE_X;
1274 if (Up(cmd))
1275 vel.y = -SLIDE_Y;
1276 else if (Down(cmd))
1277 vel.y = SLIDE_Y;
1278 e.u.ActorSlide.Vel = Vec2ToNet(vel);
1279 GameEventsEnqueue(&gGameEvents, e);
1280
1281 actor->slideLock = SLIDE_LOCK;
1282 }
1283
1284 static void ActorAddBloodSplatters(
1285 TActor *a, const int power, const float mass, const struct vec2 hitVector);
1286
1287 static void ActorUpdatePosition(TActor *actor, int ticks);
1288 static void ActorDie(TActor *actor);
1289 void UpdateAllActors(const int ticks)
1290 {
1291 CA_FOREACH(TActor, actor, gActors)
1292 if (!actor->isInUse)
1293 {
1294 continue;
1295 }
1296 // Update pilot/vehicle statuses
1297 if (actor->vehicleUID != -1)
1298 {
1299 const TActor *vehicle = ActorGetByUID(actor->vehicleUID);
1300 if (vehicle->dead)
1301 {
1302 actor->vehicleUID = -1;
1303 }
1304 }
1305 if (actor->pilotUID != -1 && actor->pilotUID != actor->uid)
1306 {
1307 const TActor *pilot = ActorGetByUID(actor->pilotUID);
1308 if (pilot->dead)
1309 {
1310 actor->pilotUID = -1;
1311 }
1312 }
1313 ActorUpdatePosition(actor, ticks);
1314 UpdateActorState(actor, ticks);
1315 const NamedSprites *deathSprites = CharacterClassGetDeathSprites(
1316 ActorGetCharacter(actor)->Class, &gPicManager);
1317 if (actor->dead && (deathSprites == NULL ||
1318 actor->dead - 1 > (int)deathSprites->pics.size))
1319 {
1320 if (!gCampaign.IsClient)
1321 {
1322 ActorDie(actor);
1323 }
1324 continue;
1325 }
1326 // Find actors that are on the same team and colliding,
1327 // and repel them
1328 if (!gCampaign.IsClient &&
1329 gCollisionSystem.allyCollision == ALLYCOLLISION_REPEL)
1330 {
1331 const CollisionParams params = {
1332 THING_IMPASSABLE, COLLISIONTEAM_NONE, IsPVP(gCampaign.Entry.Mode),
1333 false};
1334 const Thing *collidingItem = OverlapGetFirstItem(
1335 &actor->thing, actor->Pos, actor->thing.size, actor->thing.Vel,
1336 params);
1337 if (collidingItem && collidingItem->kind == KIND_CHARACTER)
1338 {
1339 TActor *collidingActor = CArrayGet(&gActors, collidingItem->id);
1340 if (CalcCollisionTeam(1, collidingActor) ==
1341 CalcCollisionTeam(1, actor))
1342 {
1343 struct vec2 v =
1344 svec2_subtract(actor->Pos, collidingActor->Pos);
1345 if (svec2_is_zero(v))
1346 {
1347 v = svec2(1, 0);
1348 }
1349 v = svec2_scale(svec2_normalize(v), REPEL_STRENGTH);
1350 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_IMPULSE);
1351 e.u.ActorImpulse.UID = actor->uid;
1352 e.u.ActorImpulse.Vel = Vec2ToNet(v);
1353 e.u.ActorImpulse.Pos = Vec2ToNet(actor->Pos);
1354 GameEventsEnqueue(&gGameEvents, e);
1355 e.u.ActorImpulse.UID = collidingActor->uid;
1356 e.u.ActorImpulse.Vel = Vec2ToNet(svec2_scale(v, -1));
1357 e.u.ActorImpulse.Pos = Vec2ToNet(collidingActor->Pos);
1358 GameEventsEnqueue(&gGameEvents, e);
1359 }
1360 }
1361 }
1362 // If low on health, bleed
1363 if (ActorIsLowHealth(actor))
1364 {
1365 actor->bleedCounter -= ticks;
1366 if (actor->bleedCounter <= 0)
1367 {
1368 ActorAddBloodSplatters(actor, 1, 1.0f, svec2_zero());
1369 actor->bleedCounter += ActorGetHealthPercent(actor);
1370 }
1371 }
1372 CA_FOREACH_END()
1373 }
1374 static void CheckManualPickups(TActor *a);
1375 static void ActorUpdatePosition(TActor *actor, int ticks)
1376 {
1377 struct vec2 newPos;
1378 // If piloting a vehicle, set position to that of vehicle
1379 if (actor->vehicleUID != -1)
1380 {
1381 const TActor *vehicle = ActorGetByUID(actor->vehicleUID);
1382 newPos = vehicle->Pos;
1383 }
1384 else
1385 {
1386 newPos = svec2_add(actor->Pos, actor->MoveVel);
1387 if (!svec2_is_zero(actor->thing.Vel))
1388 {
1389 newPos =
1390 svec2_add(newPos, svec2_scale(actor->thing.Vel, (float)ticks));
1391
1392 for (int i = 0; i < ticks; i++)
1393 {
1394 if (actor->thing.Vel.x > FLT_EPSILON)
1395 {
1396 actor->thing.Vel.x =
1397 MAX(0, actor->thing.Vel.x - VEL_DECAY_X);
1398 }
1399 else if (actor->thing.Vel.x < -FLT_EPSILON)
1400 {
1401 actor->thing.Vel.x =
1402 MIN(0, actor->thing.Vel.x + VEL_DECAY_X);
1403 }
1404 if (actor->thing.Vel.y > FLT_EPSILON)
1405 {
1406 actor->thing.Vel.y =
1407 MAX(0, actor->thing.Vel.y - VEL_DECAY_Y);
1408 }
1409 else if (actor->thing.Vel.y < FLT_EPSILON)
1410 {
1411 actor->thing.Vel.y =
1412 MIN(0, actor->thing.Vel.y + VEL_DECAY_Y);
1413 }
1414 }
1415 }
1416 }
1417
1418 if (!svec2_is_nearly_equal(actor->Pos, newPos, EPSILON_POS))
1419 {
1420 TryMoveActor(actor, newPos);
1421 }
1422 // Check if we're standing over any manual pickups
1423 CheckManualPickups(actor);
1424 }
1425 // Check if the actor is over any manual pickups
1426 static bool CheckManualPickupFunc(
1427 Thing *ti, void *data, const struct vec2 colA, const struct vec2 colB,
1428 const struct vec2 normal);
1429 // Check if the actor is over any unpiloted vehicles
1430 static void CheckManualPilot(TActor *a, const CollisionParams params);
1431 static void CheckManualPickups(TActor *a)
1432 {
1433 // NPCs can't pickup
1434 if (a->PlayerUID < 0)
1435 return;
1436 const CollisionParams params = {
1437 0, CalcCollisionTeam(true, a), IsPVP(gCampaign.Entry.Mode), false};
1438 OverlapThings(
1439 &a->thing, a->Pos, a->thing.Vel, a->thing.size, params,
1440 CheckManualPickupFunc, a, NULL, NULL, NULL);
1441 const CollisionParams paramsPilot = {
1442 THING_IMPASSABLE | THING_CAN_BE_SHOT, params.Team, params.IsPVP, true};
1443 CheckManualPilot(a, paramsPilot);
1444 }
1445 static bool CheckManualPickupFunc(
1446 Thing *ti, void *data, const struct vec2 colA, const struct vec2 colB,
1447 const struct vec2 normal)
1448 {
1449 UNUSED(colA);
1450 UNUSED(colB);
1451 UNUSED(normal);
1452 TActor *a = data;
1453 if (ti->kind != KIND_PICKUP)
1454 return true;
1455 const Pickup *p = CArrayGet(&gPickups, ti->id);
1456 if (!PickupIsManual(a, p))
1457 return true;
1458 // "Say" that the weapon must be picked up using a command
1459 const PlayerData *pData = PlayerDataGetByUID(a->PlayerUID);
1460 if (pData->IsLocal && IsPlayerHuman(pData))
1461 {
1462 char buttonName[64];
1463 strcpy(buttonName, "");
1464 InputGetButtonName(
1465 pData->inputDevice, pData->deviceIndex, CMD_BUTTON2, buttonName);
1466 const char *pickupName = PickupClassGetName(p->class);
1467 char buf[256];
1468 sprintf(buf, "%s to pick up\n%s", buttonName, pickupName);
1469 // Hack: remove anything beyond a "+" symbol, so we can have pickups
1470 // with the same name but with an invisible suffix
1471 char *plus = strrchr(buf, '+');
1472 if (plus)
1473 {
1474 *plus = '\0';
1475 }
1476 ActorSetChatter(a, buf, 2);
1477 }
1478 // If co-op AI, alert it so it can try to pick the gun up
1479 if (a->aiContext != NULL)
1480 {
1481 CA_FOREACH(const PickupEffect, pe, p->class->Effects)
1482 switch (pe->Type)
1483 {
1484 case PICKUP_GUN:
1485 AICoopOnPickupGun(a, pe->u.GunId);
1486 break;
1487 default:
1488 break;
1489 }
1490 CA_FOREACH_END()
1491 }
1492 a->CanPickupSpecial = true;
1493 return false;
1494 }
1495 static void CheckManualPilot(TActor *a, const CollisionParams params)
1496 {
1497 if (a->vehicleUID >= 0)
1498 {
1499 return;
1500 }
1501 const Thing *ti = OverlapGetFirstItem(
1502 &a->thing, a->Pos, a->thing.size, a->thing.Vel, params);
1503 if (ti == NULL || ti->kind != KIND_CHARACTER)
1504 return;
1505 const TActor *vehicle = CArrayGet(&gActors, ti->id);
1506 if (vehicle->pilotUID >= 0)
1507 return;
1508 // "Say" that we can pilot using a command
1509 const PlayerData *pData = PlayerDataGetByUID(a->PlayerUID);
1510 if (pData->IsLocal && IsPlayerHuman(pData))
1511 {
1512 char buttonName[64];
1513 strcpy(buttonName, "");
1514 InputGetButtonName(
1515 pData->inputDevice, pData->deviceIndex, CMD_BUTTON2, buttonName);
1516 const char *vehicleName = ActorGetCharacter(vehicle)->Class->Name;
1517 char buf[256];
1518 sprintf(buf, "%s to pilot\n%s", buttonName, vehicleName);
1519 ActorSetChatter(a, buf, 2);
1520 }
1521 // TODO: co-op AI pilot
1522 a->CanPickupSpecial = true;
1523 }
1524 static void ActorDie(TActor *actor)
1525 {
1526 // Add corpse
1527 if (ConfigGetEnum(&gConfig, "Graphics.Gore") != GORE_NONE)
1528 {
1529 const Character *c = ActorGetCharacter(actor);
1530 GameEvent ea = GameEventNew(GAME_EVENT_MAP_OBJECT_ADD);
1531 ea.u.MapObjectAdd.UID = ObjsGetNextUID();
1532 const MapObject *corpse = StrMapObject(c->Class->Corpse);
1533 if (!corpse)
1534 {
1535 corpse = GetRandomBloodPool();
1536 ea.u.MapObjectAdd.Mask = Color2Net(c->Class->BloodColor);
1537 }
1538 strcpy(ea.u.MapObjectAdd.MapObjectClass, corpse->Name);
1539 ea.u.MapObjectAdd.Pos = Vec2ToNet(actor->Pos);
1540 ea.u.MapObjectAdd.ThingFlags = MapObjectGetFlags(corpse);
1541 ea.u.MapObjectAdd.Health = corpse->Health;
1542 GameEventsEnqueue(&gGameEvents, ea);
1543 }
1544
1545 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_DIE);
1546 e.u.ActorDie.UID = actor->uid;
1547 GameEventsEnqueue(&gGameEvents, e);
1548
1549 // Persist player ammo for when they respawn
1550 ActorPersistPlayerWeaponsAndAmmo(actor);
1551 }
1552 static bool IsUnarmedBot(const TActor *actor);
1553 static void ActorAddAmmoPickup(const TActor *actor)
1554 {
1555 if (IsUnarmedBot(actor))
1556 {
1557 return;
1558 }
1559
1560 // Add ammo pickups for each of the actor's guns
1561 for (int i = 0; i < MAX_WEAPONS; i++)
1562 {
1563 const Weapon *w = &actor->guns[i];
1564 if (w->Gun == NULL)
1565 {
1566 continue;
1567 }
1568
1569 for (int j = 0; j < WeaponClassNumBarrels(w->Gun); j++)
1570 {
1571 const int ammoId = WC_BARREL_ATTR(*(w->Gun), AmmoId, j);
1572 // Check if the actor's gun has ammo at all
1573 if (ammoId < 0)
1574 {
1575 continue;
1576 }
1577 // Don't spawn ammo if no players use it
1578 if (PlayersNumUseAmmo(ammoId) == 0)
1579 {
1580 continue;
1581 }
1582
1583 GameEvent e = GameEventNew(GAME_EVENT_ADD_PICKUP);
1584 const Ammo *a = AmmoGetById(&gAmmo, ammoId);
1585 sprintf(e.u.AddPickup.PickupClass, "ammo_%s", a->Name);
1586 // Add a little random offset so the pickups aren't all together
1587 const struct vec2 offset = svec2(
1588 (float)RAND_INT(-TILE_WIDTH, TILE_WIDTH) / 2,
1589 (float)RAND_INT(-TILE_HEIGHT, TILE_HEIGHT) / 2);
1590 e.u.AddPickup.Pos = Vec2ToNet(svec2_add(actor->Pos, offset));
1591 GameEventsEnqueue(&gGameEvents, e);
1592 }
1593 }
1594 }
1595 static bool HasGunPickups(const WeaponClass *wc, const int n);
1596 static void ActorAddGunPickup(const TActor *actor)
1597 {
1598 if (IsUnarmedBot(actor))
1599 {
1600 return;
1601 }
1602
1603 // Select a valid gun to drop
1604 for (int i = 0; i < MAX_WEAPONS; i++)
1605 {
1606 const WeaponClass *wc = actor->guns[i].Gun;
1607 if (wc == NULL)
1608 continue;
1609 if (!wc->CanDrop)
1610 continue;
1611 if (wc->DropGun)
1612 {
1613 wc = StrWeaponClass(wc->DropGun);
1614 CASSERT(wc != NULL, "Cannot find gun to drop");
1615 }
1616 // Don't drop gun if there's gun pickups for this already
1617 if (HasGunPickups(wc, 2))
1618 continue;
1619 PickupAddGun(wc, actor->Pos);
1620 break;
1621 }
1622 }
1623 static bool HasGunPickup(const Pickup *p, const int wcId);
1624 static bool HasGunPickups(const WeaponClass *wc, const int n)
1625 {
1626 const int wcId = WeaponClassId(wc);
1627 int count = 0;
1628 CA_FOREACH(const Pickup, p, gPickups)
1629 if (!p->isInUse)
1630 {
1631 continue;
1632 }
1633 if (HasGunPickup(p, wcId))
1634 {
1635 count++;
1636 if (count >= n)
1637 {
1638 return true;
1639 }
1640 }
1641 CA_FOREACH_END()
1642 return false;
1643 }
1644 static bool HasGunPickup(const Pickup *p, const int wcId)
1645 {
1646 CA_FOREACH(const PickupEffect, pe, p->class->Effects)
1647 if (pe->Type == PICKUP_GUN && pe->u.GunId == wcId)
1648 {
1649 return true;
1650 }
1651 CA_FOREACH_END()
1652 return false;
1653 }
1654 static bool IsUnarmedBot(const TActor *actor)
1655 {
1656 // Note: if the actor is AI with no shooting time,
1657 // then it's an unarmed actor
1658 const Character *c = ActorGetCharacter(actor);
1659 return c->bot != NULL && c->bot->probabilityToShoot == 0;
1660 }
1661
1662 static void VehicleTakePilot(const TActor *vehicle);
1663 // Check whether actors are overlapping with unpiloted vehicles,
1664 // and automatically pilot them
1665 // Only called at start of mission
1666 void ActorsPilotVehicles(void)
1667 {
1668 CA_FOREACH(const TActor, vehicle, gActors)
1669 if (!vehicle->isInUse)
1670 {
1671 continue;
1672 }
1673 if (vehicle->pilotUID == -1)
1674 {
1675 VehicleTakePilot(vehicle);
1676 }
1677 CA_FOREACH_END()
1678 }
1679 static void VehicleTakePilot(const TActor *vehicle)
1680 {
1681 CA_FOREACH(const TActor, pilot, gActors)
1682 if (!pilot->isInUse)
1683 {
1684 continue;
1685 }
1686 if (pilot->pilotUID == pilot->uid &&
1687 AABBOverlap(
1688 vehicle->Pos, pilot->Pos, vehicle->thing.size, pilot->thing.size))
1689 {
1690 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_PILOT);
1691 e.u.Pilot.On = true;
1692 e.u.Pilot.UID = pilot->uid;
1693 e.u.Pilot.VehicleUID = vehicle->uid;
1694 GameEventsEnqueue(&gGameEvents, e);
1695 break;
1696 }
1697 CA_FOREACH_END()
1698 }
1699
1700 void ActorsInit(void)
1701 {
1702 CArrayInit(&gActors, sizeof(TActor));
1703 CArrayReserve(&gActors, 64);
1704 sActorUIDs = 0;
1705 }
1706 void ActorsTerminate(void)
1707 {
1708 CA_FOREACH(TActor, a, gActors)
1709 if (!a->isInUse)
1710 continue;
1711 ActorDestroy(a);
1712 CA_FOREACH_END()
1713 CArrayTerminate(&gActors);
1714 }
1715 int ActorsGetNextUID(void)
1716 {
1717 return sActorUIDs++;
1718 }
1719 int ActorsGetFreeIndex(void)
1720 {
1721 // Find an empty slot in actor list
1722 // actors.size if no slot found (i.e. add to end)
1723 CA_FOREACH(const TActor, a, gActors)
1724 if (!a->isInUse)
1725 {
1726 return _ca_index;
1727 }
1728 CA_FOREACH_END()
1729 return (int)gActors.size;
1730 }
1731
1732 static void GoreEmitterInit(Emitter *em, const char *particleClassName);
1733 TActor *ActorAdd(NActorAdd aa)
1734 {
1735 // Don't add if UID exists
1736 if (ActorGetByUID(aa.UID) != NULL)
1737 {
1738 LOG(LM_ACTOR, LL_DEBUG, "actor uid(%d) already exists; not adding",
1739 (int)aa.UID);
1740 return NULL;
1741 }
1742 const int id = ActorsGetFreeIndex();
1743 while (id >= (int)gActors.size)
1744 {
1745 TActor a;
1746 memset(&a, 0, sizeof a);
1747 CArrayPushBack(&gActors, &a);
1748 }
1749 TActor *actor = CArrayGet(&gActors, id);
1750 memset(actor, 0, sizeof *actor);
1751 actor->uid = aa.UID;
1752 LOG(LM_ACTOR, LL_DEBUG, "add actor uid(%d) playerUID(%d)", actor->uid,
1753 aa.PlayerUID);
1754 actor->pilotUID = aa.PilotUID;
1755 actor->vehicleUID = aa.VehicleUID;
1756 CArrayInit(&actor->ammo, sizeof(int));
1757 for (int i = 0; i < AmmoGetNumClasses(&gAmmo); i++)
1758 {
1759 // Initialise with twice the standard ammo amount
1760 const int amount =
1761 AmmoGetById(&gAmmo, i)->Amount * AMMO_STARTING_MULTIPLE;
1762 CArrayPushBack(&actor->ammo, &amount);
1763 }
1764 if (gMission.missionData && gMission.missionData->WeaponPersist)
1765 {
1766 for (int i = 0; i < aa.Ammo_count; i++)
1767 {
1768 // Use persisted ammo amount if it is greater,
1769 // or if buy/sell is enabled
1770 const Ammo *ammo = AmmoGetById(&gAmmo, aa.Ammo[i].Id);
1771 if (ammo && (gCampaign.Setting.BuyAndSell ||
1772 (int)aa.Ammo[i].Amount >
1773 ammo->Amount * AMMO_STARTING_MULTIPLE))
1774 {
1775 CArraySet(&actor->ammo, aa.Ammo[i].Id, &aa.Ammo[i].Amount);
1776 }
1777 }
1778 }
1779 actor->PlayerUID = aa.PlayerUID;
1780 actor->charId = aa.CharId;
1781 const Character *c = ActorGetCharacter(actor);
1782 if (aa.PlayerUID >= 0)
1783 {
1784 // Add all player weapons
1785 PlayerData *p = PlayerDataGetByUID(aa.PlayerUID);
1786 for (int i = 0; i < MAX_WEAPONS; i++)
1787 {
1788 Weapon gun = WeaponCreate(p->guns[i]);
1789 actor->guns[i] = gun;
1790 if (i < MAX_GUNS && ACTOR_GET_GUN(actor)->Gun == NULL)
1791 {
1792 actor->gunIndex = i;
1793 }
1794 }
1795 p->ActorUID = aa.UID;
1796 }
1797 else
1798 {
1799 // Add sole weapon from character type
1800 Weapon gun = WeaponCreate(c->Gun);
1801 actor->guns[0] = gun;
1802 actor->gunIndex = 0;
1803 if (c->Melee)
1804 {
1805 Weapon melee = WeaponCreate(c->Melee);
1806 actor->guns[MELEE_SLOT] = melee;
1807 }
1808 }
1809 actor->health = aa.Health;
1810 actor->action = ACTORACTION_MOVING;
1811 actor->thing.Pos.x = actor->thing.Pos.y = -1;
1812 actor->thing.kind = KIND_CHARACTER;
1813 actor->thing.drawFunc = NULL;
1814 actor->thing.size = svec2i(ACTOR_W, ACTOR_H);
1815 actor->thing.flags = THING_IMPASSABLE | THING_CAN_BE_SHOT | aa.ThingFlags;
1816 actor->thing.id = id;
1817 actor->isInUse = true;
1818
1819 actor->flags = FLAGS_SLEEPING | c->flags;
1820 // Flag corrections
1821 if (actor->flags & FLAGS_AWAKEALWAYS)
1822 {
1823 actor->flags &= ~FLAGS_SLEEPING;
1824 }
1825 // Rescue objectives always have follower flag on
1826 if (actor->thing.flags & THING_OBJECTIVE)
1827 {
1828 const Objective *o = CArrayGet(
1829 &gMission.missionData->Objectives,
1830 ObjectiveFromThing(actor->thing.flags));
1831 if (o->Type == OBJECTIVE_RESCUE)
1832 {
1833 // If they don't have prisoner flag set, automatically rescue
1834 // them
1835 if (!(actor->flags & FLAGS_PRISONER) && !gCampaign.IsClient)
1836 {
1837 GameEvent e = GameEventNew(GAME_EVENT_RESCUE_CHARACTER);
1838 e.u.Rescue.UID = aa.UID;
1839 GameEventsEnqueue(&gGameEvents, e);
1840 UpdateMissionObjective(
1841 &gMission, actor->thing.flags, OBJECTIVE_RESCUE, 1);
1842 }
1843 }
1844 }
1845
1846 actor->direction = aa.Direction;
1847 actor->DrawRadians = (float)dir2radians[actor->direction];
1848 actor->anim = AnimationGetActorAnimation(ACTORANIMATION_IDLE);
1849 actor->slideLock = 0;
1850 if (c->bot)
1851 {
1852 actor->aiContext = AIContextNew();
1853 ActorSetAIState(actor, AI_STATE_IDLE);
1854 }
1855
1856 const ParticleClass *barrelSmoke =
1857 StrParticleClass(&gParticleClasses, "smoke");
1858 if (barrelSmoke)
1859 {
1860 EmitterInit(
1861 &actor->barrelSmoke, barrelSmoke, svec2_zero(), -0.05f, 0.05f, 3,
1862 3, 0, 0, 10);
1863 }
1864 const ParticleClass *healthPlus =
1865 StrParticleClass(&gParticleClasses, "health_plus");
1866 if (healthPlus)
1867 {
1868 EmitterInit(
1869 &actor->healEffect, healthPlus, svec2_zero(), -0.1f, 0.1f, 0, 0, 0,
1870 0, 0);
1871 }
1872 GoreEmitterInit(&actor->blood1, "blood1");
1873 GoreEmitterInit(&actor->blood2, "blood2");
1874 GoreEmitterInit(&actor->blood3, "blood3");
1875
1876 TryMoveActor(actor, NetToVec2(aa.Pos));
1877
1878 return actor;
1879 }
1880 static void GoreEmitterInit(Emitter *em, const char *particleClassName)
1881 {
1882 EmitterInit(
1883 em, StrParticleClass(&gParticleClasses, particleClassName),
1884 svec2_zero(), 0, GORE_EMITTER_MAX_SPEED, 6, 12, -0.1, 0.1, 0);
1885 }
1886
1887 void ActorDestroy(TActor *a)
1888 {
1889 CASSERT(a->isInUse, "Destroying in-use actor");
1890 CArrayTerminate(&a->ammo);
1891 MapRemoveThing(&gMap, &a->thing);
1892 // Set PlayerData's ActorUID to -1 to signify actor destruction
1893 PlayerData *p = PlayerDataGetByUID(a->PlayerUID);
1894 if (p != NULL)
1895 p->ActorUID = -1;
1896 AIContextDestroy(a->aiContext);
1897 a->isInUse = false;
1898 }
1899
1900 TActor *ActorGetByUID(const int uid)
1901 {
1902 CA_FOREACH(TActor, a, gActors)
1903 if (a->uid == uid)
1904 {
1905 return a;
1906 }
1907 CA_FOREACH_END()
1908 return NULL;
1909 }
1910
1911 const Character *ActorGetCharacter(const TActor *a)
1912 {
1913 if (a->PlayerUID >= 0)
1914 {
1915 return &PlayerDataGetByUID(a->PlayerUID)->Char;
1916 }
1917 return CArrayGet(&gCampaign.Setting.characters.OtherChars, a->charId);
1918 }
1919
1920 struct vec2 ActorGetAverageWeaponMuzzleOffset(const TActor *a)
1921 {
1922 const Weapon *w = ACTOR_GET_WEAPON(a);
1923 struct vec2 offset = svec2_zero();
1924 for (int i = 0; i < WeaponClassNumBarrels(w->Gun); i++)
1925 {
1926 offset = svec2_add(offset, ActorGetMuzzleOffset(a, w, i));
1927 }
1928 return svec2_scale(offset, 1.0f / (float)WeaponClassNumBarrels(w->Gun));
1929 }
1930 struct vec2 ActorGetMuzzleOffset(
1931 const TActor *a, const Weapon *w, const int barrel)
1932 {
1933 const Character *c = ActorGetCharacter(a);
1934 const CharSprites *cs = c->Class->Sprites;
1935 return WeaponClassGetBarrelMuzzleOffset(
1936 w->Gun, cs, barrel, a->direction, w->barrels[barrel].state);
1937 }
1938 int ActorWeaponGetAmmo(
1939 const TActor *a, const WeaponClass *wc, const int barrel)
1940 {
1941 if (wc == NULL)
1942 {
1943 return 0;
1944 }
1945 const int ammoId = WC_BARREL_ATTR(*wc, AmmoId, barrel);
1946 if (ammoId == -1)
1947 {
1948 return -1;
1949 }
1950 return *(int *)CArrayGet(&a->ammo, ammoId);
1951 }
1952 int ActorGetCanFireBarrel(const TActor *a, const Weapon *w)
1953 {
1954 if (w->Gun == NULL)
1955 {
1956 return -1;
1957 }
1958 const int barrel = WeaponGetUnlockedBarrel(w);
1959 if (barrel == -1)
1960 {
1961 return -1;
1962 }
1963 const bool hasAmmo = ActorWeaponGetAmmo(a, w->Gun, barrel) != 0;
1964 if (gCampaign.Setting.Ammo && !hasAmmo)
1965 {
1966 // TODO: multi guns not firing if the first gun is out of ammo
1967 return -1;
1968 }
1969 return barrel;
1970 }
1971 bool ActorCanSwitchToWeapon(const TActor *a, const int slot)
1972 {
1973 const WeaponClass *wc = a->guns[slot].Gun;
1974 if (wc == NULL)
1975 {
1976 return false;
1977 }
1978 // Don't cycle to auto-melee or default melee unless there are no guns with
1979 // ammo
1980 if (slot == MELEE_SLOT && wc->u.Normal.Auto)
1981 {
1982 for (int i = 0; i < MELEE_SLOT; i++)
1983 {
1984 const WeaponClass *wc2 = a->guns[i].Gun;
1985 if (wc2 != NULL)
1986 {
1987 if (!gCampaign.Setting.Ammo)
1988 {
1989 return false;
1990 }
1991 for (int j = 0; j < WeaponClassNumBarrels(wc2); j++)
1992 {
1993 if (ActorWeaponGetAmmo(a, wc2, j) != 0)
1994 {
1995 return false;
1996 }
1997 }
1998 }
1999 }
2000 }
2001 // Don't switch to grenade, unless the player has no grenade button
2002 if (slot == GRENADE_SLOT)
2003 {
2004 const PlayerData *p = PlayerDataGetByUID(a->PlayerUID);
2005 return !PlayerHasGrenadeButton(p);
2006 }
2007 return true;
2008 }
2009 bool ActorTrySwitchWeapon(const TActor *a)
2010 {
2011 // Find the next weapon to switch to
2012 const int startIndex = ActorGetNumGuns(a) > 0 ? a->gunIndex : MAX_GUNS;
2013 int weaponIndex = startIndex;
2014 do
2015 {
2016 weaponIndex = (weaponIndex + 1) % MAX_WEAPONS;
2017 } while (!ActorCanSwitchToWeapon(a, weaponIndex));
2018 if (weaponIndex == startIndex)
2019 {
2020 // No other weapon to switch to
2021 return false;
2022 }
2023
2024 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_SWITCH_GUN);
2025 e.u.ActorSwitchGun.UID = a->uid;
2026 e.u.ActorSwitchGun.GunIdx = weaponIndex;
2027 GameEventsEnqueue(&gGameEvents, e);
2028 return true;
2029 }
2030 void ActorSwitchGun(const NActorSwitchGun sg)
2031 {
2032 TActor *a = ActorGetByUID(sg.UID);
2033 if (a == NULL || !a->isInUse)
2034 return;
2035 a->gunIndex = sg.GunIdx;
2036 if (sg.GunIdx < MELEE_SLOT)
2037 {
2038 a->lastGunIdx = sg.GunIdx;
2039 }
2040 const WeaponClass *gun = ACTOR_GET_WEAPON(a)->Gun;
2041 SoundPlayAt(&gSoundDevice, gun->SwitchSound, a->thing.Pos);
2042 // Show gun switch text as chatter, but only for PCs
2043 if (a->PlayerUID >= 0)
2044 {
2045 ActorSetChatter(a, gun->name, CHATTER_SWITCH_GUN);
2046 }
2047 }
2048
2049 void ActorPickupGun(const TActor *a, const WeaponClass *wc)
2050 {
2051 int actorsGunIdx = ActorFindGun(a, wc);
2052 if (actorsGunIdx >= 0)
2053 {
2054 // Actor already has gun
2055
2056 // Switch to the same gun
2057 if (ActorCanSwitchToWeapon(a, actorsGunIdx))
2058 {
2059 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_SWITCH_GUN);
2060 e.u.ActorSwitchGun.UID = a->uid;
2061 e.u.ActorSwitchGun.GunIdx = actorsGunIdx;
2062 GameEventsEnqueue(&gGameEvents, e);
2063 }
2064
2065 // Drop the same gun
2066 PickupAddGun(wc, a->Pos);
2067 }
2068 else
2069 {
2070 // Make sure weapons are picked up in the correct slot
2071 int slotStart, slotEnd;
2072 GunTypeGetSlotStartEnd(wc->Type, &slotStart, &slotEnd);
2073 if (actorsGunIdx < slotStart || actorsGunIdx > slotEnd)
2074 {
2075 actorsGunIdx = slotStart;
2076 }
2077
2078 // Pickup gun
2079 // Replace the current gun, unless there's a free slot, in which case
2080 // pick up into the free spot
2081 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_REPLACE_GUN);
2082 e.u.ActorReplaceGun.UID = a->uid;
2083 strcpy(e.u.ActorReplaceGun.Gun, wc->name);
2084 switch (wc->Type)
2085 {
2086 case GUNTYPE_MELEE:
2087 e.u.ActorReplaceGun.GunIdx = MELEE_SLOT;
2088 break;
2089 case GUNTYPE_GRENADE:
2090 e.u.ActorReplaceGun.GunIdx = GRENADE_SLOT;
2091 break;
2092 default:
2093 if (a->gunIndex < MELEE_SLOT)
2094 {
2095 e.u.ActorReplaceGun.GunIdx = a->gunIndex;
2096 }
2097 else
2098 {
2099 e.u.ActorReplaceGun.GunIdx = 0;
2100 }
2101 break;
2102 }
2103 int replaceGunIndex = e.u.ActorReplaceGun.GunIdx;
2104 for (int i = slotStart; i <= slotEnd; i++)
2105 {
2106 if (a->guns[i].Gun == NULL)
2107 {
2108 e.u.ActorReplaceGun.GunIdx = i;
2109 replaceGunIndex = -1;
2110 break;
2111 }
2112 }
2113 GameEventsEnqueue(&gGameEvents, e);
2114
2115 // If replacing a gun, "drop" the gun being replaced (i.e. create a gun
2116 // pickup)
2117 if (replaceGunIndex >= 0)
2118 {
2119 PickupAddGun(a->guns[replaceGunIndex].Gun, a->Pos);
2120 }
2121 }
2122 }
2123
2124 bool ActorIsImmune(const TActor *actor, const special_damage_e damage)
2125 {
2126 switch (damage)
2127 {
2128 case SPECIAL_FLAME:
2129 return actor->flags & FLAGS_ASBESTOS;
2130 case SPECIAL_POISON:
2131 case SPECIAL_PETRIFY: // fallthrough
2132 return actor->flags & FLAGS_IMMUNITY;
2133 case SPECIAL_CONFUSE:
2134 return actor->flags & FLAGS_IMMUNITY;
2135 default:
2136 break;
2137 }
2138 // Don't bother if health already 0 or less
2139 if (actor->health <= 0)
2140 {
2141 return 1;
2142 }
2143 return 0;
2144 }
2145
2146 bool ActorTakesDamage(const TActor *actor, const special_damage_e damage)
2147 {
2148 switch (damage)
2149 {
2150 case SPECIAL_FLAME:
2151 return !(actor->flags & FLAGS_ASBESTOS);
2152 default:
2153 return true;
2154 }
2155 }
2156
2157 #define MAX_POISONED_COUNT 140
2158
2159 static void ActorTakeSpecialDamage(
2160 TActor *actor, const special_damage_e damage, const int ticks)
2161 {
2162 if (ActorIsImmune(actor, damage))
2163 {
2164 return;
2165 }
2166 switch (damage)
2167 {
2168 case SPECIAL_FLAME:
2169 actor->flamed = ticks;
2170 break;
2171 case SPECIAL_POISON:
2172 actor->poisoned = MIN(actor->poisoned + ticks, MAX_POISONED_COUNT);
2173 break;
2174 case SPECIAL_PETRIFY:
2175 if (!actor->petrified)
2176 {
2177 actor->petrified = ticks;
2178 }
2179 break;
2180 case SPECIAL_CONFUSE:
2181 actor->confused = ticks;
2182 break;
2183 default:
2184 // do nothing
2185 break;
2186 }
2187 }
2188
2189 static void ActorTakeHit(TActor *actor, const NThingDamage d);
2190 void ActorHit(const NThingDamage d)
2191 {
2192 TActor *a = ActorGetByUID(d.UID);
2193 if (!a->isInUse)
2194 return;
2195
2196 ActorTakeHit(a, d);
2197 if (d.Power > 0)
2198 {
2199 DamageActor(a, d.Power, d.SourceActorUID);
2200
2201 // Add damage text
2202 // See if there is one already; if so remove it and add a new one,
2203 // combining the damage numbers
2204 int damage = (int)d.Power;
2205 struct vec2 pos =
2206 svec2_add(a->Pos, svec2(RAND_FLOAT(-3, 3), RAND_FLOAT(-3, 3)));
2207 CA_FOREACH(const Particle, p, gParticles)
2208 if (p->isInUse && p->ActorUID == a->uid)
2209 {
2210 damage += a->accumulatedDamage;
2211 if (svec2_distance(pos, p->Pos) <
2212 DAMAGE_TEXT_DISTANCE_RESET_THRESHOLD)
2213 {
2214 pos = p->Pos;
2215 }
2216 GameEvent e = GameEventNew(GAME_EVENT_PARTICLE_REMOVE);
2217 e.u.ParticleRemoveId = _ca_index;
2218 GameEventsEnqueue(&gGameEvents, e);
2219 break;
2220 }
2221 CA_FOREACH_END()
2222 a->accumulatedDamage = damage;
2223 a->damageCooldownTicks = 0;
2224
2225 GameEvent s = GameEventNew(GAME_EVENT_ADD_PARTICLE);
2226 s.u.AddParticle.Class =
2227 StrParticleClass(&gParticleClasses, "damage_text");
2228 s.u.AddParticle.ActorUID = a->uid;
2229 s.u.AddParticle.Pos = pos;
2230 s.u.AddParticle.Z = BULLET_Z * Z_FACTOR;
2231 s.u.AddParticle.DZ = 3;
2232 sprintf(s.u.AddParticle.Text, "-%d", damage);
2233 GameEventsEnqueue(&gGameEvents, s);
2234
2235 ActorAddBloodSplatters(a, d.Power, d.Mass, NetToVec2(d.Vel));
2236
2237 // Rumble if taking hit
2238 if (a->PlayerUID >= 0)
2239 {
2240 const PlayerData *p = PlayerDataGetByUID(a->PlayerUID);
2241 if (p->inputDevice == INPUT_DEVICE_JOYSTICK)
2242 {
2243 JoyImpact(p->deviceIndex);
2244 }
2245 }
2246
2247 a->grimaceCounter = GRIMACE_HIT_TICKS;
2248 }
2249 }
2250
2251 static void ActorTakeHit(TActor *actor, const NThingDamage d)
2252 {
2253 // Wake up if this is an AI
2254 if (!gCampaign.IsClient)
2255 {
2256 AIWake(actor, 1);
2257 }
2258 const TActor *source = ActorGetByUID(d.SourceActorUID);
2259 const int playerUID = source != NULL ? source->PlayerUID : -1;
2260 if (ActorIsInvulnerable(
2261 actor, d.Flags, playerUID, gCampaign.Entry.Mode, d.Special))
2262 {
2263 return;
2264 }
2265 ActorTakeSpecialDamage(actor, d.Special, d.SpecialTicks);
2266
2267 // Update hits
2268 // TODO: correct accuracy for persistent bullets
2269 if (!gCampaign.IsClient && playerUID >= 0 &&
2270 strlen(d.SourceWeaponClassName) > 0)
2271 {
2272 PlayerData *p = PlayerDataGetByUID(playerUID);
2273 const WeaponClass *wc = StrWeaponClass(d.SourceWeaponClassName);
2274 WeaponUsagesUpdate(p->WeaponUsages, wc, 0, 1);
2275 }
2276 }
2277
2278 bool ActorIsInvulnerable(
2279 const TActor *actor, const int flags, const int playerUID,
2280 const GameMode mode, const special_damage_e special)
2281 {
2282 if (actor->flags & FLAGS_INVULNERABLE)
2283 {
2284 return true;
2285 }
2286
2287 if (!(flags & FLAGS_HURTALWAYS) && !(actor->flags & FLAGS_VICTIM))
2288 {
2289 // Same player hits
2290 if (playerUID >= 0 && playerUID == actor->PlayerUID)
2291 {
2292 return true;
2293 }
2294 const bool isGood = playerUID >= 0 || (flags & FLAGS_GOOD_GUY);
2295 const bool isTargetGood =
2296 actor->PlayerUID >= 0 || (actor->flags & FLAGS_GOOD_GUY);
2297 // Friendly fire (NPCs)
2298 if (!IsPVP(mode) && !ConfigGetBool(&gConfig, "Game.FriendlyFire") &&
2299 isGood && isTargetGood)
2300 {
2301 return true;
2302 }
2303 // Enemies don't hurt each other
2304 if (!isGood && !isTargetGood)
2305 {
2306 return true;
2307 }
2308 if (!ActorTakesDamage(actor, special))
2309 {
2310 return true;
2311 }
2312 }
2313
2314 return false;
2315 }
2316
2317 static void ActorAddBloodSplatters(
2318 TActor *a, const int power, const float mass, const struct vec2 hitVector)
2319 {
2320 const GoreAmount ga = ConfigGetEnum(&gConfig, "Graphics.Gore");
2321 if (ga == GORE_NONE)
2322 return;
2323 const color_t bloodColor = ActorGetCharacter(a)->Class->BloodColor;
2324 if (bloodColor.a == 0)
2325 {
2326 return;
2327 }
2328
2329 // Emit blood based on power and gore setting
2330 int bloodPower = power * 2;
2331 // Randomly cycle through the blood types
2332 int bloodSize = 1;
2333 const struct vec2 hitVNorm = svec2_normalize(hitVector);
2334 const float speedBase = MAX(1.0f, mass) * SHOT_IMPULSE_FACTOR;
2335 while (bloodPower > 0)
2336 {
2337 Emitter *em = NULL;
2338 switch (bloodSize)
2339 {
2340 case 1:
2341 em = &a->blood1;
2342 break;
2343 case 2:
2344 em = &a->blood2;
2345 break;
2346 default:
2347 em = &a->blood3;
2348 break;
2349 }
2350 bloodSize++;
2351 if (bloodSize > 3)
2352 {
2353 bloodSize = 1;
2354 }
2355 const struct vec2 vel =
2356 svec2_scale(hitVNorm, speedBase * RAND_FLOAT(0.5f, 1));
2357 AddParticle ap;
2358 memset(&ap, 0, sizeof ap);
2359 ap.Pos = a->Pos;
2360 ap.Angle = NAN;
2361 ap.Z = 10;
2362 ap.Vel = vel;
2363 ap.Mask = bloodColor;
2364 EmitterStart(em, &ap);
2365 switch (ga)
2366 {
2367 case GORE_LOW:
2368 bloodPower /= 8;
2369 break;
2370 case GORE_MEDIUM:
2371 bloodPower /= 2;
2372 break;
2373 default:
2374 bloodPower = bloodPower * 7 / 8;
2375 break;
2376 }
2377 }
2378 }
2379
2380 int ActorGetMaxHeal(const TActor *a, const bool exceedMax)
2381 {
2382 const Character *c = ActorGetCharacter(a);
2383 return exceedMax ? c->excessHealth : c->maxHealth;
2384 }
2385
2386 int ActorGetHealthPercent(const TActor *a)
2387 {
2388 const int maxHealth = ActorGetCharacter(a)->maxHealth;
2389 return a->health * 100 / maxHealth;
2390 }
2391
2392 bool ActorIsLowHealth(const TActor *a)
2393 {
2394 return ActorGetHealthPercent(a) < LOW_HEALTH_PERCENTAGE;
2395 }
2396
2397 bool ActorIsGrimacing(const TActor *a)
2398 {
2399 const Weapon *gun = ACTOR_GET_WEAPON(a);
2400 if (gun->Gun)
2401 {
2402 for (int i = 0; i < WeaponClassNumBarrels(gun->Gun); i++)
2403 {
2404 if (gun->barrels[i].state == GUNSTATE_FIRING ||
2405 gun->barrels[i].state == GUNSTATE_RECOIL)
2406 {
2407 return true;
2408 }
2409 }
2410 }
2411 return (a->grimaceCounter % GRIMACE_PERIOD) > GRIMACE_PERIOD / 2;
2412 }
2413
2414 bool ActorIsLocalPlayer(const int uid)
2415 {
2416 const TActor *a = ActorGetByUID(uid);
2417 // Don't accept updates if actor doesn't exist
2418 // This can happen in the very first frame, where we haven't yet
2419 // processed an actor add message
2420 // Otherwise this shouldn't happen
2421 if (a == NULL)
2422 return true;
2423
2424 return PlayerIsLocal(a->PlayerUID);
2425 }
2426
2427 void ActorPersistPlayerWeaponsAndAmmo(const TActor *a)
2428 {
2429 // Update the player's weapons and ammo based on their actor
2430 PlayerData *p = PlayerDataGetByUID(a->PlayerUID);
2431 if (p == NULL)
2432 {
2433 return;
2434 }
2435 for (int i = 0; i < MAX_WEAPONS; i++)
2436 {
2437 p->guns[i] = a->guns[i].Gun;
2438 }
2439 CArrayCopy(&p->ammo, &a->ammo);
2440 }