DEADSOFTWARE

Game: Use proper syntax of sets for game options instead of raw bitwise operations
[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 NeedSend: Boolean;
58 end;
60 function g_Map_Load(Res: String): Boolean;
61 function g_Map_GetMapInfo(Res: String): TMapInfo;
62 function g_Map_GetMapsList(WADName: String): SSArray;
63 function g_Map_Exist(Res: String): Boolean;
64 procedure g_Map_Free(freeTextures: Boolean=true);
65 procedure g_Map_Update();
67 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
69 procedure g_Map_DrawPanels (PanelType: Word; hasAmbient: Boolean; constref ambColor: TDFColor); // unaccelerated
70 procedure g_Map_CollectDrawPanels (x0, y0, wdt, hgt: Integer);
72 procedure g_Map_DrawBack(dx, dy: Integer);
73 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word;
74 PanelType: Word; b1x3: Boolean=false): Boolean;
75 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
77 procedure g_Map_EnableWallGUID (pguid: Integer);
78 procedure g_Map_DisableWallGUID (pguid: Integer);
79 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
81 // HACK!!!
82 procedure g_Map_EnableWall_XXX (ID: DWORD);
83 procedure g_Map_DisableWall_XXX (ID: DWORD);
84 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer);
86 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
88 procedure g_Map_ReAdd_DieTriggers();
89 function g_Map_IsSpecialTexture(Texture: String): Boolean;
91 function g_Map_GetPoint(PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
92 function g_Map_GetPointCount(PointType: Byte): Word;
93 function g_Map_GetRandomPointType(): Byte;
95 function g_Map_HaveFlagPoints(): Boolean;
97 procedure g_Map_ResetFlag(Flag: Byte);
98 procedure g_Map_DrawFlags();
100 procedure g_Map_SaveState (st: TStream);
101 procedure g_Map_LoadState (st: TStream);
103 procedure g_Map_DrawPanelShadowVolumes(lightX: Integer; lightY: Integer; radius: Integer);
105 // returns panel or nil
106 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
107 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
109 // returns panel or nil
110 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
111 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
113 type
114 TForEachPanelCB = function (pan: TPanel): Boolean is nested; // return `true` to stop
116 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
117 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
119 // trace liquid, stepping by `dx` and `dy`
120 // return last seen liquid coords, and `false` if we're started outside of the liquid
121 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
124 // return `true` from `cb` to stop
125 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
127 procedure g_Map_NetSendInterestingPanels (); // yay!
130 procedure g_Map_ProfilersBegin ();
131 procedure g_Map_ProfilersEnd ();
134 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
137 function g_Map_MinX (): Integer; inline;
138 function g_Map_MinY (): Integer; inline;
139 function g_Map_MaxX (): Integer; inline;
140 function g_Map_MaxY (): Integer; inline;
142 const
143 NNF_NO_NAME = 0;
144 NNF_NAME_BEFORE = 1;
145 NNF_NAME_EQUALS = 2;
146 NNF_NAME_AFTER = 3;
148 function g_Texture_NumNameFindStart(name: String): Boolean;
149 function g_Texture_NumNameFindNext(var newName: String): Byte;
151 const
152 RESPAWNPOINT_PLAYER1 = 1;
153 RESPAWNPOINT_PLAYER2 = 2;
154 RESPAWNPOINT_DM = 3;
155 RESPAWNPOINT_RED = 4;
156 RESPAWNPOINT_BLUE = 5;
158 FLAG_NONE = 0;
159 FLAG_RED = 1;
160 FLAG_BLUE = 2;
161 FLAG_DOM = 3;
163 FLAG_STATE_NONE = 0;
164 FLAG_STATE_NORMAL = 1;
165 FLAG_STATE_DROPPED = 2;
166 FLAG_STATE_CAPTURED = 3;
167 FLAG_STATE_SCORED = 4; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
168 FLAG_STATE_RETURNED = 5; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
170 FLAG_TIME = 720; // 20 seconds
172 SKY_STRETCH: Single = 1.5;
174 const
175 GridTagInvalid = 0;
177 (* draw order:
178 PANEL_BACK
179 PANEL_STEP
180 PANEL_WALL
181 PANEL_CLOSEDOOR
182 PANEL_ACID1
183 PANEL_ACID2
184 PANEL_WATER
185 PANEL_FORE
186 *)
187 // sorted by draw priority
188 GridTagBack = 1 shl 0; // gRenderBackgrounds
189 GridTagStep = 1 shl 1; // gSteps
190 GridTagWall = 1 shl 2; // gWalls
191 GridTagDoor = 1 shl 3; // gWalls
192 GridTagAcid1 = 1 shl 4; // gAcid1
193 GridTagAcid2 = 1 shl 5; // gAcid2
194 GridTagWater = 1 shl 6; // gWater
195 GridTagFore = 1 shl 7; // gRenderForegrounds
196 // the following are invisible
197 GridTagLift = 1 shl 8; // gLifts
198 GridTagBlockMon = 1 shl 9; // gBlockMon
200 GridTagSolid = (GridTagWall or GridTagDoor);
201 GridTagObstacle = (GridTagStep or GridTagWall or GridTagDoor);
202 GridTagLiquid = (GridTagAcid1 or GridTagAcid2 or GridTagWater);
204 GridDrawableMask = (GridTagBack or GridTagStep or GridTagWall or GridTagDoor or GridTagAcid1 or GridTagAcid2 or GridTagWater or GridTagFore);
207 type
208 TBinHeapPanelDrawCmp = class
209 public
210 class function less (const a, b: TPanel): Boolean; inline;
211 end;
213 TBinHeapPanelDraw = specialize TBinaryHeapBase<TPanel, TBinHeapPanelDrawCmp>;
215 var
216 gWalls: TPanelArray;
217 gRenderBackgrounds: TPanelArray;
218 gRenderForegrounds: TPanelArray;
219 gWater, gAcid1, gAcid2: TPanelArray;
220 gSteps: TPanelArray;
221 gLifts: TPanelArray;
222 gBlockMon: TPanelArray;
223 gFlags: array [FLAG_RED..FLAG_BLUE] of TFlag;
224 //gDOMFlags: array of TFlag;
225 gMapInfo: TMapInfo;
226 gBackSize: TDFPoint;
227 gDoorMap: array of array of DWORD;
228 gLiftMap: array of array of DWORD;
229 gWADHash: TMD5Digest;
230 BackID: DWORD = DWORD(-1);
231 gExternalResources: array of TDiskFileInfo = nil;
232 gMovingWallIds: array of Integer = nil;
234 gdbg_map_use_accel_render: Boolean = true;
235 gdbg_map_use_accel_coldet: Boolean = true;
236 profMapCollision: TProfiler = nil; //WARNING: FOR DEBUGGING ONLY!
237 gDrawPanelList: TBinHeapPanelDraw = nil; // binary heap of all walls we have to render, populated by `g_Map_CollectDrawPanels()`
239 gCurrentMap: TDynRecord = nil;
240 gCurrentMapFileName: AnsiString = ''; // so we can skip texture reloading
241 gTestMap: String = '';
244 function panelTypeToTag (panelType: Word): Integer; // returns GridTagXXX
247 type
248 TPanelGrid = specialize TBodyGridBase<TPanel>;
250 var
251 mapGrid: TPanelGrid = nil; // DO NOT USE! public for debugging only!
254 implementation
256 uses
257 {$INCLUDE ../nogl/noGLuses.inc}
258 e_input, g_main, e_log, e_texture, e_res, g_items, g_gfx, g_console,
259 g_weapons, g_game, g_sound, e_sound, CONFIG,
260 g_options, g_triggers, g_player,
261 Math, g_monsters, g_saveload, g_language, g_netmsg,
262 sfs, xstreams, hashtable, wadreader,
263 ImagingTypes, Imaging, ImagingUtility,
264 ImagingGif, ImagingNetworkGraphics,
265 g_res_downloader;
267 const
268 FLAGRECT: TRectWH = (X:15; Y:12; Width:33; Height:52);
269 MUSIC_SIGNATURE = $4953554D; // 'MUSI'
270 FLAG_SIGNATURE = $47414C46; // 'FLAG'
273 // ////////////////////////////////////////////////////////////////////////// //
274 procedure mapWarningCB (const msg: AnsiString; line, col: Integer);
275 begin
276 if (line > 0) then
277 begin
278 e_LogWritefln('parse error at (%s,%s): %s', [line, col, msg], TMsgType.Warning);
279 end
280 else
281 begin
282 e_LogWritefln('parse error: %s', [msg], TMsgType.Warning);
283 end;
284 end;
287 // ////////////////////////////////////////////////////////////////////////// //
288 var
289 panByGUID: array of TPanel = nil;
292 // ////////////////////////////////////////////////////////////////////////// //
293 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
294 begin
295 //if (panByGUID = nil) or (not panByGUID.get(aguid, result)) then result := nil;
296 if (aguid >= 0) and (aguid < Length(panByGUID)) then result := panByGUID[aguid] else result := nil;
297 end;
300 // return `true` from `cb` to stop
301 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
302 var
303 pan: TPanel;
304 begin
305 result := nil;
306 if not assigned(cb) then exit;
307 for pan in panByGUID do
308 begin
309 if cb(pan) then begin result := pan; exit; end;
310 end;
311 end;
314 procedure g_Map_NetSendInterestingPanels ();
315 var
316 pan: TPanel;
317 begin
318 if g_Game_IsServer and g_Game_IsNet then
319 begin
320 for pan in panByGUID do
321 begin
322 if pan.gncNeedSend then MH_SEND_PanelState(pan.guid);
323 end;
324 end;
325 end;
328 // ////////////////////////////////////////////////////////////////////////// //
329 function g_Map_MinX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0 else result := 0; end;
330 function g_Map_MinY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0 else result := 0; end;
331 function g_Map_MaxX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0+mapGrid.gridWidth-1 else result := 0; end;
332 function g_Map_MaxY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0+mapGrid.gridHeight-1 else result := 0; end;
335 // ////////////////////////////////////////////////////////////////////////// //
336 var
337 dfmapdef: TDynMapDef = nil;
340 procedure loadMapDefinition ();
341 var
342 pr: TTextParser = nil;
343 st: TStream = nil;
344 WAD: TWADFile = nil;
345 begin
346 if (dfmapdef <> nil) then exit;
348 try
349 e_LogWritefln('parsing "mapdef.txt"...', []);
350 st := e_OpenResourceRO(DataDirs, 'mapdef.txt');
351 e_LogWritefln('found local "mapdef.txt"', []);
352 except
353 st := nil;
354 end;
356 if (st = nil) then
357 begin
358 WAD := TWADFile.Create();
359 if not WAD.ReadFile(GameWAD) then
360 begin
361 //raise Exception.Create('cannot load "game.wad"');
362 st := nil;
363 end
364 else
365 begin
366 st := WAD.openFileStream('mapdef.txt');
367 end;
368 end;
370 try
371 if (st = nil) then
372 begin
373 //raise Exception.Create('cannot open "mapdef.txt"');
374 e_LogWriteln('using default "mapdef.txt"...');
375 pr := TStrTextParser.Create(defaultMapDef);
376 end
377 else
378 begin
379 pr := TFileTextParser.Create(st);
380 end;
381 except on e: Exception do
382 begin
383 e_LogWritefln('something is VERY wrong here! -- ', [e.message]);
384 raise;
385 end;
386 end;
388 try
389 dfmapdef := TDynMapDef.Create(pr);
390 except
391 on e: TDynParseException do
392 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
393 on e: Exception do
394 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [pr.tokLine, pr.tokCol, e.message]);
395 end;
397 st.Free();
398 WAD.Free();
399 end;
402 // ////////////////////////////////////////////////////////////////////////// //
403 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
404 var
405 wst: TSFSMemoryChunkStream = nil;
406 begin
407 result := nil;
408 if (dataLen < 4) then exit;
410 if (dfmapdef = nil) then writeln('need to load mapdef');
411 loadMapDefinition();
412 if (dfmapdef = nil) then raise Exception.Create('internal map loader error');
414 wst := TSFSMemoryChunkStream.Create(data, dataLen);
415 try
416 result := dfmapdef.parseMap(wst);
417 except
418 on e: TDynParseException do
419 begin
420 e_LogWritefln('ERROR at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
421 wst.Free();
422 result := nil;
423 exit;
424 end;
425 on e: Exception do
426 begin
427 e_LogWritefln('ERROR: %s', [e.message]);
428 wst.Free();
429 result := nil;
430 exit;
431 end;
432 end;
434 //e_LogWriteln('map parsed.');
435 end;
438 // ////////////////////////////////////////////////////////////////////////// //
439 var
440 NNF_PureName: String; // Èìÿ òåêñòóðû áåç öèôð â êîíöå
441 NNF_PureExt: String; // extension postfix
442 NNF_FirstNum: Integer; // ×èñëî ó íà÷àëüíîé òåêñòóðû
443 NNF_CurrentNum: Integer; // Ñëåäóþùåå ÷èñëî ó òåêñòóðû
446 function g_Texture_NumNameFindStart(name: String): Boolean;
447 var
448 i, j: Integer;
450 begin
451 Result := False;
452 NNF_PureName := '';
453 NNF_PureExt := '';
454 NNF_FirstNum := -1;
455 NNF_CurrentNum := -1;
457 for i := Length(name) downto 1 do
458 if (name[i] = '_') then // "_" - ñèìâîë íà÷àëà íîìåðíîãî ïîñòôèêñà
459 begin
460 if i = Length(name) then
461 begin // Íåò öèôð â êîíöå ñòðîêè
462 Exit;
463 end
464 else
465 begin
466 j := i + 1;
467 while (j <= Length(name)) and (name[j] <> '.') do inc(j);
468 NNF_PureName := Copy(name, 1, i);
469 NNF_PureExt := Copy(name, j);
470 name := Copy(name, i + 1, j - i - 1);
471 Break;
472 end;
473 end;
475 // Íå ïåðåâåñòè â ÷èñëî:
476 if not TryStrToInt(name, NNF_FirstNum) then
477 Exit;
479 NNF_CurrentNum := 0;
481 Result := True;
482 end;
485 function g_Texture_NumNameFindNext(var newName: String): Byte;
486 begin
487 if (NNF_PureName = '') or (NNF_CurrentNum < 0) then
488 begin
489 newName := '';
490 Result := NNF_NO_NAME;
491 Exit;
492 end;
494 newName := NNF_PureName + IntToStr(NNF_CurrentNum) + NNF_PureExt;
496 if NNF_CurrentNum < NNF_FirstNum then
497 Result := NNF_NAME_BEFORE
498 else
499 if NNF_CurrentNum > NNF_FirstNum then
500 Result := NNF_NAME_AFTER
501 else
502 Result := NNF_NAME_EQUALS;
504 Inc(NNF_CurrentNum);
505 end;
508 // ////////////////////////////////////////////////////////////////////////// //
509 function panelTypeToTag (panelType: Word): Integer;
510 begin
511 case panelType of
512 PANEL_WALL: result := GridTagWall; // gWalls
513 PANEL_OPENDOOR, PANEL_CLOSEDOOR: result := GridTagDoor; // gWalls
514 PANEL_BACK: result := GridTagBack; // gRenderBackgrounds
515 PANEL_FORE: result := GridTagFore; // gRenderForegrounds
516 PANEL_WATER: result := GridTagWater; // gWater
517 PANEL_ACID1: result := GridTagAcid1; // gAcid1
518 PANEL_ACID2: result := GridTagAcid2; // gAcid2
519 PANEL_STEP: result := GridTagStep; // gSteps
520 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: result := GridTagLift; // gLifts -- this is for all lifts
521 PANEL_BLOCKMON: result := GridTagBlockMon; // gBlockMon -- this is for all blockmons
522 else result := GridTagInvalid;
523 end;
524 end;
527 class function TBinHeapPanelDrawCmp.less (const a, b: TPanel): Boolean; inline;
528 begin
529 if (a.tag < b.tag) then begin result := true; exit; end;
530 if (a.tag > b.tag) then begin result := false; exit; end;
531 result := (a.arrIdx < b.arrIdx);
532 end;
534 procedure dplClear ();
535 begin
536 if (gDrawPanelList = nil) then gDrawPanelList := TBinHeapPanelDraw.Create() else gDrawPanelList.clear();
537 end;
540 var
541 Textures: TLevelTextureArray = nil;
542 TextNameHash: THashStrInt = nil; // key: texture name; value: index in `Textures`
543 BadTextNameHash: THashStrInt = nil; // set; so we won't spam with non-existing texture messages
544 RespawnPoints: array of TRespawnPoint;
545 FlagPoints: array[FLAG_RED..FLAG_BLUE] of PFlagPoint;
546 //DOMFlagPoints: Array of TFlagPoint;
549 procedure g_Map_ProfilersBegin ();
550 begin
551 if (profMapCollision = nil) then profMapCollision := TProfiler.Create('COLSOLID', g_profile_history_size);
552 if (profMapCollision <> nil) then profMapCollision.mainBegin(g_profile_collision);
553 // create sections
554 if g_profile_collision and (profMapCollision <> nil) then
555 begin
556 profMapCollision.sectionBegin('*solids');
557 profMapCollision.sectionEnd();
558 profMapCollision.sectionBegin('liquids');
559 profMapCollision.sectionEnd();
560 end;
561 end;
563 procedure g_Map_ProfilersEnd ();
564 begin
565 if (profMapCollision <> nil) then profMapCollision.mainEnd();
566 end;
569 // wall index in `gWalls` or -1
570 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
571 var
572 ex, ey: Integer;
573 begin
574 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, (GridTagWall or GridTagDoor));
575 if (result <> nil) then
576 begin
577 if (hitx <> nil) then hitx^ := ex;
578 if (hity <> nil) then hity^ := ey;
579 end
580 else
581 begin
582 if (hitx <> nil) then hitx^ := x1;
583 if (hity <> nil) then hity^ := y1;
584 end;
585 end;
587 // returns panel or nil
588 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
589 var
590 ex, ey: Integer;
591 begin
592 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, tag);
593 if (result <> nil) then
594 begin
595 if (hitx <> nil) then hitx^ := ex;
596 if (hity <> nil) then hity^ := ey;
597 end
598 else
599 begin
600 if (hitx <> nil) then hitx^ := x1;
601 if (hity <> nil) then hity^ := y1;
602 end;
603 end;
606 function xxPanAtPointChecker (pan: TPanel; panelType: Word): Boolean; inline;
607 begin
608 if ((pan.tag and GridTagLift) <> 0) then
609 begin
610 // stop if the lift of the right type
611 result :=
612 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
613 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
614 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
615 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT)));
616 exit;
617 end;
618 result := true; // otherwise, stop anyway, 'cause `forEachAtPoint()` is guaranteed to call this only for correct panels
619 end;
621 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
622 var
623 tagmask: Integer = 0;
624 mwit: PPanel;
625 it: TPanelGrid.Iter;
626 begin
627 result := false;
629 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
630 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
631 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
632 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
633 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
634 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
635 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
637 if (tagmask = 0) then exit;// just in case
639 if ((tagmask and GridTagLift) <> 0) then
640 begin
641 // slow
642 it := mapGrid.forEachAtPoint(x, y, tagmask);
643 for mwit in it do if (xxPanAtPointChecker(mwit^, PanelType)) then begin result := true; break; end;
644 end
645 else
646 begin
647 // fast
648 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true);
649 result := (it.length <> 0); // firsthit
650 end;
651 it.release();
652 end;
655 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
656 var
657 it: TPanelGrid.Iter;
658 begin
659 result := nil;
660 if (tagmask = 0) then exit;
661 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true); // firsthit
662 if (it.length <> 0) then result := it.first^;
663 it.release();
664 end;
667 function g_Map_IsSpecialTexture(Texture: String): Boolean;
668 begin
669 Result := (Texture = TEXTURE_NAME_WATER) or
670 (Texture = TEXTURE_NAME_ACID1) or
671 (Texture = TEXTURE_NAME_ACID2);
672 end;
674 procedure CreateDoorMap();
675 var
676 PanelArray: Array of record
677 X, Y: Integer;
678 Width, Height: Word;
679 Active: Boolean;
680 PanelID: DWORD;
681 end;
682 a, b, c, m, i, len: Integer;
683 ok: Boolean;
684 begin
685 if gWalls = nil then
686 Exit;
688 i := 0;
689 len := 128;
690 SetLength(PanelArray, len);
692 for a := 0 to High(gWalls) do
693 if gWalls[a].Door then
694 begin
695 PanelArray[i].X := gWalls[a].X;
696 PanelArray[i].Y := gWalls[a].Y;
697 PanelArray[i].Width := gWalls[a].Width;
698 PanelArray[i].Height := gWalls[a].Height;
699 PanelArray[i].Active := True;
700 PanelArray[i].PanelID := a;
702 i := i + 1;
703 if i = len then
704 begin
705 len := len + 128;
706 SetLength(PanelArray, len);
707 end;
708 end;
710 // Íåò äâåðåé:
711 if i = 0 then
712 begin
713 PanelArray := nil;
714 Exit;
715 end;
717 SetLength(gDoorMap, 0);
719 g_Game_SetLoadingText(_lc[I_LOAD_DOOR_MAP], i-1, False);
721 for a := 0 to i-1 do
722 if PanelArray[a].Active then
723 begin
724 PanelArray[a].Active := False;
725 m := Length(gDoorMap);
726 SetLength(gDoorMap, m+1);
727 SetLength(gDoorMap[m], 1);
728 gDoorMap[m, 0] := PanelArray[a].PanelID;
729 ok := True;
731 while ok do
732 begin
733 ok := False;
735 for b := 0 to i-1 do
736 if PanelArray[b].Active then
737 for c := 0 to High(gDoorMap[m]) do
738 if {((gRenderWalls[PanelArray[b].RenderPanelID].TextureID = gRenderWalls[gDoorMap[m, c]].TextureID) or
739 gRenderWalls[PanelArray[b].RenderPanelID].Hide or gRenderWalls[gDoorMap[m, c]].Hide) and}
740 g_CollideAround(PanelArray[b].X, PanelArray[b].Y,
741 PanelArray[b].Width, PanelArray[b].Height,
742 gWalls[gDoorMap[m, c]].X,
743 gWalls[gDoorMap[m, c]].Y,
744 gWalls[gDoorMap[m, c]].Width,
745 gWalls[gDoorMap[m, c]].Height) then
746 begin
747 PanelArray[b].Active := False;
748 SetLength(gDoorMap[m],
749 Length(gDoorMap[m])+1);
750 gDoorMap[m, High(gDoorMap[m])] := PanelArray[b].PanelID;
751 ok := True;
752 Break;
753 end;
754 end;
756 g_Game_StepLoading();
757 end;
759 PanelArray := nil;
760 end;
762 procedure CreateLiftMap();
763 var
764 PanelArray: Array of record
765 X, Y: Integer;
766 Width, Height: Word;
767 Active: Boolean;
768 end;
769 a, b, c, len, i, j: Integer;
770 ok: Boolean;
771 begin
772 if gLifts = nil then
773 Exit;
775 len := Length(gLifts);
776 SetLength(PanelArray, len);
778 for a := 0 to len-1 do
779 begin
780 PanelArray[a].X := gLifts[a].X;
781 PanelArray[a].Y := gLifts[a].Y;
782 PanelArray[a].Width := gLifts[a].Width;
783 PanelArray[a].Height := gLifts[a].Height;
784 PanelArray[a].Active := True;
785 end;
787 SetLength(gLiftMap, len);
788 i := 0;
790 g_Game_SetLoadingText(_lc[I_LOAD_LIFT_MAP], len-1, False);
792 for a := 0 to len-1 do
793 if PanelArray[a].Active then
794 begin
795 PanelArray[a].Active := False;
796 SetLength(gLiftMap[i], 32);
797 j := 0;
798 gLiftMap[i, j] := a;
799 ok := True;
801 while ok do
802 begin
803 ok := False;
804 for b := 0 to len-1 do
805 if PanelArray[b].Active then
806 for c := 0 to j do
807 if g_CollideAround(PanelArray[b].X,
808 PanelArray[b].Y,
809 PanelArray[b].Width,
810 PanelArray[b].Height,
811 PanelArray[gLiftMap[i, c]].X,
812 PanelArray[gLiftMap[i, c]].Y,
813 PanelArray[gLiftMap[i, c]].Width,
814 PanelArray[gLiftMap[i, c]].Height) then
815 begin
816 PanelArray[b].Active := False;
817 j := j+1;
818 if j > High(gLiftMap[i]) then
819 SetLength(gLiftMap[i],
820 Length(gLiftMap[i])+32);
822 gLiftMap[i, j] := b;
823 ok := True;
825 Break;
826 end;
827 end;
829 SetLength(gLiftMap[i], j+1);
830 i := i+1;
832 g_Game_StepLoading();
833 end;
835 SetLength(gLiftMap, i);
837 PanelArray := nil;
838 end;
840 function CreatePanel (PanelRec: TDynRecord; AddTextures: TAddTextureArray; CurTex: Integer): Integer;
841 var
842 len: Integer;
843 panels: ^TPanelArray;
844 pan: TPanel;
845 pguid: Integer;
846 begin
847 Result := -1;
849 case PanelRec.PanelType of
850 PANEL_WALL, PANEL_OPENDOOR, PANEL_CLOSEDOOR: panels := @gWalls;
851 PANEL_BACK: panels := @gRenderBackgrounds;
852 PANEL_FORE: panels := @gRenderForegrounds;
853 PANEL_WATER: panels := @gWater;
854 PANEL_ACID1: panels := @gAcid1;
855 PANEL_ACID2: panels := @gAcid2;
856 PANEL_STEP: panels := @gSteps;
857 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: panels := @gLifts;
858 PANEL_BLOCKMON: panels := @gBlockMon;
859 else exit;
860 end;
862 len := Length(panels^);
863 SetLength(panels^, len+1);
865 pguid := Length(panByGUID);
866 SetLength(panByGUID, pguid+1); //FIXME!
867 pan := TPanel.Create(PanelRec, AddTextures, CurTex, Textures, pguid);
868 assert(pguid >= 0);
869 assert(pguid < Length(panByGUID));
870 panByGUID[pguid] := pan;
871 panels^[len] := pan;
872 pan.arrIdx := len;
873 pan.proxyId := -1;
874 pan.tag := panelTypeToTag(PanelRec.PanelType);
876 PanelRec.user['panel_guid'] := pguid;
878 //result := len;
879 result := pguid;
880 end;
883 function CreateNullTexture(RecName: String): Integer;
884 begin
885 RecName := toLowerCase1251(RecName);
886 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
887 if TextNameHash.get(RecName, result) then exit; // i found her!
889 SetLength(Textures, Length(Textures)+1);
890 result := High(Textures);
892 with Textures[High(Textures)] do
893 begin
894 TextureName := RecName;
895 Width := 1;
896 Height := 1;
897 Anim := False;
898 TextureID := LongWord(TEXTURE_NONE);
899 end;
901 TextNameHash.put(RecName, result);
902 end;
905 function extractWadName (resourceName: string): string;
906 var
907 posN: Integer;
908 begin
909 posN := Pos(':', resourceName);
910 if posN > 0 then
911 Result:= Copy(resourceName, 0, posN-1)
912 else
913 Result := '';
914 end;
917 procedure addResToExternalResList (res: AnsiString);
918 var
919 uname: AnsiString;
920 f: Integer;
921 fi: TDiskFileInfo;
922 begin
923 if g_Game_IsClient or not g_Game_IsNet then exit;
924 if (length(res) = 0) then exit; // map wad
925 //res := extractWadName(res);
926 //if (length(res) = 0) then exit; // map wad
927 uname := toLowerCase1251(res);
928 // do not add duplicates
929 for f := 0 to High(gExternalResources) do
930 begin
931 if (gExternalResources[f].userName = uname) then exit;
932 end;
933 //writeln('***(000) addResToExternalResList: res=[', res, ']');
934 // add new resource
935 fi.userName := uname;
936 if not findFileCI(res) then exit;
937 //writeln('***(001) addResToExternalResList: res=[', res, ']');
938 fi.diskName := res;
939 if (not GetDiskFileInfo(res, fi)) then
940 begin
941 fi.tag := -1;
942 end
943 else
944 begin
945 //writeln('***(002) addResToExternalResList: res=[', res, ']');
946 fi.tag := 0; // non-zero means "cannot caclucate hash"
947 try
948 fi.hash := MD5File(fi.diskName);
949 except
950 fi.tag := -1;
951 end;
952 end;
953 //e_LogWritefln('addext: res=[%s]; uname=[%s]; diskName=[%s]', [res, fi.userName, fi.diskName]);
954 SetLength(gExternalResources, length(gExternalResources)+1);
955 gExternalResources[High(gExternalResources)] := fi;
956 end;
959 procedure compactExtResList ();
960 var
961 src, dest: Integer;
962 begin
963 src := 0;
964 dest := 0;
965 for src := 0 to High(gExternalResources) do
966 begin
967 if (gExternalResources[src].tag = 0) then
968 begin
969 // copy it
970 if (dest <> src) then gExternalResources[dest] := gExternalResources[src];
971 Inc(dest);
972 end;
973 end;
974 if (dest <> length(gExternalResources)) then SetLength(gExternalResources, dest);
975 end;
978 function GetReplacementWad (WadName: AnsiString): AnsiString;
979 begin
980 result := '';
981 if WadName <> '' then
982 begin
983 result := WadName;
984 if g_Game_IsClient then result := g_Res_FindReplacementWad(WadName);
985 if (result = WadName) then result := e_FindWad(WadDirs, result)
986 end;
987 end;
990 procedure generateExternalResourcesList (map: TDynRecord);
991 begin
992 SetLength(gExternalResources, 0);
993 addResToExternalResList(GetReplacementWad(g_ExtractWadName(map.MusicName)));
994 addResToExternalResList(GetReplacementWad(g_ExtractWadName(map.SkyName)));
995 end;
998 function CreateTexture (RecName: AnsiString; Map: string; log: Boolean): Integer;
999 var
1000 WAD: TWADFile;
1001 TextureData: Pointer;
1002 WADName: String;
1003 a, ResLength: Integer;
1004 begin
1005 RecName := toLowerCase1251(RecName);
1006 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
1007 if TextNameHash.get(RecName, result) then
1008 begin
1009 // i found her!
1010 //e_LogWritefln('texture ''%s'' already loaded (%s)', [RecName, result]);
1011 exit;
1012 end;
1014 Result := -1;
1016 if (BadTextNameHash <> nil) and BadTextNameHash.has(RecName) then exit; // don't do it again and again
1019 if Textures <> nil then
1020 begin
1021 for a := 0 to High(Textures) do
1022 begin
1023 if (Textures[a].TextureName = RecName) then
1024 begin // Òåêñòóðà ñ òàêèì èìåíåì óæå åñòü
1025 e_LogWritefln('texture ''%s'' already loaded', [RecName]);
1026 Result := a;
1027 Exit;
1028 end;
1029 end;
1030 end;
1033 // Òåêñòóðû ñî ñïåöèàëüíûìè èìåíàìè (âîäà, ëàâà, êèñëîòà):
1034 if (RecName = TEXTURE_NAME_WATER) or
1035 (RecName = TEXTURE_NAME_ACID1) or
1036 (RecName = TEXTURE_NAME_ACID2) then
1037 begin
1038 SetLength(Textures, Length(Textures)+1);
1040 with Textures[High(Textures)] do
1041 begin
1042 TextureName := RecName;
1043 if (TextureName = TEXTURE_NAME_WATER) then TextureID := LongWord(TEXTURE_SPECIAL_WATER)
1044 else if (TextureName = TEXTURE_NAME_ACID1) then TextureID := LongWord(TEXTURE_SPECIAL_ACID1)
1045 else if (TextureName = TEXTURE_NAME_ACID2) then TextureID := LongWord(TEXTURE_SPECIAL_ACID2);
1047 Anim := False;
1048 end;
1050 result := High(Textures);
1051 TextNameHash.put(RecName, result);
1052 Exit;
1053 end;
1055 // Çàãðóæàåì ðåñóðñ òåêñòóðû â ïàìÿòü èç WAD'à:
1056 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1057 if (WADName <> '') then addResToExternalResList(WADName);
1058 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
1060 WAD := TWADFile.Create();
1061 WAD.ReadFile(WADName);
1063 //txname := RecName;
1065 if (WADName = Map) and WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength) then
1066 begin
1067 FreeMem(TextureData);
1068 RecName := 'COMMON\ALIEN';
1069 end;
1072 if WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength, log) then
1073 begin
1074 SetLength(Textures, Length(Textures)+1);
1075 if not e_CreateTextureMem(TextureData, ResLength, Textures[High(Textures)].TextureID) then
1076 begin
1077 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
1078 SetLength(Textures, Length(Textures)-1);
1079 result := -1;
1080 Exit;
1081 end;
1082 e_GetTextureSize(Textures[High(Textures)].TextureID, @Textures[High(Textures)].Width, @Textures[High(Textures)].Height);
1083 FreeMem(TextureData);
1084 Textures[High(Textures)].TextureName := RecName;
1085 Textures[High(Textures)].Anim := False;
1087 result := High(Textures);
1088 TextNameHash.put(RecName, result);
1089 end
1090 else // Íåò òàêîãî ðåóñðñà â WAD'å
1091 begin
1092 //e_WriteLog(Format('SHIT! Error loading texture %s : %s', [RecName, g_ExtractFilePathName(RecName)]), MSG_WARNING);
1093 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1094 if log and (not BadTextNameHash.get(RecName, a)) then
1095 begin
1096 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
1097 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1098 end;
1099 BadTextNameHash.put(RecName, -1);
1100 end;
1102 WAD.Free();
1103 end;
1106 function CreateAnimTexture(RecName: String; Map: string; log: Boolean): Integer;
1107 var
1108 WAD: TWADFile;
1109 TextureWAD: PChar = nil;
1110 TextData: Pointer = nil;
1111 TextureData: Pointer = nil;
1112 cfg: TConfig = nil;
1113 WADName: String;
1114 ResLength: Integer;
1115 TextureResource: String;
1116 _width, _height, _framecount, _speed: Integer;
1117 _backanimation: Boolean;
1118 //imgfmt: string;
1119 ia: TDynImageDataArray = nil;
1120 f, c, frdelay, frloop: Integer;
1121 begin
1122 RecName := toLowerCase1251(RecName);
1123 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
1124 if TextNameHash.get(RecName, result) then
1125 begin
1126 // i found her!
1127 //e_LogWritefln('animated texture ''%s'' already loaded (%s)', [RecName, result]);
1128 exit;
1129 end;
1131 result := -1;
1133 //e_LogWritefln('*** Loading animated texture "%s"', [RecName]);
1135 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1136 if BadTextNameHash.get(RecName, f) then
1137 begin
1138 //e_WriteLog(Format('no animation texture %s (don''t worry)', [RecName]), MSG_NOTIFY);
1139 exit;
1140 end;
1142 // ×èòàåì WAD-ðåñóðñ àíèì.òåêñòóðû èç WAD'à â ïàìÿòü:
1143 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1144 if (WADName <> '') then addResToExternalResList(WADName);
1145 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
1147 WAD := TWADFile.Create();
1148 try
1149 //if WADName <> '' then WADName := GameDir+'/wads/'+WADName else WADName := Map;
1151 WAD.ReadFile(WADName);
1153 if not WAD.GetResource(g_ExtractFilePathName(RecName), TextureWAD, ResLength, log) then
1154 begin
1155 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1156 if log and (not BadTextNameHash.get(RecName, f)) then
1157 begin
1158 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1159 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1160 end;
1161 BadTextNameHash.put(RecName, -1);
1162 exit;
1163 end;
1165 {TEST
1166 if WADName = Map then
1167 begin
1168 //FreeMem(TextureWAD);
1169 if not WAD.GetResource('COMMON/animation', TextureWAD, ResLength) then Halt(1);
1170 end;
1173 WAD.FreeWAD();
1175 if ResLength < 6 then
1176 begin
1177 e_WriteLog(Format('Animated texture file "%s" too short', [RecName]), TMsgType.Warning);
1178 BadTextNameHash.put(RecName, -1);
1179 exit;
1180 end;
1182 // ýòî ïòèöà? ýòî ñàìîë¸ò?
1183 if isWadData(TextureWAD, ResLength) then
1184 begin
1185 // íåò, ýòî ñóïåðìåí!
1186 if not WAD.ReadMemory(TextureWAD, ResLength) then
1187 begin
1188 e_WriteLog(Format('Animated texture WAD file "%s" is invalid', [RecName]), TMsgType.Warning);
1189 BadTextNameHash.put(RecName, -1);
1190 exit;
1191 end;
1193 // ×èòàåì INI-ðåñóðñ àíèì. òåêñòóðû è çàïîìèíàåì åãî óñòàíîâêè:
1194 if not WAD.GetResource('TEXT/ANIM', TextData, ResLength) then
1195 begin
1196 e_WriteLog(Format('Animated texture file "%s" has invalid INI', [RecName]), TMsgType.Warning);
1197 BadTextNameHash.put(RecName, -1);
1198 exit;
1199 end;
1201 cfg := TConfig.CreateMem(TextData, ResLength);
1203 TextureResource := cfg.ReadStr('', 'resource', '');
1204 if TextureResource = '' then
1205 begin
1206 e_WriteLog(Format('Animated texture WAD file "%s" has no "resource"', [RecName]), TMsgType.Warning);
1207 BadTextNameHash.put(RecName, -1);
1208 exit;
1209 end;
1211 _width := cfg.ReadInt('', 'framewidth', 0);
1212 _height := cfg.ReadInt('', 'frameheight', 0);
1213 _framecount := cfg.ReadInt('', 'framecount', 0);
1214 _speed := cfg.ReadInt('', 'waitcount', 0);
1215 _backanimation := cfg.ReadBool('', 'backanimation', False);
1217 cfg.Free();
1218 cfg := nil;
1220 // ×èòàåì ðåñóðñ òåêñòóð (êàäðîâ) àíèì. òåêñòóðû â ïàìÿòü:
1221 if not WAD.GetResource('TEXTURES/'+TextureResource, TextureData, ResLength) then
1222 begin
1223 e_WriteLog(Format('Animated texture WAD file "%s" has no texture "%s"', [RecName, 'TEXTURES/'+TextureResource]), TMsgType.Warning);
1224 BadTextNameHash.put(RecName, -1);
1225 exit;
1226 end;
1228 WAD.Free();
1229 WAD := nil;
1231 SetLength(Textures, Length(Textures)+1);
1232 with Textures[High(Textures)] do
1233 begin
1234 // Ñîçäàåì êàäðû àíèì. òåêñòóðû èç ïàìÿòè:
1235 if g_Frames_CreateMemory(@FramesID, '', TextureData, ResLength, _width, _height, _framecount, _backanimation) then
1236 begin
1237 TextureName := RecName;
1238 Width := _width;
1239 Height := _height;
1240 Anim := True;
1241 FramesCount := _framecount;
1242 Speed := _speed;
1243 result := High(Textures);
1244 TextNameHash.put(RecName, result);
1245 end
1246 else
1247 begin
1248 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1249 if log and (not BadTextNameHash.get(RecName, f)) then
1250 begin
1251 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1252 end;
1253 BadTextNameHash.put(RecName, -1);
1254 end;
1255 end;
1256 end
1257 else
1258 begin
1259 // try animated image
1261 imgfmt := DetermineMemoryFormat(TextureWAD, ResLength);
1262 if length(imgfmt) = 0 then
1263 begin
1264 e_WriteLog(Format('Animated texture file "%s" has unknown format', [RecName]), MSG_WARNING);
1265 exit;
1266 end;
1268 GlobalMetadata.ClearMetaItems();
1269 GlobalMetadata.ClearMetaItemsForSaving();
1270 if not LoadMultiImageFromMemory(TextureWAD, ResLength, ia) then
1271 begin
1272 e_WriteLog(Format('Animated texture file "%s" cannot be loaded', [RecName]), TMsgType.Warning);
1273 BadTextNameHash.put(RecName, -1);
1274 exit;
1275 end;
1276 if length(ia) = 0 then
1277 begin
1278 e_WriteLog(Format('Animated texture file "%s" has no frames', [RecName]), TMsgType.Warning);
1279 BadTextNameHash.put(RecName, -1);
1280 exit;
1281 end;
1283 WAD.Free();
1284 WAD := nil;
1286 _width := ia[0].width;
1287 _height := ia[0].height;
1288 _framecount := length(ia);
1289 _speed := 1;
1290 _backanimation := false;
1291 frdelay := -1;
1292 frloop := -666;
1293 if GlobalMetadata.HasMetaItem(SMetaFrameDelay) then
1294 begin
1295 //writeln(' frame delay: ', GlobalMetadata.MetaItems[SMetaFrameDelay]);
1296 try
1297 f := GlobalMetadata.MetaItems[SMetaFrameDelay];
1298 frdelay := f;
1299 if f < 0 then f := 0;
1300 // rounding ;-)
1301 c := f mod 28;
1302 if c < 13 then c := 0 else c := 1;
1303 f := (f div 28)+c;
1304 if f < 1 then f := 1 else if f > 255 then f := 255;
1305 _speed := f;
1306 except
1307 end;
1308 end;
1309 if GlobalMetadata.HasMetaItem(SMetaAnimationLoops) then
1310 begin
1311 //writeln(' frame loop : ', GlobalMetadata.MetaItems[SMetaAnimationLoops]);
1312 try
1313 f := GlobalMetadata.MetaItems[SMetaAnimationLoops];
1314 frloop := f;
1315 if f <> 0 then _backanimation := true; // non-infinite looping == forth-and-back
1316 except
1317 end;
1318 end;
1319 //writeln(' creating animated texture with ', length(ia), ' frames (delay:', _speed, '; backloop:', _backanimation, ') from "', RecName, '"...');
1320 //for f := 0 to high(ia) do writeln(' frame #', f, ': ', ia[f].width, 'x', ia[f].height);
1321 f := ord(_backanimation);
1322 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);
1324 SetLength(Textures, Length(Textures)+1);
1325 // cîçäàåì êàäðû àíèì. òåêñòóðû èç êàðòèíîê
1326 if g_CreateFramesImg(ia, @Textures[High(Textures)].FramesID, '', _backanimation) then
1327 begin
1328 Textures[High(Textures)].TextureName := RecName;
1329 Textures[High(Textures)].Width := _width;
1330 Textures[High(Textures)].Height := _height;
1331 Textures[High(Textures)].Anim := True;
1332 Textures[High(Textures)].FramesCount := length(ia);
1333 Textures[High(Textures)].Speed := _speed;
1334 result := High(Textures);
1335 TextNameHash.put(RecName, result);
1336 //writeln(' CREATED!');
1337 end
1338 else
1339 begin
1340 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1341 if log and (not BadTextNameHash.get(RecName, f)) then
1342 begin
1343 e_WriteLog(Format('Error loading animation texture "%s" images', [RecName]), TMsgType.Warning);
1344 end;
1345 BadTextNameHash.put(RecName, -1);
1346 end;
1347 end;
1348 finally
1349 for f := 0 to High(ia) do FreeImage(ia[f]);
1350 WAD.Free();
1351 cfg.Free();
1352 if (TextureWAD <> nil) then FreeMem(TextureWAD);
1353 if (TextData <> nil) then FreeMem(TextData);
1354 if (TextureData <> nil) then FreeMem(TextureData);
1355 end;
1356 end;
1358 procedure CreateItem(Item: TDynRecord);
1359 begin
1360 if g_Game_IsClient then Exit;
1362 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) and
1363 ByteBool(Item.Options and ITEM_OPTION_ONLYDM) then
1364 Exit;
1366 g_Items_Create(Item.X, Item.Y, Item.ItemType, ByteBool(Item.Options and ITEM_OPTION_FALL),
1367 gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF, GM_COOP]);
1368 end;
1370 procedure CreateArea(Area: TDynRecord);
1371 var
1372 a: Integer;
1373 id: DWORD = 0;
1374 begin
1375 case Area.AreaType of
1376 AREA_DMPOINT, AREA_PLAYERPOINT1, AREA_PLAYERPOINT2,
1377 AREA_REDTEAMPOINT, AREA_BLUETEAMPOINT:
1378 begin
1379 SetLength(RespawnPoints, Length(RespawnPoints)+1);
1380 with RespawnPoints[High(RespawnPoints)] do
1381 begin
1382 X := Area.X;
1383 Y := Area.Y;
1384 Direction := TDirection(Area.Direction);
1386 case Area.AreaType of
1387 AREA_DMPOINT: PointType := RESPAWNPOINT_DM;
1388 AREA_PLAYERPOINT1: PointType := RESPAWNPOINT_PLAYER1;
1389 AREA_PLAYERPOINT2: PointType := RESPAWNPOINT_PLAYER2;
1390 AREA_REDTEAMPOINT: PointType := RESPAWNPOINT_RED;
1391 AREA_BLUETEAMPOINT: PointType := RESPAWNPOINT_BLUE;
1392 end;
1393 end;
1394 end;
1396 AREA_REDFLAG, AREA_BLUEFLAG:
1397 begin
1398 if Area.AreaType = AREA_REDFLAG then a := FLAG_RED else a := FLAG_BLUE;
1400 if FlagPoints[a] <> nil then Exit;
1402 New(FlagPoints[a]);
1404 with FlagPoints[a]^ do
1405 begin
1406 X := Area.X-FLAGRECT.X;
1407 Y := Area.Y-FLAGRECT.Y;
1408 Direction := TDirection(Area.Direction);
1409 end;
1411 with gFlags[a] do
1412 begin
1413 case a of
1414 FLAG_RED: g_Frames_Get(id, 'FRAMES_FLAG_RED');
1415 FLAG_BLUE: g_Frames_Get(id, 'FRAMES_FLAG_BLUE');
1416 end;
1418 Animation := TAnimation.Create(id, True, 8);
1419 Obj.Rect := FLAGRECT;
1421 g_Map_ResetFlag(a);
1422 end;
1423 end;
1425 AREA_DOMFLAG:
1426 begin
1427 {SetLength(DOMFlagPoints, Length(DOMFlagPoints)+1);
1428 with DOMFlagPoints[High(DOMFlagPoints)] do
1429 begin
1430 X := Area.X;
1431 Y := Area.Y;
1432 Direction := TDirection(Area.Direction);
1433 end;
1435 g_Map_CreateFlag(DOMFlagPoints[High(DOMFlagPoints)], FLAG_DOM, FLAG_STATE_NORMAL);}
1436 end;
1437 end;
1438 end;
1440 function CreateTrigger (amapIdx: Integer; Trigger: TDynRecord; atpanid, atrigpanid: Integer): Integer;
1441 var
1442 _trigger: TTrigger;
1443 tp: TPanel;
1444 begin
1445 result := -1;
1446 if g_Game_IsClient and not (Trigger.TriggerType in [TRIGGER_SOUND, TRIGGER_MUSIC]) then Exit;
1448 with _trigger do
1449 begin
1450 mapId := Trigger.id;
1451 mapIndex := amapIdx;
1452 X := Trigger.X;
1453 Y := Trigger.Y;
1454 Width := Trigger.Width;
1455 Height := Trigger.Height;
1456 Enabled := Trigger.Enabled;
1457 TexturePanelGUID := atpanid;
1458 TriggerType := Trigger.TriggerType;
1459 ActivateType := Trigger.ActivateType;
1460 Keys := Trigger.Keys;
1461 trigPanelGUID := atrigpanid;
1462 // HACK: used in TPanel.CanChangeTexture. maybe there's a better way?
1463 if TexturePanelGUID <> -1 then
1464 begin
1465 tp := g_Map_PanelByGUID(TexturePanelGUID);
1466 if (tp <> nil) then tp.hasTexTrigger := True;
1467 end;
1468 end;
1470 result := Integer(g_Triggers_Create(_trigger, Trigger));
1471 end;
1473 procedure CreateMonster(monster: TDynRecord);
1474 var
1475 a: Integer;
1476 mon: TMonster;
1477 begin
1478 if g_Game_IsClient then Exit;
1480 if (gGameSettings.GameType = GT_SINGLE)
1481 or (TGameOption.MONSTERS in gGameSettings.Options) then
1482 begin
1483 mon := g_Monsters_Create(monster.MonsterType, monster.X, monster.Y, TDirection(monster.Direction));
1485 if gTriggers <> nil then
1486 begin
1487 for a := 0 to High(gTriggers) do
1488 begin
1489 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1490 begin
1491 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1492 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1493 end;
1494 end;
1495 end;
1497 if monster.MonsterType <> MONSTER_BARREL then Inc(gTotalMonsters);
1498 end;
1499 end;
1501 procedure g_Map_ReAdd_DieTriggers();
1503 function monsDieTrig (mon: TMonster): Boolean;
1504 var
1505 a: Integer;
1506 //tw: TStrTextWriter;
1507 begin
1508 result := false; // don't stop
1509 mon.ClearTriggers();
1510 for a := 0 to High(gTriggers) do
1511 begin
1512 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1513 begin
1514 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1516 tw := TStrTextWriter.Create();
1517 try
1518 gTriggers[a].trigData.writeTo(tw);
1519 e_LogWritefln('=== trigger #%s ==='#10'%s'#10'---', [a, tw.str]);
1520 finally
1521 tw.Free();
1522 end;
1524 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1525 end;
1526 end;
1527 end;
1529 begin
1530 if g_Game_IsClient then Exit;
1532 g_Mons_ForEach(monsDieTrig);
1533 end;
1535 procedure mapCreateGrid ();
1536 var
1537 mapX0: Integer = $3fffffff;
1538 mapY0: Integer = $3fffffff;
1539 mapX1: Integer = -$3fffffff;
1540 mapY1: Integer = -$3fffffff;
1542 procedure calcBoundingBox (constref panels: TPanelArray);
1543 var
1544 idx: Integer;
1545 pan: TPanel;
1546 begin
1547 for idx := 0 to High(panels) do
1548 begin
1549 pan := panels[idx];
1550 if not pan.visvalid then continue;
1551 if (pan.Width < 1) or (pan.Height < 1) then continue;
1552 if (mapX0 > pan.x0) then mapX0 := pan.x0;
1553 if (mapY0 > pan.y0) then mapY0 := pan.y0;
1554 if (mapX1 < pan.x1) then mapX1 := pan.x1;
1555 if (mapY1 < pan.y1) then mapY1 := pan.y1;
1556 end;
1557 end;
1559 procedure addPanelsToGrid (constref panels: TPanelArray);
1560 var
1561 idx: Integer;
1562 pan: TPanel;
1563 newtag: Integer;
1564 begin
1565 //tag := panelTypeToTag(tag);
1566 for idx := 0 to High(panels) do
1567 begin
1568 pan := panels[idx];
1569 if not pan.visvalid then continue;
1570 if (pan.proxyId <> -1) then
1571 begin
1572 {$IF DEFINED(D2F_DEBUG)}
1573 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);
1574 {$ENDIF}
1575 continue;
1576 end;
1577 case pan.PanelType of
1578 PANEL_WALL: newtag := GridTagWall;
1579 PANEL_OPENDOOR, PANEL_CLOSEDOOR: newtag := GridTagDoor;
1580 PANEL_BACK: newtag := GridTagBack;
1581 PANEL_FORE: newtag := GridTagFore;
1582 PANEL_WATER: newtag := GridTagWater;
1583 PANEL_ACID1: newtag := GridTagAcid1;
1584 PANEL_ACID2: newtag := GridTagAcid2;
1585 PANEL_STEP: newtag := GridTagStep;
1586 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: newtag := GridTagLift;
1587 PANEL_BLOCKMON: newtag := GridTagBlockMon;
1588 else continue; // oops
1589 end;
1590 pan.tag := newtag;
1592 pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, newtag);
1593 // "enabled" flag has meaning only for doors and walls (engine assumes it); but meh...
1594 mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
1595 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
1597 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
1598 begin
1599 e_WriteLog(Format('INSERTED wall #%d(%d) enabled (%d)', [Integer(idx), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId])]), MSG_NOTIFY);
1600 end;
1602 {$ENDIF}
1603 end;
1604 end;
1606 begin
1607 mapGrid.Free();
1608 mapGrid := nil;
1610 calcBoundingBox(gWalls);
1611 calcBoundingBox(gRenderBackgrounds);
1612 calcBoundingBox(gRenderForegrounds);
1613 calcBoundingBox(gWater);
1614 calcBoundingBox(gAcid1);
1615 calcBoundingBox(gAcid2);
1616 calcBoundingBox(gSteps);
1617 calcBoundingBox(gLifts);
1618 calcBoundingBox(gBlockMon);
1620 e_LogWritefln('map dimensions: (%d,%d)-(%d,%d); editor size:(0,0)-(%d,%d)', [mapX0, mapY0, mapX1, mapY1, gMapInfo.Width, gMapInfo.Height]);
1622 if (mapX0 > 0) then mapX0 := 0;
1623 if (mapY0 > 0) then mapY0 := 0;
1625 if (mapX1 < gMapInfo.Width-1) then mapX1 := gMapInfo.Width-1;
1626 if (mapY1 < gMapInfo.Height-1) then mapY1 := gMapInfo.Height-1;
1628 mapGrid := TPanelGrid.Create(mapX0-128, mapY0-128, mapX1-mapX0+1+128*2, mapY1-mapY0+1+128*2);
1629 //mapGrid := TPanelGrid.Create(0, 0, gMapInfo.Width, gMapInfo.Height);
1631 addPanelsToGrid(gWalls);
1632 addPanelsToGrid(gRenderBackgrounds);
1633 addPanelsToGrid(gRenderForegrounds);
1634 addPanelsToGrid(gWater);
1635 addPanelsToGrid(gAcid1);
1636 addPanelsToGrid(gAcid2);
1637 addPanelsToGrid(gSteps);
1638 addPanelsToGrid(gLifts); // it doesn't matter which LIFT type is used here
1639 addPanelsToGrid(gBlockMon);
1641 mapGrid.dumpStats();
1643 g_Mons_InitTree(mapGrid.gridX0, mapGrid.gridY0, mapGrid.gridWidth, mapGrid.gridHeight);
1644 end;
1647 function g_Map_Load(Res: String): Boolean;
1648 const
1649 DefaultMusRes = 'Standart.wad:STDMUS\MUS1';
1650 DefaultSkyRes = 'Standart.wad:STDSKY\SKY0';
1651 type
1652 PTRec = ^TTRec;
1653 TTRec = record
1654 //TexturePanel: Integer;
1655 tnum: Integer;
1656 id: Integer;
1657 trigrec: TDynRecord;
1658 // texture pane;
1659 texPanelIdx: Integer;
1660 texPanel: TDynRecord;
1661 // "action" panel
1662 actPanelIdx: Integer;
1663 actPanel: TDynRecord;
1664 end;
1665 var
1666 WAD, TestWAD: TWADFile;
1667 //mapReader: TDynRecord = nil;
1668 mapTextureList: TDynField = nil; //TTexturesRec1Array; tagInt: texture index
1669 panels: TDynField = nil; //TPanelsRec1Array;
1670 items: TDynField = nil; //TItemsRec1Array;
1671 monsters: TDynField = nil; //TMonsterRec1Array;
1672 areas: TDynField = nil; //TAreasRec1Array;
1673 triggers: TDynField = nil; //TTriggersRec1Array;
1674 b, c, k: Integer;
1675 PanelID: DWORD;
1676 AddTextures: TAddTextureArray;
1677 TriggersTable: array of TTRec;
1678 FileName, mapResName, TexName, s: AnsiString;
1679 Data: Pointer;
1680 Len: Integer;
1681 ok, isAnim: Boolean;
1682 CurTex, ntn: Integer;
1683 rec, texrec: TDynRecord;
1684 pttit: PTRec;
1685 pannum, trignum, cnt, tgpid: Integer;
1686 stt: UInt64;
1687 moveSpeed{, moveStart, moveEnd}: TDFPoint;
1688 //moveActive: Boolean;
1689 pan: TPanel;
1690 mapOk: Boolean = false;
1691 usedTextures: THashStrInt = nil; // key: mapTextureList
1692 begin
1693 mapGrid.Free();
1694 mapGrid := nil;
1695 TestWAD := nil;
1696 Data := nil;
1698 //gCurrentMap.Free();
1699 //gCurrentMap := nil;
1701 panByGUID := nil;
1703 Result := False;
1704 gMapInfo.Map := Res;
1705 TriggersTable := nil;
1706 //mapReader := nil;
1708 sfsGCDisable(); // temporary disable removing of temporary volumes
1709 try
1710 // Çàãðóçêà WAD (åñëè ó íàñ íåò óæå çàãðóæåíîé êàðòû)
1711 if (gCurrentMap = nil) then
1712 begin
1713 FileName := g_ExtractWadName(Res);
1714 e_LogWritefln('Loading map WAD [%s] (res=[%s])', [FileName, Res], TMsgType.Notify);
1715 g_Game_SetLoadingText(_lc[I_LOAD_WAD_FILE], 0, False);
1717 WAD := TWADFile.Create();
1718 if not WAD.ReadFile(FileName) then
1719 begin
1720 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [FileName]));
1721 WAD.Free();
1722 Exit;
1723 end;
1725 if gTestMap <> '' then
1726 begin
1727 s := g_ExtractWadName(gTestMap);
1728 TestWAD := TWADFile.Create();
1729 if not TestWAD.ReadFile(s) then
1730 begin
1731 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_WAD], [s]));
1732 TestWAD.Free();
1733 TestWAD := nil;
1734 end;
1735 end;
1737 if TestWAD <> nil then
1738 begin
1739 mapResName := g_ExtractFileName(gTestMap);
1740 if not TestWAD.GetMapResource(mapResName, Data, Len) then
1741 begin
1742 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1743 Data := nil;
1744 end else
1745 e_WriteLog('Using test map: '+gTestMap, TMsgType.Notify);
1746 TestWAD.Free();
1747 TestWAD := nil;
1748 end;
1750 if Data = nil then
1751 begin
1752 //k8: why loader ignores path here?
1753 mapResName := g_ExtractFileName(Res);
1754 if not WAD.GetMapResource(mapResName, Data, Len) then
1755 begin
1756 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1757 WAD.Free();
1758 Exit;
1759 end;
1760 end;
1762 WAD.Free();
1764 if (Len < 4) then
1765 begin
1766 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1767 FreeMem(Data);
1768 exit;
1769 end;
1771 // Çàãðóçêà êàðòû:
1772 e_LogWritefln('Loading map: %s', [mapResName], TMsgType.Notify);
1773 g_Game_SetLoadingText(_lc[I_LOAD_MAP], 0, False);
1775 stt := getTimeMicro();
1777 try
1778 gCurrentMap := g_Map_ParseMap(Data, Len);
1779 except
1780 gCurrentMap.Free();
1781 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]));
1782 FreeMem(Data);
1783 gCurrentMapFileName := '';
1784 Exit;
1785 end;
1787 FreeMem(Data);
1789 if (gCurrentMap = nil) then
1790 begin
1791 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1792 gCurrentMapFileName := '';
1793 exit;
1794 end;
1795 end
1796 else
1797 begin
1798 stt := getTimeMicro();
1799 end;
1801 //gCurrentMap := mapReader;
1803 generateExternalResourcesList(gCurrentMap);
1804 mapTextureList := gCurrentMap['texture'];
1805 // get all other lists here too
1806 panels := gCurrentMap['panel'];
1807 triggers := gCurrentMap['trigger'];
1808 items := gCurrentMap['item'];
1809 areas := gCurrentMap['area'];
1810 monsters := gCurrentMap['monster'];
1812 // Çàãðóçêà îïèñàíèÿ êàðòû:
1813 e_WriteLog(' Reading map info...', TMsgType.Notify);
1814 g_Game_SetLoadingText(_lc[I_LOAD_MAP_HEADER], 0, False);
1816 with gMapInfo do
1817 begin
1818 Name := gCurrentMap.MapName;
1819 Description := gCurrentMap.MapDesc;
1820 Author := gCurrentMap.MapAuthor;
1821 MusicName := gCurrentMap.MusicName;
1822 SkyName := gCurrentMap.SkyName;
1823 Height := gCurrentMap.Height;
1824 Width := gCurrentMap.Width;
1825 end;
1827 // Çàãðóçêà òåêñòóð:
1828 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], 0, False);
1829 // Äîáàâëåíèå òåêñòóð â Textures[]:
1830 if (mapTextureList <> nil) and (mapTextureList.count > 0) then
1831 begin
1832 e_WriteLog(' Loading textures:', TMsgType.Notify);
1833 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], mapTextureList.count-1, False);
1835 // find used textures
1836 usedTextures := THashStrInt.Create();
1837 try
1838 if (panels <> nil) and (panels.count > 0) then
1839 begin
1840 for rec in panels do
1841 begin
1842 texrec := rec.TextureRec;
1843 if (texrec <> nil) then usedTextures.put(toLowerCase1251(texrec.Resource), 42);
1844 end;
1845 end;
1847 cnt := -1;
1848 for rec in mapTextureList do
1849 begin
1850 cnt += 1;
1851 if not usedTextures.has(toLowerCase1251(rec.Resource)) then
1852 begin
1853 rec.tagInt := -1; // just in case
1854 e_LogWritefln(' Unused texture #%d: %s', [cnt, rec.Resource]);
1855 end
1856 else
1857 begin
1858 {$IF DEFINED(D2F_DEBUG_TXLOAD)}
1859 e_LogWritefln(' Loading texture #%d: %s', [cnt, rec.Resource]);
1860 {$ENDIF}
1861 //if g_Map_IsSpecialTexture(s) then e_WriteLog(' SPECIAL!', MSG_NOTIFY);
1862 // TODO: Unify the texture reader - static textures are a special case of dynamic ones, just with only one frame.
1863 if rec.Anim then
1864 begin
1865 // Àíèìèðîâàííàÿ òåêñòóðà
1866 ntn := CreateAnimTexture(rec.Resource, FileName, True);
1867 if (ntn < 0) then
1868 begin
1869 // FIXME: I think, CreateAnimTexture() will load static textures too, just as animated ones with one frame.
1870 ntn := CreateTexture(rec.Resource, FileName, False);
1871 if (ntn < 0) then
1872 g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_ANIM], [rec.Resource]))
1873 else
1874 begin
1875 rec.user['animated'] := False;
1876 e_LogWritefln(' wrong (outdated?) anim flag hint - texture #%d is actually static: %s', [cnt, rec.Resource]);
1877 end;
1878 end;
1879 end
1880 else
1881 begin
1882 // Îáû÷íàÿ òåêñòóðà
1883 ntn := CreateTexture(rec.Resource, FileName, True);
1884 if (ntn < 0) then
1885 begin
1886 ntn := CreateAnimTexture(rec.Resource, FileName, False);
1887 if (ntn < 0) then
1888 g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_SIMPLE], [rec.Resource]))
1889 else
1890 begin
1891 rec.user['animated'] := True;
1892 e_LogWritefln(' wrong (outdated?) anim flag hint - texture #%d is actually animated: %s', [cnt, rec.Resource]);
1893 end;
1894 end;
1895 end;
1896 if (ntn < 0) then ntn := CreateNullTexture(rec.Resource);
1898 rec.tagInt := ntn; // remember texture number
1899 end;
1900 g_Game_StepLoading();
1901 end;
1902 finally
1903 usedTextures.Free();
1904 end;
1906 // set panel tagInt to texture index
1907 if (panels <> nil) then
1908 begin
1909 for rec in panels do
1910 begin
1911 texrec := rec.TextureRec;
1912 if (texrec = nil) then rec.tagInt := -1 else rec.tagInt := texrec.tagInt;
1913 end;
1914 end;
1915 end;
1918 // Çàãðóçêà òðèããåðîâ
1919 gTriggerClientID := 0;
1920 e_WriteLog(' Loading triggers...', TMsgType.Notify);
1921 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS], 0, False);
1923 // Çàãðóçêà ïàíåëåé
1924 e_WriteLog(' Loading panels...', TMsgType.Notify);
1925 g_Game_SetLoadingText(_lc[I_LOAD_PANELS], 0, False);
1927 // check texture numbers for panels
1928 if (panels <> nil) and (panels.count > 0) then
1929 begin
1930 for rec in panels do
1931 begin
1932 if (rec.tagInt < 0) then
1933 begin
1934 e_WriteLog('error loading map: invalid texture index for panel', TMsgType.Fatal);
1935 result := false;
1936 gCurrentMap.Free();
1937 gCurrentMap := nil;
1938 gCurrentMapFileName := '';
1939 exit;
1940 end;
1941 end;
1942 end;
1944 // Ñîçäàíèå òàáëèöû òðèããåðîâ (ñîîòâåòñòâèå ïàíåëåé òðèããåðàì)
1945 if (triggers <> nil) and (triggers.count > 0) then
1946 begin
1947 e_WriteLog(' Setting up trigger table...', TMsgType.Notify);
1948 //SetLength(TriggersTable, triggers.count);
1949 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS_TABLE], triggers.count-1, False);
1951 SetLength(TriggersTable, triggers.count);
1952 trignum := -1;
1953 for rec in triggers do
1954 begin
1955 Inc(trignum);
1956 pttit := @TriggersTable[trignum];
1957 pttit.trigrec := rec;
1958 // Ñìåíà òåêñòóðû (âîçìîæíî, êíîïêè)
1959 pttit.texPanelIdx := -1; // will be fixed later
1960 pttit.texPanel := rec.TexturePanelRec;
1961 // action panel
1962 pttit.actPanelIdx := -1;
1963 if (rec.trigRec <> nil) then pttit.actPanel := rec.trigRec.tgPanelRec else pttit.actPanel := nil;
1964 // set flag
1965 if (pttit.texPanel <> nil) then pttit.texPanel.userPanelTrigRef := true;
1966 if (pttit.actPanel <> nil) then pttit.actPanel.userPanelTrigRef := true;
1967 // update progress
1968 g_Game_StepLoading();
1969 end;
1970 end;
1972 // Ñîçäàåì ïàíåëè
1973 if (panels <> nil) and (panels.count > 0) then
1974 begin
1975 e_WriteLog(' Setting up trigger links...', TMsgType.Notify);
1976 g_Game_SetLoadingText(_lc[I_LOAD_LINK_TRIGGERS], panels.count-1, False);
1978 pannum := -1;
1979 for rec in panels do
1980 begin
1981 Inc(pannum);
1982 //e_LogWritefln('PANSTART: pannum=%s', [pannum]);
1983 texrec := nil;
1984 SetLength(AddTextures, 0);
1985 CurTex := -1;
1986 ok := false;
1988 if (mapTextureList <> nil) then
1989 begin
1990 texrec := rec.TextureRec;
1991 ok := (texrec <> nil);
1992 end;
1994 if ok then
1995 begin
1996 // Ñìîòðèì, ññûëàþòñÿ ëè íà ýòó ïàíåëü òðèããåðû.
1997 // Åñëè äà - òî íàäî ñîçäàòü åùå òåêñòóð
1998 ok := false;
1999 if (TriggersTable <> nil) and (mapTextureList <> nil) then
2000 begin
2001 if rec.userPanelTrigRef then
2002 begin
2003 // e_LogWritefln('trigref for panel %s', [pannum]);
2004 ok := True;
2005 end;
2006 end;
2007 end;
2009 if ok then
2010 begin
2011 // Åñòü ññûëêè òðèããåðîâ íà ýòó ïàíåëü
2012 s := texrec.Resource;
2014 // Ñïåö-òåêñòóðû çàïðåùåíû
2015 if g_Map_IsSpecialTexture(s) then
2016 begin
2017 ok := false
2018 end
2019 else
2020 begin
2021 // Îïðåäåëÿåì íàëè÷èå è ïîëîæåíèå öèôð â êîíöå ñòðîêè
2022 ok := g_Texture_NumNameFindStart(s);
2023 end;
2025 // Åñëè ok, çíà÷èò åñòü öèôðû â êîíöå.
2026 // Çàãðóæàåì òåêñòóðû ñ îñòàëüíûìè #
2027 if ok then
2028 begin
2029 k := NNF_NAME_BEFORE;
2030 // Öèêë ïî èçìåíåíèþ èìåíè òåêñòóðû
2031 while ok or (k = NNF_NAME_BEFORE) or (k = NNF_NAME_EQUALS) do
2032 begin
2033 k := g_Texture_NumNameFindNext(TexName);
2035 if (k = NNF_NAME_BEFORE) or (k = NNF_NAME_AFTER) then
2036 begin
2037 // Ïðîáóåì äîáàâèòü íîâóþ òåêñòóðó
2038 if texrec.Anim then
2039 begin
2040 // Íà÷àëüíàÿ - àíèìèðîâàííàÿ, èùåì àíèìèðîâàííóþ
2041 isAnim := True;
2042 //e_LogWritefln('000: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2043 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2044 //e_LogWritefln('001: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2045 if not ok then
2046 begin
2047 // Íåò àíèìèðîâàííîé, èùåì îáû÷íóþ
2048 isAnim := False;
2049 //e_LogWritefln('002: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2050 ok := CreateTexture(TexName, FileName, False) >= 0;
2051 //e_LogWritefln('003: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2052 end;
2053 end
2054 else
2055 begin
2056 // Íà÷àëüíàÿ - îáû÷íàÿ, èùåì îáû÷íóþ
2057 isAnim := False;
2058 //e_LogWritefln('004: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2059 ok := CreateTexture(TexName, FileName, False) >= 0;
2060 //e_LogWritefln('005: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2061 if not ok then
2062 begin
2063 // Íåò îáû÷íîé, èùåì àíèìèðîâàííóþ
2064 isAnim := True;
2065 //e_LogWritefln('006: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2066 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2067 //e_LogWritefln('007: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2068 end;
2069 end;
2071 // Îíà ñóùåñòâóåò. Çàíîñèì åå ID â ñïèñîê ïàíåëè
2072 if ok then
2073 begin
2075 for c := 0 to High(Textures) do
2076 begin
2077 if (Textures[c].TextureName = TexName) then
2078 begin
2079 SetLength(AddTextures, Length(AddTextures)+1);
2080 AddTextures[High(AddTextures)].Texture := c;
2081 AddTextures[High(AddTextures)].Anim := isAnim;
2082 break;
2083 end;
2084 end;
2086 if (TextNameHash <> nil) and TextNameHash.get(toLowerCase1251(TexName), c) then
2087 begin
2088 SetLength(AddTextures, Length(AddTextures)+1);
2089 AddTextures[High(AddTextures)].Texture := c;
2090 AddTextures[High(AddTextures)].Anim := isAnim;
2091 end;
2092 end;
2093 end
2094 else
2095 begin
2096 if k = NNF_NAME_EQUALS then
2097 begin
2098 // Çàíîñèì òåêóùóþ òåêñòóðó íà ñâîå ìåñòî
2099 SetLength(AddTextures, Length(AddTextures)+1);
2100 AddTextures[High(AddTextures)].Texture := rec.tagInt; // internal texture number, not map index
2101 AddTextures[High(AddTextures)].Anim := texrec.Anim;
2102 CurTex := High(AddTextures);
2103 ok := true;
2104 end
2105 else // NNF_NO_NAME
2106 begin
2107 ok := false;
2108 end;
2109 end;
2110 end; // while ok...
2112 ok := true;
2113 end; // if ok - åñòü ñìåæíûå òåêñòóðû
2114 end; // if ok - ññûëàþòñÿ òðèããåðû
2116 if not ok then
2117 begin
2118 // Çàíîñèì òîëüêî òåêóùóþ òåêñòóðó
2119 SetLength(AddTextures, 1);
2120 AddTextures[0].Texture := rec.tagInt; // internal texture number, not map index
2121 AddTextures[0].Anim := false;
2122 if (texrec <> nil) then AddTextures[0].Anim := texrec.Anim;
2123 CurTex := 0;
2124 end;
2126 //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);
2128 //e_LogWritefln('PANADD: pannum=%s', [pannum]);
2130 // Ñîçäàåì ïàíåëü è çàïîìèíàåì åå GUID
2131 //e_LogWritefln('new panel; tcount=%s; curtex=%s', [Length(AddTextures), CurTex]);
2132 PanelID := CreatePanel(rec, AddTextures, CurTex);
2133 //e_LogWritefln('panel #%s of type %s got guid #%s', [pannum, rec.PanelType, PanelID]);
2134 rec.userPanelId := PanelID; // remember game panel id, we'll fix triggers later
2136 // setup lifts
2137 moveSpeed := rec.moveSpeed;
2138 //moveStart := rec.moveStart;
2139 //moveEnd := rec.moveEnd;
2140 //moveActive := rec['move_active'].value;
2141 if not moveSpeed.isZero then
2142 begin
2143 SetLength(gMovingWallIds, Length(gMovingWallIds)+1);
2144 gMovingWallIds[High(gMovingWallIds)] := PanelID;
2145 //e_LogWritefln('found moving panel ''%s'' (idx=%s; id=%s)', [rec.id, pannum, PanelID]);
2146 end;
2148 //e_LogWritefln('PANEND: pannum=%s', [pannum]);
2150 g_Game_StepLoading();
2151 end;
2152 end;
2154 // ×èíèì ID'û ïàíåëåé, êîòîðûå èñïîëüçóþòñÿ â òðèããåðàõ
2155 for b := 0 to High(TriggersTable) do
2156 begin
2157 if (TriggersTable[b].texPanel <> nil) then TriggersTable[b].texPanelIdx := TriggersTable[b].texPanel.userPanelId;
2158 if (TriggersTable[b].actPanel <> nil) then TriggersTable[b].actPanelIdx := TriggersTable[b].actPanel.userPanelId;
2159 end;
2161 // create map grid, init other grids (for monsters, for example)
2162 e_WriteLog('Creating map grid', TMsgType.Notify);
2163 mapCreateGrid();
2165 // Åñëè íå LoadState, òî ñîçäàåì òðèããåðû
2166 if (triggers <> nil) and (panels <> nil) and (not gLoadGameMode) then
2167 begin
2168 e_LogWritefln(' Creating triggers (%d)...', [triggers.count]);
2169 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_TRIGGERS], 0, False);
2170 // Óêàçûâàåì òèï ïàíåëè, åñëè åñòü
2171 trignum := -1;
2172 for rec in triggers do
2173 begin
2174 Inc(trignum);
2175 tgpid := TriggersTable[trignum].actPanelIdx;
2176 //e_LogWritefln('creating trigger #%s; texpantype=%s; shotpantype=%s (%d,%d)', [trignum, b, c, TriggersTable[trignum].texPanIdx, TriggersTable[trignum].ShotPanelIdx]);
2177 TriggersTable[trignum].tnum := trignum;
2178 TriggersTable[trignum].id := CreateTrigger(trignum, rec, TriggersTable[trignum].texPanelIdx, tgpid);
2179 end;
2180 end;
2182 //FIXME: use hashtable!
2183 for pan in panByGUID do
2184 begin
2185 if (pan.endPosTrigId >= 0) and (pan.endPosTrigId < Length(TriggersTable)) then
2186 begin
2187 pan.endPosTrigId := TriggersTable[pan.endPosTrigId].id;
2188 end;
2189 if (pan.endSizeTrigId >= 0) and (pan.endSizeTrigId < Length(TriggersTable)) then
2190 begin
2191 pan.endSizeTrigId := TriggersTable[pan.endSizeTrigId].id;
2192 end;
2193 end;
2195 // Çàãðóçêà ïðåäìåòîâ
2196 e_WriteLog(' Loading items...', TMsgType.Notify);
2197 g_Game_SetLoadingText(_lc[I_LOAD_ITEMS], 0, False);
2199 // Åñëè íå LoadState, òî ñîçäàåì ïðåäìåòû
2200 if (items <> nil) and not gLoadGameMode then
2201 begin
2202 e_WriteLog(' Spawning items...', TMsgType.Notify);
2203 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_ITEMS], 0, False);
2204 for rec in items do CreateItem(rec);
2205 end;
2207 // Çàãðóçêà îáëàñòåé
2208 e_WriteLog(' Loading areas...', TMsgType.Notify);
2209 g_Game_SetLoadingText(_lc[I_LOAD_AREAS], 0, False);
2211 // Åñëè íå LoadState, òî ñîçäàåì îáëàñòè
2212 if areas <> nil then
2213 begin
2214 e_WriteLog(' Creating areas...', TMsgType.Notify);
2215 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_AREAS], 0, False);
2216 for rec in areas do CreateArea(rec);
2217 end;
2219 // Çàãðóçêà ìîíñòðîâ
2220 e_WriteLog(' Loading monsters...', TMsgType.Notify);
2221 g_Game_SetLoadingText(_lc[I_LOAD_MONSTERS], 0, False);
2223 gTotalMonsters := 0;
2225 // Åñëè íå LoadState, òî ñîçäàåì ìîíñòðîâ
2226 if (monsters <> nil) and not gLoadGameMode then
2227 begin
2228 e_WriteLog(' Spawning monsters...', TMsgType.Notify);
2229 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_MONSTERS], 0, False);
2230 for rec in monsters do CreateMonster(rec);
2231 end;
2233 //gCurrentMap := mapReader; // this will be our current map now
2234 gCurrentMapFileName := Res;
2235 //mapReader := nil;
2237 // Çàãðóçêà íåáà
2238 if (gMapInfo.SkyName <> '') then
2239 begin
2240 e_WriteLog(' Loading sky: ' + gMapInfo.SkyName, TMsgType.Notify);
2241 g_Game_SetLoadingText(_lc[I_LOAD_SKY], 0, False);
2242 if gTextureFilter then TEXTUREFILTER := GL_LINEAR else TEXTUREFILTER := GL_NEAREST;
2243 try
2244 s := e_GetResourcePath(WadDirs, gMapInfo.SkyName, g_ExtractWadName(Res));
2245 if g_Texture_CreateWAD(BackID, s) then
2246 g_Game_SetupScreenSize
2247 else
2248 g_FatalError(Format(_lc[I_GAME_ERROR_SKY], [s]))
2249 finally
2250 TEXTUREFILTER := GL_NEAREST;
2251 end;
2252 end;
2254 // Çàãðóçêà ìóçûêè
2255 ok := False;
2256 if gMapInfo.MusicName <> '' then
2257 begin
2258 e_WriteLog(' Loading music: ' + gMapInfo.MusicName, TMsgType.Notify);
2259 g_Game_SetLoadingText(_lc[I_LOAD_MUSIC], 0, False);
2261 s := e_GetResourcePath(WadDirs, gMapInfo.MusicName, g_ExtractWadName(Res));
2262 if g_Sound_CreateWADEx(gMapInfo.MusicName, s, True) then
2263 ok := True
2264 else
2265 g_FatalError(Format(_lc[I_GAME_ERROR_MUSIC], [s]));
2266 end;
2268 // Îñòàëüíûå óñòàíâêè
2269 CreateDoorMap();
2270 CreateLiftMap();
2272 g_Items_Init();
2273 g_Weapon_Init();
2274 g_Monsters_Init();
2276 // Åñëè íå LoadState, òî ñîçäàåì êàðòó ñòîëêíîâåíèé:
2277 if not gLoadGameMode then g_GFX_Init();
2279 // Ñáðîñ ëîêàëüíûõ ìàññèâîâ:
2280 mapTextureList := nil;
2281 panels := nil;
2282 items := nil;
2283 areas := nil;
2284 triggers := nil;
2285 TriggersTable := nil;
2286 AddTextures := nil;
2288 // Âêëþ÷àåì ìóçûêó, åñëè ýòî íå çàãðóçêà:
2289 if ok and (not gLoadGameMode) then
2290 begin
2291 gMusic.SetByName(gMapInfo.MusicName);
2292 gMusic.Play();
2293 end
2294 else
2295 begin
2296 gMusic.SetByName('');
2297 end;
2299 stt := getTimeMicro()-stt;
2300 e_LogWritefln('map loaded in %s.%s milliseconds', [Integer(stt div 1000), Integer(stt mod 1000)]);
2301 mapOk := true;
2302 finally
2303 sfsGCEnable(); // enable releasing unused volumes
2304 //mapReader.Free();
2305 e_UnpressAllKeys; // why not?
2306 if not mapOk then
2307 begin
2308 gCurrentMap.Free();
2309 gCurrentMap := nil;
2310 gCurrentMapFileName := '';
2311 end;
2312 end;
2314 compactExtResList();
2315 e_WriteLog('Done loading map.', TMsgType.Notify);
2316 Result := True;
2317 end;
2320 function g_Map_GetMapInfo(Res: String): TMapInfo;
2321 var
2322 WAD: TWADFile;
2323 mapReader: TDynRecord;
2324 //Header: TMapHeaderRec_1;
2325 FileName: String;
2326 Data: Pointer;
2327 Len: Integer;
2328 begin
2329 FillChar(Result, SizeOf(Result), 0);
2330 FileName := g_ExtractWadName(Res);
2332 WAD := TWADFile.Create();
2333 if not WAD.ReadFile(FileName) then
2334 begin
2335 WAD.Free();
2336 Exit;
2337 end;
2339 //k8: it ignores path again
2340 if not WAD.GetMapResource(g_ExtractFileName(Res), Data, Len) then
2341 begin
2342 WAD.Free();
2343 Exit;
2344 end;
2346 WAD.Free();
2348 try
2349 mapReader := g_Map_ParseMap(Data, Len);
2350 except
2351 mapReader := nil;
2352 FreeMem(Data);
2353 exit;
2354 end;
2356 FreeMem(Data);
2358 if (mapReader = nil) then exit;
2360 if (mapReader.Width > 0) and (mapReader.Height > 0) then
2361 begin
2362 Result.Name := mapReader.MapName;
2363 Result.Description := mapReader.MapDesc;
2364 Result.Map := Res;
2365 Result.Author := mapReader.MapAuthor;
2366 Result.Height := mapReader.Height;
2367 Result.Width := mapReader.Width;
2368 end
2369 else
2370 begin
2371 g_Console_Add(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]), True);
2372 //ZeroMemory(@Header, SizeOf(Header));
2373 Result.Name := _lc[I_GAME_ERROR_MAP_SELECT];
2374 Result.Description := _lc[I_GAME_ERROR_MAP_SELECT];
2375 Result.Map := Res;
2376 Result.Author := '';
2377 Result.Height := 0;
2378 Result.Width := 0;
2379 end;
2381 mapReader.Free();
2382 end;
2384 function g_Map_GetMapsList(WADName: string): SSArray;
2385 var
2386 WAD: TWADFile;
2387 a: Integer;
2388 ResList: SSArray;
2389 begin
2390 Result := nil;
2391 WAD := TWADFile.Create();
2392 if not WAD.ReadFile(WADName) then
2393 begin
2394 WAD.Free();
2395 Exit;
2396 end;
2397 ResList := WAD.GetMapResources();
2398 if ResList <> nil then
2399 begin
2400 for a := 0 to High(ResList) do
2401 begin
2402 SetLength(Result, Length(Result)+1);
2403 Result[High(Result)] := ResList[a];
2404 end;
2405 end;
2406 WAD.Free();
2407 end;
2409 function g_Map_Exist(Res: string): Boolean;
2410 var
2411 WAD: TWADFile;
2412 FileName, mnn: string;
2413 ResList: SSArray;
2414 a: Integer;
2415 begin
2416 Result := False;
2418 FileName := addWadExtension(g_ExtractWadName(Res));
2420 WAD := TWADFile.Create;
2421 if not WAD.ReadFile(FileName) then
2422 begin
2423 WAD.Free();
2424 Exit;
2425 end;
2427 ResList := WAD.GetMapResources();
2428 WAD.Free();
2430 mnn := g_ExtractFileName(Res);
2431 if ResList <> nil then
2432 for a := 0 to High(ResList) do if StrEquCI1251(ResList[a], mnn) then
2433 begin
2434 Result := True;
2435 Exit;
2436 end;
2437 end;
2439 procedure g_Map_Free(freeTextures: Boolean=true);
2440 var
2441 a: Integer;
2443 procedure FreePanelArray(var panels: TPanelArray);
2444 var
2445 i: Integer;
2447 begin
2448 if panels <> nil then
2449 begin
2450 for i := 0 to High(panels) do
2451 panels[i].Free();
2452 panels := nil;
2453 end;
2454 end;
2456 begin
2457 g_GFX_Free();
2458 g_Weapon_Free();
2459 g_Items_Free();
2460 g_Triggers_Free();
2461 g_Monsters_Free();
2463 RespawnPoints := nil;
2464 if FlagPoints[FLAG_RED] <> nil then
2465 begin
2466 Dispose(FlagPoints[FLAG_RED]);
2467 FlagPoints[FLAG_RED] := nil;
2468 end;
2469 if FlagPoints[FLAG_BLUE] <> nil then
2470 begin
2471 Dispose(FlagPoints[FLAG_BLUE]);
2472 FlagPoints[FLAG_BLUE] := nil;
2473 end;
2474 //DOMFlagPoints := nil;
2476 //gDOMFlags := nil;
2478 if (Length(gCurrentMapFileName) <> 0) then
2479 begin
2480 e_LogWritefln('g_Map_Free: previous map was ''%s''...', [gCurrentMapFileName]);
2481 end
2482 else
2483 begin
2484 e_LogWritefln('g_Map_Free: no previous map.', []);
2485 end;
2487 if freeTextures then
2488 begin
2489 e_LogWritefln('g_Map_Free: clearing textures...', []);
2490 if (Textures <> nil) then
2491 begin
2492 for a := 0 to High(Textures) do
2493 begin
2494 if not g_Map_IsSpecialTexture(Textures[a].TextureName) then
2495 begin
2496 if Textures[a].Anim then
2497 begin
2498 g_Frames_DeleteByID(Textures[a].FramesID)
2499 end
2500 else
2501 begin
2502 if (Textures[a].TextureID <> LongWord(TEXTURE_NONE)) then
2503 begin
2504 e_DeleteTexture(Textures[a].TextureID);
2505 end;
2506 end;
2507 end;
2508 end;
2509 Textures := nil;
2510 end;
2511 TextNameHash.Free();
2512 TextNameHash := nil;
2513 BadTextNameHash.Free();
2514 BadTextNameHash := nil;
2515 gCurrentMapFileName := '';
2516 gCurrentMap.Free();
2517 gCurrentMap := nil;
2518 end;
2520 panByGUID := nil;
2522 FreePanelArray(gWalls);
2523 FreePanelArray(gRenderBackgrounds);
2524 FreePanelArray(gRenderForegrounds);
2525 FreePanelArray(gWater);
2526 FreePanelArray(gAcid1);
2527 FreePanelArray(gAcid2);
2528 FreePanelArray(gSteps);
2529 FreePanelArray(gLifts);
2530 FreePanelArray(gBlockMon);
2531 gMovingWallIds := nil;
2533 if BackID <> DWORD(-1) then
2534 begin
2535 gBackSize.X := 0;
2536 gBackSize.Y := 0;
2537 e_DeleteTexture(BackID);
2538 BackID := DWORD(-1);
2539 end;
2541 g_Game_StopAllSounds(False);
2542 gMusic.FreeSound();
2543 g_Sound_Delete(gMapInfo.MusicName);
2545 gMapInfo.Name := '';
2546 gMapInfo.Description := '';
2547 gMapInfo.MusicName := '';
2548 gMapInfo.Height := 0;
2549 gMapInfo.Width := 0;
2551 gDoorMap := nil;
2552 gLiftMap := nil;
2553 end;
2555 procedure g_Map_Update();
2556 var
2557 a, d, j: Integer;
2558 m: Word;
2559 s: String;
2560 b: Byte;
2562 procedure UpdatePanelArray(var panels: TPanelArray);
2563 var
2564 i: Integer;
2566 begin
2567 for i := 0 to High(panels) do panels[i].Update();
2568 end;
2570 begin
2571 if g_dbgpan_mplat_step then g_dbgpan_mplat_active := true;
2573 UpdatePanelArray(gWalls);
2574 UpdatePanelArray(gRenderBackgrounds);
2575 UpdatePanelArray(gRenderForegrounds);
2576 UpdatePanelArray(gWater);
2577 UpdatePanelArray(gAcid1);
2578 UpdatePanelArray(gAcid2);
2579 UpdatePanelArray(gSteps);
2581 if g_dbgpan_mplat_step then begin g_dbgpan_mplat_step := false; g_dbgpan_mplat_active := false; end;
2583 if gGameSettings.GameMode = GM_CTF then
2584 begin
2585 for a := FLAG_RED to FLAG_BLUE do
2586 begin
2587 if not (gFlags[a].State in [FLAG_STATE_NONE, FLAG_STATE_CAPTURED]) then
2588 begin
2589 with gFlags[a] do
2590 begin
2591 if gFlags[a].Animation <> nil then gFlags[a].Animation.Update();
2593 Obj.oldX := Obj.X;
2594 Obj.oldY := Obj.Y;
2596 m := g_Obj_Move(@Obj, True, True);
2598 NeedSend := NeedSend or (Obj.X <> Obj.oldX) or (Obj.Y <> Obj.oldY);
2600 if gTime mod (GAME_TICK*2) <> 0 then Continue;
2602 // Ñîïðîòèâëåíèå âîçäóõà
2603 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
2605 // Òàéìàóò ïîòåðÿííîãî ôëàãà, ëèáî îí âûïàë çà êàðòó
2606 if ((Count = 0) or ByteBool(m and MOVE_FALLOUT)) and g_Game_IsServer then
2607 begin
2608 g_Map_ResetFlag(a);
2609 gFlags[a].CaptureTime := 0;
2610 if a = FLAG_RED then
2611 s := _lc[I_PLAYER_FLAG_RED]
2612 else
2613 s := _lc[I_PLAYER_FLAG_BLUE];
2614 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
2616 if (((gPlayer1 <> nil) and (((gPlayer1.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer1.Team = TEAM_BLUE) and (a = FLAG_BLUE))))
2617 or ((gPlayer2 <> nil) and (((gPlayer2.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer2.Team = TEAM_BLUE) and (a = FLAG_BLUE))))) then
2618 b := 0
2619 else
2620 b := 1;
2622 if not sound_ret_flag[b].IsPlaying() then
2623 sound_ret_flag[b].Play();
2625 if g_Game_IsNet then
2626 MH_SEND_FlagEvent(FLAG_STATE_RETURNED, a, 0);
2627 Continue;
2628 end;
2630 if Count > 0 then Count -= 1;
2632 // Èãðîê áåðåò ôëàã
2633 if gPlayers <> nil then
2634 begin
2635 j := Random(Length(gPlayers)) - 1;
2636 for d := 0 to High(gPlayers) do
2637 begin
2638 Inc(j);
2639 if j > High(gPlayers) then j := 0;
2640 if gPlayers[j] <> nil then
2641 begin
2642 if gPlayers[j].alive and g_Obj_Collide(@Obj, @gPlayers[j].Obj) then
2643 begin
2644 if gPlayers[j].GetFlag(a) then Break;
2645 end;
2646 end;
2647 end;
2648 end;
2649 end;
2650 end;
2651 end;
2652 end;
2653 end;
2656 // old algo
2657 procedure g_Map_DrawPanels (PanelType: Word; hasAmbient: Boolean; constref ambColor: TDFColor);
2659 procedure DrawPanels (constref panels: TPanelArray; drawDoors: Boolean=False);
2660 var
2661 idx: Integer;
2662 begin
2663 if (panels <> nil) then
2664 begin
2665 // alas, no visible set
2666 for idx := 0 to High(panels) do
2667 begin
2668 if not (drawDoors xor panels[idx].Door) then panels[idx].Draw(hasAmbient, ambColor);
2669 end;
2670 end;
2671 end;
2673 begin
2674 case PanelType of
2675 PANEL_WALL: DrawPanels(gWalls);
2676 PANEL_CLOSEDOOR: DrawPanels(gWalls, True);
2677 PANEL_BACK: DrawPanels(gRenderBackgrounds);
2678 PANEL_FORE: DrawPanels(gRenderForegrounds);
2679 PANEL_WATER: DrawPanels(gWater);
2680 PANEL_ACID1: DrawPanels(gAcid1);
2681 PANEL_ACID2: DrawPanels(gAcid2);
2682 PANEL_STEP: DrawPanels(gSteps);
2683 end;
2684 end;
2687 // new algo
2688 procedure g_Map_CollectDrawPanels (x0, y0, wdt, hgt: Integer);
2689 var
2690 mwit: PPanel;
2691 it: TPanelGrid.Iter;
2692 begin
2693 dplClear();
2694 it := mapGrid.forEachInAABB(x0, y0, wdt, hgt, GridDrawableMask);
2695 for mwit in it do if (((mwit^.tag and GridTagDoor) <> 0) = mwit^.Door) then gDrawPanelList.insert(mwit^);
2696 it.release();
2697 // list will be rendered in `g_game.DrawPlayer()`
2698 end;
2701 procedure g_Map_DrawPanelShadowVolumes (lightX: Integer; lightY: Integer; radius: Integer);
2702 var
2703 mwit: PPanel;
2704 it: TPanelGrid.Iter;
2705 begin
2706 it := mapGrid.forEachInAABB(lightX-radius, lightY-radius, radius*2, radius*2, (GridTagWall or GridTagDoor));
2707 for mwit in it do mwit^.DrawShadowVolume(lightX, lightY, radius);
2708 it.release();
2709 end;
2712 procedure g_Map_DrawBack(dx, dy: Integer);
2713 begin
2714 if gDrawBackGround and (BackID <> DWORD(-1)) then
2715 e_DrawSize(BackID, dx, dy, 0, False, False, gBackSize.X, gBackSize.Y)
2716 else
2717 e_Clear(GL_COLOR_BUFFER_BIT, 0, 0, 0);
2718 end;
2720 function g_Map_CollidePanelOld(X, Y: Integer; Width, Height: Word;
2721 PanelType: Word; b1x3: Boolean=false): Boolean;
2722 var
2723 a, h: Integer;
2724 begin
2725 Result := False;
2727 if WordBool(PanelType and PANEL_WALL) then
2728 if gWalls <> nil then
2729 begin
2730 h := High(gWalls);
2732 for a := 0 to h do
2733 if gWalls[a].Enabled and
2734 g_Collide(X, Y, Width, Height,
2735 gWalls[a].X, gWalls[a].Y,
2736 gWalls[a].Width, gWalls[a].Height) then
2737 begin
2738 Result := True;
2739 Exit;
2740 end;
2741 end;
2743 if WordBool(PanelType and PANEL_WATER) then
2744 if gWater <> nil then
2745 begin
2746 h := High(gWater);
2748 for a := 0 to h do
2749 if g_Collide(X, Y, Width, Height,
2750 gWater[a].X, gWater[a].Y,
2751 gWater[a].Width, gWater[a].Height) then
2752 begin
2753 Result := True;
2754 Exit;
2755 end;
2756 end;
2758 if WordBool(PanelType and PANEL_ACID1) then
2759 if gAcid1 <> nil then
2760 begin
2761 h := High(gAcid1);
2763 for a := 0 to h do
2764 if g_Collide(X, Y, Width, Height,
2765 gAcid1[a].X, gAcid1[a].Y,
2766 gAcid1[a].Width, gAcid1[a].Height) then
2767 begin
2768 Result := True;
2769 Exit;
2770 end;
2771 end;
2773 if WordBool(PanelType and PANEL_ACID2) then
2774 if gAcid2 <> nil then
2775 begin
2776 h := High(gAcid2);
2778 for a := 0 to h do
2779 if g_Collide(X, Y, Width, Height,
2780 gAcid2[a].X, gAcid2[a].Y,
2781 gAcid2[a].Width, gAcid2[a].Height) then
2782 begin
2783 Result := True;
2784 Exit;
2785 end;
2786 end;
2788 if WordBool(PanelType and PANEL_STEP) then
2789 if gSteps <> nil then
2790 begin
2791 h := High(gSteps);
2793 for a := 0 to h do
2794 if g_Collide(X, Y, Width, Height,
2795 gSteps[a].X, gSteps[a].Y,
2796 gSteps[a].Width, gSteps[a].Height) then
2797 begin
2798 Result := True;
2799 Exit;
2800 end;
2801 end;
2803 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then
2804 if gLifts <> nil then
2805 begin
2806 h := High(gLifts);
2808 for a := 0 to h do
2809 if ((WordBool(PanelType and (PANEL_LIFTUP)) and (gLifts[a].LiftType = LIFTTYPE_UP)) or
2810 (WordBool(PanelType and (PANEL_LIFTDOWN)) and (gLifts[a].LiftType = LIFTTYPE_DOWN)) or
2811 (WordBool(PanelType and (PANEL_LIFTLEFT)) and (gLifts[a].LiftType = LIFTTYPE_LEFT)) or
2812 (WordBool(PanelType and (PANEL_LIFTRIGHT)) and (gLifts[a].LiftType = LIFTTYPE_RIGHT))) and
2813 g_Collide(X, Y, Width, Height,
2814 gLifts[a].X, gLifts[a].Y,
2815 gLifts[a].Width, gLifts[a].Height) then
2816 begin
2817 Result := True;
2818 Exit;
2819 end;
2820 end;
2822 if WordBool(PanelType and PANEL_BLOCKMON) then
2823 if gBlockMon <> nil then
2824 begin
2825 h := High(gBlockMon);
2827 for a := 0 to h do
2828 if ( (not b1x3) or
2829 ((gBlockMon[a].Width + gBlockMon[a].Height) >= 64) ) and
2830 g_Collide(X, Y, Width, Height,
2831 gBlockMon[a].X, gBlockMon[a].Y,
2832 gBlockMon[a].Width, gBlockMon[a].Height) then
2833 begin
2834 Result := True;
2835 Exit;
2836 end;
2837 end;
2838 end;
2840 function g_Map_CollideLiquid_TextureOld(X, Y: Integer; Width, Height: Word): DWORD;
2841 var
2842 texid: DWORD;
2844 function checkPanels (constref panels: TPanelArray): Boolean;
2845 var
2846 a: Integer;
2847 begin
2848 result := false;
2849 if panels = nil then exit;
2850 for a := 0 to High(panels) do
2851 begin
2852 if g_Collide(X, Y, Width, Height, panels[a].X, panels[a].Y, panels[a].Width, panels[a].Height) then
2853 begin
2854 result := true;
2855 texid := panels[a].GetTextureID();
2856 exit;
2857 end;
2858 end;
2859 end;
2861 begin
2862 texid := LongWord(TEXTURE_NONE);
2863 result := texid;
2864 if not checkPanels(gWater) then
2865 if not checkPanels(gAcid1) then
2866 if not checkPanels(gAcid2) then exit;
2867 result := texid;
2868 end;
2871 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word; PanelType: Word; b1x3: Boolean): Boolean;
2872 const
2873 SlowMask = GridTagLift or GridTagBlockMon;
2875 function checker (pan: TPanel; tag: Integer): Boolean;
2876 begin
2878 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
2879 begin
2880 result := pan.Enabled;
2881 exit;
2882 end;
2885 if ((tag and GridTagLift) <> 0) then
2886 begin
2887 result :=
2888 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2889 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2890 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2891 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2892 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2893 exit;
2894 end;
2896 if ((tag and GridTagBlockMon) <> 0) then
2897 begin
2898 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2899 exit;
2900 end;
2902 // other shit
2903 //result := g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2904 result := true; // i found her!
2905 end;
2907 var
2908 tagmask: Integer = 0;
2909 mwit: PPanel;
2910 it: TPanelGrid.Iter;
2911 pan: TPanel;
2912 begin
2913 result := false;
2914 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
2915 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
2916 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
2917 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
2918 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
2919 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
2920 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
2922 if (tagmask = 0) then exit; // just in case
2924 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('*solids');
2925 if gdbg_map_use_accel_coldet then
2926 begin
2927 if ((tagmask and SlowMask) <> 0) then
2928 begin
2929 // slow
2930 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask);
2931 for mwit in it do
2932 begin
2933 pan := mwit^;
2934 if ((pan.tag and GridTagLift) <> 0) then
2935 begin
2936 result :=
2937 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2938 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2939 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2940 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2941 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2942 end
2943 else if ((pan.tag and GridTagBlockMon) <> 0) then
2944 begin
2945 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2946 end
2947 else
2948 begin
2949 // other shit
2950 result := true; // i found her!
2951 end;
2952 if (result) then break;
2953 end;
2954 end
2955 else
2956 begin
2957 // fast
2958 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask, false, true); // return first hit
2959 result := (it.length > 0);
2960 end;
2961 it.release();
2962 end
2963 else
2964 begin
2965 result := g_Map_CollidePanelOld(X, Y, Width, Height, PanelType, b1x3);
2966 end;
2967 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2968 end;
2971 // returns `true` if we need to stop
2972 function liquidChecker (pan: TPanel; var texid: DWORD; var cctype: Integer): Boolean; inline;
2973 begin
2974 result := false;
2975 //if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2)) = 0) then exit;
2976 // check priorities
2977 case cctype of
2978 0: if ((pan.tag and GridTagWater) = 0) then exit; // allowed: water
2979 1: if ((pan.tag and (GridTagWater or GridTagAcid1)) = 0) then exit; // allowed: water, acid1
2980 //2: if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2) = 0) then exit; // allowed: water, acid1, acid2
2981 end;
2982 // collision?
2983 //if not g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height) then exit;
2984 // yeah
2985 texid := pan.GetTextureID();
2986 // water? water has the highest priority, so stop right here
2987 if ((pan.tag and GridTagWater) <> 0) then begin cctype := 0; result := true; exit; end;
2988 // acid2?
2989 if ((pan.tag and GridTagAcid2) <> 0) then cctype := 2;
2990 // acid1?
2991 if ((pan.tag and GridTagAcid1) <> 0) then cctype := 1;
2992 end;
2994 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
2995 var
2996 cctype: Integer = 3; // priority: 0: water was hit, 1: acid1 was hit, 2: acid2 was hit; 3: nothing was hit
2997 mwit: PPanel;
2998 it: TPanelGrid.Iter;
2999 begin
3000 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('liquids');
3001 if gdbg_map_use_accel_coldet then
3002 begin
3003 result := LongWord(TEXTURE_NONE);
3004 it := mapGrid.forEachInAABB(X, Y, Width, Height, (GridTagWater or GridTagAcid1 or GridTagAcid2));
3005 for mwit in it do if (liquidChecker(mwit^, result, cctype)) then break;
3006 it.release();
3007 end
3008 else
3009 begin
3010 result := g_Map_CollideLiquid_TextureOld(X, Y, Width, Height);
3011 end;
3012 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
3013 end;
3016 procedure g_Map_EnableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_EnableWallGUID(gWalls[ID].guid); end;
3017 procedure g_Map_DisableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_DisableWallGUID(gWalls[ID].guid); end;
3018 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer); begin if (ID < Length(gLifts)) then g_Map_SetLiftGUID(gLifts[ID].guid, t); end;
3021 procedure g_Map_EnableWallGUID (pguid: Integer);
3022 var
3023 pan: TPanel;
3024 begin
3025 //pan := gWalls[ID];
3026 pan := g_Map_PanelByGUID(pguid);
3027 if (pan = nil) then exit;
3028 if pan.Enabled and mapGrid.proxyEnabled[pan.proxyId] then exit;
3030 pan.Enabled := True;
3031 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, true);
3033 mapGrid.proxyEnabled[pan.proxyId] := true;
3034 //if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := true
3035 //else pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, GridTagDoor);
3037 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3038 // mark platform as interesting
3039 pan.setDirty();
3041 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
3042 //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);
3043 {$ENDIF}
3044 end;
3047 procedure g_Map_DisableWallGUID (pguid: Integer);
3048 var
3049 pan: TPanel;
3050 begin
3051 //pan := gWalls[ID];
3052 pan := g_Map_PanelByGUID(pguid);
3053 if (pan = nil) then exit;
3054 if (not pan.Enabled) and (not mapGrid.proxyEnabled[pan.proxyId]) then exit;
3056 pan.Enabled := False;
3057 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, false);
3059 mapGrid.proxyEnabled[pan.proxyId] := false;
3060 //if (pan.proxyId >= 0) then begin mapGrid.removeBody(pan.proxyId); pan.proxyId := -1; end;
3062 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3063 // mark platform as interesting
3064 pan.setDirty();
3066 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
3067 //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);
3068 {$ENDIF}
3069 end;
3072 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
3073 var
3074 tp: TPanel;
3075 begin
3076 tp := g_Map_PanelByGUID(pguid);
3077 if (tp = nil) then exit;
3078 tp.NextTexture(AnimLoop);
3079 if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelTexture(pguid, AnimLoop);
3080 end;
3083 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
3084 var
3085 pan: TPanel;
3086 begin
3087 //pan := gLifts[ID];
3088 pan := g_Map_PanelByGUID(pguid);
3089 if (pan = nil) then exit;
3090 if not pan.isGLift then exit;
3092 if ({gLifts[ID]}pan.LiftType = t) then exit; //!FIXME!TRIGANY!
3094 with {gLifts[ID]} pan do
3095 begin
3096 LiftType := t;
3098 g_Mark(X, Y, Width, Height, MARK_LIFT, false);
3099 //TODO: make separate lift tags, and change tag here
3101 case LiftType of
3102 LIFTTYPE_UP: g_Mark(X, Y, Width, Height, MARK_LIFTUP);
3103 LIFTTYPE_DOWN: g_Mark(X, Y, Width, Height, MARK_LIFTDOWN);
3104 LIFTTYPE_LEFT: g_Mark(X, Y, Width, Height, MARK_LIFTLEFT);
3105 LIFTTYPE_RIGHT: g_Mark(X, Y, Width, Height, MARK_LIFTRIGHT);
3106 end;
3108 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3109 // mark platform as interesting
3110 pan.setDirty();
3111 end;
3112 end;
3115 function g_Map_GetPoint (PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
3116 var
3117 a: Integer;
3118 PointsArray: Array of TRespawnPoint;
3119 begin
3120 Result := False;
3121 SetLength(PointsArray, 0);
3123 if RespawnPoints = nil then
3124 Exit;
3126 for a := 0 to High(RespawnPoints) do
3127 if RespawnPoints[a].PointType = PointType then
3128 begin
3129 SetLength(PointsArray, Length(PointsArray)+1);
3130 PointsArray[High(PointsArray)] := RespawnPoints[a];
3131 end;
3133 if PointsArray = nil then
3134 Exit;
3136 RespawnPoint := PointsArray[Random(Length(PointsArray))];
3137 Result := True;
3138 end;
3140 function g_Map_GetPointCount(PointType: Byte): Word;
3141 var
3142 a: Integer;
3143 begin
3144 Result := 0;
3146 if RespawnPoints = nil then
3147 Exit;
3149 for a := 0 to High(RespawnPoints) do
3150 if RespawnPoints[a].PointType = PointType then
3151 Result := Result + 1;
3152 end;
3154 function g_Map_GetRandomPointType(): Byte;
3155 begin
3156 if RespawnPoints = nil then
3157 Result := 255
3158 else
3159 Result := RespawnPoints[Random(Length(RespawnPoints))].PointType;
3160 end;
3162 function g_Map_HaveFlagPoints(): Boolean;
3163 begin
3164 Result := (FlagPoints[FLAG_RED] <> nil) and (FlagPoints[FLAG_BLUE] <> nil);
3165 end;
3167 procedure g_Map_ResetFlag(Flag: Byte);
3168 begin
3169 with gFlags[Flag] do
3170 begin
3171 Obj.X := -1000;
3172 Obj.Y := -1000;
3173 Obj.Vel.X := 0;
3174 Obj.Vel.Y := 0;
3175 Direction := TDirection.D_LEFT;
3176 State := FLAG_STATE_NONE;
3177 if FlagPoints[Flag] <> nil then
3178 begin
3179 Obj.X := FlagPoints[Flag]^.X;
3180 Obj.Y := FlagPoints[Flag]^.Y;
3181 Direction := FlagPoints[Flag]^.Direction;
3182 State := FLAG_STATE_NORMAL;
3183 end;
3184 Obj.oldX := Obj.X;
3185 Obj.oldY := Obj.Y;
3186 NeedSend := False; // the event will take care of this
3187 Count := -1;
3188 end;
3189 end;
3191 procedure g_Map_DrawFlags();
3192 var
3193 i, dx: Integer;
3194 tx, ty: Integer;
3195 Mirror: TMirrorType;
3196 begin
3197 if gGameSettings.GameMode <> GM_CTF then
3198 Exit;
3200 for i := FLAG_RED to FLAG_BLUE do
3201 with gFlags[i] do
3202 if State <> FLAG_STATE_CAPTURED then
3203 begin
3204 if State = FLAG_STATE_NONE then
3205 continue;
3207 Obj.lerp(gLerpFactor, tx, ty);
3209 if Direction = TDirection.D_LEFT then
3210 begin
3211 Mirror := TMirrorType.Horizontal;
3212 dx := -1;
3213 end
3214 else
3215 begin
3216 Mirror := TMirrorType.None;
3217 dx := 1;
3218 end;
3220 Animation.Draw(tx+dx, ty+1, Mirror);
3222 if g_debug_Frames then
3223 begin
3224 e_DrawQuad(Obj.X+Obj.Rect.X,
3225 Obj.Y+Obj.Rect.Y,
3226 Obj.X+Obj.Rect.X+Obj.Rect.Width-1,
3227 Obj.Y+Obj.Rect.Y+Obj.Rect.Height-1,
3228 0, 255, 0);
3229 end;
3230 end;
3231 end;
3234 procedure g_Map_SaveState (st: TStream);
3235 var
3236 str: String;
3238 procedure savePanels ();
3239 var
3240 pan: TPanel;
3241 begin
3242 // Ñîõðàíÿåì ïàíåëè
3243 utils.writeInt(st, LongInt(Length(panByGUID)));
3244 for pan in panByGUID do pan.SaveState(st);
3245 end;
3247 procedure saveFlag (flag: PFlag);
3248 var
3249 b: Byte;
3250 begin
3251 utils.writeSign(st, 'FLAG');
3252 utils.writeInt(st, Byte(0)); // version
3253 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3254 utils.writeInt(st, Byte(flag^.RespawnType));
3255 // Ñîñòîÿíèå ôëàãà
3256 utils.writeInt(st, Byte(flag^.State));
3257 // Íàïðàâëåíèå ôëàãà
3258 if flag^.Direction = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
3259 utils.writeInt(st, Byte(b));
3260 // Îáúåêò ôëàãà
3261 Obj_SaveState(st, @flag^.Obj);
3262 end;
3264 begin
3265 savePanels();
3267 // Ñîõðàíÿåì ìóçûêó
3268 utils.writeSign(st, 'MUSI');
3269 utils.writeInt(st, Byte(0));
3270 // Íàçâàíèå ìóçûêè
3271 assert(gMusic <> nil, 'g_Map_SaveState: gMusic = nil');
3272 if gMusic.NoMusic then str := '' else str := gMusic.Name;
3273 utils.writeStr(st, str);
3274 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3275 utils.writeInt(st, LongWord(gMusic.GetPosition()));
3276 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3277 utils.writeBool(st, gMusic.SpecPause);
3279 ///// Ñîõðàíÿåì êîëè÷åñòâî ìîíñòðîâ: /////
3280 utils.writeInt(st, LongInt(gTotalMonsters));
3281 ///// /////
3283 //// Ñîõðàíÿåì ôëàãè, åñëè ýòî CTF: /////
3284 if (gGameSettings.GameMode = GM_CTF) then
3285 begin
3286 // Ôëàã Êðàñíîé êîìàíäû
3287 saveFlag(@gFlags[FLAG_RED]);
3288 // Ôëàã Ñèíåé êîìàíäû
3289 saveFlag(@gFlags[FLAG_BLUE]);
3290 end;
3291 ///// /////
3293 ///// Ñîõðàíÿåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3294 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3295 begin
3296 // Î÷êè Êðàñíîé êîìàíäû
3297 utils.writeInt(st, SmallInt(gTeamStat[TEAM_RED].Score));
3298 // Î÷êè Ñèíåé êîìàíäû
3299 utils.writeInt(st, SmallInt(gTeamStat[TEAM_BLUE].Score));
3300 end;
3301 ///// /////
3302 end;
3305 procedure g_Map_LoadState (st: TStream);
3306 var
3307 dw: DWORD;
3308 str: String;
3309 boo: Boolean;
3311 procedure loadPanels ();
3312 var
3313 pan: TPanel;
3314 begin
3315 // Çàãðóæàåì ïàíåëè
3316 if (Length(panByGUID) <> utils.readLongInt(st)) then raise XStreamError.Create('invalid number of saved panels');
3317 for pan in panByGUID do
3318 begin
3319 pan.LoadState(st);
3320 if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
3321 end;
3322 end;
3324 procedure loadFlag (flag: PFlag);
3325 var
3326 b: Byte;
3327 begin
3328 // Ñèãíàòóðà ôëàãà
3329 if not utils.checkSign(st, 'FLAG') then raise XStreamError.Create('invalid flag signature');
3330 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid flag version');
3331 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3332 flag^.RespawnType := utils.readByte(st);
3333 // Ñîñòîÿíèå ôëàãà
3334 flag^.State := utils.readByte(st);
3335 // Íàïðàâëåíèå ôëàãà
3336 b := utils.readByte(st);
3337 if (b = 1) then flag^.Direction := TDirection.D_LEFT else flag^.Direction := TDirection.D_RIGHT; // b = 2
3338 // Îáúåêò ôëàãà
3339 Obj_LoadState(@flag^.Obj, st);
3340 end;
3342 begin
3343 if (st = nil) then exit;
3345 ///// Çàãðóæàåì ñïèñêè ïàíåëåé: /////
3346 loadPanels();
3347 ///// /////
3349 // Îáíîâëÿåì êàðòó ñòîëêíîâåíèé è ñåòêó
3350 g_GFX_Init();
3351 //mapCreateGrid();
3353 ///// Çàãðóæàåì ìóçûêó: /////
3354 if not utils.checkSign(st, 'MUSI') then raise XStreamError.Create('invalid music signature');
3355 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid music version');
3356 // Íàçâàíèå ìóçûêè
3357 assert(gMusic <> nil, 'g_Map_LoadState: gMusic = nil');
3358 str := utils.readStr(st);
3359 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3360 dw := utils.readLongWord(st);
3361 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3362 boo := utils.readBool(st);
3363 // Çàïóñêàåì ýòó ìóçûêó
3364 gMusic.SetByName(str);
3365 gMusic.SpecPause := boo;
3366 gMusic.Play();
3367 gMusic.Pause(true);
3368 gMusic.SetPosition(dw);
3369 ///// /////
3371 ///// Çàãðóæàåì êîëè÷åñòâî ìîíñòðîâ: /////
3372 gTotalMonsters := utils.readLongInt(st);
3373 ///// /////
3375 //// Çàãðóæàåì ôëàãè, åñëè ýòî CTF: /////
3376 if (gGameSettings.GameMode = GM_CTF) then
3377 begin
3378 // Ôëàã Êðàñíîé êîìàíäû
3379 loadFlag(@gFlags[FLAG_RED]);
3380 // Ôëàã Ñèíåé êîìàíäû
3381 loadFlag(@gFlags[FLAG_BLUE]);
3382 end;
3383 ///// /////
3385 ///// Çàãðóæàåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3386 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3387 begin
3388 // Î÷êè Êðàñíîé êîìàíäû
3389 gTeamStat[TEAM_RED].Score := utils.readSmallInt(st);
3390 // Î÷êè Ñèíåé êîìàíäû
3391 gTeamStat[TEAM_BLUE].Score := utils.readSmallInt(st);
3392 end;
3393 ///// /////
3394 end;
3397 // trace liquid, stepping by `dx` and `dy`
3398 // return last seen liquid coords, and `false` if we're started outside of the liquid
3399 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
3400 const
3401 MaskLiquid = GridTagWater or GridTagAcid1 or GridTagAcid2;
3402 begin
3403 topx := x;
3404 topy := y;
3405 // started outside of the liquid?
3406 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then begin result := false; exit; end;
3407 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then begin result := false; exit; end;
3408 if (dx = 0) and (dy = 0) then begin result := false; exit; end; // sanity check
3409 result := true;
3410 while true do
3411 begin
3412 Inc(x, dx);
3413 Inc(y, dy);
3414 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then exit; // out of the water, just exit
3415 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then exit; // out of the water, just exit
3416 topx := x;
3417 topy := y;
3418 end;
3419 end;
3422 begin
3423 DynWarningCB := mapWarningCB;
3424 end.