Debian Codegraph @

src/game.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-2022, 2024 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 "game.h"
50
51 #include <assert.h>
52
53 #include <cdogs/actor_placement.h>
54 #include <cdogs/actors.h>
55 #include <cdogs/ai.h>
56 #include <cdogs/ai_coop.h>
57 #include <cdogs/automap.h>
58 #include <cdogs/draw/drawtools.h>
59 #include <cdogs/events.h>
60 #include <cdogs/grafx_bg.h>
61 #include <cdogs/handle_game_events.h>
62 #include <cdogs/log.h>
63 #include <cdogs/los.h>
64 #include <cdogs/map_build.h>
65 #include <cdogs/music.h>
66 #include <cdogs/net_client.h>
67 #include <cdogs/net_server.h>
68 #include <cdogs/objs.h>
69 #include <cdogs/pickup.h>
70
71 #include "briefing_screens.h"
72 #include "loading_screens.h"
73 #include "prep.h"
74 #include "screens_end.h"
75
76 static void PlayerSpecialCommands(TActor *actor, const int cmd)
77 {
78 if (Button2(cmd) && CMD_HAS_DIRECTION(cmd))
79 {
80 if (ConfigGetEnum(&gConfig, "Game.SwitchMoveStyle") ==
81 SWITCHMOVE_SLIDE &&
82 actor->vehicleUID == -1)
83 {
84 SlideActor(actor, cmd);
85 }
86 }
87 else if (
88 !Button2(actor->lastCmd) && Button2(cmd) && !actor->specialCmdDir &&
89 !actor->CanPickupSpecial &&
90 !(ConfigGetEnum(&gConfig, "Game.SwitchMoveStyle") ==
91 SWITCHMOVE_SLIDE &&
92 CMD_HAS_DIRECTION(cmd)))
93 {
94 if (actor->vehicleUID >= 0)
95 {
96 // Dismount
97 GameEvent e = GameEventNew(GAME_EVENT_ACTOR_PILOT);
98 e.u.Pilot.On = false;
99 e.u.Pilot.UID = actor->uid;
100 e.u.Pilot.VehicleUID = actor->vehicleUID;
101 GameEventsEnqueue(&gGameEvents, e);
102 }
103 else
104 {
105 ActorTrySwitchWeapon(actor);
106 }
107 }
108 }
109
110 static void RunGameTerminate(GameLoopData *data);
111 static void RunGameOnEnter(GameLoopData *data);
112 static void RunGameOnExit(GameLoopData *data);
113 static void RunGameInput(GameLoopData *data);
114 static GameLoopResult RunGameUpdate(GameLoopData *data, LoopRunner *l);
115 static void RunGameDraw(GameLoopData *data);
116 GameLoopData *RunGame(Campaign *co, struct MissionOptions *m, Map *map)
117 {
118 RunGameData *data;
119 CMALLOC(data, sizeof *data);
120 GameInit(data, co, m, map);
121 GameLoopData *g = GameLoopDataNew(
122 data, RunGameTerminate, RunGameOnEnter, RunGameOnExit, RunGameInput,
123 RunGameUpdate, RunGameDraw);
124 g->FPS = ConfigGetInt(&gConfig, "Game.FPS");
125 g->SuperhotMode = ConfigGetBool(&gConfig, "Game.Superhot(tm)Mode");
126 return g;
127 }
128 static void RunGameReset(RunGameData *rData)
129 {
130 // Clear the background
131 BlitFillBuf(&gGraphicsDevice, colorBlack);
132 BlitUpdateFromBuf(&gGraphicsDevice, gGraphicsDevice.bkg);
133 CameraReset(&rData->Camera);
134 }
135 static void OnGfxChangeCallback(void *data, const bool resetBg)
136 {
137 RunGameData *rData = data;
138 if (resetBg)
139 {
140 RunGameReset(rData);
141 }
142 rData->pm.ms.size = svec2i(
143 rData->pm.ms.graphics->cachedConfig.Res.x,
144 rData->pm.ms.graphics->cachedConfig.Res.y);
145 }
146 static void RunGameTerminate(GameLoopData *data)
147 {
148 RunGameData *rData = data->Data;
149
150 CFREE(rData);
151 }
152 static void RunGameOnEnter(GameLoopData *data)
153 {
154 RunGameData *rData = data->Data;
155
156 RunGameReset(rData);
157
158 CampaignSeedRandom(rData->co);
159 MapBuild(
160 rData->map, rData->m->missionData, !rData->co->IsClient,
161 rData->m->index, rData->co->Entry.Mode,
162 &rData->co->Setting.characters);
163
164 // Seed random if PVP mode (otherwise players will always spawn in same
165 // position)
166 if (IsPVP(rData->co->Entry.Mode))
167 {
168 srand((unsigned int)time(NULL));
169 }
170
171 if (!rData->co->IsClient)
172 {
173 // For PVP modes, mark all map as explored
174 if (IsPVP(rData->co->Entry.Mode))
175 {
176 MapMarkAllAsVisited(rData->map);
177 }
178
179 // Reset players for the mission
180 CA_FOREACH(const PlayerData, p, gPlayerDatas)
181 // Only reset for local players; for remote ones wait for the
182 // client ready message
183 if (!p->IsLocal)
184 continue;
185 GameEvent e = GameEventNew(GAME_EVENT_PLAYER_DATA);
186 e.u.PlayerData = PlayerDataMissionReset(p);
187 GameEventsEnqueue(&gGameEvents, e);
188 CA_FOREACH_END()
189 // Process the events to force add the players
190 HandleGameEvents(&gGameEvents, NULL, NULL, NULL, NULL);
191
192 // Note: place players first,
193 // as bad guys are placed away from players
194 struct vec2 firstPos = svec2_zero();
195 CA_FOREACH(const PlayerData, p, gPlayerDatas)
196 if (!p->Ready)
197 continue;
198 firstPos = PlacePlayer(&gMap, p, firstPos, true);
199 CA_FOREACH_END()
200 if (!IsPVP(rData->co->Entry.Mode))
201 {
202 InitializeBadGuys();
203 CreateEnemies();
204 }
205 }
206
207 CameraInit(&rData->Camera);
208 // If there are no players, show the full map before starting
209 if (GetNumPlayers(PLAYER_ANY, false, true) == 0)
210 {
211 LOSSetAllVisible(&rData->map->LOS);
212 rData->Camera.lastPosition =
213 Vec2CenterOfTile(svec2i_scale_divide(rData->map->Size, 2));
214 rData->Camera.FollowNextPlayer = true;
215 }
216 if (rData->co->Setting.RandomPickups)
217 {
218 HealthSpawnerInit(&rData->healthSpawner, rData->map);
219 CArrayInit(&rData->ammoSpawners, sizeof(PowerupSpawner));
220 for (int i = 0; i < AmmoGetNumClasses(&gAmmo); i++)
221 {
222 PowerupSpawner ps;
223 AmmoSpawnerInit(&ps, rData->map, i);
224 CArrayPushBack(&rData->ammoSpawners, &ps);
225 }
226 }
227
228 PauseMenuInit(
229 &rData->pm, &gEventHandlers, &gGraphicsDevice, OnGfxChangeCallback,
230 rData);
231
232 rData->m->state = MISSION_STATE_WAITING;
233 rData->m->isDone = false;
234 rData->m->DoneCounter = 0;
235
236 NetServerSendGameStartMessages(&gNetServer, NET_SERVER_BCAST);
237 GameEvent start = GameEventNew(GAME_EVENT_GAME_START);
238 GameEventsEnqueue(&gGameEvents, start);
239
240 // Start of mission message
241 GameEvent e = GameEventNew(GAME_EVENT_SET_MESSAGE);
242 if (HasRounds(rData->co->Entry.Mode))
243 {
244 // Display which round it is
245 int totalScores = 0;
246 CA_FOREACH(const PlayerData, p, gPlayerDatas)
247 totalScores += p->Totals.Score;
248 CA_FOREACH_END()
249 sprintf(e.u.SetMessage.Message, "Round %d", totalScores + 1);
250 }
251 else if (IsPVP(rData->co->Entry.Mode))
252 {
253 strcpy(e.u.SetMessage.Message, "Fight!");
254 }
255 else
256 {
257 // Show title of mission
258 strncat(
259 e.u.SetMessage.Message, rData->m->missionData->Title,
260 sizeof e.u.SetMessage.Message - 1);
261 }
262 e.u.SetMessage.Ticks = 3000;
263 GameEventsEnqueue(&gGameEvents, e);
264 }
265 static void RunGameOnExit(GameLoopData *data)
266 {
267 RunGameData *rData = data->Data;
268
269 LOG(LM_MAIN, LL_INFO, "Game finished");
270
271 // Flush events
272 HandleGameEvents(&gGameEvents, NULL, NULL, NULL, NULL);
273
274 PowerupSpawnerTerminate(&rData->healthSpawner);
275 CA_FOREACH(PowerupSpawner, a, rData->ammoSpawners)
276 PowerupSpawnerTerminate(a);
277 CA_FOREACH_END()
278 CArrayTerminate(&rData->ammoSpawners);
279 CameraTerminate(&rData->Camera);
280 PauseMenuTerminate(&rData->pm);
281
282 // Draw background
283 GrafxRedrawBackground(&gGraphicsDevice, rData->Camera.lastPosition);
284 // Clear other texures
285 BlitClearBuf(&gGraphicsDevice);
286 BlitUpdateFromBuf(&gGraphicsDevice, gGraphicsDevice.hud);
287 if (gGraphicsDevice.cachedConfig.SecondWindow)
288 {
289 BlitUpdateFromBuf(&gGraphicsDevice, gGraphicsDevice.hud2);
290 }
291
292 // Unready all the players
293 CA_FOREACH(PlayerData, p, gPlayerDatas)
294 p->Ready = false;
295 CA_FOREACH_END()
296 gNetClient.Ready = false;
297
298 // Calculate remaining health and survived
299 CA_FOREACH(PlayerData, p, gPlayerDatas)
300 p->survived = IsPlayerAlive(p);
301 if (IsPlayerAlive(p))
302 {
303 const TActor *player = ActorGetByUID(p->ActorUID);
304 p->hp = player->health;
305 }
306 CA_FOREACH_END()
307 }
308 static void RunGameInput(GameLoopData *data)
309 {
310 RunGameData *rData = data->Data;
311
312 if (gEventHandlers.HasQuit)
313 {
314 GameEvent e = GameEventNew(GAME_EVENT_MISSION_END);
315 e.u.MissionEnd.IsQuit = true;
316 GameEventsEnqueue(&gGameEvents, e);
317 return;
318 }
319
320 int lastCmdAll = 0;
321 for (int i = 0; i < MAX_LOCAL_PLAYERS; i++)
322 {
323 rData->lastCmds[i] = rData->cmds[i];
324 lastCmdAll |= rData->lastCmds[i];
325 }
326 memset(rData->cmds, 0, sizeof rData->cmds);
327 int cmdAll = 0;
328 if (GetNumPlayers(PLAYER_ANY, false, true) == 0)
329 {
330 // If no players, allow default keyboard to control camera
331 rData->cmds[0] = GetKeyboardCmd(&gEventHandlers.keyboard, 0, false);
332 }
333 else
334 {
335 int idx = 0;
336 for (int i = 0; i < (int)gPlayerDatas.size; i++, idx++)
337 {
338 const PlayerData *p = CArrayGet(&gPlayerDatas, i);
339 if (!p->IsLocal)
340 {
341 idx--;
342 continue;
343 }
344 rData->cmds[idx] = GetGameCmd(&gEventHandlers, p);
345 cmdAll |= rData->cmds[idx];
346 }
347 }
348
349 // If in Superhot(tm) Mode, don't update unless there was an input in this
350 // or the last frame
351 data->SkipNextFrame = data->SuperhotMode && !lastCmdAll;
352
353 const bool wasPaused = PauseMenuIsShown(&rData->pm);
354
355 // Update and check if we want to quit
356 if (PauseMenuUpdate(&rData->pm, rData->cmds, rData->lastCmds))
357 {
358 // Need to unpause to process the quit
359 data->SkipNextFrame = true;
360 }
361
362 if (!PauseMenuIsShown(&rData->pm))
363 {
364 // Check if automap key is pressed by any player
365 // Toggle
366 if (IsAutoMapEnabled(gCampaign.Entry.Mode) &&
367 (KeyIsPressed(
368 &gEventHandlers.keyboard,
369 ConfigGetInt(&gConfig, "Input.PlayerCodes0.map")) ||
370 ((cmdAll & CMD_MAP) && !(lastCmdAll & CMD_MAP))))
371 {
372 rData->isMap = !rData->isMap;
373 SoundPlay(
374 &gSoundDevice,
375 StrSound(rData->isMap ? "map_open" : "map_close"));
376 }
377 if (wasPaused)
378 {
379 // Clear all user inputs if we're using the pause menu
380 memset(rData->cmds, 0, sizeof rData->cmds);
381 memset(rData->lastCmds, 0, sizeof rData->lastCmds);
382 KeyLockKeys(&gEventHandlers.keyboard);
383 JoyLock(&gEventHandlers.joysticks);
384 }
385 }
386
387 if (!wasPaused && PauseMenuIsShown(&rData->pm))
388 {
389 // Don't show map if pause menu is shown
390 rData->isMap = false;
391 // Clear all user inputs if we're using the pause menu
392 memset(rData->cmds, 0, sizeof rData->cmds);
393 memset(rData->lastCmds, 0, sizeof rData->lastCmds);
394 }
395
396 CameraInput(&rData->Camera, rData->cmds[0], rData->lastCmds[0]);
397 }
398 static void NextLoop(RunGameData *rData, LoopRunner *l);
399 static void CheckMissionCompletion(const struct MissionOptions *mo);
400 static GameLoopResult RunGameUpdate(GameLoopData *data, LoopRunner *l)
401 {
402 RunGameData *rData = data->Data;
403
404 // Detect exit
405 if (rData->m->isDone)
406 {
407 rData->m->DoneCounter--;
408 if (rData->m->DoneCounter <= 0)
409 {
410 NextLoop(rData, l);
411 return UPDATE_RESULT_OK;
412 }
413 else
414 {
415 return UPDATE_RESULT_DRAW;
416 }
417 }
418
419 // Check if game can begin
420 if (!rData->m->HasBegun && MissionCanBegin())
421 {
422 GameEvent begin = GameEventNew(GAME_EVENT_GAME_BEGIN);
423 begin.u.GameBegin.MissionTime = gMission.time;
424 GameEventsEnqueue(&gGameEvents, begin);
425 }
426
427 // Set mission complete and display exit if it is complete
428 MissionSetMessageIfComplete(rData->m);
429
430 // If we're not hosting a net game,
431 // don't update if the game has paused or has automap shown
432 // Important: don't consider paused if we are trying to quit
433 const bool paused = PauseMenuIsShown(&rData->pm) || rData->isMap;
434 if (!gCampaign.IsClient && !ConfigGetBool(&gConfig, "StartServer") &&
435 paused && !gEventHandlers.HasQuit)
436 {
437 return UPDATE_RESULT_DRAW;
438 }
439
440 if (data->SkipNextFrame)
441 {
442 return UPDATE_RESULT_DRAW;
443 }
444
445 // If split screen never and players are too close to the
446 // edge of the screen, forcefully pull them towards the center
447 if (ConfigGetEnum(&gConfig, "Interface.Splitscreen") ==
448 SPLITSCREEN_NEVER &&
449 GetNumPlayers(PLAYER_ALIVE_OR_DYING, true, true) > 1 &&
450 !IsPVP(gCampaign.Entry.Mode))
451 {
452 const int w = gGraphicsDevice.cachedConfig.Res.x;
453 const int h = gGraphicsDevice.cachedConfig.Res.y;
454 const struct vec2i screen = svec2i_add(
455 svec2i_assign_vec2(PlayersGetMidpoint()), svec2i(-w / 2, -h / 2));
456 CA_FOREACH(const PlayerData, pd, gPlayerDatas)
457 if (!pd->IsLocal || !IsPlayerAlive(pd))
458 {
459 continue;
460 }
461 const TActor *p = ActorGetByUID(pd->ActorUID);
462 const int pad = CAMERA_SPLIT_PADDING;
463 struct vec2 vel = svec2_zero();
464 if (screen.x + pad > p->thing.Pos.x && p->thing.Vel.x < 1)
465 {
466 vel.x = screen.x + pad - p->thing.Pos.x;
467 }
468 else if (screen.x + w - pad < p->thing.Pos.x && p->thing.Vel.x > -1)
469 {
470 vel.x = screen.x + w - pad - p->thing.Pos.x;
471 }
472 if (screen.y + pad > p->thing.Pos.y && p->thing.Vel.y < 1)
473 {
474 vel.y = screen.y + pad - p->thing.Pos.y;
475 }
476 else if (screen.y + h - pad < p->thing.Pos.y && p->thing.Vel.y > -1)
477 {
478 vel.y = screen.y + h - pad - p->thing.Pos.y;
479 }
480 if (!svec2_is_zero(vel))
481 {
482 GameEvent ei = GameEventNew(GAME_EVENT_ACTOR_IMPULSE);
483 ei.u.ActorImpulse.UID = p->uid;
484 ei.u.ActorImpulse.Vel = Vec2ToNet(svec2_scale(vel, 0.25f));
485 ei.u.ActorImpulse.Pos = Vec2ToNet(svec2_zero());
486 GameEventsEnqueue(&gGameEvents, ei);
487 LOG(LM_MAIN, LL_TRACE,
488 "playerUID(%d) pos(%f, %f) screen(%d, %d) impulse(%f, %f)",
489 p->uid, p->thing.Pos.x, p->thing.Pos.y, screen.x, screen.y,
490 ei.u.ActorImpulse.Vel.x, ei.u.ActorImpulse.Vel.y);
491 }
492 CA_FOREACH_END()
493 }
494
495 const int ticksPerFrame = 1;
496
497 if (gPlayerDatas.size > 0)
498 {
499 LOSReset(&gMap.LOS);
500 for (int i = 0, idx = 0; i < (int)gPlayerDatas.size; i++, idx++)
501 {
502 const PlayerData *p = CArrayGet(&gPlayerDatas, i);
503 if (p->ActorUID == -1)
504 continue;
505 TActor *player = ActorGetByUID(p->ActorUID);
506
507 // Calculate LOS for all players alive or dying
508 LOSCalcFrom(
509 &gMap, Vec2ToTile(player->thing.Pos), !gCampaign.IsClient);
510
511 if (player->dead)
512 continue;
513
514 // Only handle inputs/commands for local players
515 if (!p->IsLocal)
516 {
517 idx--;
518 continue;
519 }
520 if (p->inputDevice == INPUT_DEVICE_AI)
521 {
522 rData->cmds[idx] = AICoopGetCmd(player, ticksPerFrame);
523 }
524 PlayerSpecialCommands(player, rData->cmds[idx]);
525 rData->cmds[idx] =
526 CommandActor(player, rData->cmds[idx], ticksPerFrame);
527 }
528 }
529
530 // Disable sounds on the first frame
531 GameUpdate(rData, ticksPerFrame, data->Frames == 0 ? NULL : &gSoundDevice);
532
533 CameraUpdate(&rData->Camera, ticksPerFrame, 1000 / data->FPS);
534
535 return UPDATE_RESULT_DRAW;
536 }
537 static void PersistPlayerWeaponsAndAmmo(PlayerData *p);
538 static void NextLoop(RunGameData *rData, LoopRunner *l)
539 {
540 // Find the next screen to switch to
541 const bool hasLocalPlayers = GetNumPlayers(PLAYER_ANY, false, true) > 0;
542 const int survivingPlayers = GetNumPlayers(PLAYER_ALIVE, false, false);
543 const bool survivedAndCompletedObjectives =
544 survivingPlayers > 0 && MissionAllObjectivesComplete(&gMission);
545 // Persist player weapons/ammo
546 CA_FOREACH(PlayerData, p, gPlayerDatas)
547 PersistPlayerWeaponsAndAmmo(p);
548 CA_FOREACH_END()
549
550 // Switch to a score screen if there are local players and we haven't quit
551 GameLoopData *nextScreen = NULL;
552 const bool showScores = !rData->co->IsQuit && hasLocalPlayers;
553 if (showScores)
554 {
555 switch (rData->co->Entry.Mode)
556 {
557 case GAME_MODE_DOGFIGHT:
558 nextScreen = ScreenDogfightScores();
559 break;
560 case GAME_MODE_DEATHMATCH:
561 nextScreen = ScreenDeathmatchFinalScores();
562 break;
563 default:
564 // In co-op (non-PVP) modes, at least one player must survive
565 nextScreen = ScreenMissionSummary(
566 rData->co, rData->m, survivedAndCompletedObjectives);
567 break;
568 }
569 }
570 LoopRunnerPush(l, ScreenLoading("Debriefing...", true, nextScreen, true));
571 if (!HasRounds(rData->co->Entry.Mode) && !rData->co->IsComplete)
572 {
573 rData->co->MissionIndex = rData->m->NextMission;
574 }
575 }
576 static void PersistPlayerWeaponsAndAmmo(PlayerData *p)
577 {
578 if (!IsPlayerAlive(p))
579 return;
580 const TActor *a = ActorGetByUID(p->ActorUID);
581 ActorPersistPlayerWeaponsAndAmmo(a);
582 }
583 static void CheckMissionCompletion(const struct MissionOptions *mo)
584 {
585 // Check if we need to update explore objectives
586 CA_FOREACH(const Objective, o, mo->missionData->Objectives)
587 if (o->Type != OBJECTIVE_INVESTIGATE)
588 continue;
589 const int update = MapGetExploredPercentage(&gMap) - o->done;
590 if (update > 0 && !gCampaign.IsClient)
591 {
592 GameEvent e = GameEventNew(GAME_EVENT_OBJECTIVE_UPDATE);
593 e.u.ObjectiveUpdate.ObjectiveId = _ca_index;
594 e.u.ObjectiveUpdate.Count = update;
595 GameEventsEnqueue(&gGameEvents, e);
596 }
597 CA_FOREACH_END()
598
599 const bool complete =
600 GetNumPlayers(PLAYER_ALIVE_OR_DYING, false, false) > 0 &&
601 IsMissionComplete(mo);
602 const int exitIndex = AllSurvivingPlayersInSameExit();
603 const bool canExit = complete && (!MapHasExits(&gMap) || exitIndex >= 0);
604 if (mo->state == MISSION_STATE_PLAY && canExit)
605 {
606 GameEvent e = GameEventNew(GAME_EVENT_MISSION_PICKUP);
607 GameEventsEnqueue(&gGameEvents, e);
608 }
609 if (mo->state == MISSION_STATE_PICKUP && !canExit)
610 {
611 GameEvent e = GameEventNew(GAME_EVENT_MISSION_INCOMPLETE);
612 GameEventsEnqueue(&gGameEvents, e);
613 }
614 if (mo->state == MISSION_STATE_PICKUP &&
615 mo->pickupTime + PICKUP_LIMIT <= mo->time)
616 {
617 GameEvent e = GameEventNew(GAME_EVENT_MISSION_END);
618 if (exitIndex >= 0)
619 {
620 const Exit *exit = CArrayGet(&gMap.exits, exitIndex);
621 e.u.MissionEnd.Mission = exit->Mission;
622 }
623 else
624 {
625 e.u.MissionEnd.Mission = mo->index + 1;
626 }
627 GameEventsEnqueue(&gGameEvents, e);
628 }
629
630 // Check that all players have been destroyed
631 // If the server has no players at all, wait for a player to join
632 if (gPlayerDatas.size > 0)
633 {
634 // Note: there's a period of time where players are dying
635 // Wait until after this period before ending the game
636 bool allPlayersDestroyed = true;
637 CA_FOREACH(const PlayerData, p, gPlayerDatas)
638 if (p->ActorUID != -1)
639 {
640 allPlayersDestroyed = false;
641 break;
642 }
643 CA_FOREACH_END()
644 if (allPlayersDestroyed && AreAllPlayersDeadAndNoLives())
645 {
646 GameEvent e = GameEventNew(GAME_EVENT_MISSION_END);
647 e.u.MissionEnd.Delay = GAME_OVER_DELAY;
648 e.u.MissionEnd.Mission = mo->index;
649 GameEventsEnqueue(&gGameEvents, e);
650 }
651 }
652 }
653 static void RunGameDraw(GameLoopData *data)
654 {
655 RunGameData *rData = data->Data;
656
657 // Draw game layer
658 BlitClearBuf(&gGraphicsDevice);
659 CameraDraw(&rData->Camera, rData->Camera.HUD.DrawData);
660 BlitUpdateFromBuf(&gGraphicsDevice, gGraphicsDevice.screen);
661
662 // Draw HUD layer
663 BlitClearBuf(&gGraphicsDevice);
664 CameraDrawMode(&rData->Camera);
665 HUDDraw(
666 &rData->Camera.HUD, rData->Camera.NumViews,
667 PauseMenuIsShown(&rData->pm));
668 PauseMenuDraw(&rData->pm);
669 // Draw automap if enabled
670 if (rData->isMap)
671 {
672 AutomapDraw(&gGraphicsDevice, NULL, 0, rData->Camera.HUD.showExit);
673 }
674 BlitUpdateFromBuf(&gGraphicsDevice, gGraphicsDevice.hud);
675
676 if (gGraphicsDevice.cachedConfig.SecondWindow)
677 {
678 BlitClearBuf(&gGraphicsDevice);
679 if (IsAutoMapEnabled(gCampaign.Entry.Mode))
680 {
681 AutomapDraw(
682 &gGraphicsDevice, gGraphicsDevice.secondWindow.renderer, 0,
683 rData->Camera.HUD.showExit);
684 }
685 BlitUpdateFromBuf(&gGraphicsDevice, gGraphicsDevice.hud2);
686 }
687 }
688
689 void GameInit(
690 RunGameData *data, Campaign *co, struct MissionOptions *m, Map *map)
691 {
692 memset(data, 0, sizeof *data);
693 data->co = co;
694 data->m = m;
695 data->map = map;
696 }
697
698 void GameUpdate(RunGameData *data, const int ticksPerFrame, SoundDevice *sd)
699 {
700 // Update all the things in the game
701
702 if (!gCampaign.IsClient)
703 {
704 data->aiUpdateCounter -= ticksPerFrame;
705 if (data->aiUpdateCounter <= 0)
706 {
707 const int enemies = AICommand(ticksPerFrame);
708 AIAddRandomEnemies(enemies, data->m->missionData);
709 data->aiUpdateCounter = 4;
710 }
711 else
712 {
713 AICommandLast(ticksPerFrame);
714 }
715 }
716
717 UpdateAllActors(ticksPerFrame);
718 UpdateObjects(ticksPerFrame);
719 UpdateMobileObjects(ticksPerFrame);
720 PickupsUpdate(&gPickups, ticksPerFrame);
721 ParticlesUpdate(&gParticles, ticksPerFrame);
722 MapUpdate(data->map);
723
724 UpdateWatches(&data->map->triggers, ticksPerFrame);
725
726 PowerupSpawnerUpdate(&data->healthSpawner, ticksPerFrame);
727 CA_FOREACH(PowerupSpawner, a, data->ammoSpawners)
728 PowerupSpawnerUpdate(a, ticksPerFrame);
729 CA_FOREACH_END()
730
731 if (!gCampaign.IsClient)
732 {
733 CheckMissionCompletion(data->m);
734 }
735 else if (!NetClientIsConnected(&gNetClient))
736 {
737 // Check if disconnected from server; end mission
738 const NMissionEnd me = NMissionEnd_init_zero;
739 MissionDone(&gMission, me);
740 }
741
742 HandleGameEvents(
743 &gGameEvents, &data->Camera, &data->healthSpawner, &data->ammoSpawners,
744 sd);
745
746 data->m->time += ticksPerFrame;
747
748 if (gEventHandlers.HasResolutionChanged)
749 {
750 RunGameReset(data);
751 }
752 }