DEADSOFTWARE

fixed texture trigger bug
[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, either version 3 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *)
16 {$INCLUDE ../shared/a_modes.inc}
17 {$DEFINE MAP_DEBUG_ENABLED_FLAG}
18 unit g_map;
20 interface
22 uses
23 SysUtils, Classes, mempool,
24 e_graphics, g_basic, MAPDEF, g_textures,
25 g_phys, utils, g_panel, g_grid, md5, binheap, xprofiler, xparser, xdynrec;
27 type
28 TMapInfo = record
29 Map: String;
30 Name: String;
31 Description: String;
32 Author: String;
33 MusicName: String;
34 SkyName: String;
35 Height: Word;
36 Width: Word;
37 end;
39 PRespawnPoint = ^TRespawnPoint;
40 TRespawnPoint = record
41 X, Y: Integer;
42 Direction: TDirection;
43 PointType: Byte;
44 end;
46 PFlagPoint = ^TFlagPoint;
47 TFlagPoint = TRespawnPoint;
49 PFlag = ^TFlag;
50 TFlag = record
51 Obj: TObj;
52 RespawnType: Byte;
53 State: Byte;
54 Count: Integer;
55 CaptureTime: LongWord;
56 Animation: TAnimation;
57 Direction: TDirection;
58 end;
60 function g_Map_Load(Res: String): Boolean;
61 function g_Map_GetMapInfo(Res: String): TMapInfo;
62 function g_Map_GetMapsList(WADName: String): SSArray;
63 function g_Map_Exist(Res: String): Boolean;
64 procedure g_Map_Free(freeTextures: Boolean=true);
65 procedure g_Map_Update();
67 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
69 procedure g_Map_DrawPanels (PanelType: Word; hasAmbient: Boolean; constref ambColor: TDFColor); // unaccelerated
70 procedure g_Map_CollectDrawPanels (x0, y0, wdt, hgt: Integer);
72 procedure g_Map_DrawBack(dx, dy: Integer);
73 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word;
74 PanelType: Word; b1x3: Boolean=false): Boolean;
75 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
77 procedure g_Map_EnableWallGUID (pguid: Integer);
78 procedure g_Map_DisableWallGUID (pguid: Integer);
79 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
81 // HACK!!!
82 procedure g_Map_EnableWall_XXX (ID: DWORD);
83 procedure g_Map_DisableWall_XXX (ID: DWORD);
84 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer);
86 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
88 procedure g_Map_ReAdd_DieTriggers();
89 function g_Map_IsSpecialTexture(Texture: String): Boolean;
91 function g_Map_GetPoint(PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
92 function g_Map_GetPointCount(PointType: Byte): Word;
94 function g_Map_HaveFlagPoints(): Boolean;
96 procedure g_Map_ResetFlag(Flag: Byte);
97 procedure g_Map_DrawFlags();
99 procedure g_Map_SaveState (st: TStream);
100 procedure g_Map_LoadState (st: TStream);
102 procedure g_Map_DrawPanelShadowVolumes(lightX: Integer; lightY: Integer; radius: Integer);
104 // returns panel or nil
105 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
106 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
108 // returns panel or nil
109 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
110 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
112 type
113 TForEachPanelCB = function (pan: TPanel): Boolean is nested; // return `true` to stop
115 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
116 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
118 // trace liquid, stepping by `dx` and `dy`
119 // return last seen liquid coords, and `false` if we're started outside of the liquid
120 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
123 // return `true` from `cb` to stop
124 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
126 procedure g_Map_NetSendInterestingPanels (); // yay!
129 procedure g_Map_ProfilersBegin ();
130 procedure g_Map_ProfilersEnd ();
133 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
136 function g_Map_MinX (): Integer; inline;
137 function g_Map_MinY (): Integer; inline;
138 function g_Map_MaxX (): Integer; inline;
139 function g_Map_MaxY (): Integer; inline;
141 const
142 NNF_NO_NAME = 0;
143 NNF_NAME_BEFORE = 1;
144 NNF_NAME_EQUALS = 2;
145 NNF_NAME_AFTER = 3;
147 function g_Texture_NumNameFindStart(name: String): Boolean;
148 function g_Texture_NumNameFindNext(var newName: String): Byte;
150 const
151 RESPAWNPOINT_PLAYER1 = 1;
152 RESPAWNPOINT_PLAYER2 = 2;
153 RESPAWNPOINT_DM = 3;
154 RESPAWNPOINT_RED = 4;
155 RESPAWNPOINT_BLUE = 5;
157 FLAG_NONE = 0;
158 FLAG_RED = 1;
159 FLAG_BLUE = 2;
160 FLAG_DOM = 3;
162 FLAG_STATE_NONE = 0;
163 FLAG_STATE_NORMAL = 1;
164 FLAG_STATE_DROPPED = 2;
165 FLAG_STATE_CAPTURED = 3;
166 FLAG_STATE_SCORED = 4; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
167 FLAG_STATE_RETURNED = 5; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
169 FLAG_TIME = 720; // 20 seconds
171 SKY_STRETCH: Single = 1.5;
173 const
174 GridTagInvalid = 0;
176 (* draw order:
177 PANEL_BACK
178 PANEL_STEP
179 PANEL_WALL
180 PANEL_CLOSEDOOR
181 PANEL_ACID1
182 PANEL_ACID2
183 PANEL_WATER
184 PANEL_FORE
185 *)
186 // sorted by draw priority
187 GridTagBack = 1 shl 0; // gRenderBackgrounds
188 GridTagStep = 1 shl 1; // gSteps
189 GridTagWall = 1 shl 2; // gWalls
190 GridTagDoor = 1 shl 3; // gWalls
191 GridTagAcid1 = 1 shl 4; // gAcid1
192 GridTagAcid2 = 1 shl 5; // gAcid2
193 GridTagWater = 1 shl 6; // gWater
194 GridTagFore = 1 shl 7; // gRenderForegrounds
195 // the following are invisible
196 GridTagLift = 1 shl 8; // gLifts
197 GridTagBlockMon = 1 shl 9; // gBlockMon
199 GridTagObstacle = (GridTagStep or GridTagWall or GridTagDoor);
200 GridTagLiquid = (GridTagAcid1 or GridTagAcid2 or GridTagWater);
202 GridDrawableMask = (GridTagBack or GridTagStep or GridTagWall or GridTagDoor or GridTagAcid1 or GridTagAcid2 or GridTagWater or GridTagFore);
205 type
206 TBinHeapPanelDrawCmp = class
207 public
208 class function less (const a, b: TPanel): Boolean; inline;
209 end;
211 TBinHeapPanelDraw = specialize TBinaryHeapBase<TPanel, TBinHeapPanelDrawCmp>;
213 var
214 gWalls: TPanelArray;
215 gRenderBackgrounds: TPanelArray;
216 gRenderForegrounds: TPanelArray;
217 gWater, gAcid1, gAcid2: TPanelArray;
218 gSteps: TPanelArray;
219 gLifts: TPanelArray;
220 gBlockMon: TPanelArray;
221 gFlags: array [FLAG_RED..FLAG_BLUE] of TFlag;
222 //gDOMFlags: array of TFlag;
223 gMapInfo: TMapInfo;
224 gBackSize: TDFPoint;
225 gDoorMap: array of array of DWORD;
226 gLiftMap: array of array of DWORD;
227 gWADHash: TMD5Digest;
228 BackID: DWORD = DWORD(-1);
229 gExternalResources: TStringList;
230 gMovingWallIds: array of Integer = nil;
232 gdbg_map_use_accel_render: Boolean = true;
233 gdbg_map_use_accel_coldet: Boolean = true;
234 profMapCollision: TProfiler = nil; //WARNING: FOR DEBUGGING ONLY!
235 gDrawPanelList: TBinHeapPanelDraw = nil; // binary heap of all walls we have to render, populated by `g_Map_CollectDrawPanels()`
237 gCurrentMap: TDynRecord = nil;
238 gCurrentMapFileName: AnsiString = ''; // so we can skip texture reloading
239 gTestMap: String = '';
242 function panelTypeToTag (panelType: Word): Integer; // returns GridTagXXX
245 type
246 TPanelGrid = specialize TBodyGridBase<TPanel>;
248 var
249 mapGrid: TPanelGrid = nil; // DO NOT USE! public for debugging only!
252 implementation
254 uses
255 e_input, g_main, e_log, e_texture, g_items, g_gfx, g_console,
256 GL, GLExt, g_weapons, g_game, g_sound, e_sound, CONFIG,
257 g_options, g_triggers, g_player,
258 Math, g_monsters, g_saveload, g_language, g_netmsg,
259 sfs, xstreams, hashtable, wadreader,
260 ImagingTypes, Imaging, ImagingUtility,
261 ImagingGif, ImagingNetworkGraphics;
263 const
264 FLAGRECT: TRectWH = (X:15; Y:12; Width:33; Height:52);
265 MUSIC_SIGNATURE = $4953554D; // 'MUSI'
266 FLAG_SIGNATURE = $47414C46; // 'FLAG'
269 // ////////////////////////////////////////////////////////////////////////// //
270 procedure mapWarningCB (const msg: AnsiString; line, col: Integer);
271 begin
272 if (line > 0) then
273 begin
274 e_LogWritefln('parse error at (%s,%s): %s', [line, col, msg], TMsgType.Warning);
275 end
276 else
277 begin
278 e_LogWritefln('parse error: %s', [msg], TMsgType.Warning);
279 end;
280 end;
283 // ////////////////////////////////////////////////////////////////////////// //
284 var
285 panByGUID: array of TPanel = nil;
288 // ////////////////////////////////////////////////////////////////////////// //
289 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
290 begin
291 //if (panByGUID = nil) or (not panByGUID.get(aguid, result)) then result := nil;
292 if (aguid >= 0) and (aguid < Length(panByGUID)) then result := panByGUID[aguid] else result := nil;
293 end;
296 // return `true` from `cb` to stop
297 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
298 var
299 pan: TPanel;
300 begin
301 result := nil;
302 if not assigned(cb) then exit;
303 for pan in panByGUID do
304 begin
305 if cb(pan) then begin result := pan; exit; end;
306 end;
307 end;
310 procedure g_Map_NetSendInterestingPanels ();
311 var
312 pan: TPanel;
313 begin
314 if g_Game_IsServer and g_Game_IsNet then
315 begin
316 for pan in panByGUID do
317 begin
318 if pan.gncNeedSend then MH_SEND_PanelState(pan.guid);
319 end;
320 end;
321 end;
324 // ////////////////////////////////////////////////////////////////////////// //
325 function g_Map_MinX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0 else result := 0; end;
326 function g_Map_MinY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0 else result := 0; end;
327 function g_Map_MaxX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0+mapGrid.gridWidth-1 else result := 0; end;
328 function g_Map_MaxY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0+mapGrid.gridHeight-1 else result := 0; end;
331 // ////////////////////////////////////////////////////////////////////////// //
332 var
333 dfmapdef: TDynMapDef = nil;
336 procedure loadMapDefinition ();
337 var
338 pr: TTextParser = nil;
339 st: TStream = nil;
340 WAD: TWADFile = nil;
341 begin
342 if (dfmapdef <> nil) then exit;
344 try
345 e_LogWritefln('parsing "mapdef.txt"...', []);
346 st := openDiskFileRO(DataDir+'mapdef.txt');
347 e_LogWritefln('found local "%smapdef.txt"', [DataDir]);
348 except
349 st := nil;
350 end;
352 if (st = nil) then
353 begin
354 WAD := TWADFile.Create();
355 if not WAD.ReadFile(GameWAD) then
356 begin
357 //raise Exception.Create('cannot load "game.wad"');
358 st := nil;
359 end
360 else
361 begin
362 st := WAD.openFileStream('mapdef.txt');
363 end;
364 end;
366 try
367 if (st = nil) then
368 begin
369 //raise Exception.Create('cannot open "mapdef.txt"');
370 e_LogWriteln('using default "mapdef.txt"...');
371 pr := TStrTextParser.Create(defaultMapDef);
372 end
373 else
374 begin
375 pr := TFileTextParser.Create(st);
376 end;
377 except on e: Exception do
378 begin
379 e_LogWritefln('something is VERY wrong here! -- ', [e.message]);
380 raise;
381 end;
382 end;
384 try
385 dfmapdef := TDynMapDef.Create(pr);
386 except
387 on e: TDynParseException do
388 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
389 on e: Exception do
390 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [pr.tokLine, pr.tokCol, e.message]);
391 end;
393 st.Free();
394 WAD.Free();
395 end;
398 // ////////////////////////////////////////////////////////////////////////// //
399 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
400 var
401 wst: TSFSMemoryChunkStream = nil;
402 begin
403 result := nil;
404 if (dataLen < 4) then exit;
406 if (dfmapdef = nil) then writeln('need to load mapdef');
407 loadMapDefinition();
408 if (dfmapdef = nil) then raise Exception.Create('internal map loader error');
410 wst := TSFSMemoryChunkStream.Create(data, dataLen);
411 try
412 result := dfmapdef.parseMap(wst);
413 except
414 on e: TDynParseException do
415 begin
416 e_LogWritefln('ERROR at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
417 wst.Free();
418 result := nil;
419 exit;
420 end;
421 on e: Exception do
422 begin
423 e_LogWritefln('ERROR: %s', [e.message]);
424 wst.Free();
425 result := nil;
426 exit;
427 end;
428 end;
430 //e_LogWriteln('map parsed.');
431 end;
434 // ////////////////////////////////////////////////////////////////////////// //
435 var
436 NNF_PureName: String; // Èìÿ òåêñòóðû áåç öèôð â êîíöå
437 NNF_FirstNum: Integer; // ×èñëî ó íà÷àëüíîé òåêñòóðû
438 NNF_CurrentNum: Integer; // Ñëåäóþùåå ÷èñëî ó òåêñòóðû
441 function g_Texture_NumNameFindStart(name: String): Boolean;
442 var
443 i: Integer;
445 begin
446 Result := False;
447 NNF_PureName := '';
448 NNF_FirstNum := -1;
449 NNF_CurrentNum := -1;
451 for i := Length(name) downto 1 do
452 if (name[i] = '_') then // "_" - ñèìâîë íà÷àëà íîìåðíîãî ïîñòôèêñà
453 begin
454 if i = Length(name) then
455 begin // Íåò öèôð â êîíöå ñòðîêè
456 Exit;
457 end
458 else
459 begin
460 NNF_PureName := Copy(name, 1, i);
461 Delete(name, 1, i);
462 Break;
463 end;
464 end;
466 // Íå ïåðåâåñòè â ÷èñëî:
467 if not TryStrToInt(name, NNF_FirstNum) then
468 Exit;
470 NNF_CurrentNum := 0;
472 Result := True;
473 end;
476 function g_Texture_NumNameFindNext(var newName: String): Byte;
477 begin
478 if (NNF_PureName = '') or (NNF_CurrentNum < 0) then
479 begin
480 newName := '';
481 Result := NNF_NO_NAME;
482 Exit;
483 end;
485 newName := NNF_PureName + IntToStr(NNF_CurrentNum);
487 if NNF_CurrentNum < NNF_FirstNum then
488 Result := NNF_NAME_BEFORE
489 else
490 if NNF_CurrentNum > NNF_FirstNum then
491 Result := NNF_NAME_AFTER
492 else
493 Result := NNF_NAME_EQUALS;
495 Inc(NNF_CurrentNum);
496 end;
499 // ////////////////////////////////////////////////////////////////////////// //
500 function panelTypeToTag (panelType: Word): Integer;
501 begin
502 case panelType of
503 PANEL_WALL: result := GridTagWall; // gWalls
504 PANEL_OPENDOOR, PANEL_CLOSEDOOR: result := GridTagDoor; // gWalls
505 PANEL_BACK: result := GridTagBack; // gRenderBackgrounds
506 PANEL_FORE: result := GridTagFore; // gRenderForegrounds
507 PANEL_WATER: result := GridTagWater; // gWater
508 PANEL_ACID1: result := GridTagAcid1; // gAcid1
509 PANEL_ACID2: result := GridTagAcid2; // gAcid2
510 PANEL_STEP: result := GridTagStep; // gSteps
511 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: result := GridTagLift; // gLifts -- this is for all lifts
512 PANEL_BLOCKMON: result := GridTagBlockMon; // gBlockMon -- this is for all blockmons
513 else result := GridTagInvalid;
514 end;
515 end;
518 class function TBinHeapPanelDrawCmp.less (const a, b: TPanel): Boolean; inline;
519 begin
520 if (a.tag < b.tag) then begin result := true; exit; end;
521 if (a.tag > b.tag) then begin result := false; exit; end;
522 result := (a.arrIdx < b.arrIdx);
523 end;
525 procedure dplClear ();
526 begin
527 if (gDrawPanelList = nil) then gDrawPanelList := TBinHeapPanelDraw.Create() else gDrawPanelList.clear();
528 end;
531 var
532 Textures: TLevelTextureArray = nil;
533 TextNameHash: THashStrInt = nil; // key: texture name; value: index in `Textures`
534 BadTextNameHash: THashStrInt = nil; // set; so we won't spam with non-existing texture messages
535 RespawnPoints: array of TRespawnPoint;
536 FlagPoints: array[FLAG_RED..FLAG_BLUE] of PFlagPoint;
537 //DOMFlagPoints: Array of TFlagPoint;
540 procedure g_Map_ProfilersBegin ();
541 begin
542 if (profMapCollision = nil) then profMapCollision := TProfiler.Create('COLSOLID', g_profile_history_size);
543 profMapCollision.mainBegin(g_profile_collision);
544 // create sections
545 if g_profile_collision then
546 begin
547 profMapCollision.sectionBegin('*solids');
548 profMapCollision.sectionEnd();
549 profMapCollision.sectionBegin('liquids');
550 profMapCollision.sectionEnd();
551 end;
552 end;
554 procedure g_Map_ProfilersEnd ();
555 begin
556 if (profMapCollision <> nil) then profMapCollision.mainEnd();
557 end;
560 // wall index in `gWalls` or -1
561 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
562 var
563 ex, ey: Integer;
564 begin
565 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, (GridTagWall or GridTagDoor));
566 if (result <> nil) then
567 begin
568 if (hitx <> nil) then hitx^ := ex;
569 if (hity <> nil) then hity^ := ey;
570 end
571 else
572 begin
573 if (hitx <> nil) then hitx^ := x1;
574 if (hity <> nil) then hity^ := y1;
575 end;
576 end;
578 // returns panel or nil
579 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
580 var
581 ex, ey: Integer;
582 begin
583 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, tag);
584 if (result <> nil) then
585 begin
586 if (hitx <> nil) then hitx^ := ex;
587 if (hity <> nil) then hity^ := ey;
588 end
589 else
590 begin
591 if (hitx <> nil) then hitx^ := x1;
592 if (hity <> nil) then hity^ := y1;
593 end;
594 end;
597 function xxPanAtPointChecker (pan: TPanel; panelType: Word): Boolean; inline;
598 begin
599 if ((pan.tag and GridTagLift) <> 0) then
600 begin
601 // stop if the lift of the right type
602 result :=
603 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = 0)) or
604 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = 1)) or
605 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = 2)) or
606 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = 3)));
607 exit;
608 end;
609 result := true; // otherwise, stop anyway, 'cause `forEachAtPoint()` is guaranteed to call this only for correct panels
610 end;
612 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
613 var
614 tagmask: Integer = 0;
615 mwit: PPanel;
616 it: TPanelGrid.Iter;
617 begin
618 result := false;
620 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
621 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
622 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
623 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
624 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
625 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
626 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
628 if (tagmask = 0) then exit;// just in case
630 if ((tagmask and GridTagLift) <> 0) then
631 begin
632 // slow
633 it := mapGrid.forEachAtPoint(x, y, tagmask);
634 for mwit in it do if (xxPanAtPointChecker(mwit^, PanelType)) then begin result := true; break; end;
635 end
636 else
637 begin
638 // fast
639 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true);
640 result := (it.length <> 0); // firsthit
641 end;
642 it.release();
643 end;
646 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
647 var
648 it: TPanelGrid.Iter;
649 begin
650 result := nil;
651 if (tagmask = 0) then exit;
652 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true); // firsthit
653 if (it.length <> 0) then result := it.first^;
654 it.release();
655 end;
658 function g_Map_IsSpecialTexture(Texture: String): Boolean;
659 begin
660 Result := (Texture = TEXTURE_NAME_WATER) or
661 (Texture = TEXTURE_NAME_ACID1) or
662 (Texture = TEXTURE_NAME_ACID2);
663 end;
665 procedure CreateDoorMap();
666 var
667 PanelArray: Array of record
668 X, Y: Integer;
669 Width, Height: Word;
670 Active: Boolean;
671 PanelID: DWORD;
672 end;
673 a, b, c, m, i, len: Integer;
674 ok: Boolean;
675 begin
676 if gWalls = nil then
677 Exit;
679 i := 0;
680 len := 128;
681 SetLength(PanelArray, len);
683 for a := 0 to High(gWalls) do
684 if gWalls[a].Door then
685 begin
686 PanelArray[i].X := gWalls[a].X;
687 PanelArray[i].Y := gWalls[a].Y;
688 PanelArray[i].Width := gWalls[a].Width;
689 PanelArray[i].Height := gWalls[a].Height;
690 PanelArray[i].Active := True;
691 PanelArray[i].PanelID := a;
693 i := i + 1;
694 if i = len then
695 begin
696 len := len + 128;
697 SetLength(PanelArray, len);
698 end;
699 end;
701 // Íåò äâåðåé:
702 if i = 0 then
703 begin
704 PanelArray := nil;
705 Exit;
706 end;
708 SetLength(gDoorMap, 0);
710 g_Game_SetLoadingText(_lc[I_LOAD_DOOR_MAP], i-1, False);
712 for a := 0 to i-1 do
713 if PanelArray[a].Active then
714 begin
715 PanelArray[a].Active := False;
716 m := Length(gDoorMap);
717 SetLength(gDoorMap, m+1);
718 SetLength(gDoorMap[m], 1);
719 gDoorMap[m, 0] := PanelArray[a].PanelID;
720 ok := True;
722 while ok do
723 begin
724 ok := False;
726 for b := 0 to i-1 do
727 if PanelArray[b].Active then
728 for c := 0 to High(gDoorMap[m]) do
729 if {((gRenderWalls[PanelArray[b].RenderPanelID].TextureID = gRenderWalls[gDoorMap[m, c]].TextureID) or
730 gRenderWalls[PanelArray[b].RenderPanelID].Hide or gRenderWalls[gDoorMap[m, c]].Hide) and}
731 g_CollideAround(PanelArray[b].X, PanelArray[b].Y,
732 PanelArray[b].Width, PanelArray[b].Height,
733 gWalls[gDoorMap[m, c]].X,
734 gWalls[gDoorMap[m, c]].Y,
735 gWalls[gDoorMap[m, c]].Width,
736 gWalls[gDoorMap[m, c]].Height) then
737 begin
738 PanelArray[b].Active := False;
739 SetLength(gDoorMap[m],
740 Length(gDoorMap[m])+1);
741 gDoorMap[m, High(gDoorMap[m])] := PanelArray[b].PanelID;
742 ok := True;
743 Break;
744 end;
745 end;
747 g_Game_StepLoading();
748 end;
750 PanelArray := nil;
751 end;
753 procedure CreateLiftMap();
754 var
755 PanelArray: Array of record
756 X, Y: Integer;
757 Width, Height: Word;
758 Active: Boolean;
759 end;
760 a, b, c, len, i, j: Integer;
761 ok: Boolean;
762 begin
763 if gLifts = nil then
764 Exit;
766 len := Length(gLifts);
767 SetLength(PanelArray, len);
769 for a := 0 to len-1 do
770 begin
771 PanelArray[a].X := gLifts[a].X;
772 PanelArray[a].Y := gLifts[a].Y;
773 PanelArray[a].Width := gLifts[a].Width;
774 PanelArray[a].Height := gLifts[a].Height;
775 PanelArray[a].Active := True;
776 end;
778 SetLength(gLiftMap, len);
779 i := 0;
781 g_Game_SetLoadingText(_lc[I_LOAD_LIFT_MAP], len-1, False);
783 for a := 0 to len-1 do
784 if PanelArray[a].Active then
785 begin
786 PanelArray[a].Active := False;
787 SetLength(gLiftMap[i], 32);
788 j := 0;
789 gLiftMap[i, j] := a;
790 ok := True;
792 while ok do
793 begin
794 ok := False;
795 for b := 0 to len-1 do
796 if PanelArray[b].Active then
797 for c := 0 to j do
798 if g_CollideAround(PanelArray[b].X,
799 PanelArray[b].Y,
800 PanelArray[b].Width,
801 PanelArray[b].Height,
802 PanelArray[gLiftMap[i, c]].X,
803 PanelArray[gLiftMap[i, c]].Y,
804 PanelArray[gLiftMap[i, c]].Width,
805 PanelArray[gLiftMap[i, c]].Height) then
806 begin
807 PanelArray[b].Active := False;
808 j := j+1;
809 if j > High(gLiftMap[i]) then
810 SetLength(gLiftMap[i],
811 Length(gLiftMap[i])+32);
813 gLiftMap[i, j] := b;
814 ok := True;
816 Break;
817 end;
818 end;
820 SetLength(gLiftMap[i], j+1);
821 i := i+1;
823 g_Game_StepLoading();
824 end;
826 SetLength(gLiftMap, i);
828 PanelArray := nil;
829 end;
831 function CreatePanel (PanelRec: TDynRecord; AddTextures: TAddTextureArray; CurTex: Integer): Integer;
832 var
833 len: Integer;
834 panels: ^TPanelArray;
835 pan: TPanel;
836 pguid: Integer;
837 begin
838 Result := -1;
840 case PanelRec.PanelType of
841 PANEL_WALL, PANEL_OPENDOOR, PANEL_CLOSEDOOR: panels := @gWalls;
842 PANEL_BACK: panels := @gRenderBackgrounds;
843 PANEL_FORE: panels := @gRenderForegrounds;
844 PANEL_WATER: panels := @gWater;
845 PANEL_ACID1: panels := @gAcid1;
846 PANEL_ACID2: panels := @gAcid2;
847 PANEL_STEP: panels := @gSteps;
848 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: panels := @gLifts;
849 PANEL_BLOCKMON: panels := @gBlockMon;
850 else exit;
851 end;
853 len := Length(panels^);
854 SetLength(panels^, len+1);
856 pguid := Length(panByGUID);
857 SetLength(panByGUID, pguid+1); //FIXME!
858 pan := TPanel.Create(PanelRec, AddTextures, CurTex, Textures, pguid);
859 assert(pguid >= 0);
860 assert(pguid < Length(panByGUID));
861 panByGUID[pguid] := pan;
862 panels^[len] := pan;
863 pan.arrIdx := len;
864 pan.proxyId := -1;
865 pan.tag := panelTypeToTag(PanelRec.PanelType);
867 PanelRec.user['panel_guid'] := pguid;
869 //result := len;
870 result := pguid;
871 end;
874 function CreateNullTexture(RecName: String): Integer;
875 begin
876 RecName := toLowerCase1251(RecName);
877 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
878 if TextNameHash.get(RecName, result) then exit; // i found her!
880 SetLength(Textures, Length(Textures)+1);
881 result := High(Textures);
883 with Textures[High(Textures)] do
884 begin
885 TextureName := RecName;
886 Width := 1;
887 Height := 1;
888 Anim := False;
889 TextureID := LongWord(TEXTURE_NONE);
890 end;
892 TextNameHash.put(RecName, result);
893 end;
896 function CreateTexture(RecName: AnsiString; Map: string; log: Boolean): Integer;
897 var
898 WAD: TWADFile;
899 TextureData: Pointer;
900 WADName: String;
901 a, ResLength: Integer;
902 begin
903 RecName := toLowerCase1251(RecName);
904 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
905 if TextNameHash.get(RecName, result) then
906 begin
907 // i found her!
908 //e_LogWritefln('texture ''%s'' already loaded (%s)', [RecName, result]);
909 exit;
910 end;
912 Result := -1;
914 if (BadTextNameHash <> nil) and BadTextNameHash.has(RecName) then exit; // don't do it again and again
917 if Textures <> nil then
918 begin
919 for a := 0 to High(Textures) do
920 begin
921 if (Textures[a].TextureName = RecName) then
922 begin // Òåêñòóðà ñ òàêèì èìåíåì óæå åñòü
923 e_LogWritefln('texture ''%s'' already loaded', [RecName]);
924 Result := a;
925 Exit;
926 end;
927 end;
928 end;
931 // Òåêñòóðû ñî ñïåöèàëüíûìè èìåíàìè (âîäà, ëàâà, êèñëîòà):
932 if (RecName = TEXTURE_NAME_WATER) or
933 (RecName = TEXTURE_NAME_ACID1) or
934 (RecName = TEXTURE_NAME_ACID2) then
935 begin
936 SetLength(Textures, Length(Textures)+1);
938 with Textures[High(Textures)] do
939 begin
940 TextureName := RecName;
941 if (TextureName = TEXTURE_NAME_WATER) then TextureID := LongWord(TEXTURE_SPECIAL_WATER)
942 else if (TextureName = TEXTURE_NAME_ACID1) then TextureID := LongWord(TEXTURE_SPECIAL_ACID1)
943 else if (TextureName = TEXTURE_NAME_ACID2) then TextureID := LongWord(TEXTURE_SPECIAL_ACID2);
945 Anim := False;
946 end;
948 result := High(Textures);
949 TextNameHash.put(RecName, result);
950 Exit;
951 end;
953 // Çàãðóæàåì ðåñóðñ òåêñòóðû â ïàìÿòü èç WAD'à:
954 WADName := g_ExtractWadName(RecName);
956 WAD := TWADFile.Create();
958 if WADName <> '' then WADName := GameDir+'/wads/'+WADName else WADName := Map;
960 WAD.ReadFile(WADName);
962 //txname := RecName;
964 if (WADName = Map) and WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength) then
965 begin
966 FreeMem(TextureData);
967 RecName := 'COMMON\ALIEN';
968 end;
971 if WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength, log) then
972 begin
973 SetLength(Textures, Length(Textures)+1);
974 if not e_CreateTextureMem(TextureData, ResLength, Textures[High(Textures)].TextureID) then
975 begin
976 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
977 SetLength(Textures, Length(Textures)-1);
978 result := -1;
979 Exit;
980 end;
981 e_GetTextureSize(Textures[High(Textures)].TextureID, @Textures[High(Textures)].Width, @Textures[High(Textures)].Height);
982 FreeMem(TextureData);
983 Textures[High(Textures)].TextureName := RecName;
984 Textures[High(Textures)].Anim := False;
986 result := High(Textures);
987 TextNameHash.put(RecName, result);
988 end
989 else // Íåò òàêîãî ðåóñðñà â WAD'å
990 begin
991 //e_WriteLog(Format('SHIT! Error loading texture %s : %s', [RecName, g_ExtractFilePathName(RecName)]), MSG_WARNING);
992 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
993 if log and (not BadTextNameHash.get(RecName, a)) then
994 begin
995 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
996 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
997 end;
998 BadTextNameHash.put(RecName, -1);
999 end;
1001 WAD.Free();
1002 end;
1005 function CreateAnimTexture(RecName: String; Map: string; log: Boolean): Integer;
1006 var
1007 WAD: TWADFile;
1008 TextureWAD: PChar = nil;
1009 TextData: Pointer = nil;
1010 TextureData: Pointer = nil;
1011 cfg: TConfig = nil;
1012 WADName: String;
1013 ResLength: Integer;
1014 TextureResource: String;
1015 _width, _height, _framecount, _speed: Integer;
1016 _backanimation: Boolean;
1017 //imgfmt: string;
1018 ia: TDynImageDataArray = nil;
1019 f, c, frdelay, frloop: Integer;
1020 begin
1021 RecName := toLowerCase1251(RecName);
1022 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
1023 if TextNameHash.get(RecName, result) then
1024 begin
1025 // i found her!
1026 //e_LogWritefln('animated texture ''%s'' already loaded (%s)', [RecName, result]);
1027 exit;
1028 end;
1030 result := -1;
1032 //e_LogWritefln('*** Loading animated texture "%s"', [RecName]);
1034 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1035 if BadTextNameHash.get(RecName, f) then
1036 begin
1037 //e_WriteLog(Format('no animation texture %s (don''t worry)', [RecName]), MSG_NOTIFY);
1038 exit;
1039 end;
1041 // ×èòàåì WAD-ðåñóðñ àíèì.òåêñòóðû èç WAD'à â ïàìÿòü:
1042 WADName := g_ExtractWadName(RecName);
1044 WAD := TWADFile.Create();
1045 try
1046 if WADName <> '' then WADName := GameDir+'/wads/'+WADName else WADName := Map;
1048 WAD.ReadFile(WADName);
1050 if not WAD.GetResource(g_ExtractFilePathName(RecName), TextureWAD, ResLength, log) then
1051 begin
1052 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1053 if log and (not BadTextNameHash.get(RecName, f)) then
1054 begin
1055 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1056 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1057 end;
1058 BadTextNameHash.put(RecName, -1);
1059 exit;
1060 end;
1062 {TEST
1063 if WADName = Map then
1064 begin
1065 //FreeMem(TextureWAD);
1066 if not WAD.GetResource('COMMON/animation', TextureWAD, ResLength) then Halt(1);
1067 end;
1070 WAD.FreeWAD();
1072 if ResLength < 6 then
1073 begin
1074 e_WriteLog(Format('Animated texture file "%s" too short', [RecName]), TMsgType.Warning);
1075 BadTextNameHash.put(RecName, -1);
1076 exit;
1077 end;
1079 // ýòî ïòèöà? ýòî ñàìîë¸ò?
1080 if (TextureWAD[0] = 'D') and (TextureWAD[1] = 'F') and
1081 (TextureWAD[2] = 'W') and (TextureWAD[3] = 'A') and (TextureWAD[4] = 'D') then
1082 begin
1083 // íåò, ýòî ñóïåðìåí!
1084 if not WAD.ReadMemory(TextureWAD, ResLength) then
1085 begin
1086 e_WriteLog(Format('Animated texture WAD file "%s" is invalid', [RecName]), TMsgType.Warning);
1087 BadTextNameHash.put(RecName, -1);
1088 exit;
1089 end;
1091 // ×èòàåì INI-ðåñóðñ àíèì. òåêñòóðû è çàïîìèíàåì åãî óñòàíîâêè:
1092 if not WAD.GetResource('TEXT/ANIM', TextData, ResLength) then
1093 begin
1094 e_WriteLog(Format('Animated texture file "%s" has invalid INI', [RecName]), TMsgType.Warning);
1095 BadTextNameHash.put(RecName, -1);
1096 exit;
1097 end;
1099 cfg := TConfig.CreateMem(TextData, ResLength);
1101 TextureResource := cfg.ReadStr('', 'resource', '');
1102 if TextureResource = '' then
1103 begin
1104 e_WriteLog(Format('Animated texture WAD file "%s" has no "resource"', [RecName]), TMsgType.Warning);
1105 BadTextNameHash.put(RecName, -1);
1106 exit;
1107 end;
1109 _width := cfg.ReadInt('', 'framewidth', 0);
1110 _height := cfg.ReadInt('', 'frameheight', 0);
1111 _framecount := cfg.ReadInt('', 'framecount', 0);
1112 _speed := cfg.ReadInt('', 'waitcount', 0);
1113 _backanimation := cfg.ReadBool('', 'backanimation', False);
1115 cfg.Free();
1116 cfg := nil;
1118 // ×èòàåì ðåñóðñ òåêñòóð (êàäðîâ) àíèì. òåêñòóðû â ïàìÿòü:
1119 if not WAD.GetResource('TEXTURES/'+TextureResource, TextureData, ResLength) then
1120 begin
1121 e_WriteLog(Format('Animated texture WAD file "%s" has no texture "%s"', [RecName, 'TEXTURES/'+TextureResource]), TMsgType.Warning);
1122 BadTextNameHash.put(RecName, -1);
1123 exit;
1124 end;
1126 WAD.Free();
1127 WAD := nil;
1129 SetLength(Textures, Length(Textures)+1);
1130 with Textures[High(Textures)] do
1131 begin
1132 // Ñîçäàåì êàäðû àíèì. òåêñòóðû èç ïàìÿòè:
1133 if g_Frames_CreateMemory(@FramesID, '', TextureData, ResLength, _width, _height, _framecount, _backanimation) then
1134 begin
1135 TextureName := RecName;
1136 Width := _width;
1137 Height := _height;
1138 Anim := True;
1139 FramesCount := _framecount;
1140 Speed := _speed;
1141 result := High(Textures);
1142 TextNameHash.put(RecName, result);
1143 end
1144 else
1145 begin
1146 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1147 if log and (not BadTextNameHash.get(RecName, f)) then
1148 begin
1149 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1150 end;
1151 BadTextNameHash.put(RecName, -1);
1152 end;
1153 end;
1154 end
1155 else
1156 begin
1157 // try animated image
1159 imgfmt := DetermineMemoryFormat(TextureWAD, ResLength);
1160 if length(imgfmt) = 0 then
1161 begin
1162 e_WriteLog(Format('Animated texture file "%s" has unknown format', [RecName]), MSG_WARNING);
1163 exit;
1164 end;
1166 GlobalMetadata.ClearMetaItems();
1167 GlobalMetadata.ClearMetaItemsForSaving();
1168 if not LoadMultiImageFromMemory(TextureWAD, ResLength, ia) then
1169 begin
1170 e_WriteLog(Format('Animated texture file "%s" cannot be loaded', [RecName]), TMsgType.Warning);
1171 BadTextNameHash.put(RecName, -1);
1172 exit;
1173 end;
1174 if length(ia) = 0 then
1175 begin
1176 e_WriteLog(Format('Animated texture file "%s" has no frames', [RecName]), TMsgType.Warning);
1177 BadTextNameHash.put(RecName, -1);
1178 exit;
1179 end;
1181 WAD.Free();
1182 WAD := nil;
1184 _width := ia[0].width;
1185 _height := ia[0].height;
1186 _framecount := length(ia);
1187 _speed := 1;
1188 _backanimation := false;
1189 frdelay := -1;
1190 frloop := -666;
1191 if GlobalMetadata.HasMetaItem(SMetaFrameDelay) then
1192 begin
1193 //writeln(' frame delay: ', GlobalMetadata.MetaItems[SMetaFrameDelay]);
1194 try
1195 f := GlobalMetadata.MetaItems[SMetaFrameDelay];
1196 frdelay := f;
1197 if f < 0 then f := 0;
1198 // rounding ;-)
1199 c := f mod 28;
1200 if c < 13 then c := 0 else c := 1;
1201 f := (f div 28)+c;
1202 if f < 1 then f := 1 else if f > 255 then f := 255;
1203 _speed := f;
1204 except
1205 end;
1206 end;
1207 if GlobalMetadata.HasMetaItem(SMetaAnimationLoops) then
1208 begin
1209 //writeln(' frame loop : ', GlobalMetadata.MetaItems[SMetaAnimationLoops]);
1210 try
1211 f := GlobalMetadata.MetaItems[SMetaAnimationLoops];
1212 frloop := f;
1213 if f <> 0 then _backanimation := true; // non-infinite looping == forth-and-back
1214 except
1215 end;
1216 end;
1217 //writeln(' creating animated texture with ', length(ia), ' frames (delay:', _speed, '; backloop:', _backanimation, ') from "', RecName, '"...');
1218 //for f := 0 to high(ia) do writeln(' frame #', f, ': ', ia[f].width, 'x', ia[f].height);
1219 f := ord(_backanimation);
1220 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);
1222 SetLength(Textures, Length(Textures)+1);
1223 // cîçäàåì êàäðû àíèì. òåêñòóðû èç êàðòèíîê
1224 if g_CreateFramesImg(ia, @Textures[High(Textures)].FramesID, '', _backanimation) then
1225 begin
1226 Textures[High(Textures)].TextureName := RecName;
1227 Textures[High(Textures)].Width := _width;
1228 Textures[High(Textures)].Height := _height;
1229 Textures[High(Textures)].Anim := True;
1230 Textures[High(Textures)].FramesCount := length(ia);
1231 Textures[High(Textures)].Speed := _speed;
1232 result := High(Textures);
1233 TextNameHash.put(RecName, result);
1234 //writeln(' CREATED!');
1235 end
1236 else
1237 begin
1238 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1239 if log and (not BadTextNameHash.get(RecName, f)) then
1240 begin
1241 e_WriteLog(Format('Error loading animation texture "%s" images', [RecName]), TMsgType.Warning);
1242 end;
1243 BadTextNameHash.put(RecName, -1);
1244 end;
1245 end;
1246 finally
1247 for f := 0 to High(ia) do FreeImage(ia[f]);
1248 WAD.Free();
1249 cfg.Free();
1250 if (TextureWAD <> nil) then FreeMem(TextureWAD);
1251 if (TextData <> nil) then FreeMem(TextData);
1252 if (TextureData <> nil) then FreeMem(TextureData);
1253 end;
1254 end;
1256 procedure CreateItem(Item: TDynRecord);
1257 begin
1258 if g_Game_IsClient then Exit;
1260 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) and
1261 ByteBool(Item.Options and ITEM_OPTION_ONLYDM) then
1262 Exit;
1264 g_Items_Create(Item.X, Item.Y, Item.ItemType, ByteBool(Item.Options and ITEM_OPTION_FALL),
1265 gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF, GM_COOP]);
1266 end;
1268 procedure CreateArea(Area: TDynRecord);
1269 var
1270 a: Integer;
1271 id: DWORD = 0;
1272 begin
1273 case Area.AreaType of
1274 AREA_DMPOINT, AREA_PLAYERPOINT1, AREA_PLAYERPOINT2,
1275 AREA_REDTEAMPOINT, AREA_BLUETEAMPOINT:
1276 begin
1277 SetLength(RespawnPoints, Length(RespawnPoints)+1);
1278 with RespawnPoints[High(RespawnPoints)] do
1279 begin
1280 X := Area.X;
1281 Y := Area.Y;
1282 Direction := TDirection(Area.Direction);
1284 case Area.AreaType of
1285 AREA_DMPOINT: PointType := RESPAWNPOINT_DM;
1286 AREA_PLAYERPOINT1: PointType := RESPAWNPOINT_PLAYER1;
1287 AREA_PLAYERPOINT2: PointType := RESPAWNPOINT_PLAYER2;
1288 AREA_REDTEAMPOINT: PointType := RESPAWNPOINT_RED;
1289 AREA_BLUETEAMPOINT: PointType := RESPAWNPOINT_BLUE;
1290 end;
1291 end;
1292 end;
1294 AREA_REDFLAG, AREA_BLUEFLAG:
1295 begin
1296 if Area.AreaType = AREA_REDFLAG then a := FLAG_RED else a := FLAG_BLUE;
1298 if FlagPoints[a] <> nil then Exit;
1300 New(FlagPoints[a]);
1302 with FlagPoints[a]^ do
1303 begin
1304 X := Area.X-FLAGRECT.X;
1305 Y := Area.Y-FLAGRECT.Y;
1306 Direction := TDirection(Area.Direction);
1307 end;
1309 with gFlags[a] do
1310 begin
1311 case a of
1312 FLAG_RED: g_Frames_Get(id, 'FRAMES_FLAG_RED');
1313 FLAG_BLUE: g_Frames_Get(id, 'FRAMES_FLAG_BLUE');
1314 end;
1316 Animation := TAnimation.Create(id, True, 8);
1317 Obj.Rect := FLAGRECT;
1319 g_Map_ResetFlag(a);
1320 end;
1321 end;
1323 AREA_DOMFLAG:
1324 begin
1325 {SetLength(DOMFlagPoints, Length(DOMFlagPoints)+1);
1326 with DOMFlagPoints[High(DOMFlagPoints)] do
1327 begin
1328 X := Area.X;
1329 Y := Area.Y;
1330 Direction := TDirection(Area.Direction);
1331 end;
1333 g_Map_CreateFlag(DOMFlagPoints[High(DOMFlagPoints)], FLAG_DOM, FLAG_STATE_NORMAL);}
1334 end;
1335 end;
1336 end;
1338 function CreateTrigger (amapIdx: Integer; Trigger: TDynRecord; atpanid, atrigpanid: Integer): Integer;
1339 var
1340 _trigger: TTrigger;
1341 tp: TPanel;
1342 begin
1343 result := -1;
1344 if g_Game_IsClient and not (Trigger.TriggerType in [TRIGGER_SOUND, TRIGGER_MUSIC]) then Exit;
1346 with _trigger do
1347 begin
1348 mapId := Trigger.id;
1349 mapIndex := amapIdx;
1350 X := Trigger.X;
1351 Y := Trigger.Y;
1352 Width := Trigger.Width;
1353 Height := Trigger.Height;
1354 Enabled := Trigger.Enabled;
1355 TexturePanelGUID := atpanid;
1356 TriggerType := Trigger.TriggerType;
1357 ActivateType := Trigger.ActivateType;
1358 Keys := Trigger.Keys;
1359 trigPanelGUID := atrigpanid;
1360 // HACK: used in TPanel.CanChangeTexture. maybe there's a better way?
1361 if TexturePanelGUID <> -1 then
1362 begin
1363 tp := g_Map_PanelByGUID(TexturePanelGUID);
1364 if (tp <> nil) then tp.hasTexTrigger := True;
1365 end;
1366 end;
1368 result := Integer(g_Triggers_Create(_trigger, Trigger));
1369 end;
1371 procedure CreateMonster(monster: TDynRecord);
1372 var
1373 a: Integer;
1374 mon: TMonster;
1375 begin
1376 if g_Game_IsClient then Exit;
1378 if (gGameSettings.GameType = GT_SINGLE)
1379 or LongBool(gGameSettings.Options and GAME_OPTION_MONSTERS) then
1380 begin
1381 mon := g_Monsters_Create(monster.MonsterType, monster.X, monster.Y, TDirection(monster.Direction));
1383 if gTriggers <> nil then
1384 begin
1385 for a := 0 to High(gTriggers) do
1386 begin
1387 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1388 begin
1389 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1390 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1391 end;
1392 end;
1393 end;
1395 if monster.MonsterType <> MONSTER_BARREL then Inc(gTotalMonsters);
1396 end;
1397 end;
1399 procedure g_Map_ReAdd_DieTriggers();
1401 function monsDieTrig (mon: TMonster): Boolean;
1402 var
1403 a: Integer;
1404 //tw: TStrTextWriter;
1405 begin
1406 result := false; // don't stop
1407 mon.ClearTriggers();
1408 for a := 0 to High(gTriggers) do
1409 begin
1410 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1411 begin
1412 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1414 tw := TStrTextWriter.Create();
1415 try
1416 gTriggers[a].trigData.writeTo(tw);
1417 e_LogWritefln('=== trigger #%s ==='#10'%s'#10'---', [a, tw.str]);
1418 finally
1419 tw.Free();
1420 end;
1422 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1423 end;
1424 end;
1425 end;
1427 begin
1428 if g_Game_IsClient then Exit;
1430 g_Mons_ForEach(monsDieTrig);
1431 end;
1433 function extractWadName(resourceName: string): string;
1434 var
1435 posN: Integer;
1436 begin
1437 posN := Pos(':', resourceName);
1438 if posN > 0 then
1439 Result:= Copy(resourceName, 0, posN-1)
1440 else
1441 Result := '';
1442 end;
1444 procedure addResToExternalResList(res: string);
1445 begin
1446 res := extractWadName(res);
1447 if (res <> '') and (gExternalResources.IndexOf(res) = -1) then
1448 gExternalResources.Add(res);
1449 end;
1451 procedure generateExternalResourcesList({mapReader: TMapReader_1}map: TDynRecord);
1452 //var
1453 //textures: TTexturesRec1Array;
1454 //textures: TDynField;
1455 //trec: TDynRecord;
1456 //mapHeader: TMapHeaderRec_1;
1457 //i: integer;
1458 //resFile: String = '';
1459 begin
1460 if gExternalResources = nil then
1461 gExternalResources := TStringList.Create;
1463 gExternalResources.Clear;
1465 (*
1467 textures := GetTextures(map);
1468 for i := 0 to High(textures) do
1469 begin
1470 addResToExternalResList(resFile);
1471 end;
1474 textures := map['texture'];
1475 if (textures <> nil) then
1476 begin
1477 for trec in textures do
1478 begin
1479 addResToExternalResList(resFile);
1480 end;
1481 end;
1483 textures := nil;
1484 *)
1486 //mapHeader := GetMapHeader(map);
1488 addResToExternalResList(map.MusicName);
1489 addResToExternalResList(map.SkyName);
1490 end;
1493 procedure mapCreateGrid ();
1494 var
1495 mapX0: Integer = $3fffffff;
1496 mapY0: Integer = $3fffffff;
1497 mapX1: Integer = -$3fffffff;
1498 mapY1: Integer = -$3fffffff;
1500 procedure calcBoundingBox (constref panels: TPanelArray);
1501 var
1502 idx: Integer;
1503 pan: TPanel;
1504 begin
1505 for idx := 0 to High(panels) do
1506 begin
1507 pan := panels[idx];
1508 if not pan.visvalid then continue;
1509 if (pan.Width < 1) or (pan.Height < 1) then continue;
1510 if (mapX0 > pan.x0) then mapX0 := pan.x0;
1511 if (mapY0 > pan.y0) then mapY0 := pan.y0;
1512 if (mapX1 < pan.x1) then mapX1 := pan.x1;
1513 if (mapY1 < pan.y1) then mapY1 := pan.y1;
1514 end;
1515 end;
1517 procedure addPanelsToGrid (constref panels: TPanelArray);
1518 var
1519 idx: Integer;
1520 pan: TPanel;
1521 newtag: Integer;
1522 begin
1523 //tag := panelTypeToTag(tag);
1524 for idx := 0 to High(panels) do
1525 begin
1526 pan := panels[idx];
1527 if not pan.visvalid then continue;
1528 if (pan.proxyId <> -1) then
1529 begin
1530 {$IF DEFINED(D2F_DEBUG)}
1531 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);
1532 {$ENDIF}
1533 continue;
1534 end;
1535 case pan.PanelType of
1536 PANEL_WALL: newtag := GridTagWall;
1537 PANEL_OPENDOOR, PANEL_CLOSEDOOR: newtag := GridTagDoor;
1538 PANEL_BACK: newtag := GridTagBack;
1539 PANEL_FORE: newtag := GridTagFore;
1540 PANEL_WATER: newtag := GridTagWater;
1541 PANEL_ACID1: newtag := GridTagAcid1;
1542 PANEL_ACID2: newtag := GridTagAcid2;
1543 PANEL_STEP: newtag := GridTagStep;
1544 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: newtag := GridTagLift;
1545 PANEL_BLOCKMON: newtag := GridTagBlockMon;
1546 else continue; // oops
1547 end;
1548 pan.tag := newtag;
1550 pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, newtag);
1551 // "enabled" flag has meaning only for doors and walls (engine assumes it); but meh...
1552 mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
1553 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
1555 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
1556 begin
1557 e_WriteLog(Format('INSERTED wall #%d(%d) enabled (%d)', [Integer(idx), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId])]), MSG_NOTIFY);
1558 end;
1560 {$ENDIF}
1561 end;
1562 end;
1564 begin
1565 mapGrid.Free();
1566 mapGrid := nil;
1568 calcBoundingBox(gWalls);
1569 calcBoundingBox(gRenderBackgrounds);
1570 calcBoundingBox(gRenderForegrounds);
1571 calcBoundingBox(gWater);
1572 calcBoundingBox(gAcid1);
1573 calcBoundingBox(gAcid2);
1574 calcBoundingBox(gSteps);
1575 calcBoundingBox(gLifts);
1576 calcBoundingBox(gBlockMon);
1578 e_LogWritefln('map dimensions: (%d,%d)-(%d,%d); editor size:(0,0)-(%d,%d)', [mapX0, mapY0, mapX1, mapY1, gMapInfo.Width, gMapInfo.Height]);
1580 if (mapX0 > 0) then mapX0 := 0;
1581 if (mapY0 > 0) then mapY0 := 0;
1583 if (mapX1 < gMapInfo.Width-1) then mapX1 := gMapInfo.Width-1;
1584 if (mapY1 < gMapInfo.Height-1) then mapY1 := gMapInfo.Height-1;
1586 mapGrid := TPanelGrid.Create(mapX0-128, mapY0-128, mapX1-mapX0+1+128*2, mapY1-mapY0+1+128*2);
1587 //mapGrid := TPanelGrid.Create(0, 0, gMapInfo.Width, gMapInfo.Height);
1589 addPanelsToGrid(gWalls);
1590 addPanelsToGrid(gRenderBackgrounds);
1591 addPanelsToGrid(gRenderForegrounds);
1592 addPanelsToGrid(gWater);
1593 addPanelsToGrid(gAcid1);
1594 addPanelsToGrid(gAcid2);
1595 addPanelsToGrid(gSteps);
1596 addPanelsToGrid(gLifts); // it doesn't matter which LIFT type is used here
1597 addPanelsToGrid(gBlockMon);
1599 mapGrid.dumpStats();
1601 g_Mons_InitTree(mapGrid.gridX0, mapGrid.gridY0, mapGrid.gridWidth, mapGrid.gridHeight);
1602 end;
1605 function g_Map_Load(Res: String): Boolean;
1606 const
1607 DefaultMusRes = 'Standart.wad:STDMUS\MUS1';
1608 DefaultSkyRes = 'Standart.wad:STDSKY\SKY0';
1609 type
1610 PTRec = ^TTRec;
1611 TTRec = record
1612 //TexturePanel: Integer;
1613 tnum: Integer;
1614 id: Integer;
1615 trigrec: TDynRecord;
1616 // texture pane;
1617 texPanelIdx: Integer;
1618 texPanel: TDynRecord;
1619 // "action" panel
1620 actPanelIdx: Integer;
1621 actPanel: TDynRecord;
1622 end;
1623 var
1624 WAD, TestWAD: TWADFile;
1625 //mapReader: TDynRecord = nil;
1626 mapTextureList: TDynField = nil; //TTexturesRec1Array; tagInt: texture index
1627 panels: TDynField = nil; //TPanelsRec1Array;
1628 items: TDynField = nil; //TItemsRec1Array;
1629 monsters: TDynField = nil; //TMonsterRec1Array;
1630 areas: TDynField = nil; //TAreasRec1Array;
1631 triggers: TDynField = nil; //TTriggersRec1Array;
1632 b, c, k: Integer;
1633 PanelID: DWORD;
1634 AddTextures: TAddTextureArray;
1635 TriggersTable: array of TTRec;
1636 FileName, mapResName, TexName, s: AnsiString;
1637 Data: Pointer;
1638 Len: Integer;
1639 ok, isAnim: Boolean;
1640 CurTex, ntn: Integer;
1641 rec, texrec: TDynRecord;
1642 pttit: PTRec;
1643 pannum, trignum, cnt, tgpid: Integer;
1644 stt: UInt64;
1645 moveSpeed{, moveStart, moveEnd}: TDFPoint;
1646 //moveActive: Boolean;
1647 pan: TPanel;
1648 mapOk: Boolean = false;
1649 usedTextures: THashStrInt = nil; // key: mapTextureList
1650 begin
1651 mapGrid.Free();
1652 mapGrid := nil;
1653 TestWAD := nil;
1654 Data := nil;
1656 //gCurrentMap.Free();
1657 //gCurrentMap := nil;
1659 panByGUID := nil;
1661 Result := False;
1662 gMapInfo.Map := Res;
1663 TriggersTable := nil;
1664 //mapReader := nil;
1666 sfsGCDisable(); // temporary disable removing of temporary volumes
1667 try
1668 // Çàãðóçêà WAD (åñëè ó íàñ íåò óæå çàãðóæåíîé êàðòû)
1669 if (gCurrentMap = nil) then
1670 begin
1671 FileName := g_ExtractWadName(Res);
1672 e_WriteLog('Loading map WAD: '+FileName, TMsgType.Notify);
1673 g_Game_SetLoadingText(_lc[I_LOAD_WAD_FILE], 0, False);
1675 WAD := TWADFile.Create();
1676 if not WAD.ReadFile(FileName) then
1677 begin
1678 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [FileName]));
1679 WAD.Free();
1680 Exit;
1681 end;
1683 if gTestMap <> '' then
1684 begin
1685 s := g_ExtractWadName(gTestMap);
1686 TestWAD := TWADFile.Create();
1687 if not TestWAD.ReadFile(s) then
1688 begin
1689 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_WAD], [s]));
1690 TestWAD.Free();
1691 TestWAD := nil;
1692 end;
1693 end;
1695 if TestWAD <> nil then
1696 begin
1697 mapResName := g_ExtractFileName(gTestMap);
1698 if not TestWAD.GetMapResource(mapResName, Data, Len) then
1699 begin
1700 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1701 Data := nil;
1702 end else
1703 e_WriteLog('Using test map: '+gTestMap, TMsgType.Notify);
1704 TestWAD.Free();
1705 TestWAD := nil;
1706 end;
1708 if Data = nil then
1709 begin
1710 //k8: why loader ignores path here?
1711 mapResName := g_ExtractFileName(Res);
1712 if not WAD.GetMapResource(mapResName, Data, Len) then
1713 begin
1714 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1715 WAD.Free();
1716 Exit;
1717 end;
1718 end;
1720 WAD.Free();
1722 if (Len < 4) then
1723 begin
1724 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1725 FreeMem(Data);
1726 exit;
1727 end;
1729 // Çàãðóçêà êàðòû:
1730 e_LogWritefln('Loading map: %s', [mapResName], TMsgType.Notify);
1731 g_Game_SetLoadingText(_lc[I_LOAD_MAP], 0, False);
1733 stt := getTimeMicro();
1735 try
1736 gCurrentMap := g_Map_ParseMap(Data, Len);
1737 except
1738 gCurrentMap.Free();
1739 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]));
1740 FreeMem(Data);
1741 gCurrentMapFileName := '';
1742 Exit;
1743 end;
1745 FreeMem(Data);
1747 if (gCurrentMap = nil) then
1748 begin
1749 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1750 gCurrentMapFileName := '';
1751 exit;
1752 end;
1753 end
1754 else
1755 begin
1756 stt := getTimeMicro();
1757 end;
1759 //gCurrentMap := mapReader;
1761 generateExternalResourcesList(gCurrentMap);
1762 mapTextureList := gCurrentMap['texture'];
1763 // get all other lists here too
1764 panels := gCurrentMap['panel'];
1765 triggers := gCurrentMap['trigger'];
1766 items := gCurrentMap['item'];
1767 areas := gCurrentMap['area'];
1768 monsters := gCurrentMap['monster'];
1770 // Çàãðóçêà îïèñàíèÿ êàðòû:
1771 e_WriteLog(' Reading map info...', TMsgType.Notify);
1772 g_Game_SetLoadingText(_lc[I_LOAD_MAP_HEADER], 0, False);
1774 with gMapInfo do
1775 begin
1776 Name := gCurrentMap.MapName;
1777 Description := gCurrentMap.MapDesc;
1778 Author := gCurrentMap.MapAuthor;
1779 MusicName := gCurrentMap.MusicName;
1780 SkyName := gCurrentMap.SkyName;
1781 Height := gCurrentMap.Height;
1782 Width := gCurrentMap.Width;
1783 end;
1785 // Çàãðóçêà òåêñòóð:
1786 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], 0, False);
1787 // Äîáàâëåíèå òåêñòóð â Textures[]:
1788 if (mapTextureList <> nil) and (mapTextureList.count > 0) then
1789 begin
1790 e_WriteLog(' Loading textures:', TMsgType.Notify);
1791 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], mapTextureList.count-1, False);
1793 // find used textures
1794 usedTextures := THashStrInt.Create();
1795 try
1796 if (panels <> nil) and (panels.count > 0) then
1797 begin
1798 for rec in panels do
1799 begin
1800 texrec := rec.TextureRec;
1801 if (texrec <> nil) then usedTextures.put(toLowerCase1251(texrec.Resource), 42);
1802 end;
1803 end;
1805 cnt := -1;
1806 for rec in mapTextureList do
1807 begin
1808 Inc(cnt);
1809 if not usedTextures.has(toLowerCase1251(rec.Resource)) then
1810 begin
1811 rec.tagInt := -1; // just in case
1812 e_LogWritefln(' Unused texture #%d: %s', [cnt, rec.Resource]);
1813 end
1814 else
1815 begin
1816 {$IF DEFINED(D2F_DEBUG_TXLOAD)}
1817 e_LogWritefln(' Loading texture #%d: %s', [cnt, rec.Resource]);
1818 {$ENDIF}
1819 //if g_Map_IsSpecialTexture(s) then e_WriteLog(' SPECIAL!', MSG_NOTIFY);
1820 if rec.Anim then
1821 begin
1822 // Àíèìèðîâàííàÿ òåêñòóðà
1823 ntn := CreateAnimTexture(rec.Resource, FileName, True);
1824 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_ANIM], [rec.Resource]));
1825 end
1826 else
1827 begin
1828 // Îáû÷íàÿ òåêñòóðà
1829 ntn := CreateTexture(rec.Resource, FileName, True);
1830 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_SIMPLE], [rec.Resource]));
1831 end;
1832 if (ntn < 0) then ntn := CreateNullTexture(rec.Resource);
1834 rec.tagInt := ntn; // remember texture number
1835 end;
1836 g_Game_StepLoading();
1837 end;
1838 finally
1839 usedTextures.Free();
1840 end;
1842 // set panel tagInt to texture index
1843 if (panels <> nil) then
1844 begin
1845 for rec in panels do
1846 begin
1847 texrec := rec.TextureRec;
1848 if (texrec = nil) then rec.tagInt := -1 else rec.tagInt := texrec.tagInt;
1849 end;
1850 end;
1851 end;
1854 // Çàãðóçêà òðèããåðîâ
1855 gTriggerClientID := 0;
1856 e_WriteLog(' Loading triggers...', TMsgType.Notify);
1857 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS], 0, False);
1859 // Çàãðóçêà ïàíåëåé
1860 e_WriteLog(' Loading panels...', TMsgType.Notify);
1861 g_Game_SetLoadingText(_lc[I_LOAD_PANELS], 0, False);
1863 // check texture numbers for panels
1864 if (panels <> nil) and (panels.count > 0) then
1865 begin
1866 for rec in panels do
1867 begin
1868 if (rec.tagInt < 0) then
1869 begin
1870 e_WriteLog('error loading map: invalid texture index for panel', TMsgType.Fatal);
1871 result := false;
1872 gCurrentMap.Free();
1873 gCurrentMap := nil;
1874 gCurrentMapFileName := '';
1875 exit;
1876 end;
1877 end;
1878 end;
1880 // Ñîçäàíèå òàáëèöû òðèããåðîâ (ñîîòâåòñòâèå ïàíåëåé òðèããåðàì)
1881 if (triggers <> nil) and (triggers.count > 0) then
1882 begin
1883 e_WriteLog(' Setting up trigger table...', TMsgType.Notify);
1884 //SetLength(TriggersTable, triggers.count);
1885 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS_TABLE], triggers.count-1, False);
1887 SetLength(TriggersTable, triggers.count);
1888 trignum := -1;
1889 for rec in triggers do
1890 begin
1891 Inc(trignum);
1892 pttit := @TriggersTable[trignum];
1893 pttit.trigrec := rec;
1894 // Ñìåíà òåêñòóðû (âîçìîæíî, êíîïêè)
1895 pttit.texPanelIdx := -1; // will be fixed later
1896 pttit.texPanel := rec.TexturePanelRec;
1897 // action panel
1898 pttit.actPanelIdx := -1;
1899 if (rec.trigRec <> nil) then pttit.actPanel := rec.trigRec.tgPanelRec else pttit.actPanel := nil;
1900 // set flag
1901 if (pttit.texPanel <> nil) then pttit.texPanel.userPanelTrigRef := true;
1902 if (pttit.actPanel <> nil) then pttit.actPanel.userPanelTrigRef := true;
1903 // update progress
1904 g_Game_StepLoading();
1905 end;
1906 end;
1908 // Ñîçäàåì ïàíåëè
1909 if (panels <> nil) and (panels.count > 0) then
1910 begin
1911 e_WriteLog(' Setting up trigger links...', TMsgType.Notify);
1912 g_Game_SetLoadingText(_lc[I_LOAD_LINK_TRIGGERS], panels.count-1, False);
1914 pannum := -1;
1915 for rec in panels do
1916 begin
1917 Inc(pannum);
1918 //e_LogWritefln('PANSTART: pannum=%s', [pannum]);
1919 texrec := nil;
1920 SetLength(AddTextures, 0);
1921 CurTex := -1;
1922 ok := false;
1924 if (mapTextureList <> nil) then
1925 begin
1926 texrec := rec.TextureRec;
1927 ok := (texrec <> nil);
1928 end;
1930 if ok then
1931 begin
1932 // Ñìîòðèì, ññûëàþòñÿ ëè íà ýòó ïàíåëü òðèããåðû.
1933 // Åñëè äà - òî íàäî ñîçäàòü åùå òåêñòóð
1934 ok := false;
1935 if (TriggersTable <> nil) and (mapTextureList <> nil) then
1936 begin
1937 if rec.userPanelTrigRef then
1938 begin
1939 // e_LogWritefln('trigref for panel %s', [pannum]);
1940 ok := True;
1941 end;
1942 end;
1943 end;
1945 if ok then
1946 begin
1947 // Åñòü ññûëêè òðèããåðîâ íà ýòó ïàíåëü
1948 s := texrec.Resource;
1950 // Ñïåö-òåêñòóðû çàïðåùåíû
1951 if g_Map_IsSpecialTexture(s) then
1952 begin
1953 ok := false
1954 end
1955 else
1956 begin
1957 // Îïðåäåëÿåì íàëè÷èå è ïîëîæåíèå öèôð â êîíöå ñòðîêè
1958 ok := g_Texture_NumNameFindStart(s);
1959 end;
1961 // Åñëè ok, çíà÷èò åñòü öèôðû â êîíöå.
1962 // Çàãðóæàåì òåêñòóðû ñ îñòàëüíûìè #
1963 if ok then
1964 begin
1965 k := NNF_NAME_BEFORE;
1966 // Öèêë ïî èçìåíåíèþ èìåíè òåêñòóðû
1967 while ok or (k = NNF_NAME_BEFORE) or (k = NNF_NAME_EQUALS) do
1968 begin
1969 k := g_Texture_NumNameFindNext(TexName);
1971 if (k = NNF_NAME_BEFORE) or (k = NNF_NAME_AFTER) then
1972 begin
1973 // Ïðîáóåì äîáàâèòü íîâóþ òåêñòóðó
1974 if texrec.Anim then
1975 begin
1976 // Íà÷àëüíàÿ - àíèìèðîâàííàÿ, èùåì àíèìèðîâàííóþ
1977 isAnim := True;
1978 //e_LogWritefln('000: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1979 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
1980 //e_LogWritefln('001: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1981 if not ok then
1982 begin
1983 // Íåò àíèìèðîâàííîé, èùåì îáû÷íóþ
1984 isAnim := False;
1985 //e_LogWritefln('002: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1986 ok := CreateTexture(TexName, FileName, False) >= 0;
1987 //e_LogWritefln('003: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1988 end;
1989 end
1990 else
1991 begin
1992 // Íà÷àëüíàÿ - îáû÷íàÿ, èùåì îáû÷íóþ
1993 isAnim := False;
1994 //e_LogWritefln('004: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1995 ok := CreateTexture(TexName, FileName, False) >= 0;
1996 //e_LogWritefln('005: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1997 if not ok then
1998 begin
1999 // Íåò îáû÷íîé, èùåì àíèìèðîâàííóþ
2000 isAnim := True;
2001 //e_LogWritefln('006: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2002 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2003 //e_LogWritefln('007: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2004 end;
2005 end;
2007 // Îíà ñóùåñòâóåò. Çàíîñèì åå ID â ñïèñîê ïàíåëè
2008 if ok then
2009 begin
2011 for c := 0 to High(Textures) do
2012 begin
2013 if (Textures[c].TextureName = TexName) then
2014 begin
2015 SetLength(AddTextures, Length(AddTextures)+1);
2016 AddTextures[High(AddTextures)].Texture := c;
2017 AddTextures[High(AddTextures)].Anim := isAnim;
2018 break;
2019 end;
2020 end;
2022 if (TextNameHash <> nil) and TextNameHash.get(toLowerCase1251(TexName), c) then
2023 begin
2024 SetLength(AddTextures, Length(AddTextures)+1);
2025 AddTextures[High(AddTextures)].Texture := c;
2026 AddTextures[High(AddTextures)].Anim := isAnim;
2027 end;
2028 end;
2029 end
2030 else
2031 begin
2032 if k = NNF_NAME_EQUALS then
2033 begin
2034 // Çàíîñèì òåêóùóþ òåêñòóðó íà ñâîå ìåñòî
2035 SetLength(AddTextures, Length(AddTextures)+1);
2036 AddTextures[High(AddTextures)].Texture := rec.tagInt; // internal texture number, not map index
2037 AddTextures[High(AddTextures)].Anim := texrec.Anim;
2038 CurTex := High(AddTextures);
2039 ok := true;
2040 end
2041 else // NNF_NO_NAME
2042 begin
2043 ok := false;
2044 end;
2045 end;
2046 end; // while ok...
2048 ok := true;
2049 end; // if ok - åñòü ñìåæíûå òåêñòóðû
2050 end; // if ok - ññûëàþòñÿ òðèããåðû
2052 if not ok then
2053 begin
2054 // Çàíîñèì òîëüêî òåêóùóþ òåêñòóðó
2055 SetLength(AddTextures, 1);
2056 AddTextures[0].Texture := rec.tagInt; // internal texture number, not map index
2057 AddTextures[0].Anim := false;
2058 if (texrec <> nil) then AddTextures[0].Anim := texrec.Anim;
2059 CurTex := 0;
2060 end;
2062 //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);
2064 //e_LogWritefln('PANADD: pannum=%s', [pannum]);
2066 // Ñîçäàåì ïàíåëü è çàïîìèíàåì åå GUID
2067 //e_LogWritefln('new panel; tcount=%s; curtex=%s', [Length(AddTextures), CurTex]);
2068 PanelID := CreatePanel(rec, AddTextures, CurTex);
2069 //e_LogWritefln('panel #%s of type %s got guid #%s', [pannum, rec.PanelType, PanelID]);
2070 rec.userPanelId := PanelID; // remember game panel id, we'll fix triggers later
2072 // setup lifts
2073 moveSpeed := rec.moveSpeed;
2074 //moveStart := rec.moveStart;
2075 //moveEnd := rec.moveEnd;
2076 //moveActive := rec['move_active'].value;
2077 if not moveSpeed.isZero then
2078 begin
2079 SetLength(gMovingWallIds, Length(gMovingWallIds)+1);
2080 gMovingWallIds[High(gMovingWallIds)] := PanelID;
2081 //e_LogWritefln('found moving panel ''%s'' (idx=%s; id=%s)', [rec.id, pannum, PanelID]);
2082 end;
2084 //e_LogWritefln('PANEND: pannum=%s', [pannum]);
2086 g_Game_StepLoading();
2087 end;
2088 end;
2090 // ×èíèì ID'û ïàíåëåé, êîòîðûå èñïîëüçóþòñÿ â òðèããåðàõ
2091 for b := 0 to High(TriggersTable) do
2092 begin
2093 if (TriggersTable[b].texPanel <> nil) then TriggersTable[b].texPanelIdx := TriggersTable[b].texPanel.userPanelId;
2094 if (TriggersTable[b].actPanel <> nil) then TriggersTable[b].actPanelIdx := TriggersTable[b].actPanel.userPanelId;
2095 end;
2097 // create map grid, init other grids (for monsters, for example)
2098 e_WriteLog('Creating map grid', TMsgType.Notify);
2099 mapCreateGrid();
2101 // Åñëè íå LoadState, òî ñîçäàåì òðèããåðû
2102 if (triggers <> nil) and (panels <> nil) and (not gLoadGameMode) then
2103 begin
2104 e_LogWritefln(' Creating triggers (%d)...', [triggers.count]);
2105 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_TRIGGERS], 0, False);
2106 // Óêàçûâàåì òèï ïàíåëè, åñëè åñòü
2107 trignum := -1;
2108 for rec in triggers do
2109 begin
2110 Inc(trignum);
2111 tgpid := TriggersTable[trignum].actPanelIdx;
2112 //e_LogWritefln('creating trigger #%s; texpantype=%s; shotpantype=%s (%d,%d)', [trignum, b, c, TriggersTable[trignum].texPanIdx, TriggersTable[trignum].ShotPanelIdx]);
2113 TriggersTable[trignum].tnum := trignum;
2114 TriggersTable[trignum].id := CreateTrigger(trignum, rec, TriggersTable[trignum].texPanelIdx, tgpid);
2115 end;
2116 end;
2118 //FIXME: use hashtable!
2119 for pan in panByGUID do
2120 begin
2121 if (pan.endPosTrigId >= 0) and (pan.endPosTrigId < Length(TriggersTable)) then
2122 begin
2123 pan.endPosTrigId := TriggersTable[pan.endPosTrigId].id;
2124 end;
2125 if (pan.endSizeTrigId >= 0) and (pan.endSizeTrigId < Length(TriggersTable)) then
2126 begin
2127 pan.endSizeTrigId := TriggersTable[pan.endSizeTrigId].id;
2128 end;
2129 end;
2131 // Çàãðóçêà ïðåäìåòîâ
2132 e_WriteLog(' Loading items...', TMsgType.Notify);
2133 g_Game_SetLoadingText(_lc[I_LOAD_ITEMS], 0, False);
2135 // Åñëè íå LoadState, òî ñîçäàåì ïðåäìåòû
2136 if (items <> nil) and not gLoadGameMode then
2137 begin
2138 e_WriteLog(' Spawning items...', TMsgType.Notify);
2139 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_ITEMS], 0, False);
2140 for rec in items do CreateItem(rec);
2141 end;
2143 // Çàãðóçêà îáëàñòåé
2144 e_WriteLog(' Loading areas...', TMsgType.Notify);
2145 g_Game_SetLoadingText(_lc[I_LOAD_AREAS], 0, False);
2147 // Åñëè íå LoadState, òî ñîçäàåì îáëàñòè
2148 if areas <> nil then
2149 begin
2150 e_WriteLog(' Creating areas...', TMsgType.Notify);
2151 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_AREAS], 0, False);
2152 for rec in areas do CreateArea(rec);
2153 end;
2155 // Çàãðóçêà ìîíñòðîâ
2156 e_WriteLog(' Loading monsters...', TMsgType.Notify);
2157 g_Game_SetLoadingText(_lc[I_LOAD_MONSTERS], 0, False);
2159 gTotalMonsters := 0;
2161 // Åñëè íå LoadState, òî ñîçäàåì ìîíñòðîâ
2162 if (monsters <> nil) and not gLoadGameMode then
2163 begin
2164 e_WriteLog(' Spawning monsters...', TMsgType.Notify);
2165 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_MONSTERS], 0, False);
2166 for rec in monsters do CreateMonster(rec);
2167 end;
2169 //gCurrentMap := mapReader; // this will be our current map now
2170 gCurrentMapFileName := Res;
2171 //mapReader := nil;
2173 // Çàãðóçêà íåáà
2174 if (gMapInfo.SkyName <> '') then
2175 begin
2176 e_WriteLog(' Loading sky: ' + gMapInfo.SkyName, TMsgType.Notify);
2177 g_Game_SetLoadingText(_lc[I_LOAD_SKY], 0, False);
2178 FileName := g_ExtractWadName(gMapInfo.SkyName);
2180 if (FileName <> '') then FileName := GameDir+'/wads/'+FileName else FileName := g_ExtractWadName(Res);
2182 if gTextureFilter then TEXTUREFILTER := GL_LINEAR else TEXTUREFILTER := GL_NEAREST;
2183 try
2184 s := FileName+':'+g_ExtractFilePathName(gMapInfo.SkyName);
2185 if g_Texture_CreateWAD(BackID, s) then
2186 begin
2187 g_Game_SetupScreenSize();
2188 end
2189 else
2190 begin
2191 g_FatalError(Format(_lc[I_GAME_ERROR_SKY], [s]));
2192 end;
2193 finally
2194 TEXTUREFILTER := GL_NEAREST;
2195 end;
2196 end;
2198 // Çàãðóçêà ìóçûêè
2199 ok := False;
2200 if gMapInfo.MusicName <> '' then
2201 begin
2202 e_WriteLog(' Loading music: ' + gMapInfo.MusicName, TMsgType.Notify);
2203 g_Game_SetLoadingText(_lc[I_LOAD_MUSIC], 0, False);
2204 FileName := g_ExtractWadName(gMapInfo.MusicName);
2206 if FileName <> '' then
2207 FileName := GameDir+'/wads/'+FileName
2208 else
2209 begin
2210 FileName := g_ExtractWadName(Res);
2211 end;
2213 s := FileName+':'+g_ExtractFilePathName(gMapInfo.MusicName);
2214 if g_Sound_CreateWADEx(gMapInfo.MusicName, s, True) then
2215 ok := True
2216 else
2217 g_FatalError(Format(_lc[I_GAME_ERROR_MUSIC], [s]));
2218 end;
2220 // Îñòàëüíûå óñòàíâêè
2221 CreateDoorMap();
2222 CreateLiftMap();
2224 g_Items_Init();
2225 g_Weapon_Init();
2226 g_Monsters_Init();
2228 // Åñëè íå LoadState, òî ñîçäàåì êàðòó ñòîëêíîâåíèé:
2229 if not gLoadGameMode then g_GFX_Init();
2231 // Ñáðîñ ëîêàëüíûõ ìàññèâîâ:
2232 mapTextureList := nil;
2233 panels := nil;
2234 items := nil;
2235 areas := nil;
2236 triggers := nil;
2237 TriggersTable := nil;
2238 AddTextures := nil;
2240 // Âêëþ÷àåì ìóçûêó, åñëè ýòî íå çàãðóçêà:
2241 if ok and (not gLoadGameMode) then
2242 begin
2243 gMusic.SetByName(gMapInfo.MusicName);
2244 gMusic.Play();
2245 end
2246 else
2247 begin
2248 gMusic.SetByName('');
2249 end;
2251 stt := getTimeMicro()-stt;
2252 e_LogWritefln('map loaded in %s.%s milliseconds', [Integer(stt div 1000), Integer(stt mod 1000)]);
2253 mapOk := true;
2254 finally
2255 sfsGCEnable(); // enable releasing unused volumes
2256 //mapReader.Free();
2257 e_ClearInputBuffer(); // why not?
2258 if not mapOk then
2259 begin
2260 gCurrentMap.Free();
2261 gCurrentMap := nil;
2262 gCurrentMapFileName := '';
2263 end;
2264 end;
2266 e_WriteLog('Done loading map.', TMsgType.Notify);
2267 Result := True;
2268 end;
2271 function g_Map_GetMapInfo(Res: String): TMapInfo;
2272 var
2273 WAD: TWADFile;
2274 mapReader: TDynRecord;
2275 //Header: TMapHeaderRec_1;
2276 FileName: String;
2277 Data: Pointer;
2278 Len: Integer;
2279 begin
2280 FillChar(Result, SizeOf(Result), 0);
2281 FileName := g_ExtractWadName(Res);
2283 WAD := TWADFile.Create();
2284 if not WAD.ReadFile(FileName) then
2285 begin
2286 WAD.Free();
2287 Exit;
2288 end;
2290 //k8: it ignores path again
2291 if not WAD.GetMapResource(g_ExtractFileName(Res), Data, Len) then
2292 begin
2293 WAD.Free();
2294 Exit;
2295 end;
2297 WAD.Free();
2299 try
2300 mapReader := g_Map_ParseMap(Data, Len);
2301 except
2302 mapReader := nil;
2303 FreeMem(Data);
2304 exit;
2305 end;
2307 FreeMem(Data);
2309 if (mapReader = nil) then exit;
2311 if (mapReader.Width > 0) and (mapReader.Height > 0) then
2312 begin
2313 Result.Name := mapReader.MapName;
2314 Result.Description := mapReader.MapDesc;
2315 Result.Map := Res;
2316 Result.Author := mapReader.MapAuthor;
2317 Result.Height := mapReader.Height;
2318 Result.Width := mapReader.Width;
2319 end
2320 else
2321 begin
2322 g_Console_Add(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]), True);
2323 //ZeroMemory(@Header, SizeOf(Header));
2324 Result.Name := _lc[I_GAME_ERROR_MAP_SELECT];
2325 Result.Description := _lc[I_GAME_ERROR_MAP_SELECT];
2326 Result.Map := Res;
2327 Result.Author := '';
2328 Result.Height := 0;
2329 Result.Width := 0;
2330 end;
2332 mapReader.Free();
2333 end;
2335 function g_Map_GetMapsList(WADName: string): SSArray;
2336 var
2337 WAD: TWADFile;
2338 a: Integer;
2339 ResList: SSArray;
2340 begin
2341 Result := nil;
2342 WAD := TWADFile.Create();
2343 if not WAD.ReadFile(WADName) then
2344 begin
2345 WAD.Free();
2346 Exit;
2347 end;
2348 ResList := WAD.GetMapResources();
2349 if ResList <> nil then
2350 begin
2351 for a := 0 to High(ResList) do
2352 begin
2353 SetLength(Result, Length(Result)+1);
2354 Result[High(Result)] := ResList[a];
2355 end;
2356 end;
2357 WAD.Free();
2358 end;
2360 function g_Map_Exist(Res: string): Boolean;
2361 var
2362 WAD: TWADFile;
2363 FileName, mnn: string;
2364 ResList: SSArray;
2365 a: Integer;
2366 begin
2367 Result := False;
2369 FileName := addWadExtension(g_ExtractWadName(Res));
2371 WAD := TWADFile.Create;
2372 if not WAD.ReadFile(FileName) then
2373 begin
2374 WAD.Free();
2375 Exit;
2376 end;
2378 ResList := WAD.GetMapResources();
2379 WAD.Free();
2381 mnn := g_ExtractFileName(Res);
2382 if ResList <> nil then
2383 for a := 0 to High(ResList) do if StrEquCI1251(ResList[a], mnn) then
2384 begin
2385 Result := True;
2386 Exit;
2387 end;
2388 end;
2390 procedure g_Map_Free(freeTextures: Boolean=true);
2391 var
2392 a: Integer;
2394 procedure FreePanelArray(var panels: TPanelArray);
2395 var
2396 i: Integer;
2398 begin
2399 if panels <> nil then
2400 begin
2401 for i := 0 to High(panels) do
2402 panels[i].Free();
2403 panels := nil;
2404 end;
2405 end;
2407 begin
2408 g_GFX_Free();
2409 g_Weapon_Free();
2410 g_Items_Free();
2411 g_Triggers_Free();
2412 g_Monsters_Free();
2414 RespawnPoints := nil;
2415 if FlagPoints[FLAG_RED] <> nil then
2416 begin
2417 Dispose(FlagPoints[FLAG_RED]);
2418 FlagPoints[FLAG_RED] := nil;
2419 end;
2420 if FlagPoints[FLAG_BLUE] <> nil then
2421 begin
2422 Dispose(FlagPoints[FLAG_BLUE]);
2423 FlagPoints[FLAG_BLUE] := nil;
2424 end;
2425 //DOMFlagPoints := nil;
2427 //gDOMFlags := nil;
2429 if (Length(gCurrentMapFileName) <> 0) then
2430 begin
2431 e_LogWritefln('g_Map_Free: previous map was ''%s''...', [gCurrentMapFileName]);
2432 end
2433 else
2434 begin
2435 e_LogWritefln('g_Map_Free: no previous map.', []);
2436 end;
2438 if freeTextures then
2439 begin
2440 e_LogWritefln('g_Map_Free: clearing textures...', []);
2441 if (Textures <> nil) then
2442 begin
2443 for a := 0 to High(Textures) do
2444 begin
2445 if not g_Map_IsSpecialTexture(Textures[a].TextureName) then
2446 begin
2447 if Textures[a].Anim then
2448 begin
2449 g_Frames_DeleteByID(Textures[a].FramesID)
2450 end
2451 else
2452 begin
2453 if (Textures[a].TextureID <> LongWord(TEXTURE_NONE)) then
2454 begin
2455 e_DeleteTexture(Textures[a].TextureID);
2456 end;
2457 end;
2458 end;
2459 end;
2460 Textures := nil;
2461 end;
2462 TextNameHash.Free();
2463 TextNameHash := nil;
2464 BadTextNameHash.Free();
2465 BadTextNameHash := nil;
2466 gCurrentMapFileName := '';
2467 gCurrentMap.Free();
2468 gCurrentMap := nil;
2469 end;
2471 panByGUID := nil;
2473 FreePanelArray(gWalls);
2474 FreePanelArray(gRenderBackgrounds);
2475 FreePanelArray(gRenderForegrounds);
2476 FreePanelArray(gWater);
2477 FreePanelArray(gAcid1);
2478 FreePanelArray(gAcid2);
2479 FreePanelArray(gSteps);
2480 FreePanelArray(gLifts);
2481 FreePanelArray(gBlockMon);
2482 gMovingWallIds := nil;
2484 if BackID <> DWORD(-1) then
2485 begin
2486 gBackSize.X := 0;
2487 gBackSize.Y := 0;
2488 e_DeleteTexture(BackID);
2489 BackID := DWORD(-1);
2490 end;
2492 g_Game_StopAllSounds(False);
2493 gMusic.FreeSound();
2494 g_Sound_Delete(gMapInfo.MusicName);
2496 gMapInfo.Name := '';
2497 gMapInfo.Description := '';
2498 gMapInfo.MusicName := '';
2499 gMapInfo.Height := 0;
2500 gMapInfo.Width := 0;
2502 gDoorMap := nil;
2503 gLiftMap := nil;
2504 end;
2506 procedure g_Map_Update();
2507 var
2508 a, d, j: Integer;
2509 m: Word;
2510 s: String;
2512 procedure UpdatePanelArray(var panels: TPanelArray);
2513 var
2514 i: Integer;
2516 begin
2517 for i := 0 to High(panels) do panels[i].Update();
2518 end;
2520 begin
2521 if g_dbgpan_mplat_step then g_dbgpan_mplat_active := true;
2523 UpdatePanelArray(gWalls);
2524 UpdatePanelArray(gRenderBackgrounds);
2525 UpdatePanelArray(gRenderForegrounds);
2526 UpdatePanelArray(gWater);
2527 UpdatePanelArray(gAcid1);
2528 UpdatePanelArray(gAcid2);
2529 UpdatePanelArray(gSteps);
2531 if g_dbgpan_mplat_step then begin g_dbgpan_mplat_step := false; g_dbgpan_mplat_active := false; end;
2533 if gGameSettings.GameMode = GM_CTF then
2534 begin
2535 for a := FLAG_RED to FLAG_BLUE do
2536 begin
2537 if not (gFlags[a].State in [FLAG_STATE_NONE, FLAG_STATE_CAPTURED]) then
2538 begin
2539 with gFlags[a] do
2540 begin
2541 if gFlags[a].Animation <> nil then gFlags[a].Animation.Update();
2543 m := g_Obj_Move(@Obj, True, True);
2545 if gTime mod (GAME_TICK*2) <> 0 then Continue;
2547 // Ñîïðîòèâëåíèå âîçäóõà
2548 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
2550 // Òàéìàóò ïîòåðÿííîãî ôëàãà, ëèáî îí âûïàë çà êàðòó
2551 if ((Count = 0) or ByteBool(m and MOVE_FALLOUT)) and g_Game_IsServer then
2552 begin
2553 g_Map_ResetFlag(a);
2554 gFlags[a].CaptureTime := 0;
2555 if a = FLAG_RED then
2556 s := _lc[I_PLAYER_FLAG_RED]
2557 else
2558 s := _lc[I_PLAYER_FLAG_BLUE];
2559 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
2561 if g_Game_IsNet then
2562 MH_SEND_FlagEvent(FLAG_STATE_RETURNED, a, 0);
2563 Continue;
2564 end;
2566 if Count > 0 then Count -= 1;
2568 // Èãðîê áåðåò ôëàã
2569 if gPlayers <> nil then
2570 begin
2571 j := Random(Length(gPlayers)) - 1;
2572 for d := 0 to High(gPlayers) do
2573 begin
2574 Inc(j);
2575 if j > High(gPlayers) then j := 0;
2576 if gPlayers[j] <> nil then
2577 begin
2578 if gPlayers[j].alive and g_Obj_Collide(@Obj, @gPlayers[j].Obj) then
2579 begin
2580 if gPlayers[j].GetFlag(a) then Break;
2581 end;
2582 end;
2583 end;
2584 end;
2585 end;
2586 end;
2587 end;
2588 end;
2589 end;
2592 // old algo
2593 procedure g_Map_DrawPanels (PanelType: Word; hasAmbient: Boolean; constref ambColor: TDFColor);
2595 procedure DrawPanels (constref panels: TPanelArray; drawDoors: Boolean=False);
2596 var
2597 idx: Integer;
2598 begin
2599 if (panels <> nil) then
2600 begin
2601 // alas, no visible set
2602 for idx := 0 to High(panels) do
2603 begin
2604 if not (drawDoors xor panels[idx].Door) then panels[idx].Draw(hasAmbient, ambColor);
2605 end;
2606 end;
2607 end;
2609 begin
2610 case PanelType of
2611 PANEL_WALL: DrawPanels(gWalls);
2612 PANEL_CLOSEDOOR: DrawPanels(gWalls, True);
2613 PANEL_BACK: DrawPanels(gRenderBackgrounds);
2614 PANEL_FORE: DrawPanels(gRenderForegrounds);
2615 PANEL_WATER: DrawPanels(gWater);
2616 PANEL_ACID1: DrawPanels(gAcid1);
2617 PANEL_ACID2: DrawPanels(gAcid2);
2618 PANEL_STEP: DrawPanels(gSteps);
2619 end;
2620 end;
2623 // new algo
2624 procedure g_Map_CollectDrawPanels (x0, y0, wdt, hgt: Integer);
2625 var
2626 mwit: PPanel;
2627 it: TPanelGrid.Iter;
2628 begin
2629 dplClear();
2630 it := mapGrid.forEachInAABB(x0, y0, wdt, hgt, GridDrawableMask);
2631 for mwit in it do if (((mwit^.tag and GridTagDoor) <> 0) = mwit^.Door) then gDrawPanelList.insert(mwit^);
2632 it.release();
2633 // list will be rendered in `g_game.DrawPlayer()`
2634 end;
2637 procedure g_Map_DrawPanelShadowVolumes (lightX: Integer; lightY: Integer; radius: Integer);
2638 var
2639 mwit: PPanel;
2640 it: TPanelGrid.Iter;
2641 begin
2642 it := mapGrid.forEachInAABB(lightX-radius, lightY-radius, radius*2, radius*2, (GridTagWall or GridTagDoor));
2643 for mwit in it do mwit^.DrawShadowVolume(lightX, lightY, radius);
2644 it.release();
2645 end;
2648 procedure g_Map_DrawBack(dx, dy: Integer);
2649 begin
2650 if gDrawBackGround and (BackID <> DWORD(-1)) then
2651 e_DrawSize(BackID, dx, dy, 0, False, False, gBackSize.X, gBackSize.Y)
2652 else
2653 e_Clear(GL_COLOR_BUFFER_BIT, 0, 0, 0);
2654 end;
2656 function g_Map_CollidePanelOld(X, Y: Integer; Width, Height: Word;
2657 PanelType: Word; b1x3: Boolean=false): Boolean;
2658 var
2659 a, h: Integer;
2660 begin
2661 Result := False;
2663 if WordBool(PanelType and PANEL_WALL) then
2664 if gWalls <> nil then
2665 begin
2666 h := High(gWalls);
2668 for a := 0 to h do
2669 if gWalls[a].Enabled and
2670 g_Collide(X, Y, Width, Height,
2671 gWalls[a].X, gWalls[a].Y,
2672 gWalls[a].Width, gWalls[a].Height) then
2673 begin
2674 Result := True;
2675 Exit;
2676 end;
2677 end;
2679 if WordBool(PanelType and PANEL_WATER) then
2680 if gWater <> nil then
2681 begin
2682 h := High(gWater);
2684 for a := 0 to h do
2685 if g_Collide(X, Y, Width, Height,
2686 gWater[a].X, gWater[a].Y,
2687 gWater[a].Width, gWater[a].Height) then
2688 begin
2689 Result := True;
2690 Exit;
2691 end;
2692 end;
2694 if WordBool(PanelType and PANEL_ACID1) then
2695 if gAcid1 <> nil then
2696 begin
2697 h := High(gAcid1);
2699 for a := 0 to h do
2700 if g_Collide(X, Y, Width, Height,
2701 gAcid1[a].X, gAcid1[a].Y,
2702 gAcid1[a].Width, gAcid1[a].Height) then
2703 begin
2704 Result := True;
2705 Exit;
2706 end;
2707 end;
2709 if WordBool(PanelType and PANEL_ACID2) then
2710 if gAcid2 <> nil then
2711 begin
2712 h := High(gAcid2);
2714 for a := 0 to h do
2715 if g_Collide(X, Y, Width, Height,
2716 gAcid2[a].X, gAcid2[a].Y,
2717 gAcid2[a].Width, gAcid2[a].Height) then
2718 begin
2719 Result := True;
2720 Exit;
2721 end;
2722 end;
2724 if WordBool(PanelType and PANEL_STEP) then
2725 if gSteps <> nil then
2726 begin
2727 h := High(gSteps);
2729 for a := 0 to h do
2730 if g_Collide(X, Y, Width, Height,
2731 gSteps[a].X, gSteps[a].Y,
2732 gSteps[a].Width, gSteps[a].Height) then
2733 begin
2734 Result := True;
2735 Exit;
2736 end;
2737 end;
2739 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then
2740 if gLifts <> nil then
2741 begin
2742 h := High(gLifts);
2744 for a := 0 to h do
2745 if ((WordBool(PanelType and (PANEL_LIFTUP)) and (gLifts[a].LiftType = 0)) or
2746 (WordBool(PanelType and (PANEL_LIFTDOWN)) and (gLifts[a].LiftType = 1)) or
2747 (WordBool(PanelType and (PANEL_LIFTLEFT)) and (gLifts[a].LiftType = 2)) or
2748 (WordBool(PanelType and (PANEL_LIFTRIGHT)) and (gLifts[a].LiftType = 3))) and
2749 g_Collide(X, Y, Width, Height,
2750 gLifts[a].X, gLifts[a].Y,
2751 gLifts[a].Width, gLifts[a].Height) then
2752 begin
2753 Result := True;
2754 Exit;
2755 end;
2756 end;
2758 if WordBool(PanelType and PANEL_BLOCKMON) then
2759 if gBlockMon <> nil then
2760 begin
2761 h := High(gBlockMon);
2763 for a := 0 to h do
2764 if ( (not b1x3) or
2765 ((gBlockMon[a].Width + gBlockMon[a].Height) >= 64) ) and
2766 g_Collide(X, Y, Width, Height,
2767 gBlockMon[a].X, gBlockMon[a].Y,
2768 gBlockMon[a].Width, gBlockMon[a].Height) then
2769 begin
2770 Result := True;
2771 Exit;
2772 end;
2773 end;
2774 end;
2776 function g_Map_CollideLiquid_TextureOld(X, Y: Integer; Width, Height: Word): DWORD;
2777 var
2778 texid: DWORD;
2780 function checkPanels (constref panels: TPanelArray): Boolean;
2781 var
2782 a: Integer;
2783 begin
2784 result := false;
2785 if panels = nil then exit;
2786 for a := 0 to High(panels) do
2787 begin
2788 if g_Collide(X, Y, Width, Height, panels[a].X, panels[a].Y, panels[a].Width, panels[a].Height) then
2789 begin
2790 result := true;
2791 texid := panels[a].GetTextureID();
2792 exit;
2793 end;
2794 end;
2795 end;
2797 begin
2798 texid := LongWord(TEXTURE_NONE);
2799 result := texid;
2800 if not checkPanels(gWater) then
2801 if not checkPanels(gAcid1) then
2802 if not checkPanels(gAcid2) then exit;
2803 result := texid;
2804 end;
2807 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word; PanelType: Word; b1x3: Boolean): Boolean;
2808 const
2809 SlowMask = GridTagLift or GridTagBlockMon;
2811 function checker (pan: TPanel; tag: Integer): Boolean;
2812 begin
2814 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
2815 begin
2816 result := pan.Enabled;
2817 exit;
2818 end;
2821 if ((tag and GridTagLift) <> 0) then
2822 begin
2823 result :=
2824 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = 0)) or
2825 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = 1)) or
2826 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = 2)) or
2827 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = 3))) {and
2828 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2829 exit;
2830 end;
2832 if ((tag and GridTagBlockMon) <> 0) then
2833 begin
2834 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2835 exit;
2836 end;
2838 // other shit
2839 //result := g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2840 result := true; // i found her!
2841 end;
2843 var
2844 tagmask: Integer = 0;
2845 mwit: PPanel;
2846 it: TPanelGrid.Iter;
2847 pan: TPanel;
2848 begin
2849 result := false;
2850 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
2851 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
2852 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
2853 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
2854 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
2855 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
2856 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
2858 if (tagmask = 0) then exit; // just in case
2860 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('*solids');
2861 if gdbg_map_use_accel_coldet then
2862 begin
2863 if ((tagmask and SlowMask) <> 0) then
2864 begin
2865 // slow
2866 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask);
2867 for mwit in it do
2868 begin
2869 pan := mwit^;
2870 if ((pan.tag and GridTagLift) <> 0) then
2871 begin
2872 result :=
2873 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = 0)) or
2874 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = 1)) or
2875 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = 2)) or
2876 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = 3))) {and
2877 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2878 end
2879 else if ((pan.tag and GridTagBlockMon) <> 0) then
2880 begin
2881 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2882 end
2883 else
2884 begin
2885 // other shit
2886 result := true; // i found her!
2887 end;
2888 if (result) then break;
2889 end;
2890 end
2891 else
2892 begin
2893 // fast
2894 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask, false, true); // return first hit
2895 result := (it.length > 0);
2896 end;
2897 it.release();
2898 end
2899 else
2900 begin
2901 result := g_Map_CollidePanelOld(X, Y, Width, Height, PanelType, b1x3);
2902 end;
2903 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2904 end;
2907 // returns `true` if we need to stop
2908 function liquidChecker (pan: TPanel; var texid: DWORD; var cctype: Integer): Boolean; inline;
2909 begin
2910 result := false;
2911 //if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2)) = 0) then exit;
2912 // check priorities
2913 case cctype of
2914 0: if ((pan.tag and GridTagWater) = 0) then exit; // allowed: water
2915 1: if ((pan.tag and (GridTagWater or GridTagAcid1)) = 0) then exit; // allowed: water, acid1
2916 //2: if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2) = 0) then exit; // allowed: water, acid1, acid2
2917 end;
2918 // collision?
2919 //if not g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height) then exit;
2920 // yeah
2921 texid := pan.GetTextureID();
2922 // water? water has the highest priority, so stop right here
2923 if ((pan.tag and GridTagWater) <> 0) then begin cctype := 0; result := true; exit; end;
2924 // acid2?
2925 if ((pan.tag and GridTagAcid2) <> 0) then cctype := 2;
2926 // acid1?
2927 if ((pan.tag and GridTagAcid1) <> 0) then cctype := 1;
2928 end;
2930 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
2931 var
2932 cctype: Integer = 3; // priority: 0: water was hit, 1: acid1 was hit, 2: acid2 was hit; 3: nothing was hit
2933 mwit: PPanel;
2934 it: TPanelGrid.Iter;
2935 begin
2936 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('liquids');
2937 if gdbg_map_use_accel_coldet then
2938 begin
2939 result := LongWord(TEXTURE_NONE);
2940 it := mapGrid.forEachInAABB(X, Y, Width, Height, (GridTagWater or GridTagAcid1 or GridTagAcid2));
2941 for mwit in it do if (liquidChecker(mwit^, result, cctype)) then break;
2942 it.release();
2943 end
2944 else
2945 begin
2946 result := g_Map_CollideLiquid_TextureOld(X, Y, Width, Height);
2947 end;
2948 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2949 end;
2952 procedure g_Map_EnableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_EnableWallGUID(gWalls[ID].guid); end;
2953 procedure g_Map_DisableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_DisableWallGUID(gWalls[ID].guid); end;
2954 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer); begin if (ID < Length(gLifts)) then g_Map_SetLiftGUID(gLifts[ID].guid, t); end;
2957 procedure g_Map_EnableWallGUID (pguid: Integer);
2958 var
2959 pan: TPanel;
2960 begin
2961 //pan := gWalls[ID];
2962 pan := g_Map_PanelByGUID(pguid);
2963 if (pan = nil) then exit;
2964 if pan.Enabled and mapGrid.proxyEnabled[pan.proxyId] then exit;
2966 pan.Enabled := True;
2967 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, true);
2969 mapGrid.proxyEnabled[pan.proxyId] := true;
2970 //if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := true
2971 //else pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, GridTagDoor);
2973 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
2974 // mark platform as interesting
2975 pan.setDirty();
2977 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
2978 //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);
2979 {$ENDIF}
2980 end;
2983 procedure g_Map_DisableWallGUID (pguid: Integer);
2984 var
2985 pan: TPanel;
2986 begin
2987 //pan := gWalls[ID];
2988 pan := g_Map_PanelByGUID(pguid);
2989 if (pan = nil) then exit;
2990 if (not pan.Enabled) and (not mapGrid.proxyEnabled[pan.proxyId]) then exit;
2992 pan.Enabled := False;
2993 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, false);
2995 mapGrid.proxyEnabled[pan.proxyId] := false;
2996 //if (pan.proxyId >= 0) then begin mapGrid.removeBody(pan.proxyId); pan.proxyId := -1; end;
2998 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
2999 // mark platform as interesting
3000 pan.setDirty();
3002 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
3003 //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);
3004 {$ENDIF}
3005 end;
3008 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
3009 var
3010 tp: TPanel;
3011 begin
3012 tp := g_Map_PanelByGUID(pguid);
3013 if (tp = nil) then exit;
3014 tp.NextTexture(AnimLoop);
3015 if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelTexture(pguid, AnimLoop);
3016 end;
3019 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
3020 var
3021 pan: TPanel;
3022 begin
3023 //pan := gLifts[ID];
3024 pan := g_Map_PanelByGUID(pguid);
3025 if (pan = nil) then exit;
3026 if not pan.isGLift then exit;
3028 if ({gLifts[ID]}pan.LiftType = t) then exit; //!FIXME!TRIGANY!
3030 with {gLifts[ID]} pan do
3031 begin
3032 LiftType := t;
3034 g_Mark(X, Y, Width, Height, MARK_LIFT, false);
3035 //TODO: make separate lift tags, and change tag here
3037 case LiftType of
3038 0: g_Mark(X, Y, Width, Height, MARK_LIFTUP);
3039 1: g_Mark(X, Y, Width, Height, MARK_LIFTDOWN);
3040 2: g_Mark(X, Y, Width, Height, MARK_LIFTLEFT);
3041 3: g_Mark(X, Y, Width, Height, MARK_LIFTRIGHT);
3042 end;
3044 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3045 // mark platform as interesting
3046 pan.setDirty();
3047 end;
3048 end;
3051 function g_Map_GetPoint (PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
3052 var
3053 a: Integer;
3054 PointsArray: Array of TRespawnPoint;
3055 begin
3056 Result := False;
3057 SetLength(PointsArray, 0);
3059 if RespawnPoints = nil then
3060 Exit;
3062 for a := 0 to High(RespawnPoints) do
3063 if RespawnPoints[a].PointType = PointType then
3064 begin
3065 SetLength(PointsArray, Length(PointsArray)+1);
3066 PointsArray[High(PointsArray)] := RespawnPoints[a];
3067 end;
3069 if PointsArray = nil then
3070 Exit;
3072 RespawnPoint := PointsArray[Random(Length(PointsArray))];
3073 Result := True;
3074 end;
3076 function g_Map_GetPointCount(PointType: Byte): Word;
3077 var
3078 a: Integer;
3079 begin
3080 Result := 0;
3082 if RespawnPoints = nil then
3083 Exit;
3085 for a := 0 to High(RespawnPoints) do
3086 if RespawnPoints[a].PointType = PointType then
3087 Result := Result + 1;
3088 end;
3090 function g_Map_HaveFlagPoints(): Boolean;
3091 begin
3092 Result := (FlagPoints[FLAG_RED] <> nil) and (FlagPoints[FLAG_BLUE] <> nil);
3093 end;
3095 procedure g_Map_ResetFlag(Flag: Byte);
3096 begin
3097 with gFlags[Flag] do
3098 begin
3099 Obj.X := -1000;
3100 Obj.Y := -1000;
3101 Obj.Vel.X := 0;
3102 Obj.Vel.Y := 0;
3103 Direction := TDirection.D_LEFT;
3104 State := FLAG_STATE_NONE;
3105 if FlagPoints[Flag] <> nil then
3106 begin
3107 Obj.X := FlagPoints[Flag]^.X;
3108 Obj.Y := FlagPoints[Flag]^.Y;
3109 Direction := FlagPoints[Flag]^.Direction;
3110 State := FLAG_STATE_NORMAL;
3111 end;
3112 Count := -1;
3113 end;
3114 end;
3116 procedure g_Map_DrawFlags();
3117 var
3118 i, dx: Integer;
3119 Mirror: TMirrorType;
3120 begin
3121 if gGameSettings.GameMode <> GM_CTF then
3122 Exit;
3124 for i := FLAG_RED to FLAG_BLUE do
3125 with gFlags[i] do
3126 if State <> FLAG_STATE_CAPTURED then
3127 begin
3128 if State = FLAG_STATE_NONE then
3129 continue;
3131 if Direction = TDirection.D_LEFT then
3132 begin
3133 Mirror := TMirrorType.Horizontal;
3134 dx := -1;
3135 end
3136 else
3137 begin
3138 Mirror := TMirrorType.None;
3139 dx := 1;
3140 end;
3142 Animation.Draw(Obj.X+dx, Obj.Y+1, Mirror);
3144 if g_debug_Frames then
3145 begin
3146 e_DrawQuad(Obj.X+Obj.Rect.X,
3147 Obj.Y+Obj.Rect.Y,
3148 Obj.X+Obj.Rect.X+Obj.Rect.Width-1,
3149 Obj.Y+Obj.Rect.Y+Obj.Rect.Height-1,
3150 0, 255, 0);
3151 end;
3152 end;
3153 end;
3156 procedure g_Map_SaveState (st: TStream);
3157 var
3158 str: String;
3160 procedure savePanels ();
3161 var
3162 pan: TPanel;
3163 begin
3164 // Ñîõðàíÿåì ïàíåëè
3165 utils.writeInt(st, LongInt(Length(panByGUID)));
3166 for pan in panByGUID do pan.SaveState(st);
3167 end;
3169 procedure saveFlag (flag: PFlag);
3170 var
3171 b: Byte;
3172 begin
3173 utils.writeSign(st, 'FLAG');
3174 utils.writeInt(st, Byte(0)); // version
3175 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3176 utils.writeInt(st, Byte(flag^.RespawnType));
3177 // Ñîñòîÿíèå ôëàãà
3178 utils.writeInt(st, Byte(flag^.State));
3179 // Íàïðàâëåíèå ôëàãà
3180 if flag^.Direction = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
3181 utils.writeInt(st, Byte(b));
3182 // Îáúåêò ôëàãà
3183 Obj_SaveState(st, @flag^.Obj);
3184 end;
3186 begin
3187 savePanels();
3189 // Ñîõðàíÿåì ìóçûêó
3190 utils.writeSign(st, 'MUSI');
3191 utils.writeInt(st, Byte(0));
3192 // Íàçâàíèå ìóçûêè
3193 assert(gMusic <> nil, 'g_Map_SaveState: gMusic = nil');
3194 if gMusic.NoMusic then str := '' else str := gMusic.Name;
3195 utils.writeStr(st, str);
3196 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3197 utils.writeInt(st, LongWord(gMusic.GetPosition()));
3198 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3199 utils.writeBool(st, gMusic.SpecPause);
3201 ///// Ñîõðàíÿåì êîëè÷åñòâî ìîíñòðîâ: /////
3202 utils.writeInt(st, LongInt(gTotalMonsters));
3203 ///// /////
3205 //// Ñîõðàíÿåì ôëàãè, åñëè ýòî CTF: /////
3206 if (gGameSettings.GameMode = GM_CTF) then
3207 begin
3208 // Ôëàã Êðàñíîé êîìàíäû
3209 saveFlag(@gFlags[FLAG_RED]);
3210 // Ôëàã Ñèíåé êîìàíäû
3211 saveFlag(@gFlags[FLAG_BLUE]);
3212 end;
3213 ///// /////
3215 ///// Ñîõðàíÿåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3216 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3217 begin
3218 // Î÷êè Êðàñíîé êîìàíäû
3219 utils.writeInt(st, SmallInt(gTeamStat[TEAM_RED].Goals));
3220 // Î÷êè Ñèíåé êîìàíäû
3221 utils.writeInt(st, SmallInt(gTeamStat[TEAM_BLUE].Goals));
3222 end;
3223 ///// /////
3224 end;
3227 procedure g_Map_LoadState (st: TStream);
3228 var
3229 dw: DWORD;
3230 str: String;
3231 boo: Boolean;
3233 procedure loadPanels ();
3234 var
3235 pan: TPanel;
3236 begin
3237 // Çàãðóæàåì ïàíåëè
3238 if (Length(panByGUID) <> utils.readLongInt(st)) then raise XStreamError.Create('invalid number of saved panels');
3239 for pan in panByGUID do
3240 begin
3241 pan.LoadState(st);
3242 if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
3243 end;
3244 end;
3246 procedure loadFlag (flag: PFlag);
3247 var
3248 b: Byte;
3249 begin
3250 // Ñèãíàòóðà ôëàãà
3251 if not utils.checkSign(st, 'FLAG') then raise XStreamError.Create('invalid flag signature');
3252 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid flag version');
3253 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3254 flag^.RespawnType := utils.readByte(st);
3255 // Ñîñòîÿíèå ôëàãà
3256 flag^.State := utils.readByte(st);
3257 // Íàïðàâëåíèå ôëàãà
3258 b := utils.readByte(st);
3259 if (b = 1) then flag^.Direction := TDirection.D_LEFT else flag^.Direction := TDirection.D_RIGHT; // b = 2
3260 // Îáúåêò ôëàãà
3261 Obj_LoadState(@flag^.Obj, st);
3262 end;
3264 begin
3265 if (st = nil) then exit;
3267 ///// Çàãðóæàåì ñïèñêè ïàíåëåé: /////
3268 loadPanels();
3269 ///// /////
3271 // Îáíîâëÿåì êàðòó ñòîëêíîâåíèé è ñåòêó
3272 g_GFX_Init();
3273 //mapCreateGrid();
3275 ///// Çàãðóæàåì ìóçûêó: /////
3276 if not utils.checkSign(st, 'MUSI') then raise XStreamError.Create('invalid music signature');
3277 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid music version');
3278 // Íàçâàíèå ìóçûêè
3279 assert(gMusic <> nil, 'g_Map_LoadState: gMusic = nil');
3280 str := utils.readStr(st);
3281 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3282 dw := utils.readLongWord(st);
3283 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3284 boo := utils.readBool(st);
3285 // Çàïóñêàåì ýòó ìóçûêó
3286 gMusic.SetByName(str);
3287 gMusic.SpecPause := boo;
3288 gMusic.Play();
3289 gMusic.Pause(true);
3290 gMusic.SetPosition(dw);
3291 ///// /////
3293 ///// Çàãðóæàåì êîëè÷åñòâî ìîíñòðîâ: /////
3294 gTotalMonsters := utils.readLongInt(st);
3295 ///// /////
3297 //// Çàãðóæàåì ôëàãè, åñëè ýòî CTF: /////
3298 if (gGameSettings.GameMode = GM_CTF) then
3299 begin
3300 // Ôëàã Êðàñíîé êîìàíäû
3301 loadFlag(@gFlags[FLAG_RED]);
3302 // Ôëàã Ñèíåé êîìàíäû
3303 loadFlag(@gFlags[FLAG_BLUE]);
3304 end;
3305 ///// /////
3307 ///// Çàãðóæàåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3308 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3309 begin
3310 // Î÷êè Êðàñíîé êîìàíäû
3311 gTeamStat[TEAM_RED].Goals := utils.readSmallInt(st);
3312 // Î÷êè Ñèíåé êîìàíäû
3313 gTeamStat[TEAM_BLUE].Goals := utils.readSmallInt(st);
3314 end;
3315 ///// /////
3316 end;
3319 // trace liquid, stepping by `dx` and `dy`
3320 // return last seen liquid coords, and `false` if we're started outside of the liquid
3321 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
3322 const
3323 MaskLiquid = GridTagWater or GridTagAcid1 or GridTagAcid2;
3324 begin
3325 topx := x;
3326 topy := y;
3327 // started outside of the liquid?
3328 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then begin result := false; exit; end;
3329 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then begin result := false; exit; end;
3330 if (dx = 0) and (dy = 0) then begin result := false; exit; end; // sanity check
3331 result := true;
3332 while true do
3333 begin
3334 Inc(x, dx);
3335 Inc(y, dy);
3336 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then exit; // out of the water, just exit
3337 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then exit; // out of the water, just exit
3338 topx := x;
3339 topy := y;
3340 end;
3341 end;
3344 begin
3345 DynWarningCB := mapWarningCB;
3346 end.