DEADSOFTWARE

6812d516e78746f006bdd531fa270a63995378e8
[d2df-sdl.git] / src / game / g_game.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE ../shared/a_modes.inc}
16 unit g_game;
18 interface
20 uses
21 {$IFDEF ENABLE_MENU}
22 g_gui,
23 {$ENDIF}
24 SysUtils, Classes, MAPDEF,
25 g_base, g_basic, g_player, g_res_downloader,
26 g_sound, utils, md5, mempool, xprofiler,
27 g_weapons
28 ;
30 type
31 TGameSettings = record
32 GameType: Byte;
33 GameMode: Byte;
34 TimeLimit: Word;
35 GoalLimit: Word;
36 WarmupTime: Word;
37 SpawnInvul: Word;
38 ItemRespawnTime: Word;
39 MaxLives: Byte;
40 Options: LongWord;
41 WAD: String;
42 end;
44 TGameEvent = record
45 Name: String;
46 Command: String;
47 end;
49 TDelayedEvent = record
50 Pending: Boolean;
51 Time: LongWord;
52 DEType: Byte;
53 DENum: Integer;
54 DEStr: String;
55 end;
57 TChatSound = record
58 Sound: TPlayableSound;
59 Tags: Array of String;
60 FullWord: Boolean;
61 end;
63 TPlayerSettings = record
64 Name: String;
65 Model: String;
66 Color: TRGB;
67 Team: Byte;
68 end;
70 TMegaWADInfo = record
71 Name: String;
72 Description: String;
73 Author: String;
74 Pic: String;
75 end;
77 THearPoint = record
78 Active: Boolean;
79 Coords: TDFPoint;
80 end;
82 function g_Game_IsNet(): Boolean;
83 function g_Game_IsServer(): Boolean;
84 function g_Game_IsClient(): Boolean;
85 procedure g_Game_Init();
86 procedure g_Game_Free (freeTextures: Boolean=true);
87 procedure g_Game_LoadData();
88 procedure g_Game_FreeData();
89 procedure g_Game_Update();
90 procedure g_Game_PreUpdate();
91 procedure g_Game_Quit();
92 function g_Game_ModeToText(Mode: Byte): string;
93 function g_Game_TextToMode(Mode: string): Byte;
94 procedure g_Game_ExecuteEvent(Name: String);
95 function g_Game_DelayEvent(DEType: Byte; Time: LongWord; Num: Integer = 0; Str: String = ''): Integer;
96 procedure g_Game_AddPlayer(Team: Byte = TEAM_NONE);
97 procedure g_Game_RemovePlayer();
98 procedure g_Game_Spectate();
99 procedure g_Game_SpectateCenterView();
100 procedure g_Game_StartSingle(Map: String; TwoPlayers: Boolean; nPlayers: Byte);
101 procedure g_Game_StartCustom(Map: String; GameMode: Byte; TimeLimit, GoalLimit: Word; MaxLives: Byte; Options: LongWord; nPlayers: Byte);
102 procedure g_Game_StartServer(Map: String; GameMode: Byte; TimeLimit, GoalLimit: Word; MaxLives: Byte; Options: LongWord; nPlayers: Byte; IPAddr: LongWord; Port: Word);
103 procedure g_Game_StartClient(Addr: String; Port: Word; PW: String);
104 procedure g_Game_Restart();
105 procedure g_Game_RestartLevel();
106 procedure g_Game_RestartRound(NoMapRestart: Boolean = False);
107 function g_Game_ClientWAD (NewWAD: String; const WHash: TMD5Digest): AnsiString;
108 function g_Game_StartMap(asMegawad: Boolean; Map: String; Force: Boolean = False; const oldMapPath: AnsiString=''): Boolean;
109 procedure g_Game_ChangeMap(const MapPath: String);
110 procedure g_Game_ExitLevel(const Map: AnsiString);
111 function g_Game_GetFirstMap(WAD: String): String;
112 function g_Game_GetNextMap(): String;
113 procedure g_Game_NextLevel();
114 procedure g_Game_Pause(Enable: Boolean);
115 procedure g_Game_HolmesPause(Enable: Boolean);
116 function g_Game_IsWatchedPlayer(UID: Word): Boolean;
117 function g_Game_IsWatchedTeam(Team: Byte): Boolean;
118 procedure g_Game_Message(Msg: String; Time: Word);
119 procedure g_Game_LoadMapList(FileName: String);
120 procedure g_Game_PauseAllSounds(Enable: Boolean);
121 procedure g_Game_StopAllSounds(all: Boolean);
122 procedure g_Game_UpdateTriggerSounds();
123 function g_Game_GetMegaWADInfo(WAD: String): TMegaWADInfo;
124 procedure g_Game_ChatSound(Text: String; Taunt: Boolean = True);
125 procedure g_Game_Announce_GoodShot(SpawnerUID: Word);
126 procedure g_Game_Announce_KillCombo(Param: Integer);
127 procedure g_Game_Announce_BodyKill(SpawnerUID: Word);
128 procedure g_Game_StartVote(Command, Initiator: string);
129 procedure g_Game_CheckVote;
130 {$IFNDEF HEADLESS}
131 procedure g_TakeScreenShot(Filename: string = '');
132 {$ENDIF}
133 procedure g_FatalError(Text: String);
134 procedure g_SimpleError(Text: String);
135 function g_Game_IsTestMap(): Boolean;
136 procedure g_Game_DeleteTestMap();
137 procedure GameCVars(P: SSArray);
138 procedure PlayerSettingsCVars(P: SSArray);
139 procedure SystemCommands(P: SSArray);
140 procedure GameCommands(P: SSArray);
141 procedure GameCheats(P: SSArray);
142 procedure DebugCommands(P: SSArray);
143 procedure g_Game_Process_Params;
144 procedure g_Game_SetLoadingText(Text: String; Max: Integer; reWrite: Boolean);
145 procedure g_Game_StepLoading(Value: Integer = -1);
146 procedure g_Game_ClearLoading();
147 procedure g_Game_SetDebugMode();
149 function IsActivePlayer(p: TPlayer): Boolean;
150 function GetActivePlayerID_Next(Skip: Integer = -1): Integer;
151 procedure SortGameStat(var stat: TPlayerStatArray);
154 {$IFDEF ENABLE_MENU}
155 procedure g_Game_InGameMenu(Show: Boolean);
156 {$ENDIF}
157 {$IFNDEF HEADLESS}
158 procedure CharPress (C: AnsiChar);
159 {$ENDIF}
160 procedure KeyPress (K: Word);
162 { procedure SetWinPause(Enable: Boolean); }
164 const
165 GAME_TICK = 28;
167 LOADING_SHOW_STEP = 100;
168 LOADING_INTERLINE = 20;
170 GT_NONE = 0;
171 GT_SINGLE = 1;
172 GT_CUSTOM = 2;
173 GT_SERVER = 3;
174 GT_CLIENT = 4;
176 GM_NONE = 0;
177 GM_DM = 1;
178 GM_TDM = 2;
179 GM_CTF = 3;
180 GM_COOP = 4;
181 GM_SINGLE = 5;
183 EXIT_QUIT = 1;
184 EXIT_SIMPLE = 2;
185 EXIT_RESTART = 3;
186 EXIT_ENDLEVELSINGLE = 4;
187 EXIT_ENDLEVELCUSTOM = 5;
189 GAME_OPTION_RESERVED = 1;
190 GAME_OPTION_TEAMDAMAGE = 2;
191 GAME_OPTION_ALLOWEXIT = 4;
192 GAME_OPTION_WEAPONSTAY = 8;
193 GAME_OPTION_MONSTERS = 16;
194 GAME_OPTION_BOTVSPLAYER = 32;
195 GAME_OPTION_BOTVSMONSTER = 64;
196 GAME_OPTION_DMKEYS = 128;
197 GAME_OPTION_TEAMHITTRACE = 256;
198 GAME_OPTION_TEAMHITPROJECTILE = 512;
199 GAME_OPTION_TEAMABSORBDAMAGE = 1024;
201 STATE_NONE = 0;
202 STATE_MENU = 1;
203 STATE_FOLD = 2;
204 STATE_INTERCUSTOM = 3;
205 STATE_INTERSINGLE = 4;
206 STATE_INTERTEXT = 5;
207 STATE_INTERPIC = 6;
208 STATE_ENDPIC = 7;
209 STATE_SLIST = 8;
211 LMS_RESPAWN_NONE = 0;
212 LMS_RESPAWN_WARMUP = 1;
213 LMS_RESPAWN_FINAL = 2;
215 SPECT_NONE = 0;
216 SPECT_STATS = 1;
217 SPECT_MAPVIEW = 2;
218 SPECT_PLAYERS = 3;
220 DE_GLOBEVENT = 0;
221 DE_BFGHIT = 1;
222 DE_KILLCOMBO = 2;
223 DE_BODYKILL = 3;
225 ANNOUNCE_NONE = 0;
226 ANNOUNCE_ME = 1;
227 ANNOUNCE_MEPLUS = 2;
228 ANNOUNCE_ALL = 3;
230 CONFIG_FILENAME = 'Doom2DF.cfg';
232 TEST_MAP_NAME = '$$$_TEST_$$$';
234 STD_PLAYER_MODEL = 'Doomer';
236 {$IFDEF HEADLESS}
237 DEFAULT_PLAYERS = 0;
238 {$ELSE}
239 DEFAULT_PLAYERS = 1;
240 {$ENDIF}
242 STATFILE_VERSION = $03;
244 var
245 gGameSettings: TGameSettings;
246 gPlayer1Settings: TPlayerSettings;
247 gPlayer2Settings: TPlayerSettings;
248 gGameOn: Boolean;
249 gPlayerScreenSize: TDFPoint;
250 gPlayer1ScreenCoord: TDFPoint;
251 gPlayer2ScreenCoord: TDFPoint;
252 gPlayer1: TPlayer = nil;
253 gPlayer2: TPlayer = nil;
254 gPlayerDrawn: TPlayer = nil;
255 gTime: LongWord;
256 gLerpFactor: Single = 1.0;
257 gSwitchGameMode: Byte = GM_DM;
258 gHearPoint1, gHearPoint2: THearPoint;
259 gSoundEffectsDF: Boolean = False;
260 gSoundTriggerTime: Word = 0;
261 gAnnouncer: Integer = ANNOUNCE_NONE;
262 goodsnd: array[0..3] of TPlayableSound;
263 killsnd: array[0..3] of TPlayableSound;
264 hahasnd: array[0..2] of TPlayableSound;
265 sound_get_flag: array[0..1] of TPlayableSound;
266 sound_lost_flag: array[0..1] of TPlayableSound;
267 sound_ret_flag: array[0..1] of TPlayableSound;
268 sound_cap_flag: array[0..1] of TPlayableSound;
269 gBodyKillEvent: Integer = -1;
270 gDefInterTime: ShortInt = -1;
271 gInterEndTime: LongWord = 0;
272 gInterTime: LongWord = 0;
273 gServInterTime: Byte = 0;
274 gGameStartTime: LongWord = 0;
275 gTotalMonsters: Integer = 0;
276 gPauseMain: Boolean = false;
277 gPauseHolmes: Boolean = false;
278 gShowTime: Boolean = False;
279 gShowFPS: Boolean = False;
280 gShowGoals: Boolean = True;
281 gShowStat: Boolean = True;
282 gShowPIDs: Boolean = False;
283 gShowKillMsg: Boolean = True;
284 gShowLives: Boolean = True;
285 gShowPing: Boolean = False;
286 gShowMap: Boolean = False;
287 gExit: Byte = 0;
288 gState: Byte = STATE_NONE;
289 sX, sY: Integer;
290 sWidth, sHeight: Word;
291 gSpectMode: Byte = SPECT_NONE;
292 gSpectHUD: Boolean = True;
293 gSpectKeyPress: Boolean = False;
294 gSpectX: Integer = 0;
295 gSpectY: Integer = 0;
296 gSpectStep: Byte = 8;
297 gSpectViewTwo: Boolean = False;
298 gSpectPID1: Integer = -1;
299 gSpectPID2: Integer = -1;
300 gSpectAuto: Boolean = False;
301 gSpectAutoNext: LongWord;
302 gSpectAutoStepX: Integer;
303 gSpectAutoStepY: Integer;
304 gMusic: TMusic = nil;
305 gLoadGameMode: Boolean;
306 gCheats: Boolean = False;
307 gMapOnce: Boolean = False;
308 gMapToDelete: String;
309 gTempDelete: Boolean = False;
310 gLastMap: Boolean = False;
311 gScreenWidth: Word;
312 gScreenHeight: Word;
313 gResolutionChange: Boolean = False;
314 gRC_Width, gRC_Height: Integer;
315 gRC_FullScreen, gRC_Maximized: Boolean;
316 gLanguageChange: Boolean = False;
317 gDebugMode: Boolean = False;
318 g_debug_Sounds: Boolean = False;
319 g_debug_Frames: Boolean = False;
320 g_debug_WinMsgs: Boolean = False;
321 g_debug_MonsterOff: Boolean = False;
322 g_debug_BotAIOff: Byte = 0;
323 g_debug_HealthBar: Boolean = False;
324 g_Debug_Player: Boolean = False;
325 gCoopMonstersKilled: Word = 0;
326 gCoopSecretsFound: Word = 0;
327 gCoopTotalMonstersKilled: Word = 0;
328 gCoopTotalSecretsFound: Word = 0;
329 gCoopTotalMonsters: Word = 0;
330 gCoopTotalSecrets: Word = 0;
331 gStatsOff: Boolean = False;
332 gStatsPressed: Boolean = False;
333 gExitByTrigger: Boolean = False;
334 gNextMap: String = '';
335 gLMSRespawn: Byte = LMS_RESPAWN_NONE;
336 gLMSRespawnTime: Cardinal = 0;
337 gLMSSoftSpawn: Boolean = False;
338 gMissionFailed: Boolean = False;
339 gVoteInProgress: Boolean = False;
340 gVotePassed: Boolean = False;
341 gVoteCommand: string = '';
342 gVoteTimer: Cardinal = 0;
343 gVoteCmdTimer: Cardinal = 0;
344 gVoteCount: Integer = 0;
345 gVoteTimeout: Cardinal = 30;
346 gVoted: Boolean = False;
347 gVotesEnabled: Boolean = True;
348 gEvents: Array of TGameEvent;
349 gDelayedEvents: Array of TDelayedEvent;
350 gUseChatSounds: Boolean = True;
351 gChatSounds: Array of TChatSound;
352 gSelectWeapon: Array [0..1, WP_FIRST..WP_LAST] of Boolean; // [player, weapon]
353 gInterReadyCount: Integer = 0;
355 g_dbg_ignore_bounds: Boolean = false;
356 r_smallmap_h: Integer = 0; // 0: left; 1: center; 2: right
357 r_smallmap_v: Integer = 2; // 0: top; 1: center; 2: bottom
359 // move button values:
360 // bits 0-1: l/r state:
361 // 0: neither left, nor right pressed
362 // 1: left pressed
363 // 2: right pressed
364 // bits 4-5: l/r state when strafe was pressed
365 P1MoveButton: Byte = 0;
366 P2MoveButton: Byte = 0;
368 g_profile_frame_update: Boolean = false;
369 g_profile_frame_draw: Boolean = false;
370 g_profile_collision: Boolean = false;
371 g_profile_los: Boolean = false;
372 g_profile_history_size: Integer = 1000;
374 g_rlayer_back: Boolean = true;
375 g_rlayer_step: Boolean = true;
376 g_rlayer_wall: Boolean = true;
377 g_rlayer_door: Boolean = true;
378 g_rlayer_acid1: Boolean = true;
379 g_rlayer_acid2: Boolean = true;
380 g_rlayer_water: Boolean = true;
381 g_rlayer_fore: Boolean = true;
383 wNeedTimeReset: Boolean = false;
385 procedure g_ResetDynlights ();
386 procedure g_AddDynLight (x, y, radius: Integer; r, g, b, a: Single);
387 procedure g_DynLightExplosion (x, y, radius: Integer; r, g, b: Single);
389 function conIsCheatsEnabled (): Boolean; inline;
390 function gPause (): Boolean; inline;
392 type (* private state *)
393 TEndCustomGameStat = record
394 PlayerStat: TPlayerStatArray;
395 TeamStat: TTeamStat;
396 GameTime: LongWord;
397 GameMode: Byte;
398 Map, MapName: String;
399 end;
401 TEndSingleGameStat = record
402 PlayerStat: Array [0..1] of record
403 Kills: Integer;
404 Secrets: Integer;
405 end;
406 GameTime: LongWord;
407 TwoPlayers: Boolean;
408 TotalSecrets: Integer;
409 end;
411 TLoadingStat = record
412 CurValue: Integer;
413 MaxValue: Integer;
414 ShowCount: Integer;
415 Msgs: Array of String;
416 NextMsg: Word;
417 PBarWasHere: Boolean; // did we draw a progress bar for this message?
418 end;
420 TDynLight = record
421 x, y, radius: Integer;
422 r, g, b, a: Single;
423 exploCount: Integer;
424 exploRadius: Integer;
425 end;
427 var (* private state *)
428 CustomStat: TEndCustomGameStat;
429 StatShotDone: Boolean;
430 StatFilename: string = ''; // used by stat screenshot to save with the same name as the csv
431 SingleStat: TEndSingleGameStat;
432 LoadingStat: TLoadingStat;
433 MessageText: String;
434 IsDrawStat: Boolean;
435 EndingGameCounter: Byte;
436 UPS: Word;
437 g_playerLight: Boolean;
438 g_dynLights: array of TDynLight = nil;
439 g_dynLightCount: Integer = 0;
440 EndPicPath: AnsiString; // full path, used by render
442 implementation
444 uses
445 {$IFDEF ENABLE_HOLMES}
446 g_holmes,
447 {$ENDIF}
448 {$IFDEF ENABLE_MENU}
449 g_menu,
450 {$ENDIF}
451 {$IFDEF ENABLE_GFX}
452 g_gfx,
453 {$ENDIF}
454 {$IFDEF ENABLE_GIBS}
455 g_gibs,
456 {$ENDIF}
457 {$IFDEF ENABLE_SHELLS}
458 g_shells,
459 {$ENDIF}
460 {$IFDEF ENABLE_CORPSES}
461 g_corpses,
462 {$ENDIF}
463 {$IFNDEF HEADLESS}
464 r_render, g_system,
465 {$ENDIF}
466 e_res, g_window,
467 e_input, e_log, g_console, g_items, g_map, g_panel,
468 g_playermodel, g_options, Math,
469 g_triggers, g_monsters, e_sound, CONFIG,
470 g_language, g_net, g_phys,
471 ENet, e_msg, g_netmsg, g_netmaster,
472 sfs, wadreader;
474 var
475 charbuff: packed array [0..15] of AnsiChar = (
476 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
477 );
479 function Translit (const S: AnsiString): AnsiString;
480 var
481 i: Integer;
482 begin
483 Result := S;
484 for i := 1 to Length(Result) do
485 begin
486 case Result[i] of
487 #$C9: Result[i] := 'Q';
488 #$D6: Result[i] := 'W';
489 #$D3: Result[i] := 'E';
490 #$CA: Result[i] := 'R';
491 #$C5: Result[i] := 'T';
492 #$CD: Result[i] := 'Y';
493 #$C3: Result[i] := 'U';
494 #$D8: Result[i] := 'I';
495 #$D9: Result[i] := 'O';
496 #$C7: Result[i] := 'P';
497 #$D5: Result[i] := '['; //Chr(219);
498 #$DA: Result[i] := ']'; //Chr(221);
499 #$D4: Result[i] := 'A';
500 #$DB: Result[i] := 'S';
501 #$C2: Result[i] := 'D';
502 #$C0: Result[i] := 'F';
503 #$CF: Result[i] := 'G';
504 #$D0: Result[i] := 'H';
505 #$CE: Result[i] := 'J';
506 #$CB: Result[i] := 'K';
507 #$C4: Result[i] := 'L';
508 #$C6: Result[i] := ';'; //Chr(186);
509 #$DD: Result[i] := #39; //Chr(222);
510 #$DF: Result[i] := 'Z';
511 #$D7: Result[i] := 'X';
512 #$D1: Result[i] := 'C';
513 #$CC: Result[i] := 'V';
514 #$C8: Result[i] := 'B';
515 #$D2: Result[i] := 'N';
516 #$DC: Result[i] := 'M';
517 #$C1: Result[i] := ','; //Chr(188);
518 #$DE: Result[i] := '.'; //Chr(190);
519 end;
520 end;
521 end;
524 function CheckCheat (ct: TStrings_Locale; eofs: Integer=0): Boolean;
525 var
526 ls1, ls2: string;
527 begin
528 ls1 := CheatEng[ct];
529 ls2 := Translit(CheatRus[ct]);
530 if length(ls1) = 0 then ls1 := '~';
531 if length(ls2) = 0 then ls2 := '~';
532 result :=
533 (Copy(charbuff, 17-Length(ls1)-eofs, Length(ls1)) = ls1) or
534 (Translit(Copy(charbuff, 17-Length(ls1)-eofs, Length(ls1))) = ls1) or
535 (Copy(charbuff, 17-Length(ls2)-eofs, Length(ls2)) = ls2) or
536 (Translit(Copy(charbuff, 17-Length(ls2)-eofs, Length(ls2))) = ls2);
538 if ct = I_GAME_CHEAT_JETPACK then
539 begin
540 e_WriteLog('ls1: ['+ls1+']', MSG_NOTIFY);
541 e_WriteLog('ls2: ['+ls2+']', MSG_NOTIFY);
542 e_WriteLog('bf0: ['+Copy(charbuff, 17-Length(ls1)-eofs, Length(ls1))+']', MSG_NOTIFY);
543 e_WriteLog('bf1: ['+Translit(Copy(charbuff, 17-Length(ls1)-eofs, Length(ls1)))+']', MSG_NOTIFY);
544 e_WriteLog('bf2: ['+Copy(charbuff, 17-Length(ls2)-eofs, Length(ls2))+']', MSG_NOTIFY);
545 e_WriteLog('bf3: ['+Translit(Copy(charbuff, 17-Length(ls2)-eofs, Length(ls2)))+']', MSG_NOTIFY);
546 end;
548 end;
550 procedure Cheat ();
551 const
552 CHEAT_DAMAGE = 500;
553 label
554 Cheated;
555 var
556 s, s2: string;
557 c: ShortString;
558 a: Integer;
559 begin
561 if (not gGameOn) or (not gCheats) or ((gGameSettings.GameType <> GT_SINGLE) and
562 (gGameSettings.GameMode <> GM_COOP) and (not gDebugMode))
563 or g_Game_IsNet then Exit;
565 if not gGameOn then exit;
566 if not conIsCheatsEnabled then exit;
568 s := 'SOUND_GAME_RADIO';
570 //
571 if CheckCheat(I_GAME_CHEAT_GODMODE) then
572 begin
573 if gPlayer1 <> nil then gPlayer1.GodMode := not gPlayer1.GodMode;
574 if gPlayer2 <> nil then gPlayer2.GodMode := not gPlayer2.GodMode;
575 goto Cheated;
576 end;
577 // RAMBO
578 if CheckCheat(I_GAME_CHEAT_WEAPONS) then
579 begin
580 if gPlayer1 <> nil then gPlayer1.AllRulez(False);
581 if gPlayer2 <> nil then gPlayer2.AllRulez(False);
582 goto Cheated;
583 end;
584 // TANK
585 if CheckCheat(I_GAME_CHEAT_HEALTH) then
586 begin
587 if gPlayer1 <> nil then gPlayer1.AllRulez(True);
588 if gPlayer2 <> nil then gPlayer2.AllRulez(True);
589 goto Cheated;
590 end;
591 // IDDQD
592 if CheckCheat(I_GAME_CHEAT_DEATH) then
593 begin
594 if gPlayer1 <> nil then gPlayer1.Damage(CHEAT_DAMAGE, 0, 0, 0, HIT_TRAP);
595 if gPlayer2 <> nil then gPlayer2.Damage(CHEAT_DAMAGE, 0, 0, 0, HIT_TRAP);
596 s := 'SOUND_MONSTER_HAHA';
597 goto Cheated;
598 end;
599 //
600 if CheckCheat(I_GAME_CHEAT_DOORS) then
601 begin
602 g_Triggers_OpenAll();
603 goto Cheated;
604 end;
605 // GOODBYE
606 if CheckCheat(I_GAME_CHEAT_NEXTMAP) then
607 begin
608 if gTriggers <> nil then
609 for a := 0 to High(gTriggers) do
610 if gTriggers[a].TriggerType = TRIGGER_EXIT then
611 begin
612 gExitByTrigger := True;
613 //g_Game_ExitLevel(gTriggers[a].Data.MapName);
614 g_Game_ExitLevel(gTriggers[a].tgcMap);
615 Break;
616 end;
617 goto Cheated;
618 end;
619 //
620 s2 := Copy(charbuff, 15, 2);
621 if CheckCheat(I_GAME_CHEAT_CHANGEMAP, 2) and (s2[1] >= '0') and (s2[1] <= '9') and (s2[2] >= '0') and (s2[2] <= '9') then
622 begin
623 if g_Map_Exist(gGameSettings.WAD + ':\MAP' + s2) then
624 begin
625 c := 'MAP' + s2;
626 g_Game_ExitLevel(c);
627 end;
628 goto Cheated;
629 end;
630 //
631 if CheckCheat(I_GAME_CHEAT_FLY) then
632 begin
633 gFly := not gFly;
634 goto Cheated;
635 end;
636 // BULLFROG
637 if CheckCheat(I_GAME_CHEAT_JUMPS) then
638 begin
639 VEL_JUMP := 30-VEL_JUMP;
640 goto Cheated;
641 end;
642 // FORMULA1
643 if CheckCheat(I_GAME_CHEAT_SPEED) then
644 begin
645 MAX_RUNVEL := 32-MAX_RUNVEL;
646 goto Cheated;
647 end;
648 // CONDOM
649 if CheckCheat(I_GAME_CHEAT_SUIT) then
650 begin
651 if gPlayer1 <> nil then gPlayer1.GiveItem(ITEM_SUIT);
652 if gPlayer2 <> nil then gPlayer2.GiveItem(ITEM_SUIT);
653 goto Cheated;
654 end;
655 //
656 if CheckCheat(I_GAME_CHEAT_AIR) then
657 begin
658 if gPlayer1 <> nil then gPlayer1.GiveItem(ITEM_OXYGEN);
659 if gPlayer2 <> nil then gPlayer2.GiveItem(ITEM_OXYGEN);
660 goto Cheated;
661 end;
662 // PURELOVE
663 if CheckCheat(I_GAME_CHEAT_BERSERK) then
664 begin
665 if gPlayer1 <> nil then gPlayer1.GiveItem(ITEM_MEDKIT_BLACK);
666 if gPlayer2 <> nil then gPlayer2.GiveItem(ITEM_MEDKIT_BLACK);
667 goto Cheated;
668 end;
669 //
670 if CheckCheat(I_GAME_CHEAT_JETPACK) then
671 begin
672 if gPlayer1 <> nil then gPlayer1.GiveItem(ITEM_JETPACK);
673 if gPlayer2 <> nil then gPlayer2.GiveItem(ITEM_JETPACK);
674 goto Cheated;
675 end;
676 // CASPER
677 if CheckCheat(I_GAME_CHEAT_NOCLIP) then
678 begin
679 if gPlayer1 <> nil then gPlayer1.SwitchNoClip;
680 if gPlayer2 <> nil then gPlayer2.SwitchNoClip;
681 goto Cheated;
682 end;
683 //
684 if CheckCheat(I_GAME_CHEAT_NOTARGET) then
685 begin
686 if gPlayer1 <> nil then gPlayer1.NoTarget := not gPlayer1.NoTarget;
687 if gPlayer2 <> nil then gPlayer2.NoTarget := not gPlayer2.NoTarget;
688 goto Cheated;
689 end;
690 // INFERNO
691 if CheckCheat(I_GAME_CHEAT_NORELOAD) then
692 begin
693 if gPlayer1 <> nil then gPlayer1.NoReload := not gPlayer1.NoReload;
694 if gPlayer2 <> nil then gPlayer2.NoReload := not gPlayer2.NoReload;
695 goto Cheated;
696 end;
697 if CheckCheat(I_GAME_CHEAT_AIMLINE) then
698 begin
699 gAimLine := not gAimLine;
700 goto Cheated;
701 end;
702 if CheckCheat(I_GAME_CHEAT_AUTOMAP) then
703 begin
704 gShowMap := not gShowMap;
705 goto Cheated;
706 end;
707 Exit;
709 Cheated:
710 g_Sound_PlayEx(s);
711 end;
714 {$IFDEF ENABLE_MENU}
715 procedure KeyPress (K: Word);
716 var Msg: g_gui.TMessage;
717 begin
718 case K of
719 VK_ESCAPE: // <Esc>:
720 begin
721 if (g_ActiveWindow <> nil) then
722 begin
723 Msg.Msg := WM_KEYDOWN;
724 Msg.WParam := VK_ESCAPE;
725 g_ActiveWindow.OnMessage(Msg);
726 if (not g_Game_IsNet) and (g_ActiveWindow = nil) then g_Game_Pause(false); //Fn loves to do this
727 end
728 else if (gState <> STATE_FOLD) then
729 begin
730 if gGameOn or (gState = STATE_INTERSINGLE) or (gState = STATE_INTERCUSTOM) then
731 begin
732 g_Game_InGameMenu(True);
733 end
734 else if (gExit = 0) and (gState <> STATE_SLIST) then
735 begin
736 if (gState <> STATE_MENU) then
737 begin
738 if (NetMode <> NET_NONE) then
739 begin
740 g_Game_StopAllSounds(True);
741 g_Game_Free;
742 gState := STATE_MENU;
743 Exit;
744 end;
745 end;
746 g_GUI_ShowWindow('MainMenu');
747 g_Sound_PlayEx('MENU_OPEN');
748 end;
749 end;
750 end;
752 IK_F2, IK_F3, IK_F4, IK_F5, IK_F6, IK_F7, IK_F10:
753 begin // <F2> .. <F6> � <F12>
754 if gGameOn and (not gConsoleShow) and (not gChatShow) then
755 begin
756 while (g_ActiveWindow <> nil) do g_GUI_HideWindow(False);
757 if (not g_Game_IsNet) then g_Game_Pause(True);
758 case K of
759 IK_F2: g_Menu_Show_SaveMenu();
760 IK_F3: g_Menu_Show_LoadMenu();
761 IK_F4: g_Menu_Show_GameSetGame();
762 IK_F5: g_Menu_Show_OptionsVideo();
763 IK_F6: g_Menu_Show_OptionsSound();
764 IK_F7: g_Menu_Show_EndGameMenu();
765 IK_F10: g_Menu_Show_QuitGameMenu();
766 end;
767 end;
768 end;
770 else
771 begin
772 gJustChatted := False;
773 if gConsoleShow or gChatShow then
774 begin
775 g_Console_Control(K);
776 end
777 else if (g_ActiveWindow <> nil) then
778 begin
779 Msg.Msg := WM_KEYDOWN;
780 Msg.WParam := K;
781 g_ActiveWindow.OnMessage(Msg);
782 end
783 else if (gState = STATE_MENU) then
784 begin
785 g_GUI_ShowWindow('MainMenu');
786 g_Sound_PlayEx('MENU_OPEN');
787 end;
788 end;
789 end;
790 end;
791 {$ELSE}
792 procedure KeyPress (K: Word);
793 begin
794 gJustChatted := False;
795 if gConsoleShow or gChatShow then
796 begin
797 g_Console_Control(K);
798 end
799 end;
800 {$ENDIF}
802 {$IFNDEF HEADLESS}
803 procedure CharPress (C: AnsiChar);
804 {$IFDEF ENABLE_MENU}
805 var Msg: g_gui.TMessage;
806 {$ENDIF}
807 var a: Integer;
808 begin
809 if gConsoleShow or gChatShow then
810 begin
811 g_Console_Char(C);
812 end
813 {$IFDEF ENABLE_MENU}
814 else if g_ActiveWindow <> nil then
815 begin
816 Msg.Msg := WM_CHAR;
817 Msg.WParam := Ord(C);
818 g_ActiveWindow.OnMessage(Msg);
819 end
820 {$ENDIF}
821 else
822 begin
823 for a := 0 to 14 do
824 begin
825 charbuff[a] := charbuff[a + 1];
826 end;
827 charbuff[15] := upcase1251(C);
828 Cheat;
829 end;
830 end;
831 {$ENDIF}
834 // ////////////////////////////////////////////////////////////////////////// //
835 function gPause (): Boolean; inline; begin result := gPauseMain or gPauseHolmes; end;
837 procedure g_ResetDynlights ();
838 var
839 lnum, idx: Integer;
840 begin
841 if not gwin_has_stencil then begin g_dynLightCount := 0; exit; end;
842 lnum := 0;
843 for idx := 0 to g_dynLightCount-1 do
844 begin
845 if g_dynLights[idx].exploCount = -666 then
846 begin
847 // skip it
848 end
849 else
850 begin
851 // explosion
852 Inc(g_dynLights[idx].exploCount);
853 if (g_dynLights[idx].exploCount < 10) then
854 begin
855 g_dynLights[idx].radius := g_dynLights[idx].exploRadius+g_dynLights[idx].exploCount*8;
856 g_dynLights[idx].a := 0.4+g_dynLights[idx].exploCount/10;
857 if (g_dynLights[idx].a > 0.8) then g_dynLights[idx].a := 0.8;
858 if lnum <> idx then g_dynLights[lnum] := g_dynLights[idx];
859 Inc(lnum);
860 end;
861 end;
862 end;
863 g_dynLightCount := lnum;
864 end;
866 procedure g_AddDynLight (x, y, radius: Integer; r, g, b, a: Single);
867 begin
868 if not gwin_has_stencil then exit;
869 if g_dynLightCount = length(g_dynLights) then SetLength(g_dynLights, g_dynLightCount+1024);
870 g_dynLights[g_dynLightCount].x := x;
871 g_dynLights[g_dynLightCount].y := y;
872 g_dynLights[g_dynLightCount].radius := radius;
873 g_dynLights[g_dynLightCount].r := r;
874 g_dynLights[g_dynLightCount].g := g;
875 g_dynLights[g_dynLightCount].b := b;
876 g_dynLights[g_dynLightCount].a := a;
877 g_dynLights[g_dynLightCount].exploCount := -666;
878 Inc(g_dynLightCount);
879 end;
881 procedure g_DynLightExplosion (x, y, radius: Integer; r, g, b: Single);
882 begin
883 if not gwin_has_stencil then exit;
884 if g_dynLightCount = length(g_dynLights) then SetLength(g_dynLights, g_dynLightCount+1024);
885 g_dynLights[g_dynLightCount].x := x;
886 g_dynLights[g_dynLightCount].y := y;
887 g_dynLights[g_dynLightCount].radius := 0;
888 g_dynLights[g_dynLightCount].exploRadius := radius;
889 g_dynLights[g_dynLightCount].r := r;
890 g_dynLights[g_dynLightCount].g := g;
891 g_dynLights[g_dynLightCount].b := b;
892 g_dynLights[g_dynLightCount].a := 0;
893 g_dynLights[g_dynLightCount].exploCount := 0;
894 Inc(g_dynLightCount);
895 end;
897 // ////////////////////////////////////////////////////////////////////////// //
898 function conIsCheatsEnabled (): Boolean; inline;
899 begin
900 result := false;
901 if g_Game_IsNet then exit;
902 if not gDebugMode then
903 begin
904 //if not gCheats then exit;
905 if not (gGameSettings.GameType in [GT_SINGLE, GT_CUSTOM]) then exit;
906 if not (gGameSettings.GameMode in [GM_COOP, GM_SINGLE]) then exit;
907 end;
908 result := true;
909 end;
911 // ////////////////////////////////////////////////////////////////////////// //
912 type
913 TParamStrValue = record
914 Name: String;
915 Value: String;
916 end;
918 TParamStrValues = Array of TParamStrValue;
920 const
921 INTER_ACTION_TEXT = 1;
922 INTER_ACTION_PIC = 2;
923 INTER_ACTION_MUSIC = 3;
925 var
926 UPSCounter: Word;
927 UPSTime: LongWord;
928 DataLoaded: Boolean = False;
929 MessageTime: Word;
930 MapList: SSArray = nil;
931 MapIndex: Integer = -1;
932 InterReadyTime: Integer = -1;
933 StatDate: string = '';
934 MegaWAD: record
935 info: TMegaWADInfo;
936 endpic: String;
937 endmus: String;
938 end;
939 InterText: record
940 lines: SSArray;
941 img: String;
942 cur_line: Integer;
943 cur_char: Integer;
944 counter: Integer;
945 endtext: Boolean;
946 end;
948 function Compare(a, b: TPlayerStat): Integer;
949 begin
950 if a.Spectator then Result := 1
951 else if b.Spectator then Result := -1
952 else if a.Frags < b.Frags then Result := 1
953 else if a.Frags > b.Frags then Result := -1
954 else if a.Deaths < b.Deaths then Result := -1
955 else if a.Deaths > b.Deaths then Result := 1
956 else if a.Kills < b.Kills then Result := -1
957 else Result := 1;
958 end;
960 procedure SortGameStat(var stat: TPlayerStatArray);
961 var
962 I, J: Integer;
963 T: TPlayerStat;
964 begin
965 if stat = nil then Exit;
967 for I := High(stat) downto Low(stat) do
968 for J := Low(stat) to High(stat) - 1 do
969 if Compare(stat[J], stat[J + 1]) = 1 then
970 begin
971 T := stat[J];
972 stat[J] := stat[J + 1];
973 stat[J + 1] := T;
974 end;
975 end;
977 // saves a shitty CSV containing the game stats passed to it
978 procedure SaveGameStat(Stat: TEndCustomGameStat; Path: string);
979 var
980 s: TextFile;
981 dir, fname, map, mode, etime: String;
982 I: Integer;
983 begin
984 try
985 dir := e_GetWriteableDir(StatsDirs);
986 // stats are placed in stats/yy/mm/dd/*.csv
987 fname := e_CatPath(dir, Path);
988 ForceDirectories(fname); // ensure yy/mm/dd exists within the stats dir
989 fname := e_CatPath(fname, StatFilename + '.csv');
990 AssignFile(s, fname);
991 try
992 Rewrite(s);
993 // line 1: stats ver, datetime, server name, map name, game mode, time limit, score limit, dmflags, game time, num players
994 if g_Game_IsNet then fname := NetServerName else fname := '';
995 map := g_ExtractWadNameNoPath(gMapInfo.Map) + ':/' + g_ExtractFileName(gMapInfo.Map);
996 mode := g_Game_ModeToText(Stat.GameMode);
997 etime := Format('%d:%.2d:%.2d', [
998 Stat.GameTime div 1000 div 3600,
999 (Stat.GameTime div 1000 div 60) mod 60,
1000 Stat.GameTime div 1000 mod 60
1001 ]);
1002 WriteLn(s, 'stats_ver,datetime,server,map,mode,timelimit,scorelimit,dmflags,time,num_players');
1003 WriteLn(s, Format('%d,%s,%s,%s,%s,%u,%u,%u,%s,%d', [
1004 STATFILE_VERSION,
1005 StatDate,
1006 dquoteStr(fname),
1007 dquoteStr(map),
1008 mode,
1009 gGameSettings.TimeLimit,
1010 gGameSettings.GoalLimit,
1011 gGameSettings.Options,
1012 etime,
1013 Length(Stat.PlayerStat)
1014 ]));
1015 // line 2: game specific shit
1016 // if it's a team game: red score, blue score
1017 // if it's a coop game: monsters killed, monsters total, secrets found, secrets total
1018 // otherwise nothing
1019 if Stat.GameMode in [GM_TDM, GM_CTF] then
1020 WriteLn(s,
1021 Format('red_score,blue_score' + LineEnding + '%d,%d', [Stat.TeamStat[TEAM_RED].Goals, Stat.TeamStat[TEAM_BLUE].Goals]))
1022 else if Stat.GameMode in [GM_COOP, GM_SINGLE] then
1023 WriteLn(s,
1024 Format('mon_killed,mon_total,secrets_found,secrets_total' + LineEnding + '%d,%d,%d,%d',[gCoopMonstersKilled, gTotalMonsters, gCoopSecretsFound, gSecretsCount]));
1025 // lines 3-...: team, player name, frags, deaths
1026 WriteLn(s, 'team,name,frags,deaths');
1027 for I := Low(Stat.PlayerStat) to High(Stat.PlayerStat) do
1028 with Stat.PlayerStat[I] do
1029 WriteLn(s, Format('%d,%s,%d,%d', [Team, dquoteStr(Name), Frags, Deaths]));
1030 except
1031 g_Console_Add(Format(_lc[I_CONSOLE_ERROR_WRITE], [fname]));
1032 end;
1033 except
1034 g_Console_Add('could not create gamestats file "' + fname + '"');
1035 end;
1036 CloseFile(s);
1037 end;
1039 function g_Game_ModeToText(Mode: Byte): string;
1040 begin
1041 Result := '';
1042 case Mode of
1043 GM_DM: Result := _lc[I_MENU_GAME_TYPE_DM];
1044 GM_TDM: Result := _lc[I_MENU_GAME_TYPE_TDM];
1045 GM_CTF: Result := _lc[I_MENU_GAME_TYPE_CTF];
1046 GM_COOP: Result := _lc[I_MENU_GAME_TYPE_COOP];
1047 GM_SINGLE: Result := _lc[I_MENU_GAME_TYPE_SINGLE];
1048 end;
1049 end;
1051 function g_Game_TextToMode(Mode: string): Byte;
1052 begin
1053 Result := GM_NONE;
1054 Mode := UpperCase(Mode);
1055 if Mode = _lc[I_MENU_GAME_TYPE_DM] then
1056 begin
1057 Result := GM_DM;
1058 Exit;
1059 end;
1060 if Mode = _lc[I_MENU_GAME_TYPE_TDM] then
1061 begin
1062 Result := GM_TDM;
1063 Exit;
1064 end;
1065 if Mode = _lc[I_MENU_GAME_TYPE_CTF] then
1066 begin
1067 Result := GM_CTF;
1068 Exit;
1069 end;
1070 if Mode = _lc[I_MENU_GAME_TYPE_COOP] then
1071 begin
1072 Result := GM_COOP;
1073 Exit;
1074 end;
1075 if Mode = _lc[I_MENU_GAME_TYPE_SINGLE] then
1076 begin
1077 Result := GM_SINGLE;
1078 Exit;
1079 end;
1080 end;
1082 function g_Game_IsNet(): Boolean;
1083 begin
1084 Result := (gGameSettings.GameType in [GT_SERVER, GT_CLIENT]);
1085 end;
1087 function g_Game_IsServer(): Boolean;
1088 begin
1089 Result := (gGameSettings.GameType in [GT_SINGLE, GT_CUSTOM, GT_SERVER]);
1090 end;
1092 function g_Game_IsClient(): Boolean;
1093 begin
1094 Result := (gGameSettings.GameType = GT_CLIENT);
1095 end;
1097 function g_Game_GetMegaWADInfo(WAD: String): TMegaWADInfo;
1098 var
1099 w: TWADFile;
1100 cfg: TConfig;
1101 p: Pointer;
1102 len: Integer;
1103 begin
1104 Result.name := ExtractFileName(WAD);
1105 Result.description := '';
1106 Result.author := '';
1108 w := TWADFile.Create();
1109 w.ReadFile(WAD);
1111 if not w.GetResource('INTERSCRIPT', p, len) then
1112 begin
1113 w.Free();
1114 Exit;
1115 end;
1117 cfg := TConfig.CreateMem(p, len);
1118 Result.name := cfg.ReadStr('megawad', 'name', ExtractFileName(WAD));
1119 Result.description := cfg.ReadStr('megawad', 'description', '');
1120 Result.author := cfg.ReadStr('megawad', 'author', '');
1121 Result.pic := cfg.ReadStr('megawad', 'pic', '');
1122 cfg.Free();
1124 FreeMem(p);
1125 end;
1127 procedure g_Game_FreeWAD;
1128 begin
1129 EndPicPath := '';
1130 g_Sound_Delete('MUSIC_endmus');
1131 ZeroMemory(@MegaWAD, SizeOf(MegaWAD));
1132 gGameSettings.WAD := '';
1133 end;
1135 procedure g_Game_LoadWAD(WAD: string);
1136 var
1137 w: TWADFile;
1138 cfg: TConfig;
1139 p: Pointer;
1140 len: Integer;
1141 s: AnsiString;
1142 begin
1143 g_Game_FreeWAD();
1144 gGameSettings.WAD := WAD;
1145 if not (gGameSettings.GameMode in [GM_COOP, GM_SINGLE]) then
1146 Exit;
1148 MegaWAD.info := g_Game_GetMegaWADInfo(WAD);
1150 w := TWADFile.Create();
1151 w.ReadFile(WAD);
1153 if not w.GetResource('INTERSCRIPT', p, len) then
1154 begin
1155 w.Free();
1156 Exit;
1157 end;
1159 cfg := TConfig.CreateMem(p, len);
1161 EndPicPath := '';
1162 MegaWAD.endpic := cfg.ReadStr('megawad', 'endpic', '');
1163 if MegaWAD.endpic <> '' then
1164 EndPicPath := e_GetResourcePath(WadDirs, MegaWAD.endpic, WAD);
1166 MegaWAD.endmus := cfg.ReadStr('megawad', 'endmus', 'Standart.wad:D2DMUS\КОНЕЦ');
1167 if MegaWAD.endmus <> '' then
1168 begin
1169 s := e_GetResourcePath(WadDirs, MegaWAD.endmus, WAD);
1170 g_Sound_CreateWADEx('MUSIC_endmus', s, True);
1171 end;
1173 cfg.Free();
1174 FreeMem(p);
1175 w.Free();
1176 end;
1178 {procedure start_trigger(t: string);
1179 begin
1180 end;
1182 function next_trigger(): Boolean;
1183 begin
1184 end;}
1186 procedure DisableCheats();
1187 begin
1188 MAX_RUNVEL := 8;
1189 VEL_JUMP := 10;
1190 gFly := False;
1192 if gPlayer1 <> nil then gPlayer1.GodMode := False;
1193 if gPlayer2 <> nil then gPlayer2.GodMode := False;
1194 if gPlayer1 <> nil then gPlayer1.NoTarget := False;
1195 if gPlayer2 <> nil then gPlayer2.NoTarget := False;
1197 {$IF DEFINED(D2F_DEBUG)}
1198 if gPlayer1 <> nil then gPlayer1.NoTarget := True;
1199 gAimLine := g_dbg_aimline_on;
1200 {$ENDIF}
1201 end;
1203 procedure g_Game_ExecuteEvent(Name: String);
1204 var
1205 a: Integer;
1206 begin
1207 if Name = '' then
1208 Exit;
1209 if gEvents = nil then
1210 Exit;
1211 for a := 0 to High(gEvents) do
1212 if gEvents[a].Name = Name then
1213 begin
1214 if gEvents[a].Command <> '' then
1215 g_Console_Process(gEvents[a].Command, True);
1216 break;
1217 end;
1218 end;
1220 function g_Game_DelayEvent(DEType: Byte; Time: LongWord; Num: Integer = 0; Str: String = ''): Integer;
1221 var
1222 a, n: Integer;
1223 begin
1224 n := -1;
1225 if gDelayedEvents <> nil then
1226 for a := 0 to High(gDelayedEvents) do
1227 if not gDelayedEvents[a].Pending then
1228 begin
1229 n := a;
1230 break;
1231 end;
1232 if n = -1 then
1233 begin
1234 SetLength(gDelayedEvents, Length(gDelayedEvents) + 1);
1235 n := High(gDelayedEvents);
1236 end;
1237 gDelayedEvents[n].Pending := True;
1238 gDelayedEvents[n].DEType := DEType;
1239 gDelayedEvents[n].DENum := Num;
1240 gDelayedEvents[n].DEStr := Str;
1241 if DEType = DE_GLOBEVENT then
1242 gDelayedEvents[n].Time := (GetTickCount64() {div 1000}) + Time
1243 else
1244 gDelayedEvents[n].Time := gTime + Time;
1245 Result := n;
1246 end;
1248 procedure EndGame();
1249 var
1250 a: Integer;
1251 FileName: string;
1252 t: TDateTime;
1253 begin
1254 if g_Game_IsNet and g_Game_IsServer then
1255 MH_SEND_GameEvent(NET_EV_MAPEND, Byte(gMissionFailed));
1257 // Стоп игра:
1258 gPauseMain := false;
1259 gPauseHolmes := false;
1260 gGameOn := false;
1262 g_Game_StopAllSounds(False);
1264 MessageTime := 0;
1265 MessageText := '';
1267 EndingGameCounter := 0;
1269 {$IFDEF ENABLE_MENU}
1270 g_ActiveWindow := nil;
1271 {$ENDIF}
1273 gLMSRespawn := LMS_RESPAWN_NONE;
1274 gLMSRespawnTime := 0;
1276 case gExit of
1277 EXIT_SIMPLE: // Выход через меню или конец теста
1278 begin
1279 g_Game_Free();
1280 if gMapOnce then
1281 begin // Это был тест
1282 g_Game_Quit();
1283 end
1284 else
1285 begin // Выход в главное меню
1286 {$IFDEF DISABLE_MENU}
1287 gState := STATE_MENU; // ???
1288 {$ELSE}
1289 gMusic.SetByName('MUSIC_MENU');
1290 gMusic.Play();
1291 if gState <> STATE_SLIST then
1292 begin
1293 g_GUI_ShowWindow('MainMenu');
1294 gState := STATE_MENU;
1295 end
1296 else
1297 begin
1298 // Обновляем список серверов
1299 slReturnPressed := True;
1300 if g_Net_Slist_Fetch(slCurrent) then
1301 begin
1302 if slCurrent = nil then
1303 slWaitStr := _lc[I_NET_SLIST_NOSERVERS];
1304 end
1305 else
1306 slWaitStr := _lc[I_NET_SLIST_ERROR];
1307 g_Serverlist_GenerateTable(slCurrent, slTable);
1308 end;
1309 {$ENDIF}
1310 g_Game_ExecuteEvent('ongameend');
1311 end;
1312 end;
1314 EXIT_RESTART: // Начать уровень сначала
1315 begin
1316 if not g_Game_IsClient then g_Game_Restart();
1317 end;
1319 EXIT_ENDLEVELCUSTOM: // Закончился уровень в Своей игре
1320 begin
1321 // Статистика Своей игры:
1322 FileName := g_ExtractWadName(gMapInfo.Map);
1324 CustomStat.GameTime := gTime;
1325 CustomStat.Map := ExtractFileName(FileName)+':'+g_ExtractFileName(gMapInfo.Map); //ResName;
1326 CustomStat.MapName := gMapInfo.Name;
1327 CustomStat.GameMode := gGameSettings.GameMode;
1328 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
1329 CustomStat.TeamStat := gTeamStat;
1331 CustomStat.PlayerStat := nil;
1333 // Статистика игроков:
1334 if gPlayers <> nil then
1335 begin
1336 for a := 0 to High(gPlayers) do
1337 if gPlayers[a] <> nil then
1338 begin
1339 SetLength(CustomStat.PlayerStat, Length(CustomStat.PlayerStat)+1);
1340 with CustomStat.PlayerStat[High(CustomStat.PlayerStat)] do
1341 begin
1342 Num := a;
1343 Name := gPlayers[a].Name;
1344 Frags := gPlayers[a].Frags;
1345 Deaths := gPlayers[a].Death;
1346 Kills := gPlayers[a].Kills;
1347 Team := gPlayers[a].Team;
1348 Color := gPlayers[a].Model.Color;
1349 Spectator := gPlayers[a].FSpectator;
1350 end;
1351 end;
1353 SortGameStat(CustomStat.PlayerStat);
1355 if (gSaveStats or gScreenshotStats) and (Length(CustomStat.PlayerStat) > 1) then
1356 begin
1357 t := Now;
1358 if g_Game_IsNet then StatFilename := NetServerName else StatFilename := 'local';
1359 StatDate := FormatDateTime('yymmdd_hhnnss', t);
1360 StatFilename := StatFilename + '_' + CustomStat.Map + '_' + g_Game_ModeToText(CustomStat.GameMode);
1361 StatFilename := sanitizeFilename(StatFilename) + '_' + StatDate;
1362 if gSaveStats then
1363 SaveGameStat(CustomStat, FormatDateTime('yyyy"/"mm"/"dd', t));
1364 end;
1366 StatShotDone := False;
1367 end;
1369 g_Game_ExecuteEvent('onmapend');
1370 if not g_Game_IsClient then g_Player_ResetReady;
1371 gInterReadyCount := 0;
1373 // Затухающий экран:
1374 EndingGameCounter := 255;
1375 gState := STATE_FOLD;
1376 gInterTime := 0;
1377 if gDefInterTime < 0 then
1378 gInterEndTime := IfThen((gGameSettings.GameType = GT_SERVER) and (gPlayer1 = nil), 15000, 25000)
1379 else
1380 gInterEndTime := gDefInterTime * 1000;
1381 end;
1383 EXIT_ENDLEVELSINGLE: // Закончился уровень в Одиночной игре
1384 begin
1385 // Статистика Одиночной игры:
1386 SingleStat.GameTime := gTime;
1387 SingleStat.TwoPlayers := gPlayer2 <> nil;
1388 SingleStat.TotalSecrets := gSecretsCount;
1389 // Статистика первого игрока:
1390 SingleStat.PlayerStat[0].Kills := gPlayer1.MonsterKills;
1391 SingleStat.PlayerStat[0].Secrets := gPlayer1.Secrets;
1392 // Статистика второго игрока (если есть):
1393 if SingleStat.TwoPlayers then
1394 begin
1395 SingleStat.PlayerStat[1].Kills := gPlayer2.MonsterKills;
1396 SingleStat.PlayerStat[1].Secrets := gPlayer2.Secrets;
1397 end;
1399 g_Game_ExecuteEvent('onmapend');
1401 // Есть еще карты:
1402 if gNextMap <> '' then
1403 begin
1404 gMusic.SetByName('MUSIC_INTERMUS');
1405 gMusic.Play();
1406 gState := STATE_INTERSINGLE;
1407 e_UnpressAllKeys();
1409 g_Game_ExecuteEvent('oninter');
1410 end
1411 else // Больше нет карт
1412 begin
1413 // Затухающий экран:
1414 EndingGameCounter := 255;
1415 gState := STATE_FOLD;
1416 end;
1417 end;
1418 end;
1420 // Окончание обработано:
1421 if gExit <> EXIT_QUIT then
1422 gExit := 0;
1423 end;
1425 procedure g_Game_Init();
1426 begin
1427 gExit := 0;
1428 gMapToDelete := '';
1429 gTempDelete := False;
1431 sfsGCDisable(); // temporary disable removing of temporary volumes
1433 try
1434 g_Game_ClearLoading();
1435 g_Game_SetLoadingText(Format('Doom 2D: Forever %s', [GAME_VERSION]), 0, False);
1436 g_Game_SetLoadingText('', 0, False);
1438 // g_Game_SetLoadingText(_lc[I_LOAD_MODELS], 0, False);
1440 gGameOn := false;
1441 gPauseMain := false;
1442 gPauseHolmes := false;
1443 gTime := 0;
1445 {e_MouseInfo.Accel := 1.0;}
1447 g_Game_SetLoadingText(_lc[I_LOAD_GAME_DATA], 0, False);
1448 g_Game_LoadData();
1450 g_Game_SetLoadingText(_lc[I_LOAD_MUSIC], 0, False);
1451 g_Sound_CreateWADEx('MUSIC_INTERMUS', GameWAD+':MUSIC\INTERMUS', True);
1452 g_Sound_CreateWADEx('MUSIC_MENU', GameWAD+':MUSIC\MENU', True);
1453 g_Sound_CreateWADEx('MUSIC_ROUNDMUS', GameWAD+':MUSIC\ROUNDMUS', True, True);
1454 g_Sound_CreateWADEx('MUSIC_STDENDMUS', GameWAD+':MUSIC\ENDMUS', True);
1456 gMusic := TMusic.Create();
1457 gMusic.SetByName('MUSIC_MENU');
1458 gMusic.Play();
1460 gGameSettings.WarmupTime := 30;
1462 gState := STATE_MENU;
1464 SetLength(gEvents, 6);
1465 gEvents[0].Name := 'ongamestart';
1466 gEvents[1].Name := 'ongameend';
1467 gEvents[2].Name := 'onmapstart';
1468 gEvents[3].Name := 'onmapend';
1469 gEvents[4].Name := 'oninter';
1470 gEvents[5].Name := 'onwadend';
1471 finally
1472 sfsGCEnable(); // enable releasing unused volumes
1473 end;
1474 end;
1476 procedure g_Game_Free(freeTextures: Boolean=true);
1477 begin
1478 if NetMode = NET_CLIENT then g_Net_Disconnect();
1479 if NetMode = NET_SERVER then g_Net_Host_Die();
1481 g_Map_Free(freeTextures);
1482 g_Player_Free();
1484 {$IFDEF ENABLE_GIBS}
1485 g_Gibs_RemoveAll;
1486 {$ENDIF}
1487 {$IFDEF ENALBE_SHELLS}
1488 g_Shells_RemoveAll;
1489 {$ENDIF}
1490 {$IFDEF ENABLE_CORPSES}
1491 g_Corpses_RemoveAll;
1492 {$ENDIF}
1494 gGameSettings.GameType := GT_NONE;
1495 if gGameSettings.GameMode = GM_SINGLE then
1496 gGameSettings.GameMode := GM_DM;
1497 gSwitchGameMode := gGameSettings.GameMode;
1499 gChatShow := False;
1500 gExitByTrigger := False;
1501 end;
1503 function IsActivePlayer(p: TPlayer): Boolean;
1504 begin
1505 Result := False;
1506 if p = nil then
1507 Exit;
1508 Result := (not p.FDummy) and (not p.FSpectator);
1509 end;
1511 function GetActivePlayerID_Next(Skip: Integer = -1): Integer;
1512 var
1513 a, idx: Integer;
1514 ids: Array of Word;
1515 begin
1516 Result := -1;
1517 if gPlayers = nil then
1518 Exit;
1519 SetLength(ids, 0);
1520 idx := -1;
1521 for a := Low(gPlayers) to High(gPlayers) do
1522 if IsActivePlayer(gPlayers[a]) then
1523 begin
1524 SetLength(ids, Length(ids) + 1);
1525 ids[High(ids)] := gPlayers[a].UID;
1526 if gPlayers[a].UID = Skip then
1527 idx := High(ids);
1528 end;
1529 if Length(ids) = 0 then
1530 Exit;
1531 if idx = -1 then
1532 Result := ids[0]
1533 else
1534 Result := ids[(idx + 1) mod Length(ids)];
1535 end;
1537 function GetActivePlayerID_Prev(Skip: Integer = -1): Integer;
1538 var
1539 a, idx: Integer;
1540 ids: Array of Word;
1541 begin
1542 Result := -1;
1543 if gPlayers = nil then
1544 Exit;
1545 SetLength(ids, 0);
1546 idx := -1;
1547 for a := Low(gPlayers) to High(gPlayers) do
1548 if IsActivePlayer(gPlayers[a]) then
1549 begin
1550 SetLength(ids, Length(ids) + 1);
1551 ids[High(ids)] := gPlayers[a].UID;
1552 if gPlayers[a].UID = Skip then
1553 idx := High(ids);
1554 end;
1555 if Length(ids) = 0 then
1556 Exit;
1557 if idx = -1 then
1558 Result := ids[Length(ids) - 1]
1559 else
1560 Result := ids[(Length(ids) - 1 + idx) mod Length(ids)];
1561 end;
1563 function GetActivePlayerID_Random(Skip: Integer = -1): Integer;
1564 var
1565 a, idx: Integer;
1566 ids: Array of Word;
1567 begin
1568 Result := -1;
1569 if gPlayers = nil then
1570 Exit;
1571 SetLength(ids, 0);
1572 idx := -1;
1573 for a := Low(gPlayers) to High(gPlayers) do
1574 if IsActivePlayer(gPlayers[a]) then
1575 begin
1576 SetLength(ids, Length(ids) + 1);
1577 ids[High(ids)] := gPlayers[a].UID;
1578 if gPlayers[a].UID = Skip then
1579 idx := High(ids);
1580 end;
1581 if Length(ids) = 0 then
1582 Exit;
1583 if Length(ids) = 1 then
1584 begin
1585 Result := ids[0];
1586 Exit;
1587 end;
1588 Result := ids[Random(Length(ids))];
1589 a := 10;
1590 while (idx <> -1) and (Result = Skip) and (a > 0) do
1591 begin
1592 Result := ids[Random(Length(ids))];
1593 Dec(a);
1594 end;
1595 end;
1597 function GetRandomSpectMode(Current: Byte): Byte;
1598 label
1599 retry;
1600 begin
1601 Result := Current;
1602 retry:
1603 case Random(7) of
1604 0: Result := SPECT_STATS;
1605 1: Result := SPECT_MAPVIEW;
1606 2: Result := SPECT_MAPVIEW;
1607 3: Result := SPECT_PLAYERS;
1608 4: Result := SPECT_PLAYERS;
1609 5: Result := SPECT_PLAYERS;
1610 6: Result := SPECT_PLAYERS;
1611 end;
1612 if (Current in [SPECT_STATS, SPECT_MAPVIEW]) and (Current = Result) then
1613 goto retry;
1614 end;
1616 procedure ProcessPlayerControls (plr: TPlayer; p: Integer; var MoveButton: Byte);
1617 var
1618 time: Word;
1619 strafeDir: Byte;
1620 i: Integer;
1621 begin
1622 if (plr = nil) then exit;
1623 if (p = 2) then time := 1000 else time := 1;
1624 strafeDir := MoveButton shr 4;
1625 MoveButton := MoveButton and $0F;
1627 if gPlayerAction[p, ACTION_MOVELEFT] and (not gPlayerAction[p, ACTION_MOVERIGHT]) then
1628 MoveButton := 1 // Нажата только "Влево"
1629 else if (not gPlayerAction[p, ACTION_MOVELEFT]) and gPlayerAction[p, ACTION_MOVERIGHT] then
1630 MoveButton := 2 // Нажата только "Вправо"
1631 else if (not gPlayerAction[p, ACTION_MOVELEFT]) and (not gPlayerAction[p, ACTION_MOVERIGHT]) then
1632 MoveButton := 0; // Не нажаты ни "Влево", ни "Вправо"
1634 // Сейчас или раньше были нажаты "Влево"/"Вправо" => передаем игроку:
1635 if MoveButton = 1 then
1636 plr.PressKey(KEY_LEFT, time)
1637 else if MoveButton = 2 then
1638 plr.PressKey(KEY_RIGHT, time);
1640 // if we have "strafe" key, turn off old strafe mechanics
1641 if gPlayerAction[p, ACTION_STRAFE] then
1642 begin
1643 // new strafe mechanics
1644 if (strafeDir = 0) then
1645 strafeDir := MoveButton; // start strafing
1646 // now set direction according to strafe (reversed)
1647 if (strafeDir = 2) then
1648 plr.SetDirection(TDirection.D_LEFT)
1649 else if (strafeDir = 1) then
1650 plr.SetDirection(TDirection.D_RIGHT)
1651 end
1652 else
1653 begin
1654 strafeDir := 0; // not strafing anymore
1655 // Раньше была нажата "Вправо", а сейчас "Влево" => бежим вправо, смотрим влево:
1656 if (MoveButton = 2) and gPlayerAction[p, ACTION_MOVELEFT] then
1657 plr.SetDirection(TDirection.D_LEFT)
1658 // Раньше была нажата "Влево", а сейчас "Вправо" => бежим влево, смотрим вправо:
1659 else if (MoveButton = 1) and gPlayerAction[p, ACTION_MOVERIGHT] then
1660 plr.SetDirection(TDirection.D_RIGHT)
1661 // Что-то было нажато и не изменилось => куда бежим, туда и смотрим:
1662 else if MoveButton <> 0 then
1663 plr.SetDirection(TDirection(MoveButton-1))
1664 end;
1666 // fix movebutton state
1667 MoveButton := MoveButton or (strafeDir shl 4);
1669 // Остальные клавиши:
1670 if gPlayerAction[p, ACTION_JUMP] then plr.PressKey(KEY_JUMP, time);
1671 if gPlayerAction[p, ACTION_LOOKUP] then plr.PressKey(KEY_UP, time);
1672 if gPlayerAction[p, ACTION_LOOKDOWN] then plr.PressKey(KEY_DOWN, time);
1673 if gPlayerAction[p, ACTION_ATTACK] then plr.PressKey(KEY_FIRE);
1674 if gPlayerAction[p, ACTION_WEAPNEXT] then plr.PressKey(KEY_NEXTWEAPON);
1675 if gPlayerAction[p, ACTION_WEAPPREV] then plr.PressKey(KEY_PREVWEAPON);
1676 if gPlayerAction[p, ACTION_ACTIVATE] then plr.PressKey(KEY_OPEN);
1678 gPlayerAction[p, ACTION_WEAPNEXT] := False; // HACK, remove after readyweaon&pendinweapon implementation
1679 gPlayerAction[p, ACTION_WEAPPREV] := False; // HACK, remove after readyweaon&pendinweapon implementation
1681 for i := WP_FIRST to WP_LAST do
1682 begin
1683 if gSelectWeapon[p, i] then
1684 begin
1685 plr.QueueWeaponSwitch(i); // all choices are passed there, and god will take the best
1686 gSelectWeapon[p, i] := False
1687 end
1688 end;
1690 {$IFDEF ENABLE_MENU}
1691 // HACK: add dynlight here
1692 if gwin_k8_enable_light_experiments then
1693 begin
1694 if e_KeyPressed(IK_F8) and gGameOn and (not gConsoleShow) and (g_ActiveWindow = nil) then
1695 begin
1696 g_playerLight := true;
1697 end;
1698 if e_KeyPressed(IK_F9) and gGameOn and (not gConsoleShow) and (g_ActiveWindow = nil) then
1699 begin
1700 g_playerLight := false;
1701 end;
1702 end;
1704 if gwin_has_stencil and g_playerLight then g_AddDynLight(plr.GameX+32, plr.GameY+40, 128, 1, 1, 0, 0.6);
1705 {$ENDIF}
1706 end;
1708 // HACK: don't have a "key was pressed" function
1709 procedure InterReady();
1710 begin
1711 if InterReadyTime > gTime then Exit;
1712 InterReadyTime := gTime + 3000;
1713 MC_SEND_CheatRequest(NET_CHEAT_READY);
1714 end;
1716 procedure g_Game_PreUpdate();
1717 begin
1718 // these are in separate PreUpdate functions because they can interact during Update()
1719 // and are synced over the net
1720 // we don't care that much about corpses and gibs
1721 g_Player_PreUpdate();
1722 g_Monsters_PreUpdate();
1723 g_Items_PreUpdate();
1724 g_Weapon_PreUpdate();
1725 end;
1727 procedure g_Game_Update();
1728 var
1729 {$IFDEF ENABLE_MENU}
1730 Msg: g_gui.TMessage;
1731 w: Word;
1732 {$ENDIF}
1733 Time: Int64;
1734 a: Byte;
1735 i, b: Integer;
1737 function sendMonsPos (mon: TMonster): Boolean;
1738 begin
1739 result := false; // don't stop
1740 // this will also reset "need-send" flag
1741 if mon.gncNeedSend then
1742 begin
1743 MH_SEND_MonsterPos(mon.UID);
1744 end
1745 else if (mon.MonsterType = MONSTER_BARREL) then
1746 begin
1747 if (mon.GameVelX <> 0) or (mon.GameVelY <> 0) then MH_SEND_MonsterPos(mon.UID);
1748 end
1749 else if (mon.MonsterState <> MONSTATE_SLEEP) then
1750 begin
1751 if (mon.MonsterState <> MONSTATE_DEAD) or (mon.GameVelX <> 0) or (mon.GameVelY <> 0) then MH_SEND_MonsterPos(mon.UID);
1752 end;
1753 end;
1755 function sendMonsPosUnexpected (mon: TMonster): Boolean;
1756 begin
1757 result := false; // don't stop
1758 // this will also reset "need-send" flag
1759 if mon.gncNeedSend then MH_SEND_MonsterPos(mon.UID);
1760 end;
1762 var
1763 reliableUpdate: Boolean;
1764 begin
1765 g_ResetDynlights();
1766 framePool.reset();
1768 // Пора выключать игру:
1769 if gExit = EXIT_QUIT then
1770 Exit;
1771 // Игра закончилась - обрабатываем:
1772 if gExit <> 0 then
1773 begin
1774 EndGame();
1775 if gExit = EXIT_QUIT then
1776 Exit;
1777 end;
1779 // Читаем клавиатуру и джойстик, если окно активно
1780 // no need to, as we'll do it in event handler
1782 // Обновляем консоль (движение и сообщения):
1783 g_Console_Update();
1785 if (NetMode = NET_NONE) and (g_Game_IsNet) and (gGameOn or (gState in [STATE_FOLD, STATE_INTERCUSTOM])) then
1786 begin
1787 gExit := EXIT_SIMPLE;
1788 EndGame();
1789 Exit;
1790 end;
1792 // process master server communications
1793 g_Net_Slist_Pulse();
1795 case gState of
1796 STATE_INTERSINGLE, // Статистка после прохождения уровня в Одиночной игре
1797 STATE_INTERCUSTOM, // Статистка после прохождения уровня в Своей игре
1798 STATE_INTERTEXT, // Текст между уровнями
1799 STATE_INTERPIC: // Картинка между уровнями
1800 begin
1801 if g_Game_IsNet and g_Game_IsServer then
1802 begin
1803 gInterTime := gInterTime + GAME_TICK;
1804 a := Min((gInterEndTime - gInterTime) div 1000 + 1, 255);
1805 if a <> gServInterTime then
1806 begin
1807 gServInterTime := a;
1808 MH_SEND_TimeSync(gServInterTime);
1809 end;
1810 end;
1812 if (not g_Game_IsClient) and
1816 e_KeyPressed(IK_RETURN) or e_KeyPressed(IK_KPRETURN) or e_KeyPressed(IK_SPACE) or
1817 e_KeyPressed(VK_FIRE) or e_KeyPressed(VK_OPEN) or
1818 e_KeyPressed(JOY0_ATTACK) or e_KeyPressed(JOY1_ATTACK) or
1819 e_KeyPressed(JOY2_ATTACK) or e_KeyPressed(JOY3_ATTACK)
1821 and (not gJustChatted) and (not gConsoleShow) and (not gChatShow)
1822 {$IFDEF ENABLE_MENU}
1823 and (g_ActiveWindow = nil)
1824 {$ENDIF}
1826 or (g_Game_IsNet and ((gInterTime > gInterEndTime) or ((gInterReadyCount >= NetClientCount) and (NetClientCount > 0))))
1828 then
1829 begin // Нажали <Enter>/<Пробел> или прошло достаточно времени:
1830 g_Game_StopAllSounds(True);
1832 if gMapOnce then // Это был тест
1833 gExit := EXIT_SIMPLE
1834 else
1835 if gNextMap <> '' then // Переходим на следующую карту
1836 g_Game_ChangeMap(gNextMap)
1837 else // Следующей карты нет
1838 begin
1839 if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER] then
1840 begin
1841 // Выход в главное меню:
1842 g_Game_Free;
1843 {$IFDEF ENABLE_MENU}
1844 g_GUI_ShowWindow('MainMenu');
1845 gMusic.SetByName('MUSIC_MENU');
1846 gMusic.Play();
1847 {$ENDIF}
1848 gState := STATE_MENU;
1849 end else
1850 begin
1851 // Финальная картинка:
1852 g_Game_ExecuteEvent('onwadend');
1853 g_Game_Free();
1854 if not gMusic.SetByName('MUSIC_endmus') then
1855 gMusic.SetByName('MUSIC_STDENDMUS');
1856 gMusic.Play();
1857 gState := STATE_ENDPIC;
1858 end;
1859 g_Game_ExecuteEvent('ongameend');
1860 end;
1862 Exit;
1863 end
1864 else if g_Game_IsClient and
1867 e_KeyPressed(IK_RETURN) or e_KeyPressed(IK_KPRETURN) or e_KeyPressed(IK_SPACE) or
1868 e_KeyPressed(VK_FIRE) or e_KeyPressed(VK_OPEN) or
1869 e_KeyPressed(JOY0_ATTACK) or e_KeyPressed(JOY1_ATTACK) or
1870 e_KeyPressed(JOY2_ATTACK) or e_KeyPressed(JOY3_ATTACK)
1872 and (not gJustChatted) and (not gConsoleShow) and (not gChatShow)
1873 {$IFDEF ENABLE_MENU}
1874 and (g_ActiveWindow = nil)
1875 {$ENDIF}
1877 then
1878 begin
1879 // ready / unready
1880 InterReady();
1881 end;
1883 if gState = STATE_INTERTEXT then
1884 if InterText.counter > 0 then
1885 InterText.counter := InterText.counter - 1;
1886 end;
1888 STATE_FOLD: // Затухание экрана
1889 begin
1890 if EndingGameCounter = 0 then
1891 begin
1892 // Закончился уровень в Своей игре:
1893 if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT] then
1894 begin
1895 InterReadyTime := -1;
1896 if gLastMap and (gGameSettings.GameMode = GM_COOP) then
1897 begin
1898 g_Game_ExecuteEvent('onwadend');
1899 if not gMusic.SetByName('MUSIC_endmus') then
1900 gMusic.SetByName('MUSIC_STDENDMUS');
1901 end
1902 else
1903 gMusic.SetByName('MUSIC_ROUNDMUS');
1905 gMusic.Play();
1906 gState := STATE_INTERCUSTOM;
1907 e_UnpressAllKeys();
1908 end
1909 else // Закончилась последняя карта в Одиночной игре
1910 begin
1911 gMusic.SetByName('MUSIC_INTERMUS');
1912 gMusic.Play();
1913 gState := STATE_INTERSINGLE;
1914 e_UnpressAllKeys();
1915 end;
1916 g_Game_ExecuteEvent('oninter');
1917 end
1918 else
1919 DecMin(EndingGameCounter, 6, 0);
1920 end;
1922 STATE_ENDPIC: // Картинка окончания мегаВада
1923 begin
1924 if gMapOnce then // Это был тест
1925 begin
1926 gExit := EXIT_SIMPLE;
1927 Exit;
1928 end;
1929 end;
1931 STATE_SLIST:
1932 g_Serverlist_Control(slCurrent, slTable);
1933 end;
1935 // Статистика по Tab:
1936 if gGameOn then
1937 IsDrawStat := (not gConsoleShow) and (not gChatShow) and (gGameSettings.GameType <> GT_SINGLE) and g_Console_Action(ACTION_SCORES);
1939 // Игра идет:
1940 if gGameOn and not gPause and (gState <> STATE_FOLD) then
1941 begin
1942 // Время += 28 миллисекунд:
1943 gTime := gTime + GAME_TICK;
1945 // Сообщение посередине экрана:
1946 if MessageTime = 0 then
1947 MessageText := '';
1948 if MessageTime > 0 then
1949 MessageTime := MessageTime - 1;
1951 if (g_Game_IsServer) then
1952 begin
1953 // Был задан лимит времени:
1954 if (gGameSettings.TimeLimit > 0) then
1955 if (gTime - gGameStartTime) div 1000 >= gGameSettings.TimeLimit then
1956 begin // Он прошел => конец уровня
1957 g_Game_NextLevel();
1958 Exit;
1959 end;
1961 // Надо респавнить игроков в LMS:
1962 if (gLMSRespawn > LMS_RESPAWN_NONE) and (gLMSRespawnTime < gTime) then
1963 g_Game_RestartRound(gLMSSoftSpawn);
1965 // Проверим результат голосования, если время прошло
1966 if gVoteInProgress and (gVoteTimer < gTime) then
1967 g_Game_CheckVote
1968 else if gVotePassed and (gVoteCmdTimer < gTime) then
1969 begin
1970 g_Console_Process(gVoteCommand);
1971 gVoteCommand := '';
1972 gVotePassed := False;
1973 end;
1975 // Замеряем время захвата флагов
1976 if gFlags[FLAG_RED].State = FLAG_STATE_CAPTURED then
1977 gFlags[FLAG_RED].CaptureTime := gFlags[FLAG_RED].CaptureTime + GAME_TICK;
1978 if gFlags[FLAG_BLUE].State = FLAG_STATE_CAPTURED then
1979 gFlags[FLAG_BLUE].CaptureTime := gFlags[FLAG_BLUE].CaptureTime + GAME_TICK;
1981 // Был задан лимит побед:
1982 if (gGameSettings.GoalLimit > 0) then
1983 begin
1984 b := 0;
1986 if gGameSettings.GameMode = GM_DM then
1987 begin // В DM ищем игрока с max фрагами
1988 for i := 0 to High(gPlayers) do
1989 if gPlayers[i] <> nil then
1990 if gPlayers[i].Frags > b then
1991 b := gPlayers[i].Frags;
1992 end
1993 else
1994 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
1995 begin // В CTF/TDM выбираем команду с наибольшим счетом
1996 b := Max(gTeamStat[TEAM_RED].Goals, gTeamStat[TEAM_BLUE].Goals);
1997 end;
1999 // Лимит побед набран => конец уровня:
2000 if b >= gGameSettings.GoalLimit then
2001 begin
2002 g_Game_NextLevel();
2003 Exit;
2004 end;
2005 end;
2007 // Обрабатываем клавиши игроков:
2008 if gPlayer1 <> nil then gPlayer1.ReleaseKeys();
2009 if gPlayer2 <> nil then gPlayer2.ReleaseKeys();
2010 {$IFDEF DISABLE_MENU}
2011 if (not gConsoleShow) and (not gChatShow) then
2012 {$ELSE}
2013 if (not gConsoleShow) and (not gChatShow) and (g_ActiveWindow = nil) then
2014 {$ENDIF}
2015 begin
2016 ProcessPlayerControls(gPlayer1, 0, P1MoveButton);
2017 ProcessPlayerControls(gPlayer2, 1, P2MoveButton);
2018 end // if not console
2019 else
2020 begin
2021 if g_Game_IsNet and (gPlayer1 <> nil) then gPlayer1.PressKey(KEY_CHAT, 10000);
2022 end;
2023 // process weapon switch queue
2024 end; // if server
2026 // Наблюдатель
2027 if (gPlayer1 = nil) and (gPlayer2 = nil)
2028 and (not gConsoleShow) and (not gChatShow)
2029 {$IFDEF ENABLE_MENU}
2030 and (g_ActiveWindow = nil)
2031 {$ENDIF}
2032 then
2033 begin
2034 if not gSpectKeyPress then
2035 begin
2036 if gPlayerAction[0, ACTION_JUMP] and (not gSpectAuto) then
2037 begin
2038 // switch spect mode
2039 case gSpectMode of
2040 SPECT_NONE: ; // not spectator
2041 SPECT_STATS,
2042 SPECT_MAPVIEW: Inc(gSpectMode);
2043 SPECT_PLAYERS: gSpectMode := SPECT_STATS; // reset to 1
2044 end;
2045 gSpectKeyPress := True;
2046 end;
2047 if (gSpectMode = SPECT_MAPVIEW)
2048 and (not gSpectAuto) then
2049 begin
2050 if gPlayerAction[0, ACTION_MOVELEFT] then
2051 gSpectX := Max(gSpectX - gSpectStep, 0);
2052 if gPlayerAction[0, ACTION_MOVERIGHT] then
2053 gSpectX := Min(gSpectX + gSpectStep, gMapInfo.Width - gScreenWidth);
2054 if gPlayerAction[0, ACTION_LOOKUP] then
2055 gSpectY := Max(gSpectY - gSpectStep, 0);
2056 if gPlayerAction[0, ACTION_LOOKDOWN] then
2057 gSpectY := Min(gSpectY + gSpectStep, gMapInfo.Height - gScreenHeight);
2058 if gPlayerAction[0, ACTION_WEAPPREV] then
2059 begin
2060 // decrease step
2061 if gSpectStep > 4 then gSpectStep := gSpectStep shr 1;
2062 gSpectKeyPress := True;
2063 end;
2064 if gPlayerAction[0, ACTION_WEAPNEXT] then
2065 begin
2066 // increase step
2067 if gSpectStep < 64 then gSpectStep := gSpectStep shl 1;
2068 gSpectKeyPress := True;
2069 end;
2070 end;
2071 if (gSpectMode = SPECT_PLAYERS)
2072 and (not gSpectAuto) then
2073 begin
2074 if gPlayerAction[0, ACTION_LOOKUP] then
2075 begin
2076 // add second view
2077 gSpectViewTwo := True;
2078 gSpectKeyPress := True;
2079 end;
2080 if gPlayerAction[0, ACTION_LOOKDOWN] then
2081 begin
2082 // remove second view
2083 gSpectViewTwo := False;
2084 gSpectKeyPress := True;
2085 end;
2086 if gPlayerAction[0, ACTION_MOVELEFT] then
2087 begin
2088 // prev player (view 1)
2089 gSpectPID1 := GetActivePlayerID_Prev(gSpectPID1);
2090 gSpectKeyPress := True;
2091 end;
2092 if gPlayerAction[0, ACTION_MOVERIGHT] then
2093 begin
2094 // next player (view 1)
2095 gSpectPID1 := GetActivePlayerID_Next(gSpectPID1);
2096 gSpectKeyPress := True;
2097 end;
2098 if gPlayerAction[0, ACTION_WEAPPREV] then
2099 begin
2100 // prev player (view 2)
2101 gSpectPID2 := GetActivePlayerID_Prev(gSpectPID2);
2102 gSpectKeyPress := True;
2103 end;
2104 if gPlayerAction[0, ACTION_WEAPNEXT] then
2105 begin
2106 // next player (view 2)
2107 gSpectPID2 := GetActivePlayerID_Next(gSpectPID2);
2108 gSpectKeyPress := True;
2109 end;
2110 end;
2111 if gPlayerAction[0, ACTION_ATTACK] then
2112 begin
2113 if (gSpectMode = SPECT_STATS) and (not gSpectAuto) then
2114 begin
2115 gSpectAuto := True;
2116 gSpectAutoNext := 0;
2117 gSpectViewTwo := False;
2118 gSpectKeyPress := True;
2119 end
2120 else
2121 if gSpectAuto then
2122 begin
2123 gSpectMode := SPECT_STATS;
2124 gSpectAuto := False;
2125 gSpectKeyPress := True;
2126 end;
2127 end;
2128 end
2129 else
2130 if (not gPlayerAction[0, ACTION_JUMP]) and
2131 (not gPlayerAction[0, ACTION_ATTACK]) and
2132 (not gPlayerAction[0, ACTION_MOVELEFT]) and
2133 (not gPlayerAction[0, ACTION_MOVERIGHT]) and
2134 (not gPlayerAction[0, ACTION_LOOKUP]) and
2135 (not gPlayerAction[0, ACTION_LOOKDOWN]) and
2136 (not gPlayerAction[0, ACTION_WEAPPREV]) and
2137 (not gPlayerAction[0, ACTION_WEAPNEXT]) then
2138 gSpectKeyPress := False;
2140 if gSpectAuto then
2141 begin
2142 if gSpectMode = SPECT_MAPVIEW then
2143 begin
2144 i := Min(Max(gSpectX + gSpectAutoStepX, 0), gMapInfo.Width - gScreenWidth);
2145 if i = gSpectX then
2146 gSpectAutoNext := gTime
2147 else
2148 gSpectX := i;
2149 i := Min(Max(gSpectY + gSpectAutoStepY, 0), gMapInfo.Height - gScreenHeight);
2150 if i = gSpectY then
2151 gSpectAutoNext := gTime
2152 else
2153 gSpectY := i;
2154 end;
2155 if gSpectAutoNext <= gTime then
2156 begin
2157 if gSpectAutoNext > 0 then
2158 begin
2159 gSpectMode := GetRandomSpectMode(gSpectMode);
2160 case gSpectMode of
2161 SPECT_MAPVIEW:
2162 begin
2163 gSpectX := Random(gMapInfo.Width - gScreenWidth);
2164 gSpectY := Random(gMapInfo.Height - gScreenHeight);
2165 gSpectAutoStepX := Random(9) - 4;
2166 gSpectAutoStepY := Random(9) - 4;
2167 if ((gSpectX < 800) and (gSpectAutoStepX < 0)) or
2168 ((gSpectX > gMapInfo.Width - gScreenWidth - 800) and (gSpectAutoStepX > 0)) then
2169 gSpectAutoStepX := gSpectAutoStepX * -1;
2170 if ((gSpectY < 800) and (gSpectAutoStepY < 0)) or
2171 ((gSpectY > gMapInfo.Height - gScreenHeight - 800) and (gSpectAutoStepY > 0)) then
2172 gSpectAutoStepY := gSpectAutoStepY * -1;
2173 end;
2174 SPECT_PLAYERS:
2175 begin
2176 gSpectPID1 := GetActivePlayerID_Random(gSpectPID1);
2177 end;
2178 end;
2179 end;
2180 case gSpectMode of
2181 SPECT_STATS: gSpectAutoNext := gTime + (Random(3) + 5) * 1000;
2182 SPECT_MAPVIEW: gSpectAutoNext := gTime + (Random(4) + 7) * 1000;
2183 SPECT_PLAYERS: gSpectAutoNext := gTime + (Random(7) + 8) * 1000;
2184 end;
2185 end;
2186 end;
2187 end;
2189 // Обновляем все остальное:
2190 g_Map_Update();
2191 g_Items_Update();
2192 g_Triggers_Update();
2193 g_Weapon_Update();
2194 g_Monsters_Update();
2195 {$IFDEF ENABLE_GFX}
2196 g_GFX_Update;
2197 {$ENDIF}
2198 g_Player_UpdateAll();
2199 {$IFDEF ENABLE_GIBS}
2200 g_Gibs_Update;
2201 {$ENDIF}
2202 {$IFDEF ENABLE_CORPSES}
2203 g_Corpses_Update;
2204 {$ENDIF}
2205 {$IFDEF ENABLE_SHELLS}
2206 g_Shells_Update;
2207 {$ENDIF}
2209 // server: send newly spawned monsters unconditionally
2210 if (gGameSettings.GameType = GT_SERVER) then
2211 begin
2212 if (Length(gMonstersSpawned) > 0) then
2213 begin
2214 for I := 0 to High(gMonstersSpawned) do MH_SEND_MonsterSpawn(gMonstersSpawned[I]);
2215 SetLength(gMonstersSpawned, 0);
2216 end;
2217 end;
2219 if (gSoundTriggerTime > 8) then
2220 begin
2221 g_Game_UpdateTriggerSounds();
2222 gSoundTriggerTime := 0;
2223 end
2224 else
2225 begin
2226 Inc(gSoundTriggerTime);
2227 end;
2229 if (NetMode = NET_SERVER) then
2230 begin
2231 Inc(NetTimeToUpdate);
2232 Inc(NetTimeToReliable);
2234 // send monster updates
2235 if (NetTimeToReliable >= NetRelupdRate) or (NetTimeToUpdate >= NetUpdateRate) then
2236 begin
2237 // send all monsters (periodic sync)
2238 reliableUpdate := (NetTimeToReliable >= NetRelupdRate);
2240 for I := 0 to High(gPlayers) do
2241 begin
2242 if (gPlayers[I] <> nil) then MH_SEND_PlayerPos(reliableUpdate, gPlayers[I].UID);
2243 end;
2245 g_Mons_ForEach(sendMonsPos);
2247 if reliableUpdate then
2248 begin
2249 NetTimeToReliable := 0;
2250 NetTimeToUpdate := NetUpdateRate;
2251 end
2252 else
2253 begin
2254 NetTimeToUpdate := 0;
2255 end;
2256 end
2257 else
2258 begin
2259 // send only mosters with some unexpected changes
2260 g_Mons_ForEach(sendMonsPosUnexpected);
2261 end;
2263 // send unexpected platform changes
2264 g_Map_NetSendInterestingPanels();
2266 g_Net_Slist_ServerUpdate();
2268 if NetUseMaster then
2269 begin
2270 if (gTime >= NetTimeToMaster) or g_Net_Slist_IsConnectionInProgress then
2271 begin
2272 if (not g_Net_Slist_IsConnectionActive) then g_Net_Slist_Connect(false); // non-blocking connection to the master
2273 g_Net_Slist_Update;
2274 NetTimeToMaster := gTime + NetMasterRate;
2275 end;
2276 end;
2278 end
2279 else if (NetMode = NET_CLIENT) then
2280 begin
2281 MC_SEND_PlayerPos();
2282 end;
2283 end; // if gameOn ...
2285 // Активно окно интерфейса - передаем клавиши ему:
2286 {$IFDEF ENABLE_MENU}
2287 if g_ActiveWindow <> nil then
2288 begin
2289 w := e_GetFirstKeyPressed();
2291 if (w <> IK_INVALID) then
2292 begin
2293 Msg.Msg := MESSAGE_DIKEY;
2294 Msg.wParam := w;
2295 g_ActiveWindow.OnMessage(Msg);
2296 end;
2298 // Если оно от этого не закрылось, то обновляем:
2299 if g_ActiveWindow <> nil then
2300 g_ActiveWindow.Update();
2302 // Нужно сменить разрешение:
2303 if gResolutionChange then
2304 begin
2305 {$IFNDEF HEADLESS}
2306 e_WriteLog('Changing resolution', TMsgType.Notify);
2307 r_Render_Apply;
2308 {$ENDIF}
2309 gResolutionChange := False;
2310 g_ActiveWindow := nil;
2311 end;
2313 // Нужно сменить язык:
2314 if gLanguageChange then
2315 begin
2316 //e_WriteLog('Read language file', MSG_NOTIFY);
2317 //g_Language_Load(DataDir + gLanguage + '.txt');
2318 g_Language_Set(gLanguage);
2319 g_Menu_Reset();
2320 gLanguageChange := False;
2321 end;
2322 end;
2324 // Горячая клавиша для вызова меню выхода из игры (F10):
2325 if e_KeyPressed(IK_F10) and
2326 gGameOn and
2327 (not gConsoleShow) and
2328 (g_ActiveWindow = nil) then
2329 begin
2330 KeyPress(IK_F10);
2331 end;
2332 {$ENDIF}
2334 Time := GetTickCount64() {div 1000};
2336 // Обработка отложенных событий:
2337 if gDelayedEvents <> nil then
2338 for a := 0 to High(gDelayedEvents) do
2339 if gDelayedEvents[a].Pending and
2341 ((gDelayedEvents[a].DEType = DE_GLOBEVENT) and (gDelayedEvents[a].Time <= Time)) or
2342 ((gDelayedEvents[a].DEType > DE_GLOBEVENT) and (gDelayedEvents[a].Time <= gTime))
2343 ) then
2344 begin
2345 case gDelayedEvents[a].DEType of
2346 DE_GLOBEVENT:
2347 g_Game_ExecuteEvent(gDelayedEvents[a].DEStr);
2348 DE_BFGHIT:
2349 if gGameOn then
2350 g_Game_Announce_GoodShot(gDelayedEvents[a].DENum);
2351 DE_KILLCOMBO:
2352 if gGameOn then
2353 begin
2354 g_Game_Announce_KillCombo(gDelayedEvents[a].DENum);
2355 if g_Game_IsNet and g_Game_IsServer then
2356 MH_SEND_GameEvent(NET_EV_KILLCOMBO, gDelayedEvents[a].DENum);
2357 end;
2358 DE_BODYKILL:
2359 if gGameOn then
2360 g_Game_Announce_BodyKill(gDelayedEvents[a].DENum);
2361 end;
2362 gDelayedEvents[a].Pending := False;
2363 end;
2365 // Каждую секунду обновляем счетчик обновлений:
2366 UPSCounter := UPSCounter + 1;
2367 if Time - UPSTime >= 1000 then
2368 begin
2369 UPS := UPSCounter;
2370 UPSCounter := 0;
2371 UPSTime := Time;
2372 end;
2374 if gGameOn then
2375 begin
2376 g_Weapon_AddDynLights();
2377 g_Items_AddDynLights();
2378 end;
2379 end;
2381 procedure g_Game_LoadChatSounds(Resource: string);
2382 var
2383 WAD: TWADFile;
2384 FileName, Snd: string;
2385 p: Pointer;
2386 len, cnt, tags, i, j: Integer;
2387 cfg: TConfig;
2388 begin
2389 FileName := g_ExtractWadName(Resource);
2391 WAD := TWADFile.Create();
2392 WAD.ReadFile(FileName);
2394 if not WAD.GetResource(g_ExtractFilePathName(Resource), p, len) then
2395 begin
2396 gChatSounds := nil;
2397 WAD.Free();
2398 Exit;
2399 end;
2401 cfg := TConfig.CreateMem(p, len);
2402 cnt := cfg.ReadInt('ChatSounds', 'Count', 0);
2404 SetLength(gChatSounds, cnt);
2405 for i := 0 to Length(gChatSounds) - 1 do
2406 begin
2407 gChatSounds[i].Sound := nil;
2408 Snd := Trim(cfg.ReadStr(IntToStr(i), 'Sound', ''));
2409 tags := cfg.ReadInt(IntToStr(i), 'Tags', 0);
2410 if (Snd = '') or (Tags <= 0) then
2411 continue;
2412 g_Sound_CreateWADEx('SOUND_CHAT_MACRO' + IntToStr(i), GameWAD+':'+Snd);
2413 gChatSounds[i].Sound := TPlayableSound.Create();
2414 gChatSounds[i].Sound.SetByName('SOUND_CHAT_MACRO' + IntToStr(i));
2415 SetLength(gChatSounds[i].Tags, tags);
2416 for j := 0 to tags - 1 do
2417 gChatSounds[i].Tags[j] := toLowerCase1251(cfg.ReadStr(IntToStr(i), 'Tag' + IntToStr(j), ''));
2418 gChatSounds[i].FullWord := cfg.ReadBool(IntToStr(i), 'FullWord', False);
2419 end;
2421 cfg.Free();
2422 WAD.Free();
2423 end;
2425 procedure g_Game_FreeChatSounds();
2426 var
2427 i: Integer;
2428 begin
2429 for i := 0 to Length(gChatSounds) - 1 do
2430 begin
2431 gChatSounds[i].Sound.Free();
2432 g_Sound_Delete('SOUND_CHAT_MACRO' + IntToStr(i));
2433 end;
2434 SetLength(gChatSounds, 0);
2435 gChatSounds := nil;
2436 end;
2438 procedure g_Game_LoadData();
2439 begin
2440 if DataLoaded then Exit;
2442 e_WriteLog('Loading game data...', TMsgType.Notify);
2444 g_Sound_CreateWADEx('SOUND_GAME_TELEPORT', GameWAD+':SOUNDS\TELEPORT');
2445 g_Sound_CreateWADEx('SOUND_GAME_NOTELEPORT', GameWAD+':SOUNDS\NOTELEPORT');
2446 g_Sound_CreateWADEx('SOUND_GAME_SECRET', GameWAD+':SOUNDS\SECRET');
2447 g_Sound_CreateWADEx('SOUND_GAME_DOOROPEN', GameWAD+':SOUNDS\DOOROPEN');
2448 g_Sound_CreateWADEx('SOUND_GAME_DOORCLOSE', GameWAD+':SOUNDS\DOORCLOSE');
2449 g_Sound_CreateWADEx('SOUND_GAME_BULK1', GameWAD+':SOUNDS\BULK1');
2450 g_Sound_CreateWADEx('SOUND_GAME_BULK2', GameWAD+':SOUNDS\BULK2');
2451 g_Sound_CreateWADEx('SOUND_GAME_BUBBLE1', GameWAD+':SOUNDS\BUBBLE1');
2452 g_Sound_CreateWADEx('SOUND_GAME_BUBBLE2', GameWAD+':SOUNDS\BUBBLE2');
2453 g_Sound_CreateWADEx('SOUND_GAME_BURNING', GameWAD+':SOUNDS\BURNING');
2454 g_Sound_CreateWADEx('SOUND_GAME_SWITCH1', GameWAD+':SOUNDS\SWITCH1');
2455 g_Sound_CreateWADEx('SOUND_GAME_SWITCH0', GameWAD+':SOUNDS\SWITCH0');
2456 g_Sound_CreateWADEx('SOUND_GAME_RADIO', GameWAD+':SOUNDS\RADIO');
2457 g_Sound_CreateWADEx('SOUND_ANNOUNCER_GOOD1', GameWAD+':SOUNDS\GOOD1');
2458 g_Sound_CreateWADEx('SOUND_ANNOUNCER_GOOD2', GameWAD+':SOUNDS\GOOD2');
2459 g_Sound_CreateWADEx('SOUND_ANNOUNCER_GOOD3', GameWAD+':SOUNDS\GOOD3');
2460 g_Sound_CreateWADEx('SOUND_ANNOUNCER_GOOD4', GameWAD+':SOUNDS\GOOD4');
2461 g_Sound_CreateWADEx('SOUND_ANNOUNCER_KILL2X', GameWAD+':SOUNDS\KILL2X');
2462 g_Sound_CreateWADEx('SOUND_ANNOUNCER_KILL3X', GameWAD+':SOUNDS\KILL3X');
2463 g_Sound_CreateWADEx('SOUND_ANNOUNCER_KILL4X', GameWAD+':SOUNDS\KILL4X');
2464 g_Sound_CreateWADEx('SOUND_ANNOUNCER_KILLMX', GameWAD+':SOUNDS\KILLMX');
2465 g_Sound_CreateWADEx('SOUND_ANNOUNCER_MUHAHA1', GameWAD+':SOUNDS\MUHAHA1');
2466 g_Sound_CreateWADEx('SOUND_ANNOUNCER_MUHAHA2', GameWAD+':SOUNDS\MUHAHA2');
2467 g_Sound_CreateWADEx('SOUND_ANNOUNCER_MUHAHA3', GameWAD+':SOUNDS\MUHAHA3');
2468 g_Sound_CreateWADEx('SOUND_CTF_GET1', GameWAD+':SOUNDS\GETFLAG1');
2469 g_Sound_CreateWADEx('SOUND_CTF_GET2', GameWAD+':SOUNDS\GETFLAG2');
2470 g_Sound_CreateWADEx('SOUND_CTF_LOST1', GameWAD+':SOUNDS\LOSTFLG1');
2471 g_Sound_CreateWADEx('SOUND_CTF_LOST2', GameWAD+':SOUNDS\LOSTFLG2');
2472 g_Sound_CreateWADEx('SOUND_CTF_RETURN1', GameWAD+':SOUNDS\RETFLAG1');
2473 g_Sound_CreateWADEx('SOUND_CTF_RETURN2', GameWAD+':SOUNDS\RETFLAG2');
2474 g_Sound_CreateWADEx('SOUND_CTF_CAPTURE1', GameWAD+':SOUNDS\CAPFLAG1');
2475 g_Sound_CreateWADEx('SOUND_CTF_CAPTURE2', GameWAD+':SOUNDS\CAPFLAG2');
2477 goodsnd[0] := TPlayableSound.Create();
2478 goodsnd[1] := TPlayableSound.Create();
2479 goodsnd[2] := TPlayableSound.Create();
2480 goodsnd[3] := TPlayableSound.Create();
2482 goodsnd[0].SetByName('SOUND_ANNOUNCER_GOOD1');
2483 goodsnd[1].SetByName('SOUND_ANNOUNCER_GOOD2');
2484 goodsnd[2].SetByName('SOUND_ANNOUNCER_GOOD3');
2485 goodsnd[3].SetByName('SOUND_ANNOUNCER_GOOD4');
2487 killsnd[0] := TPlayableSound.Create();
2488 killsnd[1] := TPlayableSound.Create();
2489 killsnd[2] := TPlayableSound.Create();
2490 killsnd[3] := TPlayableSound.Create();
2492 killsnd[0].SetByName('SOUND_ANNOUNCER_KILL2X');
2493 killsnd[1].SetByName('SOUND_ANNOUNCER_KILL3X');
2494 killsnd[2].SetByName('SOUND_ANNOUNCER_KILL4X');
2495 killsnd[3].SetByName('SOUND_ANNOUNCER_KILLMX');
2497 hahasnd[0] := TPlayableSound.Create();
2498 hahasnd[1] := TPlayableSound.Create();
2499 hahasnd[2] := TPlayableSound.Create();
2501 hahasnd[0].SetByName('SOUND_ANNOUNCER_MUHAHA1');
2502 hahasnd[1].SetByName('SOUND_ANNOUNCER_MUHAHA2');
2503 hahasnd[2].SetByName('SOUND_ANNOUNCER_MUHAHA3');
2505 sound_get_flag[0] := TPlayableSound.Create();
2506 sound_get_flag[1] := TPlayableSound.Create();
2507 sound_lost_flag[0] := TPlayableSound.Create();
2508 sound_lost_flag[1] := TPlayableSound.Create();
2509 sound_ret_flag[0] := TPlayableSound.Create();
2510 sound_ret_flag[1] := TPlayableSound.Create();
2511 sound_cap_flag[0] := TPlayableSound.Create();
2512 sound_cap_flag[1] := TPlayableSound.Create();
2514 sound_get_flag[0].SetByName('SOUND_CTF_GET1');
2515 sound_get_flag[1].SetByName('SOUND_CTF_GET2');
2516 sound_lost_flag[0].SetByName('SOUND_CTF_LOST1');
2517 sound_lost_flag[1].SetByName('SOUND_CTF_LOST2');
2518 sound_ret_flag[0].SetByName('SOUND_CTF_RETURN1');
2519 sound_ret_flag[1].SetByName('SOUND_CTF_RETURN2');
2520 sound_cap_flag[0].SetByName('SOUND_CTF_CAPTURE1');
2521 sound_cap_flag[1].SetByName('SOUND_CTF_CAPTURE2');
2523 g_Game_LoadChatSounds(GameWAD+':CHATSND\SNDCFG');
2525 g_Game_SetLoadingText(_lc[I_LOAD_ITEMS_DATA], 0, False);
2526 g_Items_LoadData();
2528 g_Game_SetLoadingText(_lc[I_LOAD_WEAPONS_DATA], 0, False);
2529 g_Weapon_LoadData();
2531 g_Monsters_LoadData();
2533 DataLoaded := True;
2534 end;
2536 procedure g_Game_Quit();
2537 begin
2538 g_Game_StopAllSounds(True);
2539 gMusic.Free();
2540 g_Game_FreeData();
2541 g_PlayerModel_FreeData();
2542 {$IFNDEF HEADLESS}
2543 //g_Menu_Free(); //k8: this segfaults after resolution change; who cares?
2544 {$ENDIF}
2546 if NetInitDone then g_Net_Free;
2548 // remove map after test
2549 if gMapToDelete <> '' then
2550 g_Game_DeleteTestMap();
2552 gExit := EXIT_QUIT;
2554 {$IFNDEF HEADLESS}
2555 sys_RequestQuit;
2556 {$ENDIF}
2557 end;
2559 procedure g_Game_FreeData();
2560 begin
2561 if not DataLoaded then Exit;
2563 g_Items_FreeData();
2564 g_Weapon_FreeData();
2565 g_Monsters_FreeData();
2567 e_WriteLog('Releasing game data...', TMsgType.Notify);
2569 g_Sound_Delete('SOUND_GAME_TELEPORT');
2570 g_Sound_Delete('SOUND_GAME_NOTELEPORT');
2571 g_Sound_Delete('SOUND_GAME_SECRET');
2572 g_Sound_Delete('SOUND_GAME_DOOROPEN');
2573 g_Sound_Delete('SOUND_GAME_DOORCLOSE');
2574 g_Sound_Delete('SOUND_GAME_BULK1');
2575 g_Sound_Delete('SOUND_GAME_BULK2');
2576 g_Sound_Delete('SOUND_GAME_BUBBLE1');
2577 g_Sound_Delete('SOUND_GAME_BUBBLE2');
2578 g_Sound_Delete('SOUND_GAME_BURNING');
2579 g_Sound_Delete('SOUND_GAME_SWITCH1');
2580 g_Sound_Delete('SOUND_GAME_SWITCH0');
2582 goodsnd[0].Free();
2583 goodsnd[1].Free();
2584 goodsnd[2].Free();
2585 goodsnd[3].Free();
2587 g_Sound_Delete('SOUND_ANNOUNCER_GOOD1');
2588 g_Sound_Delete('SOUND_ANNOUNCER_GOOD2');
2589 g_Sound_Delete('SOUND_ANNOUNCER_GOOD3');
2590 g_Sound_Delete('SOUND_ANNOUNCER_GOOD4');
2592 killsnd[0].Free();
2593 killsnd[1].Free();
2594 killsnd[2].Free();
2595 killsnd[3].Free();
2597 g_Sound_Delete('SOUND_ANNOUNCER_KILL2X');
2598 g_Sound_Delete('SOUND_ANNOUNCER_KILL3X');
2599 g_Sound_Delete('SOUND_ANNOUNCER_KILL4X');
2600 g_Sound_Delete('SOUND_ANNOUNCER_KILLMX');
2602 hahasnd[0].Free();
2603 hahasnd[1].Free();
2604 hahasnd[2].Free();
2606 g_Sound_Delete('SOUND_ANNOUNCER_MUHAHA1');
2607 g_Sound_Delete('SOUND_ANNOUNCER_MUHAHA2');
2608 g_Sound_Delete('SOUND_ANNOUNCER_MUHAHA3');
2610 sound_get_flag[0].Free();
2611 sound_get_flag[1].Free();
2612 sound_lost_flag[0].Free();
2613 sound_lost_flag[1].Free();
2614 sound_ret_flag[0].Free();
2615 sound_ret_flag[1].Free();
2616 sound_cap_flag[0].Free();
2617 sound_cap_flag[1].Free();
2619 g_Sound_Delete('SOUND_CTF_GET1');
2620 g_Sound_Delete('SOUND_CTF_GET2');
2621 g_Sound_Delete('SOUND_CTF_LOST1');
2622 g_Sound_Delete('SOUND_CTF_LOST2');
2623 g_Sound_Delete('SOUND_CTF_RETURN1');
2624 g_Sound_Delete('SOUND_CTF_RETURN2');
2625 g_Sound_Delete('SOUND_CTF_CAPTURE1');
2626 g_Sound_Delete('SOUND_CTF_CAPTURE2');
2628 g_Game_FreeChatSounds();
2630 DataLoaded := False;
2631 end;
2633 procedure g_FatalError(Text: String);
2634 begin
2635 g_Console_Add(Format(_lc[I_FATAL_ERROR], [Text]), True);
2636 e_WriteLog(Format(_lc[I_FATAL_ERROR], [Text]), TMsgType.Warning);
2638 gExit := EXIT_SIMPLE;
2639 if gGameOn then EndGame;
2640 end;
2642 procedure g_SimpleError(Text: String);
2643 begin
2644 g_Console_Add(Format(_lc[I_SIMPLE_ERROR], [Text]), True);
2645 e_WriteLog(Format(_lc[I_SIMPLE_ERROR], [Text]), TMsgType.Warning);
2646 end;
2648 procedure g_Game_AddPlayer(Team: Byte = TEAM_NONE);
2649 begin
2650 if ((not gGameOn) and (gState <> STATE_INTERCUSTOM))
2651 or (not (gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT])) then
2652 Exit;
2654 if (gGameSettings.MaxLives > 0) and (gLMSRespawn = LMS_RESPAWN_NONE) then
2655 Exit;
2657 if gPlayer1 = nil then
2658 begin
2659 if g_Game_IsClient then
2660 begin
2661 if NetPlrUID1 > -1 then
2662 MC_SEND_CheatRequest(NET_CHEAT_SPECTATE);
2663 Exit;
2664 end;
2666 if not (Team in [TEAM_RED, TEAM_BLUE]) then
2667 Team := gPlayer1Settings.Team;
2669 // Создание первого игрока:
2670 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
2671 gPlayer1Settings.Color,
2672 Team, False));
2673 if gPlayer1 = nil then
2674 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]))
2675 else
2676 begin
2677 gPlayer1.Name := gPlayer1Settings.Name;
2678 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [gPlayer1.Name]), True);
2679 if g_Game_IsServer and g_Game_IsNet then
2680 MH_SEND_PlayerCreate(gPlayer1.UID);
2681 gPlayer1.Respawn(False, True);
2682 g_Net_Slist_ServerPlayerComes();
2683 end;
2685 Exit;
2686 end;
2687 if gPlayer2 = nil then
2688 begin
2689 if g_Game_IsClient then
2690 begin
2691 if NetPlrUID2 > -1 then
2692 gPlayer2 := g_Player_Get(NetPlrUID2);
2693 Exit;
2694 end;
2696 if not (Team in [TEAM_RED, TEAM_BLUE]) then
2697 Team := gPlayer2Settings.Team;
2699 // Создание второго игрока:
2700 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
2701 gPlayer2Settings.Color,
2702 Team, False));
2703 if gPlayer2 = nil then
2704 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]))
2705 else
2706 begin
2707 gPlayer2.Name := gPlayer2Settings.Name;
2708 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [gPlayer2.Name]), True);
2709 if g_Game_IsServer and g_Game_IsNet then
2710 MH_SEND_PlayerCreate(gPlayer2.UID);
2711 gPlayer2.Respawn(False, True);
2712 g_Net_Slist_ServerPlayerComes();
2713 end;
2715 Exit;
2716 end;
2717 end;
2719 procedure g_Game_RemovePlayer();
2720 var
2721 Pl: TPlayer;
2722 begin
2723 if ((not gGameOn) and (gState <> STATE_INTERCUSTOM))
2724 or (not (gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT])) then
2725 Exit;
2726 Pl := gPlayer2;
2727 if Pl <> nil then
2728 begin
2729 if g_Game_IsServer then
2730 begin
2731 Pl.Lives := 0;
2732 Pl.Kill(K_SIMPLEKILL, 0, HIT_DISCON);
2733 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [Pl.Name]), True);
2734 g_Player_Remove(Pl.UID);
2735 g_Net_Slist_ServerPlayerLeaves();
2736 end
2737 else
2738 begin
2739 gSpectLatchPID2 := Pl.UID;
2740 gPlayer2 := nil;
2741 end;
2742 Exit;
2743 end;
2744 Pl := gPlayer1;
2745 if Pl <> nil then
2746 begin
2747 if g_Game_IsServer then
2748 begin
2749 Pl.Lives := 0;
2750 Pl.Kill(K_SIMPLEKILL, 0, HIT_DISCON);
2751 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [Pl.Name]), True);
2752 g_Player_Remove(Pl.UID);
2753 g_Net_Slist_ServerPlayerLeaves();
2754 end else
2755 begin
2756 gSpectLatchPID1 := Pl.UID;
2757 gPlayer1 := nil;
2758 MC_SEND_CheatRequest(NET_CHEAT_SPECTATE);
2759 end;
2760 Exit;
2761 end;
2762 g_Net_Slist_ServerPlayerLeaves();
2763 end;
2765 procedure g_Game_Spectate();
2766 begin
2767 g_Game_RemovePlayer();
2768 if gPlayer1 <> nil then
2769 g_Game_RemovePlayer();
2770 end;
2772 procedure g_Game_SpectateCenterView();
2773 begin
2774 gSpectX := Max(gMapInfo.Width div 2 - gScreenWidth div 2, 0);
2775 gSpectY := Max(gMapInfo.Height div 2 - gScreenHeight div 2, 0);
2776 end;
2778 procedure g_Game_StartSingle(Map: String; TwoPlayers: Boolean; nPlayers: Byte);
2779 var
2780 i, nPl: Integer;
2781 tmps: AnsiString;
2782 begin
2783 g_Game_Free();
2785 e_WriteLog('Starting singleplayer game...', TMsgType.Notify);
2787 g_Game_ClearLoading();
2789 // Настройки игры:
2790 FillByte(gGameSettings, SizeOf(TGameSettings), 0);
2791 gAimLine := False;
2792 gShowMap := False;
2793 gGameSettings.GameType := GT_SINGLE;
2794 gGameSettings.MaxLives := 0;
2795 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_ALLOWEXIT;
2796 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_MONSTERS;
2797 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_BOTVSMONSTER;
2798 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_TEAMHITPROJECTILE;
2799 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_TEAMHITTRACE;
2800 gSwitchGameMode := GM_SINGLE;
2802 gLMSRespawn := LMS_RESPAWN_NONE;
2803 gLMSRespawnTime := 0;
2804 gSpectLatchPID1 := 0;
2805 gSpectLatchPID2 := 0;
2807 g_Game_ExecuteEvent('ongamestart');
2809 // Создание первого игрока:
2810 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
2811 gPlayer1Settings.Color,
2812 gPlayer1Settings.Team, False));
2813 if gPlayer1 = nil then
2814 begin
2815 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
2816 Exit;
2817 end;
2819 gPlayer1.Name := gPlayer1Settings.Name;
2820 nPl := 1;
2822 // Создание второго игрока, если есть:
2823 if TwoPlayers then
2824 begin
2825 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
2826 gPlayer2Settings.Color,
2827 gPlayer2Settings.Team, False));
2828 if gPlayer2 = nil then
2829 begin
2830 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]));
2831 Exit;
2832 end;
2834 gPlayer2.Name := gPlayer2Settings.Name;
2835 Inc(nPl);
2836 end;
2838 // Загрузка и запуск карты:
2839 if not g_Game_StartMap(false{asMegawad}, MAP, True) then
2840 begin
2841 if (Pos(':\', Map) > 0) or (Pos(':/', Map) > 0) then tmps := Map else tmps := gGameSettings.WAD + ':\' + MAP;
2842 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [tmps]));
2843 Exit;
2844 end;
2846 // Настройки игроков и ботов:
2847 g_Player_Init();
2849 // Создаем ботов:
2850 for i := nPl+1 to nPlayers do
2851 g_Player_Create(STD_PLAYER_MODEL, _RGB(0, 0, 0), 0, True);
2852 end;
2854 procedure g_Game_StartCustom(Map: String; GameMode: Byte;
2855 TimeLimit, GoalLimit: Word;
2856 MaxLives: Byte;
2857 Options: LongWord; nPlayers: Byte);
2858 var
2859 i, nPl: Integer;
2860 begin
2861 g_Game_Free();
2863 e_WriteLog('Starting custom game...', TMsgType.Notify);
2865 g_Game_ClearLoading();
2867 // Настройки игры:
2868 gGameSettings.GameType := GT_CUSTOM;
2869 gGameSettings.GameMode := GameMode;
2870 gSwitchGameMode := GameMode;
2871 gGameSettings.TimeLimit := TimeLimit;
2872 gGameSettings.GoalLimit := GoalLimit;
2873 gGameSettings.MaxLives := IfThen(GameMode = GM_CTF, 0, MaxLives);
2874 gGameSettings.Options := Options;
2876 gCoopTotalMonstersKilled := 0;
2877 gCoopTotalSecretsFound := 0;
2878 gCoopTotalMonsters := 0;
2879 gCoopTotalSecrets := 0;
2880 gAimLine := False;
2881 gShowMap := False;
2883 gLMSRespawn := LMS_RESPAWN_NONE;
2884 gLMSRespawnTime := 0;
2885 gSpectLatchPID1 := 0;
2886 gSpectLatchPID2 := 0;
2888 g_Game_ExecuteEvent('ongamestart');
2890 // Режим наблюдателя:
2891 if nPlayers = 0 then
2892 begin
2893 gPlayer1 := nil;
2894 gPlayer2 := nil;
2895 end;
2897 nPl := 0;
2898 if nPlayers >= 1 then
2899 begin
2900 // Создание первого игрока:
2901 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
2902 gPlayer1Settings.Color,
2903 gPlayer1Settings.Team, False));
2904 if gPlayer1 = nil then
2905 begin
2906 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
2907 Exit;
2908 end;
2910 gPlayer1.Name := gPlayer1Settings.Name;
2911 Inc(nPl);
2912 end;
2914 if nPlayers >= 2 then
2915 begin
2916 // Создание второго игрока:
2917 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
2918 gPlayer2Settings.Color,
2919 gPlayer2Settings.Team, False));
2920 if gPlayer2 = nil then
2921 begin
2922 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]));
2923 Exit;
2924 end;
2926 gPlayer2.Name := gPlayer2Settings.Name;
2927 Inc(nPl);
2928 end;
2930 // Загрузка и запуск карты:
2931 if not g_Game_StartMap(true{asMegawad}, Map, True) then
2932 begin
2933 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Map]));
2934 Exit;
2935 end;
2937 // Нет точек появления:
2938 if (g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) +
2939 g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) +
2940 g_Map_GetPointCount(RESPAWNPOINT_DM) +
2941 g_Map_GetPointCount(RESPAWNPOINT_RED)+
2942 g_Map_GetPointCount(RESPAWNPOINT_BLUE)) < 1 then
2943 begin
2944 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
2945 Exit;
2946 end;
2948 // Настройки игроков и ботов:
2949 g_Player_Init();
2951 // Создаем ботов:
2952 for i := nPl+1 to nPlayers do
2953 g_Player_Create(STD_PLAYER_MODEL, _RGB(0, 0, 0), 0, True);
2954 end;
2956 procedure g_Game_StartServer(Map: String; GameMode: Byte;
2957 TimeLimit, GoalLimit: Word; MaxLives: Byte;
2958 Options: LongWord; nPlayers: Byte;
2959 IPAddr: LongWord; Port: Word);
2960 begin
2961 g_Game_Free();
2962 g_Net_Slist_ServerClosed();
2964 e_WriteLog('Starting net game (server)...', TMsgType.Notify);
2966 g_Game_ClearLoading();
2968 // Настройки игры:
2969 gGameSettings.GameType := GT_SERVER;
2970 gGameSettings.GameMode := GameMode;
2971 gSwitchGameMode := GameMode;
2972 gGameSettings.TimeLimit := TimeLimit;
2973 gGameSettings.GoalLimit := GoalLimit;
2974 gGameSettings.MaxLives := IfThen(GameMode = GM_CTF, 0, MaxLives);
2975 gGameSettings.Options := Options;
2977 gCoopTotalMonstersKilled := 0;
2978 gCoopTotalSecretsFound := 0;
2979 gCoopTotalMonsters := 0;
2980 gCoopTotalSecrets := 0;
2981 gAimLine := False;
2982 gShowMap := False;
2984 gLMSRespawn := LMS_RESPAWN_NONE;
2985 gLMSRespawnTime := 0;
2986 gSpectLatchPID1 := 0;
2987 gSpectLatchPID2 := 0;
2989 g_Game_ExecuteEvent('ongamestart');
2991 // Режим наблюдателя:
2992 if nPlayers = 0 then
2993 begin
2994 gPlayer1 := nil;
2995 gPlayer2 := nil;
2996 end;
2998 if nPlayers >= 1 then
2999 begin
3000 // Создание первого игрока:
3001 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
3002 gPlayer1Settings.Color,
3003 gPlayer1Settings.Team, False));
3004 if gPlayer1 = nil then
3005 begin
3006 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
3007 Exit;
3008 end;
3010 gPlayer1.Name := gPlayer1Settings.Name;
3011 end;
3013 if nPlayers >= 2 then
3014 begin
3015 // Создание второго игрока:
3016 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
3017 gPlayer2Settings.Color,
3018 gPlayer2Settings.Team, False));
3019 if gPlayer2 = nil then
3020 begin
3021 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]));
3022 Exit;
3023 end;
3025 gPlayer2.Name := gPlayer2Settings.Name;
3026 end;
3028 g_Game_SetLoadingText(_lc[I_LOAD_HOST], 0, False);
3029 if NetForwardPorts then
3030 g_Game_SetLoadingText(_lc[I_LOAD_PORTS], 0, False);
3032 // Стартуем сервер
3033 if not g_Net_Host(IPAddr, Port, NetMaxClients) then
3034 begin
3035 g_FatalError(_lc[I_NET_MSG] + Format(_lc[I_NET_ERR_HOST], [Port]));
3036 Exit;
3037 end;
3039 g_Net_Slist_Set(NetMasterList);
3041 g_Net_Slist_ServerStarted();
3043 // Загрузка и запуск карты:
3044 if not g_Game_StartMap(false{asMegawad}, Map, True) then
3045 begin
3046 g_Net_Slist_ServerClosed();
3047 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Map]));
3048 Exit;
3049 end;
3051 // Нет точек появления:
3052 if (g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) +
3053 g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) +
3054 g_Map_GetPointCount(RESPAWNPOINT_DM) +
3055 g_Map_GetPointCount(RESPAWNPOINT_RED)+
3056 g_Map_GetPointCount(RESPAWNPOINT_BLUE)) < 1 then
3057 begin
3058 g_Net_Slist_ServerClosed();
3059 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
3060 Exit;
3061 end;
3063 // Настройки игроков и ботов:
3064 g_Player_Init();
3066 g_Net_Slist_ServerMapStarted();
3067 NetState := NET_STATE_GAME;
3068 end;
3070 procedure g_Game_StartClient(Addr: String; Port: Word; PW: String);
3071 var
3072 Map: String;
3073 WadName: string;
3074 Ptr: Pointer;
3075 T: Cardinal;
3076 MID: Byte;
3077 State: Byte;
3078 OuterLoop: Boolean;
3079 newResPath: string;
3080 InMsg: TMsg;
3081 begin
3082 g_Game_Free();
3084 State := 0;
3085 e_WriteLog('Starting net game (client)...', TMsgType.Notify);
3086 e_WriteLog('NET: Trying to connect to ' + Addr + ':' + IntToStr(Port) + '...', TMsgType.Notify);
3088 g_Game_ClearLoading();
3090 // Настройки игры:
3091 gGameSettings.GameType := GT_CLIENT;
3093 gCoopTotalMonstersKilled := 0;
3094 gCoopTotalSecretsFound := 0;
3095 gCoopTotalMonsters := 0;
3096 gCoopTotalSecrets := 0;
3097 gAimLine := False;
3098 gShowMap := False;
3100 g_Game_ExecuteEvent('ongamestart');
3102 NetState := NET_STATE_AUTH;
3104 g_Game_SetLoadingText(_lc[I_LOAD_CONNECT], 0, False);
3106 // create (or update) map/resource databases
3107 g_Res_CreateDatabases(true);
3109 gLMSRespawn := LMS_RESPAWN_NONE;
3110 gLMSRespawnTime := 0;
3111 gSpectLatchPID1 := 0;
3112 gSpectLatchPID2 := 0;
3114 // Стартуем клиент
3115 if not g_Net_Connect(Addr, Port) then
3116 begin
3117 g_FatalError(_lc[I_NET_MSG] + _lc[I_NET_ERR_CONN]);
3118 NetState := NET_STATE_NONE;
3119 Exit;
3120 end;
3122 g_Game_SetLoadingText(_lc[I_LOAD_SEND_INFO], 0, False);
3123 MC_SEND_Info(PW);
3124 g_Game_SetLoadingText(_lc[I_LOAD_WAIT_INFO], 0, False);
3126 OuterLoop := True;
3127 while OuterLoop do
3128 begin
3129 // fuck! https://www.mail-archive.com/enet-discuss@cubik.org/msg00852.html
3130 // tl;dr: on shitdows, we can get -1 sometimes, and it is *NOT* a failure.
3131 // thank you, enet. let's ignore failures altogether then.
3132 while (enet_host_service(NetHost, @NetEvent, 50) > 0) do
3133 begin
3134 if (NetEvent.kind = ENET_EVENT_TYPE_RECEIVE) then
3135 begin
3136 if (NetEvent.channelID = NET_CHAN_DOWNLOAD_EX) then
3137 begin
3138 // ignore all download packets, they're processed by separate code
3139 enet_packet_destroy(NetEvent.packet);
3140 continue;
3141 end;
3142 Ptr := NetEvent.packet^.data;
3143 if not InMsg.Init(Ptr, NetEvent.packet^.dataLength, True) then
3144 begin
3145 enet_packet_destroy(NetEvent.packet);
3146 continue;
3147 end;
3149 InMsg.ReadLongWord(); // skip size
3150 MID := InMsg.ReadByte();
3152 if (MID = NET_MSG_INFO) and (State = 0) then
3153 begin
3154 NetMyID := InMsg.ReadByte();
3155 NetPlrUID1 := InMsg.ReadWord();
3157 WadName := InMsg.ReadString();
3158 Map := InMsg.ReadString();
3160 gWADHash := InMsg.ReadMD5();
3162 gGameSettings.GameMode := InMsg.ReadByte();
3163 gSwitchGameMode := gGameSettings.GameMode;
3164 gGameSettings.GoalLimit := InMsg.ReadWord();
3165 gGameSettings.TimeLimit := InMsg.ReadWord();
3166 gGameSettings.MaxLives := InMsg.ReadByte();
3167 gGameSettings.Options := InMsg.ReadLongWord();
3168 T := InMsg.ReadLongWord();
3170 //newResPath := g_Res_SearchSameWAD(MapsDir, WadName, gWADHash);
3171 //if newResPath = '' then
3172 begin
3173 //g_Game_SetLoadingText(_lc[I_LOAD_DL_RES], 0, False);
3174 newResPath := g_Res_DownloadMapWAD(ExtractFileName(WadName), gWADHash);
3175 if newResPath = '' then
3176 begin
3177 g_FatalError(_lc[I_NET_ERR_HASH]);
3178 enet_packet_destroy(NetEvent.packet);
3179 NetState := NET_STATE_NONE;
3180 Exit;
3181 end;
3182 e_LogWritefln('using downloaded map wad [%s] for [%s]`', [newResPath, WadName], TMsgType.Notify);
3183 end;
3184 //newResPath := ExtractRelativePath(MapsDir, newResPath);
3187 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
3188 gPlayer1Settings.Color,
3189 gPlayer1Settings.Team, False));
3191 if gPlayer1 = nil then
3192 begin
3193 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
3195 enet_packet_destroy(NetEvent.packet);
3196 NetState := NET_STATE_NONE;
3197 Exit;
3198 end;
3200 gPlayer1.Name := gPlayer1Settings.Name;
3201 gPlayer1.UID := NetPlrUID1;
3202 gPlayer1.Reset(True);
3204 if not g_Game_StartMap(false{asMegawad}, newResPath + ':\' + Map, True) then
3205 begin
3206 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [WadName + ':\' + Map]));
3208 enet_packet_destroy(NetEvent.packet);
3209 NetState := NET_STATE_NONE;
3210 Exit;
3211 end;
3213 gTime := T;
3215 State := 1;
3216 OuterLoop := False;
3217 enet_packet_destroy(NetEvent.packet);
3218 break;
3219 end
3220 else
3221 enet_packet_destroy(NetEvent.packet);
3222 end
3223 else
3224 begin
3225 if (NetEvent.kind = ENET_EVENT_TYPE_DISCONNECT) then
3226 begin
3227 State := 0;
3228 if (NetEvent.data <= NET_DISC_MAX) then
3229 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' ' +
3230 _lc[TStrings_Locale(Cardinal(I_NET_DISC_NONE) + NetEvent.data)], True);
3231 OuterLoop := False;
3232 Break;
3233 end;
3234 end;
3235 end;
3237 ProcessLoading(true);
3239 if g_Net_UserRequestExit() then
3240 begin
3241 State := 0;
3242 break;
3243 end;
3244 end;
3246 if State <> 1 then
3247 begin
3248 g_FatalError(_lc[I_NET_MSG] + _lc[I_NET_ERR_CONN]);
3249 NetState := NET_STATE_NONE;
3250 Exit;
3251 end;
3253 g_Player_Init();
3254 NetState := NET_STATE_GAME;
3255 MC_SEND_FullStateRequest;
3256 e_WriteLog('NET: Connection successful.', TMsgType.Notify);
3257 end;
3259 var
3260 lastAsMegaWad: Boolean = false;
3262 procedure g_Game_ChangeMap(const MapPath: String);
3263 var
3264 Force: Boolean;
3265 begin
3266 g_Game_ClearLoading();
3268 Force := gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF];
3269 // Если уровень завершился по триггеру Выход, не очищать инвентарь
3270 if gExitByTrigger then
3271 begin
3272 Force := False;
3273 gExitByTrigger := False;
3274 end;
3275 if not g_Game_StartMap(lastAsMegaWad, MapPath, Force) then
3276 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [MapPath]));
3277 end;
3279 procedure g_Game_Restart();
3280 var
3281 Map: string;
3282 begin
3283 if g_Game_IsClient then
3284 Exit;
3285 map := g_ExtractFileName(gMapInfo.Map);
3286 e_LogWritefln('g_Game_Restart: map = "%s" gCurrentMapFileName = "%s"', [map, gCurrentMapFileName]);
3288 MessageTime := 0;
3289 gGameOn := False;
3290 g_Game_ClearLoading();
3291 g_Game_StartMap(lastAsMegaWad, Map, True, gCurrentMapFileName);
3292 end;
3294 function g_Game_StartMap (asMegawad: Boolean; Map: String; Force: Boolean = False; const oldMapPath: AnsiString=''): Boolean;
3295 var
3296 NewWAD, ResName: String;
3297 I: Integer;
3298 nws: AnsiString;
3299 begin
3300 g_Map_Free((Map <> gCurrentMapFileName) and (oldMapPath <> gCurrentMapFileName));
3302 {$IFDEF ENABLE_GIBS}
3303 g_Gibs_RemoveAll;
3304 {$ENDIF}
3305 {$IFDEF ENALBE_SHELLS}
3306 g_Shells_RemoveAll;
3307 {$ENDIF}
3308 {$IFDEF ENABLE_CORPSES}
3309 g_Corpses_RemoveAll;
3310 {$ENDIF}
3312 if (not g_Game_IsClient) and
3313 (gSwitchGameMode <> gGameSettings.GameMode) and
3314 (gGameSettings.GameMode <> GM_SINGLE) then
3315 begin
3316 if gSwitchGameMode = GM_CTF then
3317 gGameSettings.MaxLives := 0;
3318 gGameSettings.GameMode := gSwitchGameMode;
3319 Force := True;
3320 end else
3321 gSwitchGameMode := gGameSettings.GameMode;
3323 g_Player_ResetTeams();
3325 lastAsMegaWad := asMegawad;
3326 if isWadPath(Map) then
3327 begin
3328 NewWAD := g_ExtractWadName(Map);
3329 ResName := g_ExtractFileName(Map);
3330 if g_Game_IsServer then
3331 begin
3332 nws := findDiskWad(NewWAD);
3333 //writeln('000: Map=[', Map, ']; nws=[', nws, ']; NewWAD=[', NewWAD, ']');
3334 if (asMegawad) then
3335 begin
3336 if (length(nws) = 0) then nws := e_FindWad(MegawadDirs, NewWAD);
3337 if (length(nws) = 0) then nws := e_FindWad(MapDirs, NewWAD);
3338 end
3339 else
3340 begin
3341 if (length(nws) = 0) then nws := e_FindWad(MapDirs, NewWAD);
3342 if (length(nws) = 0) then nws := e_FindWad(MegawadDirs, NewWAD);
3343 end;
3344 //if (length(nws) = 0) then nws := e_FindWad(MapDownloadDirs, NewWAD);
3345 //writeln('001: Map=[', Map, ']; nws=[', nws, ']; NewWAD=[', NewWAD, ']');
3346 //nws := NewWAD;
3347 if (length(nws) = 0) then
3348 begin
3349 ResName := ''; // failed
3350 end
3351 else
3352 begin
3353 NewWAD := nws;
3354 if (g_Game_IsNet) then gWADHash := MD5File(nws);
3355 //writeln('********: nws=', nws, ' : Map=', Map, ' : nw=', NewWAD, ' : resname=', ResName);
3356 g_Game_LoadWAD(NewWAD);
3357 end;
3358 end
3359 else
3360 begin
3361 // hash received in MC_RECV_GameEvent -> NET_EV_MAPSTART
3362 NewWAD := g_Game_ClientWAD(NewWAD, gWADHash);
3363 end;
3364 end
3365 else
3366 begin
3367 NewWAD := gGameSettings.WAD;
3368 ResName := Map;
3369 end;
3371 gTime := 0;
3373 //writeln('********: gsw=', gGameSettings.WAD, '; rn=', ResName);
3374 result := false;
3375 if (ResName <> '') and (NewWAD <> '') then
3376 begin
3377 //result := g_Map_Load(gGameSettings.WAD + ':\' + ResName);
3378 result := g_Map_Load(NewWAD+':\'+ResName);
3379 {$IFNDEF HEADLESS}
3380 r_Render_LoadTextures;
3381 {$ENDIF}
3382 end;
3383 if Result then
3384 begin
3385 g_Player_ResetAll(Force or gLastMap, gGameSettings.GameType = GT_SINGLE);
3387 gState := STATE_NONE;
3388 {$IFDEF ENABLE_MENU}
3389 g_ActiveWindow := nil;
3390 {$ENDIF}
3391 gGameOn := True;
3393 DisableCheats();
3394 wNeedTimeReset := True;
3396 if gGameSettings.GameMode = GM_CTF then
3397 begin
3398 g_Map_ResetFlag(FLAG_RED);
3399 g_Map_ResetFlag(FLAG_BLUE);
3400 // CTF, а флагов нет:
3401 if not g_Map_HaveFlagPoints() then
3402 g_SimpleError(_lc[I_GAME_ERROR_CTF]);
3403 end;
3404 end
3405 else
3406 begin
3407 gState := STATE_MENU;
3408 gGameOn := False;
3409 end;
3411 gExit := 0;
3412 gPauseMain := false;
3413 gPauseHolmes := false;
3414 NetTimeToUpdate := 1;
3415 NetTimeToReliable := 0;
3416 NetTimeToMaster := NetMasterRate;
3417 gSpectLatchPID1 := 0;
3418 gSpectLatchPID2 := 0;
3419 gMissionFailed := False;
3420 gNextMap := '';
3422 gCoopMonstersKilled := 0;
3423 gCoopSecretsFound := 0;
3425 gVoteInProgress := False;
3426 gVotePassed := False;
3427 gVoteCount := 0;
3428 gVoted := False;
3430 gStatsOff := False;
3432 if not gGameOn then Exit;
3434 g_Game_SpectateCenterView();
3436 if g_Game_IsServer then
3437 begin
3438 if (gGameSettings.MaxLives > 0) and (gGameSettings.WarmupTime > 0) then
3439 begin
3440 gLMSRespawn := LMS_RESPAWN_WARMUP;
3441 gLMSRespawnTime := gTime + gGameSettings.WarmupTime*1000;
3442 gLMSSoftSpawn := True;
3443 if g_Game_IsNet then
3444 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime);
3445 end
3446 else
3447 begin
3448 gLMSRespawn := LMS_RESPAWN_NONE;
3449 gLMSRespawnTime := 0;
3450 end;
3451 end;
3453 if NetMode = NET_SERVER then
3454 begin
3455 MH_SEND_GameEvent(NET_EV_MAPSTART, gGameSettings.GameMode, Map);
3457 // Мастерсервер
3458 g_Net_Slist_ServerMapStarted();
3460 if NetClients <> nil then
3461 for I := 0 to High(NetClients) do
3462 if NetClients[I].Used then
3463 begin
3464 NetClients[I].Voted := False;
3465 if NetClients[I].RequestedFullUpdate then
3466 begin
3467 MH_SEND_Everything((NetClients[I].State = NET_STATE_AUTH), I);
3468 NetClients[I].RequestedFullUpdate := False;
3469 end;
3470 end;
3472 g_Net_UnbanNonPermHosts();
3473 end;
3475 if gLastMap then
3476 begin
3477 gCoopTotalMonstersKilled := 0;
3478 gCoopTotalSecretsFound := 0;
3479 gCoopTotalMonsters := 0;
3480 gCoopTotalSecrets := 0;
3481 gLastMap := False;
3482 end;
3484 g_Game_ExecuteEvent('onmapstart');
3485 end;
3487 procedure SetFirstLevel;
3488 begin
3489 gNextMap := '';
3491 MapList := g_Map_GetMapsList(gGameSettings.WAD);
3492 if MapList = nil then
3493 Exit;
3495 SortSArray(MapList);
3496 gNextMap := MapList[Low(MapList)];
3498 MapList := nil;
3499 end;
3501 procedure g_Game_ExitLevel(const Map: AnsiString);
3502 begin
3503 gNextMap := Map;
3505 gCoopTotalMonstersKilled := gCoopTotalMonstersKilled + gCoopMonstersKilled;
3506 gCoopTotalSecretsFound := gCoopTotalSecretsFound + gCoopSecretsFound;
3507 gCoopTotalMonsters := gCoopTotalMonsters + gTotalMonsters;
3508 gCoopTotalSecrets := gCoopTotalSecrets + gSecretsCount;
3510 // Вышли в выход в Одиночной игре:
3511 if gGameSettings.GameType = GT_SINGLE then
3512 gExit := EXIT_ENDLEVELSINGLE
3513 else // Вышли в выход в Своей игре
3514 begin
3515 gExit := EXIT_ENDLEVELCUSTOM;
3516 if gGameSettings.GameMode = GM_COOP then
3517 g_Player_RememberAll;
3519 if not g_Map_Exist(gGameSettings.WAD + ':\' + gNextMap) then
3520 begin
3521 gLastMap := True;
3522 if gGameSettings.GameMode = GM_COOP then
3523 gStatsOff := True;
3525 gStatsPressed := True;
3526 gNextMap := 'MAP01';
3528 if not g_Map_Exist(gGameSettings.WAD + ':\' + gNextMap) then
3529 g_Game_NextLevel;
3531 if g_Game_IsNet then
3532 begin
3533 MH_SEND_GameStats();
3534 MH_SEND_CoopStats();
3535 end;
3536 end;
3537 end;
3538 end;
3540 procedure g_Game_RestartLevel();
3541 var
3542 Map: string;
3543 begin
3544 if gGameSettings.GameMode = GM_SINGLE then
3545 begin
3546 g_Game_Restart();
3547 Exit;
3548 end;
3549 gExit := EXIT_ENDLEVELCUSTOM;
3550 Map := g_ExtractFileName(gMapInfo.Map);
3551 gNextMap := Map;
3552 end;
3554 function g_Game_ClientWAD (NewWAD: String; const WHash: TMD5Digest): AnsiString;
3555 var
3556 gWAD{, xwad}: String;
3557 begin
3558 result := NewWAD;
3559 if not g_Game_IsClient then Exit;
3560 //e_LogWritefln('*** g_Game_ClientWAD: `%s`', [NewWAD]);
3562 gWAD := g_Res_DownloadMapWAD(ExtractFileName(NewWAD), WHash);
3563 if gWAD = '' then
3564 begin
3565 result := '';
3566 g_Game_Free();
3567 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [ExtractFileName(NewWAD)]));
3568 Exit;
3569 end;
3571 e_LogWritefln('using downloaded client map wad [%s] for [%s]', [gWAD, NewWAD], TMsgType.Notify);
3572 NewWAD := gWAD;
3574 g_Game_LoadWAD(NewWAD);
3575 result := NewWAD;
3578 if LowerCase(NewWAD) = LowerCase(gGameSettings.WAD) then Exit;
3579 gWAD := g_Res_SearchSameWAD(MapsDir, ExtractFileName(NewWAD), WHash);
3580 if gWAD = '' then
3581 begin
3582 g_Game_SetLoadingText(_lc[I_LOAD_DL_RES], 0, False);
3583 gWAD := g_Res_DownloadMapWAD(ExtractFileName(NewWAD), WHash);
3584 if gWAD = '' then
3585 begin
3586 g_Game_Free();
3587 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [ExtractFileName(NewWAD)]));
3588 Exit;
3589 end;
3590 end;
3591 NewWAD := ExtractRelativePath(MapsDir, gWAD);
3592 g_Game_LoadWAD(NewWAD);
3594 end;
3596 procedure g_Game_RestartRound(NoMapRestart: Boolean = False);
3597 var
3598 i, n, nb, nr: Integer;
3599 begin
3600 if not g_Game_IsServer then Exit;
3601 if gLMSRespawn = LMS_RESPAWN_NONE then Exit;
3602 gLMSRespawn := LMS_RESPAWN_NONE;
3603 gLMSRespawnTime := 0;
3604 MessageTime := 0;
3606 if (gGameSettings.GameMode = GM_COOP) and not NoMapRestart then
3607 begin
3608 gMissionFailed := True;
3609 g_Game_RestartLevel;
3610 Exit;
3611 end;
3613 n := 0; nb := 0; nr := 0;
3614 for i := Low(gPlayers) to High(gPlayers) do
3615 if (gPlayers[i] <> nil) and
3616 ((not gPlayers[i].FSpectator) or gPlayers[i].FWantsInGame or
3617 (gPlayers[i] is TBot)) then
3618 begin
3619 Inc(n);
3620 if gPlayers[i].Team = TEAM_RED then Inc(nr)
3621 else if gPlayers[i].Team = TEAM_BLUE then Inc(nb)
3622 end;
3624 if (n < 1) or ((gGameSettings.GameMode = GM_TDM) and ((nr = 0) or (nb = 0))) then
3625 begin
3626 // wait a second until the fuckers finally decide to join
3627 gLMSRespawn := LMS_RESPAWN_WARMUP;
3628 gLMSRespawnTime := gTime + gGameSettings.WarmupTime*1000;
3629 gLMSSoftSpawn := NoMapRestart;
3630 if g_Game_IsNet then
3631 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime);
3632 Exit;
3633 end;
3635 {$IFDEF ENABLE_GIBS}
3636 g_Gibs_RemoveAll;
3637 {$ENDIF}
3638 {$IFDEF ENALBE_SHELLS}
3639 g_Shells_RemoveAll;
3640 {$ENDIF}
3641 {$IFDEF ENABLE_CORPSES}
3642 g_Corpses_RemoveAll;
3643 {$ENDIF}
3645 g_Game_Message(_lc[I_MESSAGE_LMS_START], 144);
3646 if g_Game_IsNet then
3647 MH_SEND_GameEvent(NET_EV_LMS_START);
3649 for i := Low(gPlayers) to High(gPlayers) do
3650 begin
3651 if gPlayers[i] = nil then continue;
3652 if gPlayers[i] is TBot then gPlayers[i].FWantsInGame := True;
3653 // don't touch normal spectators
3654 if gPlayers[i].FSpectator and not gPlayers[i].FWantsInGame then
3655 begin
3656 gPlayers[i].FNoRespawn := True;
3657 gPlayers[i].Lives := 0;
3658 if g_Game_IsNet then
3659 MH_SEND_PlayerStats(gPlayers[I].UID);
3660 continue;
3661 end;
3662 gPlayers[i].FNoRespawn := False;
3663 gPlayers[i].Lives := gGameSettings.MaxLives;
3664 gPlayers[i].Respawn(False, True);
3665 if gGameSettings.GameMode = GM_COOP then
3666 begin
3667 gPlayers[i].Frags := 0;
3668 gPlayers[i].RecallState;
3669 end;
3670 if (gPlayer1 = nil) and (gSpectLatchPID1 > 0) then
3671 gPlayer1 := g_Player_Get(gSpectLatchPID1);
3672 if (gPlayer2 = nil) and (gSpectLatchPID2 > 0) then
3673 gPlayer2 := g_Player_Get(gSpectLatchPID2);
3674 end;
3676 g_Items_RestartRound();
3678 gLMSSoftSpawn := False;
3679 end;
3681 function g_Game_GetFirstMap(WAD: String): String;
3682 begin
3683 Result := '';
3685 MapList := g_Map_GetMapsList(WAD);
3686 if MapList = nil then
3687 Exit;
3689 SortSArray(MapList);
3690 Result := MapList[Low(MapList)];
3692 if not g_Map_Exist(WAD + ':\' + Result) then
3693 Result := '';
3695 MapList := nil;
3696 end;
3698 function g_Game_GetNextMap(): String;
3699 var
3700 I: Integer;
3701 Map: string;
3702 begin
3703 Result := '';
3705 MapList := g_Map_GetMapsList(gGameSettings.WAD);
3706 if MapList = nil then
3707 Exit;
3709 Map := g_ExtractFileName(gMapInfo.Map);
3711 SortSArray(MapList);
3712 MapIndex := -255;
3713 for I := Low(MapList) to High(MapList) do
3714 if Map = MapList[I] then
3715 begin
3716 MapIndex := I;
3717 Break;
3718 end;
3720 if MapIndex <> -255 then
3721 begin
3722 if MapIndex = High(MapList) then
3723 Result := MapList[Low(MapList)]
3724 else
3725 Result := MapList[MapIndex + 1];
3727 if not g_Map_Exist(gGameSettings.WAD + ':\' + Result) then Result := Map;
3728 end;
3730 MapList := nil;
3731 end;
3733 procedure g_Game_NextLevel();
3734 begin
3735 if gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF, GM_COOP] then
3736 gExit := EXIT_ENDLEVELCUSTOM
3737 else
3738 begin
3739 gExit := EXIT_ENDLEVELSINGLE;
3740 Exit;
3741 end;
3743 if gNextMap <> '' then Exit;
3744 gNextMap := g_Game_GetNextMap();
3745 end;
3747 function g_Game_IsTestMap(): Boolean;
3748 begin
3749 result := StrEquCI1251(TEST_MAP_NAME, g_ExtractFileName(gMapInfo.Map));
3750 end;
3752 procedure g_Game_DeleteTestMap();
3753 var
3754 a: Integer;
3755 //MapName: AnsiString;
3756 WadName: string;
3758 WAD: TWADFile;
3759 MapList: SSArray;
3760 time: Integer;
3762 begin
3763 a := Pos('.wad:\', toLowerCase1251(gMapToDelete));
3764 if (a = 0) then a := Pos('.wad:/', toLowerCase1251(gMapToDelete));
3765 if (a = 0) then exit;
3767 // Выделяем имя wad-файла и имя карты
3768 WadName := Copy(gMapToDelete, 1, a+3);
3769 Delete(gMapToDelete, 1, a+5);
3770 gMapToDelete := UpperCase(gMapToDelete);
3771 //MapName := '';
3772 //CopyMemory(@MapName[0], @gMapToDelete[1], Min(16, Length(gMapToDelete)));
3775 // Имя карты не стандартное тестовое:
3776 if MapName <> TEST_MAP_NAME then
3777 Exit;
3779 if not gTempDelete then
3780 begin
3781 time := g_GetFileTime(WadName);
3782 WAD := TWADFile.Create();
3784 // Читаем Wad-файл:
3785 if not WAD.ReadFile(WadName) then
3786 begin // Нет такого WAD-файла
3787 WAD.Free();
3788 Exit;
3789 end;
3791 // Составляем список карт и ищем нужную:
3792 WAD.CreateImage();
3793 MapList := WAD.GetResourcesList('');
3795 if MapList <> nil then
3796 for a := 0 to High(MapList) do
3797 if MapList[a] = MapName then
3798 begin
3799 // Удаляем и сохраняем:
3800 WAD.RemoveResource('', MapName);
3801 WAD.SaveTo(WadName);
3802 Break;
3803 end;
3805 WAD.Free();
3806 g_SetFileTime(WadName, time);
3807 end else
3809 if gTempDelete then DeleteFile(WadName);
3810 end;
3812 procedure GameCVars(P: SSArray);
3813 var
3814 a, b: Integer;
3815 stat: TPlayerStatArray;
3816 cmd: string;
3818 procedure ParseGameFlag(Flag: LongWord; OffMsg, OnMsg: TStrings_Locale; OnMapChange: Boolean = False);
3819 var
3820 x: Boolean;
3821 begin
3822 if Length(P) > 1 then
3823 begin
3824 x := P[1] = '1';
3826 if x then
3827 gsGameFlags := gsGameFlags or Flag
3828 else
3829 gsGameFlags := gsGameFlags and (not Flag);
3831 if g_Game_IsServer then
3832 begin
3833 if x then
3834 gGameSettings.Options := gGameSettings.Options or Flag
3835 else
3836 gGameSettings.Options := gGameSettings.Options and (not Flag);
3837 if g_Game_IsNet then MH_SEND_GameSettings;
3838 end;
3839 end;
3841 if LongBool(gsGameFlags and Flag) then
3842 g_Console_Add(_lc[OnMsg])
3843 else
3844 g_Console_Add(_lc[OffMsg]);
3846 if OnMapChange and g_Game_IsServer then
3847 g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
3848 end;
3850 begin
3851 stat := nil;
3852 cmd := LowerCase(P[0]);
3854 if cmd = 'g_gamemode' then
3855 begin
3856 if (Length(P) > 1) then
3857 begin
3858 a := g_Game_TextToMode(P[1]);
3859 if a = GM_SINGLE then a := GM_COOP;
3860 gsGameMode := g_Game_ModeToText(a);
3861 if g_Game_IsServer then
3862 begin
3863 gSwitchGameMode := a;
3864 if (gGameOn and (gGameSettings.GameMode = GM_SINGLE)) or
3865 (gState = STATE_INTERSINGLE) then
3866 gSwitchGameMode := GM_SINGLE;
3867 if not gGameOn then
3868 gGameSettings.GameMode := gSwitchGameMode;
3869 end;
3870 end;
3872 if gSwitchGameMode = gGameSettings.GameMode then
3873 g_Console_Add(Format(_lc[I_MSG_GAMEMODE_CURRENT],
3874 [g_Game_ModeToText(gGameSettings.GameMode)]))
3875 else
3876 g_Console_Add(Format(_lc[I_MSG_GAMEMODE_CHANGE],
3877 [g_Game_ModeToText(gGameSettings.GameMode),
3878 g_Game_ModeToText(gSwitchGameMode)]));
3879 end
3880 else if cmd = 'g_friendlyfire' then
3881 begin
3882 ParseGameFlag(GAME_OPTION_TEAMDAMAGE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3883 end
3884 else if cmd = 'g_friendly_absorb_damage' then
3885 begin
3886 ParseGameFlag(GAME_OPTION_TEAMABSORBDAMAGE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3887 end
3888 else if cmd = 'g_friendly_hit_trace' then
3889 begin
3890 ParseGameFlag(GAME_OPTION_TEAMHITTRACE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3891 end
3892 else if cmd = 'g_friendly_hit_projectile' then
3893 begin
3894 ParseGameFlag(GAME_OPTION_TEAMHITPROJECTILE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3895 end
3896 else if cmd = 'g_weaponstay' then
3897 begin
3898 ParseGameFlag(GAME_OPTION_WEAPONSTAY, I_MSG_WEAPONSTAY_OFF, I_MSG_WEAPONSTAY_ON);
3899 end
3900 else if cmd = 'g_allow_exit' then
3901 begin
3902 ParseGameFlag(GAME_OPTION_ALLOWEXIT, I_MSG_ALLOWEXIT_OFF, I_MSG_ALLOWEXIT_ON, True);
3903 end
3904 else if cmd = 'g_allow_monsters' then
3905 begin
3906 ParseGameFlag(GAME_OPTION_MONSTERS, I_MSG_ALLOWMON_OFF, I_MSG_ALLOWMON_ON, True);
3907 end
3908 else if cmd = 'g_bot_vsplayers' then
3909 begin
3910 ParseGameFlag(GAME_OPTION_BOTVSPLAYER, I_MSG_BOTSVSPLAYERS_OFF, I_MSG_BOTSVSPLAYERS_ON);
3911 end
3912 else if cmd = 'g_bot_vsmonsters' then
3913 begin
3914 ParseGameFlag(GAME_OPTION_BOTVSMONSTER, I_MSG_BOTSVSMONSTERS_OFF, I_MSG_BOTSVSMONSTERS_ON);
3915 end
3916 else if cmd = 'g_dm_keys' then
3917 begin
3918 ParseGameFlag(GAME_OPTION_DMKEYS, I_MSG_DMKEYS_OFF, I_MSG_DMKEYS_ON, True);
3919 end
3920 else if cmd = 'g_gameflags' then
3921 begin
3922 if Length(P) > 1 then
3923 begin
3924 gsGameFlags := StrToDWordDef(P[1], gsGameFlags);
3925 if g_Game_IsServer then
3926 begin
3927 gGameSettings.Options := gsGameFlags;
3928 if g_Game_IsNet then MH_SEND_GameSettings;
3929 end;
3930 end;
3932 g_Console_Add(Format('%s %u', [cmd, gsGameFlags]));
3933 end
3934 else if cmd = 'g_warmup_time' then
3935 begin
3936 if Length(P) > 1 then
3937 begin
3938 gsWarmupTime := nclamp(StrToIntDef(P[1], gsWarmupTime), 0, $FFFF);
3939 if g_Game_IsServer then
3940 begin
3941 gGameSettings.WarmupTime := gsWarmupTime;
3942 // extend warmup if it's already going
3943 if gLMSRespawn = LMS_RESPAWN_WARMUP then
3944 begin
3945 gLMSRespawnTime := gTime + gsWarmupTime * 1000;
3946 if g_Game_IsNet then MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime);
3947 end;
3948 if g_Game_IsNet then MH_SEND_GameSettings;
3949 end;
3950 end;
3952 g_Console_Add(Format(_lc[I_MSG_WARMUP], [Integer(gsWarmupTime)]));
3953 if g_Game_IsServer then g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
3954 end
3955 else if cmd = 'g_spawn_invul' then
3956 begin
3957 if Length(P) > 1 then
3958 begin
3959 gsSpawnInvul := nclamp(StrToIntDef(P[1], gsSpawnInvul), 0, $FFFF);
3960 if g_Game_IsServer then
3961 begin
3962 gGameSettings.SpawnInvul := gsSpawnInvul;
3963 if g_Game_IsNet then MH_SEND_GameSettings;
3964 end;
3965 end;
3967 g_Console_Add(Format('%s %d', [cmd, Integer(gsSpawnInvul)]));
3968 end
3969 else if cmd = 'g_item_respawn_time' then
3970 begin
3971 if Length(P) > 1 then
3972 begin
3973 gsItemRespawnTime := nclamp(StrToIntDef(P[1], gsItemRespawnTime), 0, $FFFF);
3974 if g_Game_IsServer then
3975 begin
3976 gGameSettings.ItemRespawnTime := gsItemRespawnTime;
3977 if g_Game_IsNet then MH_SEND_GameSettings;
3978 end;
3979 end;
3981 g_Console_Add(Format('%s %d', [cmd, Integer(gsItemRespawnTime)]));
3982 if g_Game_IsServer then g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
3983 end
3984 else if cmd = 'sv_intertime' then
3985 begin
3986 if (Length(P) > 1) then
3987 gDefInterTime := Min(Max(StrToIntDef(P[1], gDefInterTime), -1), 120);
3989 g_Console_Add(cmd + ' = ' + IntToStr(gDefInterTime));
3990 end
3991 else if cmd = 'g_max_particles' then
3992 begin
3993 if Length(p) = 2 then
3994 begin
3995 {$IFDEF ENABLE_GFX}
3996 a := Max(0, StrToInt(p[1]));
3997 g_GFX_SetMax(a)
3998 {$ENDIF}
3999 end
4000 else if Length(p) = 1 then
4001 begin
4002 {$IFDEF ENABLE_GFX}
4003 e_LogWritefln('%s', [g_GFX_GetMax()])
4004 {$ELSE}
4005 e_LogWritefln('%s', [0])
4006 {$ENDIF}
4007 end
4008 else
4009 begin
4010 e_LogWritefln('usage: %s <n>', [cmd])
4011 end
4012 end
4013 else if cmd = 'g_max_shells' then
4014 begin
4015 if Length(p) = 2 then
4016 begin
4017 {$IFDEF ENABLE_SHELLS}
4018 a := Max(0, StrToInt(p[1]));
4019 g_Shells_SetMax(a)
4020 {$ENDIF}
4021 end
4022 else if Length(p) = 1 then
4023 begin
4024 {$IFDEF ENABLE_SHELLS}
4025 e_LogWritefln('%s', [g_Shells_GetMax()])
4026 {$ELSE}
4027 e_LogWritefln('%s', [0])
4028 {$ENDIF}
4029 end
4030 else
4031 begin
4032 e_LogWritefln('usage: %s <n>', [cmd])
4033 end
4034 end
4035 else if cmd = 'g_max_gibs' then
4036 begin
4037 if Length(p) = 2 then
4038 begin
4039 {$IFDEF ENABLE_GIBS}
4040 a := Max(0, StrToInt(p[1]));
4041 g_Gibs_SetMax(a)
4042 {$ENDIF}
4043 end
4044 else if Length(p) = 1 then
4045 begin
4046 {$IFDEF ENABLE_GIBS}
4047 e_LogWritefln('%s', [g_Gibs_GetMax()])
4048 {$ELSE}
4049 e_LogWritefln('%s', [0])
4050 {$ENDIF}
4051 end
4052 else
4053 begin
4054 e_LogWritefln('usage: %s <n>', [cmd])
4055 end
4056 end
4057 else if cmd = 'g_max_corpses' then
4058 begin
4059 if Length(p) = 2 then
4060 begin
4061 {$IFDEF ENABLE_CORPSES}
4062 a := Max(0, StrToInt(p[1]));
4063 g_Corpses_SetMax(a)
4064 {$ENDIF}
4065 end
4066 else if Length(p) = 1 then
4067 begin
4068 {$IFDEF ENABLE_CORPSES}
4069 e_LogWritefln('%s', [g_Corpses_GetMax()])
4070 {$ELSE}
4071 e_LogWritefln('%s', [0])
4072 {$ENDIF}
4073 end
4074 else
4075 begin
4076 e_LogWritefln('usage: %s <n>', [cmd])
4077 end
4078 end
4079 else if cmd = 'g_scorelimit' then
4080 begin
4081 if Length(P) > 1 then
4082 begin
4083 gsGoalLimit := nclamp(StrToIntDef(P[1], gsGoalLimit), 0, $FFFF);
4085 if g_Game_IsServer then
4086 begin
4087 b := 0;
4088 if gGameSettings.GameMode = GM_DM then
4089 begin // DM
4090 stat := g_Player_GetStats();
4091 if stat <> nil then
4092 for a := 0 to High(stat) do
4093 if stat[a].Frags > b then
4094 b := stat[a].Frags;
4095 end
4096 else // TDM/CTF
4097 b := Max(gTeamStat[TEAM_RED].Goals, gTeamStat[TEAM_BLUE].Goals);
4099 // if someone has a higher score, set it to that instead
4100 gsGoalLimit := max(gsGoalLimit, b);
4101 gGameSettings.GoalLimit := gsGoalLimit;
4103 if g_Game_IsNet then MH_SEND_GameSettings;
4104 end;
4105 end;
4107 g_Console_Add(Format(_lc[I_MSG_SCORE_LIMIT], [Integer(gsGoalLimit)]));
4108 end
4109 else if cmd = 'g_timelimit' then
4110 begin
4111 if Length(P) > 1 then
4112 begin
4113 gsTimeLimit := nclamp(StrToIntDef(P[1], gsTimeLimit), 0, $FFFF);
4114 if g_Game_IsServer then
4115 begin
4116 gGameSettings.TimeLimit := gsTimeLimit;
4117 if g_Game_IsNet then MH_SEND_GameSettings;
4118 end;
4119 end;
4120 g_Console_Add(Format(_lc[I_MSG_TIME_LIMIT],
4121 [gsTimeLimit div 3600,
4122 (gsTimeLimit div 60) mod 60,
4123 gsTimeLimit mod 60]));
4124 end
4125 else if cmd = 'g_maxlives' then
4126 begin
4127 if Length(P) > 1 then
4128 begin
4129 gsMaxLives := nclamp(StrToIntDef(P[1], gsMaxLives), 0, $FFFF);
4130 if g_Game_IsServer then
4131 begin
4132 gGameSettings.MaxLives := gsMaxLives;
4133 if g_Game_IsNet then MH_SEND_GameSettings;
4134 end;
4135 end;
4137 g_Console_Add(Format(_lc[I_MSG_LIVES], [Integer(gsMaxLives)]));
4138 end;
4139 end;
4141 procedure PlayerSettingsCVars(P: SSArray);
4142 var
4143 cmd: string;
4144 team: Byte;
4146 function ParseTeam(s: string): Byte;
4147 begin
4148 result := 0;
4149 case s of
4150 'red', '1': result := TEAM_RED;
4151 'blue', '2': result := TEAM_BLUE;
4152 else result := TEAM_NONE;
4153 end;
4154 end;
4155 begin
4156 cmd := LowerCase(P[0]);
4157 case cmd of
4158 'p1_name':
4159 begin
4160 if (Length(P) > 1) then
4161 begin
4162 gPlayer1Settings.Name := b_Text_Unformat(P[1]);
4163 if g_Game_IsClient then
4164 MC_SEND_PlayerSettings
4165 else if gGameOn and (gPlayer1 <> nil) then
4166 begin
4167 gPlayer1.Name := b_Text_Unformat(P[1]);
4168 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer1.UID);
4169 end;
4170 end;
4171 end;
4172 'p2_name':
4173 begin
4174 if (Length(P) > 1) then
4175 begin
4176 gPlayer2Settings.Name := b_Text_Unformat(P[1]);
4177 if g_Game_IsClient then
4178 MC_SEND_PlayerSettings
4179 else if gGameOn and (gPlayer2 <> nil) then
4180 begin
4181 gPlayer2.Name := b_Text_Unformat(P[1]);
4182 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer2.UID);
4183 end;
4184 end;
4185 end;
4186 'p1_color':
4187 begin
4188 if Length(P) > 3 then
4189 begin
4190 gPlayer1Settings.Color := _RGB(EnsureRange(StrToIntDef(P[1], 0), 0, 255),
4191 EnsureRange(StrToIntDef(P[2], 0), 0, 255),
4192 EnsureRange(StrToIntDef(P[3], 0), 0, 255));
4193 if g_Game_IsClient then
4194 MC_SEND_PlayerSettings
4195 else if gGameOn and (gPlayer1 <> nil) then
4196 begin
4197 gPlayer1.SetColor(gPlayer1Settings.Color);
4198 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer1.UID);
4199 end;
4200 end;
4201 end;
4202 'p2_color':
4203 begin
4204 if Length(P) > 3 then
4205 begin
4206 gPlayer2Settings.Color := _RGB(EnsureRange(StrToIntDef(P[1], 0), 0, 255),
4207 EnsureRange(StrToIntDef(P[2], 0), 0, 255),
4208 EnsureRange(StrToIntDef(P[3], 0), 0, 255));
4209 if g_Game_IsClient then
4210 MC_SEND_PlayerSettings
4211 else if gGameOn and (gPlayer2 <> nil) then
4212 begin
4213 gPlayer2.SetColor(gPlayer2Settings.Color);
4214 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer2.UID);
4215 end;
4216 end;
4217 end;
4218 'p1_model':
4219 begin
4220 if (Length(P) > 1) then
4221 begin
4222 gPlayer1Settings.Model := P[1];
4223 if g_Game_IsClient then
4224 MC_SEND_PlayerSettings
4225 else if gGameOn and (gPlayer1 <> nil) then
4226 begin
4227 gPlayer1.FActualModelName := gPlayer1Settings.Model;
4228 gPlayer1.SetModel(gPlayer1Settings.Model);
4229 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer1.UID);
4230 end;
4231 end;
4232 end;
4233 'p2_model':
4234 begin
4235 if (Length(P) > 1) then
4236 begin
4237 gPlayer2Settings.Model := P[1];
4238 if g_Game_IsClient then
4239 MC_SEND_PlayerSettings
4240 else if gGameOn and (gPlayer2 <> nil) then
4241 begin
4242 gPlayer2.FActualModelName := gPlayer2Settings.Model;
4243 gPlayer2.SetModel(gPlayer2Settings.Model);
4244 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer2.UID);
4245 end;
4246 end;
4247 end;
4248 'p1_team':
4249 begin
4250 // TODO: switch teams if in game or store this separately
4251 if (Length(P) > 1) then
4252 begin
4253 team := ParseTeam(P[1]);
4254 if team = TEAM_NONE then
4255 g_Console_Add('expected ''red'', ''blue'', 1 or 2')
4256 else if not gGameOn and not g_Game_IsNet then
4257 gPlayer1Settings.Team := team
4258 else
4259 g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
4260 end;
4261 end;
4262 'p2_team':
4263 begin
4264 // TODO: switch teams if in game or store this separately
4265 if (Length(P) > 1) then
4266 begin
4267 team := ParseTeam(P[1]);
4268 if team = TEAM_NONE then
4269 g_Console_Add('expected ''red'', ''blue'', 1 or 2')
4270 else if not gGameOn and not g_Game_IsNet then
4271 gPlayer2Settings.Team := team
4272 else
4273 g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
4274 end;
4275 end;
4276 end;
4277 end;
4279 procedure PrintHeapStats();
4280 var
4281 hs: TFPCHeapStatus;
4282 begin
4283 hs := GetFPCHeapStatus();
4284 e_LogWriteLn ('v===== heap status =====v');
4285 e_LogWriteFln('max heap size = %d k', [hs.MaxHeapSize div 1024]);
4286 e_LogWriteFln('max heap used = %d k', [hs.MaxHeapUsed div 1024]);
4287 e_LogWriteFln('cur heap size = %d k', [hs.CurrHeapSize div 1024]);
4288 e_LogWriteFln('cur heap used = %d k', [hs.CurrHeapUsed div 1024]);
4289 e_LogWriteFln('cur heap free = %d k', [hs.CurrHeapFree div 1024]);
4290 e_LogWriteLn ('^=======================^');
4291 end;
4293 procedure DebugCommands(P: SSArray);
4294 var
4295 a, b: Integer;
4296 cmd: string;
4297 //pt: TDFPoint;
4298 mon: TMonster;
4299 begin
4300 // Команды отладочного режима:
4301 if {gDebugMode}conIsCheatsEnabled then
4302 begin
4303 cmd := LowerCase(P[0]);
4304 if cmd = 'd_window' then
4305 begin
4306 g_Console_Add(Format('gScreenWidth = %d, gScreenHeight = %d', [gScreenWidth, gScreenHeight]));
4307 g_Console_Add(Format('gScreenWidth = %d, gScreenHeight = %d', [gScreenWidth, gScreenHeight]));
4308 end
4309 else if cmd = 'd_sounds' then
4310 begin
4311 if (Length(P) > 1) and
4312 ((P[1] = '1') or (P[1] = '0')) then
4313 g_Debug_Sounds := (P[1][1] = '1');
4315 g_Console_Add(Format('d_sounds is %d', [Byte(g_Debug_Sounds)]));
4316 end
4317 else if cmd = 'd_frames' then
4318 begin
4319 if (Length(P) > 1) and
4320 ((P[1] = '1') or (P[1] = '0')) then
4321 g_Debug_Frames := (P[1][1] = '1');
4323 g_Console_Add(Format('d_frames is %d', [Byte(g_Debug_Frames)]));
4324 end
4325 else if cmd = 'd_winmsg' then
4326 begin
4327 if (Length(P) > 1) and
4328 ((P[1] = '1') or (P[1] = '0')) then
4329 g_Debug_WinMsgs := (P[1][1] = '1');
4331 g_Console_Add(Format('d_winmsg is %d', [Byte(g_Debug_WinMsgs)]));
4332 end
4333 else if (cmd = 'd_monoff') and not g_Game_IsNet then
4334 begin
4335 if (Length(P) > 1) and
4336 ((P[1] = '1') or (P[1] = '0')) then
4337 g_Debug_MonsterOff := (P[1][1] = '1');
4339 g_Console_Add(Format('d_monoff is %d', [Byte(g_debug_MonsterOff)]));
4340 end
4341 else if (cmd = 'd_botoff') and not g_Game_IsNet then
4342 begin
4343 if Length(P) > 1 then
4344 case P[1][1] of
4345 '0': g_debug_BotAIOff := 0;
4346 '1': g_debug_BotAIOff := 1;
4347 '2': g_debug_BotAIOff := 2;
4348 '3': g_debug_BotAIOff := 3;
4349 end;
4351 g_Console_Add(Format('d_botoff is %d', [g_debug_BotAIOff]));
4352 end
4353 else if cmd = 'd_monster' then
4354 begin
4355 if gGameOn and (gPlayer1 <> nil) and (gPlayer1.alive) and (not g_Game_IsNet) then
4356 if Length(P) < 2 then
4357 begin
4358 g_Console_Add(cmd + ' [ID | Name] [behaviour]');
4359 g_Console_Add('ID | Name');
4360 for b := MONSTER_DEMON to MONSTER_MAN do
4361 g_Console_Add(Format('%2d | %s', [b, g_Mons_NameByTypeId(b)]));
4362 conwriteln('behav. num'#10'normal 0'#10'killer 1'#10'maniac 2'#10'insane 3'#10'cannibal 4'#10'good 5');
4363 end else
4364 begin
4365 a := StrToIntDef(P[1], 0);
4366 if (a < MONSTER_DEMON) or (a > MONSTER_MAN) then
4367 a := g_Mons_TypeIdByName(P[1]);
4369 if (a < MONSTER_DEMON) or (a > MONSTER_MAN) then
4370 g_Console_Add(Format(_lc[I_MSG_NO_MONSTER], [P[1]]))
4371 else
4372 begin
4373 with gPlayer1.Obj do
4374 begin
4375 mon := g_Monsters_Create(a,
4376 X + Rect.X + (Rect.Width div 2),
4377 Y + Rect.Y + Rect.Height,
4378 gPlayer1.Direction, True);
4379 end;
4380 if (Length(P) > 2) and (mon <> nil) then
4381 begin
4382 if (CompareText(P[2], 'normal') = 0) then mon.MonsterBehaviour := BH_NORMAL
4383 else if (CompareText(P[2], 'killer') = 0) then mon.MonsterBehaviour := BH_KILLER
4384 else if (CompareText(P[2], 'maniac') = 0) then mon.MonsterBehaviour := BH_MANIAC
4385 else if (CompareText(P[2], 'insane') = 0) then mon.MonsterBehaviour := BH_INSANE
4386 else if (CompareText(P[2], 'cannibal') = 0) then mon.MonsterBehaviour := BH_CANNIBAL
4387 else if (CompareText(P[2], 'good') = 0) then mon.MonsterBehaviour := BH_GOOD
4388 else if (CompareText(P[2], 'friend') = 0) then mon.MonsterBehaviour := BH_GOOD
4389 else if (CompareText(P[2], 'friendly') = 0) then mon.MonsterBehaviour := BH_GOOD
4390 else mon.MonsterBehaviour := Min(Max(StrToIntDef(P[2], BH_NORMAL), BH_NORMAL), BH_GOOD);
4391 end;
4392 end;
4393 end;
4394 end
4395 else if (cmd = 'd_health') then
4396 begin
4397 if (Length(P) > 1) and
4398 ((P[1] = '1') or (P[1] = '0')) then
4399 g_debug_HealthBar := (P[1][1] = '1');
4401 g_Console_Add(Format('d_health is %d', [Byte(g_debug_HealthBar)]));
4402 end
4403 else if (cmd = 'd_player') then
4404 begin
4405 if (Length(P) > 1) and
4406 ((P[1] = '1') or (P[1] = '0')) then
4407 g_debug_Player := (P[1][1] = '1');
4409 g_Console_Add(Format(cmd + ' is %d', [Byte(g_Debug_Player)]));
4410 end
4411 else if (cmd = 'd_mem') then
4412 begin
4413 PrintHeapStats();
4414 end;
4415 end
4416 else
4417 g_Console_Add(_lc[I_MSG_NOT_DEBUG]);
4418 end;
4421 procedure GameCheats(P: SSArray);
4422 var
4423 cmd: string;
4424 f, a: Integer;
4425 plr: TPlayer;
4426 begin
4427 if (not gGameOn) or (not conIsCheatsEnabled) then
4428 begin
4429 g_Console_Add('not available');
4430 exit;
4431 end;
4432 plr := gPlayer1;
4433 if plr = nil then
4434 begin
4435 g_Console_Add('where is the player?!');
4436 exit;
4437 end;
4438 cmd := LowerCase(P[0]);
4439 // god
4440 if cmd = 'god' then
4441 begin
4442 plr.GodMode := not plr.GodMode;
4443 if plr.GodMode then g_Console_Add('player is godlike now') else g_Console_Add('player is mortal now');
4444 exit;
4445 end;
4446 // give <health|exit|weapons|air|suit|jetpack|berserk|all>
4447 if cmd = 'give' then
4448 begin
4449 if length(P) < 2 then begin g_Console_Add('give what?!'); exit; end;
4450 for f := 1 to High(P) do
4451 begin
4452 cmd := LowerCase(P[f]);
4453 if cmd = 'health' then begin plr.RestoreHealthArmor(); g_Console_Add('player feels himself better'); continue; end;
4454 if (cmd = 'all') {or (cmd = 'weapons')} then begin plr.AllRulez(False); g_Console_Add('player got the gifts'); continue; end;
4455 if cmd = 'exit' then
4456 begin
4457 if gTriggers <> nil then
4458 begin
4459 for a := 0 to High(gTriggers) do
4460 begin
4461 if gTriggers[a].TriggerType = TRIGGER_EXIT then
4462 begin
4463 g_Console_Add('player left the map');
4464 gExitByTrigger := True;
4465 //g_Game_ExitLevel(gTriggers[a].Data.MapName);
4466 g_Game_ExitLevel(gTriggers[a].tgcMap);
4467 break;
4468 end;
4469 end;
4470 end;
4471 continue;
4472 end;
4474 if cmd = 'air' then begin plr.GiveItem(ITEM_OXYGEN); g_Console_Add('player got some air'); continue; end;
4475 if cmd = 'jetpack' then begin plr.GiveItem(ITEM_JETPACK); g_Console_Add('player got a jetpack'); continue; end;
4476 if cmd = 'suit' then begin plr.GiveItem(ITEM_SUIT); g_Console_Add('player got an envirosuit'); continue; end;
4477 if cmd = 'berserk' then begin plr.GiveItem(ITEM_MEDKIT_BLACK); g_Console_Add('player got a berserk pack'); continue; end;
4478 if cmd = 'backpack' then begin plr.GiveItem(ITEM_AMMO_BACKPACK); g_Console_Add('player got a backpack'); continue; end;
4480 if cmd = 'helmet' then begin plr.GiveItem(ITEM_HELMET); g_Console_Add('player got a helmet'); continue; end;
4481 if cmd = 'bottle' then begin plr.GiveItem(ITEM_BOTTLE); g_Console_Add('player got a bottle of health'); continue; end;
4483 if cmd = 'stimpack' then begin plr.GiveItem(ITEM_MEDKIT_SMALL); g_Console_Add('player got a stimpack'); continue; end;
4484 if (cmd = 'medkit') or (cmd = 'medikit') or (cmd = 'medpack') or (cmd = 'medipack') then begin plr.GiveItem(ITEM_MEDKIT_LARGE); g_Console_Add('player got a '+cmd); continue; end;
4486 if cmd = 'greenarmor' then begin plr.GiveItem(ITEM_ARMOR_GREEN); g_Console_Add('player got a security armor'); continue; end;
4487 if cmd = 'bluearmor' then begin plr.GiveItem(ITEM_ARMOR_BLUE); g_Console_Add('player got a combat armor'); continue; end;
4489 if (cmd = 'megasphere') or (cmd = 'mega') then begin plr.GiveItem(ITEM_SPHERE_BLUE); g_Console_Add('player got a megasphere'); continue; end;
4490 if (cmd = 'soulsphere') or (cmd = 'soul')then begin plr.GiveItem(ITEM_SPHERE_WHITE); g_Console_Add('player got a soul sphere'); continue; end;
4492 if (cmd = 'invul') or (cmd = 'invulnerability') then begin plr.GiveItem(ITEM_INVUL); g_Console_Add('player got invulnerability'); continue; end;
4493 if (cmd = 'invis') or (cmd = 'invisibility') then begin plr.GiveItem(ITEM_INVIS); g_Console_Add('player got invisibility'); continue; end;
4495 if cmd = 'redkey' then begin plr.GiveItem(ITEM_KEY_RED); g_Console_Add('player got the red key'); continue; end;
4496 if cmd = 'greenkey' then begin plr.GiveItem(ITEM_KEY_GREEN); g_Console_Add('player got the green key'); continue; end;
4497 if cmd = 'bluekey' then begin plr.GiveItem(ITEM_KEY_BLUE); g_Console_Add('player got the blue key'); continue; end;
4499 if (cmd = 'shotgun') or (cmd = 'sg') then begin plr.GiveItem(ITEM_WEAPON_SHOTGUN1); g_Console_Add('player got a shotgun'); continue; end;
4500 if (cmd = 'supershotgun') or (cmd = 'ssg') then begin plr.GiveItem(ITEM_WEAPON_SHOTGUN2); g_Console_Add('player got a supershotgun'); continue; end;
4501 if cmd = 'chaingun' then begin plr.GiveItem(ITEM_WEAPON_CHAINGUN); g_Console_Add('player got a chaingun'); continue; end;
4502 if (cmd = 'launcher') or (cmd = 'rocketlauncher') or (cmd = 'rl') then begin plr.GiveItem(ITEM_WEAPON_ROCKETLAUNCHER); g_Console_Add('player got a rocket launcher'); continue; end;
4503 if cmd = 'plasmagun' then begin plr.GiveItem(ITEM_WEAPON_PLASMA); g_Console_Add('player got a plasma gun'); continue; end;
4504 if cmd = 'bfg' then begin plr.GiveItem(ITEM_WEAPON_BFG); g_Console_Add('player got a BFG-9000'); continue; end;
4506 if (cmd = 'shotgunzz') or (cmd = 'sgzz') then begin plr.GiveItem(ITEM_WEAPON_SHOTGUN1); plr.GiveItem(ITEM_AMMO_SHELLS_BOX); g_Console_Add('player got a shotgun'); continue; end;
4507 if (cmd = 'supershotgunzz') or (cmd = 'ssgzz') then begin plr.GiveItem(ITEM_WEAPON_SHOTGUN2); plr.GiveItem(ITEM_AMMO_SHELLS_BOX); g_Console_Add('player got a supershotgun'); continue; end;
4508 if cmd = 'chaingunzz' then begin plr.GiveItem(ITEM_WEAPON_CHAINGUN); plr.GiveItem(ITEM_AMMO_BULLETS_BOX); g_Console_Add('player got a chaingun'); continue; end;
4509 if (cmd = 'launcherzz') or (cmd = 'rocketlauncherzz') or (cmd = 'rlzz') then begin plr.GiveItem(ITEM_WEAPON_ROCKETLAUNCHER); plr.GiveItem(ITEM_AMMO_ROCKET_BOX); g_Console_Add('player got a rocket launcher'); continue; end;
4510 if cmd = 'plasmagunzz' then begin plr.GiveItem(ITEM_WEAPON_PLASMA); plr.GiveItem(ITEM_AMMO_CELL_BIG); g_Console_Add('player got a plasma gun'); continue; end;
4511 if cmd = 'bfgzz' then begin plr.GiveItem(ITEM_WEAPON_BFG); plr.GiveItem(ITEM_AMMO_CELL_BIG); g_Console_Add('player got a BFG-9000'); continue; end;
4513 if cmd = 'superchaingun' then begin plr.GiveItem(ITEM_WEAPON_SUPERPULEMET); g_Console_Add('player got a superchaingun'); continue; end;
4514 if cmd = 'superchaingunzz' then begin plr.GiveItem(ITEM_WEAPON_SUPERPULEMET); plr.GiveItem(ITEM_AMMO_BULLETS_BOX); g_Console_Add('player got a superchaingun'); continue; end;
4516 if (cmd = 'flamer') or (cmd = 'flamethrower') or (cmd = 'ft') then begin plr.GiveItem(ITEM_WEAPON_FLAMETHROWER); g_Console_Add('player got a flame thrower'); continue; end;
4517 if (cmd = 'flamerzz') or (cmd = 'flamethrowerzz') or (cmd = 'ftzz') then begin plr.GiveItem(ITEM_WEAPON_FLAMETHROWER); plr.GiveItem(ITEM_AMMO_FUELCAN); g_Console_Add('player got a flame thrower'); continue; end;
4519 if cmd = 'chainsaw' then begin plr.GiveItem(ITEM_WEAPON_SAW); g_Console_Add('player got a chainsaw'); continue; end;
4521 if cmd = 'ammo' then
4522 begin
4523 plr.GiveItem(ITEM_AMMO_SHELLS_BOX);
4524 plr.GiveItem(ITEM_AMMO_BULLETS_BOX);
4525 plr.GiveItem(ITEM_AMMO_CELL_BIG);
4526 plr.GiveItem(ITEM_AMMO_ROCKET_BOX);
4527 plr.GiveItem(ITEM_AMMO_FUELCAN);
4528 g_Console_Add('player got some ammo');
4529 continue;
4530 end;
4532 if cmd = 'clip' then begin plr.GiveItem(ITEM_AMMO_BULLETS); g_Console_Add('player got some bullets'); continue; end;
4533 if cmd = 'bullets' then begin plr.GiveItem(ITEM_AMMO_BULLETS_BOX); g_Console_Add('player got a box of bullets'); continue; end;
4535 if cmd = 'shells' then begin plr.GiveItem(ITEM_AMMO_SHELLS); g_Console_Add('player got some shells'); continue; end;
4536 if cmd = 'shellbox' then begin plr.GiveItem(ITEM_AMMO_SHELLS_BOX); g_Console_Add('player got a box of shells'); continue; end;
4538 if cmd = 'cells' then begin plr.GiveItem(ITEM_AMMO_CELL); g_Console_Add('player got some cells'); continue; end;
4539 if cmd = 'battery' then begin plr.GiveItem(ITEM_AMMO_CELL_BIG); g_Console_Add('player got cell battery'); continue; end;
4541 if cmd = 'rocket' then begin plr.GiveItem(ITEM_AMMO_ROCKET); g_Console_Add('player got a rocket'); continue; end;
4542 if cmd = 'rocketbox' then begin plr.GiveItem(ITEM_AMMO_ROCKET_BOX); g_Console_Add('player got some rockets'); continue; end;
4544 if (cmd = 'fuel') or (cmd = 'fuelcan') then begin plr.GiveItem(ITEM_AMMO_FUELCAN); g_Console_Add('player got fuel canister'); continue; end;
4546 if cmd = 'weapons' then
4547 begin
4548 plr.GiveItem(ITEM_WEAPON_SHOTGUN1);
4549 plr.GiveItem(ITEM_WEAPON_SHOTGUN2);
4550 plr.GiveItem(ITEM_WEAPON_CHAINGUN);
4551 plr.GiveItem(ITEM_WEAPON_ROCKETLAUNCHER);
4552 plr.GiveItem(ITEM_WEAPON_PLASMA);
4553 plr.GiveItem(ITEM_WEAPON_BFG);
4554 g_Console_Add('player got weapons');
4555 continue;
4556 end;
4558 if cmd = 'keys' then
4559 begin
4560 plr.GiveItem(ITEM_KEY_RED);
4561 plr.GiveItem(ITEM_KEY_GREEN);
4562 plr.GiveItem(ITEM_KEY_BLUE);
4563 g_Console_Add('player got all keys');
4564 continue;
4565 end;
4567 g_Console_Add('i don''t know how to give '''+cmd+'''!');
4568 end;
4569 exit;
4570 end;
4571 // open
4572 if cmd = 'open' then
4573 begin
4574 g_Console_Add('player activated sesame');
4575 g_Triggers_OpenAll();
4576 exit;
4577 end;
4578 // fly
4579 if cmd = 'fly' then
4580 begin
4581 gFly := not gFly;
4582 if gFly then g_Console_Add('player feels himself lighter') else g_Console_Add('player lost his wings');
4583 exit;
4584 end;
4585 // noclip
4586 if cmd = 'noclip' then
4587 begin
4588 plr.SwitchNoClip;
4589 g_Console_Add('wall hardeness adjusted');
4590 exit;
4591 end;
4592 // notarget
4593 if cmd = 'notarget' then
4594 begin
4595 plr.NoTarget := not plr.NoTarget;
4596 if plr.NoTarget then g_Console_Add('player hides in shadows') else g_Console_Add('player is brave again');
4597 exit;
4598 end;
4599 // noreload
4600 if cmd = 'noreload' then
4601 begin
4602 plr.NoReload := not plr.NoReload;
4603 if plr.NoReload then g_Console_Add('player is action hero now') else g_Console_Add('player is ordinary man now');
4604 exit;
4605 end;
4606 // speedy
4607 if cmd = 'speedy' then
4608 begin
4609 MAX_RUNVEL := 32-MAX_RUNVEL;
4610 g_Console_Add('speed adjusted');
4611 exit;
4612 end;
4613 // jumpy
4614 if cmd = 'jumpy' then
4615 begin
4616 VEL_JUMP := 30-VEL_JUMP;
4617 g_Console_Add('jump height adjusted');
4618 exit;
4619 end;
4620 // automap
4621 if cmd = 'automap' then
4622 begin
4623 gShowMap := not gShowMap;
4624 if gShowMap then g_Console_Add('player gains second sight') else g_Console_Add('player lost second sight');
4625 exit;
4626 end;
4627 // aimline
4628 if cmd = 'aimline' then
4629 begin
4630 gAimLine := not gAimLine;
4631 if gAimLine then g_Console_Add('player gains laser sight') else g_Console_Add('player lost laser sight');
4632 exit;
4633 end;
4634 end;
4636 procedure GameCommands(P: SSArray);
4637 var
4638 a, b: Integer;
4639 s, pw: String;
4640 chstr: string;
4641 cmd: string;
4642 pl: pTNetClient = nil;
4643 plr: TPlayer;
4644 prt: Word;
4645 nm: Boolean;
4646 listen: LongWord;
4647 found: Boolean;
4648 begin
4649 // Общие команды:
4650 cmd := LowerCase(P[0]);
4651 chstr := '';
4652 if cmd = 'pause' then
4653 begin
4654 {$IFDEF ENABLE_MENU}
4655 if (g_ActiveWindow = nil) then
4656 g_Game_Pause(not gPauseMain);
4657 {$ELSE}
4658 g_Game_Pause(not gPauseMain);
4659 {$ENDIF}
4660 end
4661 else if cmd = 'endgame' then
4662 gExit := EXIT_SIMPLE
4663 else if cmd = 'restart' then
4664 begin
4665 if gGameOn or (gState in [STATE_INTERSINGLE, STATE_INTERCUSTOM]) then
4666 begin
4667 if g_Game_IsClient then
4668 begin
4669 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4670 Exit;
4671 end;
4672 g_Game_Restart();
4673 end else
4674 g_Console_Add(_lc[I_MSG_NOT_GAME]);
4675 end
4676 else if cmd = 'kick' then
4677 begin
4678 if g_Game_IsServer then
4679 begin
4680 if Length(P) < 2 then
4681 begin
4682 g_Console_Add('kick <name>');
4683 Exit;
4684 end;
4685 if P[1] = '' then
4686 begin
4687 g_Console_Add('kick <name>');
4688 Exit;
4689 end;
4691 if g_Game_IsNet then
4692 pl := g_Net_Client_ByName(P[1]);
4693 if (pl <> nil) then
4694 begin
4695 s := g_Net_ClientName_ByID(pl^.ID);
4696 enet_peer_disconnect(pl^.Peer, NET_DISC_KICK);
4697 g_Console_Add(Format(_lc[I_PLAYER_KICK], [s]));
4698 MH_SEND_GameEvent(NET_EV_PLAYER_KICK, 0, s);
4699 g_Net_Slist_ServerPlayerLeaves();
4700 end else if gPlayers <> nil then
4701 for a := Low(gPlayers) to High(gPlayers) do
4702 if gPlayers[a] <> nil then
4703 if Copy(LowerCase(gPlayers[a].Name), 1, Length(P[1])) = LowerCase(P[1]) then
4704 begin
4705 // Не отключать основных игроков в сингле
4706 if not(gPlayers[a] is TBot) and (gGameSettings.GameType = GT_SINGLE) then
4707 continue;
4708 gPlayers[a].Lives := 0;
4709 gPlayers[a].Kill(K_SIMPLEKILL, 0, HIT_DISCON);
4710 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [gPlayers[a].Name]), True);
4711 g_Player_Remove(gPlayers[a].UID);
4712 g_Net_Slist_ServerPlayerLeaves();
4713 // Если не перемешать, при добавлении новых ботов появятся старые
4714 g_Bot_MixNames();
4715 end;
4716 end else
4717 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
4718 end
4719 else if cmd = 'kick_id' then
4720 begin
4721 if g_Game_IsServer and g_Game_IsNet then
4722 begin
4723 if Length(P) < 2 then
4724 begin
4725 g_Console_Add('kick_id <client ID>');
4726 Exit;
4727 end;
4728 if P[1] = '' then
4729 begin
4730 g_Console_Add('kick_id <client ID>');
4731 Exit;
4732 end;
4734 a := StrToIntDef(P[1], 0);
4735 if (NetClients <> nil) and (a <= High(NetClients)) then
4736 begin
4737 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
4738 begin
4739 s := g_Net_ClientName_ByID(NetClients[a].ID);
4740 enet_peer_disconnect(NetClients[a].Peer, NET_DISC_KICK);
4741 g_Console_Add(Format(_lc[I_PLAYER_KICK], [s]));
4742 MH_SEND_GameEvent(NET_EV_PLAYER_KICK, 0, s);
4743 g_Net_Slist_ServerPlayerLeaves();
4744 end;
4745 end;
4746 end else
4747 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4748 end
4749 else if cmd = 'kick_pid' then
4750 begin
4751 if g_Game_IsServer and g_Game_IsNet then
4752 begin
4753 if Length(P) < 2 then
4754 begin
4755 g_Console_Add('kick_pid <player ID>');
4756 Exit;
4757 end;
4758 if P[1] = '' then
4759 begin
4760 g_Console_Add('kick_pid <player ID>');
4761 Exit;
4762 end;
4764 a := StrToIntDef(P[1], 0);
4765 pl := g_Net_Client_ByPlayer(a);
4766 if (pl <> nil) and pl^.Used and (pl^.Peer <> nil) then
4767 begin
4768 s := g_Net_ClientName_ByID(pl^.ID);
4769 enet_peer_disconnect(pl^.Peer, NET_DISC_KICK);
4770 g_Console_Add(Format(_lc[I_PLAYER_KICK], [s]));
4771 MH_SEND_GameEvent(NET_EV_PLAYER_KICK, 0, s);
4772 g_Net_Slist_ServerPlayerLeaves();
4773 end;
4774 end else
4775 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4776 end
4777 else if cmd = 'ban' then
4778 begin
4779 if g_Game_IsServer and g_Game_IsNet then
4780 begin
4781 if Length(P) < 2 then
4782 begin
4783 g_Console_Add('ban <name>');
4784 Exit;
4785 end;
4786 if P[1] = '' then
4787 begin
4788 g_Console_Add('ban <name>');
4789 Exit;
4790 end;
4792 pl := g_Net_Client_ByName(P[1]);
4793 if (pl <> nil) then
4794 begin
4795 s := g_Net_ClientName_ByID(pl^.ID);
4796 g_Net_BanHost(pl^.Peer^.address.host, False);
4797 enet_peer_disconnect(pl^.Peer, NET_DISC_TEMPBAN);
4798 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4799 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4800 g_Net_Slist_ServerPlayerLeaves();
4801 end else
4802 g_Console_Add(Format(_lc[I_NET_ERR_NAME404], [P[1]]));
4803 end else
4804 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4805 end
4806 else if cmd = 'ban_id' then
4807 begin
4808 if g_Game_IsServer and g_Game_IsNet then
4809 begin
4810 if Length(P) < 2 then
4811 begin
4812 g_Console_Add('ban_id <client ID>');
4813 Exit;
4814 end;
4815 if P[1] = '' then
4816 begin
4817 g_Console_Add('ban_id <client ID>');
4818 Exit;
4819 end;
4821 a := StrToIntDef(P[1], 0);
4822 if (NetClients <> nil) and (a <= High(NetClients)) then
4823 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
4824 begin
4825 s := g_Net_ClientName_ByID(NetClients[a].ID);
4826 g_Net_BanHost(NetClients[a].Peer^.address.host, False);
4827 enet_peer_disconnect(NetClients[a].Peer, NET_DISC_TEMPBAN);
4828 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4829 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4830 g_Net_Slist_ServerPlayerLeaves();
4831 end;
4832 end else
4833 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4834 end
4835 else if cmd = 'ban_pid' then
4836 begin
4837 if g_Game_IsServer and g_Game_IsNet then
4838 begin
4839 if Length(P) < 2 then
4840 begin
4841 g_Console_Add('ban_pid <player ID>');
4842 Exit;
4843 end;
4844 if P[1] = '' then
4845 begin
4846 g_Console_Add('ban_pid <player ID>');
4847 Exit;
4848 end;
4850 a := StrToIntDef(P[1], 0);
4851 pl := g_Net_Client_ByPlayer(a);
4852 if (pl <> nil) and pl^.Used and (pl^.Peer <> nil) then
4853 begin
4854 s := g_Net_ClientName_ByID(pl^.ID);
4855 g_Net_BanHost(pl^.Peer^.address.host, False);
4856 enet_peer_disconnect(pl^.Peer, NET_DISC_TEMPBAN);
4857 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4858 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4859 g_Net_Slist_ServerPlayerLeaves();
4860 end;
4861 end else
4862 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4863 end
4864 else if cmd = 'permban' then
4865 begin
4866 if g_Game_IsServer and g_Game_IsNet then
4867 begin
4868 if Length(P) < 2 then
4869 begin
4870 g_Console_Add('permban <name>');
4871 Exit;
4872 end;
4873 if P[1] = '' then
4874 begin
4875 g_Console_Add('permban <name>');
4876 Exit;
4877 end;
4879 pl := g_Net_Client_ByName(P[1]);
4880 if (pl <> nil) then
4881 begin
4882 s := g_Net_ClientName_ByID(pl^.ID);
4883 g_Net_BanHost(pl^.Peer^.address.host);
4884 enet_peer_disconnect(pl^.Peer, NET_DISC_BAN);
4885 g_Net_SaveBanList();
4886 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4887 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4888 g_Net_Slist_ServerPlayerLeaves();
4889 end else
4890 g_Console_Add(Format(_lc[I_NET_ERR_NAME404], [P[1]]));
4891 end else
4892 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4893 end
4894 else if cmd = 'permban_id' then
4895 begin
4896 if g_Game_IsServer and g_Game_IsNet then
4897 begin
4898 if Length(P) < 2 then
4899 begin
4900 g_Console_Add('permban_id <client ID>');
4901 Exit;
4902 end;
4903 if P[1] = '' then
4904 begin
4905 g_Console_Add('permban_id <client ID>');
4906 Exit;
4907 end;
4909 a := StrToIntDef(P[1], 0);
4910 if (NetClients <> nil) and (a <= High(NetClients)) then
4911 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
4912 begin
4913 s := g_Net_ClientName_ByID(NetClients[a].ID);
4914 g_Net_BanHost(NetClients[a].Peer^.address.host);
4915 enet_peer_disconnect(NetClients[a].Peer, NET_DISC_BAN);
4916 g_Net_SaveBanList();
4917 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4918 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4919 g_Net_Slist_ServerPlayerLeaves();
4920 end;
4921 end else
4922 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4923 end
4924 else if cmd = 'permban_pid' then
4925 begin
4926 if g_Game_IsServer and g_Game_IsNet then
4927 begin
4928 if Length(P) < 2 then
4929 begin
4930 g_Console_Add('permban_pid <player ID>');
4931 Exit;
4932 end;
4933 if P[1] = '' then
4934 begin
4935 g_Console_Add('permban_pid <player ID>');
4936 Exit;
4937 end;
4939 a := StrToIntDef(P[1], 0);
4940 pl := g_Net_Client_ByPlayer(a);
4941 if (pl <> nil) and pl^.Used and (pl^.Peer <> nil) then
4942 begin
4943 s := g_Net_ClientName_ByID(pl^.ID);
4944 g_Net_BanHost(pl^.Peer^.address.host);
4945 enet_peer_disconnect(pl^.Peer, NET_DISC_BAN);
4946 g_Net_SaveBanList();
4947 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4948 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4949 g_Net_Slist_ServerPlayerLeaves();
4950 end;
4951 end else
4952 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4953 end
4954 else if cmd = 'permban_ip' then
4955 begin
4956 if g_Game_IsServer and g_Game_IsNet then
4957 begin
4958 if Length(P) < 2 then
4959 begin
4960 g_Console_Add('permban_ip <IP address>');
4961 Exit;
4962 end;
4963 if P[1] = '' then
4964 begin
4965 g_Console_Add('permban_ip <IP address>');
4966 Exit;
4967 end;
4969 g_Net_BanHost(P[1]);
4970 g_Net_SaveBanList();
4971 g_Console_Add(Format(_lc[I_PLAYER_BAN], [P[1]]));
4972 end else
4973 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4974 end
4975 else if cmd = 'unban' then
4976 begin
4977 if g_Game_IsServer and g_Game_IsNet then
4978 begin
4979 if Length(P) < 2 then
4980 begin
4981 g_Console_Add('unban <IP Address>');
4982 Exit;
4983 end;
4984 if P[1] = '' then
4985 begin
4986 g_Console_Add('unban <IP Address>');
4987 Exit;
4988 end;
4990 if g_Net_UnbanHost(P[1]) then
4991 begin
4992 g_Console_Add(Format(_lc[I_MSG_UNBAN_OK], [P[1]]));
4993 g_Net_SaveBanList();
4994 end else
4995 g_Console_Add(Format(_lc[I_MSG_UNBAN_FAIL], [P[1]]));
4996 end else
4997 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4998 end
4999 else if cmd = 'clientlist' then
5000 begin
5001 if g_Game_IsServer and g_Game_IsNet then
5002 begin
5003 b := 0;
5004 if NetClients <> nil then
5005 for a := Low(NetClients) to High(NetClients) do
5006 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
5007 begin
5008 plr := g_Player_Get(NetClients[a].Player);
5009 if plr = nil then continue;
5010 Inc(b);
5011 g_Console_Add(Format('#%2d: %-15s | %s', [a,
5012 IpToStr(NetClients[a].Peer^.address.host), plr.Name]));
5013 end;
5014 if b = 0 then
5015 g_Console_Add(_lc[I_MSG_NOCLIENTS]);
5016 end else
5017 g_Console_Add(_lc[I_MSG_SERVERONLY]);
5018 end
5019 else if cmd = 'connect' then
5020 begin
5021 if (NetMode = NET_NONE) then
5022 begin
5023 if Length(P) < 2 then
5024 begin
5025 g_Console_Add('connect <IP> [port] [password]');
5026 Exit;
5027 end;
5028 if P[1] = '' then
5029 begin
5030 g_Console_Add('connect <IP> [port] [password]');
5031 Exit;
5032 end;
5034 if Length(P) > 2 then
5035 prt := StrToIntDef(P[2], 25666)
5036 else
5037 prt := 25666;
5039 if Length(P) > 3 then
5040 pw := P[3]
5041 else
5042 pw := '';
5044 g_Game_StartClient(P[1], prt, pw);
5045 end;
5046 end
5047 else if cmd = 'disconnect' then
5048 begin
5049 if (NetMode = NET_CLIENT) then
5050 g_Net_Disconnect();
5051 end
5052 else if cmd = 'reconnect' then
5053 begin
5054 if (NetMode = NET_SERVER) then
5055 Exit;
5057 if (NetMode = NET_CLIENT) then
5058 begin
5059 g_Net_Disconnect();
5060 gExit := EXIT_SIMPLE;
5061 EndGame;
5062 end;
5064 //TODO: Use last successful password to reconnect, instead of ''
5065 g_Game_StartClient(NetClientIP, NetClientPort, '');
5066 end
5067 else if (cmd = 'addbot') or
5068 (cmd = 'bot_add') then
5069 begin
5070 if Length(P) > 2 then
5071 g_Bot_Add(TEAM_NONE, StrToIntDef(P[1], 2), StrToIntDef(P[2], 100))
5072 else if Length(P) > 1 then
5073 g_Bot_Add(TEAM_NONE, StrToIntDef(P[1], 2))
5074 else
5075 g_Bot_Add(TEAM_NONE, 2);
5076 end
5077 else if cmd = 'bot_addlist' then
5078 begin
5079 if Length(P) > 1 then
5080 begin
5081 if Length(P) = 2 then
5082 g_Bot_AddList(TEAM_NONE, P[1], StrToIntDef(P[1], -1))
5083 else if Length(P) = 3 then
5084 g_Bot_AddList(TEAM_NONE, P[1], StrToIntDef(P[1], -1), StrToIntDef(P[2], 100))
5085 else
5086 g_Bot_AddList(IfThen(P[2] = 'red', TEAM_RED, TEAM_BLUE), P[1], StrToIntDef(P[1], -1));
5087 end;
5088 end
5089 else if cmd = 'bot_removeall' then
5090 g_Bot_RemoveAll()
5091 else if cmd = 'chat' then
5092 begin
5093 if g_Game_IsNet then
5094 begin
5095 if Length(P) > 1 then
5096 begin
5097 for a := 1 to High(P) do
5098 chstr := chstr + P[a] + ' ';
5100 if Length(chstr) > 200 then SetLength(chstr, 200);
5102 if Length(chstr) < 1 then
5103 begin
5104 g_Console_Add('chat <text>');
5105 Exit;
5106 end;
5108 chstr := b_Text_Format(chstr);
5109 if g_Game_IsClient then
5110 MC_SEND_Chat(chstr, NET_CHAT_PLAYER)
5111 else
5112 MH_SEND_Chat(gPlayer1Settings.Name + ': ' + chstr, NET_CHAT_PLAYER);
5113 end
5114 else
5115 g_Console_Add('chat <text>');
5116 end else
5117 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
5118 end
5119 else if cmd = 'teamchat' then
5120 begin
5121 if g_Game_IsNet and (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then
5122 begin
5123 if Length(P) > 1 then
5124 begin
5125 for a := 1 to High(P) do
5126 chstr := chstr + P[a] + ' ';
5128 if Length(chstr) > 200 then SetLength(chstr, 200);
5130 if Length(chstr) < 1 then
5131 begin
5132 g_Console_Add('teamchat <text>');
5133 Exit;
5134 end;
5136 chstr := b_Text_Format(chstr);
5137 if g_Game_IsClient then
5138 MC_SEND_Chat(chstr, NET_CHAT_TEAM)
5139 else
5140 MH_SEND_Chat(gPlayer1Settings.Name + ': ' + chstr, NET_CHAT_TEAM,
5141 gPlayer1Settings.Team);
5142 end
5143 else
5144 g_Console_Add('teamchat <text>');
5145 end else
5146 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
5147 end
5148 else if cmd = 'game' then
5149 begin
5150 if gGameSettings.GameType <> GT_NONE then
5151 begin
5152 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
5153 Exit;
5154 end;
5155 if Length(P) = 1 then
5156 begin
5157 g_Console_Add(cmd + ' <WAD> [MAP] [# players]');
5158 Exit;
5159 end;
5160 // game not started yet, load fist map from some wad
5161 found := false;
5162 s := addWadExtension(P[1]);
5163 found := e_FindResource(AllMapDirs, s);
5164 P[1] := s;
5165 if found then
5166 begin
5167 P[1] := ExpandFileName(P[1]);
5168 // if map not choosed then set first map
5169 if Length(P) < 3 then
5170 begin
5171 SetLength(P, 3);
5172 P[2] := g_Game_GetFirstMap(P[1]);
5173 end;
5175 s := P[1] + ':\' + UpperCase(P[2]);
5177 if g_Map_Exist(s) then
5178 begin
5179 // start game
5180 g_Game_Free();
5181 with gGameSettings do
5182 begin
5183 Options := gsGameFlags;
5184 GameMode := g_Game_TextToMode(gsGameMode);
5185 if gSwitchGameMode <> GM_NONE then
5186 GameMode := gSwitchGameMode;
5187 if GameMode = GM_NONE then GameMode := GM_DM;
5188 if GameMode = GM_SINGLE then GameMode := GM_COOP;
5189 b := 1;
5190 if Length(P) >= 4 then
5191 b := StrToIntDef(P[3], 1);
5192 g_Game_StartCustom(s, GameMode, TimeLimit,
5193 GoalLimit, MaxLives, Options, b);
5194 end;
5195 end
5196 else
5197 if P[2] = '' then
5198 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[1]]))
5199 else
5200 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [UpperCase(P[2]), P[1]]));
5201 end else
5202 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]));
5203 end
5204 else if cmd = 'host' then
5205 begin
5206 if gGameSettings.GameType <> GT_NONE then
5207 begin
5208 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
5209 Exit;
5210 end;
5211 if Length(P) < 4 then
5212 begin
5213 g_Console_Add(cmd + ' <listen IP> <port> <WAD> [MAP] [# players]');
5214 Exit;
5215 end;
5216 if not StrToIp(P[1], listen) then
5217 Exit;
5218 prt := StrToIntDef(P[2], 25666);
5220 s := addWadExtension(P[3]);
5221 found := e_FindResource(AllMapDirs, s);
5222 P[3] := s;
5223 if found then
5224 begin
5225 // get first map in wad, if not specified
5226 if Length(P) < 5 then
5227 begin
5228 SetLength(P, 5);
5229 P[4] := g_Game_GetFirstMap(P[1]);
5230 end;
5231 s := P[3] + ':\' + UpperCase(P[4]);
5232 if g_Map_Exist(s) then
5233 begin
5234 // start game
5235 g_Game_Free();
5236 with gGameSettings do
5237 begin
5238 Options := gsGameFlags;
5239 GameMode := g_Game_TextToMode(gsGameMode);
5240 if gSwitchGameMode <> GM_NONE then GameMode := gSwitchGameMode;
5241 if GameMode = GM_NONE then GameMode := GM_DM;
5242 if GameMode = GM_SINGLE then GameMode := GM_COOP;
5243 b := 0;
5244 if Length(P) >= 6 then
5245 b := StrToIntDef(P[5], 0);
5246 g_Game_StartServer(s, GameMode, TimeLimit, GoalLimit, MaxLives, Options, b, listen, prt)
5247 end
5248 end
5249 else
5250 begin
5251 if P[4] = '' then
5252 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[3]]))
5253 else
5254 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [UpperCase(P[4]), P[3]]))
5255 end
5256 end
5257 else
5258 begin
5259 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[3]]))
5260 end
5261 end
5262 else if cmd = 'map' then
5263 begin
5264 if Length(P) = 1 then
5265 begin
5266 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5267 begin
5268 g_Console_Add(cmd + ' <MAP>');
5269 g_Console_Add(cmd + ' <WAD> [MAP]')
5270 end
5271 else
5272 begin
5273 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5274 end
5275 end
5276 else
5277 begin
5278 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5279 begin
5280 if Length(P) < 3 then
5281 begin
5282 // first param is map or wad
5283 s := UpperCase(P[1]);
5284 if g_Map_Exist(gGameSettings.WAD + ':\' + s) then
5285 begin
5286 gExitByTrigger := False;
5287 if gGameOn then
5288 begin
5289 // already in game, finish current map
5290 gNextMap := s;
5291 gExit := EXIT_ENDLEVELCUSTOM;
5292 end
5293 else
5294 begin
5295 // intermission, so change map immediately
5296 g_Game_ChangeMap(s)
5297 end
5298 end
5299 else
5300 begin
5301 s := P[1];
5302 found := e_FindResource(AllMapDirs, s);
5303 P[1] := s;
5304 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [s, 'WAD ' + P[1]]));
5305 if found then
5306 begin
5307 // no such map, found wad
5308 pw := P[1];
5309 SetLength(P, 3);
5310 P[1] := ExpandFileName(pw);
5311 P[2] := g_Game_GetFirstMap(P[1]);
5312 s := P[1] + ':\' + P[2];
5313 if g_Map_Exist(s) then
5314 begin
5315 gExitByTrigger := False;
5316 if gGameOn then
5317 begin
5318 // already in game, finish current map
5319 gNextMap := s;
5320 gExit := EXIT_ENDLEVELCUSTOM
5321 end
5322 else
5323 begin
5324 // intermission, so change map immediately
5325 g_Game_ChangeMap(s)
5326 end
5327 end
5328 else
5329 begin
5330 if P[2] = '' then
5331 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[1]]))
5332 else
5333 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5334 end
5335 end
5336 else
5337 begin
5338 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5339 end
5340 end;
5341 end
5342 else
5343 begin
5344 s := addWadExtension(P[1]);
5345 found := e_FindResource(AllMapDirs, s);
5346 P[1] := s;
5347 if found then
5348 begin
5349 P[2] := UpperCase(P[2]);
5350 s := P[1] + ':\' + P[2];
5351 if g_Map_Exist(s) then
5352 begin
5353 gExitByTrigger := False;
5354 if gGameOn then
5355 begin
5356 gNextMap := s;
5357 gExit := EXIT_ENDLEVELCUSTOM
5358 end
5359 else
5360 begin
5361 g_Game_ChangeMap(s)
5362 end
5363 end
5364 else
5365 begin
5366 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5367 end
5368 end
5369 else
5370 begin
5371 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5372 end
5373 end
5374 end
5375 else
5376 begin
5377 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5378 end
5379 end
5380 end
5381 else if cmd = 'nextmap' then
5382 begin
5383 if not(gGameOn or (gState = STATE_INTERCUSTOM)) then
5384 begin
5385 g_Console_Add(_lc[I_MSG_NOT_GAME])
5386 end
5387 else
5388 begin
5389 nm := True;
5390 if Length(P) = 1 then
5391 begin
5392 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5393 begin
5394 g_Console_Add(cmd + ' <MAP>');
5395 g_Console_Add(cmd + ' <WAD> [MAP]');
5396 end
5397 else
5398 begin
5399 nm := False;
5400 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
5401 end;
5402 end
5403 else
5404 begin
5405 nm := False;
5406 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5407 begin
5408 if Length(P) < 3 then
5409 begin
5410 // first param is map or wad
5411 s := UpperCase(P[1]);
5412 if g_Map_Exist(gGameSettings.WAD + ':\' + s) then
5413 begin
5414 // map founded
5415 gExitByTrigger := False;
5416 gNextMap := s;
5417 nm := True;
5418 end
5419 else
5420 begin
5421 // no such map, found wad
5422 pw := addWadExtension(P[1]);
5423 found := e_FindResource(MapDirs, pw);
5424 if not found then
5425 found := e_FindResource(WadDirs, pw);
5426 P[1] := pw;
5427 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [s, P[1]]));
5428 if found then
5429 begin
5430 // map not specified, select first map
5431 SetLength(P, 3);
5432 P[2] := g_Game_GetFirstMap(P[1]);
5433 s := P[1] + ':\' + P[2];
5434 if g_Map_Exist(s) then
5435 begin
5436 gExitByTrigger := False;
5437 gNextMap := s;
5438 nm := True
5439 end
5440 else
5441 begin
5442 if P[2] = '' then
5443 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[1]]))
5444 else
5445 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5446 end
5447 end
5448 else
5449 begin
5450 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5451 end
5452 end
5453 end
5454 else
5455 begin
5456 // specified two params wad + map
5457 pw := addWadExtension(P[1]);
5458 found := e_FindResource(MapDirs, pw);
5459 if not found then
5460 found := e_FindResource(MapDirs, pw);
5461 P[1] := pw;
5462 if found then
5463 begin
5464 P[2] := UpperCase(P[2]);
5465 s := P[1] + ':\' + P[2];
5466 if g_Map_Exist(s) then
5467 begin
5468 gExitByTrigger := False;
5469 gNextMap := s;
5470 nm := True
5471 end
5472 else
5473 begin
5474 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5475 end
5476 end
5477 else
5478 begin
5479 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5480 end
5481 end
5482 end
5483 else
5484 begin
5485 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5486 end
5487 end;
5488 if nm then
5489 begin
5490 if gNextMap = '' then
5491 g_Console_Add(_lc[I_MSG_NEXTMAP_UNSET])
5492 else
5493 g_Console_Add(Format(_lc[I_MSG_NEXTMAP_SET], [gNextMap]))
5494 end
5495 end
5496 end
5497 else if (cmd = 'endmap') or (cmd = 'goodbye') then
5498 begin
5499 if not gGameOn then
5500 begin
5501 g_Console_Add(_lc[I_MSG_NOT_GAME])
5502 end
5503 else
5504 begin
5505 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5506 begin
5507 gExitByTrigger := False;
5508 // next map not specified, try to find trigger EXIT
5509 if (gNextMap = '') and (gTriggers <> nil) then
5510 begin
5511 for a := 0 to High(gTriggers) do
5512 begin
5513 if gTriggers[a].TriggerType = TRIGGER_EXIT then
5514 begin
5515 gExitByTrigger := True;
5516 //gNextMap := gTriggers[a].Data.MapName;
5517 gNextMap := gTriggers[a].tgcMap;
5518 Break
5519 end
5520 end
5521 end;
5522 if gNextMap = '' then
5523 gNextMap := g_Game_GetNextMap();
5524 if not isWadPath(gNextMap) then
5525 s := gGameSettings.WAD + ':\' + gNextMap
5526 else
5527 s := gNextMap;
5528 if g_Map_Exist(s) then
5529 gExit := EXIT_ENDLEVELCUSTOM
5530 else
5531 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [gNextMap]))
5532 end
5533 else
5534 begin
5535 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5536 end
5537 end
5538 end
5539 else if (cmd = 'event') then
5540 begin
5541 if (Length(P) <= 1) then
5542 begin
5543 for a := 0 to High(gEvents) do
5544 if gEvents[a].Command = '' then
5545 g_Console_Add(gEvents[a].Name + ' <none>')
5546 else
5547 g_Console_Add(gEvents[a].Name + ' "' + gEvents[a].Command + '"');
5548 Exit;
5549 end;
5550 if (Length(P) = 2) then
5551 begin
5552 for a := 0 to High(gEvents) do
5553 if gEvents[a].Name = P[1] then
5554 if gEvents[a].Command = '' then
5555 g_Console_Add(gEvents[a].Name + ' <none>')
5556 else
5557 g_Console_Add(gEvents[a].Name + ' "' + gEvents[a].Command + '"');
5558 Exit;
5559 end;
5560 for a := 0 to High(gEvents) do
5561 if gEvents[a].Name = P[1] then
5562 begin
5563 gEvents[a].Command := '';
5564 for b := 2 to High(P) do
5565 if Pos(' ', P[b]) = 0 then
5566 gEvents[a].Command := gEvents[a].Command + ' ' + P[b]
5567 else
5568 gEvents[a].Command := gEvents[a].Command + ' "' + P[b] + '"';
5569 gEvents[a].Command := Trim(gEvents[a].Command);
5570 Exit;
5571 end;
5572 end
5573 else if cmd = 'suicide' then
5574 begin
5575 if gGameOn then
5576 begin
5577 if g_Game_IsClient then
5578 MC_SEND_CheatRequest(NET_CHEAT_SUICIDE)
5579 else
5580 begin
5581 if gPlayer1 <> nil then
5582 gPlayer1.Damage(SUICIDE_DAMAGE, gPlayer1.UID, 0, 0, HIT_SELF);
5583 if gPlayer2 <> nil then
5584 gPlayer2.Damage(SUICIDE_DAMAGE, gPlayer2.UID, 0, 0, HIT_SELF);
5585 end;
5586 end;
5587 end
5588 else if cmd = 'screenshot' then
5589 begin
5590 {$IFNDEF HEADLESS}
5591 g_TakeScreenShot()
5592 {$ENDIF}
5593 end
5594 else if cmd = 'weapon' then
5595 begin
5596 if Length(p) = 2 then
5597 begin
5598 a := WP_FIRST + StrToInt(p[1]) - 1;
5599 if (a >= WP_FIRST) and (a <= WP_LAST) then
5600 gSelectWeapon[0, a] := True
5601 end
5602 end
5603 else if (cmd = 'p1_weapon') or (cmd = 'p2_weapon') then
5604 begin
5605 if Length(p) = 2 then
5606 begin
5607 a := WP_FIRST + StrToInt(p[1]) - 1;
5608 b := ord(cmd[2]) - ord('1');
5609 if (a >= WP_FIRST) and (a <= WP_LAST) then
5610 gSelectWeapon[b, a] := True
5611 end
5612 end
5613 // Команды Своей игры:
5614 else if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT] then
5615 begin
5616 if cmd = 'bot_addred' then
5617 begin
5618 if Length(P) > 1 then
5619 g_Bot_Add(TEAM_RED, StrToIntDef(P[1], 2))
5620 else
5621 g_Bot_Add(TEAM_RED, 2);
5622 end
5623 else if cmd = 'bot_addblue' then
5624 begin
5625 if Length(P) > 1 then
5626 g_Bot_Add(TEAM_BLUE, StrToIntDef(P[1], 2))
5627 else
5628 g_Bot_Add(TEAM_BLUE, 2);
5629 end
5630 else if cmd = 'spectate' then
5631 begin
5632 if not gGameOn then
5633 Exit;
5634 g_Game_Spectate();
5635 end
5636 else if cmd = 'say' then
5637 begin
5638 if g_Game_IsServer and g_Game_IsNet then
5639 begin
5640 if Length(P) > 1 then
5641 begin
5642 chstr := '';
5643 for a := 1 to High(P) do
5644 chstr := chstr + P[a] + ' ';
5646 if Length(chstr) > 200 then SetLength(chstr, 200);
5648 if Length(chstr) < 1 then
5649 begin
5650 g_Console_Add('say <text>');
5651 Exit;
5652 end;
5654 chstr := b_Text_Format(chstr);
5655 MH_SEND_Chat(chstr, NET_CHAT_PLAYER);
5656 end
5657 else g_Console_Add('say <text>');
5658 end else
5659 g_Console_Add(_lc[I_MSG_SERVERONLY]);
5660 end
5661 else if cmd = 'tell' then
5662 begin
5663 if g_Game_IsServer and g_Game_IsNet then
5664 begin
5665 if (Length(P) > 2) and (P[1] <> '') then
5666 begin
5667 chstr := '';
5668 for a := 2 to High(P) do
5669 chstr := chstr + P[a] + ' ';
5671 if Length(chstr) > 200 then SetLength(chstr, 200);
5673 if Length(chstr) < 1 then
5674 begin
5675 g_Console_Add('tell <playername> <text>');
5676 Exit;
5677 end;
5679 pl := g_Net_Client_ByName(P[1]);
5680 if pl <> nil then
5681 MH_SEND_Chat(b_Text_Format(chstr), NET_CHAT_PLAYER, pl^.ID)
5682 else
5683 g_Console_Add(Format(_lc[I_NET_ERR_NAME404], [P[1]]));
5684 end
5685 else g_Console_Add('tell <playername> <text>');
5686 end else
5687 g_Console_Add(_lc[I_MSG_SERVERONLY]);
5688 end
5689 else if cmd = 'centerprint' then
5690 begin
5691 if (Length(P) > 2) and (P[1] <> '') then
5692 begin
5693 chstr := '';
5694 for a := 2 to High(P) do
5695 chstr := chstr + P[a] + ' ';
5697 if Length(chstr) > 200 then SetLength(chstr, 200);
5699 if Length(chstr) < 1 then
5700 begin
5701 g_Console_Add('centerprint <timeout> <text>');
5702 Exit;
5703 end;
5705 a := StrToIntDef(P[1], 100);
5706 chstr := b_Text_Format(chstr);
5707 g_Game_Message(chstr, a);
5708 if g_Game_IsNet and g_Game_IsServer then
5709 MH_SEND_GameEvent(NET_EV_BIGTEXT, a, chstr);
5710 end
5711 else g_Console_Add('centerprint <timeout> <text>');
5712 end
5713 else if (cmd = 'overtime') and not g_Game_IsClient then
5714 begin
5715 if (Length(P) = 1) or (StrToIntDef(P[1], -1) <= 0) then
5716 Exit;
5717 // Дополнительное время:
5718 gGameSettings.TimeLimit := (gTime - gGameStartTime) div 1000 + Word(StrToIntDef(P[1], 0));
5720 g_Console_Add(Format(_lc[I_MSG_TIME_LIMIT],
5721 [gGameSettings.TimeLimit div 3600,
5722 (gGameSettings.TimeLimit div 60) mod 60,
5723 gGameSettings.TimeLimit mod 60]));
5724 if g_Game_IsNet then MH_SEND_GameSettings;
5725 end
5726 else if (cmd = 'rcon_password') and g_Game_IsClient then
5727 begin
5728 if (Length(P) <= 1) then
5729 g_Console_Add('rcon_password <password>')
5730 else
5731 MC_SEND_RCONPassword(P[1]);
5732 end
5733 else if cmd = 'rcon' then
5734 begin
5735 if g_Game_IsClient then
5736 begin
5737 if Length(P) > 1 then
5738 begin
5739 chstr := '';
5740 for a := 1 to High(P) do
5741 chstr := chstr + P[a] + ' ';
5743 if Length(chstr) > 200 then SetLength(chstr, 200);
5745 if Length(chstr) < 1 then
5746 begin
5747 g_Console_Add('rcon <command>');
5748 Exit;
5749 end;
5751 MC_SEND_RCONCommand(chstr);
5752 end
5753 else g_Console_Add('rcon <command>');
5754 end;
5755 end
5756 else if cmd = 'ready' then
5757 begin
5758 if g_Game_IsServer and (gLMSRespawn = LMS_RESPAWN_WARMUP) then
5759 gLMSRespawnTime := gTime + 100;
5760 end
5761 else if (cmd = 'callvote') and g_Game_IsNet then
5762 begin
5763 if Length(P) > 1 then
5764 begin
5765 chstr := '';
5766 for a := 1 to High(P) do begin
5767 if a > 1 then chstr := chstr + ' ';
5768 chstr := chstr + P[a];
5769 end;
5771 if Length(chstr) > 200 then SetLength(chstr, 200);
5773 if Length(chstr) < 1 then
5774 begin
5775 g_Console_Add('callvote <command>');
5776 Exit;
5777 end;
5779 if g_Game_IsClient then
5780 MC_SEND_Vote(True, chstr)
5781 else
5782 g_Game_StartVote(chstr, gPlayer1Settings.Name);
5783 g_Console_Process('vote', True);
5784 end
5785 else
5786 g_Console_Add('callvote <command>');
5787 end
5788 else if (cmd = 'vote') and g_Game_IsNet then
5789 begin
5790 if g_Game_IsClient then
5791 MC_SEND_Vote(False)
5792 else if gVoteInProgress then
5793 begin
5794 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
5795 a := Floor((NetClientCount+1)/2.0) + 1
5796 else
5797 a := Floor(NetClientCount/2.0) + 1;
5798 if gVoted then
5799 begin
5800 Dec(gVoteCount);
5801 gVoted := False;
5802 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_REVOKED], [gPlayer1Settings.Name, gVoteCount, a]), True);
5803 MH_SEND_VoteEvent(NET_VE_REVOKE, gPlayer1Settings.Name, 'a', gVoteCount, a);
5804 end
5805 else
5806 begin
5807 Inc(gVoteCount);
5808 gVoted := True;
5809 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_VOTE], [gPlayer1Settings.Name, gVoteCount, a]), True);
5810 MH_SEND_VoteEvent(NET_VE_VOTE, gPlayer1Settings.Name, 'a', gVoteCount, a);
5811 g_Game_CheckVote;
5812 end;
5813 end;
5814 end
5815 end;
5816 end;
5818 procedure SystemCommands(P: SSArray);
5819 var
5820 cmd: string;
5821 begin
5822 cmd := LowerCase(P[0]);
5823 case cmd of
5824 'exit', 'quit':
5825 begin
5826 g_Game_Free();
5827 g_Game_Quit();
5828 end;
5829 {$IFNDEF HEADLESS}
5830 'r_reset':
5831 r_Render_Apply;
5832 {$ENDIF}
5833 'r_maxfps':
5834 begin
5835 if Length(p) = 2 then
5836 begin
5837 gMaxFPS := StrToIntDef(p[1], gMaxFPS);
5838 if gMaxFPS > 0 then
5839 gFrameTime := 1000 div gMaxFPS
5840 else
5841 gFrameTime := 0;
5842 end;
5843 e_LogWritefln('r_maxfps %d', [gMaxFPS]);
5844 end;
5845 'g_language':
5846 begin
5847 if Length(p) = 2 then
5848 begin
5849 gAskLanguage := true;
5850 gLanguage := LANGUAGE_ENGLISH;
5851 case LowerCase(p[1]) of
5852 'english':
5853 begin
5854 gAskLanguage := false;
5855 gLanguage := LANGUAGE_ENGLISH;
5856 end;
5857 'russian':
5858 begin
5859 gAskLanguage := false;
5860 gLanguage := LANGUAGE_RUSSIAN;
5861 end;
5862 'ask':
5863 begin
5864 gAskLanguage := true;
5865 gLanguage := LANGUAGE_ENGLISH;
5866 end;
5867 end;
5868 g_Language_Set(gLanguage);
5869 end
5870 else
5871 begin
5872 e_LogWritefln('usage: %s <English|Russian|Ask>', [cmd]);
5873 end
5874 end;
5875 end;
5876 end;
5878 {$IFNDEF HEADLESS}
5879 procedure g_TakeScreenShot(Filename: string = '');
5880 var t: TDateTime; dir, date, name: String;
5881 begin
5882 if e_NoGraphics then
5883 Exit;
5885 dir := e_GetWriteableDir(ScreenshotDirs);
5886 if Filename = '' then
5887 begin
5888 t := Now;
5889 DateTimeToString(date, 'yyyy-mm-dd-hh-nn-ss', t);
5890 Filename := 'screenshot-' + date;
5891 end;
5893 name := e_CatPath(dir, Filename + '.png');
5894 if r_Render_WriteScreenShot(name) then
5895 g_Console_Add(Format(_lc[I_CONSOLE_SCREENSHOT], [name]))
5896 else
5897 g_Console_Add(Format(_lc[I_CONSOLE_ERROR_WRITE], [name]));
5898 end;
5899 {$ENDIF}
5901 {$IFDEF ENABLE_MENU}
5902 procedure g_Game_InGameMenu(Show: Boolean);
5903 begin
5904 if (g_ActiveWindow = nil) and Show then
5905 begin
5906 if gGameSettings.GameType = GT_SINGLE then
5907 g_GUI_ShowWindow('GameSingleMenu')
5908 else
5909 begin
5910 if g_Game_IsClient then
5911 g_GUI_ShowWindow('GameClientMenu')
5912 else
5913 if g_Game_IsNet then
5914 g_GUI_ShowWindow('GameServerMenu')
5915 else
5916 g_GUI_ShowWindow('GameCustomMenu');
5917 end;
5918 g_Sound_PlayEx('MENU_OPEN');
5920 // Пауза при меню только в одиночной игре:
5921 if (not g_Game_IsNet) then
5922 g_Game_Pause(True);
5923 end
5924 else
5925 if (g_ActiveWindow <> nil) and (not Show) then
5926 begin
5927 // Пауза при меню только в одиночной игре:
5928 if (not g_Game_IsNet) then
5929 g_Game_Pause(False);
5930 end;
5931 end;
5932 {$ENDIF}
5934 procedure g_Game_Pause (Enable: Boolean);
5935 var
5936 oldPause: Boolean;
5937 begin
5938 if not gGameOn then exit;
5940 if not (gGameSettings.GameType in [GT_SINGLE, GT_CUSTOM]) then exit;
5942 oldPause := gPause;
5943 gPauseMain := Enable;
5945 if (gPause <> oldPause) then g_Game_PauseAllSounds(gPause);
5946 end;
5948 procedure g_Game_HolmesPause (Enable: Boolean);
5949 var
5950 oldPause: Boolean;
5951 begin
5952 if not gGameOn then exit;
5953 if not (gGameSettings.GameType in [GT_SINGLE, GT_CUSTOM]) then exit;
5955 oldPause := gPause;
5956 gPauseHolmes := Enable;
5958 if (gPause <> oldPause) then g_Game_PauseAllSounds(gPause);
5959 end;
5961 procedure g_Game_PauseAllSounds(Enable: Boolean);
5962 var
5963 i: Integer;
5964 begin
5965 // Триггеры:
5966 if gTriggers <> nil then
5967 for i := 0 to High(gTriggers) do
5968 with gTriggers[i] do
5969 if (TriggerType = TRIGGER_SOUND) and
5970 (Sound <> nil) and
5971 Sound.IsPlaying() then
5972 begin
5973 Sound.Pause(Enable);
5974 end;
5976 // Звуки игроков:
5977 if gPlayers <> nil then
5978 for i := 0 to High(gPlayers) do
5979 if gPlayers[i] <> nil then
5980 gPlayers[i].PauseSounds(Enable);
5982 // Музыка:
5983 if gMusic <> nil then
5984 gMusic.Pause(Enable);
5985 end;
5987 procedure g_Game_StopAllSounds(all: Boolean);
5988 var
5989 i: Integer;
5990 begin
5991 if gTriggers <> nil then
5992 for i := 0 to High(gTriggers) do
5993 with gTriggers[i] do
5994 if (TriggerType = TRIGGER_SOUND) and
5995 (Sound <> nil) then
5996 Sound.Stop();
5998 if gMusic <> nil then
5999 gMusic.Stop();
6001 if all then
6002 e_StopChannels();
6003 end;
6005 procedure g_Game_UpdateTriggerSounds;
6006 var i: Integer;
6007 begin
6008 if gTriggers <> nil then
6009 for i := 0 to High(gTriggers) do
6010 with gTriggers[i] do
6011 if (TriggerType = TRIGGER_SOUND) and (Sound <> nil) and tgcLocal and Sound.IsPlaying() then
6012 Sound.SetCoordsRect(X, Y, Width, Height, tgcVolume / 255.0)
6013 end;
6015 function g_Game_IsWatchedPlayer(UID: Word): Boolean;
6016 begin
6017 Result := False;
6018 if (gPlayer1 <> nil) and (gPlayer1.UID = UID) then
6019 begin
6020 Result := True;
6021 Exit;
6022 end;
6023 if (gPlayer2 <> nil) and (gPlayer2.UID = UID) then
6024 begin
6025 Result := True;
6026 Exit;
6027 end;
6028 if gSpectMode <> SPECT_PLAYERS then
6029 Exit;
6030 if gSpectPID1 = UID then
6031 begin
6032 Result := True;
6033 Exit;
6034 end;
6035 if gSpectViewTwo and (gSpectPID2 = UID) then
6036 begin
6037 Result := True;
6038 Exit;
6039 end;
6040 end;
6042 function g_Game_IsWatchedTeam(Team: Byte): Boolean;
6043 var
6044 Pl: TPlayer;
6045 begin
6046 Result := False;
6047 if (gPlayer1 <> nil) and (gPlayer1.Team = Team) then
6048 begin
6049 Result := True;
6050 Exit;
6051 end;
6052 if (gPlayer2 <> nil) and (gPlayer2.Team = Team) then
6053 begin
6054 Result := True;
6055 Exit;
6056 end;
6057 if gSpectMode <> SPECT_PLAYERS then
6058 Exit;
6059 Pl := g_Player_Get(gSpectPID1);
6060 if (Pl <> nil) and (Pl.Team = Team) then
6061 begin
6062 Result := True;
6063 Exit;
6064 end;
6065 if gSpectViewTwo then
6066 begin
6067 Pl := g_Player_Get(gSpectPID2);
6068 if (Pl <> nil) and (Pl.Team = Team) then
6069 begin
6070 Result := True;
6071 Exit;
6072 end;
6073 end;
6074 end;
6076 procedure g_Game_Message (Msg: string; Time: Word);
6077 begin
6078 MessageText := Msg;
6079 MessageTime := Time;
6080 end;
6082 procedure g_Game_ChatSound(Text: String; Taunt: Boolean = True);
6083 const
6084 punct: Array[0..13] of String =
6085 ('.', ',', ':', ';', '!', '?', '(', ')', '''', '"', '/', '\', '*', '^');
6086 var
6087 i, j: Integer;
6088 ok: Boolean;
6089 fpText: String;
6091 function IsPunctuation(S: String): Boolean;
6092 var
6093 i: Integer;
6094 begin
6095 Result := False;
6096 if Length(S) <> 1 then
6097 Exit;
6098 for i := Low(punct) to High(punct) do
6099 if S = punct[i] then
6100 begin
6101 Result := True;
6102 break;
6103 end;
6104 end;
6105 function FilterPunctuation(S: String): String;
6106 var
6107 i: Integer;
6108 begin
6109 for i := Low(punct) to High(punct) do
6110 S := StringReplace(S, punct[i], ' ', [rfReplaceAll]);
6111 Result := S;
6112 end;
6113 begin
6114 ok := False;
6116 if gUseChatSounds and Taunt and (gChatSounds <> nil) and (Pos(': ', Text) > 0) then
6117 begin
6118 // remove player name
6119 Delete(Text, 1, Pos(': ', Text) + 2 - 1);
6120 // for FullWord check
6121 Text := toLowerCase1251(' ' + Text + ' ');
6122 fpText := FilterPunctuation(Text);
6124 for i := 0 to Length(gChatSounds) - 1 do
6125 begin
6126 ok := True;
6127 for j := 0 to Length(gChatSounds[i].Tags) - 1 do
6128 begin
6129 if gChatSounds[i].FullWord and (not IsPunctuation(gChatSounds[i].Tags[j])) then
6130 ok := Pos(' ' + gChatSounds[i].Tags[j] + ' ', fpText) > 0
6131 else
6132 ok := Pos(gChatSounds[i].Tags[j], Text) > 0;
6133 if not ok then
6134 break;
6135 end;
6136 if ok then
6137 begin
6138 gChatSounds[i].Sound.Play();
6139 break;
6140 end;
6141 end;
6142 end;
6143 if not ok then
6144 g_Sound_PlayEx('SOUND_GAME_RADIO');
6145 end;
6147 procedure g_Game_Announce_GoodShot(SpawnerUID: Word);
6148 var
6149 a: Integer;
6150 begin
6151 case gAnnouncer of
6152 ANNOUNCE_NONE:
6153 Exit;
6154 ANNOUNCE_ME,
6155 ANNOUNCE_MEPLUS:
6156 if not g_Game_IsWatchedPlayer(SpawnerUID) then
6157 Exit;
6158 end;
6159 for a := 0 to 3 do
6160 if goodsnd[a].IsPlaying() then
6161 Exit;
6163 goodsnd[Random(4)].Play();
6164 end;
6166 procedure g_Game_Announce_KillCombo(Param: Integer);
6167 var
6168 UID: Word;
6169 c, n: Byte;
6170 Pl: TPlayer;
6171 Name: String;
6172 begin
6173 UID := Param and $FFFF;
6174 c := Param shr 16;
6175 if c < 2 then
6176 Exit;
6178 Pl := g_Player_Get(UID);
6179 if Pl = nil then
6180 Name := '?'
6181 else
6182 Name := Pl.Name;
6184 case c of
6185 2: begin
6186 n := 0;
6187 g_Console_Add(Format(_lc[I_PLAYER_KILL_2X], [Name]), True);
6188 end;
6189 3: begin
6190 n := 1;
6191 g_Console_Add(Format(_lc[I_PLAYER_KILL_3X], [Name]), True);
6192 end;
6193 4: begin
6194 n := 2;
6195 g_Console_Add(Format(_lc[I_PLAYER_KILL_4X], [Name]), True);
6196 end;
6197 else begin
6198 n := 3;
6199 g_Console_Add(Format(_lc[I_PLAYER_KILL_MX], [Name]), True);
6200 end;
6201 end;
6203 case gAnnouncer of
6204 ANNOUNCE_NONE:
6205 Exit;
6206 ANNOUNCE_ME:
6207 if not g_Game_IsWatchedPlayer(UID) then
6208 Exit;
6209 ANNOUNCE_MEPLUS:
6210 if (not g_Game_IsWatchedPlayer(UID)) and (c < 4) then
6211 Exit;
6212 end;
6214 if killsnd[n].IsPlaying() then
6215 killsnd[n].Stop();
6216 killsnd[n].Play();
6217 end;
6219 procedure g_Game_Announce_BodyKill(SpawnerUID: Word);
6220 var
6221 a: Integer;
6222 begin
6223 case gAnnouncer of
6224 ANNOUNCE_NONE:
6225 Exit;
6226 ANNOUNCE_ME:
6227 if not g_Game_IsWatchedPlayer(SpawnerUID) then
6228 Exit;
6229 end;
6230 for a := 0 to 2 do
6231 if hahasnd[a].IsPlaying() then
6232 Exit;
6234 hahasnd[Random(3)].Play();
6235 end;
6237 procedure g_Game_StartVote(Command, Initiator: string);
6238 var
6239 Need: Integer;
6240 begin
6241 if not gVotesEnabled then Exit;
6242 if gGameSettings.GameType <> GT_SERVER then Exit;
6243 if gVoteInProgress or gVotePassed then
6244 begin
6245 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_INPROGRESS], [gVoteCommand]), True);
6246 MH_SEND_VoteEvent(NET_VE_INPROGRESS, gVoteCommand);
6247 Exit;
6248 end;
6249 gVoteInProgress := True;
6250 gVotePassed := False;
6251 gVoteTimer := gTime + gVoteTimeout * 1000;
6252 gVoteCount := 0;
6253 gVoted := False;
6254 gVoteCommand := Command;
6256 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
6257 Need := Floor((NetClientCount+1)/2.0)+1
6258 else
6259 Need := Floor(NetClientCount/2.0)+1;
6260 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_STARTED], [Initiator, Command, Need]), True);
6261 MH_SEND_VoteEvent(NET_VE_STARTED, Initiator, Command, Need);
6262 end;
6264 procedure g_Game_CheckVote;
6265 var
6266 I, Need: Integer;
6267 begin
6268 if gGameSettings.GameType <> GT_SERVER then Exit;
6269 if not gVoteInProgress then Exit;
6271 if (gTime >= gVoteTimer) then
6272 begin
6273 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
6274 Need := Floor((NetClientCount+1)/2.0) + 1
6275 else
6276 Need := Floor(NetClientCount/2.0) + 1;
6277 if gVoteCount >= Need then
6278 begin
6279 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_PASSED], [gVoteCommand]), True);
6280 MH_SEND_VoteEvent(NET_VE_PASSED, gVoteCommand);
6281 gVotePassed := True;
6282 gVoteCmdTimer := gTime + 5000;
6283 end
6284 else
6285 begin
6286 g_Console_Add(_lc[I_MESSAGE_VOTE_FAILED], True);
6287 MH_SEND_VoteEvent(NET_VE_FAILED);
6288 end;
6289 if NetClients <> nil then
6290 for I := Low(NetClients) to High(NetClients) do
6291 if NetClients[i].Used then
6292 NetClients[i].Voted := False;
6293 gVoteInProgress := False;
6294 gVoted := False;
6295 gVoteCount := 0;
6296 end
6297 else
6298 begin
6299 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
6300 Need := Floor((NetClientCount+1)/2.0) + 1
6301 else
6302 Need := Floor(NetClientCount/2.0) + 1;
6303 if gVoteCount >= Need then
6304 begin
6305 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_PASSED], [gVoteCommand]), True);
6306 MH_SEND_VoteEvent(NET_VE_PASSED, gVoteCommand);
6307 gVoteInProgress := False;
6308 gVotePassed := True;
6309 gVoteCmdTimer := gTime + 5000;
6310 gVoted := False;
6311 gVoteCount := 0;
6312 if NetClients <> nil then
6313 for I := Low(NetClients) to High(NetClients) do
6314 if NetClients[i].Used then
6315 NetClients[i].Voted := False;
6316 end;
6317 end;
6318 end;
6320 procedure g_Game_LoadMapList(FileName: string);
6321 var
6322 ListFile: TextFile;
6323 s: string;
6324 begin
6325 MapList := nil;
6326 MapIndex := -1;
6328 if not FileExists(FileName) then Exit;
6330 AssignFile(ListFile, FileName);
6331 Reset(ListFile);
6332 while not EOF(ListFile) do
6333 begin
6334 ReadLn(ListFile, s);
6336 s := Trim(s);
6337 if s = '' then Continue;
6339 SetLength(MapList, Length(MapList)+1);
6340 MapList[High(MapList)] := s;
6341 end;
6342 CloseFile(ListFile);
6343 end;
6345 procedure g_Game_SetDebugMode();
6346 begin
6347 gDebugMode := True;
6348 // Читы (даже в своей игре):
6349 gCheats := True;
6350 end;
6352 procedure g_Game_SetLoadingText(Text: String; Max: Integer; reWrite: Boolean);
6353 var
6354 i: Word;
6355 begin
6356 if Length(LoadingStat.Msgs) = 0 then
6357 Exit;
6359 with LoadingStat do
6360 begin
6361 if not reWrite then
6362 begin // Переходим на следующую строку или скроллируем:
6363 if NextMsg = Length(Msgs) then
6364 begin // scroll
6365 for i := 0 to High(Msgs)-1 do
6366 Msgs[i] := Msgs[i+1];
6367 end
6368 else
6369 Inc(NextMsg);
6370 end else
6371 if NextMsg = 0 then
6372 Inc(NextMsg);
6374 Msgs[NextMsg-1] := Text;
6375 CurValue := 0;
6376 MaxValue := Max;
6377 ShowCount := 0;
6378 PBarWasHere := false;
6379 end;
6381 {$IFDEF ENABLE_MENU}
6382 g_ActiveWindow := nil;
6383 {$ENDIF}
6385 ProcessLoading(true);
6386 end;
6388 procedure g_Game_StepLoading(Value: Integer = -1);
6389 begin
6390 with LoadingStat do
6391 begin
6392 if Value = -1 then
6393 begin
6394 Inc(CurValue);
6395 Inc(ShowCount);
6396 end
6397 else
6398 CurValue := Value;
6399 if (ShowCount > LOADING_SHOW_STEP) or (Value > -1) then
6400 begin
6401 ShowCount := 0;
6402 ProcessLoading();
6403 end;
6404 end;
6405 end;
6407 procedure g_Game_ClearLoading();
6408 var
6409 len: Word;
6410 begin
6411 with LoadingStat do
6412 begin
6413 CurValue := 0;
6414 MaxValue := 0;
6415 ShowCount := 0;
6416 len := ((gScreenHeight div 3)*2 - 50) div LOADING_INTERLINE;
6417 if len < 1 then len := 1;
6418 SetLength(Msgs, len);
6419 for len := Low(Msgs) to High(Msgs) do
6420 Msgs[len] := '';
6421 NextMsg := 0;
6422 PBarWasHere := false;
6423 end;
6424 end;
6426 procedure Parse_Params(var pars: TParamStrValues);
6427 var
6428 i: Integer;
6429 s: String;
6430 begin
6431 SetLength(pars, 0);
6432 i := 1;
6433 while i <= ParamCount do
6434 begin
6435 s := ParamStr(i);
6436 if (s[1] = '-') and (Length(s) > 1) then
6437 begin
6438 if (s[2] = '-') and (Length(s) > 2) then
6439 begin // Одиночный параметр
6440 SetLength(pars, Length(pars) + 1);
6441 with pars[High(pars)] do
6442 begin
6443 Name := LowerCase(s);
6444 Value := '+';
6445 end;
6446 end
6447 else
6448 if (i < ParamCount) then
6449 begin // Параметр со значением
6450 Inc(i);
6451 SetLength(pars, Length(pars) + 1);
6452 with pars[High(pars)] do
6453 begin
6454 Name := LowerCase(s);
6455 Value := LowerCase(ParamStr(i));
6456 end;
6457 end;
6458 end;
6460 Inc(i);
6461 end;
6462 end;
6464 function Find_Param_Value(var pars: TParamStrValues; aName: String): String;
6465 var
6466 i: Integer;
6467 begin
6468 Result := '';
6469 for i := 0 to High(pars) do
6470 if pars[i].Name = aName then
6471 begin
6472 Result := pars[i].Value;
6473 Break;
6474 end;
6475 end;
6477 procedure g_Game_Process_Params();
6478 var
6479 pars: TParamStrValues;
6480 map: String;
6481 GMode, n: Byte;
6482 LimT, LimS: Integer;
6483 Opt: LongWord;
6484 Lives: Integer;
6485 s: String;
6486 Port: Integer;
6487 ip: String;
6488 F: TextFile;
6489 begin
6490 Parse_Params(pars);
6492 // Debug mode:
6493 s := Find_Param_Value(pars, '--debug');
6494 if (s <> '') then
6495 begin
6496 g_Game_SetDebugMode();
6497 s := Find_Param_Value(pars, '--netdump');
6498 if (s <> '') then
6499 NetDump := True;
6500 end;
6502 // Connect when game loads
6503 ip := Find_Param_Value(pars, '-connect');
6505 if ip <> '' then
6506 begin
6507 s := Find_Param_Value(pars, '-port');
6508 if (s = '') or not TryStrToInt(s, Port) then
6509 Port := 25666;
6511 s := Find_Param_Value(pars, '-pw');
6513 g_Game_StartClient(ip, Port, s);
6514 Exit;
6515 end;
6517 s := LowerCase(Find_Param_Value(pars, '-dbg-mainwad'));
6518 if (s <> '') then
6519 begin
6520 gDefaultMegawadStart := s;
6521 end;
6523 if (Find_Param_Value(pars, '--dbg-mainwad-restore') <> '') or
6524 (Find_Param_Value(pars, '--dbg-mainwad-default') <> '') then
6525 begin
6526 gDefaultMegawadStart := DF_Default_Megawad_Start;
6527 end;
6529 // Start map when game loads:
6530 map := LowerCase(Find_Param_Value(pars, '-map'));
6531 if isWadPath(map) then
6532 begin
6533 // Game mode:
6534 s := Find_Param_Value(pars, '-gm');
6535 GMode := g_Game_TextToMode(s);
6536 if GMode = GM_NONE then GMode := GM_DM;
6537 if GMode = GM_SINGLE then GMode := GM_COOP;
6539 // Time limit:
6540 s := Find_Param_Value(pars, '-limt');
6541 if (s = '') or (not TryStrToInt(s, LimT)) then
6542 LimT := 0;
6543 if LimT < 0 then
6544 LimT := 0;
6546 // Goal limit:
6547 s := Find_Param_Value(pars, '-lims');
6548 if (s = '') or (not TryStrToInt(s, LimS)) then
6549 LimS := 0;
6550 if LimS < 0 then
6551 LimS := 0;
6553 // Lives limit:
6554 s := Find_Param_Value(pars, '-lives');
6555 if (s = '') or (not TryStrToInt(s, Lives)) then
6556 Lives := 0;
6557 if Lives < 0 then
6558 Lives := 0;
6560 // Options:
6561 s := Find_Param_Value(pars, '-opt');
6562 if (s = '') then
6563 Opt := gsGameFlags
6564 else
6565 Opt := StrToIntDef(s, 0);
6567 // Close after map:
6568 s := Find_Param_Value(pars, '--close');
6569 if (s <> '') then
6570 gMapOnce := True;
6572 // Override map to test:
6573 s := LowerCase(Find_Param_Value(pars, '-testmap'));
6574 if s <> '' then
6575 begin
6576 if e_IsValidResourceName(s) then
6577 e_FindResource(AllMapDirs, s);
6578 gTestMap := ExpandFileName(s);
6579 end;
6581 // Delete test map after play:
6582 s := Find_Param_Value(pars, '--testdelete');
6583 if (s <> '') then
6584 begin
6585 //gMapToDelete := MapsDir + map;
6586 e_WriteLog('"--testdelete" is deprecated, use --tempdelete.', TMsgType.Fatal);
6587 Halt(1);
6588 end;
6590 // Delete temporary WAD after play:
6591 s := Find_Param_Value(pars, '--tempdelete');
6592 if (s <> '') and (gTestMap <> '') then
6593 begin
6594 gMapToDelete := gTestMap;
6595 gTempDelete := True;
6596 end;
6598 // Number of players:
6599 s := Find_Param_Value(pars, '-pl');
6600 if (s = '') then
6601 n := DEFAULT_PLAYERS
6602 else
6603 n := StrToIntDef(s, DEFAULT_PLAYERS);
6605 // Start:
6606 s := Find_Param_Value(pars, '-port');
6607 if (s = '') or not TryStrToInt(s, Port) then
6608 g_Game_StartCustom(map, GMode, LimT, LimS, Lives, Opt, n)
6609 else
6610 g_Game_StartServer(map, GMode, LimT, LimS, Lives, Opt, n, 0, Port);
6611 end;
6613 // Execute script when game loads:
6614 s := Find_Param_Value(pars, '-exec');
6615 if s <> '' then
6616 begin
6617 // if not isWadPath(s) then
6618 // s := GameDir + '/' + s;
6620 {$I-}
6621 AssignFile(F, s);
6622 Reset(F);
6623 if IOResult <> 0 then
6624 begin
6625 e_WriteLog(Format(_lc[I_SIMPLE_ERROR], ['Failed to read file: ' + s]), TMsgType.Warning);
6626 g_Console_Add(Format(_lc[I_CONSOLE_ERROR_READ], [s]));
6627 CloseFile(F);
6628 Exit;
6629 end;
6630 e_WriteLog('Executing script: ' + s, TMsgType.Notify);
6631 g_Console_Add(Format(_lc[I_CONSOLE_EXEC], [s]));
6633 while not EOF(F) do
6634 begin
6635 ReadLn(F, s);
6636 if IOResult <> 0 then
6637 begin
6638 e_WriteLog(Format(_lc[I_SIMPLE_ERROR], ['Failed to read file: ' + s]), TMsgType.Warning);
6639 g_Console_Add(Format(_lc[I_CONSOLE_ERROR_READ], [s]));
6640 CloseFile(F);
6641 Exit;
6642 end;
6643 if Pos('#', s) <> 1 then // script comment
6644 g_Console_Process(s, True);
6645 end;
6647 CloseFile(F);
6648 {$I+}
6649 end;
6651 SetLength(pars, 0);
6652 end;
6654 begin
6655 conRegVar('pf_draw_frame', @g_profile_frame_draw, 'draw frame rendering profiles', 'render profiles');
6656 //conRegVar('pf_update_frame', @g_profile_frame_update, 'draw frame updating profiles', 'update profiles');
6657 conRegVar('pf_coldet', @g_profile_collision, 'draw collision detection profiles', 'coldet profiles');
6658 conRegVar('pf_los', @g_profile_los, 'draw monster LOS profiles', 'monster LOS profiles');
6660 conRegVar('r_sq_draw', @gdbg_map_use_accel_render, 'accelerated spatial queries in rendering', 'accelerated rendering');
6661 conRegVar('cd_sq_enabled', @gdbg_map_use_accel_coldet, 'accelerated spatial queries in map coldet', 'accelerated map coldet');
6662 conRegVar('mon_sq_enabled', @gmon_debug_use_sqaccel, 'accelerated spatial queries for monsters', 'accelerated monster coldet');
6663 conRegVar('wtrace_sq_enabled', @gwep_debug_fast_trace, 'accelerated spatial queries for weapon hitscan trace', 'accelerated weapon hitscan');
6665 {$IFDEF ENABLE_GFX}
6666 conRegVar('pr_enabled', @gpart_dbg_enabled, 'enable/disable particles', 'particles');
6667 conRegVar('pr_phys_enabled', @gpart_dbg_phys_enabled, 'enable/disable particle physics', 'particle physics');
6668 {$ENDIF}
6670 conRegVar('los_enabled', @gmon_dbg_los_enabled, 'enable/disable monster LOS calculations', 'monster LOS', true);
6671 conRegVar('mon_think', @gmon_debug_think, 'enable/disable monster thinking', 'monster thinking', true);
6673 {$IFDEF ENABLE_HOLMES}
6674 conRegVar('dbg_holmes', @g_holmes_enabled, 'enable/disable Holmes', 'Holmes', true);
6675 {$ENDIF}
6677 conRegVar('dbg_ignore_level_bounds', @g_dbg_ignore_bounds, 'ignore level bounds', '', false);
6679 conRegVar('light_enabled', @gwin_k8_enable_light_experiments, 'enable/disable dynamic lighting', 'lighting');
6680 conRegVar('light_player_halo', @g_playerLight, 'enable/disable player halo', 'player light halo');
6682 conRegVar('r_smallmap_align_h', @r_smallmap_h, 'halign: 0: left; 1: center; 2: right', 'horizontal aligning of small maps');
6683 conRegVar('r_smallmap_align_v', @r_smallmap_v, 'valign: 0: top; 1: center; 2: bottom', 'vertial aligning of small maps');
6685 conRegVar('r_showfps', @gShowFPS, 'draw fps counter', 'draw fps counter');
6686 conRegVar('r_showtime', @gShowTime, 'show game time', 'show game time');
6687 conRegVar('r_showping', @gShowPing, 'show ping', 'show ping');
6688 conRegVar('r_showscore', @gShowGoals, 'show score', 'show score');
6689 conRegVar('r_showkillmsg', @gShowKillMsg, 'show kill log', 'show kill log');
6690 conRegVar('r_showlives', @gShowLives, 'show lives', 'show lives');
6691 conRegVar('r_showspect', @gSpectHUD, 'show spectator hud', 'show spectator hud');
6692 conRegVar('r_showstat', @gShowStat, 'show stats', 'show stats');
6693 conRegVar('r_showpids', @gShowPIDs, 'show PIDs', 'show PIDs');
6694 end.