DEADSOFTWARE

map: look for replacement resource wads only for network client mode
[d2df-sdl.git] / src / game / g_map.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE ../shared/a_modes.inc}
16 {$DEFINE MAP_DEBUG_ENABLED_FLAG}
17 unit g_map;
19 interface
21 uses
22 SysUtils, Classes, mempool,
23 e_graphics, g_basic, MAPDEF, g_textures,
24 g_phys, utils, g_panel, g_grid, md5, binheap, xprofiler, xparser, xdynrec;
26 type
27 TMapInfo = record
28 Map: String;
29 Name: String;
30 Description: String;
31 Author: String;
32 MusicName: String;
33 SkyName: String;
34 Height: Word;
35 Width: Word;
36 end;
38 PRespawnPoint = ^TRespawnPoint;
39 TRespawnPoint = record
40 X, Y: Integer;
41 Direction: TDirection;
42 PointType: Byte;
43 end;
45 PFlagPoint = ^TFlagPoint;
46 TFlagPoint = TRespawnPoint;
48 PFlag = ^TFlag;
49 TFlag = record
50 Obj: TObj;
51 RespawnType: Byte;
52 State: Byte;
53 Count: Integer;
54 CaptureTime: LongWord;
55 Animation: TAnimation;
56 Direction: TDirection;
57 end;
59 function g_Map_Load(Res: String): Boolean;
60 function g_Map_GetMapInfo(Res: String): TMapInfo;
61 function g_Map_GetMapsList(WADName: String): SSArray;
62 function g_Map_Exist(Res: String): Boolean;
63 procedure g_Map_Free(freeTextures: Boolean=true);
64 procedure g_Map_Update();
66 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
68 procedure g_Map_DrawPanels (PanelType: Word; hasAmbient: Boolean; constref ambColor: TDFColor); // unaccelerated
69 procedure g_Map_CollectDrawPanels (x0, y0, wdt, hgt: Integer);
71 procedure g_Map_DrawBack(dx, dy: Integer);
72 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word;
73 PanelType: Word; b1x3: Boolean=false): Boolean;
74 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
76 procedure g_Map_EnableWallGUID (pguid: Integer);
77 procedure g_Map_DisableWallGUID (pguid: Integer);
78 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
80 // HACK!!!
81 procedure g_Map_EnableWall_XXX (ID: DWORD);
82 procedure g_Map_DisableWall_XXX (ID: DWORD);
83 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer);
85 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
87 procedure g_Map_ReAdd_DieTriggers();
88 function g_Map_IsSpecialTexture(Texture: String): Boolean;
90 function g_Map_GetPoint(PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
91 function g_Map_GetPointCount(PointType: Byte): Word;
93 function g_Map_HaveFlagPoints(): Boolean;
95 procedure g_Map_ResetFlag(Flag: Byte);
96 procedure g_Map_DrawFlags();
98 procedure g_Map_SaveState (st: TStream);
99 procedure g_Map_LoadState (st: TStream);
101 procedure g_Map_DrawPanelShadowVolumes(lightX: Integer; lightY: Integer; radius: Integer);
103 // returns panel or nil
104 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
105 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
107 // returns panel or nil
108 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
109 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
111 type
112 TForEachPanelCB = function (pan: TPanel): Boolean is nested; // return `true` to stop
114 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
115 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
117 // trace liquid, stepping by `dx` and `dy`
118 // return last seen liquid coords, and `false` if we're started outside of the liquid
119 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
122 // return `true` from `cb` to stop
123 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
125 procedure g_Map_NetSendInterestingPanels (); // yay!
128 procedure g_Map_ProfilersBegin ();
129 procedure g_Map_ProfilersEnd ();
132 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
135 function g_Map_MinX (): Integer; inline;
136 function g_Map_MinY (): Integer; inline;
137 function g_Map_MaxX (): Integer; inline;
138 function g_Map_MaxY (): Integer; inline;
140 const
141 NNF_NO_NAME = 0;
142 NNF_NAME_BEFORE = 1;
143 NNF_NAME_EQUALS = 2;
144 NNF_NAME_AFTER = 3;
146 function g_Texture_NumNameFindStart(name: String): Boolean;
147 function g_Texture_NumNameFindNext(var newName: String): Byte;
149 const
150 RESPAWNPOINT_PLAYER1 = 1;
151 RESPAWNPOINT_PLAYER2 = 2;
152 RESPAWNPOINT_DM = 3;
153 RESPAWNPOINT_RED = 4;
154 RESPAWNPOINT_BLUE = 5;
156 FLAG_NONE = 0;
157 FLAG_RED = 1;
158 FLAG_BLUE = 2;
159 FLAG_DOM = 3;
161 FLAG_STATE_NONE = 0;
162 FLAG_STATE_NORMAL = 1;
163 FLAG_STATE_DROPPED = 2;
164 FLAG_STATE_CAPTURED = 3;
165 FLAG_STATE_SCORED = 4; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
166 FLAG_STATE_RETURNED = 5; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
168 FLAG_TIME = 720; // 20 seconds
170 SKY_STRETCH: Single = 1.5;
172 const
173 GridTagInvalid = 0;
175 (* draw order:
176 PANEL_BACK
177 PANEL_STEP
178 PANEL_WALL
179 PANEL_CLOSEDOOR
180 PANEL_ACID1
181 PANEL_ACID2
182 PANEL_WATER
183 PANEL_FORE
184 *)
185 // sorted by draw priority
186 GridTagBack = 1 shl 0; // gRenderBackgrounds
187 GridTagStep = 1 shl 1; // gSteps
188 GridTagWall = 1 shl 2; // gWalls
189 GridTagDoor = 1 shl 3; // gWalls
190 GridTagAcid1 = 1 shl 4; // gAcid1
191 GridTagAcid2 = 1 shl 5; // gAcid2
192 GridTagWater = 1 shl 6; // gWater
193 GridTagFore = 1 shl 7; // gRenderForegrounds
194 // the following are invisible
195 GridTagLift = 1 shl 8; // gLifts
196 GridTagBlockMon = 1 shl 9; // gBlockMon
198 GridTagSolid = (GridTagWall or GridTagDoor);
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: array of TDiskFileInfo = nil;
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 {$INCLUDE ../nogl/noGLuses.inc}
256 e_input, g_main, e_log, e_texture, g_items, g_gfx, g_console,
257 g_weapons, g_game, g_sound, e_sound, CONFIG,
258 g_options, g_triggers, g_player,
259 Math, g_monsters, g_saveload, g_language, g_netmsg,
260 sfs, xstreams, hashtable, wadreader,
261 ImagingTypes, Imaging, ImagingUtility,
262 ImagingGif, ImagingNetworkGraphics,
263 g_res_downloader;
265 const
266 FLAGRECT: TRectWH = (X:15; Y:12; Width:33; Height:52);
267 MUSIC_SIGNATURE = $4953554D; // 'MUSI'
268 FLAG_SIGNATURE = $47414C46; // 'FLAG'
271 // ////////////////////////////////////////////////////////////////////////// //
272 procedure mapWarningCB (const msg: AnsiString; line, col: Integer);
273 begin
274 if (line > 0) then
275 begin
276 e_LogWritefln('parse error at (%s,%s): %s', [line, col, msg], TMsgType.Warning);
277 end
278 else
279 begin
280 e_LogWritefln('parse error: %s', [msg], TMsgType.Warning);
281 end;
282 end;
285 // ////////////////////////////////////////////////////////////////////////// //
286 var
287 panByGUID: array of TPanel = nil;
290 // ////////////////////////////////////////////////////////////////////////// //
291 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
292 begin
293 //if (panByGUID = nil) or (not panByGUID.get(aguid, result)) then result := nil;
294 if (aguid >= 0) and (aguid < Length(panByGUID)) then result := panByGUID[aguid] else result := nil;
295 end;
298 // return `true` from `cb` to stop
299 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
300 var
301 pan: TPanel;
302 begin
303 result := nil;
304 if not assigned(cb) then exit;
305 for pan in panByGUID do
306 begin
307 if cb(pan) then begin result := pan; exit; end;
308 end;
309 end;
312 procedure g_Map_NetSendInterestingPanels ();
313 var
314 pan: TPanel;
315 begin
316 if g_Game_IsServer and g_Game_IsNet then
317 begin
318 for pan in panByGUID do
319 begin
320 if pan.gncNeedSend then MH_SEND_PanelState(pan.guid);
321 end;
322 end;
323 end;
326 // ////////////////////////////////////////////////////////////////////////// //
327 function g_Map_MinX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0 else result := 0; end;
328 function g_Map_MinY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0 else result := 0; end;
329 function g_Map_MaxX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0+mapGrid.gridWidth-1 else result := 0; end;
330 function g_Map_MaxY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0+mapGrid.gridHeight-1 else result := 0; end;
333 // ////////////////////////////////////////////////////////////////////////// //
334 var
335 dfmapdef: TDynMapDef = nil;
338 procedure loadMapDefinition ();
339 var
340 pr: TTextParser = nil;
341 st: TStream = nil;
342 WAD: TWADFile = nil;
343 begin
344 if (dfmapdef <> nil) then exit;
346 try
347 e_LogWritefln('parsing "mapdef.txt"...', []);
348 st := openDiskFileRO(DataDir+'mapdef.txt');
349 e_LogWritefln('found local "%smapdef.txt"', [DataDir]);
350 except
351 st := nil;
352 end;
354 if (st = nil) then
355 begin
356 WAD := TWADFile.Create();
357 if not WAD.ReadFile(GameWAD) then
358 begin
359 //raise Exception.Create('cannot load "game.wad"');
360 st := nil;
361 end
362 else
363 begin
364 st := WAD.openFileStream('mapdef.txt');
365 end;
366 end;
368 try
369 if (st = nil) then
370 begin
371 //raise Exception.Create('cannot open "mapdef.txt"');
372 e_LogWriteln('using default "mapdef.txt"...');
373 pr := TStrTextParser.Create(defaultMapDef);
374 end
375 else
376 begin
377 pr := TFileTextParser.Create(st);
378 end;
379 except on e: Exception do
380 begin
381 e_LogWritefln('something is VERY wrong here! -- ', [e.message]);
382 raise;
383 end;
384 end;
386 try
387 dfmapdef := TDynMapDef.Create(pr);
388 except
389 on e: TDynParseException do
390 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
391 on e: Exception do
392 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [pr.tokLine, pr.tokCol, e.message]);
393 end;
395 st.Free();
396 WAD.Free();
397 end;
400 // ////////////////////////////////////////////////////////////////////////// //
401 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
402 var
403 wst: TSFSMemoryChunkStream = nil;
404 begin
405 result := nil;
406 if (dataLen < 4) then exit;
408 if (dfmapdef = nil) then writeln('need to load mapdef');
409 loadMapDefinition();
410 if (dfmapdef = nil) then raise Exception.Create('internal map loader error');
412 wst := TSFSMemoryChunkStream.Create(data, dataLen);
413 try
414 result := dfmapdef.parseMap(wst);
415 except
416 on e: TDynParseException do
417 begin
418 e_LogWritefln('ERROR at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
419 wst.Free();
420 result := nil;
421 exit;
422 end;
423 on e: Exception do
424 begin
425 e_LogWritefln('ERROR: %s', [e.message]);
426 wst.Free();
427 result := nil;
428 exit;
429 end;
430 end;
432 //e_LogWriteln('map parsed.');
433 end;
436 // ////////////////////////////////////////////////////////////////////////// //
437 var
438 NNF_PureName: String; // Èìÿ òåêñòóðû áåç öèôð â êîíöå
439 NNF_PureExt: String; // extension postfix
440 NNF_FirstNum: Integer; // ×èñëî ó íà÷àëüíîé òåêñòóðû
441 NNF_CurrentNum: Integer; // Ñëåäóþùåå ÷èñëî ó òåêñòóðû
444 function g_Texture_NumNameFindStart(name: String): Boolean;
445 var
446 i, j: Integer;
448 begin
449 Result := False;
450 NNF_PureName := '';
451 NNF_PureExt := '';
452 NNF_FirstNum := -1;
453 NNF_CurrentNum := -1;
455 for i := Length(name) downto 1 do
456 if (name[i] = '_') then // "_" - ñèìâîë íà÷àëà íîìåðíîãî ïîñòôèêñà
457 begin
458 if i = Length(name) then
459 begin // Íåò öèôð â êîíöå ñòðîêè
460 Exit;
461 end
462 else
463 begin
464 j := i + 1;
465 while (j <= Length(name)) and (name[j] <> '.') do inc(j);
466 NNF_PureName := Copy(name, 1, i);
467 NNF_PureExt := Copy(name, j);
468 name := Copy(name, i + 1, j - i - 1);
469 Break;
470 end;
471 end;
473 // Íå ïåðåâåñòè â ÷èñëî:
474 if not TryStrToInt(name, NNF_FirstNum) then
475 Exit;
477 NNF_CurrentNum := 0;
479 Result := True;
480 end;
483 function g_Texture_NumNameFindNext(var newName: String): Byte;
484 begin
485 if (NNF_PureName = '') or (NNF_CurrentNum < 0) then
486 begin
487 newName := '';
488 Result := NNF_NO_NAME;
489 Exit;
490 end;
492 newName := NNF_PureName + IntToStr(NNF_CurrentNum) + NNF_PureExt;
494 if NNF_CurrentNum < NNF_FirstNum then
495 Result := NNF_NAME_BEFORE
496 else
497 if NNF_CurrentNum > NNF_FirstNum then
498 Result := NNF_NAME_AFTER
499 else
500 Result := NNF_NAME_EQUALS;
502 Inc(NNF_CurrentNum);
503 end;
506 // ////////////////////////////////////////////////////////////////////////// //
507 function panelTypeToTag (panelType: Word): Integer;
508 begin
509 case panelType of
510 PANEL_WALL: result := GridTagWall; // gWalls
511 PANEL_OPENDOOR, PANEL_CLOSEDOOR: result := GridTagDoor; // gWalls
512 PANEL_BACK: result := GridTagBack; // gRenderBackgrounds
513 PANEL_FORE: result := GridTagFore; // gRenderForegrounds
514 PANEL_WATER: result := GridTagWater; // gWater
515 PANEL_ACID1: result := GridTagAcid1; // gAcid1
516 PANEL_ACID2: result := GridTagAcid2; // gAcid2
517 PANEL_STEP: result := GridTagStep; // gSteps
518 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: result := GridTagLift; // gLifts -- this is for all lifts
519 PANEL_BLOCKMON: result := GridTagBlockMon; // gBlockMon -- this is for all blockmons
520 else result := GridTagInvalid;
521 end;
522 end;
525 class function TBinHeapPanelDrawCmp.less (const a, b: TPanel): Boolean; inline;
526 begin
527 if (a.tag < b.tag) then begin result := true; exit; end;
528 if (a.tag > b.tag) then begin result := false; exit; end;
529 result := (a.arrIdx < b.arrIdx);
530 end;
532 procedure dplClear ();
533 begin
534 if (gDrawPanelList = nil) then gDrawPanelList := TBinHeapPanelDraw.Create() else gDrawPanelList.clear();
535 end;
538 var
539 Textures: TLevelTextureArray = nil;
540 TextNameHash: THashStrInt = nil; // key: texture name; value: index in `Textures`
541 BadTextNameHash: THashStrInt = nil; // set; so we won't spam with non-existing texture messages
542 RespawnPoints: array of TRespawnPoint;
543 FlagPoints: array[FLAG_RED..FLAG_BLUE] of PFlagPoint;
544 //DOMFlagPoints: Array of TFlagPoint;
547 procedure g_Map_ProfilersBegin ();
548 begin
549 if (profMapCollision = nil) then profMapCollision := TProfiler.Create('COLSOLID', g_profile_history_size);
550 if (profMapCollision <> nil) then profMapCollision.mainBegin(g_profile_collision);
551 // create sections
552 if g_profile_collision and (profMapCollision <> nil) then
553 begin
554 profMapCollision.sectionBegin('*solids');
555 profMapCollision.sectionEnd();
556 profMapCollision.sectionBegin('liquids');
557 profMapCollision.sectionEnd();
558 end;
559 end;
561 procedure g_Map_ProfilersEnd ();
562 begin
563 if (profMapCollision <> nil) then profMapCollision.mainEnd();
564 end;
567 // wall index in `gWalls` or -1
568 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
569 var
570 ex, ey: Integer;
571 begin
572 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, (GridTagWall or GridTagDoor));
573 if (result <> nil) then
574 begin
575 if (hitx <> nil) then hitx^ := ex;
576 if (hity <> nil) then hity^ := ey;
577 end
578 else
579 begin
580 if (hitx <> nil) then hitx^ := x1;
581 if (hity <> nil) then hity^ := y1;
582 end;
583 end;
585 // returns panel or nil
586 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
587 var
588 ex, ey: Integer;
589 begin
590 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, tag);
591 if (result <> nil) then
592 begin
593 if (hitx <> nil) then hitx^ := ex;
594 if (hity <> nil) then hity^ := ey;
595 end
596 else
597 begin
598 if (hitx <> nil) then hitx^ := x1;
599 if (hity <> nil) then hity^ := y1;
600 end;
601 end;
604 function xxPanAtPointChecker (pan: TPanel; panelType: Word): Boolean; inline;
605 begin
606 if ((pan.tag and GridTagLift) <> 0) then
607 begin
608 // stop if the lift of the right type
609 result :=
610 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
611 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
612 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
613 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT)));
614 exit;
615 end;
616 result := true; // otherwise, stop anyway, 'cause `forEachAtPoint()` is guaranteed to call this only for correct panels
617 end;
619 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
620 var
621 tagmask: Integer = 0;
622 mwit: PPanel;
623 it: TPanelGrid.Iter;
624 begin
625 result := false;
627 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
628 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
629 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
630 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
631 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
632 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
633 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
635 if (tagmask = 0) then exit;// just in case
637 if ((tagmask and GridTagLift) <> 0) then
638 begin
639 // slow
640 it := mapGrid.forEachAtPoint(x, y, tagmask);
641 for mwit in it do if (xxPanAtPointChecker(mwit^, PanelType)) then begin result := true; break; end;
642 end
643 else
644 begin
645 // fast
646 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true);
647 result := (it.length <> 0); // firsthit
648 end;
649 it.release();
650 end;
653 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
654 var
655 it: TPanelGrid.Iter;
656 begin
657 result := nil;
658 if (tagmask = 0) then exit;
659 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true); // firsthit
660 if (it.length <> 0) then result := it.first^;
661 it.release();
662 end;
665 function g_Map_IsSpecialTexture(Texture: String): Boolean;
666 begin
667 Result := (Texture = TEXTURE_NAME_WATER) or
668 (Texture = TEXTURE_NAME_ACID1) or
669 (Texture = TEXTURE_NAME_ACID2);
670 end;
672 procedure CreateDoorMap();
673 var
674 PanelArray: Array of record
675 X, Y: Integer;
676 Width, Height: Word;
677 Active: Boolean;
678 PanelID: DWORD;
679 end;
680 a, b, c, m, i, len: Integer;
681 ok: Boolean;
682 begin
683 if gWalls = nil then
684 Exit;
686 i := 0;
687 len := 128;
688 SetLength(PanelArray, len);
690 for a := 0 to High(gWalls) do
691 if gWalls[a].Door then
692 begin
693 PanelArray[i].X := gWalls[a].X;
694 PanelArray[i].Y := gWalls[a].Y;
695 PanelArray[i].Width := gWalls[a].Width;
696 PanelArray[i].Height := gWalls[a].Height;
697 PanelArray[i].Active := True;
698 PanelArray[i].PanelID := a;
700 i := i + 1;
701 if i = len then
702 begin
703 len := len + 128;
704 SetLength(PanelArray, len);
705 end;
706 end;
708 // Íåò äâåðåé:
709 if i = 0 then
710 begin
711 PanelArray := nil;
712 Exit;
713 end;
715 SetLength(gDoorMap, 0);
717 g_Game_SetLoadingText(_lc[I_LOAD_DOOR_MAP], i-1, False);
719 for a := 0 to i-1 do
720 if PanelArray[a].Active then
721 begin
722 PanelArray[a].Active := False;
723 m := Length(gDoorMap);
724 SetLength(gDoorMap, m+1);
725 SetLength(gDoorMap[m], 1);
726 gDoorMap[m, 0] := PanelArray[a].PanelID;
727 ok := True;
729 while ok do
730 begin
731 ok := False;
733 for b := 0 to i-1 do
734 if PanelArray[b].Active then
735 for c := 0 to High(gDoorMap[m]) do
736 if {((gRenderWalls[PanelArray[b].RenderPanelID].TextureID = gRenderWalls[gDoorMap[m, c]].TextureID) or
737 gRenderWalls[PanelArray[b].RenderPanelID].Hide or gRenderWalls[gDoorMap[m, c]].Hide) and}
738 g_CollideAround(PanelArray[b].X, PanelArray[b].Y,
739 PanelArray[b].Width, PanelArray[b].Height,
740 gWalls[gDoorMap[m, c]].X,
741 gWalls[gDoorMap[m, c]].Y,
742 gWalls[gDoorMap[m, c]].Width,
743 gWalls[gDoorMap[m, c]].Height) then
744 begin
745 PanelArray[b].Active := False;
746 SetLength(gDoorMap[m],
747 Length(gDoorMap[m])+1);
748 gDoorMap[m, High(gDoorMap[m])] := PanelArray[b].PanelID;
749 ok := True;
750 Break;
751 end;
752 end;
754 g_Game_StepLoading();
755 end;
757 PanelArray := nil;
758 end;
760 procedure CreateLiftMap();
761 var
762 PanelArray: Array of record
763 X, Y: Integer;
764 Width, Height: Word;
765 Active: Boolean;
766 end;
767 a, b, c, len, i, j: Integer;
768 ok: Boolean;
769 begin
770 if gLifts = nil then
771 Exit;
773 len := Length(gLifts);
774 SetLength(PanelArray, len);
776 for a := 0 to len-1 do
777 begin
778 PanelArray[a].X := gLifts[a].X;
779 PanelArray[a].Y := gLifts[a].Y;
780 PanelArray[a].Width := gLifts[a].Width;
781 PanelArray[a].Height := gLifts[a].Height;
782 PanelArray[a].Active := True;
783 end;
785 SetLength(gLiftMap, len);
786 i := 0;
788 g_Game_SetLoadingText(_lc[I_LOAD_LIFT_MAP], len-1, False);
790 for a := 0 to len-1 do
791 if PanelArray[a].Active then
792 begin
793 PanelArray[a].Active := False;
794 SetLength(gLiftMap[i], 32);
795 j := 0;
796 gLiftMap[i, j] := a;
797 ok := True;
799 while ok do
800 begin
801 ok := False;
802 for b := 0 to len-1 do
803 if PanelArray[b].Active then
804 for c := 0 to j do
805 if g_CollideAround(PanelArray[b].X,
806 PanelArray[b].Y,
807 PanelArray[b].Width,
808 PanelArray[b].Height,
809 PanelArray[gLiftMap[i, c]].X,
810 PanelArray[gLiftMap[i, c]].Y,
811 PanelArray[gLiftMap[i, c]].Width,
812 PanelArray[gLiftMap[i, c]].Height) then
813 begin
814 PanelArray[b].Active := False;
815 j := j+1;
816 if j > High(gLiftMap[i]) then
817 SetLength(gLiftMap[i],
818 Length(gLiftMap[i])+32);
820 gLiftMap[i, j] := b;
821 ok := True;
823 Break;
824 end;
825 end;
827 SetLength(gLiftMap[i], j+1);
828 i := i+1;
830 g_Game_StepLoading();
831 end;
833 SetLength(gLiftMap, i);
835 PanelArray := nil;
836 end;
838 function CreatePanel (PanelRec: TDynRecord; AddTextures: TAddTextureArray; CurTex: Integer): Integer;
839 var
840 len: Integer;
841 panels: ^TPanelArray;
842 pan: TPanel;
843 pguid: Integer;
844 begin
845 Result := -1;
847 case PanelRec.PanelType of
848 PANEL_WALL, PANEL_OPENDOOR, PANEL_CLOSEDOOR: panels := @gWalls;
849 PANEL_BACK: panels := @gRenderBackgrounds;
850 PANEL_FORE: panels := @gRenderForegrounds;
851 PANEL_WATER: panels := @gWater;
852 PANEL_ACID1: panels := @gAcid1;
853 PANEL_ACID2: panels := @gAcid2;
854 PANEL_STEP: panels := @gSteps;
855 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: panels := @gLifts;
856 PANEL_BLOCKMON: panels := @gBlockMon;
857 else exit;
858 end;
860 len := Length(panels^);
861 SetLength(panels^, len+1);
863 pguid := Length(panByGUID);
864 SetLength(panByGUID, pguid+1); //FIXME!
865 pan := TPanel.Create(PanelRec, AddTextures, CurTex, Textures, pguid);
866 assert(pguid >= 0);
867 assert(pguid < Length(panByGUID));
868 panByGUID[pguid] := pan;
869 panels^[len] := pan;
870 pan.arrIdx := len;
871 pan.proxyId := -1;
872 pan.tag := panelTypeToTag(PanelRec.PanelType);
874 PanelRec.user['panel_guid'] := pguid;
876 //result := len;
877 result := pguid;
878 end;
881 function CreateNullTexture(RecName: String): Integer;
882 begin
883 RecName := toLowerCase1251(RecName);
884 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
885 if TextNameHash.get(RecName, result) then exit; // i found her!
887 SetLength(Textures, Length(Textures)+1);
888 result := High(Textures);
890 with Textures[High(Textures)] do
891 begin
892 TextureName := RecName;
893 Width := 1;
894 Height := 1;
895 Anim := False;
896 TextureID := LongWord(TEXTURE_NONE);
897 end;
899 TextNameHash.put(RecName, result);
900 end;
903 function GetReplacementWad (WadName: AnsiString): AnsiString;
904 begin
905 if (length(WadName) = 0) then
906 begin
907 result := '';
908 end
909 else
910 begin
911 result := WadName;
912 if g_Game_IsClient then result := g_Res_FindReplacementWad(WadName);
913 if (result = WadName) then result := GameDir+'/wads/'+result;
914 end;
915 end;
918 function CreateTexture(RecName: AnsiString; Map: string; log: Boolean): Integer;
919 var
920 WAD: TWADFile;
921 TextureData: Pointer;
922 WADName: String;
923 a, ResLength: Integer;
924 begin
925 RecName := toLowerCase1251(RecName);
926 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
927 if TextNameHash.get(RecName, result) then
928 begin
929 // i found her!
930 //e_LogWritefln('texture ''%s'' already loaded (%s)', [RecName, result]);
931 exit;
932 end;
934 Result := -1;
936 if (BadTextNameHash <> nil) and BadTextNameHash.has(RecName) then exit; // don't do it again and again
939 if Textures <> nil then
940 begin
941 for a := 0 to High(Textures) do
942 begin
943 if (Textures[a].TextureName = RecName) then
944 begin // Òåêñòóðà ñ òàêèì èìåíåì óæå åñòü
945 e_LogWritefln('texture ''%s'' already loaded', [RecName]);
946 Result := a;
947 Exit;
948 end;
949 end;
950 end;
953 // Òåêñòóðû ñî ñïåöèàëüíûìè èìåíàìè (âîäà, ëàâà, êèñëîòà):
954 if (RecName = TEXTURE_NAME_WATER) or
955 (RecName = TEXTURE_NAME_ACID1) or
956 (RecName = TEXTURE_NAME_ACID2) then
957 begin
958 SetLength(Textures, Length(Textures)+1);
960 with Textures[High(Textures)] do
961 begin
962 TextureName := RecName;
963 if (TextureName = TEXTURE_NAME_WATER) then TextureID := LongWord(TEXTURE_SPECIAL_WATER)
964 else if (TextureName = TEXTURE_NAME_ACID1) then TextureID := LongWord(TEXTURE_SPECIAL_ACID1)
965 else if (TextureName = TEXTURE_NAME_ACID2) then TextureID := LongWord(TEXTURE_SPECIAL_ACID2);
967 Anim := False;
968 end;
970 result := High(Textures);
971 TextNameHash.put(RecName, result);
972 Exit;
973 end;
975 // Çàãðóæàåì ðåñóðñ òåêñòóðû â ïàìÿòü èç WAD'à:
976 WADName := GetReplacementWad(g_ExtractWadName(RecName));
977 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
979 WAD := TWADFile.Create();
980 WAD.ReadFile(WADName);
982 //txname := RecName;
984 if (WADName = Map) and WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength) then
985 begin
986 FreeMem(TextureData);
987 RecName := 'COMMON\ALIEN';
988 end;
991 if WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength, log) then
992 begin
993 SetLength(Textures, Length(Textures)+1);
994 if not e_CreateTextureMem(TextureData, ResLength, Textures[High(Textures)].TextureID) then
995 begin
996 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
997 SetLength(Textures, Length(Textures)-1);
998 result := -1;
999 Exit;
1000 end;
1001 e_GetTextureSize(Textures[High(Textures)].TextureID, @Textures[High(Textures)].Width, @Textures[High(Textures)].Height);
1002 FreeMem(TextureData);
1003 Textures[High(Textures)].TextureName := RecName;
1004 Textures[High(Textures)].Anim := False;
1006 result := High(Textures);
1007 TextNameHash.put(RecName, result);
1008 end
1009 else // Íåò òàêîãî ðåóñðñà â WAD'å
1010 begin
1011 //e_WriteLog(Format('SHIT! Error loading texture %s : %s', [RecName, g_ExtractFilePathName(RecName)]), MSG_WARNING);
1012 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1013 if log and (not BadTextNameHash.get(RecName, a)) then
1014 begin
1015 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
1016 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1017 end;
1018 BadTextNameHash.put(RecName, -1);
1019 end;
1021 WAD.Free();
1022 end;
1025 function CreateAnimTexture(RecName: String; Map: string; log: Boolean): Integer;
1026 var
1027 WAD: TWADFile;
1028 TextureWAD: PChar = nil;
1029 TextData: Pointer = nil;
1030 TextureData: Pointer = nil;
1031 cfg: TConfig = nil;
1032 WADName: String;
1033 ResLength: Integer;
1034 TextureResource: String;
1035 _width, _height, _framecount, _speed: Integer;
1036 _backanimation: Boolean;
1037 //imgfmt: string;
1038 ia: TDynImageDataArray = nil;
1039 f, c, frdelay, frloop: Integer;
1040 begin
1041 RecName := toLowerCase1251(RecName);
1042 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
1043 if TextNameHash.get(RecName, result) then
1044 begin
1045 // i found her!
1046 //e_LogWritefln('animated texture ''%s'' already loaded (%s)', [RecName, result]);
1047 exit;
1048 end;
1050 result := -1;
1052 //e_LogWritefln('*** Loading animated texture "%s"', [RecName]);
1054 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1055 if BadTextNameHash.get(RecName, f) then
1056 begin
1057 //e_WriteLog(Format('no animation texture %s (don''t worry)', [RecName]), MSG_NOTIFY);
1058 exit;
1059 end;
1061 // ×èòàåì WAD-ðåñóðñ àíèì.òåêñòóðû èç WAD'à â ïàìÿòü:
1062 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1063 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
1065 WAD := TWADFile.Create();
1066 try
1067 //if WADName <> '' then WADName := GameDir+'/wads/'+WADName else WADName := Map;
1069 WAD.ReadFile(WADName);
1071 if not WAD.GetResource(g_ExtractFilePathName(RecName), TextureWAD, ResLength, log) then
1072 begin
1073 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1074 if log and (not BadTextNameHash.get(RecName, f)) then
1075 begin
1076 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1077 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1078 end;
1079 BadTextNameHash.put(RecName, -1);
1080 exit;
1081 end;
1083 {TEST
1084 if WADName = Map then
1085 begin
1086 //FreeMem(TextureWAD);
1087 if not WAD.GetResource('COMMON/animation', TextureWAD, ResLength) then Halt(1);
1088 end;
1091 WAD.FreeWAD();
1093 if ResLength < 6 then
1094 begin
1095 e_WriteLog(Format('Animated texture file "%s" too short', [RecName]), TMsgType.Warning);
1096 BadTextNameHash.put(RecName, -1);
1097 exit;
1098 end;
1100 // ýòî ïòèöà? ýòî ñàìîë¸ò?
1101 if isWadData(TextureWAD, ResLength) then
1102 begin
1103 // íåò, ýòî ñóïåðìåí!
1104 if not WAD.ReadMemory(TextureWAD, ResLength) then
1105 begin
1106 e_WriteLog(Format('Animated texture WAD file "%s" is invalid', [RecName]), TMsgType.Warning);
1107 BadTextNameHash.put(RecName, -1);
1108 exit;
1109 end;
1111 // ×èòàåì INI-ðåñóðñ àíèì. òåêñòóðû è çàïîìèíàåì åãî óñòàíîâêè:
1112 if not WAD.GetResource('TEXT/ANIM', TextData, ResLength) then
1113 begin
1114 e_WriteLog(Format('Animated texture file "%s" has invalid INI', [RecName]), TMsgType.Warning);
1115 BadTextNameHash.put(RecName, -1);
1116 exit;
1117 end;
1119 cfg := TConfig.CreateMem(TextData, ResLength);
1121 TextureResource := cfg.ReadStr('', 'resource', '');
1122 if TextureResource = '' then
1123 begin
1124 e_WriteLog(Format('Animated texture WAD file "%s" has no "resource"', [RecName]), TMsgType.Warning);
1125 BadTextNameHash.put(RecName, -1);
1126 exit;
1127 end;
1129 _width := cfg.ReadInt('', 'framewidth', 0);
1130 _height := cfg.ReadInt('', 'frameheight', 0);
1131 _framecount := cfg.ReadInt('', 'framecount', 0);
1132 _speed := cfg.ReadInt('', 'waitcount', 0);
1133 _backanimation := cfg.ReadBool('', 'backanimation', False);
1135 cfg.Free();
1136 cfg := nil;
1138 // ×èòàåì ðåñóðñ òåêñòóð (êàäðîâ) àíèì. òåêñòóðû â ïàìÿòü:
1139 if not WAD.GetResource('TEXTURES/'+TextureResource, TextureData, ResLength) then
1140 begin
1141 e_WriteLog(Format('Animated texture WAD file "%s" has no texture "%s"', [RecName, 'TEXTURES/'+TextureResource]), TMsgType.Warning);
1142 BadTextNameHash.put(RecName, -1);
1143 exit;
1144 end;
1146 WAD.Free();
1147 WAD := nil;
1149 SetLength(Textures, Length(Textures)+1);
1150 with Textures[High(Textures)] do
1151 begin
1152 // Ñîçäàåì êàäðû àíèì. òåêñòóðû èç ïàìÿòè:
1153 if g_Frames_CreateMemory(@FramesID, '', TextureData, ResLength, _width, _height, _framecount, _backanimation) then
1154 begin
1155 TextureName := RecName;
1156 Width := _width;
1157 Height := _height;
1158 Anim := True;
1159 FramesCount := _framecount;
1160 Speed := _speed;
1161 result := High(Textures);
1162 TextNameHash.put(RecName, result);
1163 end
1164 else
1165 begin
1166 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1167 if log and (not BadTextNameHash.get(RecName, f)) then
1168 begin
1169 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1170 end;
1171 BadTextNameHash.put(RecName, -1);
1172 end;
1173 end;
1174 end
1175 else
1176 begin
1177 // try animated image
1179 imgfmt := DetermineMemoryFormat(TextureWAD, ResLength);
1180 if length(imgfmt) = 0 then
1181 begin
1182 e_WriteLog(Format('Animated texture file "%s" has unknown format', [RecName]), MSG_WARNING);
1183 exit;
1184 end;
1186 GlobalMetadata.ClearMetaItems();
1187 GlobalMetadata.ClearMetaItemsForSaving();
1188 if not LoadMultiImageFromMemory(TextureWAD, ResLength, ia) then
1189 begin
1190 e_WriteLog(Format('Animated texture file "%s" cannot be loaded', [RecName]), TMsgType.Warning);
1191 BadTextNameHash.put(RecName, -1);
1192 exit;
1193 end;
1194 if length(ia) = 0 then
1195 begin
1196 e_WriteLog(Format('Animated texture file "%s" has no frames', [RecName]), TMsgType.Warning);
1197 BadTextNameHash.put(RecName, -1);
1198 exit;
1199 end;
1201 WAD.Free();
1202 WAD := nil;
1204 _width := ia[0].width;
1205 _height := ia[0].height;
1206 _framecount := length(ia);
1207 _speed := 1;
1208 _backanimation := false;
1209 frdelay := -1;
1210 frloop := -666;
1211 if GlobalMetadata.HasMetaItem(SMetaFrameDelay) then
1212 begin
1213 //writeln(' frame delay: ', GlobalMetadata.MetaItems[SMetaFrameDelay]);
1214 try
1215 f := GlobalMetadata.MetaItems[SMetaFrameDelay];
1216 frdelay := f;
1217 if f < 0 then f := 0;
1218 // rounding ;-)
1219 c := f mod 28;
1220 if c < 13 then c := 0 else c := 1;
1221 f := (f div 28)+c;
1222 if f < 1 then f := 1 else if f > 255 then f := 255;
1223 _speed := f;
1224 except
1225 end;
1226 end;
1227 if GlobalMetadata.HasMetaItem(SMetaAnimationLoops) then
1228 begin
1229 //writeln(' frame loop : ', GlobalMetadata.MetaItems[SMetaAnimationLoops]);
1230 try
1231 f := GlobalMetadata.MetaItems[SMetaAnimationLoops];
1232 frloop := f;
1233 if f <> 0 then _backanimation := true; // non-infinite looping == forth-and-back
1234 except
1235 end;
1236 end;
1237 //writeln(' creating animated texture with ', length(ia), ' frames (delay:', _speed, '; backloop:', _backanimation, ') from "', RecName, '"...');
1238 //for f := 0 to high(ia) do writeln(' frame #', f, ': ', ia[f].width, 'x', ia[f].height);
1239 f := ord(_backanimation);
1240 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);
1242 SetLength(Textures, Length(Textures)+1);
1243 // cîçäàåì êàäðû àíèì. òåêñòóðû èç êàðòèíîê
1244 if g_CreateFramesImg(ia, @Textures[High(Textures)].FramesID, '', _backanimation) then
1245 begin
1246 Textures[High(Textures)].TextureName := RecName;
1247 Textures[High(Textures)].Width := _width;
1248 Textures[High(Textures)].Height := _height;
1249 Textures[High(Textures)].Anim := True;
1250 Textures[High(Textures)].FramesCount := length(ia);
1251 Textures[High(Textures)].Speed := _speed;
1252 result := High(Textures);
1253 TextNameHash.put(RecName, result);
1254 //writeln(' CREATED!');
1255 end
1256 else
1257 begin
1258 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1259 if log and (not BadTextNameHash.get(RecName, f)) then
1260 begin
1261 e_WriteLog(Format('Error loading animation texture "%s" images', [RecName]), TMsgType.Warning);
1262 end;
1263 BadTextNameHash.put(RecName, -1);
1264 end;
1265 end;
1266 finally
1267 for f := 0 to High(ia) do FreeImage(ia[f]);
1268 WAD.Free();
1269 cfg.Free();
1270 if (TextureWAD <> nil) then FreeMem(TextureWAD);
1271 if (TextData <> nil) then FreeMem(TextData);
1272 if (TextureData <> nil) then FreeMem(TextureData);
1273 end;
1274 end;
1276 procedure CreateItem(Item: TDynRecord);
1277 begin
1278 if g_Game_IsClient then Exit;
1280 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) and
1281 ByteBool(Item.Options and ITEM_OPTION_ONLYDM) then
1282 Exit;
1284 g_Items_Create(Item.X, Item.Y, Item.ItemType, ByteBool(Item.Options and ITEM_OPTION_FALL),
1285 gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF, GM_COOP]);
1286 end;
1288 procedure CreateArea(Area: TDynRecord);
1289 var
1290 a: Integer;
1291 id: DWORD = 0;
1292 begin
1293 case Area.AreaType of
1294 AREA_DMPOINT, AREA_PLAYERPOINT1, AREA_PLAYERPOINT2,
1295 AREA_REDTEAMPOINT, AREA_BLUETEAMPOINT:
1296 begin
1297 SetLength(RespawnPoints, Length(RespawnPoints)+1);
1298 with RespawnPoints[High(RespawnPoints)] do
1299 begin
1300 X := Area.X;
1301 Y := Area.Y;
1302 Direction := TDirection(Area.Direction);
1304 case Area.AreaType of
1305 AREA_DMPOINT: PointType := RESPAWNPOINT_DM;
1306 AREA_PLAYERPOINT1: PointType := RESPAWNPOINT_PLAYER1;
1307 AREA_PLAYERPOINT2: PointType := RESPAWNPOINT_PLAYER2;
1308 AREA_REDTEAMPOINT: PointType := RESPAWNPOINT_RED;
1309 AREA_BLUETEAMPOINT: PointType := RESPAWNPOINT_BLUE;
1310 end;
1311 end;
1312 end;
1314 AREA_REDFLAG, AREA_BLUEFLAG:
1315 begin
1316 if Area.AreaType = AREA_REDFLAG then a := FLAG_RED else a := FLAG_BLUE;
1318 if FlagPoints[a] <> nil then Exit;
1320 New(FlagPoints[a]);
1322 with FlagPoints[a]^ do
1323 begin
1324 X := Area.X-FLAGRECT.X;
1325 Y := Area.Y-FLAGRECT.Y;
1326 Direction := TDirection(Area.Direction);
1327 end;
1329 with gFlags[a] do
1330 begin
1331 case a of
1332 FLAG_RED: g_Frames_Get(id, 'FRAMES_FLAG_RED');
1333 FLAG_BLUE: g_Frames_Get(id, 'FRAMES_FLAG_BLUE');
1334 end;
1336 Animation := TAnimation.Create(id, True, 8);
1337 Obj.Rect := FLAGRECT;
1339 g_Map_ResetFlag(a);
1340 end;
1341 end;
1343 AREA_DOMFLAG:
1344 begin
1345 {SetLength(DOMFlagPoints, Length(DOMFlagPoints)+1);
1346 with DOMFlagPoints[High(DOMFlagPoints)] do
1347 begin
1348 X := Area.X;
1349 Y := Area.Y;
1350 Direction := TDirection(Area.Direction);
1351 end;
1353 g_Map_CreateFlag(DOMFlagPoints[High(DOMFlagPoints)], FLAG_DOM, FLAG_STATE_NORMAL);}
1354 end;
1355 end;
1356 end;
1358 function CreateTrigger (amapIdx: Integer; Trigger: TDynRecord; atpanid, atrigpanid: Integer): Integer;
1359 var
1360 _trigger: TTrigger;
1361 tp: TPanel;
1362 begin
1363 result := -1;
1364 if g_Game_IsClient and not (Trigger.TriggerType in [TRIGGER_SOUND, TRIGGER_MUSIC]) then Exit;
1366 with _trigger do
1367 begin
1368 mapId := Trigger.id;
1369 mapIndex := amapIdx;
1370 X := Trigger.X;
1371 Y := Trigger.Y;
1372 Width := Trigger.Width;
1373 Height := Trigger.Height;
1374 Enabled := Trigger.Enabled;
1375 TexturePanelGUID := atpanid;
1376 TriggerType := Trigger.TriggerType;
1377 ActivateType := Trigger.ActivateType;
1378 Keys := Trigger.Keys;
1379 trigPanelGUID := atrigpanid;
1380 // HACK: used in TPanel.CanChangeTexture. maybe there's a better way?
1381 if TexturePanelGUID <> -1 then
1382 begin
1383 tp := g_Map_PanelByGUID(TexturePanelGUID);
1384 if (tp <> nil) then tp.hasTexTrigger := True;
1385 end;
1386 end;
1388 result := Integer(g_Triggers_Create(_trigger, Trigger));
1389 end;
1391 procedure CreateMonster(monster: TDynRecord);
1392 var
1393 a: Integer;
1394 mon: TMonster;
1395 begin
1396 if g_Game_IsClient then Exit;
1398 if (gGameSettings.GameType = GT_SINGLE)
1399 or LongBool(gGameSettings.Options and GAME_OPTION_MONSTERS) then
1400 begin
1401 mon := g_Monsters_Create(monster.MonsterType, monster.X, monster.Y, TDirection(monster.Direction));
1403 if gTriggers <> nil then
1404 begin
1405 for a := 0 to High(gTriggers) do
1406 begin
1407 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1408 begin
1409 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1410 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1411 end;
1412 end;
1413 end;
1415 if monster.MonsterType <> MONSTER_BARREL then Inc(gTotalMonsters);
1416 end;
1417 end;
1419 procedure g_Map_ReAdd_DieTriggers();
1421 function monsDieTrig (mon: TMonster): Boolean;
1422 var
1423 a: Integer;
1424 //tw: TStrTextWriter;
1425 begin
1426 result := false; // don't stop
1427 mon.ClearTriggers();
1428 for a := 0 to High(gTriggers) do
1429 begin
1430 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1431 begin
1432 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1434 tw := TStrTextWriter.Create();
1435 try
1436 gTriggers[a].trigData.writeTo(tw);
1437 e_LogWritefln('=== trigger #%s ==='#10'%s'#10'---', [a, tw.str]);
1438 finally
1439 tw.Free();
1440 end;
1442 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1443 end;
1444 end;
1445 end;
1447 begin
1448 if g_Game_IsClient then Exit;
1450 g_Mons_ForEach(monsDieTrig);
1451 end;
1453 function extractWadName(resourceName: string): string;
1454 var
1455 posN: Integer;
1456 begin
1457 posN := Pos(':', resourceName);
1458 if posN > 0 then
1459 Result:= Copy(resourceName, 0, posN-1)
1460 else
1461 Result := '';
1462 end;
1465 procedure addResToExternalResList (res: AnsiString);
1466 var
1467 uname: AnsiString;
1468 f: Integer;
1469 fi: TDiskFileInfo;
1470 begin
1471 if g_Game_IsClient or not g_Game_IsNet then exit;
1472 if (length(res) = 0) then exit; // map wad
1473 res := extractWadName(res);
1474 if (length(res) = 0) then exit; // map wad
1475 uname := toLowerCase1251(res);
1476 // do not add duplicates
1477 for f := 0 to High(gExternalResources) do
1478 begin
1479 if (gExternalResources[f].userName = uname) then exit;
1480 end;
1481 // add new resource
1482 fi.userName := uname;
1483 if (not GetDiskFileInfo(GameDir+'/wads/'+res, fi)) then
1484 begin
1485 fi.tag := -1;
1486 end
1487 else
1488 begin
1489 fi.tag := 0; // non-zero means "cannot caclucate hash"
1490 try
1491 fi.hash := MD5File(fi.diskName);
1492 except
1493 fi.tag := -1;
1494 end;
1495 end;
1496 //e_LogWritefln('addext: res=[%s]; uname=[%s]; diskName=[%s]', [res, fi.userName, fi.diskName]);
1497 SetLength(gExternalResources, length(gExternalResources)+1);
1498 gExternalResources[High(gExternalResources)] := fi;
1499 end;
1502 procedure compactExtResList ();
1503 var
1504 src, dest: Integer;
1505 begin
1506 src := 0;
1507 dest := 0;
1508 for src := 0 to High(gExternalResources) do
1509 begin
1510 if (gExternalResources[src].tag = 0) then
1511 begin
1512 // copy it
1513 if (dest <> src) then gExternalResources[dest] := gExternalResources[src];
1514 Inc(dest);
1515 end;
1516 end;
1517 if (dest <> length(gExternalResources)) then SetLength(gExternalResources, dest);
1518 end;
1521 procedure generateExternalResourcesList (map: TDynRecord);
1522 begin
1523 SetLength(gExternalResources, 0);
1524 addResToExternalResList(map.MusicName);
1525 addResToExternalResList(map.SkyName);
1526 end;
1529 procedure mapCreateGrid ();
1530 var
1531 mapX0: Integer = $3fffffff;
1532 mapY0: Integer = $3fffffff;
1533 mapX1: Integer = -$3fffffff;
1534 mapY1: Integer = -$3fffffff;
1536 procedure calcBoundingBox (constref panels: TPanelArray);
1537 var
1538 idx: Integer;
1539 pan: TPanel;
1540 begin
1541 for idx := 0 to High(panels) do
1542 begin
1543 pan := panels[idx];
1544 if not pan.visvalid then continue;
1545 if (pan.Width < 1) or (pan.Height < 1) then continue;
1546 if (mapX0 > pan.x0) then mapX0 := pan.x0;
1547 if (mapY0 > pan.y0) then mapY0 := pan.y0;
1548 if (mapX1 < pan.x1) then mapX1 := pan.x1;
1549 if (mapY1 < pan.y1) then mapY1 := pan.y1;
1550 end;
1551 end;
1553 procedure addPanelsToGrid (constref panels: TPanelArray);
1554 var
1555 idx: Integer;
1556 pan: TPanel;
1557 newtag: Integer;
1558 begin
1559 //tag := panelTypeToTag(tag);
1560 for idx := 0 to High(panels) do
1561 begin
1562 pan := panels[idx];
1563 if not pan.visvalid then continue;
1564 if (pan.proxyId <> -1) then
1565 begin
1566 {$IF DEFINED(D2F_DEBUG)}
1567 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);
1568 {$ENDIF}
1569 continue;
1570 end;
1571 case pan.PanelType of
1572 PANEL_WALL: newtag := GridTagWall;
1573 PANEL_OPENDOOR, PANEL_CLOSEDOOR: newtag := GridTagDoor;
1574 PANEL_BACK: newtag := GridTagBack;
1575 PANEL_FORE: newtag := GridTagFore;
1576 PANEL_WATER: newtag := GridTagWater;
1577 PANEL_ACID1: newtag := GridTagAcid1;
1578 PANEL_ACID2: newtag := GridTagAcid2;
1579 PANEL_STEP: newtag := GridTagStep;
1580 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: newtag := GridTagLift;
1581 PANEL_BLOCKMON: newtag := GridTagBlockMon;
1582 else continue; // oops
1583 end;
1584 pan.tag := newtag;
1586 pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, newtag);
1587 // "enabled" flag has meaning only for doors and walls (engine assumes it); but meh...
1588 mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
1589 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
1591 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
1592 begin
1593 e_WriteLog(Format('INSERTED wall #%d(%d) enabled (%d)', [Integer(idx), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId])]), MSG_NOTIFY);
1594 end;
1596 {$ENDIF}
1597 end;
1598 end;
1600 begin
1601 mapGrid.Free();
1602 mapGrid := nil;
1604 calcBoundingBox(gWalls);
1605 calcBoundingBox(gRenderBackgrounds);
1606 calcBoundingBox(gRenderForegrounds);
1607 calcBoundingBox(gWater);
1608 calcBoundingBox(gAcid1);
1609 calcBoundingBox(gAcid2);
1610 calcBoundingBox(gSteps);
1611 calcBoundingBox(gLifts);
1612 calcBoundingBox(gBlockMon);
1614 e_LogWritefln('map dimensions: (%d,%d)-(%d,%d); editor size:(0,0)-(%d,%d)', [mapX0, mapY0, mapX1, mapY1, gMapInfo.Width, gMapInfo.Height]);
1616 if (mapX0 > 0) then mapX0 := 0;
1617 if (mapY0 > 0) then mapY0 := 0;
1619 if (mapX1 < gMapInfo.Width-1) then mapX1 := gMapInfo.Width-1;
1620 if (mapY1 < gMapInfo.Height-1) then mapY1 := gMapInfo.Height-1;
1622 mapGrid := TPanelGrid.Create(mapX0-128, mapY0-128, mapX1-mapX0+1+128*2, mapY1-mapY0+1+128*2);
1623 //mapGrid := TPanelGrid.Create(0, 0, gMapInfo.Width, gMapInfo.Height);
1625 addPanelsToGrid(gWalls);
1626 addPanelsToGrid(gRenderBackgrounds);
1627 addPanelsToGrid(gRenderForegrounds);
1628 addPanelsToGrid(gWater);
1629 addPanelsToGrid(gAcid1);
1630 addPanelsToGrid(gAcid2);
1631 addPanelsToGrid(gSteps);
1632 addPanelsToGrid(gLifts); // it doesn't matter which LIFT type is used here
1633 addPanelsToGrid(gBlockMon);
1635 mapGrid.dumpStats();
1637 g_Mons_InitTree(mapGrid.gridX0, mapGrid.gridY0, mapGrid.gridWidth, mapGrid.gridHeight);
1638 end;
1641 function g_Map_Load(Res: String): Boolean;
1642 const
1643 DefaultMusRes = 'Standart.wad:STDMUS\MUS1';
1644 DefaultSkyRes = 'Standart.wad:STDSKY\SKY0';
1645 type
1646 PTRec = ^TTRec;
1647 TTRec = record
1648 //TexturePanel: Integer;
1649 tnum: Integer;
1650 id: Integer;
1651 trigrec: TDynRecord;
1652 // texture pane;
1653 texPanelIdx: Integer;
1654 texPanel: TDynRecord;
1655 // "action" panel
1656 actPanelIdx: Integer;
1657 actPanel: TDynRecord;
1658 end;
1659 var
1660 WAD, TestWAD: TWADFile;
1661 //mapReader: TDynRecord = nil;
1662 mapTextureList: TDynField = nil; //TTexturesRec1Array; tagInt: texture index
1663 panels: TDynField = nil; //TPanelsRec1Array;
1664 items: TDynField = nil; //TItemsRec1Array;
1665 monsters: TDynField = nil; //TMonsterRec1Array;
1666 areas: TDynField = nil; //TAreasRec1Array;
1667 triggers: TDynField = nil; //TTriggersRec1Array;
1668 b, c, k: Integer;
1669 PanelID: DWORD;
1670 AddTextures: TAddTextureArray;
1671 TriggersTable: array of TTRec;
1672 FileName, mapResName, TexName, s: AnsiString;
1673 Data: Pointer;
1674 Len: Integer;
1675 ok, isAnim: Boolean;
1676 CurTex, ntn: Integer;
1677 rec, texrec: TDynRecord;
1678 pttit: PTRec;
1679 pannum, trignum, cnt, tgpid: Integer;
1680 stt: UInt64;
1681 moveSpeed{, moveStart, moveEnd}: TDFPoint;
1682 //moveActive: Boolean;
1683 pan: TPanel;
1684 mapOk: Boolean = false;
1685 usedTextures: THashStrInt = nil; // key: mapTextureList
1686 begin
1687 mapGrid.Free();
1688 mapGrid := nil;
1689 TestWAD := nil;
1690 Data := nil;
1692 //gCurrentMap.Free();
1693 //gCurrentMap := nil;
1695 panByGUID := nil;
1697 Result := False;
1698 gMapInfo.Map := Res;
1699 TriggersTable := nil;
1700 //mapReader := nil;
1702 sfsGCDisable(); // temporary disable removing of temporary volumes
1703 try
1704 // Çàãðóçêà WAD (åñëè ó íàñ íåò óæå çàãðóæåíîé êàðòû)
1705 if (gCurrentMap = nil) then
1706 begin
1707 FileName := g_ExtractWadName(Res);
1708 e_LogWritefln('Loading map WAD [%s] (res=[%s])', [FileName, Res], TMsgType.Notify);
1709 g_Game_SetLoadingText(_lc[I_LOAD_WAD_FILE], 0, False);
1711 WAD := TWADFile.Create();
1712 if not WAD.ReadFile(FileName) then
1713 begin
1714 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [FileName]));
1715 WAD.Free();
1716 Exit;
1717 end;
1719 if gTestMap <> '' then
1720 begin
1721 s := g_ExtractWadName(gTestMap);
1722 TestWAD := TWADFile.Create();
1723 if not TestWAD.ReadFile(s) then
1724 begin
1725 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_WAD], [s]));
1726 TestWAD.Free();
1727 TestWAD := nil;
1728 end;
1729 end;
1731 if TestWAD <> nil then
1732 begin
1733 mapResName := g_ExtractFileName(gTestMap);
1734 if not TestWAD.GetMapResource(mapResName, Data, Len) then
1735 begin
1736 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1737 Data := nil;
1738 end else
1739 e_WriteLog('Using test map: '+gTestMap, TMsgType.Notify);
1740 TestWAD.Free();
1741 TestWAD := nil;
1742 end;
1744 if Data = nil then
1745 begin
1746 //k8: why loader ignores path here?
1747 mapResName := g_ExtractFileName(Res);
1748 if not WAD.GetMapResource(mapResName, Data, Len) then
1749 begin
1750 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1751 WAD.Free();
1752 Exit;
1753 end;
1754 end;
1756 WAD.Free();
1758 if (Len < 4) then
1759 begin
1760 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1761 FreeMem(Data);
1762 exit;
1763 end;
1765 // Çàãðóçêà êàðòû:
1766 e_LogWritefln('Loading map: %s', [mapResName], TMsgType.Notify);
1767 g_Game_SetLoadingText(_lc[I_LOAD_MAP], 0, False);
1769 stt := getTimeMicro();
1771 try
1772 gCurrentMap := g_Map_ParseMap(Data, Len);
1773 except
1774 gCurrentMap.Free();
1775 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]));
1776 FreeMem(Data);
1777 gCurrentMapFileName := '';
1778 Exit;
1779 end;
1781 FreeMem(Data);
1783 if (gCurrentMap = nil) then
1784 begin
1785 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1786 gCurrentMapFileName := '';
1787 exit;
1788 end;
1789 end
1790 else
1791 begin
1792 stt := getTimeMicro();
1793 end;
1795 //gCurrentMap := mapReader;
1797 generateExternalResourcesList(gCurrentMap);
1798 mapTextureList := gCurrentMap['texture'];
1799 // get all other lists here too
1800 panels := gCurrentMap['panel'];
1801 triggers := gCurrentMap['trigger'];
1802 items := gCurrentMap['item'];
1803 areas := gCurrentMap['area'];
1804 monsters := gCurrentMap['monster'];
1806 // Çàãðóçêà îïèñàíèÿ êàðòû:
1807 e_WriteLog(' Reading map info...', TMsgType.Notify);
1808 g_Game_SetLoadingText(_lc[I_LOAD_MAP_HEADER], 0, False);
1810 with gMapInfo do
1811 begin
1812 Name := gCurrentMap.MapName;
1813 Description := gCurrentMap.MapDesc;
1814 Author := gCurrentMap.MapAuthor;
1815 MusicName := gCurrentMap.MusicName;
1816 SkyName := gCurrentMap.SkyName;
1817 Height := gCurrentMap.Height;
1818 Width := gCurrentMap.Width;
1819 end;
1821 // Çàãðóçêà òåêñòóð:
1822 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], 0, False);
1823 // Äîáàâëåíèå òåêñòóð â Textures[]:
1824 if (mapTextureList <> nil) and (mapTextureList.count > 0) then
1825 begin
1826 e_WriteLog(' Loading textures:', TMsgType.Notify);
1827 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], mapTextureList.count-1, False);
1829 // find used textures
1830 usedTextures := THashStrInt.Create();
1831 try
1832 if (panels <> nil) and (panels.count > 0) then
1833 begin
1834 for rec in panels do
1835 begin
1836 texrec := rec.TextureRec;
1837 if (texrec <> nil) then usedTextures.put(toLowerCase1251(texrec.Resource), 42);
1838 end;
1839 end;
1841 cnt := -1;
1842 for rec in mapTextureList do
1843 begin
1844 Inc(cnt);
1845 if not usedTextures.has(toLowerCase1251(rec.Resource)) then
1846 begin
1847 rec.tagInt := -1; // just in case
1848 e_LogWritefln(' Unused texture #%d: %s', [cnt, rec.Resource]);
1849 end
1850 else
1851 begin
1852 {$IF DEFINED(D2F_DEBUG_TXLOAD)}
1853 e_LogWritefln(' Loading texture #%d: %s', [cnt, rec.Resource]);
1854 {$ENDIF}
1855 //if g_Map_IsSpecialTexture(s) then e_WriteLog(' SPECIAL!', MSG_NOTIFY);
1856 if rec.Anim then
1857 begin
1858 // Àíèìèðîâàííàÿ òåêñòóðà
1859 ntn := CreateAnimTexture(rec.Resource, FileName, True);
1860 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_ANIM], [rec.Resource]));
1861 end
1862 else
1863 begin
1864 // Îáû÷íàÿ òåêñòóðà
1865 ntn := CreateTexture(rec.Resource, FileName, True);
1866 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_SIMPLE], [rec.Resource]));
1867 end;
1868 if (ntn < 0) then
1869 begin
1870 ntn := CreateNullTexture(rec.Resource);
1871 end
1872 else
1873 begin
1874 addResToExternalResList(rec.Resource);
1875 end;
1877 rec.tagInt := ntn; // remember texture number
1878 end;
1879 g_Game_StepLoading();
1880 end;
1881 finally
1882 usedTextures.Free();
1883 end;
1885 // set panel tagInt to texture index
1886 if (panels <> nil) then
1887 begin
1888 for rec in panels do
1889 begin
1890 texrec := rec.TextureRec;
1891 if (texrec = nil) then rec.tagInt := -1 else rec.tagInt := texrec.tagInt;
1892 end;
1893 end;
1894 end;
1897 // Çàãðóçêà òðèããåðîâ
1898 gTriggerClientID := 0;
1899 e_WriteLog(' Loading triggers...', TMsgType.Notify);
1900 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS], 0, False);
1902 // Çàãðóçêà ïàíåëåé
1903 e_WriteLog(' Loading panels...', TMsgType.Notify);
1904 g_Game_SetLoadingText(_lc[I_LOAD_PANELS], 0, False);
1906 // check texture numbers for panels
1907 if (panels <> nil) and (panels.count > 0) then
1908 begin
1909 for rec in panels do
1910 begin
1911 if (rec.tagInt < 0) then
1912 begin
1913 e_WriteLog('error loading map: invalid texture index for panel', TMsgType.Fatal);
1914 result := false;
1915 gCurrentMap.Free();
1916 gCurrentMap := nil;
1917 gCurrentMapFileName := '';
1918 exit;
1919 end;
1920 end;
1921 end;
1923 // Ñîçäàíèå òàáëèöû òðèããåðîâ (ñîîòâåòñòâèå ïàíåëåé òðèããåðàì)
1924 if (triggers <> nil) and (triggers.count > 0) then
1925 begin
1926 e_WriteLog(' Setting up trigger table...', TMsgType.Notify);
1927 //SetLength(TriggersTable, triggers.count);
1928 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS_TABLE], triggers.count-1, False);
1930 SetLength(TriggersTable, triggers.count);
1931 trignum := -1;
1932 for rec in triggers do
1933 begin
1934 Inc(trignum);
1935 pttit := @TriggersTable[trignum];
1936 pttit.trigrec := rec;
1937 // Ñìåíà òåêñòóðû (âîçìîæíî, êíîïêè)
1938 pttit.texPanelIdx := -1; // will be fixed later
1939 pttit.texPanel := rec.TexturePanelRec;
1940 // action panel
1941 pttit.actPanelIdx := -1;
1942 if (rec.trigRec <> nil) then pttit.actPanel := rec.trigRec.tgPanelRec else pttit.actPanel := nil;
1943 // set flag
1944 if (pttit.texPanel <> nil) then pttit.texPanel.userPanelTrigRef := true;
1945 if (pttit.actPanel <> nil) then pttit.actPanel.userPanelTrigRef := true;
1946 // update progress
1947 g_Game_StepLoading();
1948 end;
1949 end;
1951 // Ñîçäàåì ïàíåëè
1952 if (panels <> nil) and (panels.count > 0) then
1953 begin
1954 e_WriteLog(' Setting up trigger links...', TMsgType.Notify);
1955 g_Game_SetLoadingText(_lc[I_LOAD_LINK_TRIGGERS], panels.count-1, False);
1957 pannum := -1;
1958 for rec in panels do
1959 begin
1960 Inc(pannum);
1961 //e_LogWritefln('PANSTART: pannum=%s', [pannum]);
1962 texrec := nil;
1963 SetLength(AddTextures, 0);
1964 CurTex := -1;
1965 ok := false;
1967 if (mapTextureList <> nil) then
1968 begin
1969 texrec := rec.TextureRec;
1970 ok := (texrec <> nil);
1971 end;
1973 if ok then
1974 begin
1975 // Ñìîòðèì, ññûëàþòñÿ ëè íà ýòó ïàíåëü òðèããåðû.
1976 // Åñëè äà - òî íàäî ñîçäàòü åùå òåêñòóð
1977 ok := false;
1978 if (TriggersTable <> nil) and (mapTextureList <> nil) then
1979 begin
1980 if rec.userPanelTrigRef then
1981 begin
1982 // e_LogWritefln('trigref for panel %s', [pannum]);
1983 ok := True;
1984 end;
1985 end;
1986 end;
1988 if ok then
1989 begin
1990 // Åñòü ññûëêè òðèããåðîâ íà ýòó ïàíåëü
1991 s := texrec.Resource;
1993 // Ñïåö-òåêñòóðû çàïðåùåíû
1994 if g_Map_IsSpecialTexture(s) then
1995 begin
1996 ok := false
1997 end
1998 else
1999 begin
2000 // Îïðåäåëÿåì íàëè÷èå è ïîëîæåíèå öèôð â êîíöå ñòðîêè
2001 ok := g_Texture_NumNameFindStart(s);
2002 end;
2004 // Åñëè ok, çíà÷èò åñòü öèôðû â êîíöå.
2005 // Çàãðóæàåì òåêñòóðû ñ îñòàëüíûìè #
2006 if ok then
2007 begin
2008 k := NNF_NAME_BEFORE;
2009 // Öèêë ïî èçìåíåíèþ èìåíè òåêñòóðû
2010 while ok or (k = NNF_NAME_BEFORE) or (k = NNF_NAME_EQUALS) do
2011 begin
2012 k := g_Texture_NumNameFindNext(TexName);
2014 if (k = NNF_NAME_BEFORE) or (k = NNF_NAME_AFTER) then
2015 begin
2016 // Ïðîáóåì äîáàâèòü íîâóþ òåêñòóðó
2017 if texrec.Anim then
2018 begin
2019 // Íà÷àëüíàÿ - àíèìèðîâàííàÿ, èùåì àíèìèðîâàííóþ
2020 isAnim := True;
2021 //e_LogWritefln('000: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2022 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2023 //e_LogWritefln('001: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2024 if not ok then
2025 begin
2026 // Íåò àíèìèðîâàííîé, èùåì îáû÷íóþ
2027 isAnim := False;
2028 //e_LogWritefln('002: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2029 ok := CreateTexture(TexName, FileName, False) >= 0;
2030 //e_LogWritefln('003: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2031 end;
2032 end
2033 else
2034 begin
2035 // Íà÷àëüíàÿ - îáû÷íàÿ, èùåì îáû÷íóþ
2036 isAnim := False;
2037 //e_LogWritefln('004: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2038 ok := CreateTexture(TexName, FileName, False) >= 0;
2039 //e_LogWritefln('005: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2040 if not ok then
2041 begin
2042 // Íåò îáû÷íîé, èùåì àíèìèðîâàííóþ
2043 isAnim := True;
2044 //e_LogWritefln('006: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2045 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2046 //e_LogWritefln('007: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2047 end;
2048 end;
2050 // Îíà ñóùåñòâóåò. Çàíîñèì åå ID â ñïèñîê ïàíåëè
2051 if ok then
2052 begin
2054 for c := 0 to High(Textures) do
2055 begin
2056 if (Textures[c].TextureName = TexName) then
2057 begin
2058 SetLength(AddTextures, Length(AddTextures)+1);
2059 AddTextures[High(AddTextures)].Texture := c;
2060 AddTextures[High(AddTextures)].Anim := isAnim;
2061 break;
2062 end;
2063 end;
2065 if (TextNameHash <> nil) and TextNameHash.get(toLowerCase1251(TexName), c) then
2066 begin
2067 SetLength(AddTextures, Length(AddTextures)+1);
2068 AddTextures[High(AddTextures)].Texture := c;
2069 AddTextures[High(AddTextures)].Anim := isAnim;
2070 end;
2071 end;
2072 end
2073 else
2074 begin
2075 if k = NNF_NAME_EQUALS then
2076 begin
2077 // Çàíîñèì òåêóùóþ òåêñòóðó íà ñâîå ìåñòî
2078 SetLength(AddTextures, Length(AddTextures)+1);
2079 AddTextures[High(AddTextures)].Texture := rec.tagInt; // internal texture number, not map index
2080 AddTextures[High(AddTextures)].Anim := texrec.Anim;
2081 CurTex := High(AddTextures);
2082 ok := true;
2083 end
2084 else // NNF_NO_NAME
2085 begin
2086 ok := false;
2087 end;
2088 end;
2089 end; // while ok...
2091 ok := true;
2092 end; // if ok - åñòü ñìåæíûå òåêñòóðû
2093 end; // if ok - ññûëàþòñÿ òðèããåðû
2095 if not ok then
2096 begin
2097 // Çàíîñèì òîëüêî òåêóùóþ òåêñòóðó
2098 SetLength(AddTextures, 1);
2099 AddTextures[0].Texture := rec.tagInt; // internal texture number, not map index
2100 AddTextures[0].Anim := false;
2101 if (texrec <> nil) then AddTextures[0].Anim := texrec.Anim;
2102 CurTex := 0;
2103 end;
2105 //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);
2107 //e_LogWritefln('PANADD: pannum=%s', [pannum]);
2109 // Ñîçäàåì ïàíåëü è çàïîìèíàåì åå GUID
2110 //e_LogWritefln('new panel; tcount=%s; curtex=%s', [Length(AddTextures), CurTex]);
2111 PanelID := CreatePanel(rec, AddTextures, CurTex);
2112 //e_LogWritefln('panel #%s of type %s got guid #%s', [pannum, rec.PanelType, PanelID]);
2113 rec.userPanelId := PanelID; // remember game panel id, we'll fix triggers later
2115 // setup lifts
2116 moveSpeed := rec.moveSpeed;
2117 //moveStart := rec.moveStart;
2118 //moveEnd := rec.moveEnd;
2119 //moveActive := rec['move_active'].value;
2120 if not moveSpeed.isZero then
2121 begin
2122 SetLength(gMovingWallIds, Length(gMovingWallIds)+1);
2123 gMovingWallIds[High(gMovingWallIds)] := PanelID;
2124 //e_LogWritefln('found moving panel ''%s'' (idx=%s; id=%s)', [rec.id, pannum, PanelID]);
2125 end;
2127 //e_LogWritefln('PANEND: pannum=%s', [pannum]);
2129 g_Game_StepLoading();
2130 end;
2131 end;
2133 // ×èíèì ID'û ïàíåëåé, êîòîðûå èñïîëüçóþòñÿ â òðèããåðàõ
2134 for b := 0 to High(TriggersTable) do
2135 begin
2136 if (TriggersTable[b].texPanel <> nil) then TriggersTable[b].texPanelIdx := TriggersTable[b].texPanel.userPanelId;
2137 if (TriggersTable[b].actPanel <> nil) then TriggersTable[b].actPanelIdx := TriggersTable[b].actPanel.userPanelId;
2138 end;
2140 // create map grid, init other grids (for monsters, for example)
2141 e_WriteLog('Creating map grid', TMsgType.Notify);
2142 mapCreateGrid();
2144 // Åñëè íå LoadState, òî ñîçäàåì òðèããåðû
2145 if (triggers <> nil) and (panels <> nil) and (not gLoadGameMode) then
2146 begin
2147 e_LogWritefln(' Creating triggers (%d)...', [triggers.count]);
2148 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_TRIGGERS], 0, False);
2149 // Óêàçûâàåì òèï ïàíåëè, åñëè åñòü
2150 trignum := -1;
2151 for rec in triggers do
2152 begin
2153 Inc(trignum);
2154 tgpid := TriggersTable[trignum].actPanelIdx;
2155 //e_LogWritefln('creating trigger #%s; texpantype=%s; shotpantype=%s (%d,%d)', [trignum, b, c, TriggersTable[trignum].texPanIdx, TriggersTable[trignum].ShotPanelIdx]);
2156 TriggersTable[trignum].tnum := trignum;
2157 TriggersTable[trignum].id := CreateTrigger(trignum, rec, TriggersTable[trignum].texPanelIdx, tgpid);
2158 end;
2159 end;
2161 //FIXME: use hashtable!
2162 for pan in panByGUID do
2163 begin
2164 if (pan.endPosTrigId >= 0) and (pan.endPosTrigId < Length(TriggersTable)) then
2165 begin
2166 pan.endPosTrigId := TriggersTable[pan.endPosTrigId].id;
2167 end;
2168 if (pan.endSizeTrigId >= 0) and (pan.endSizeTrigId < Length(TriggersTable)) then
2169 begin
2170 pan.endSizeTrigId := TriggersTable[pan.endSizeTrigId].id;
2171 end;
2172 end;
2174 // Çàãðóçêà ïðåäìåòîâ
2175 e_WriteLog(' Loading items...', TMsgType.Notify);
2176 g_Game_SetLoadingText(_lc[I_LOAD_ITEMS], 0, False);
2178 // Åñëè íå LoadState, òî ñîçäàåì ïðåäìåòû
2179 if (items <> nil) and not gLoadGameMode then
2180 begin
2181 e_WriteLog(' Spawning items...', TMsgType.Notify);
2182 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_ITEMS], 0, False);
2183 for rec in items do CreateItem(rec);
2184 end;
2186 // Çàãðóçêà îáëàñòåé
2187 e_WriteLog(' Loading areas...', TMsgType.Notify);
2188 g_Game_SetLoadingText(_lc[I_LOAD_AREAS], 0, False);
2190 // Åñëè íå LoadState, òî ñîçäàåì îáëàñòè
2191 if areas <> nil then
2192 begin
2193 e_WriteLog(' Creating areas...', TMsgType.Notify);
2194 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_AREAS], 0, False);
2195 for rec in areas do CreateArea(rec);
2196 end;
2198 // Çàãðóçêà ìîíñòðîâ
2199 e_WriteLog(' Loading monsters...', TMsgType.Notify);
2200 g_Game_SetLoadingText(_lc[I_LOAD_MONSTERS], 0, False);
2202 gTotalMonsters := 0;
2204 // Åñëè íå LoadState, òî ñîçäàåì ìîíñòðîâ
2205 if (monsters <> nil) and not gLoadGameMode then
2206 begin
2207 e_WriteLog(' Spawning monsters...', TMsgType.Notify);
2208 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_MONSTERS], 0, False);
2209 for rec in monsters do CreateMonster(rec);
2210 end;
2212 //gCurrentMap := mapReader; // this will be our current map now
2213 gCurrentMapFileName := Res;
2214 //mapReader := nil;
2216 // Çàãðóçêà íåáà
2217 if (gMapInfo.SkyName <> '') then
2218 begin
2219 e_WriteLog(' Loading sky: ' + gMapInfo.SkyName, TMsgType.Notify);
2220 g_Game_SetLoadingText(_lc[I_LOAD_SKY], 0, False);
2221 FileName := g_ExtractWadName(gMapInfo.SkyName);
2223 if (FileName <> '') then FileName := GameDir+'/wads/'+FileName else FileName := g_ExtractWadName(Res);
2225 if gTextureFilter then TEXTUREFILTER := GL_LINEAR else TEXTUREFILTER := GL_NEAREST;
2226 try
2227 s := FileName+':'+g_ExtractFilePathName(gMapInfo.SkyName);
2228 if g_Texture_CreateWAD(BackID, s) then
2229 begin
2230 g_Game_SetupScreenSize();
2231 end
2232 else
2233 begin
2234 g_FatalError(Format(_lc[I_GAME_ERROR_SKY], [s]));
2235 end;
2236 finally
2237 TEXTUREFILTER := GL_NEAREST;
2238 end;
2239 end;
2241 // Çàãðóçêà ìóçûêè
2242 ok := False;
2243 if gMapInfo.MusicName <> '' then
2244 begin
2245 e_WriteLog(' Loading music: ' + gMapInfo.MusicName, TMsgType.Notify);
2246 g_Game_SetLoadingText(_lc[I_LOAD_MUSIC], 0, False);
2247 FileName := g_ExtractWadName(gMapInfo.MusicName);
2249 if FileName <> '' then
2250 FileName := GameDir+'/wads/'+FileName
2251 else
2252 begin
2253 FileName := g_ExtractWadName(Res);
2254 end;
2256 s := FileName+':'+g_ExtractFilePathName(gMapInfo.MusicName);
2257 if g_Sound_CreateWADEx(gMapInfo.MusicName, s, True) then
2258 ok := True
2259 else
2260 g_FatalError(Format(_lc[I_GAME_ERROR_MUSIC], [s]));
2261 end;
2263 // Îñòàëüíûå óñòàíâêè
2264 CreateDoorMap();
2265 CreateLiftMap();
2267 g_Items_Init();
2268 g_Weapon_Init();
2269 g_Monsters_Init();
2271 // Åñëè íå LoadState, òî ñîçäàåì êàðòó ñòîëêíîâåíèé:
2272 if not gLoadGameMode then g_GFX_Init();
2274 // Ñáðîñ ëîêàëüíûõ ìàññèâîâ:
2275 mapTextureList := nil;
2276 panels := nil;
2277 items := nil;
2278 areas := nil;
2279 triggers := nil;
2280 TriggersTable := nil;
2281 AddTextures := nil;
2283 // Âêëþ÷àåì ìóçûêó, åñëè ýòî íå çàãðóçêà:
2284 if ok and (not gLoadGameMode) then
2285 begin
2286 gMusic.SetByName(gMapInfo.MusicName);
2287 gMusic.Play();
2288 end
2289 else
2290 begin
2291 gMusic.SetByName('');
2292 end;
2294 stt := getTimeMicro()-stt;
2295 e_LogWritefln('map loaded in %s.%s milliseconds', [Integer(stt div 1000), Integer(stt mod 1000)]);
2296 mapOk := true;
2297 finally
2298 sfsGCEnable(); // enable releasing unused volumes
2299 //mapReader.Free();
2300 e_UnpressAllKeys; // why not?
2301 if not mapOk then
2302 begin
2303 gCurrentMap.Free();
2304 gCurrentMap := nil;
2305 gCurrentMapFileName := '';
2306 end;
2307 end;
2309 compactExtResList();
2310 e_WriteLog('Done loading map.', TMsgType.Notify);
2311 Result := True;
2312 end;
2315 function g_Map_GetMapInfo(Res: String): TMapInfo;
2316 var
2317 WAD: TWADFile;
2318 mapReader: TDynRecord;
2319 //Header: TMapHeaderRec_1;
2320 FileName: String;
2321 Data: Pointer;
2322 Len: Integer;
2323 begin
2324 FillChar(Result, SizeOf(Result), 0);
2325 FileName := g_ExtractWadName(Res);
2327 WAD := TWADFile.Create();
2328 if not WAD.ReadFile(FileName) then
2329 begin
2330 WAD.Free();
2331 Exit;
2332 end;
2334 //k8: it ignores path again
2335 if not WAD.GetMapResource(g_ExtractFileName(Res), Data, Len) then
2336 begin
2337 WAD.Free();
2338 Exit;
2339 end;
2341 WAD.Free();
2343 try
2344 mapReader := g_Map_ParseMap(Data, Len);
2345 except
2346 mapReader := nil;
2347 FreeMem(Data);
2348 exit;
2349 end;
2351 FreeMem(Data);
2353 if (mapReader = nil) then exit;
2355 if (mapReader.Width > 0) and (mapReader.Height > 0) then
2356 begin
2357 Result.Name := mapReader.MapName;
2358 Result.Description := mapReader.MapDesc;
2359 Result.Map := Res;
2360 Result.Author := mapReader.MapAuthor;
2361 Result.Height := mapReader.Height;
2362 Result.Width := mapReader.Width;
2363 end
2364 else
2365 begin
2366 g_Console_Add(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]), True);
2367 //ZeroMemory(@Header, SizeOf(Header));
2368 Result.Name := _lc[I_GAME_ERROR_MAP_SELECT];
2369 Result.Description := _lc[I_GAME_ERROR_MAP_SELECT];
2370 Result.Map := Res;
2371 Result.Author := '';
2372 Result.Height := 0;
2373 Result.Width := 0;
2374 end;
2376 mapReader.Free();
2377 end;
2379 function g_Map_GetMapsList(WADName: string): SSArray;
2380 var
2381 WAD: TWADFile;
2382 a: Integer;
2383 ResList: SSArray;
2384 begin
2385 Result := nil;
2386 WAD := TWADFile.Create();
2387 if not WAD.ReadFile(WADName) then
2388 begin
2389 WAD.Free();
2390 Exit;
2391 end;
2392 ResList := WAD.GetMapResources();
2393 if ResList <> nil then
2394 begin
2395 for a := 0 to High(ResList) do
2396 begin
2397 SetLength(Result, Length(Result)+1);
2398 Result[High(Result)] := ResList[a];
2399 end;
2400 end;
2401 WAD.Free();
2402 end;
2404 function g_Map_Exist(Res: string): Boolean;
2405 var
2406 WAD: TWADFile;
2407 FileName, mnn: string;
2408 ResList: SSArray;
2409 a: Integer;
2410 begin
2411 Result := False;
2413 FileName := addWadExtension(g_ExtractWadName(Res));
2415 WAD := TWADFile.Create;
2416 if not WAD.ReadFile(FileName) then
2417 begin
2418 WAD.Free();
2419 Exit;
2420 end;
2422 ResList := WAD.GetMapResources();
2423 WAD.Free();
2425 mnn := g_ExtractFileName(Res);
2426 if ResList <> nil then
2427 for a := 0 to High(ResList) do if StrEquCI1251(ResList[a], mnn) then
2428 begin
2429 Result := True;
2430 Exit;
2431 end;
2432 end;
2434 procedure g_Map_Free(freeTextures: Boolean=true);
2435 var
2436 a: Integer;
2438 procedure FreePanelArray(var panels: TPanelArray);
2439 var
2440 i: Integer;
2442 begin
2443 if panels <> nil then
2444 begin
2445 for i := 0 to High(panels) do
2446 panels[i].Free();
2447 panels := nil;
2448 end;
2449 end;
2451 begin
2452 g_GFX_Free();
2453 g_Weapon_Free();
2454 g_Items_Free();
2455 g_Triggers_Free();
2456 g_Monsters_Free();
2458 RespawnPoints := nil;
2459 if FlagPoints[FLAG_RED] <> nil then
2460 begin
2461 Dispose(FlagPoints[FLAG_RED]);
2462 FlagPoints[FLAG_RED] := nil;
2463 end;
2464 if FlagPoints[FLAG_BLUE] <> nil then
2465 begin
2466 Dispose(FlagPoints[FLAG_BLUE]);
2467 FlagPoints[FLAG_BLUE] := nil;
2468 end;
2469 //DOMFlagPoints := nil;
2471 //gDOMFlags := nil;
2473 if (Length(gCurrentMapFileName) <> 0) then
2474 begin
2475 e_LogWritefln('g_Map_Free: previous map was ''%s''...', [gCurrentMapFileName]);
2476 end
2477 else
2478 begin
2479 e_LogWritefln('g_Map_Free: no previous map.', []);
2480 end;
2482 if freeTextures then
2483 begin
2484 e_LogWritefln('g_Map_Free: clearing textures...', []);
2485 if (Textures <> nil) then
2486 begin
2487 for a := 0 to High(Textures) do
2488 begin
2489 if not g_Map_IsSpecialTexture(Textures[a].TextureName) then
2490 begin
2491 if Textures[a].Anim then
2492 begin
2493 g_Frames_DeleteByID(Textures[a].FramesID)
2494 end
2495 else
2496 begin
2497 if (Textures[a].TextureID <> LongWord(TEXTURE_NONE)) then
2498 begin
2499 e_DeleteTexture(Textures[a].TextureID);
2500 end;
2501 end;
2502 end;
2503 end;
2504 Textures := nil;
2505 end;
2506 TextNameHash.Free();
2507 TextNameHash := nil;
2508 BadTextNameHash.Free();
2509 BadTextNameHash := nil;
2510 gCurrentMapFileName := '';
2511 gCurrentMap.Free();
2512 gCurrentMap := nil;
2513 end;
2515 panByGUID := nil;
2517 FreePanelArray(gWalls);
2518 FreePanelArray(gRenderBackgrounds);
2519 FreePanelArray(gRenderForegrounds);
2520 FreePanelArray(gWater);
2521 FreePanelArray(gAcid1);
2522 FreePanelArray(gAcid2);
2523 FreePanelArray(gSteps);
2524 FreePanelArray(gLifts);
2525 FreePanelArray(gBlockMon);
2526 gMovingWallIds := nil;
2528 if BackID <> DWORD(-1) then
2529 begin
2530 gBackSize.X := 0;
2531 gBackSize.Y := 0;
2532 e_DeleteTexture(BackID);
2533 BackID := DWORD(-1);
2534 end;
2536 g_Game_StopAllSounds(False);
2537 gMusic.FreeSound();
2538 g_Sound_Delete(gMapInfo.MusicName);
2540 gMapInfo.Name := '';
2541 gMapInfo.Description := '';
2542 gMapInfo.MusicName := '';
2543 gMapInfo.Height := 0;
2544 gMapInfo.Width := 0;
2546 gDoorMap := nil;
2547 gLiftMap := nil;
2548 end;
2550 procedure g_Map_Update();
2551 var
2552 a, d, j: Integer;
2553 m: Word;
2554 s: String;
2555 b: Byte;
2557 procedure UpdatePanelArray(var panels: TPanelArray);
2558 var
2559 i: Integer;
2561 begin
2562 for i := 0 to High(panels) do panels[i].Update();
2563 end;
2565 begin
2566 if g_dbgpan_mplat_step then g_dbgpan_mplat_active := true;
2568 UpdatePanelArray(gWalls);
2569 UpdatePanelArray(gRenderBackgrounds);
2570 UpdatePanelArray(gRenderForegrounds);
2571 UpdatePanelArray(gWater);
2572 UpdatePanelArray(gAcid1);
2573 UpdatePanelArray(gAcid2);
2574 UpdatePanelArray(gSteps);
2576 if g_dbgpan_mplat_step then begin g_dbgpan_mplat_step := false; g_dbgpan_mplat_active := false; end;
2578 if gGameSettings.GameMode = GM_CTF then
2579 begin
2580 for a := FLAG_RED to FLAG_BLUE do
2581 begin
2582 if not (gFlags[a].State in [FLAG_STATE_NONE, FLAG_STATE_CAPTURED]) then
2583 begin
2584 with gFlags[a] do
2585 begin
2586 if gFlags[a].Animation <> nil then gFlags[a].Animation.Update();
2588 m := g_Obj_Move(@Obj, True, True);
2590 if gTime mod (GAME_TICK*2) <> 0 then Continue;
2592 // Ñîïðîòèâëåíèå âîçäóõà
2593 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
2595 // Òàéìàóò ïîòåðÿííîãî ôëàãà, ëèáî îí âûïàë çà êàðòó
2596 if ((Count = 0) or ByteBool(m and MOVE_FALLOUT)) and g_Game_IsServer then
2597 begin
2598 g_Map_ResetFlag(a);
2599 gFlags[a].CaptureTime := 0;
2600 if a = FLAG_RED then
2601 s := _lc[I_PLAYER_FLAG_RED]
2602 else
2603 s := _lc[I_PLAYER_FLAG_BLUE];
2604 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
2606 if (((gPlayer1 <> nil) and (((gPlayer1.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer1.Team = TEAM_BLUE) and (a = FLAG_BLUE))))
2607 or ((gPlayer2 <> nil) and (((gPlayer2.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer2.Team = TEAM_BLUE) and (a = FLAG_BLUE))))) then
2608 b := 0
2609 else
2610 b := 1;
2612 if not sound_ret_flag[b].IsPlaying() then
2613 sound_ret_flag[b].Play();
2615 if g_Game_IsNet then
2616 MH_SEND_FlagEvent(FLAG_STATE_RETURNED, a, 0);
2617 Continue;
2618 end;
2620 if Count > 0 then Count -= 1;
2622 // Èãðîê áåðåò ôëàã
2623 if gPlayers <> nil then
2624 begin
2625 j := Random(Length(gPlayers)) - 1;
2626 for d := 0 to High(gPlayers) do
2627 begin
2628 Inc(j);
2629 if j > High(gPlayers) then j := 0;
2630 if gPlayers[j] <> nil then
2631 begin
2632 if gPlayers[j].alive and g_Obj_Collide(@Obj, @gPlayers[j].Obj) then
2633 begin
2634 if gPlayers[j].GetFlag(a) then Break;
2635 end;
2636 end;
2637 end;
2638 end;
2639 end;
2640 end;
2641 end;
2642 end;
2643 end;
2646 // old algo
2647 procedure g_Map_DrawPanels (PanelType: Word; hasAmbient: Boolean; constref ambColor: TDFColor);
2649 procedure DrawPanels (constref panels: TPanelArray; drawDoors: Boolean=False);
2650 var
2651 idx: Integer;
2652 begin
2653 if (panels <> nil) then
2654 begin
2655 // alas, no visible set
2656 for idx := 0 to High(panels) do
2657 begin
2658 if not (drawDoors xor panels[idx].Door) then panels[idx].Draw(hasAmbient, ambColor);
2659 end;
2660 end;
2661 end;
2663 begin
2664 case PanelType of
2665 PANEL_WALL: DrawPanels(gWalls);
2666 PANEL_CLOSEDOOR: DrawPanels(gWalls, True);
2667 PANEL_BACK: DrawPanels(gRenderBackgrounds);
2668 PANEL_FORE: DrawPanels(gRenderForegrounds);
2669 PANEL_WATER: DrawPanels(gWater);
2670 PANEL_ACID1: DrawPanels(gAcid1);
2671 PANEL_ACID2: DrawPanels(gAcid2);
2672 PANEL_STEP: DrawPanels(gSteps);
2673 end;
2674 end;
2677 // new algo
2678 procedure g_Map_CollectDrawPanels (x0, y0, wdt, hgt: Integer);
2679 var
2680 mwit: PPanel;
2681 it: TPanelGrid.Iter;
2682 begin
2683 dplClear();
2684 it := mapGrid.forEachInAABB(x0, y0, wdt, hgt, GridDrawableMask);
2685 for mwit in it do if (((mwit^.tag and GridTagDoor) <> 0) = mwit^.Door) then gDrawPanelList.insert(mwit^);
2686 it.release();
2687 // list will be rendered in `g_game.DrawPlayer()`
2688 end;
2691 procedure g_Map_DrawPanelShadowVolumes (lightX: Integer; lightY: Integer; radius: Integer);
2692 var
2693 mwit: PPanel;
2694 it: TPanelGrid.Iter;
2695 begin
2696 it := mapGrid.forEachInAABB(lightX-radius, lightY-radius, radius*2, radius*2, (GridTagWall or GridTagDoor));
2697 for mwit in it do mwit^.DrawShadowVolume(lightX, lightY, radius);
2698 it.release();
2699 end;
2702 procedure g_Map_DrawBack(dx, dy: Integer);
2703 begin
2704 if gDrawBackGround and (BackID <> DWORD(-1)) then
2705 e_DrawSize(BackID, dx, dy, 0, False, False, gBackSize.X, gBackSize.Y)
2706 else
2707 e_Clear(GL_COLOR_BUFFER_BIT, 0, 0, 0);
2708 end;
2710 function g_Map_CollidePanelOld(X, Y: Integer; Width, Height: Word;
2711 PanelType: Word; b1x3: Boolean=false): Boolean;
2712 var
2713 a, h: Integer;
2714 begin
2715 Result := False;
2717 if WordBool(PanelType and PANEL_WALL) then
2718 if gWalls <> nil then
2719 begin
2720 h := High(gWalls);
2722 for a := 0 to h do
2723 if gWalls[a].Enabled and
2724 g_Collide(X, Y, Width, Height,
2725 gWalls[a].X, gWalls[a].Y,
2726 gWalls[a].Width, gWalls[a].Height) then
2727 begin
2728 Result := True;
2729 Exit;
2730 end;
2731 end;
2733 if WordBool(PanelType and PANEL_WATER) then
2734 if gWater <> nil then
2735 begin
2736 h := High(gWater);
2738 for a := 0 to h do
2739 if g_Collide(X, Y, Width, Height,
2740 gWater[a].X, gWater[a].Y,
2741 gWater[a].Width, gWater[a].Height) then
2742 begin
2743 Result := True;
2744 Exit;
2745 end;
2746 end;
2748 if WordBool(PanelType and PANEL_ACID1) then
2749 if gAcid1 <> nil then
2750 begin
2751 h := High(gAcid1);
2753 for a := 0 to h do
2754 if g_Collide(X, Y, Width, Height,
2755 gAcid1[a].X, gAcid1[a].Y,
2756 gAcid1[a].Width, gAcid1[a].Height) then
2757 begin
2758 Result := True;
2759 Exit;
2760 end;
2761 end;
2763 if WordBool(PanelType and PANEL_ACID2) then
2764 if gAcid2 <> nil then
2765 begin
2766 h := High(gAcid2);
2768 for a := 0 to h do
2769 if g_Collide(X, Y, Width, Height,
2770 gAcid2[a].X, gAcid2[a].Y,
2771 gAcid2[a].Width, gAcid2[a].Height) then
2772 begin
2773 Result := True;
2774 Exit;
2775 end;
2776 end;
2778 if WordBool(PanelType and PANEL_STEP) then
2779 if gSteps <> nil then
2780 begin
2781 h := High(gSteps);
2783 for a := 0 to h do
2784 if g_Collide(X, Y, Width, Height,
2785 gSteps[a].X, gSteps[a].Y,
2786 gSteps[a].Width, gSteps[a].Height) then
2787 begin
2788 Result := True;
2789 Exit;
2790 end;
2791 end;
2793 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then
2794 if gLifts <> nil then
2795 begin
2796 h := High(gLifts);
2798 for a := 0 to h do
2799 if ((WordBool(PanelType and (PANEL_LIFTUP)) and (gLifts[a].LiftType = LIFTTYPE_UP)) or
2800 (WordBool(PanelType and (PANEL_LIFTDOWN)) and (gLifts[a].LiftType = LIFTTYPE_DOWN)) or
2801 (WordBool(PanelType and (PANEL_LIFTLEFT)) and (gLifts[a].LiftType = LIFTTYPE_LEFT)) or
2802 (WordBool(PanelType and (PANEL_LIFTRIGHT)) and (gLifts[a].LiftType = LIFTTYPE_RIGHT))) and
2803 g_Collide(X, Y, Width, Height,
2804 gLifts[a].X, gLifts[a].Y,
2805 gLifts[a].Width, gLifts[a].Height) then
2806 begin
2807 Result := True;
2808 Exit;
2809 end;
2810 end;
2812 if WordBool(PanelType and PANEL_BLOCKMON) then
2813 if gBlockMon <> nil then
2814 begin
2815 h := High(gBlockMon);
2817 for a := 0 to h do
2818 if ( (not b1x3) or
2819 ((gBlockMon[a].Width + gBlockMon[a].Height) >= 64) ) and
2820 g_Collide(X, Y, Width, Height,
2821 gBlockMon[a].X, gBlockMon[a].Y,
2822 gBlockMon[a].Width, gBlockMon[a].Height) then
2823 begin
2824 Result := True;
2825 Exit;
2826 end;
2827 end;
2828 end;
2830 function g_Map_CollideLiquid_TextureOld(X, Y: Integer; Width, Height: Word): DWORD;
2831 var
2832 texid: DWORD;
2834 function checkPanels (constref panels: TPanelArray): Boolean;
2835 var
2836 a: Integer;
2837 begin
2838 result := false;
2839 if panels = nil then exit;
2840 for a := 0 to High(panels) do
2841 begin
2842 if g_Collide(X, Y, Width, Height, panels[a].X, panels[a].Y, panels[a].Width, panels[a].Height) then
2843 begin
2844 result := true;
2845 texid := panels[a].GetTextureID();
2846 exit;
2847 end;
2848 end;
2849 end;
2851 begin
2852 texid := LongWord(TEXTURE_NONE);
2853 result := texid;
2854 if not checkPanels(gWater) then
2855 if not checkPanels(gAcid1) then
2856 if not checkPanels(gAcid2) then exit;
2857 result := texid;
2858 end;
2861 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word; PanelType: Word; b1x3: Boolean): Boolean;
2862 const
2863 SlowMask = GridTagLift or GridTagBlockMon;
2865 function checker (pan: TPanel; tag: Integer): Boolean;
2866 begin
2868 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
2869 begin
2870 result := pan.Enabled;
2871 exit;
2872 end;
2875 if ((tag and GridTagLift) <> 0) then
2876 begin
2877 result :=
2878 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2879 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2880 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2881 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2882 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2883 exit;
2884 end;
2886 if ((tag and GridTagBlockMon) <> 0) then
2887 begin
2888 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2889 exit;
2890 end;
2892 // other shit
2893 //result := g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2894 result := true; // i found her!
2895 end;
2897 var
2898 tagmask: Integer = 0;
2899 mwit: PPanel;
2900 it: TPanelGrid.Iter;
2901 pan: TPanel;
2902 begin
2903 result := false;
2904 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
2905 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
2906 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
2907 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
2908 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
2909 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
2910 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
2912 if (tagmask = 0) then exit; // just in case
2914 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('*solids');
2915 if gdbg_map_use_accel_coldet then
2916 begin
2917 if ((tagmask and SlowMask) <> 0) then
2918 begin
2919 // slow
2920 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask);
2921 for mwit in it do
2922 begin
2923 pan := mwit^;
2924 if ((pan.tag and GridTagLift) <> 0) then
2925 begin
2926 result :=
2927 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2928 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2929 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2930 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2931 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2932 end
2933 else if ((pan.tag and GridTagBlockMon) <> 0) then
2934 begin
2935 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2936 end
2937 else
2938 begin
2939 // other shit
2940 result := true; // i found her!
2941 end;
2942 if (result) then break;
2943 end;
2944 end
2945 else
2946 begin
2947 // fast
2948 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask, false, true); // return first hit
2949 result := (it.length > 0);
2950 end;
2951 it.release();
2952 end
2953 else
2954 begin
2955 result := g_Map_CollidePanelOld(X, Y, Width, Height, PanelType, b1x3);
2956 end;
2957 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2958 end;
2961 // returns `true` if we need to stop
2962 function liquidChecker (pan: TPanel; var texid: DWORD; var cctype: Integer): Boolean; inline;
2963 begin
2964 result := false;
2965 //if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2)) = 0) then exit;
2966 // check priorities
2967 case cctype of
2968 0: if ((pan.tag and GridTagWater) = 0) then exit; // allowed: water
2969 1: if ((pan.tag and (GridTagWater or GridTagAcid1)) = 0) then exit; // allowed: water, acid1
2970 //2: if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2) = 0) then exit; // allowed: water, acid1, acid2
2971 end;
2972 // collision?
2973 //if not g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height) then exit;
2974 // yeah
2975 texid := pan.GetTextureID();
2976 // water? water has the highest priority, so stop right here
2977 if ((pan.tag and GridTagWater) <> 0) then begin cctype := 0; result := true; exit; end;
2978 // acid2?
2979 if ((pan.tag and GridTagAcid2) <> 0) then cctype := 2;
2980 // acid1?
2981 if ((pan.tag and GridTagAcid1) <> 0) then cctype := 1;
2982 end;
2984 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
2985 var
2986 cctype: Integer = 3; // priority: 0: water was hit, 1: acid1 was hit, 2: acid2 was hit; 3: nothing was hit
2987 mwit: PPanel;
2988 it: TPanelGrid.Iter;
2989 begin
2990 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('liquids');
2991 if gdbg_map_use_accel_coldet then
2992 begin
2993 result := LongWord(TEXTURE_NONE);
2994 it := mapGrid.forEachInAABB(X, Y, Width, Height, (GridTagWater or GridTagAcid1 or GridTagAcid2));
2995 for mwit in it do if (liquidChecker(mwit^, result, cctype)) then break;
2996 it.release();
2997 end
2998 else
2999 begin
3000 result := g_Map_CollideLiquid_TextureOld(X, Y, Width, Height);
3001 end;
3002 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
3003 end;
3006 procedure g_Map_EnableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_EnableWallGUID(gWalls[ID].guid); end;
3007 procedure g_Map_DisableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_DisableWallGUID(gWalls[ID].guid); end;
3008 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer); begin if (ID < Length(gLifts)) then g_Map_SetLiftGUID(gLifts[ID].guid, t); end;
3011 procedure g_Map_EnableWallGUID (pguid: Integer);
3012 var
3013 pan: TPanel;
3014 begin
3015 //pan := gWalls[ID];
3016 pan := g_Map_PanelByGUID(pguid);
3017 if (pan = nil) then exit;
3018 if pan.Enabled and mapGrid.proxyEnabled[pan.proxyId] then exit;
3020 pan.Enabled := True;
3021 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, true);
3023 mapGrid.proxyEnabled[pan.proxyId] := true;
3024 //if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := true
3025 //else pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, GridTagDoor);
3027 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3028 // mark platform as interesting
3029 pan.setDirty();
3031 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
3032 //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);
3033 {$ENDIF}
3034 end;
3037 procedure g_Map_DisableWallGUID (pguid: Integer);
3038 var
3039 pan: TPanel;
3040 begin
3041 //pan := gWalls[ID];
3042 pan := g_Map_PanelByGUID(pguid);
3043 if (pan = nil) then exit;
3044 if (not pan.Enabled) and (not mapGrid.proxyEnabled[pan.proxyId]) then exit;
3046 pan.Enabled := False;
3047 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, false);
3049 mapGrid.proxyEnabled[pan.proxyId] := false;
3050 //if (pan.proxyId >= 0) then begin mapGrid.removeBody(pan.proxyId); pan.proxyId := -1; end;
3052 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3053 // mark platform as interesting
3054 pan.setDirty();
3056 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
3057 //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);
3058 {$ENDIF}
3059 end;
3062 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
3063 var
3064 tp: TPanel;
3065 begin
3066 tp := g_Map_PanelByGUID(pguid);
3067 if (tp = nil) then exit;
3068 tp.NextTexture(AnimLoop);
3069 if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelTexture(pguid, AnimLoop);
3070 end;
3073 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
3074 var
3075 pan: TPanel;
3076 begin
3077 //pan := gLifts[ID];
3078 pan := g_Map_PanelByGUID(pguid);
3079 if (pan = nil) then exit;
3080 if not pan.isGLift then exit;
3082 if ({gLifts[ID]}pan.LiftType = t) then exit; //!FIXME!TRIGANY!
3084 with {gLifts[ID]} pan do
3085 begin
3086 LiftType := t;
3088 g_Mark(X, Y, Width, Height, MARK_LIFT, false);
3089 //TODO: make separate lift tags, and change tag here
3091 case LiftType of
3092 LIFTTYPE_UP: g_Mark(X, Y, Width, Height, MARK_LIFTUP);
3093 LIFTTYPE_DOWN: g_Mark(X, Y, Width, Height, MARK_LIFTDOWN);
3094 LIFTTYPE_LEFT: g_Mark(X, Y, Width, Height, MARK_LIFTLEFT);
3095 LIFTTYPE_RIGHT: g_Mark(X, Y, Width, Height, MARK_LIFTRIGHT);
3096 end;
3098 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3099 // mark platform as interesting
3100 pan.setDirty();
3101 end;
3102 end;
3105 function g_Map_GetPoint (PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
3106 var
3107 a: Integer;
3108 PointsArray: Array of TRespawnPoint;
3109 begin
3110 Result := False;
3111 SetLength(PointsArray, 0);
3113 if RespawnPoints = nil then
3114 Exit;
3116 for a := 0 to High(RespawnPoints) do
3117 if RespawnPoints[a].PointType = PointType then
3118 begin
3119 SetLength(PointsArray, Length(PointsArray)+1);
3120 PointsArray[High(PointsArray)] := RespawnPoints[a];
3121 end;
3123 if PointsArray = nil then
3124 Exit;
3126 RespawnPoint := PointsArray[Random(Length(PointsArray))];
3127 Result := True;
3128 end;
3130 function g_Map_GetPointCount(PointType: Byte): Word;
3131 var
3132 a: Integer;
3133 begin
3134 Result := 0;
3136 if RespawnPoints = nil then
3137 Exit;
3139 for a := 0 to High(RespawnPoints) do
3140 if RespawnPoints[a].PointType = PointType then
3141 Result := Result + 1;
3142 end;
3144 function g_Map_HaveFlagPoints(): Boolean;
3145 begin
3146 Result := (FlagPoints[FLAG_RED] <> nil) and (FlagPoints[FLAG_BLUE] <> nil);
3147 end;
3149 procedure g_Map_ResetFlag(Flag: Byte);
3150 begin
3151 with gFlags[Flag] do
3152 begin
3153 Obj.X := -1000;
3154 Obj.Y := -1000;
3155 Obj.Vel.X := 0;
3156 Obj.Vel.Y := 0;
3157 Direction := TDirection.D_LEFT;
3158 State := FLAG_STATE_NONE;
3159 if FlagPoints[Flag] <> nil then
3160 begin
3161 Obj.X := FlagPoints[Flag]^.X;
3162 Obj.Y := FlagPoints[Flag]^.Y;
3163 Direction := FlagPoints[Flag]^.Direction;
3164 State := FLAG_STATE_NORMAL;
3165 end;
3166 Count := -1;
3167 end;
3168 end;
3170 procedure g_Map_DrawFlags();
3171 var
3172 i, dx: Integer;
3173 Mirror: TMirrorType;
3174 begin
3175 if gGameSettings.GameMode <> GM_CTF then
3176 Exit;
3178 for i := FLAG_RED to FLAG_BLUE do
3179 with gFlags[i] do
3180 if State <> FLAG_STATE_CAPTURED then
3181 begin
3182 if State = FLAG_STATE_NONE then
3183 continue;
3185 if Direction = TDirection.D_LEFT then
3186 begin
3187 Mirror := TMirrorType.Horizontal;
3188 dx := -1;
3189 end
3190 else
3191 begin
3192 Mirror := TMirrorType.None;
3193 dx := 1;
3194 end;
3196 Animation.Draw(Obj.X+dx, Obj.Y+1, Mirror);
3198 if g_debug_Frames then
3199 begin
3200 e_DrawQuad(Obj.X+Obj.Rect.X,
3201 Obj.Y+Obj.Rect.Y,
3202 Obj.X+Obj.Rect.X+Obj.Rect.Width-1,
3203 Obj.Y+Obj.Rect.Y+Obj.Rect.Height-1,
3204 0, 255, 0);
3205 end;
3206 end;
3207 end;
3210 procedure g_Map_SaveState (st: TStream);
3211 var
3212 str: String;
3214 procedure savePanels ();
3215 var
3216 pan: TPanel;
3217 begin
3218 // Ñîõðàíÿåì ïàíåëè
3219 utils.writeInt(st, LongInt(Length(panByGUID)));
3220 for pan in panByGUID do pan.SaveState(st);
3221 end;
3223 procedure saveFlag (flag: PFlag);
3224 var
3225 b: Byte;
3226 begin
3227 utils.writeSign(st, 'FLAG');
3228 utils.writeInt(st, Byte(0)); // version
3229 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3230 utils.writeInt(st, Byte(flag^.RespawnType));
3231 // Ñîñòîÿíèå ôëàãà
3232 utils.writeInt(st, Byte(flag^.State));
3233 // Íàïðàâëåíèå ôëàãà
3234 if flag^.Direction = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
3235 utils.writeInt(st, Byte(b));
3236 // Îáúåêò ôëàãà
3237 Obj_SaveState(st, @flag^.Obj);
3238 end;
3240 begin
3241 savePanels();
3243 // Ñîõðàíÿåì ìóçûêó
3244 utils.writeSign(st, 'MUSI');
3245 utils.writeInt(st, Byte(0));
3246 // Íàçâàíèå ìóçûêè
3247 assert(gMusic <> nil, 'g_Map_SaveState: gMusic = nil');
3248 if gMusic.NoMusic then str := '' else str := gMusic.Name;
3249 utils.writeStr(st, str);
3250 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3251 utils.writeInt(st, LongWord(gMusic.GetPosition()));
3252 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3253 utils.writeBool(st, gMusic.SpecPause);
3255 ///// Ñîõðàíÿåì êîëè÷åñòâî ìîíñòðîâ: /////
3256 utils.writeInt(st, LongInt(gTotalMonsters));
3257 ///// /////
3259 //// Ñîõðàíÿåì ôëàãè, åñëè ýòî CTF: /////
3260 if (gGameSettings.GameMode = GM_CTF) then
3261 begin
3262 // Ôëàã Êðàñíîé êîìàíäû
3263 saveFlag(@gFlags[FLAG_RED]);
3264 // Ôëàã Ñèíåé êîìàíäû
3265 saveFlag(@gFlags[FLAG_BLUE]);
3266 end;
3267 ///// /////
3269 ///// Ñîõðàíÿåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3270 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3271 begin
3272 // Î÷êè Êðàñíîé êîìàíäû
3273 utils.writeInt(st, SmallInt(gTeamStat[TEAM_RED].Goals));
3274 // Î÷êè Ñèíåé êîìàíäû
3275 utils.writeInt(st, SmallInt(gTeamStat[TEAM_BLUE].Goals));
3276 end;
3277 ///// /////
3278 end;
3281 procedure g_Map_LoadState (st: TStream);
3282 var
3283 dw: DWORD;
3284 str: String;
3285 boo: Boolean;
3287 procedure loadPanels ();
3288 var
3289 pan: TPanel;
3290 begin
3291 // Çàãðóæàåì ïàíåëè
3292 if (Length(panByGUID) <> utils.readLongInt(st)) then raise XStreamError.Create('invalid number of saved panels');
3293 for pan in panByGUID do
3294 begin
3295 pan.LoadState(st);
3296 if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
3297 end;
3298 end;
3300 procedure loadFlag (flag: PFlag);
3301 var
3302 b: Byte;
3303 begin
3304 // Ñèãíàòóðà ôëàãà
3305 if not utils.checkSign(st, 'FLAG') then raise XStreamError.Create('invalid flag signature');
3306 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid flag version');
3307 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3308 flag^.RespawnType := utils.readByte(st);
3309 // Ñîñòîÿíèå ôëàãà
3310 flag^.State := utils.readByte(st);
3311 // Íàïðàâëåíèå ôëàãà
3312 b := utils.readByte(st);
3313 if (b = 1) then flag^.Direction := TDirection.D_LEFT else flag^.Direction := TDirection.D_RIGHT; // b = 2
3314 // Îáúåêò ôëàãà
3315 Obj_LoadState(@flag^.Obj, st);
3316 end;
3318 begin
3319 if (st = nil) then exit;
3321 ///// Çàãðóæàåì ñïèñêè ïàíåëåé: /////
3322 loadPanels();
3323 ///// /////
3325 // Îáíîâëÿåì êàðòó ñòîëêíîâåíèé è ñåòêó
3326 g_GFX_Init();
3327 //mapCreateGrid();
3329 ///// Çàãðóæàåì ìóçûêó: /////
3330 if not utils.checkSign(st, 'MUSI') then raise XStreamError.Create('invalid music signature');
3331 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid music version');
3332 // Íàçâàíèå ìóçûêè
3333 assert(gMusic <> nil, 'g_Map_LoadState: gMusic = nil');
3334 str := utils.readStr(st);
3335 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3336 dw := utils.readLongWord(st);
3337 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3338 boo := utils.readBool(st);
3339 // Çàïóñêàåì ýòó ìóçûêó
3340 gMusic.SetByName(str);
3341 gMusic.SpecPause := boo;
3342 gMusic.Play();
3343 gMusic.Pause(true);
3344 gMusic.SetPosition(dw);
3345 ///// /////
3347 ///// Çàãðóæàåì êîëè÷åñòâî ìîíñòðîâ: /////
3348 gTotalMonsters := utils.readLongInt(st);
3349 ///// /////
3351 //// Çàãðóæàåì ôëàãè, åñëè ýòî CTF: /////
3352 if (gGameSettings.GameMode = GM_CTF) then
3353 begin
3354 // Ôëàã Êðàñíîé êîìàíäû
3355 loadFlag(@gFlags[FLAG_RED]);
3356 // Ôëàã Ñèíåé êîìàíäû
3357 loadFlag(@gFlags[FLAG_BLUE]);
3358 end;
3359 ///// /////
3361 ///// Çàãðóæàåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3362 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3363 begin
3364 // Î÷êè Êðàñíîé êîìàíäû
3365 gTeamStat[TEAM_RED].Goals := utils.readSmallInt(st);
3366 // Î÷êè Ñèíåé êîìàíäû
3367 gTeamStat[TEAM_BLUE].Goals := utils.readSmallInt(st);
3368 end;
3369 ///// /////
3370 end;
3373 // trace liquid, stepping by `dx` and `dy`
3374 // return last seen liquid coords, and `false` if we're started outside of the liquid
3375 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
3376 const
3377 MaskLiquid = GridTagWater or GridTagAcid1 or GridTagAcid2;
3378 begin
3379 topx := x;
3380 topy := y;
3381 // started outside of the liquid?
3382 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then begin result := false; exit; end;
3383 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then begin result := false; exit; end;
3384 if (dx = 0) and (dy = 0) then begin result := false; exit; end; // sanity check
3385 result := true;
3386 while true do
3387 begin
3388 Inc(x, dx);
3389 Inc(y, dy);
3390 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then exit; // out of the water, just exit
3391 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then exit; // out of the water, just exit
3392 topx := x;
3393 topy := y;
3394 end;
3395 end;
3398 begin
3399 DynWarningCB := mapWarningCB;
3400 end.