DEADSOFTWARE

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