DEADSOFTWARE

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