DEADSOFTWARE

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