DEADSOFTWARE

a6e1dabcd1e197b05ed9b19e2a1f867dae033410
[d2df-sdl.git] / src / game / g_map.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 {$DEFINE MAP_DEBUG_ENABLED_FLAG}
17 unit g_map;
19 interface
21 uses
22 SysUtils, Classes, mempool,
23 g_base, r_graphics, g_basic, MAPDEF, g_textures,
24 g_phys, utils, g_panel, g_grid, md5, binheap, xprofiler, xparser, xdynrec;
26 type
27 TMapInfo = record
28 Map: String;
29 Name: String;
30 Description: String;
31 Author: String;
32 MusicName: String;
33 SkyName: String;
34 Height: Word;
35 Width: Word;
36 end;
38 PRespawnPoint = ^TRespawnPoint;
39 TRespawnPoint = record
40 X, Y: Integer;
41 Direction: TDirection;
42 PointType: Byte;
43 end;
45 PFlagPoint = ^TFlagPoint;
46 TFlagPoint = TRespawnPoint;
48 PFlag = ^TFlag;
49 TFlag = record
50 Obj: TObj;
51 RespawnType: Byte;
52 State: Byte;
53 Count: Integer;
54 CaptureTime: LongWord;
55 Animation: TAnimation;
56 Direction: TDirection;
57 end;
59 function g_Map_Load(Res: String): Boolean;
60 function g_Map_GetMapInfo(Res: String): TMapInfo;
61 function g_Map_GetMapsList(WADName: String): SSArray;
62 function g_Map_Exist(Res: String): Boolean;
63 procedure g_Map_Free(freeTextures: Boolean=true);
64 procedure g_Map_Update();
66 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
68 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word;
69 PanelType: Word; b1x3: Boolean=false): Boolean;
70 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
72 procedure g_Map_EnableWallGUID (pguid: Integer);
73 procedure g_Map_DisableWallGUID (pguid: Integer);
74 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
76 // HACK!!!
77 procedure g_Map_EnableWall_XXX (ID: DWORD);
78 procedure g_Map_DisableWall_XXX (ID: DWORD);
79 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer);
81 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
83 procedure g_Map_ReAdd_DieTriggers();
84 function g_Map_IsSpecialTexture(Texture: String): Boolean;
86 function g_Map_GetPoint(PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
87 function g_Map_GetPointCount(PointType: Byte): Word;
88 function g_Map_GetRandomPointType(): Byte;
90 function g_Map_HaveFlagPoints(): Boolean;
92 procedure g_Map_ResetFlag(Flag: Byte);
94 procedure g_Map_SaveState (st: TStream);
95 procedure g_Map_LoadState (st: TStream);
97 // returns panel or nil
98 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
99 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
101 // returns panel or nil
102 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
103 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
105 type
106 TForEachPanelCB = function (pan: TPanel): Boolean is nested; // return `true` to stop
108 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
109 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
111 // trace liquid, stepping by `dx` and `dy`
112 // return last seen liquid coords, and `false` if we're started outside of the liquid
113 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
116 // return `true` from `cb` to stop
117 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
119 procedure g_Map_NetSendInterestingPanels (); // yay!
122 procedure g_Map_ProfilersBegin ();
123 procedure g_Map_ProfilersEnd ();
126 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
129 function g_Map_MinX (): Integer; inline;
130 function g_Map_MinY (): Integer; inline;
131 function g_Map_MaxX (): Integer; inline;
132 function g_Map_MaxY (): Integer; inline;
134 const
135 NNF_NO_NAME = 0;
136 NNF_NAME_BEFORE = 1;
137 NNF_NAME_EQUALS = 2;
138 NNF_NAME_AFTER = 3;
140 function g_Texture_NumNameFindStart(name: String): Boolean;
141 function g_Texture_NumNameFindNext(var newName: String): Byte;
143 const
144 RESPAWNPOINT_PLAYER1 = 1;
145 RESPAWNPOINT_PLAYER2 = 2;
146 RESPAWNPOINT_DM = 3;
147 RESPAWNPOINT_RED = 4;
148 RESPAWNPOINT_BLUE = 5;
150 FLAG_NONE = 0;
151 FLAG_RED = 1;
152 FLAG_BLUE = 2;
153 FLAG_DOM = 3;
155 FLAG_STATE_NONE = 0;
156 FLAG_STATE_NORMAL = 1;
157 FLAG_STATE_DROPPED = 2;
158 FLAG_STATE_CAPTURED = 3;
159 FLAG_STATE_SCORED = 4; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
160 FLAG_STATE_RETURNED = 5; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
162 FLAG_TIME = 720; // 20 seconds
164 SKY_STRETCH: Single = 1.5;
166 const
167 GridTagInvalid = 0;
169 (* draw order:
170 PANEL_BACK
171 PANEL_STEP
172 PANEL_WALL
173 PANEL_CLOSEDOOR
174 PANEL_ACID1
175 PANEL_ACID2
176 PANEL_WATER
177 PANEL_FORE
178 *)
179 // sorted by draw priority
180 GridTagBack = 1 shl 0; // gRenderBackgrounds
181 GridTagStep = 1 shl 1; // gSteps
182 GridTagWall = 1 shl 2; // gWalls
183 GridTagDoor = 1 shl 3; // gWalls
184 GridTagAcid1 = 1 shl 4; // gAcid1
185 GridTagAcid2 = 1 shl 5; // gAcid2
186 GridTagWater = 1 shl 6; // gWater
187 GridTagFore = 1 shl 7; // gRenderForegrounds
188 // the following are invisible
189 GridTagLift = 1 shl 8; // gLifts
190 GridTagBlockMon = 1 shl 9; // gBlockMon
192 GridTagSolid = (GridTagWall or GridTagDoor);
193 GridTagObstacle = (GridTagStep or GridTagWall or GridTagDoor);
194 GridTagLiquid = (GridTagAcid1 or GridTagAcid2 or GridTagWater);
196 GridDrawableMask = (GridTagBack or GridTagStep or GridTagWall or GridTagDoor or GridTagAcid1 or GridTagAcid2 or GridTagWater or GridTagFore);
199 type
200 TBinHeapPanelDrawCmp = class
201 public
202 class function less (const a, b: TPanel): Boolean; inline;
203 end;
205 TBinHeapPanelDraw = specialize TBinaryHeapBase<TPanel, TBinHeapPanelDrawCmp>;
207 var
208 gWalls: TPanelArray;
209 gRenderBackgrounds: TPanelArray;
210 gRenderForegrounds: TPanelArray;
211 gWater, gAcid1, gAcid2: TPanelArray;
212 gSteps: TPanelArray;
213 gLifts: TPanelArray;
214 gBlockMon: TPanelArray;
215 gFlags: array [FLAG_RED..FLAG_BLUE] of TFlag;
216 //gDOMFlags: array of TFlag;
217 gMapInfo: TMapInfo;
218 gBackSize: TDFPoint;
219 gDoorMap: array of array of DWORD;
220 gLiftMap: array of array of DWORD;
221 gWADHash: TMD5Digest;
222 BackID: DWORD = DWORD(-1);
223 gExternalResources: array of TDiskFileInfo = nil;
224 gMovingWallIds: array of Integer = nil;
226 gdbg_map_use_accel_render: Boolean = true;
227 gdbg_map_use_accel_coldet: Boolean = true;
228 profMapCollision: TProfiler = nil; //WARNING: FOR DEBUGGING ONLY!
229 gDrawPanelList: TBinHeapPanelDraw = nil; // binary heap of all walls we have to render, populated by `g_Map_CollectDrawPanels()`
231 gCurrentMap: TDynRecord = nil;
232 gCurrentMapFileName: AnsiString = ''; // so we can skip texture reloading
233 gTestMap: String = '';
236 function panelTypeToTag (panelType: Word): Integer; // returns GridTagXXX
239 type
240 TPanelGrid = specialize TBodyGridBase<TPanel>;
242 var
243 mapGrid: TPanelGrid = nil; // DO NOT USE! public for debugging only!
246 implementation
248 uses
249 {$INCLUDE ../nogl/noGLuses.inc}
250 e_input, g_main, e_log, e_texture, e_res, g_items, g_gfx, g_console,
251 g_weapons, g_game, g_sound, e_sound, CONFIG,
252 g_options, g_triggers, g_player,
253 Math, g_monsters, g_saveload, g_language, g_netmsg,
254 sfs, xstreams, hashtable, wadreader,
255 ImagingTypes, Imaging, ImagingUtility,
256 ImagingGif, ImagingNetworkGraphics,
257 g_res_downloader;
259 const
260 FLAGRECT: TRectWH = (X:15; Y:12; Width:33; Height:52);
261 MUSIC_SIGNATURE = $4953554D; // 'MUSI'
262 FLAG_SIGNATURE = $47414C46; // 'FLAG'
265 // ////////////////////////////////////////////////////////////////////////// //
266 procedure mapWarningCB (const msg: AnsiString; line, col: Integer);
267 begin
268 if (line > 0) then
269 begin
270 e_LogWritefln('parse error at (%s,%s): %s', [line, col, msg], TMsgType.Warning);
271 end
272 else
273 begin
274 e_LogWritefln('parse error: %s', [msg], TMsgType.Warning);
275 end;
276 end;
279 // ////////////////////////////////////////////////////////////////////////// //
280 var
281 panByGUID: array of TPanel = nil;
284 // ////////////////////////////////////////////////////////////////////////// //
285 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
286 begin
287 //if (panByGUID = nil) or (not panByGUID.get(aguid, result)) then result := nil;
288 if (aguid >= 0) and (aguid < Length(panByGUID)) then result := panByGUID[aguid] else result := nil;
289 end;
292 // return `true` from `cb` to stop
293 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
294 var
295 pan: TPanel;
296 begin
297 result := nil;
298 if not assigned(cb) then exit;
299 for pan in panByGUID do
300 begin
301 if cb(pan) then begin result := pan; exit; end;
302 end;
303 end;
306 procedure g_Map_NetSendInterestingPanels ();
307 var
308 pan: TPanel;
309 begin
310 if g_Game_IsServer and g_Game_IsNet then
311 begin
312 for pan in panByGUID do
313 begin
314 if pan.gncNeedSend then MH_SEND_PanelState(pan.guid);
315 end;
316 end;
317 end;
320 // ////////////////////////////////////////////////////////////////////////// //
321 function g_Map_MinX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0 else result := 0; end;
322 function g_Map_MinY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0 else result := 0; end;
323 function g_Map_MaxX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0+mapGrid.gridWidth-1 else result := 0; end;
324 function g_Map_MaxY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0+mapGrid.gridHeight-1 else result := 0; end;
327 // ////////////////////////////////////////////////////////////////////////// //
328 var
329 dfmapdef: TDynMapDef = nil;
332 procedure loadMapDefinition ();
333 var
334 pr: TTextParser = nil;
335 st: TStream = nil;
336 WAD: TWADFile = nil;
337 begin
338 if (dfmapdef <> nil) then exit;
340 try
341 e_LogWritefln('parsing "mapdef.txt"...', []);
342 st := e_OpenResourceRO(DataDirs, 'mapdef.txt');
343 e_LogWritefln('found local "mapdef.txt"', []);
344 except
345 st := nil;
346 end;
348 if (st = nil) then
349 begin
350 WAD := TWADFile.Create();
351 if not WAD.ReadFile(GameWAD) then
352 begin
353 //raise Exception.Create('cannot load "game.wad"');
354 st := nil;
355 end
356 else
357 begin
358 st := WAD.openFileStream('mapdef.txt');
359 end;
360 end;
362 try
363 if (st = nil) then
364 begin
365 //raise Exception.Create('cannot open "mapdef.txt"');
366 e_LogWriteln('using default "mapdef.txt"...');
367 pr := TStrTextParser.Create(defaultMapDef);
368 end
369 else
370 begin
371 pr := TFileTextParser.Create(st);
372 end;
373 except on e: Exception do
374 begin
375 e_LogWritefln('something is VERY wrong here! -- ', [e.message]);
376 raise;
377 end;
378 end;
380 try
381 dfmapdef := TDynMapDef.Create(pr);
382 except
383 on e: TDynParseException do
384 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
385 on e: Exception do
386 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [pr.tokLine, pr.tokCol, e.message]);
387 end;
389 st.Free();
390 WAD.Free();
391 end;
394 // ////////////////////////////////////////////////////////////////////////// //
395 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
396 var
397 wst: TSFSMemoryChunkStream = nil;
398 begin
399 result := nil;
400 if (dataLen < 4) then exit;
402 if (dfmapdef = nil) then writeln('need to load mapdef');
403 loadMapDefinition();
404 if (dfmapdef = nil) then raise Exception.Create('internal map loader error');
406 wst := TSFSMemoryChunkStream.Create(data, dataLen);
407 try
408 result := dfmapdef.parseMap(wst);
409 except
410 on e: TDynParseException do
411 begin
412 e_LogWritefln('ERROR at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
413 wst.Free();
414 result := nil;
415 exit;
416 end;
417 on e: Exception do
418 begin
419 e_LogWritefln('ERROR: %s', [e.message]);
420 wst.Free();
421 result := nil;
422 exit;
423 end;
424 end;
426 //e_LogWriteln('map parsed.');
427 end;
430 // ////////////////////////////////////////////////////////////////////////// //
431 var
432 NNF_PureName: String; // Èìÿ òåêñòóðû áåç öèôð â êîíöå
433 NNF_PureExt: String; // extension postfix
434 NNF_FirstNum: Integer; // ×èñëî ó íà÷àëüíîé òåêñòóðû
435 NNF_CurrentNum: Integer; // Ñëåäóþùåå ÷èñëî ó òåêñòóðû
438 function g_Texture_NumNameFindStart(name: String): Boolean;
439 var
440 i, j: Integer;
442 begin
443 Result := False;
444 NNF_PureName := '';
445 NNF_PureExt := '';
446 NNF_FirstNum := -1;
447 NNF_CurrentNum := -1;
449 for i := Length(name) downto 1 do
450 if (name[i] = '_') then // "_" - ñèìâîë íà÷àëà íîìåðíîãî ïîñòôèêñà
451 begin
452 if i = Length(name) then
453 begin // Íåò öèôð â êîíöå ñòðîêè
454 Exit;
455 end
456 else
457 begin
458 j := i + 1;
459 while (j <= Length(name)) and (name[j] <> '.') do inc(j);
460 NNF_PureName := Copy(name, 1, i);
461 NNF_PureExt := Copy(name, j);
462 name := Copy(name, i + 1, j - i - 1);
463 Break;
464 end;
465 end;
467 // Íå ïåðåâåñòè â ÷èñëî:
468 if not TryStrToInt(name, NNF_FirstNum) then
469 Exit;
471 NNF_CurrentNum := 0;
473 Result := True;
474 end;
477 function g_Texture_NumNameFindNext(var newName: String): Byte;
478 begin
479 if (NNF_PureName = '') or (NNF_CurrentNum < 0) then
480 begin
481 newName := '';
482 Result := NNF_NO_NAME;
483 Exit;
484 end;
486 newName := NNF_PureName + IntToStr(NNF_CurrentNum) + NNF_PureExt;
488 if NNF_CurrentNum < NNF_FirstNum then
489 Result := NNF_NAME_BEFORE
490 else
491 if NNF_CurrentNum > NNF_FirstNum then
492 Result := NNF_NAME_AFTER
493 else
494 Result := NNF_NAME_EQUALS;
496 Inc(NNF_CurrentNum);
497 end;
500 // ////////////////////////////////////////////////////////////////////////// //
501 function panelTypeToTag (panelType: Word): Integer;
502 begin
503 case panelType of
504 PANEL_WALL: result := GridTagWall; // gWalls
505 PANEL_OPENDOOR, PANEL_CLOSEDOOR: result := GridTagDoor; // gWalls
506 PANEL_BACK: result := GridTagBack; // gRenderBackgrounds
507 PANEL_FORE: result := GridTagFore; // gRenderForegrounds
508 PANEL_WATER: result := GridTagWater; // gWater
509 PANEL_ACID1: result := GridTagAcid1; // gAcid1
510 PANEL_ACID2: result := GridTagAcid2; // gAcid2
511 PANEL_STEP: result := GridTagStep; // gSteps
512 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: result := GridTagLift; // gLifts -- this is for all lifts
513 PANEL_BLOCKMON: result := GridTagBlockMon; // gBlockMon -- this is for all blockmons
514 else result := GridTagInvalid;
515 end;
516 end;
519 class function TBinHeapPanelDrawCmp.less (const a, b: TPanel): Boolean; inline;
520 begin
521 if (a.tag < b.tag) then begin result := true; exit; end;
522 if (a.tag > b.tag) then begin result := false; exit; end;
523 result := (a.arrIdx < b.arrIdx);
524 end;
526 var
527 Textures: TLevelTextureArray = nil;
528 TextNameHash: THashStrInt = nil; // key: texture name; value: index in `Textures`
529 BadTextNameHash: THashStrInt = nil; // set; so we won't spam with non-existing texture messages
530 RespawnPoints: array of TRespawnPoint;
531 FlagPoints: array[FLAG_RED..FLAG_BLUE] of PFlagPoint;
532 //DOMFlagPoints: Array of TFlagPoint;
535 procedure g_Map_ProfilersBegin ();
536 begin
537 if (profMapCollision = nil) then profMapCollision := TProfiler.Create('COLSOLID', g_profile_history_size);
538 if (profMapCollision <> nil) then profMapCollision.mainBegin(g_profile_collision);
539 // create sections
540 if g_profile_collision and (profMapCollision <> nil) then
541 begin
542 profMapCollision.sectionBegin('*solids');
543 profMapCollision.sectionEnd();
544 profMapCollision.sectionBegin('liquids');
545 profMapCollision.sectionEnd();
546 end;
547 end;
549 procedure g_Map_ProfilersEnd ();
550 begin
551 if (profMapCollision <> nil) then profMapCollision.mainEnd();
552 end;
555 // wall index in `gWalls` or -1
556 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
557 var
558 ex, ey: Integer;
559 begin
560 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, (GridTagWall or GridTagDoor));
561 if (result <> nil) then
562 begin
563 if (hitx <> nil) then hitx^ := ex;
564 if (hity <> nil) then hity^ := ey;
565 end
566 else
567 begin
568 if (hitx <> nil) then hitx^ := x1;
569 if (hity <> nil) then hity^ := y1;
570 end;
571 end;
573 // returns panel or nil
574 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
575 var
576 ex, ey: Integer;
577 begin
578 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, tag);
579 if (result <> nil) then
580 begin
581 if (hitx <> nil) then hitx^ := ex;
582 if (hity <> nil) then hity^ := ey;
583 end
584 else
585 begin
586 if (hitx <> nil) then hitx^ := x1;
587 if (hity <> nil) then hity^ := y1;
588 end;
589 end;
592 function xxPanAtPointChecker (pan: TPanel; panelType: Word): Boolean; inline;
593 begin
594 if ((pan.tag and GridTagLift) <> 0) then
595 begin
596 // stop if the lift of the right type
597 result :=
598 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
599 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
600 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
601 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT)));
602 exit;
603 end;
604 result := true; // otherwise, stop anyway, 'cause `forEachAtPoint()` is guaranteed to call this only for correct panels
605 end;
607 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
608 var
609 tagmask: Integer = 0;
610 mwit: PPanel;
611 it: TPanelGrid.Iter;
612 begin
613 result := false;
615 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
616 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
617 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
618 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
619 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
620 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
621 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
623 if (tagmask = 0) then exit;// just in case
625 if ((tagmask and GridTagLift) <> 0) then
626 begin
627 // slow
628 it := mapGrid.forEachAtPoint(x, y, tagmask);
629 for mwit in it do if (xxPanAtPointChecker(mwit^, PanelType)) then begin result := true; break; end;
630 end
631 else
632 begin
633 // fast
634 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true);
635 result := (it.length <> 0); // firsthit
636 end;
637 it.release();
638 end;
641 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
642 var
643 it: TPanelGrid.Iter;
644 begin
645 result := nil;
646 if (tagmask = 0) then exit;
647 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true); // firsthit
648 if (it.length <> 0) then result := it.first^;
649 it.release();
650 end;
653 function g_Map_IsSpecialTexture(Texture: String): Boolean;
654 begin
655 Result := (Texture = TEXTURE_NAME_WATER) or
656 (Texture = TEXTURE_NAME_ACID1) or
657 (Texture = TEXTURE_NAME_ACID2);
658 end;
660 procedure CreateDoorMap();
661 var
662 PanelArray: Array of record
663 X, Y: Integer;
664 Width, Height: Word;
665 Active: Boolean;
666 PanelID: DWORD;
667 end;
668 a, b, c, m, i, len: Integer;
669 ok: Boolean;
670 begin
671 if gWalls = nil then
672 Exit;
674 i := 0;
675 len := 128;
676 SetLength(PanelArray, len);
678 for a := 0 to High(gWalls) do
679 if gWalls[a].Door then
680 begin
681 PanelArray[i].X := gWalls[a].X;
682 PanelArray[i].Y := gWalls[a].Y;
683 PanelArray[i].Width := gWalls[a].Width;
684 PanelArray[i].Height := gWalls[a].Height;
685 PanelArray[i].Active := True;
686 PanelArray[i].PanelID := a;
688 i := i + 1;
689 if i = len then
690 begin
691 len := len + 128;
692 SetLength(PanelArray, len);
693 end;
694 end;
696 // Íåò äâåðåé:
697 if i = 0 then
698 begin
699 PanelArray := nil;
700 Exit;
701 end;
703 SetLength(gDoorMap, 0);
705 g_Game_SetLoadingText(_lc[I_LOAD_DOOR_MAP], i-1, False);
707 for a := 0 to i-1 do
708 if PanelArray[a].Active then
709 begin
710 PanelArray[a].Active := False;
711 m := Length(gDoorMap);
712 SetLength(gDoorMap, m+1);
713 SetLength(gDoorMap[m], 1);
714 gDoorMap[m, 0] := PanelArray[a].PanelID;
715 ok := True;
717 while ok do
718 begin
719 ok := False;
721 for b := 0 to i-1 do
722 if PanelArray[b].Active then
723 for c := 0 to High(gDoorMap[m]) do
724 if {((gRenderWalls[PanelArray[b].RenderPanelID].TextureID = gRenderWalls[gDoorMap[m, c]].TextureID) or
725 gRenderWalls[PanelArray[b].RenderPanelID].Hide or gRenderWalls[gDoorMap[m, c]].Hide) and}
726 g_CollideAround(PanelArray[b].X, PanelArray[b].Y,
727 PanelArray[b].Width, PanelArray[b].Height,
728 gWalls[gDoorMap[m, c]].X,
729 gWalls[gDoorMap[m, c]].Y,
730 gWalls[gDoorMap[m, c]].Width,
731 gWalls[gDoorMap[m, c]].Height) then
732 begin
733 PanelArray[b].Active := False;
734 SetLength(gDoorMap[m],
735 Length(gDoorMap[m])+1);
736 gDoorMap[m, High(gDoorMap[m])] := PanelArray[b].PanelID;
737 ok := True;
738 Break;
739 end;
740 end;
742 g_Game_StepLoading();
743 end;
745 PanelArray := nil;
746 end;
748 procedure CreateLiftMap();
749 var
750 PanelArray: Array of record
751 X, Y: Integer;
752 Width, Height: Word;
753 Active: Boolean;
754 end;
755 a, b, c, len, i, j: Integer;
756 ok: Boolean;
757 begin
758 if gLifts = nil then
759 Exit;
761 len := Length(gLifts);
762 SetLength(PanelArray, len);
764 for a := 0 to len-1 do
765 begin
766 PanelArray[a].X := gLifts[a].X;
767 PanelArray[a].Y := gLifts[a].Y;
768 PanelArray[a].Width := gLifts[a].Width;
769 PanelArray[a].Height := gLifts[a].Height;
770 PanelArray[a].Active := True;
771 end;
773 SetLength(gLiftMap, len);
774 i := 0;
776 g_Game_SetLoadingText(_lc[I_LOAD_LIFT_MAP], len-1, False);
778 for a := 0 to len-1 do
779 if PanelArray[a].Active then
780 begin
781 PanelArray[a].Active := False;
782 SetLength(gLiftMap[i], 32);
783 j := 0;
784 gLiftMap[i, j] := a;
785 ok := True;
787 while ok do
788 begin
789 ok := False;
790 for b := 0 to len-1 do
791 if PanelArray[b].Active then
792 for c := 0 to j do
793 if g_CollideAround(PanelArray[b].X,
794 PanelArray[b].Y,
795 PanelArray[b].Width,
796 PanelArray[b].Height,
797 PanelArray[gLiftMap[i, c]].X,
798 PanelArray[gLiftMap[i, c]].Y,
799 PanelArray[gLiftMap[i, c]].Width,
800 PanelArray[gLiftMap[i, c]].Height) then
801 begin
802 PanelArray[b].Active := False;
803 j := j+1;
804 if j > High(gLiftMap[i]) then
805 SetLength(gLiftMap[i],
806 Length(gLiftMap[i])+32);
808 gLiftMap[i, j] := b;
809 ok := True;
811 Break;
812 end;
813 end;
815 SetLength(gLiftMap[i], j+1);
816 i := i+1;
818 g_Game_StepLoading();
819 end;
821 SetLength(gLiftMap, i);
823 PanelArray := nil;
824 end;
826 function CreatePanel (PanelRec: TDynRecord; AddTextures: TAddTextureArray; CurTex: Integer): Integer;
827 var
828 len: Integer;
829 panels: ^TPanelArray;
830 pan: TPanel;
831 pguid: Integer;
832 begin
833 Result := -1;
835 case PanelRec.PanelType of
836 PANEL_WALL, PANEL_OPENDOOR, PANEL_CLOSEDOOR: panels := @gWalls;
837 PANEL_BACK: panels := @gRenderBackgrounds;
838 PANEL_FORE: panels := @gRenderForegrounds;
839 PANEL_WATER: panels := @gWater;
840 PANEL_ACID1: panels := @gAcid1;
841 PANEL_ACID2: panels := @gAcid2;
842 PANEL_STEP: panels := @gSteps;
843 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: panels := @gLifts;
844 PANEL_BLOCKMON: panels := @gBlockMon;
845 else exit;
846 end;
848 len := Length(panels^);
849 SetLength(panels^, len+1);
851 pguid := Length(panByGUID);
852 SetLength(panByGUID, pguid+1); //FIXME!
853 pan := TPanel.Create(PanelRec, AddTextures, CurTex, Textures, pguid);
854 assert(pguid >= 0);
855 assert(pguid < Length(panByGUID));
856 panByGUID[pguid] := pan;
857 panels^[len] := pan;
858 pan.arrIdx := len;
859 pan.proxyId := -1;
860 pan.tag := panelTypeToTag(PanelRec.PanelType);
862 PanelRec.user['panel_guid'] := pguid;
864 //result := len;
865 result := pguid;
866 end;
869 function CreateNullTexture(RecName: String): Integer;
870 begin
871 RecName := toLowerCase1251(RecName);
872 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
873 if TextNameHash.get(RecName, result) then exit; // i found her!
875 SetLength(Textures, Length(Textures)+1);
876 result := High(Textures);
878 with Textures[High(Textures)] do
879 begin
880 TextureName := RecName;
881 Width := 1;
882 Height := 1;
883 Anim := False;
884 TextureID := LongWord(TEXTURE_NONE);
885 end;
887 TextNameHash.put(RecName, result);
888 end;
891 function extractWadName (resourceName: string): string;
892 var
893 posN: Integer;
894 begin
895 posN := Pos(':', resourceName);
896 if posN > 0 then
897 Result:= Copy(resourceName, 0, posN-1)
898 else
899 Result := '';
900 end;
903 procedure addResToExternalResList (res: AnsiString);
904 var
905 uname: AnsiString;
906 f: Integer;
907 fi: TDiskFileInfo;
908 begin
909 if g_Game_IsClient or not g_Game_IsNet then exit;
910 if (length(res) = 0) then exit; // map wad
911 //res := extractWadName(res);
912 //if (length(res) = 0) then exit; // map wad
913 uname := toLowerCase1251(res);
914 // do not add duplicates
915 for f := 0 to High(gExternalResources) do
916 begin
917 if (gExternalResources[f].userName = uname) then exit;
918 end;
919 //writeln('***(000) addResToExternalResList: res=[', res, ']');
920 // add new resource
921 fi.userName := uname;
922 if not findFileCI(res) then exit;
923 //writeln('***(001) addResToExternalResList: res=[', res, ']');
924 fi.diskName := res;
925 if (not GetDiskFileInfo(res, fi)) then
926 begin
927 fi.tag := -1;
928 end
929 else
930 begin
931 //writeln('***(002) addResToExternalResList: res=[', res, ']');
932 fi.tag := 0; // non-zero means "cannot caclucate hash"
933 try
934 fi.hash := MD5File(fi.diskName);
935 except
936 fi.tag := -1;
937 end;
938 end;
939 //e_LogWritefln('addext: res=[%s]; uname=[%s]; diskName=[%s]', [res, fi.userName, fi.diskName]);
940 SetLength(gExternalResources, length(gExternalResources)+1);
941 gExternalResources[High(gExternalResources)] := fi;
942 end;
945 procedure compactExtResList ();
946 var
947 src, dest: Integer;
948 begin
949 src := 0;
950 dest := 0;
951 for src := 0 to High(gExternalResources) do
952 begin
953 if (gExternalResources[src].tag = 0) then
954 begin
955 // copy it
956 if (dest <> src) then gExternalResources[dest] := gExternalResources[src];
957 Inc(dest);
958 end;
959 end;
960 if (dest <> length(gExternalResources)) then SetLength(gExternalResources, dest);
961 end;
964 function GetReplacementWad (WadName: AnsiString): AnsiString;
965 begin
966 result := '';
967 if WadName <> '' then
968 begin
969 result := WadName;
970 if g_Game_IsClient then result := g_Res_FindReplacementWad(WadName);
971 if (result = WadName) then result := e_FindWad(WadDirs, result)
972 end;
973 end;
976 procedure generateExternalResourcesList (map: TDynRecord);
977 begin
978 SetLength(gExternalResources, 0);
979 addResToExternalResList(GetReplacementWad(g_ExtractWadName(map.MusicName)));
980 addResToExternalResList(GetReplacementWad(g_ExtractWadName(map.SkyName)));
981 end;
984 function CreateTexture (RecName: AnsiString; Map: string; log: Boolean): Integer;
985 var
986 WAD: TWADFile;
987 TextureData: Pointer;
988 WADName: String;
989 a, ResLength: Integer;
990 begin
991 RecName := toLowerCase1251(RecName);
992 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
993 if TextNameHash.get(RecName, result) then
994 begin
995 // i found her!
996 //e_LogWritefln('texture ''%s'' already loaded (%s)', [RecName, result]);
997 exit;
998 end;
1000 Result := -1;
1002 if (BadTextNameHash <> nil) and BadTextNameHash.has(RecName) then exit; // don't do it again and again
1005 if Textures <> nil then
1006 begin
1007 for a := 0 to High(Textures) do
1008 begin
1009 if (Textures[a].TextureName = RecName) then
1010 begin // Òåêñòóðà ñ òàêèì èìåíåì óæå åñòü
1011 e_LogWritefln('texture ''%s'' already loaded', [RecName]);
1012 Result := a;
1013 Exit;
1014 end;
1015 end;
1016 end;
1019 // Òåêñòóðû ñî ñïåöèàëüíûìè èìåíàìè (âîäà, ëàâà, êèñëîòà):
1020 if (RecName = TEXTURE_NAME_WATER) or
1021 (RecName = TEXTURE_NAME_ACID1) or
1022 (RecName = TEXTURE_NAME_ACID2) then
1023 begin
1024 SetLength(Textures, Length(Textures)+1);
1026 with Textures[High(Textures)] do
1027 begin
1028 TextureName := RecName;
1029 if (TextureName = TEXTURE_NAME_WATER) then TextureID := LongWord(TEXTURE_SPECIAL_WATER)
1030 else if (TextureName = TEXTURE_NAME_ACID1) then TextureID := LongWord(TEXTURE_SPECIAL_ACID1)
1031 else if (TextureName = TEXTURE_NAME_ACID2) then TextureID := LongWord(TEXTURE_SPECIAL_ACID2);
1033 Anim := False;
1034 end;
1036 result := High(Textures);
1037 TextNameHash.put(RecName, result);
1038 Exit;
1039 end;
1041 // Çàãðóæàåì ðåñóðñ òåêñòóðû â ïàìÿòü èç WAD'à:
1042 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1043 if (WADName <> '') then addResToExternalResList(WADName);
1044 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
1046 WAD := TWADFile.Create();
1047 WAD.ReadFile(WADName);
1049 //txname := RecName;
1051 if (WADName = Map) and WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength) then
1052 begin
1053 FreeMem(TextureData);
1054 RecName := 'COMMON\ALIEN';
1055 end;
1058 if WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength, log) then
1059 begin
1060 SetLength(Textures, Length(Textures)+1);
1061 if not e_CreateTextureMem(TextureData, ResLength, Textures[High(Textures)].TextureID) then
1062 begin
1063 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
1064 SetLength(Textures, Length(Textures)-1);
1065 result := -1;
1066 Exit;
1067 end;
1068 e_GetTextureSize(Textures[High(Textures)].TextureID, @Textures[High(Textures)].Width, @Textures[High(Textures)].Height);
1069 FreeMem(TextureData);
1070 Textures[High(Textures)].TextureName := RecName;
1071 Textures[High(Textures)].Anim := False;
1073 result := High(Textures);
1074 TextNameHash.put(RecName, result);
1075 end
1076 else // Íåò òàêîãî ðåóñðñà â WAD'å
1077 begin
1078 //e_WriteLog(Format('SHIT! Error loading texture %s : %s', [RecName, g_ExtractFilePathName(RecName)]), MSG_WARNING);
1079 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1080 if log and (not BadTextNameHash.get(RecName, a)) then
1081 begin
1082 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
1083 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1084 end;
1085 BadTextNameHash.put(RecName, -1);
1086 end;
1088 WAD.Free();
1089 end;
1092 function CreateAnimTexture(RecName: String; Map: string; log: Boolean): Integer;
1093 var
1094 WAD: TWADFile;
1095 TextureWAD: PChar = nil;
1096 TextData: Pointer = nil;
1097 TextureData: Pointer = nil;
1098 cfg: TConfig = nil;
1099 WADName: String;
1100 ResLength: Integer;
1101 TextureResource: String;
1102 _width, _height, _framecount, _speed: Integer;
1103 _backanimation: Boolean;
1104 //imgfmt: string;
1105 ia: TDynImageDataArray = nil;
1106 f, c, frdelay, frloop: Integer;
1107 begin
1108 RecName := toLowerCase1251(RecName);
1109 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
1110 if TextNameHash.get(RecName, result) then
1111 begin
1112 // i found her!
1113 //e_LogWritefln('animated texture ''%s'' already loaded (%s)', [RecName, result]);
1114 exit;
1115 end;
1117 result := -1;
1119 //e_LogWritefln('*** Loading animated texture "%s"', [RecName]);
1121 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1122 if BadTextNameHash.get(RecName, f) then
1123 begin
1124 //e_WriteLog(Format('no animation texture %s (don''t worry)', [RecName]), MSG_NOTIFY);
1125 exit;
1126 end;
1128 // ×èòàåì WAD-ðåñóðñ àíèì.òåêñòóðû èç WAD'à â ïàìÿòü:
1129 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1130 if (WADName <> '') then addResToExternalResList(WADName);
1131 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
1133 WAD := TWADFile.Create();
1134 try
1135 //if WADName <> '' then WADName := GameDir+'/wads/'+WADName else WADName := Map;
1137 WAD.ReadFile(WADName);
1139 if not WAD.GetResource(g_ExtractFilePathName(RecName), TextureWAD, ResLength, log) then
1140 begin
1141 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1142 if log and (not BadTextNameHash.get(RecName, f)) then
1143 begin
1144 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1145 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1146 end;
1147 BadTextNameHash.put(RecName, -1);
1148 exit;
1149 end;
1151 {TEST
1152 if WADName = Map then
1153 begin
1154 //FreeMem(TextureWAD);
1155 if not WAD.GetResource('COMMON/animation', TextureWAD, ResLength) then Halt(1);
1156 end;
1159 WAD.FreeWAD();
1161 if ResLength < 6 then
1162 begin
1163 e_WriteLog(Format('Animated texture file "%s" too short', [RecName]), TMsgType.Warning);
1164 BadTextNameHash.put(RecName, -1);
1165 exit;
1166 end;
1168 // ýòî ïòèöà? ýòî ñàìîë¸ò?
1169 if isWadData(TextureWAD, ResLength) then
1170 begin
1171 // íåò, ýòî ñóïåðìåí!
1172 if not WAD.ReadMemory(TextureWAD, ResLength) then
1173 begin
1174 e_WriteLog(Format('Animated texture WAD file "%s" is invalid', [RecName]), TMsgType.Warning);
1175 BadTextNameHash.put(RecName, -1);
1176 exit;
1177 end;
1179 // ×èòàåì INI-ðåñóðñ àíèì. òåêñòóðû è çàïîìèíàåì åãî óñòàíîâêè:
1180 if not WAD.GetResource('TEXT/ANIM', TextData, ResLength) then
1181 begin
1182 e_WriteLog(Format('Animated texture file "%s" has invalid INI', [RecName]), TMsgType.Warning);
1183 BadTextNameHash.put(RecName, -1);
1184 exit;
1185 end;
1187 cfg := TConfig.CreateMem(TextData, ResLength);
1189 TextureResource := cfg.ReadStr('', 'resource', '');
1190 if TextureResource = '' then
1191 begin
1192 e_WriteLog(Format('Animated texture WAD file "%s" has no "resource"', [RecName]), TMsgType.Warning);
1193 BadTextNameHash.put(RecName, -1);
1194 exit;
1195 end;
1197 _width := cfg.ReadInt('', 'framewidth', 0);
1198 _height := cfg.ReadInt('', 'frameheight', 0);
1199 _framecount := cfg.ReadInt('', 'framecount', 0);
1200 _speed := cfg.ReadInt('', 'waitcount', 0);
1201 _backanimation := cfg.ReadBool('', 'backanimation', False);
1203 cfg.Free();
1204 cfg := nil;
1206 // ×èòàåì ðåñóðñ òåêñòóð (êàäðîâ) àíèì. òåêñòóðû â ïàìÿòü:
1207 if not WAD.GetResource('TEXTURES/'+TextureResource, TextureData, ResLength) then
1208 begin
1209 e_WriteLog(Format('Animated texture WAD file "%s" has no texture "%s"', [RecName, 'TEXTURES/'+TextureResource]), TMsgType.Warning);
1210 BadTextNameHash.put(RecName, -1);
1211 exit;
1212 end;
1214 WAD.Free();
1215 WAD := nil;
1217 SetLength(Textures, Length(Textures)+1);
1218 with Textures[High(Textures)] do
1219 begin
1220 // Ñîçäàåì êàäðû àíèì. òåêñòóðû èç ïàìÿòè:
1221 if g_Frames_CreateMemory(@FramesID, '', TextureData, ResLength, _width, _height, _framecount, _backanimation) then
1222 begin
1223 TextureName := RecName;
1224 Width := _width;
1225 Height := _height;
1226 Anim := True;
1227 FramesCount := _framecount;
1228 Speed := _speed;
1229 result := High(Textures);
1230 TextNameHash.put(RecName, result);
1231 end
1232 else
1233 begin
1234 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1235 if log and (not BadTextNameHash.get(RecName, f)) then
1236 begin
1237 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1238 end;
1239 BadTextNameHash.put(RecName, -1);
1240 end;
1241 end;
1242 end
1243 else
1244 begin
1245 // try animated image
1247 imgfmt := DetermineMemoryFormat(TextureWAD, ResLength);
1248 if length(imgfmt) = 0 then
1249 begin
1250 e_WriteLog(Format('Animated texture file "%s" has unknown format', [RecName]), MSG_WARNING);
1251 exit;
1252 end;
1254 GlobalMetadata.ClearMetaItems();
1255 GlobalMetadata.ClearMetaItemsForSaving();
1256 if not LoadMultiImageFromMemory(TextureWAD, ResLength, ia) then
1257 begin
1258 e_WriteLog(Format('Animated texture file "%s" cannot be loaded', [RecName]), TMsgType.Warning);
1259 BadTextNameHash.put(RecName, -1);
1260 exit;
1261 end;
1262 if length(ia) = 0 then
1263 begin
1264 e_WriteLog(Format('Animated texture file "%s" has no frames', [RecName]), TMsgType.Warning);
1265 BadTextNameHash.put(RecName, -1);
1266 exit;
1267 end;
1269 WAD.Free();
1270 WAD := nil;
1272 _width := ia[0].width;
1273 _height := ia[0].height;
1274 _framecount := length(ia);
1275 _speed := 1;
1276 _backanimation := false;
1277 frdelay := -1;
1278 frloop := -666;
1279 if GlobalMetadata.HasMetaItem(SMetaFrameDelay) then
1280 begin
1281 //writeln(' frame delay: ', GlobalMetadata.MetaItems[SMetaFrameDelay]);
1282 try
1283 f := GlobalMetadata.MetaItems[SMetaFrameDelay];
1284 frdelay := f;
1285 if f < 0 then f := 0;
1286 // rounding ;-)
1287 c := f mod 28;
1288 if c < 13 then c := 0 else c := 1;
1289 f := (f div 28)+c;
1290 if f < 1 then f := 1 else if f > 255 then f := 255;
1291 _speed := f;
1292 except
1293 end;
1294 end;
1295 if GlobalMetadata.HasMetaItem(SMetaAnimationLoops) then
1296 begin
1297 //writeln(' frame loop : ', GlobalMetadata.MetaItems[SMetaAnimationLoops]);
1298 try
1299 f := GlobalMetadata.MetaItems[SMetaAnimationLoops];
1300 frloop := f;
1301 if f <> 0 then _backanimation := true; // non-infinite looping == forth-and-back
1302 except
1303 end;
1304 end;
1305 //writeln(' creating animated texture with ', length(ia), ' frames (delay:', _speed, '; backloop:', _backanimation, ') from "', RecName, '"...');
1306 //for f := 0 to high(ia) do writeln(' frame #', f, ': ', ia[f].width, 'x', ia[f].height);
1307 f := ord(_backanimation);
1308 e_WriteLog(Format('Animated texture file "%s": %d frames (delay:%d; back:%d; frdelay:%d; frloop:%d), %dx%d', [RecName, length(ia), _speed, f, frdelay, frloop, _width, _height]), TMsgType.Notify);
1310 SetLength(Textures, Length(Textures)+1);
1311 // cîçäàåì êàäðû àíèì. òåêñòóðû èç êàðòèíîê
1312 if g_CreateFramesImg(ia, @Textures[High(Textures)].FramesID, '', _backanimation) then
1313 begin
1314 Textures[High(Textures)].TextureName := RecName;
1315 Textures[High(Textures)].Width := _width;
1316 Textures[High(Textures)].Height := _height;
1317 Textures[High(Textures)].Anim := True;
1318 Textures[High(Textures)].FramesCount := length(ia);
1319 Textures[High(Textures)].Speed := _speed;
1320 result := High(Textures);
1321 TextNameHash.put(RecName, result);
1322 //writeln(' CREATED!');
1323 end
1324 else
1325 begin
1326 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1327 if log and (not BadTextNameHash.get(RecName, f)) then
1328 begin
1329 e_WriteLog(Format('Error loading animation texture "%s" images', [RecName]), TMsgType.Warning);
1330 end;
1331 BadTextNameHash.put(RecName, -1);
1332 end;
1333 end;
1334 finally
1335 for f := 0 to High(ia) do FreeImage(ia[f]);
1336 WAD.Free();
1337 cfg.Free();
1338 if (TextureWAD <> nil) then FreeMem(TextureWAD);
1339 if (TextData <> nil) then FreeMem(TextData);
1340 if (TextureData <> nil) then FreeMem(TextureData);
1341 end;
1342 end;
1344 procedure CreateItem(Item: TDynRecord);
1345 begin
1346 if g_Game_IsClient then Exit;
1348 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) and
1349 ByteBool(Item.Options and ITEM_OPTION_ONLYDM) then
1350 Exit;
1352 g_Items_Create(Item.X, Item.Y, Item.ItemType, ByteBool(Item.Options and ITEM_OPTION_FALL),
1353 gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF, GM_COOP]);
1354 end;
1356 procedure CreateArea(Area: TDynRecord);
1357 var
1358 a: Integer;
1359 id: DWORD = 0;
1360 begin
1361 case Area.AreaType of
1362 AREA_DMPOINT, AREA_PLAYERPOINT1, AREA_PLAYERPOINT2,
1363 AREA_REDTEAMPOINT, AREA_BLUETEAMPOINT:
1364 begin
1365 SetLength(RespawnPoints, Length(RespawnPoints)+1);
1366 with RespawnPoints[High(RespawnPoints)] do
1367 begin
1368 X := Area.X;
1369 Y := Area.Y;
1370 Direction := TDirection(Area.Direction);
1372 case Area.AreaType of
1373 AREA_DMPOINT: PointType := RESPAWNPOINT_DM;
1374 AREA_PLAYERPOINT1: PointType := RESPAWNPOINT_PLAYER1;
1375 AREA_PLAYERPOINT2: PointType := RESPAWNPOINT_PLAYER2;
1376 AREA_REDTEAMPOINT: PointType := RESPAWNPOINT_RED;
1377 AREA_BLUETEAMPOINT: PointType := RESPAWNPOINT_BLUE;
1378 end;
1379 end;
1380 end;
1382 AREA_REDFLAG, AREA_BLUEFLAG:
1383 begin
1384 if Area.AreaType = AREA_REDFLAG then a := FLAG_RED else a := FLAG_BLUE;
1386 if FlagPoints[a] <> nil then Exit;
1388 New(FlagPoints[a]);
1390 with FlagPoints[a]^ do
1391 begin
1392 X := Area.X-FLAGRECT.X;
1393 Y := Area.Y-FLAGRECT.Y;
1394 Direction := TDirection(Area.Direction);
1395 end;
1397 with gFlags[a] do
1398 begin
1399 case a of
1400 FLAG_RED: g_Frames_Get(id, 'FRAMES_FLAG_RED');
1401 FLAG_BLUE: g_Frames_Get(id, 'FRAMES_FLAG_BLUE');
1402 end;
1404 Animation := TAnimation.Create(id, True, 8);
1405 Obj.Rect := FLAGRECT;
1407 g_Map_ResetFlag(a);
1408 end;
1409 end;
1411 AREA_DOMFLAG:
1412 begin
1413 {SetLength(DOMFlagPoints, Length(DOMFlagPoints)+1);
1414 with DOMFlagPoints[High(DOMFlagPoints)] do
1415 begin
1416 X := Area.X;
1417 Y := Area.Y;
1418 Direction := TDirection(Area.Direction);
1419 end;
1421 g_Map_CreateFlag(DOMFlagPoints[High(DOMFlagPoints)], FLAG_DOM, FLAG_STATE_NORMAL);}
1422 end;
1423 end;
1424 end;
1426 function CreateTrigger (amapIdx: Integer; Trigger: TDynRecord; atpanid, atrigpanid: Integer): Integer;
1427 var
1428 _trigger: TTrigger;
1429 tp: TPanel;
1430 begin
1431 result := -1;
1432 if g_Game_IsClient and not (Trigger.TriggerType in [TRIGGER_SOUND, TRIGGER_MUSIC]) then Exit;
1434 with _trigger do
1435 begin
1436 mapId := Trigger.id;
1437 mapIndex := amapIdx;
1438 X := Trigger.X;
1439 Y := Trigger.Y;
1440 Width := Trigger.Width;
1441 Height := Trigger.Height;
1442 Enabled := Trigger.Enabled;
1443 TexturePanelGUID := atpanid;
1444 TriggerType := Trigger.TriggerType;
1445 ActivateType := Trigger.ActivateType;
1446 Keys := Trigger.Keys;
1447 trigPanelGUID := atrigpanid;
1448 // HACK: used in TPanel.CanChangeTexture. maybe there's a better way?
1449 if TexturePanelGUID <> -1 then
1450 begin
1451 tp := g_Map_PanelByGUID(TexturePanelGUID);
1452 if (tp <> nil) then tp.hasTexTrigger := True;
1453 end;
1454 end;
1456 result := Integer(g_Triggers_Create(_trigger, Trigger));
1457 end;
1459 procedure CreateMonster(monster: TDynRecord);
1460 var
1461 a: Integer;
1462 mon: TMonster;
1463 begin
1464 if g_Game_IsClient then Exit;
1466 if (gGameSettings.GameType = GT_SINGLE)
1467 or LongBool(gGameSettings.Options and GAME_OPTION_MONSTERS) then
1468 begin
1469 mon := g_Monsters_Create(monster.MonsterType, monster.X, monster.Y, TDirection(monster.Direction));
1471 if gTriggers <> nil then
1472 begin
1473 for a := 0 to High(gTriggers) do
1474 begin
1475 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1476 begin
1477 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1478 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1479 end;
1480 end;
1481 end;
1483 if monster.MonsterType <> MONSTER_BARREL then Inc(gTotalMonsters);
1484 end;
1485 end;
1487 procedure g_Map_ReAdd_DieTriggers();
1489 function monsDieTrig (mon: TMonster): Boolean;
1490 var
1491 a: Integer;
1492 //tw: TStrTextWriter;
1493 begin
1494 result := false; // don't stop
1495 mon.ClearTriggers();
1496 for a := 0 to High(gTriggers) do
1497 begin
1498 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1499 begin
1500 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1502 tw := TStrTextWriter.Create();
1503 try
1504 gTriggers[a].trigData.writeTo(tw);
1505 e_LogWritefln('=== trigger #%s ==='#10'%s'#10'---', [a, tw.str]);
1506 finally
1507 tw.Free();
1508 end;
1510 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1511 end;
1512 end;
1513 end;
1515 begin
1516 if g_Game_IsClient then Exit;
1518 g_Mons_ForEach(monsDieTrig);
1519 end;
1521 procedure mapCreateGrid ();
1522 var
1523 mapX0: Integer = $3fffffff;
1524 mapY0: Integer = $3fffffff;
1525 mapX1: Integer = -$3fffffff;
1526 mapY1: Integer = -$3fffffff;
1528 procedure calcBoundingBox (constref panels: TPanelArray);
1529 var
1530 idx: Integer;
1531 pan: TPanel;
1532 begin
1533 for idx := 0 to High(panels) do
1534 begin
1535 pan := panels[idx];
1536 if not pan.visvalid then continue;
1537 if (pan.Width < 1) or (pan.Height < 1) then continue;
1538 if (mapX0 > pan.x0) then mapX0 := pan.x0;
1539 if (mapY0 > pan.y0) then mapY0 := pan.y0;
1540 if (mapX1 < pan.x1) then mapX1 := pan.x1;
1541 if (mapY1 < pan.y1) then mapY1 := pan.y1;
1542 end;
1543 end;
1545 procedure addPanelsToGrid (constref panels: TPanelArray);
1546 var
1547 idx: Integer;
1548 pan: TPanel;
1549 newtag: Integer;
1550 begin
1551 //tag := panelTypeToTag(tag);
1552 for idx := 0 to High(panels) do
1553 begin
1554 pan := panels[idx];
1555 if not pan.visvalid then continue;
1556 if (pan.proxyId <> -1) then
1557 begin
1558 {$IF DEFINED(D2F_DEBUG)}
1559 e_WriteLog(Format('DUPLICATE wall #%d(%d) enabled (%d); type:%08x', [Integer(idx), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId]), pan.PanelType]), TMsgType.Notify);
1560 {$ENDIF}
1561 continue;
1562 end;
1563 case pan.PanelType of
1564 PANEL_WALL: newtag := GridTagWall;
1565 PANEL_OPENDOOR, PANEL_CLOSEDOOR: newtag := GridTagDoor;
1566 PANEL_BACK: newtag := GridTagBack;
1567 PANEL_FORE: newtag := GridTagFore;
1568 PANEL_WATER: newtag := GridTagWater;
1569 PANEL_ACID1: newtag := GridTagAcid1;
1570 PANEL_ACID2: newtag := GridTagAcid2;
1571 PANEL_STEP: newtag := GridTagStep;
1572 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: newtag := GridTagLift;
1573 PANEL_BLOCKMON: newtag := GridTagBlockMon;
1574 else continue; // oops
1575 end;
1576 pan.tag := newtag;
1578 pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, newtag);
1579 // "enabled" flag has meaning only for doors and walls (engine assumes it); but meh...
1580 mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
1581 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
1583 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
1584 begin
1585 e_WriteLog(Format('INSERTED wall #%d(%d) enabled (%d)', [Integer(idx), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId])]), MSG_NOTIFY);
1586 end;
1588 {$ENDIF}
1589 end;
1590 end;
1592 begin
1593 mapGrid.Free();
1594 mapGrid := nil;
1596 calcBoundingBox(gWalls);
1597 calcBoundingBox(gRenderBackgrounds);
1598 calcBoundingBox(gRenderForegrounds);
1599 calcBoundingBox(gWater);
1600 calcBoundingBox(gAcid1);
1601 calcBoundingBox(gAcid2);
1602 calcBoundingBox(gSteps);
1603 calcBoundingBox(gLifts);
1604 calcBoundingBox(gBlockMon);
1606 e_LogWritefln('map dimensions: (%d,%d)-(%d,%d); editor size:(0,0)-(%d,%d)', [mapX0, mapY0, mapX1, mapY1, gMapInfo.Width, gMapInfo.Height]);
1608 if (mapX0 > 0) then mapX0 := 0;
1609 if (mapY0 > 0) then mapY0 := 0;
1611 if (mapX1 < gMapInfo.Width-1) then mapX1 := gMapInfo.Width-1;
1612 if (mapY1 < gMapInfo.Height-1) then mapY1 := gMapInfo.Height-1;
1614 mapGrid := TPanelGrid.Create(mapX0-128, mapY0-128, mapX1-mapX0+1+128*2, mapY1-mapY0+1+128*2);
1615 //mapGrid := TPanelGrid.Create(0, 0, gMapInfo.Width, gMapInfo.Height);
1617 addPanelsToGrid(gWalls);
1618 addPanelsToGrid(gRenderBackgrounds);
1619 addPanelsToGrid(gRenderForegrounds);
1620 addPanelsToGrid(gWater);
1621 addPanelsToGrid(gAcid1);
1622 addPanelsToGrid(gAcid2);
1623 addPanelsToGrid(gSteps);
1624 addPanelsToGrid(gLifts); // it doesn't matter which LIFT type is used here
1625 addPanelsToGrid(gBlockMon);
1627 mapGrid.dumpStats();
1629 g_Mons_InitTree(mapGrid.gridX0, mapGrid.gridY0, mapGrid.gridWidth, mapGrid.gridHeight);
1630 end;
1633 function g_Map_Load(Res: String): Boolean;
1634 const
1635 DefaultMusRes = 'Standart.wad:STDMUS\MUS1';
1636 DefaultSkyRes = 'Standart.wad:STDSKY\SKY0';
1637 type
1638 PTRec = ^TTRec;
1639 TTRec = record
1640 //TexturePanel: Integer;
1641 tnum: Integer;
1642 id: Integer;
1643 trigrec: TDynRecord;
1644 // texture pane;
1645 texPanelIdx: Integer;
1646 texPanel: TDynRecord;
1647 // "action" panel
1648 actPanelIdx: Integer;
1649 actPanel: TDynRecord;
1650 end;
1651 var
1652 WAD, TestWAD: TWADFile;
1653 //mapReader: TDynRecord = nil;
1654 mapTextureList: TDynField = nil; //TTexturesRec1Array; tagInt: texture index
1655 panels: TDynField = nil; //TPanelsRec1Array;
1656 items: TDynField = nil; //TItemsRec1Array;
1657 monsters: TDynField = nil; //TMonsterRec1Array;
1658 areas: TDynField = nil; //TAreasRec1Array;
1659 triggers: TDynField = nil; //TTriggersRec1Array;
1660 b, c, k: Integer;
1661 PanelID: DWORD;
1662 AddTextures: TAddTextureArray;
1663 TriggersTable: array of TTRec;
1664 FileName, mapResName, TexName, s: AnsiString;
1665 Data: Pointer;
1666 Len: Integer;
1667 ok, isAnim: Boolean;
1668 CurTex, ntn: Integer;
1669 rec, texrec: TDynRecord;
1670 pttit: PTRec;
1671 pannum, trignum, cnt, tgpid: Integer;
1672 stt: UInt64;
1673 moveSpeed{, moveStart, moveEnd}: TDFPoint;
1674 //moveActive: Boolean;
1675 pan: TPanel;
1676 mapOk: Boolean = false;
1677 usedTextures: THashStrInt = nil; // key: mapTextureList
1678 begin
1679 mapGrid.Free();
1680 mapGrid := nil;
1681 TestWAD := nil;
1682 Data := nil;
1684 //gCurrentMap.Free();
1685 //gCurrentMap := nil;
1687 panByGUID := nil;
1689 Result := False;
1690 gMapInfo.Map := Res;
1691 TriggersTable := nil;
1692 //mapReader := nil;
1694 sfsGCDisable(); // temporary disable removing of temporary volumes
1695 try
1696 // Çàãðóçêà WAD (åñëè ó íàñ íåò óæå çàãðóæåíîé êàðòû)
1697 if (gCurrentMap = nil) then
1698 begin
1699 FileName := g_ExtractWadName(Res);
1700 e_LogWritefln('Loading map WAD [%s] (res=[%s])', [FileName, Res], TMsgType.Notify);
1701 g_Game_SetLoadingText(_lc[I_LOAD_WAD_FILE], 0, False);
1703 WAD := TWADFile.Create();
1704 if not WAD.ReadFile(FileName) then
1705 begin
1706 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [FileName]));
1707 WAD.Free();
1708 Exit;
1709 end;
1711 if gTestMap <> '' then
1712 begin
1713 s := g_ExtractWadName(gTestMap);
1714 TestWAD := TWADFile.Create();
1715 if not TestWAD.ReadFile(s) then
1716 begin
1717 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_WAD], [s]));
1718 TestWAD.Free();
1719 TestWAD := nil;
1720 end;
1721 end;
1723 if TestWAD <> nil then
1724 begin
1725 mapResName := g_ExtractFileName(gTestMap);
1726 if not TestWAD.GetMapResource(mapResName, Data, Len) then
1727 begin
1728 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1729 Data := nil;
1730 end else
1731 e_WriteLog('Using test map: '+gTestMap, TMsgType.Notify);
1732 TestWAD.Free();
1733 TestWAD := nil;
1734 end;
1736 if Data = nil then
1737 begin
1738 //k8: why loader ignores path here?
1739 mapResName := g_ExtractFileName(Res);
1740 if not WAD.GetMapResource(mapResName, Data, Len) then
1741 begin
1742 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1743 WAD.Free();
1744 Exit;
1745 end;
1746 end;
1748 WAD.Free();
1750 if (Len < 4) then
1751 begin
1752 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1753 FreeMem(Data);
1754 exit;
1755 end;
1757 // Çàãðóçêà êàðòû:
1758 e_LogWritefln('Loading map: %s', [mapResName], TMsgType.Notify);
1759 g_Game_SetLoadingText(_lc[I_LOAD_MAP], 0, False);
1761 stt := getTimeMicro();
1763 try
1764 gCurrentMap := g_Map_ParseMap(Data, Len);
1765 except
1766 gCurrentMap.Free();
1767 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]));
1768 FreeMem(Data);
1769 gCurrentMapFileName := '';
1770 Exit;
1771 end;
1773 FreeMem(Data);
1775 if (gCurrentMap = nil) then
1776 begin
1777 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1778 gCurrentMapFileName := '';
1779 exit;
1780 end;
1781 end
1782 else
1783 begin
1784 stt := getTimeMicro();
1785 end;
1787 //gCurrentMap := mapReader;
1789 generateExternalResourcesList(gCurrentMap);
1790 mapTextureList := gCurrentMap['texture'];
1791 // get all other lists here too
1792 panels := gCurrentMap['panel'];
1793 triggers := gCurrentMap['trigger'];
1794 items := gCurrentMap['item'];
1795 areas := gCurrentMap['area'];
1796 monsters := gCurrentMap['monster'];
1798 // Çàãðóçêà îïèñàíèÿ êàðòû:
1799 e_WriteLog(' Reading map info...', TMsgType.Notify);
1800 g_Game_SetLoadingText(_lc[I_LOAD_MAP_HEADER], 0, False);
1802 with gMapInfo do
1803 begin
1804 Name := gCurrentMap.MapName;
1805 Description := gCurrentMap.MapDesc;
1806 Author := gCurrentMap.MapAuthor;
1807 MusicName := gCurrentMap.MusicName;
1808 SkyName := gCurrentMap.SkyName;
1809 Height := gCurrentMap.Height;
1810 Width := gCurrentMap.Width;
1811 end;
1813 // Çàãðóçêà òåêñòóð:
1814 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], 0, False);
1815 // Äîáàâëåíèå òåêñòóð â Textures[]:
1816 if (mapTextureList <> nil) and (mapTextureList.count > 0) then
1817 begin
1818 e_WriteLog(' Loading textures:', TMsgType.Notify);
1819 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], mapTextureList.count-1, False);
1821 // find used textures
1822 usedTextures := THashStrInt.Create();
1823 try
1824 if (panels <> nil) and (panels.count > 0) then
1825 begin
1826 for rec in panels do
1827 begin
1828 texrec := rec.TextureRec;
1829 if (texrec <> nil) then usedTextures.put(toLowerCase1251(texrec.Resource), 42);
1830 end;
1831 end;
1833 cnt := -1;
1834 for rec in mapTextureList do
1835 begin
1836 Inc(cnt);
1837 if not usedTextures.has(toLowerCase1251(rec.Resource)) then
1838 begin
1839 rec.tagInt := -1; // just in case
1840 e_LogWritefln(' Unused texture #%d: %s', [cnt, rec.Resource]);
1841 end
1842 else
1843 begin
1844 {$IF DEFINED(D2F_DEBUG_TXLOAD)}
1845 e_LogWritefln(' Loading texture #%d: %s', [cnt, rec.Resource]);
1846 {$ENDIF}
1847 //if g_Map_IsSpecialTexture(s) then e_WriteLog(' SPECIAL!', MSG_NOTIFY);
1848 if rec.Anim then
1849 begin
1850 // Àíèìèðîâàííàÿ òåêñòóðà
1851 ntn := CreateAnimTexture(rec.Resource, FileName, True);
1852 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_ANIM], [rec.Resource]));
1853 end
1854 else
1855 begin
1856 // Îáû÷íàÿ òåêñòóðà
1857 ntn := CreateTexture(rec.Resource, FileName, True);
1858 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_SIMPLE], [rec.Resource]));
1859 end;
1860 if (ntn < 0) then ntn := CreateNullTexture(rec.Resource);
1862 rec.tagInt := ntn; // remember texture number
1863 end;
1864 g_Game_StepLoading();
1865 end;
1866 finally
1867 usedTextures.Free();
1868 end;
1870 // set panel tagInt to texture index
1871 if (panels <> nil) then
1872 begin
1873 for rec in panels do
1874 begin
1875 texrec := rec.TextureRec;
1876 if (texrec = nil) then rec.tagInt := -1 else rec.tagInt := texrec.tagInt;
1877 end;
1878 end;
1879 end;
1882 // Çàãðóçêà òðèããåðîâ
1883 gTriggerClientID := 0;
1884 e_WriteLog(' Loading triggers...', TMsgType.Notify);
1885 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS], 0, False);
1887 // Çàãðóçêà ïàíåëåé
1888 e_WriteLog(' Loading panels...', TMsgType.Notify);
1889 g_Game_SetLoadingText(_lc[I_LOAD_PANELS], 0, False);
1891 // check texture numbers for panels
1892 if (panels <> nil) and (panels.count > 0) then
1893 begin
1894 for rec in panels do
1895 begin
1896 if (rec.tagInt < 0) then
1897 begin
1898 e_WriteLog('error loading map: invalid texture index for panel', TMsgType.Fatal);
1899 result := false;
1900 gCurrentMap.Free();
1901 gCurrentMap := nil;
1902 gCurrentMapFileName := '';
1903 exit;
1904 end;
1905 end;
1906 end;
1908 // Ñîçäàíèå òàáëèöû òðèããåðîâ (ñîîòâåòñòâèå ïàíåëåé òðèããåðàì)
1909 if (triggers <> nil) and (triggers.count > 0) then
1910 begin
1911 e_WriteLog(' Setting up trigger table...', TMsgType.Notify);
1912 //SetLength(TriggersTable, triggers.count);
1913 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS_TABLE], triggers.count-1, False);
1915 SetLength(TriggersTable, triggers.count);
1916 trignum := -1;
1917 for rec in triggers do
1918 begin
1919 Inc(trignum);
1920 pttit := @TriggersTable[trignum];
1921 pttit.trigrec := rec;
1922 // Ñìåíà òåêñòóðû (âîçìîæíî, êíîïêè)
1923 pttit.texPanelIdx := -1; // will be fixed later
1924 pttit.texPanel := rec.TexturePanelRec;
1925 // action panel
1926 pttit.actPanelIdx := -1;
1927 if (rec.trigRec <> nil) then pttit.actPanel := rec.trigRec.tgPanelRec else pttit.actPanel := nil;
1928 // set flag
1929 if (pttit.texPanel <> nil) then pttit.texPanel.userPanelTrigRef := true;
1930 if (pttit.actPanel <> nil) then pttit.actPanel.userPanelTrigRef := true;
1931 // update progress
1932 g_Game_StepLoading();
1933 end;
1934 end;
1936 // Ñîçäàåì ïàíåëè
1937 if (panels <> nil) and (panels.count > 0) then
1938 begin
1939 e_WriteLog(' Setting up trigger links...', TMsgType.Notify);
1940 g_Game_SetLoadingText(_lc[I_LOAD_LINK_TRIGGERS], panels.count-1, False);
1942 pannum := -1;
1943 for rec in panels do
1944 begin
1945 Inc(pannum);
1946 //e_LogWritefln('PANSTART: pannum=%s', [pannum]);
1947 texrec := nil;
1948 SetLength(AddTextures, 0);
1949 CurTex := -1;
1950 ok := false;
1952 if (mapTextureList <> nil) then
1953 begin
1954 texrec := rec.TextureRec;
1955 ok := (texrec <> nil);
1956 end;
1958 if ok then
1959 begin
1960 // Ñìîòðèì, ññûëàþòñÿ ëè íà ýòó ïàíåëü òðèããåðû.
1961 // Åñëè äà - òî íàäî ñîçäàòü åùå òåêñòóð
1962 ok := false;
1963 if (TriggersTable <> nil) and (mapTextureList <> nil) then
1964 begin
1965 if rec.userPanelTrigRef then
1966 begin
1967 // e_LogWritefln('trigref for panel %s', [pannum]);
1968 ok := True;
1969 end;
1970 end;
1971 end;
1973 if ok then
1974 begin
1975 // Åñòü ññûëêè òðèããåðîâ íà ýòó ïàíåëü
1976 s := texrec.Resource;
1978 // Ñïåö-òåêñòóðû çàïðåùåíû
1979 if g_Map_IsSpecialTexture(s) then
1980 begin
1981 ok := false
1982 end
1983 else
1984 begin
1985 // Îïðåäåëÿåì íàëè÷èå è ïîëîæåíèå öèôð â êîíöå ñòðîêè
1986 ok := g_Texture_NumNameFindStart(s);
1987 end;
1989 // Åñëè ok, çíà÷èò åñòü öèôðû â êîíöå.
1990 // Çàãðóæàåì òåêñòóðû ñ îñòàëüíûìè #
1991 if ok then
1992 begin
1993 k := NNF_NAME_BEFORE;
1994 // Öèêë ïî èçìåíåíèþ èìåíè òåêñòóðû
1995 while ok or (k = NNF_NAME_BEFORE) or (k = NNF_NAME_EQUALS) do
1996 begin
1997 k := g_Texture_NumNameFindNext(TexName);
1999 if (k = NNF_NAME_BEFORE) or (k = NNF_NAME_AFTER) then
2000 begin
2001 // Ïðîáóåì äîáàâèòü íîâóþ òåêñòóðó
2002 if texrec.Anim then
2003 begin
2004 // Íà÷àëüíàÿ - àíèìèðîâàííàÿ, èùåì àíèìèðîâàííóþ
2005 isAnim := True;
2006 //e_LogWritefln('000: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2007 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2008 //e_LogWritefln('001: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2009 if not ok then
2010 begin
2011 // Íåò àíèìèðîâàííîé, èùåì îáû÷íóþ
2012 isAnim := False;
2013 //e_LogWritefln('002: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2014 ok := CreateTexture(TexName, FileName, False) >= 0;
2015 //e_LogWritefln('003: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2016 end;
2017 end
2018 else
2019 begin
2020 // Íà÷àëüíàÿ - îáû÷íàÿ, èùåì îáû÷íóþ
2021 isAnim := False;
2022 //e_LogWritefln('004: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2023 ok := CreateTexture(TexName, FileName, False) >= 0;
2024 //e_LogWritefln('005: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2025 if not ok then
2026 begin
2027 // Íåò îáû÷íîé, èùåì àíèìèðîâàííóþ
2028 isAnim := True;
2029 //e_LogWritefln('006: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2030 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2031 //e_LogWritefln('007: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2032 end;
2033 end;
2035 // Îíà ñóùåñòâóåò. Çàíîñèì åå ID â ñïèñîê ïàíåëè
2036 if ok then
2037 begin
2039 for c := 0 to High(Textures) do
2040 begin
2041 if (Textures[c].TextureName = TexName) then
2042 begin
2043 SetLength(AddTextures, Length(AddTextures)+1);
2044 AddTextures[High(AddTextures)].Texture := c;
2045 AddTextures[High(AddTextures)].Anim := isAnim;
2046 break;
2047 end;
2048 end;
2050 if (TextNameHash <> nil) and TextNameHash.get(toLowerCase1251(TexName), c) then
2051 begin
2052 SetLength(AddTextures, Length(AddTextures)+1);
2053 AddTextures[High(AddTextures)].Texture := c;
2054 AddTextures[High(AddTextures)].Anim := isAnim;
2055 end;
2056 end;
2057 end
2058 else
2059 begin
2060 if k = NNF_NAME_EQUALS then
2061 begin
2062 // Çàíîñèì òåêóùóþ òåêñòóðó íà ñâîå ìåñòî
2063 SetLength(AddTextures, Length(AddTextures)+1);
2064 AddTextures[High(AddTextures)].Texture := rec.tagInt; // internal texture number, not map index
2065 AddTextures[High(AddTextures)].Anim := texrec.Anim;
2066 CurTex := High(AddTextures);
2067 ok := true;
2068 end
2069 else // NNF_NO_NAME
2070 begin
2071 ok := false;
2072 end;
2073 end;
2074 end; // while ok...
2076 ok := true;
2077 end; // if ok - åñòü ñìåæíûå òåêñòóðû
2078 end; // if ok - ññûëàþòñÿ òðèããåðû
2080 if not ok then
2081 begin
2082 // Çàíîñèì òîëüêî òåêóùóþ òåêñòóðó
2083 SetLength(AddTextures, 1);
2084 AddTextures[0].Texture := rec.tagInt; // internal texture number, not map index
2085 AddTextures[0].Anim := false;
2086 if (texrec <> nil) then AddTextures[0].Anim := texrec.Anim;
2087 CurTex := 0;
2088 end;
2090 //e_WriteLog(Format('panel #%d: TextureNum=%d; ht=%d; ht1=%d; atl=%d', [a, panels[a].TextureNum, High(mapTextureList), High(Textures), High(AddTextures)]), MSG_NOTIFY);
2092 //e_LogWritefln('PANADD: pannum=%s', [pannum]);
2094 // Ñîçäàåì ïàíåëü è çàïîìèíàåì åå GUID
2095 //e_LogWritefln('new panel; tcount=%s; curtex=%s', [Length(AddTextures), CurTex]);
2096 PanelID := CreatePanel(rec, AddTextures, CurTex);
2097 //e_LogWritefln('panel #%s of type %s got guid #%s', [pannum, rec.PanelType, PanelID]);
2098 rec.userPanelId := PanelID; // remember game panel id, we'll fix triggers later
2100 // setup lifts
2101 moveSpeed := rec.moveSpeed;
2102 //moveStart := rec.moveStart;
2103 //moveEnd := rec.moveEnd;
2104 //moveActive := rec['move_active'].value;
2105 if not moveSpeed.isZero then
2106 begin
2107 SetLength(gMovingWallIds, Length(gMovingWallIds)+1);
2108 gMovingWallIds[High(gMovingWallIds)] := PanelID;
2109 //e_LogWritefln('found moving panel ''%s'' (idx=%s; id=%s)', [rec.id, pannum, PanelID]);
2110 end;
2112 //e_LogWritefln('PANEND: pannum=%s', [pannum]);
2114 g_Game_StepLoading();
2115 end;
2116 end;
2118 // ×èíèì ID'û ïàíåëåé, êîòîðûå èñïîëüçóþòñÿ â òðèããåðàõ
2119 for b := 0 to High(TriggersTable) do
2120 begin
2121 if (TriggersTable[b].texPanel <> nil) then TriggersTable[b].texPanelIdx := TriggersTable[b].texPanel.userPanelId;
2122 if (TriggersTable[b].actPanel <> nil) then TriggersTable[b].actPanelIdx := TriggersTable[b].actPanel.userPanelId;
2123 end;
2125 // create map grid, init other grids (for monsters, for example)
2126 e_WriteLog('Creating map grid', TMsgType.Notify);
2127 mapCreateGrid();
2129 // Åñëè íå LoadState, òî ñîçäàåì òðèããåðû
2130 if (triggers <> nil) and (panels <> nil) and (not gLoadGameMode) then
2131 begin
2132 e_LogWritefln(' Creating triggers (%d)...', [triggers.count]);
2133 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_TRIGGERS], 0, False);
2134 // Óêàçûâàåì òèï ïàíåëè, åñëè åñòü
2135 trignum := -1;
2136 for rec in triggers do
2137 begin
2138 Inc(trignum);
2139 tgpid := TriggersTable[trignum].actPanelIdx;
2140 //e_LogWritefln('creating trigger #%s; texpantype=%s; shotpantype=%s (%d,%d)', [trignum, b, c, TriggersTable[trignum].texPanIdx, TriggersTable[trignum].ShotPanelIdx]);
2141 TriggersTable[trignum].tnum := trignum;
2142 TriggersTable[trignum].id := CreateTrigger(trignum, rec, TriggersTable[trignum].texPanelIdx, tgpid);
2143 end;
2144 end;
2146 //FIXME: use hashtable!
2147 for pan in panByGUID do
2148 begin
2149 if (pan.endPosTrigId >= 0) and (pan.endPosTrigId < Length(TriggersTable)) then
2150 begin
2151 pan.endPosTrigId := TriggersTable[pan.endPosTrigId].id;
2152 end;
2153 if (pan.endSizeTrigId >= 0) and (pan.endSizeTrigId < Length(TriggersTable)) then
2154 begin
2155 pan.endSizeTrigId := TriggersTable[pan.endSizeTrigId].id;
2156 end;
2157 end;
2159 // Çàãðóçêà ïðåäìåòîâ
2160 e_WriteLog(' Loading items...', TMsgType.Notify);
2161 g_Game_SetLoadingText(_lc[I_LOAD_ITEMS], 0, False);
2163 // Åñëè íå LoadState, òî ñîçäàåì ïðåäìåòû
2164 if (items <> nil) and not gLoadGameMode then
2165 begin
2166 e_WriteLog(' Spawning items...', TMsgType.Notify);
2167 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_ITEMS], 0, False);
2168 for rec in items do CreateItem(rec);
2169 end;
2171 // Çàãðóçêà îáëàñòåé
2172 e_WriteLog(' Loading areas...', TMsgType.Notify);
2173 g_Game_SetLoadingText(_lc[I_LOAD_AREAS], 0, False);
2175 // Åñëè íå LoadState, òî ñîçäàåì îáëàñòè
2176 if areas <> nil then
2177 begin
2178 e_WriteLog(' Creating areas...', TMsgType.Notify);
2179 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_AREAS], 0, False);
2180 for rec in areas do CreateArea(rec);
2181 end;
2183 // Çàãðóçêà ìîíñòðîâ
2184 e_WriteLog(' Loading monsters...', TMsgType.Notify);
2185 g_Game_SetLoadingText(_lc[I_LOAD_MONSTERS], 0, False);
2187 gTotalMonsters := 0;
2189 // Åñëè íå LoadState, òî ñîçäàåì ìîíñòðîâ
2190 if (monsters <> nil) and not gLoadGameMode then
2191 begin
2192 e_WriteLog(' Spawning monsters...', TMsgType.Notify);
2193 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_MONSTERS], 0, False);
2194 for rec in monsters do CreateMonster(rec);
2195 end;
2197 //gCurrentMap := mapReader; // this will be our current map now
2198 gCurrentMapFileName := Res;
2199 //mapReader := nil;
2201 // Çàãðóçêà íåáà
2202 if (gMapInfo.SkyName <> '') then
2203 begin
2204 e_WriteLog(' Loading sky: ' + gMapInfo.SkyName, TMsgType.Notify);
2205 g_Game_SetLoadingText(_lc[I_LOAD_SKY], 0, False);
2206 if gTextureFilter then TEXTUREFILTER := GL_LINEAR else TEXTUREFILTER := GL_NEAREST;
2207 try
2208 s := e_GetResourcePath(WadDirs, gMapInfo.SkyName, g_ExtractWadName(Res));
2209 if g_Texture_CreateWAD(BackID, s) then
2210 g_Game_SetupScreenSize
2211 else
2212 g_FatalError(Format(_lc[I_GAME_ERROR_SKY], [s]))
2213 finally
2214 TEXTUREFILTER := GL_NEAREST;
2215 end;
2216 end;
2218 // Çàãðóçêà ìóçûêè
2219 ok := False;
2220 if gMapInfo.MusicName <> '' then
2221 begin
2222 e_WriteLog(' Loading music: ' + gMapInfo.MusicName, TMsgType.Notify);
2223 g_Game_SetLoadingText(_lc[I_LOAD_MUSIC], 0, False);
2225 s := e_GetResourcePath(WadDirs, gMapInfo.MusicName, g_ExtractWadName(Res));
2226 if g_Sound_CreateWADEx(gMapInfo.MusicName, s, True) then
2227 ok := True
2228 else
2229 g_FatalError(Format(_lc[I_GAME_ERROR_MUSIC], [s]));
2230 end;
2232 // Îñòàëüíûå óñòàíâêè
2233 CreateDoorMap();
2234 CreateLiftMap();
2236 g_Items_Init();
2237 g_Weapon_Init();
2238 g_Monsters_Init();
2240 // Åñëè íå LoadState, òî ñîçäàåì êàðòó ñòîëêíîâåíèé:
2241 if not gLoadGameMode then g_GFX_Init();
2243 // Ñáðîñ ëîêàëüíûõ ìàññèâîâ:
2244 mapTextureList := nil;
2245 panels := nil;
2246 items := nil;
2247 areas := nil;
2248 triggers := nil;
2249 TriggersTable := nil;
2250 AddTextures := nil;
2252 // Âêëþ÷àåì ìóçûêó, åñëè ýòî íå çàãðóçêà:
2253 if ok and (not gLoadGameMode) then
2254 begin
2255 gMusic.SetByName(gMapInfo.MusicName);
2256 gMusic.Play();
2257 end
2258 else
2259 begin
2260 gMusic.SetByName('');
2261 end;
2263 stt := getTimeMicro()-stt;
2264 e_LogWritefln('map loaded in %s.%s milliseconds', [Integer(stt div 1000), Integer(stt mod 1000)]);
2265 mapOk := true;
2266 finally
2267 sfsGCEnable(); // enable releasing unused volumes
2268 //mapReader.Free();
2269 e_UnpressAllKeys; // why not?
2270 if not mapOk then
2271 begin
2272 gCurrentMap.Free();
2273 gCurrentMap := nil;
2274 gCurrentMapFileName := '';
2275 end;
2276 end;
2278 compactExtResList();
2279 e_WriteLog('Done loading map.', TMsgType.Notify);
2280 Result := True;
2281 end;
2284 function g_Map_GetMapInfo(Res: String): TMapInfo;
2285 var
2286 WAD: TWADFile;
2287 mapReader: TDynRecord;
2288 //Header: TMapHeaderRec_1;
2289 FileName: String;
2290 Data: Pointer;
2291 Len: Integer;
2292 begin
2293 FillChar(Result, SizeOf(Result), 0);
2294 FileName := g_ExtractWadName(Res);
2296 WAD := TWADFile.Create();
2297 if not WAD.ReadFile(FileName) then
2298 begin
2299 WAD.Free();
2300 Exit;
2301 end;
2303 //k8: it ignores path again
2304 if not WAD.GetMapResource(g_ExtractFileName(Res), Data, Len) then
2305 begin
2306 WAD.Free();
2307 Exit;
2308 end;
2310 WAD.Free();
2312 try
2313 mapReader := g_Map_ParseMap(Data, Len);
2314 except
2315 mapReader := nil;
2316 FreeMem(Data);
2317 exit;
2318 end;
2320 FreeMem(Data);
2322 if (mapReader = nil) then exit;
2324 if (mapReader.Width > 0) and (mapReader.Height > 0) then
2325 begin
2326 Result.Name := mapReader.MapName;
2327 Result.Description := mapReader.MapDesc;
2328 Result.Map := Res;
2329 Result.Author := mapReader.MapAuthor;
2330 Result.Height := mapReader.Height;
2331 Result.Width := mapReader.Width;
2332 end
2333 else
2334 begin
2335 g_Console_Add(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]), True);
2336 //ZeroMemory(@Header, SizeOf(Header));
2337 Result.Name := _lc[I_GAME_ERROR_MAP_SELECT];
2338 Result.Description := _lc[I_GAME_ERROR_MAP_SELECT];
2339 Result.Map := Res;
2340 Result.Author := '';
2341 Result.Height := 0;
2342 Result.Width := 0;
2343 end;
2345 mapReader.Free();
2346 end;
2348 function g_Map_GetMapsList(WADName: string): SSArray;
2349 var
2350 WAD: TWADFile;
2351 a: Integer;
2352 ResList: SSArray;
2353 begin
2354 Result := nil;
2355 WAD := TWADFile.Create();
2356 if not WAD.ReadFile(WADName) then
2357 begin
2358 WAD.Free();
2359 Exit;
2360 end;
2361 ResList := WAD.GetMapResources();
2362 if ResList <> nil then
2363 begin
2364 for a := 0 to High(ResList) do
2365 begin
2366 SetLength(Result, Length(Result)+1);
2367 Result[High(Result)] := ResList[a];
2368 end;
2369 end;
2370 WAD.Free();
2371 end;
2373 function g_Map_Exist(Res: string): Boolean;
2374 var
2375 WAD: TWADFile;
2376 FileName, mnn: string;
2377 ResList: SSArray;
2378 a: Integer;
2379 begin
2380 Result := False;
2382 FileName := addWadExtension(g_ExtractWadName(Res));
2384 WAD := TWADFile.Create;
2385 if not WAD.ReadFile(FileName) then
2386 begin
2387 WAD.Free();
2388 Exit;
2389 end;
2391 ResList := WAD.GetMapResources();
2392 WAD.Free();
2394 mnn := g_ExtractFileName(Res);
2395 if ResList <> nil then
2396 for a := 0 to High(ResList) do if StrEquCI1251(ResList[a], mnn) then
2397 begin
2398 Result := True;
2399 Exit;
2400 end;
2401 end;
2403 procedure g_Map_Free(freeTextures: Boolean=true);
2404 var
2405 a: Integer;
2407 procedure FreePanelArray(var panels: TPanelArray);
2408 var
2409 i: Integer;
2411 begin
2412 if panels <> nil then
2413 begin
2414 for i := 0 to High(panels) do
2415 panels[i].Free();
2416 panels := nil;
2417 end;
2418 end;
2420 begin
2421 g_GFX_Free();
2422 g_Weapon_Free();
2423 g_Items_Free();
2424 g_Triggers_Free();
2425 g_Monsters_Free();
2427 RespawnPoints := nil;
2428 if FlagPoints[FLAG_RED] <> nil then
2429 begin
2430 Dispose(FlagPoints[FLAG_RED]);
2431 FlagPoints[FLAG_RED] := nil;
2432 end;
2433 if FlagPoints[FLAG_BLUE] <> nil then
2434 begin
2435 Dispose(FlagPoints[FLAG_BLUE]);
2436 FlagPoints[FLAG_BLUE] := nil;
2437 end;
2438 //DOMFlagPoints := nil;
2440 //gDOMFlags := nil;
2442 if (Length(gCurrentMapFileName) <> 0) then
2443 begin
2444 e_LogWritefln('g_Map_Free: previous map was ''%s''...', [gCurrentMapFileName]);
2445 end
2446 else
2447 begin
2448 e_LogWritefln('g_Map_Free: no previous map.', []);
2449 end;
2451 if freeTextures then
2452 begin
2453 e_LogWritefln('g_Map_Free: clearing textures...', []);
2454 if (Textures <> nil) then
2455 begin
2456 for a := 0 to High(Textures) do
2457 begin
2458 if not g_Map_IsSpecialTexture(Textures[a].TextureName) then
2459 begin
2460 if Textures[a].Anim then
2461 begin
2462 g_Frames_DeleteByID(Textures[a].FramesID)
2463 end
2464 else
2465 begin
2466 if (Textures[a].TextureID <> LongWord(TEXTURE_NONE)) then
2467 begin
2468 e_DeleteTexture(Textures[a].TextureID);
2469 end;
2470 end;
2471 end;
2472 end;
2473 Textures := nil;
2474 end;
2475 TextNameHash.Free();
2476 TextNameHash := nil;
2477 BadTextNameHash.Free();
2478 BadTextNameHash := nil;
2479 gCurrentMapFileName := '';
2480 gCurrentMap.Free();
2481 gCurrentMap := nil;
2482 end;
2484 panByGUID := nil;
2486 FreePanelArray(gWalls);
2487 FreePanelArray(gRenderBackgrounds);
2488 FreePanelArray(gRenderForegrounds);
2489 FreePanelArray(gWater);
2490 FreePanelArray(gAcid1);
2491 FreePanelArray(gAcid2);
2492 FreePanelArray(gSteps);
2493 FreePanelArray(gLifts);
2494 FreePanelArray(gBlockMon);
2495 gMovingWallIds := nil;
2497 if BackID <> DWORD(-1) then
2498 begin
2499 gBackSize.X := 0;
2500 gBackSize.Y := 0;
2501 e_DeleteTexture(BackID);
2502 BackID := DWORD(-1);
2503 end;
2505 g_Game_StopAllSounds(False);
2506 gMusic.FreeSound();
2507 g_Sound_Delete(gMapInfo.MusicName);
2509 gMapInfo.Name := '';
2510 gMapInfo.Description := '';
2511 gMapInfo.MusicName := '';
2512 gMapInfo.Height := 0;
2513 gMapInfo.Width := 0;
2515 gDoorMap := nil;
2516 gLiftMap := nil;
2517 end;
2519 procedure g_Map_Update();
2520 var
2521 a, d, j: Integer;
2522 m: Word;
2523 s: String;
2524 b: Byte;
2526 procedure UpdatePanelArray(var panels: TPanelArray);
2527 var
2528 i: Integer;
2530 begin
2531 for i := 0 to High(panels) do panels[i].Update();
2532 end;
2534 begin
2535 if g_dbgpan_mplat_step then g_dbgpan_mplat_active := true;
2537 UpdatePanelArray(gWalls);
2538 UpdatePanelArray(gRenderBackgrounds);
2539 UpdatePanelArray(gRenderForegrounds);
2540 UpdatePanelArray(gWater);
2541 UpdatePanelArray(gAcid1);
2542 UpdatePanelArray(gAcid2);
2543 UpdatePanelArray(gSteps);
2545 if g_dbgpan_mplat_step then begin g_dbgpan_mplat_step := false; g_dbgpan_mplat_active := false; end;
2547 if gGameSettings.GameMode = GM_CTF then
2548 begin
2549 for a := FLAG_RED to FLAG_BLUE do
2550 begin
2551 if not (gFlags[a].State in [FLAG_STATE_NONE, FLAG_STATE_CAPTURED]) then
2552 begin
2553 with gFlags[a] do
2554 begin
2555 if gFlags[a].Animation <> nil then gFlags[a].Animation.Update();
2557 m := g_Obj_Move(@Obj, True, True);
2559 if gTime mod (GAME_TICK*2) <> 0 then Continue;
2561 // Ñîïðîòèâëåíèå âîçäóõà
2562 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
2564 // Òàéìàóò ïîòåðÿííîãî ôëàãà, ëèáî îí âûïàë çà êàðòó
2565 if ((Count = 0) or ByteBool(m and MOVE_FALLOUT)) and g_Game_IsServer then
2566 begin
2567 g_Map_ResetFlag(a);
2568 gFlags[a].CaptureTime := 0;
2569 if a = FLAG_RED then
2570 s := _lc[I_PLAYER_FLAG_RED]
2571 else
2572 s := _lc[I_PLAYER_FLAG_BLUE];
2573 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
2575 if (((gPlayer1 <> nil) and (((gPlayer1.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer1.Team = TEAM_BLUE) and (a = FLAG_BLUE))))
2576 or ((gPlayer2 <> nil) and (((gPlayer2.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer2.Team = TEAM_BLUE) and (a = FLAG_BLUE))))) then
2577 b := 0
2578 else
2579 b := 1;
2581 if not sound_ret_flag[b].IsPlaying() then
2582 sound_ret_flag[b].Play();
2584 if g_Game_IsNet then
2585 MH_SEND_FlagEvent(FLAG_STATE_RETURNED, a, 0);
2586 Continue;
2587 end;
2589 if Count > 0 then Count -= 1;
2591 // Èãðîê áåðåò ôëàã
2592 if gPlayers <> nil then
2593 begin
2594 j := Random(Length(gPlayers)) - 1;
2595 for d := 0 to High(gPlayers) do
2596 begin
2597 Inc(j);
2598 if j > High(gPlayers) then j := 0;
2599 if gPlayers[j] <> nil then
2600 begin
2601 if gPlayers[j].alive and g_Obj_Collide(@Obj, @gPlayers[j].Obj) then
2602 begin
2603 if gPlayers[j].GetFlag(a) then Break;
2604 end;
2605 end;
2606 end;
2607 end;
2608 end;
2609 end;
2610 end;
2611 end;
2612 end;
2614 function g_Map_CollidePanelOld(X, Y: Integer; Width, Height: Word;
2615 PanelType: Word; b1x3: Boolean=false): Boolean;
2616 var
2617 a, h: Integer;
2618 begin
2619 Result := False;
2621 if WordBool(PanelType and PANEL_WALL) then
2622 if gWalls <> nil then
2623 begin
2624 h := High(gWalls);
2626 for a := 0 to h do
2627 if gWalls[a].Enabled and
2628 g_Collide(X, Y, Width, Height,
2629 gWalls[a].X, gWalls[a].Y,
2630 gWalls[a].Width, gWalls[a].Height) then
2631 begin
2632 Result := True;
2633 Exit;
2634 end;
2635 end;
2637 if WordBool(PanelType and PANEL_WATER) then
2638 if gWater <> nil then
2639 begin
2640 h := High(gWater);
2642 for a := 0 to h do
2643 if g_Collide(X, Y, Width, Height,
2644 gWater[a].X, gWater[a].Y,
2645 gWater[a].Width, gWater[a].Height) then
2646 begin
2647 Result := True;
2648 Exit;
2649 end;
2650 end;
2652 if WordBool(PanelType and PANEL_ACID1) then
2653 if gAcid1 <> nil then
2654 begin
2655 h := High(gAcid1);
2657 for a := 0 to h do
2658 if g_Collide(X, Y, Width, Height,
2659 gAcid1[a].X, gAcid1[a].Y,
2660 gAcid1[a].Width, gAcid1[a].Height) then
2661 begin
2662 Result := True;
2663 Exit;
2664 end;
2665 end;
2667 if WordBool(PanelType and PANEL_ACID2) then
2668 if gAcid2 <> nil then
2669 begin
2670 h := High(gAcid2);
2672 for a := 0 to h do
2673 if g_Collide(X, Y, Width, Height,
2674 gAcid2[a].X, gAcid2[a].Y,
2675 gAcid2[a].Width, gAcid2[a].Height) then
2676 begin
2677 Result := True;
2678 Exit;
2679 end;
2680 end;
2682 if WordBool(PanelType and PANEL_STEP) then
2683 if gSteps <> nil then
2684 begin
2685 h := High(gSteps);
2687 for a := 0 to h do
2688 if g_Collide(X, Y, Width, Height,
2689 gSteps[a].X, gSteps[a].Y,
2690 gSteps[a].Width, gSteps[a].Height) then
2691 begin
2692 Result := True;
2693 Exit;
2694 end;
2695 end;
2697 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then
2698 if gLifts <> nil then
2699 begin
2700 h := High(gLifts);
2702 for a := 0 to h do
2703 if ((WordBool(PanelType and (PANEL_LIFTUP)) and (gLifts[a].LiftType = LIFTTYPE_UP)) or
2704 (WordBool(PanelType and (PANEL_LIFTDOWN)) and (gLifts[a].LiftType = LIFTTYPE_DOWN)) or
2705 (WordBool(PanelType and (PANEL_LIFTLEFT)) and (gLifts[a].LiftType = LIFTTYPE_LEFT)) or
2706 (WordBool(PanelType and (PANEL_LIFTRIGHT)) and (gLifts[a].LiftType = LIFTTYPE_RIGHT))) and
2707 g_Collide(X, Y, Width, Height,
2708 gLifts[a].X, gLifts[a].Y,
2709 gLifts[a].Width, gLifts[a].Height) then
2710 begin
2711 Result := True;
2712 Exit;
2713 end;
2714 end;
2716 if WordBool(PanelType and PANEL_BLOCKMON) then
2717 if gBlockMon <> nil then
2718 begin
2719 h := High(gBlockMon);
2721 for a := 0 to h do
2722 if ( (not b1x3) or
2723 ((gBlockMon[a].Width + gBlockMon[a].Height) >= 64) ) and
2724 g_Collide(X, Y, Width, Height,
2725 gBlockMon[a].X, gBlockMon[a].Y,
2726 gBlockMon[a].Width, gBlockMon[a].Height) then
2727 begin
2728 Result := True;
2729 Exit;
2730 end;
2731 end;
2732 end;
2734 function g_Map_CollideLiquid_TextureOld(X, Y: Integer; Width, Height: Word): DWORD;
2735 var
2736 texid: DWORD;
2738 function checkPanels (constref panels: TPanelArray): Boolean;
2739 var
2740 a: Integer;
2741 begin
2742 result := false;
2743 if panels = nil then exit;
2744 for a := 0 to High(panels) do
2745 begin
2746 if g_Collide(X, Y, Width, Height, panels[a].X, panels[a].Y, panels[a].Width, panels[a].Height) then
2747 begin
2748 result := true;
2749 texid := panels[a].GetTextureID();
2750 exit;
2751 end;
2752 end;
2753 end;
2755 begin
2756 texid := LongWord(TEXTURE_NONE);
2757 result := texid;
2758 if not checkPanels(gWater) then
2759 if not checkPanels(gAcid1) then
2760 if not checkPanels(gAcid2) then exit;
2761 result := texid;
2762 end;
2765 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word; PanelType: Word; b1x3: Boolean): Boolean;
2766 const
2767 SlowMask = GridTagLift or GridTagBlockMon;
2769 function checker (pan: TPanel; tag: Integer): Boolean;
2770 begin
2772 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
2773 begin
2774 result := pan.Enabled;
2775 exit;
2776 end;
2779 if ((tag and GridTagLift) <> 0) then
2780 begin
2781 result :=
2782 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2783 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2784 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2785 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2786 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2787 exit;
2788 end;
2790 if ((tag and GridTagBlockMon) <> 0) then
2791 begin
2792 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2793 exit;
2794 end;
2796 // other shit
2797 //result := g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2798 result := true; // i found her!
2799 end;
2801 var
2802 tagmask: Integer = 0;
2803 mwit: PPanel;
2804 it: TPanelGrid.Iter;
2805 pan: TPanel;
2806 begin
2807 result := false;
2808 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
2809 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
2810 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
2811 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
2812 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
2813 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
2814 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
2816 if (tagmask = 0) then exit; // just in case
2818 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('*solids');
2819 if gdbg_map_use_accel_coldet then
2820 begin
2821 if ((tagmask and SlowMask) <> 0) then
2822 begin
2823 // slow
2824 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask);
2825 for mwit in it do
2826 begin
2827 pan := mwit^;
2828 if ((pan.tag and GridTagLift) <> 0) then
2829 begin
2830 result :=
2831 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2832 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2833 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2834 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2835 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2836 end
2837 else if ((pan.tag and GridTagBlockMon) <> 0) then
2838 begin
2839 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2840 end
2841 else
2842 begin
2843 // other shit
2844 result := true; // i found her!
2845 end;
2846 if (result) then break;
2847 end;
2848 end
2849 else
2850 begin
2851 // fast
2852 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask, false, true); // return first hit
2853 result := (it.length > 0);
2854 end;
2855 it.release();
2856 end
2857 else
2858 begin
2859 result := g_Map_CollidePanelOld(X, Y, Width, Height, PanelType, b1x3);
2860 end;
2861 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2862 end;
2865 // returns `true` if we need to stop
2866 function liquidChecker (pan: TPanel; var texid: DWORD; var cctype: Integer): Boolean; inline;
2867 begin
2868 result := false;
2869 //if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2)) = 0) then exit;
2870 // check priorities
2871 case cctype of
2872 0: if ((pan.tag and GridTagWater) = 0) then exit; // allowed: water
2873 1: if ((pan.tag and (GridTagWater or GridTagAcid1)) = 0) then exit; // allowed: water, acid1
2874 //2: if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2) = 0) then exit; // allowed: water, acid1, acid2
2875 end;
2876 // collision?
2877 //if not g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height) then exit;
2878 // yeah
2879 texid := pan.GetTextureID();
2880 // water? water has the highest priority, so stop right here
2881 if ((pan.tag and GridTagWater) <> 0) then begin cctype := 0; result := true; exit; end;
2882 // acid2?
2883 if ((pan.tag and GridTagAcid2) <> 0) then cctype := 2;
2884 // acid1?
2885 if ((pan.tag and GridTagAcid1) <> 0) then cctype := 1;
2886 end;
2888 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
2889 var
2890 cctype: Integer = 3; // priority: 0: water was hit, 1: acid1 was hit, 2: acid2 was hit; 3: nothing was hit
2891 mwit: PPanel;
2892 it: TPanelGrid.Iter;
2893 begin
2894 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('liquids');
2895 if gdbg_map_use_accel_coldet then
2896 begin
2897 result := LongWord(TEXTURE_NONE);
2898 it := mapGrid.forEachInAABB(X, Y, Width, Height, (GridTagWater or GridTagAcid1 or GridTagAcid2));
2899 for mwit in it do if (liquidChecker(mwit^, result, cctype)) then break;
2900 it.release();
2901 end
2902 else
2903 begin
2904 result := g_Map_CollideLiquid_TextureOld(X, Y, Width, Height);
2905 end;
2906 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2907 end;
2910 procedure g_Map_EnableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_EnableWallGUID(gWalls[ID].guid); end;
2911 procedure g_Map_DisableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_DisableWallGUID(gWalls[ID].guid); end;
2912 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer); begin if (ID < Length(gLifts)) then g_Map_SetLiftGUID(gLifts[ID].guid, t); end;
2915 procedure g_Map_EnableWallGUID (pguid: Integer);
2916 var
2917 pan: TPanel;
2918 begin
2919 //pan := gWalls[ID];
2920 pan := g_Map_PanelByGUID(pguid);
2921 if (pan = nil) then exit;
2922 if pan.Enabled and mapGrid.proxyEnabled[pan.proxyId] then exit;
2924 pan.Enabled := True;
2925 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, true);
2927 mapGrid.proxyEnabled[pan.proxyId] := true;
2928 //if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := true
2929 //else pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, GridTagDoor);
2931 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
2932 // mark platform as interesting
2933 pan.setDirty();
2935 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
2936 //e_WriteLog(Format('ENABLE: wall #%d(%d) enabled (%d) (%d,%d)-(%d,%d)', [Integer(ID), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId]), pan.x, pan.y, pan.width, pan.height]), MSG_NOTIFY);
2937 {$ENDIF}
2938 end;
2941 procedure g_Map_DisableWallGUID (pguid: Integer);
2942 var
2943 pan: TPanel;
2944 begin
2945 //pan := gWalls[ID];
2946 pan := g_Map_PanelByGUID(pguid);
2947 if (pan = nil) then exit;
2948 if (not pan.Enabled) and (not mapGrid.proxyEnabled[pan.proxyId]) then exit;
2950 pan.Enabled := False;
2951 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, false);
2953 mapGrid.proxyEnabled[pan.proxyId] := false;
2954 //if (pan.proxyId >= 0) then begin mapGrid.removeBody(pan.proxyId); pan.proxyId := -1; end;
2956 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
2957 // mark platform as interesting
2958 pan.setDirty();
2960 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
2961 //e_WriteLog(Format('DISABLE: wall #%d(%d) disabled (%d) (%d,%d)-(%d,%d)', [Integer(ID), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId]), pan.x, pan.y, pan.width, pan.height]), MSG_NOTIFY);
2962 {$ENDIF}
2963 end;
2966 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
2967 var
2968 tp: TPanel;
2969 begin
2970 tp := g_Map_PanelByGUID(pguid);
2971 if (tp = nil) then exit;
2972 tp.NextTexture(AnimLoop);
2973 if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelTexture(pguid, AnimLoop);
2974 end;
2977 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
2978 var
2979 pan: TPanel;
2980 begin
2981 //pan := gLifts[ID];
2982 pan := g_Map_PanelByGUID(pguid);
2983 if (pan = nil) then exit;
2984 if not pan.isGLift then exit;
2986 if ({gLifts[ID]}pan.LiftType = t) then exit; //!FIXME!TRIGANY!
2988 with {gLifts[ID]} pan do
2989 begin
2990 LiftType := t;
2992 g_Mark(X, Y, Width, Height, MARK_LIFT, false);
2993 //TODO: make separate lift tags, and change tag here
2995 case LiftType of
2996 LIFTTYPE_UP: g_Mark(X, Y, Width, Height, MARK_LIFTUP);
2997 LIFTTYPE_DOWN: g_Mark(X, Y, Width, Height, MARK_LIFTDOWN);
2998 LIFTTYPE_LEFT: g_Mark(X, Y, Width, Height, MARK_LIFTLEFT);
2999 LIFTTYPE_RIGHT: g_Mark(X, Y, Width, Height, MARK_LIFTRIGHT);
3000 end;
3002 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3003 // mark platform as interesting
3004 pan.setDirty();
3005 end;
3006 end;
3009 function g_Map_GetPoint (PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
3010 var
3011 a: Integer;
3012 PointsArray: Array of TRespawnPoint;
3013 begin
3014 Result := False;
3015 SetLength(PointsArray, 0);
3017 if RespawnPoints = nil then
3018 Exit;
3020 for a := 0 to High(RespawnPoints) do
3021 if RespawnPoints[a].PointType = PointType then
3022 begin
3023 SetLength(PointsArray, Length(PointsArray)+1);
3024 PointsArray[High(PointsArray)] := RespawnPoints[a];
3025 end;
3027 if PointsArray = nil then
3028 Exit;
3030 RespawnPoint := PointsArray[Random(Length(PointsArray))];
3031 Result := True;
3032 end;
3034 function g_Map_GetPointCount(PointType: Byte): Word;
3035 var
3036 a: Integer;
3037 begin
3038 Result := 0;
3040 if RespawnPoints = nil then
3041 Exit;
3043 for a := 0 to High(RespawnPoints) do
3044 if RespawnPoints[a].PointType = PointType then
3045 Result := Result + 1;
3046 end;
3048 function g_Map_GetRandomPointType(): Byte;
3049 begin
3050 if RespawnPoints = nil then
3051 Result := 255
3052 else
3053 Result := RespawnPoints[Random(Length(RespawnPoints))].PointType;
3054 end;
3056 function g_Map_HaveFlagPoints(): Boolean;
3057 begin
3058 Result := (FlagPoints[FLAG_RED] <> nil) and (FlagPoints[FLAG_BLUE] <> nil);
3059 end;
3061 procedure g_Map_ResetFlag(Flag: Byte);
3062 begin
3063 with gFlags[Flag] do
3064 begin
3065 Obj.X := -1000;
3066 Obj.Y := -1000;
3067 Obj.Vel.X := 0;
3068 Obj.Vel.Y := 0;
3069 Direction := TDirection.D_LEFT;
3070 State := FLAG_STATE_NONE;
3071 if FlagPoints[Flag] <> nil then
3072 begin
3073 Obj.X := FlagPoints[Flag]^.X;
3074 Obj.Y := FlagPoints[Flag]^.Y;
3075 Direction := FlagPoints[Flag]^.Direction;
3076 State := FLAG_STATE_NORMAL;
3077 end;
3078 Count := -1;
3079 end;
3080 end;
3082 procedure g_Map_SaveState (st: TStream);
3083 var
3084 str: String;
3086 procedure savePanels ();
3087 var
3088 pan: TPanel;
3089 begin
3090 // Ñîõðàíÿåì ïàíåëè
3091 utils.writeInt(st, LongInt(Length(panByGUID)));
3092 for pan in panByGUID do pan.SaveState(st);
3093 end;
3095 procedure saveFlag (flag: PFlag);
3096 var
3097 b: Byte;
3098 begin
3099 utils.writeSign(st, 'FLAG');
3100 utils.writeInt(st, Byte(0)); // version
3101 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3102 utils.writeInt(st, Byte(flag^.RespawnType));
3103 // Ñîñòîÿíèå ôëàãà
3104 utils.writeInt(st, Byte(flag^.State));
3105 // Íàïðàâëåíèå ôëàãà
3106 if flag^.Direction = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
3107 utils.writeInt(st, Byte(b));
3108 // Îáúåêò ôëàãà
3109 Obj_SaveState(st, @flag^.Obj);
3110 end;
3112 begin
3113 savePanels();
3115 // Ñîõðàíÿåì ìóçûêó
3116 utils.writeSign(st, 'MUSI');
3117 utils.writeInt(st, Byte(0));
3118 // Íàçâàíèå ìóçûêè
3119 assert(gMusic <> nil, 'g_Map_SaveState: gMusic = nil');
3120 if gMusic.NoMusic then str := '' else str := gMusic.Name;
3121 utils.writeStr(st, str);
3122 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3123 utils.writeInt(st, LongWord(gMusic.GetPosition()));
3124 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3125 utils.writeBool(st, gMusic.SpecPause);
3127 ///// Ñîõðàíÿåì êîëè÷åñòâî ìîíñòðîâ: /////
3128 utils.writeInt(st, LongInt(gTotalMonsters));
3129 ///// /////
3131 //// Ñîõðàíÿåì ôëàãè, åñëè ýòî CTF: /////
3132 if (gGameSettings.GameMode = GM_CTF) then
3133 begin
3134 // Ôëàã Êðàñíîé êîìàíäû
3135 saveFlag(@gFlags[FLAG_RED]);
3136 // Ôëàã Ñèíåé êîìàíäû
3137 saveFlag(@gFlags[FLAG_BLUE]);
3138 end;
3139 ///// /////
3141 ///// Ñîõðàíÿåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3142 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3143 begin
3144 // Î÷êè Êðàñíîé êîìàíäû
3145 utils.writeInt(st, SmallInt(gTeamStat[TEAM_RED].Goals));
3146 // Î÷êè Ñèíåé êîìàíäû
3147 utils.writeInt(st, SmallInt(gTeamStat[TEAM_BLUE].Goals));
3148 end;
3149 ///// /////
3150 end;
3153 procedure g_Map_LoadState (st: TStream);
3154 var
3155 dw: DWORD;
3156 str: String;
3157 boo: Boolean;
3159 procedure loadPanels ();
3160 var
3161 pan: TPanel;
3162 begin
3163 // Çàãðóæàåì ïàíåëè
3164 if (Length(panByGUID) <> utils.readLongInt(st)) then raise XStreamError.Create('invalid number of saved panels');
3165 for pan in panByGUID do
3166 begin
3167 pan.LoadState(st);
3168 if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
3169 end;
3170 end;
3172 procedure loadFlag (flag: PFlag);
3173 var
3174 b: Byte;
3175 begin
3176 // Ñèãíàòóðà ôëàãà
3177 if not utils.checkSign(st, 'FLAG') then raise XStreamError.Create('invalid flag signature');
3178 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid flag version');
3179 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3180 flag^.RespawnType := utils.readByte(st);
3181 // Ñîñòîÿíèå ôëàãà
3182 flag^.State := utils.readByte(st);
3183 // Íàïðàâëåíèå ôëàãà
3184 b := utils.readByte(st);
3185 if (b = 1) then flag^.Direction := TDirection.D_LEFT else flag^.Direction := TDirection.D_RIGHT; // b = 2
3186 // Îáúåêò ôëàãà
3187 Obj_LoadState(@flag^.Obj, st);
3188 end;
3190 begin
3191 if (st = nil) then exit;
3193 ///// Çàãðóæàåì ñïèñêè ïàíåëåé: /////
3194 loadPanels();
3195 ///// /////
3197 // Îáíîâëÿåì êàðòó ñòîëêíîâåíèé è ñåòêó
3198 g_GFX_Init();
3199 //mapCreateGrid();
3201 ///// Çàãðóæàåì ìóçûêó: /////
3202 if not utils.checkSign(st, 'MUSI') then raise XStreamError.Create('invalid music signature');
3203 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid music version');
3204 // Íàçâàíèå ìóçûêè
3205 assert(gMusic <> nil, 'g_Map_LoadState: gMusic = nil');
3206 str := utils.readStr(st);
3207 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3208 dw := utils.readLongWord(st);
3209 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3210 boo := utils.readBool(st);
3211 // Çàïóñêàåì ýòó ìóçûêó
3212 gMusic.SetByName(str);
3213 gMusic.SpecPause := boo;
3214 gMusic.Play();
3215 gMusic.Pause(true);
3216 gMusic.SetPosition(dw);
3217 ///// /////
3219 ///// Çàãðóæàåì êîëè÷åñòâî ìîíñòðîâ: /////
3220 gTotalMonsters := utils.readLongInt(st);
3221 ///// /////
3223 //// Çàãðóæàåì ôëàãè, åñëè ýòî CTF: /////
3224 if (gGameSettings.GameMode = GM_CTF) then
3225 begin
3226 // Ôëàã Êðàñíîé êîìàíäû
3227 loadFlag(@gFlags[FLAG_RED]);
3228 // Ôëàã Ñèíåé êîìàíäû
3229 loadFlag(@gFlags[FLAG_BLUE]);
3230 end;
3231 ///// /////
3233 ///// Çàãðóæàåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3234 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3235 begin
3236 // Î÷êè Êðàñíîé êîìàíäû
3237 gTeamStat[TEAM_RED].Goals := utils.readSmallInt(st);
3238 // Î÷êè Ñèíåé êîìàíäû
3239 gTeamStat[TEAM_BLUE].Goals := utils.readSmallInt(st);
3240 end;
3241 ///// /////
3242 end;
3245 // trace liquid, stepping by `dx` and `dy`
3246 // return last seen liquid coords, and `false` if we're started outside of the liquid
3247 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
3248 const
3249 MaskLiquid = GridTagWater or GridTagAcid1 or GridTagAcid2;
3250 begin
3251 topx := x;
3252 topy := y;
3253 // started outside of the liquid?
3254 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then begin result := false; exit; end;
3255 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then begin result := false; exit; end;
3256 if (dx = 0) and (dy = 0) then begin result := false; exit; end; // sanity check
3257 result := true;
3258 while true do
3259 begin
3260 Inc(x, dx);
3261 Inc(y, dy);
3262 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then exit; // out of the water, just exit
3263 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then exit; // out of the water, just exit
3264 topx := x;
3265 topy := y;
3266 end;
3267 end;
3270 begin
3271 DynWarningCB := mapWarningCB;
3272 end.