DEADSOFTWARE

render: hide panel textures into render
[d2df-sdl.git] / src / game / g_map.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE ../shared/a_modes.inc}
16 {$DEFINE MAP_DEBUG_ENABLED_FLAG}
17 unit g_map;
19 interface
21 uses
22 SysUtils, Classes, mempool,
23 g_base, r_graphics, g_basic, MAPDEF, g_textures,
24 g_phys, utils, g_panel, g_grid, md5, binheap, xprofiler, xparser, xdynrec;
26 type
27 TMapInfo = record
28 Map: String;
29 Name: String;
30 Description: String;
31 Author: String;
32 MusicName: String;
33 SkyName: String;
34 Height: Word;
35 Width: Word;
36 end;
38 PRespawnPoint = ^TRespawnPoint;
39 TRespawnPoint = record
40 X, Y: Integer;
41 Direction: TDirection;
42 PointType: Byte;
43 end;
45 PFlagPoint = ^TFlagPoint;
46 TFlagPoint = TRespawnPoint;
48 PFlag = ^TFlag;
49 TFlag = record
50 Obj: TObj;
51 RespawnType: Byte;
52 State: Byte;
53 Count: Integer;
54 CaptureTime: LongWord;
55 Animation: TAnimation;
56 Direction: TDirection;
57 end;
59 function g_Map_Load(Res: String): Boolean;
60 function g_Map_GetMapInfo(Res: String): TMapInfo;
61 function g_Map_GetMapsList(WADName: String): SSArray;
62 function g_Map_Exist(Res: String): Boolean;
63 procedure g_Map_Free(freeTextures: Boolean=true);
64 procedure g_Map_Update();
66 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
68 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word;
69 PanelType: Word; b1x3: Boolean=false): Boolean;
70 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
72 procedure g_Map_EnableWallGUID (pguid: Integer);
73 procedure g_Map_DisableWallGUID (pguid: Integer);
74 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
76 // HACK!!!
77 procedure g_Map_EnableWall_XXX (ID: DWORD);
78 procedure g_Map_DisableWall_XXX (ID: DWORD);
79 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer);
81 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
83 procedure g_Map_ReAdd_DieTriggers();
84 function g_Map_IsSpecialTexture(Texture: String): Boolean;
86 function g_Map_GetPoint(PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
87 function g_Map_GetPointCount(PointType: Byte): Word;
88 function g_Map_GetRandomPointType(): Byte;
90 function g_Map_HaveFlagPoints(): Boolean;
92 procedure g_Map_ResetFlag(Flag: Byte);
94 procedure g_Map_SaveState (st: TStream);
95 procedure g_Map_LoadState (st: TStream);
97 // returns panel or nil
98 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
99 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
101 // returns panel or nil
102 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
103 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
105 type
106 TForEachPanelCB = function (pan: TPanel): Boolean is nested; // return `true` to stop
108 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
109 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
111 // trace liquid, stepping by `dx` and `dy`
112 // return last seen liquid coords, and `false` if we're started outside of the liquid
113 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
116 // return `true` from `cb` to stop
117 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
119 procedure g_Map_NetSendInterestingPanels (); // yay!
122 procedure g_Map_ProfilersBegin ();
123 procedure g_Map_ProfilersEnd ();
126 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
129 function g_Map_MinX (): Integer; inline;
130 function g_Map_MinY (): Integer; inline;
131 function g_Map_MaxX (): Integer; inline;
132 function g_Map_MaxY (): Integer; inline;
134 const
135 NNF_NO_NAME = 0;
136 NNF_NAME_BEFORE = 1;
137 NNF_NAME_EQUALS = 2;
138 NNF_NAME_AFTER = 3;
140 function g_Texture_NumNameFindStart(name: String): Boolean;
141 function g_Texture_NumNameFindNext(var newName: String): Byte;
143 const
144 RESPAWNPOINT_PLAYER1 = 1;
145 RESPAWNPOINT_PLAYER2 = 2;
146 RESPAWNPOINT_DM = 3;
147 RESPAWNPOINT_RED = 4;
148 RESPAWNPOINT_BLUE = 5;
150 FLAG_NONE = 0;
151 FLAG_RED = 1;
152 FLAG_BLUE = 2;
153 FLAG_DOM = 3;
155 FLAG_STATE_NONE = 0;
156 FLAG_STATE_NORMAL = 1;
157 FLAG_STATE_DROPPED = 2;
158 FLAG_STATE_CAPTURED = 3;
159 FLAG_STATE_SCORED = 4; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
160 FLAG_STATE_RETURNED = 5; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
162 FLAG_TIME = 720; // 20 seconds
164 SKY_STRETCH: Single = 1.5;
166 const
167 GridTagInvalid = 0;
169 (* draw order:
170 PANEL_BACK
171 PANEL_STEP
172 PANEL_WALL
173 PANEL_CLOSEDOOR
174 PANEL_ACID1
175 PANEL_ACID2
176 PANEL_WATER
177 PANEL_FORE
178 *)
179 // sorted by draw priority
180 GridTagBack = 1 shl 0; // gRenderBackgrounds
181 GridTagStep = 1 shl 1; // gSteps
182 GridTagWall = 1 shl 2; // gWalls
183 GridTagDoor = 1 shl 3; // gWalls
184 GridTagAcid1 = 1 shl 4; // gAcid1
185 GridTagAcid2 = 1 shl 5; // gAcid2
186 GridTagWater = 1 shl 6; // gWater
187 GridTagFore = 1 shl 7; // gRenderForegrounds
188 // the following are invisible
189 GridTagLift = 1 shl 8; // gLifts
190 GridTagBlockMon = 1 shl 9; // gBlockMon
192 GridTagSolid = (GridTagWall or GridTagDoor);
193 GridTagObstacle = (GridTagStep or GridTagWall or GridTagDoor);
194 GridTagLiquid = (GridTagAcid1 or GridTagAcid2 or GridTagWater);
196 GridDrawableMask = (GridTagBack or GridTagStep or GridTagWall or GridTagDoor or GridTagAcid1 or GridTagAcid2 or GridTagWater or GridTagFore);
199 type
200 TBinHeapPanelDrawCmp = class
201 public
202 class function less (const a, b: TPanel): Boolean; inline;
203 end;
205 TBinHeapPanelDraw = specialize TBinaryHeapBase<TPanel, TBinHeapPanelDrawCmp>;
207 var
208 gWalls: TPanelArray;
209 gRenderBackgrounds: TPanelArray;
210 gRenderForegrounds: TPanelArray;
211 gWater, gAcid1, gAcid2: TPanelArray;
212 gSteps: TPanelArray;
213 gLifts: TPanelArray;
214 gBlockMon: TPanelArray;
215 gFlags: array [FLAG_RED..FLAG_BLUE] of TFlag;
216 //gDOMFlags: array of TFlag;
217 gMapInfo: TMapInfo;
218 gBackSize: TDFPoint;
219 gDoorMap: array of array of DWORD;
220 gLiftMap: array of array of DWORD;
221 gWADHash: TMD5Digest;
222 BackID: DWORD = DWORD(-1);
223 gExternalResources: array of TDiskFileInfo = nil;
224 gMovingWallIds: array of Integer = nil;
226 gdbg_map_use_accel_render: Boolean = true;
227 gdbg_map_use_accel_coldet: Boolean = true;
228 profMapCollision: TProfiler = nil; //WARNING: FOR DEBUGGING ONLY!
229 gDrawPanelList: TBinHeapPanelDraw = nil; // binary heap of all walls we have to render, populated by `g_Map_CollectDrawPanels()`
231 gCurrentMap: TDynRecord = nil;
232 gCurrentMapFileName: AnsiString = ''; // so we can skip texture reloading
233 gTestMap: String = '';
236 function panelTypeToTag (panelType: Word): Integer; // returns GridTagXXX
239 type
240 TPanelGrid = specialize TBodyGridBase<TPanel>;
242 var
243 mapGrid: TPanelGrid = nil; // DO NOT USE! public for debugging only!
245 var (* private state *)
246 Textures: TLevelTextureArray = nil;
248 implementation
250 uses
251 e_input, e_log, e_res, g_items, g_gfx, g_console,
252 g_weapons, g_game, g_sound, e_sound, CONFIG,
253 g_options, g_triggers, g_player, r_textures, r_animations,
254 Math, g_monsters, g_saveload, g_language, g_netmsg,
255 sfs, xstreams, hashtable, wadreader,
256 g_res_downloader;
258 const
259 FLAGRECT: TRectWH = (X:15; Y:12; Width:33; Height:52);
260 MUSIC_SIGNATURE = $4953554D; // 'MUSI'
261 FLAG_SIGNATURE = $47414C46; // 'FLAG'
264 // ////////////////////////////////////////////////////////////////////////// //
265 procedure mapWarningCB (const msg: AnsiString; line, col: Integer);
266 begin
267 if (line > 0) then
268 begin
269 e_LogWritefln('parse error at (%s,%s): %s', [line, col, msg], TMsgType.Warning);
270 end
271 else
272 begin
273 e_LogWritefln('parse error: %s', [msg], TMsgType.Warning);
274 end;
275 end;
278 // ////////////////////////////////////////////////////////////////////////// //
279 var
280 panByGUID: array of TPanel = nil;
283 // ////////////////////////////////////////////////////////////////////////// //
284 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
285 begin
286 //if (panByGUID = nil) or (not panByGUID.get(aguid, result)) then result := nil;
287 if (aguid >= 0) and (aguid < Length(panByGUID)) then result := panByGUID[aguid] else result := nil;
288 end;
291 // return `true` from `cb` to stop
292 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
293 var
294 pan: TPanel;
295 begin
296 result := nil;
297 if not assigned(cb) then exit;
298 for pan in panByGUID do
299 begin
300 if cb(pan) then begin result := pan; exit; end;
301 end;
302 end;
305 procedure g_Map_NetSendInterestingPanels ();
306 var
307 pan: TPanel;
308 begin
309 if g_Game_IsServer and g_Game_IsNet then
310 begin
311 for pan in panByGUID do
312 begin
313 if pan.gncNeedSend then MH_SEND_PanelState(pan.guid);
314 end;
315 end;
316 end;
319 // ////////////////////////////////////////////////////////////////////////// //
320 function g_Map_MinX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0 else result := 0; end;
321 function g_Map_MinY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0 else result := 0; end;
322 function g_Map_MaxX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0+mapGrid.gridWidth-1 else result := 0; end;
323 function g_Map_MaxY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0+mapGrid.gridHeight-1 else result := 0; end;
326 // ////////////////////////////////////////////////////////////////////////// //
327 var
328 dfmapdef: TDynMapDef = nil;
331 procedure loadMapDefinition ();
332 var
333 pr: TTextParser = nil;
334 st: TStream = nil;
335 WAD: TWADFile = nil;
336 begin
337 if (dfmapdef <> nil) then exit;
339 try
340 e_LogWritefln('parsing "mapdef.txt"...', []);
341 st := e_OpenResourceRO(DataDirs, 'mapdef.txt');
342 e_LogWritefln('found local "mapdef.txt"', []);
343 except
344 st := nil;
345 end;
347 if (st = nil) then
348 begin
349 WAD := TWADFile.Create();
350 if not WAD.ReadFile(GameWAD) then
351 begin
352 //raise Exception.Create('cannot load "game.wad"');
353 st := nil;
354 end
355 else
356 begin
357 st := WAD.openFileStream('mapdef.txt');
358 end;
359 end;
361 try
362 if (st = nil) then
363 begin
364 //raise Exception.Create('cannot open "mapdef.txt"');
365 e_LogWriteln('using default "mapdef.txt"...');
366 pr := TStrTextParser.Create(defaultMapDef);
367 end
368 else
369 begin
370 pr := TFileTextParser.Create(st);
371 end;
372 except on e: Exception do
373 begin
374 e_LogWritefln('something is VERY wrong here! -- ', [e.message]);
375 raise;
376 end;
377 end;
379 try
380 dfmapdef := TDynMapDef.Create(pr);
381 except
382 on e: TDynParseException do
383 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
384 on e: Exception do
385 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [pr.tokLine, pr.tokCol, e.message]);
386 end;
388 st.Free();
389 WAD.Free();
390 end;
393 // ////////////////////////////////////////////////////////////////////////// //
394 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
395 var
396 wst: TSFSMemoryChunkStream = nil;
397 begin
398 result := nil;
399 if (dataLen < 4) then exit;
401 if (dfmapdef = nil) then writeln('need to load mapdef');
402 loadMapDefinition();
403 if (dfmapdef = nil) then raise Exception.Create('internal map loader error');
405 wst := TSFSMemoryChunkStream.Create(data, dataLen);
406 try
407 result := dfmapdef.parseMap(wst);
408 except
409 on e: TDynParseException do
410 begin
411 e_LogWritefln('ERROR at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
412 wst.Free();
413 result := nil;
414 exit;
415 end;
416 on e: Exception do
417 begin
418 e_LogWritefln('ERROR: %s', [e.message]);
419 wst.Free();
420 result := nil;
421 exit;
422 end;
423 end;
425 //e_LogWriteln('map parsed.');
426 end;
429 // ////////////////////////////////////////////////////////////////////////// //
430 var
431 NNF_PureName: String; // Èìÿ òåêñòóðû áåç öèôð â êîíöå
432 NNF_PureExt: String; // extension postfix
433 NNF_FirstNum: Integer; // ×èñëî ó íà÷àëüíîé òåêñòóðû
434 NNF_CurrentNum: Integer; // Ñëåäóþùåå ÷èñëî ó òåêñòóðû
437 function g_Texture_NumNameFindStart(name: String): Boolean;
438 var
439 i, j: Integer;
441 begin
442 Result := False;
443 NNF_PureName := '';
444 NNF_PureExt := '';
445 NNF_FirstNum := -1;
446 NNF_CurrentNum := -1;
448 for i := Length(name) downto 1 do
449 if (name[i] = '_') then // "_" - ñèìâîë íà÷àëà íîìåðíîãî ïîñòôèêñà
450 begin
451 if i = Length(name) then
452 begin // Íåò öèôð â êîíöå ñòðîêè
453 Exit;
454 end
455 else
456 begin
457 j := i + 1;
458 while (j <= Length(name)) and (name[j] <> '.') do inc(j);
459 NNF_PureName := Copy(name, 1, i);
460 NNF_PureExt := Copy(name, j);
461 name := Copy(name, i + 1, j - i - 1);
462 Break;
463 end;
464 end;
466 // Íå ïåðåâåñòè â ÷èñëî:
467 if not TryStrToInt(name, NNF_FirstNum) then
468 Exit;
470 NNF_CurrentNum := 0;
472 Result := True;
473 end;
476 function g_Texture_NumNameFindNext(var newName: String): Byte;
477 begin
478 if (NNF_PureName = '') or (NNF_CurrentNum < 0) then
479 begin
480 newName := '';
481 Result := NNF_NO_NAME;
482 Exit;
483 end;
485 newName := NNF_PureName + IntToStr(NNF_CurrentNum) + NNF_PureExt;
487 if NNF_CurrentNum < NNF_FirstNum then
488 Result := NNF_NAME_BEFORE
489 else
490 if NNF_CurrentNum > NNF_FirstNum then
491 Result := NNF_NAME_AFTER
492 else
493 Result := NNF_NAME_EQUALS;
495 Inc(NNF_CurrentNum);
496 end;
499 // ////////////////////////////////////////////////////////////////////////// //
500 function panelTypeToTag (panelType: Word): Integer;
501 begin
502 case panelType of
503 PANEL_WALL: result := GridTagWall; // gWalls
504 PANEL_OPENDOOR, PANEL_CLOSEDOOR: result := GridTagDoor; // gWalls
505 PANEL_BACK: result := GridTagBack; // gRenderBackgrounds
506 PANEL_FORE: result := GridTagFore; // gRenderForegrounds
507 PANEL_WATER: result := GridTagWater; // gWater
508 PANEL_ACID1: result := GridTagAcid1; // gAcid1
509 PANEL_ACID2: result := GridTagAcid2; // gAcid2
510 PANEL_STEP: result := GridTagStep; // gSteps
511 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: result := GridTagLift; // gLifts -- this is for all lifts
512 PANEL_BLOCKMON: result := GridTagBlockMon; // gBlockMon -- this is for all blockmons
513 else result := GridTagInvalid;
514 end;
515 end;
518 class function TBinHeapPanelDrawCmp.less (const a, b: TPanel): Boolean; inline;
519 begin
520 if (a.tag < b.tag) then begin result := true; exit; end;
521 if (a.tag > b.tag) then begin result := false; exit; end;
522 result := (a.arrIdx < b.arrIdx);
523 end;
525 var
526 TextNameHash: THashStrInt = nil; // key: texture name; value: index in `Textures`
527 BadTextNameHash: THashStrInt = nil; // set; so we won't spam with non-existing texture messages
528 RespawnPoints: array of TRespawnPoint;
529 FlagPoints: array[FLAG_RED..FLAG_BLUE] of PFlagPoint;
530 //DOMFlagPoints: Array of TFlagPoint;
533 procedure g_Map_ProfilersBegin ();
534 begin
535 if (profMapCollision = nil) then profMapCollision := TProfiler.Create('COLSOLID', g_profile_history_size);
536 if (profMapCollision <> nil) then profMapCollision.mainBegin(g_profile_collision);
537 // create sections
538 if g_profile_collision and (profMapCollision <> nil) then
539 begin
540 profMapCollision.sectionBegin('*solids');
541 profMapCollision.sectionEnd();
542 profMapCollision.sectionBegin('liquids');
543 profMapCollision.sectionEnd();
544 end;
545 end;
547 procedure g_Map_ProfilersEnd ();
548 begin
549 if (profMapCollision <> nil) then profMapCollision.mainEnd();
550 end;
553 // wall index in `gWalls` or -1
554 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
555 var
556 ex, ey: Integer;
557 begin
558 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, (GridTagWall or GridTagDoor));
559 if (result <> nil) then
560 begin
561 if (hitx <> nil) then hitx^ := ex;
562 if (hity <> nil) then hity^ := ey;
563 end
564 else
565 begin
566 if (hitx <> nil) then hitx^ := x1;
567 if (hity <> nil) then hity^ := y1;
568 end;
569 end;
571 // returns panel or nil
572 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
573 var
574 ex, ey: Integer;
575 begin
576 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, tag);
577 if (result <> nil) then
578 begin
579 if (hitx <> nil) then hitx^ := ex;
580 if (hity <> nil) then hity^ := ey;
581 end
582 else
583 begin
584 if (hitx <> nil) then hitx^ := x1;
585 if (hity <> nil) then hity^ := y1;
586 end;
587 end;
590 function xxPanAtPointChecker (pan: TPanel; panelType: Word): Boolean; inline;
591 begin
592 if ((pan.tag and GridTagLift) <> 0) then
593 begin
594 // stop if the lift of the right type
595 result :=
596 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
597 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
598 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
599 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT)));
600 exit;
601 end;
602 result := true; // otherwise, stop anyway, 'cause `forEachAtPoint()` is guaranteed to call this only for correct panels
603 end;
605 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
606 var
607 tagmask: Integer = 0;
608 mwit: PPanel;
609 it: TPanelGrid.Iter;
610 begin
611 result := false;
613 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
614 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
615 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
616 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
617 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
618 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
619 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
621 if (tagmask = 0) then exit;// just in case
623 if ((tagmask and GridTagLift) <> 0) then
624 begin
625 // slow
626 it := mapGrid.forEachAtPoint(x, y, tagmask);
627 for mwit in it do if (xxPanAtPointChecker(mwit^, PanelType)) then begin result := true; break; end;
628 end
629 else
630 begin
631 // fast
632 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true);
633 result := (it.length <> 0); // firsthit
634 end;
635 it.release();
636 end;
639 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
640 var
641 it: TPanelGrid.Iter;
642 begin
643 result := nil;
644 if (tagmask = 0) then exit;
645 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true); // firsthit
646 if (it.length <> 0) then result := it.first^;
647 it.release();
648 end;
651 function g_Map_IsSpecialTexture(Texture: String): Boolean;
652 begin
653 Result := (Texture = TEXTURE_NAME_WATER) or
654 (Texture = TEXTURE_NAME_ACID1) or
655 (Texture = TEXTURE_NAME_ACID2);
656 end;
658 procedure CreateDoorMap();
659 var
660 PanelArray: Array of record
661 X, Y: Integer;
662 Width, Height: Word;
663 Active: Boolean;
664 PanelID: DWORD;
665 end;
666 a, b, c, m, i, len: Integer;
667 ok: Boolean;
668 begin
669 if gWalls = nil then
670 Exit;
672 i := 0;
673 len := 128;
674 SetLength(PanelArray, len);
676 for a := 0 to High(gWalls) do
677 if gWalls[a].Door then
678 begin
679 PanelArray[i].X := gWalls[a].X;
680 PanelArray[i].Y := gWalls[a].Y;
681 PanelArray[i].Width := gWalls[a].Width;
682 PanelArray[i].Height := gWalls[a].Height;
683 PanelArray[i].Active := True;
684 PanelArray[i].PanelID := a;
686 i := i + 1;
687 if i = len then
688 begin
689 len := len + 128;
690 SetLength(PanelArray, len);
691 end;
692 end;
694 // Íåò äâåðåé:
695 if i = 0 then
696 begin
697 PanelArray := nil;
698 Exit;
699 end;
701 SetLength(gDoorMap, 0);
703 g_Game_SetLoadingText(_lc[I_LOAD_DOOR_MAP], i-1, False);
705 for a := 0 to i-1 do
706 if PanelArray[a].Active then
707 begin
708 PanelArray[a].Active := False;
709 m := Length(gDoorMap);
710 SetLength(gDoorMap, m+1);
711 SetLength(gDoorMap[m], 1);
712 gDoorMap[m, 0] := PanelArray[a].PanelID;
713 ok := True;
715 while ok do
716 begin
717 ok := False;
719 for b := 0 to i-1 do
720 if PanelArray[b].Active then
721 for c := 0 to High(gDoorMap[m]) do
722 if {((gRenderWalls[PanelArray[b].RenderPanelID].TextureID = gRenderWalls[gDoorMap[m, c]].TextureID) or
723 gRenderWalls[PanelArray[b].RenderPanelID].Hide or gRenderWalls[gDoorMap[m, c]].Hide) and}
724 g_CollideAround(PanelArray[b].X, PanelArray[b].Y,
725 PanelArray[b].Width, PanelArray[b].Height,
726 gWalls[gDoorMap[m, c]].X,
727 gWalls[gDoorMap[m, c]].Y,
728 gWalls[gDoorMap[m, c]].Width,
729 gWalls[gDoorMap[m, c]].Height) then
730 begin
731 PanelArray[b].Active := False;
732 SetLength(gDoorMap[m],
733 Length(gDoorMap[m])+1);
734 gDoorMap[m, High(gDoorMap[m])] := PanelArray[b].PanelID;
735 ok := True;
736 Break;
737 end;
738 end;
740 g_Game_StepLoading();
741 end;
743 PanelArray := nil;
744 end;
746 procedure CreateLiftMap();
747 var
748 PanelArray: Array of record
749 X, Y: Integer;
750 Width, Height: Word;
751 Active: Boolean;
752 end;
753 a, b, c, len, i, j: Integer;
754 ok: Boolean;
755 begin
756 if gLifts = nil then
757 Exit;
759 len := Length(gLifts);
760 SetLength(PanelArray, len);
762 for a := 0 to len-1 do
763 begin
764 PanelArray[a].X := gLifts[a].X;
765 PanelArray[a].Y := gLifts[a].Y;
766 PanelArray[a].Width := gLifts[a].Width;
767 PanelArray[a].Height := gLifts[a].Height;
768 PanelArray[a].Active := True;
769 end;
771 SetLength(gLiftMap, len);
772 i := 0;
774 g_Game_SetLoadingText(_lc[I_LOAD_LIFT_MAP], len-1, False);
776 for a := 0 to len-1 do
777 if PanelArray[a].Active then
778 begin
779 PanelArray[a].Active := False;
780 SetLength(gLiftMap[i], 32);
781 j := 0;
782 gLiftMap[i, j] := a;
783 ok := True;
785 while ok do
786 begin
787 ok := False;
788 for b := 0 to len-1 do
789 if PanelArray[b].Active then
790 for c := 0 to j do
791 if g_CollideAround(PanelArray[b].X,
792 PanelArray[b].Y,
793 PanelArray[b].Width,
794 PanelArray[b].Height,
795 PanelArray[gLiftMap[i, c]].X,
796 PanelArray[gLiftMap[i, c]].Y,
797 PanelArray[gLiftMap[i, c]].Width,
798 PanelArray[gLiftMap[i, c]].Height) then
799 begin
800 PanelArray[b].Active := False;
801 j := j+1;
802 if j > High(gLiftMap[i]) then
803 SetLength(gLiftMap[i],
804 Length(gLiftMap[i])+32);
806 gLiftMap[i, j] := b;
807 ok := True;
809 Break;
810 end;
811 end;
813 SetLength(gLiftMap[i], j+1);
814 i := i+1;
816 g_Game_StepLoading();
817 end;
819 SetLength(gLiftMap, i);
821 PanelArray := nil;
822 end;
824 function CreatePanel (PanelRec: TDynRecord; AddTextures: TAddTextureArray; CurTex: Integer): Integer;
825 var
826 len: Integer;
827 panels: ^TPanelArray;
828 pan: TPanel;
829 pguid: Integer;
830 begin
831 Result := -1;
833 case PanelRec.PanelType of
834 PANEL_WALL, PANEL_OPENDOOR, PANEL_CLOSEDOOR: panels := @gWalls;
835 PANEL_BACK: panels := @gRenderBackgrounds;
836 PANEL_FORE: panels := @gRenderForegrounds;
837 PANEL_WATER: panels := @gWater;
838 PANEL_ACID1: panels := @gAcid1;
839 PANEL_ACID2: panels := @gAcid2;
840 PANEL_STEP: panels := @gSteps;
841 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: panels := @gLifts;
842 PANEL_BLOCKMON: panels := @gBlockMon;
843 else exit;
844 end;
846 len := Length(panels^);
847 SetLength(panels^, len+1);
849 pguid := Length(panByGUID);
850 SetLength(panByGUID, pguid+1); //FIXME!
851 pan := TPanel.Create(PanelRec, AddTextures, CurTex, Textures, pguid);
852 assert(pguid >= 0);
853 assert(pguid < Length(panByGUID));
854 panByGUID[pguid] := pan;
855 panels^[len] := pan;
856 pan.arrIdx := len;
857 pan.proxyId := -1;
858 pan.tag := panelTypeToTag(PanelRec.PanelType);
860 PanelRec.user['panel_guid'] := pguid;
862 //result := len;
863 result := pguid;
864 end;
867 function CreateNullTexture(RecName: String): Integer;
868 begin
869 RecName := toLowerCase1251(RecName);
870 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
871 if TextNameHash.get(RecName, result) then exit; // i found her!
873 SetLength(Textures, Length(Textures) + 1);
874 Textures[High(Textures)].TextureName := RecName;
875 Textures[High(Textures)].FullName := '';
876 Textures[High(Textures)].Anim := False;
877 Result := High(Textures);
878 TextNameHash.put(RecName, result);
879 end;
882 function extractWadName (resourceName: string): string;
883 var
884 posN: Integer;
885 begin
886 posN := Pos(':', resourceName);
887 if posN > 0 then
888 Result:= Copy(resourceName, 0, posN-1)
889 else
890 Result := '';
891 end;
894 procedure addResToExternalResList (res: AnsiString);
895 var
896 uname: AnsiString;
897 f: Integer;
898 fi: TDiskFileInfo;
899 begin
900 if g_Game_IsClient or not g_Game_IsNet then exit;
901 if (length(res) = 0) then exit; // map wad
902 //res := extractWadName(res);
903 //if (length(res) = 0) then exit; // map wad
904 uname := toLowerCase1251(res);
905 // do not add duplicates
906 for f := 0 to High(gExternalResources) do
907 begin
908 if (gExternalResources[f].userName = uname) then exit;
909 end;
910 //writeln('***(000) addResToExternalResList: res=[', res, ']');
911 // add new resource
912 fi.userName := uname;
913 if not findFileCI(res) then exit;
914 //writeln('***(001) addResToExternalResList: res=[', res, ']');
915 fi.diskName := res;
916 if (not GetDiskFileInfo(res, fi)) then
917 begin
918 fi.tag := -1;
919 end
920 else
921 begin
922 //writeln('***(002) addResToExternalResList: res=[', res, ']');
923 fi.tag := 0; // non-zero means "cannot caclucate hash"
924 try
925 fi.hash := MD5File(fi.diskName);
926 except
927 fi.tag := -1;
928 end;
929 end;
930 //e_LogWritefln('addext: res=[%s]; uname=[%s]; diskName=[%s]', [res, fi.userName, fi.diskName]);
931 SetLength(gExternalResources, length(gExternalResources)+1);
932 gExternalResources[High(gExternalResources)] := fi;
933 end;
936 procedure compactExtResList ();
937 var
938 src, dest: Integer;
939 begin
940 src := 0;
941 dest := 0;
942 for src := 0 to High(gExternalResources) do
943 begin
944 if (gExternalResources[src].tag = 0) then
945 begin
946 // copy it
947 if (dest <> src) then gExternalResources[dest] := gExternalResources[src];
948 Inc(dest);
949 end;
950 end;
951 if (dest <> length(gExternalResources)) then SetLength(gExternalResources, dest);
952 end;
955 function GetReplacementWad (WadName: AnsiString): AnsiString;
956 begin
957 result := '';
958 if WadName <> '' then
959 begin
960 result := WadName;
961 if g_Game_IsClient then result := g_Res_FindReplacementWad(WadName);
962 if (result = WadName) then result := e_FindWad(WadDirs, result)
963 end;
964 end;
967 procedure generateExternalResourcesList (map: TDynRecord);
968 begin
969 SetLength(gExternalResources, 0);
970 addResToExternalResList(GetReplacementWad(g_ExtractWadName(map.MusicName)));
971 addResToExternalResList(GetReplacementWad(g_ExtractWadName(map.SkyName)));
972 end;
975 function CreateTexture (RecName: AnsiString; Map: string; log: Boolean): Integer;
976 var
977 WAD: TWADFile;
978 WADName, ResName: String;
979 ResData: Pointer;
980 ResLen: Integer;
981 begin
982 RecName := toLowerCase1251(RecName);
983 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
984 if TextNameHash.get(RecName, result) then
985 begin
986 // i found her!
987 //e_LogWritefln('texture ''%s'' already loaded (%s)', [RecName, result]);
988 exit;
989 end;
991 Result := -1;
993 if (BadTextNameHash <> nil) and BadTextNameHash.has(RecName) then
994 exit; // don't do it again and again
996 case RecName of
997 TEXTURE_NAME_WATER, TEXTURE_NAME_ACID1, TEXTURE_NAME_ACID2:
998 begin
999 SetLength(Textures, Length(Textures) + 1);
1000 Textures[High(Textures)].FullName := RecName;
1001 Textures[High(Textures)].TextureName := RecName;
1002 Textures[High(Textures)].Anim := False;
1003 Result := High(Textures);
1004 TextNameHash.put(RecName, result);
1005 end
1006 else
1007 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1008 if (WADName <> '') then
1009 addResToExternalResList(WADName);
1010 if WADName = '' then
1011 WADName := Map;
1012 ResName := g_ExtractFilePathName(RecName);
1014 // !!! we have a better way to check that resource exists?
1015 WAD := TWADFile.Create();
1016 if WAD.ReadFile(WadName) and WAD.GetResource(ResName, ResData, ResLen, log) then
1017 begin
1018 FreeMem(ResData);
1019 SetLength(Textures, Length(Textures) + 1);
1020 Textures[High(Textures)].FullName := WADName + ':' + ResName;
1021 Textures[High(Textures)].TextureName := RecName;
1022 Textures[High(Textures)].Anim := False;
1023 Result := High(Textures);
1024 TextNameHash.put(RecName, result);
1025 end;
1026 WAD.Free;
1027 end;
1028 end;
1031 function CreateAnimTexture(RecName: String; Map: string; log: Boolean): Integer;
1032 var
1033 WAD: TWADFile;
1034 TextureWAD: PChar = nil;
1035 TextData: Pointer = nil;
1036 cfg: TConfig = nil;
1037 WADName: String;
1038 ResLength: Integer;
1039 f: Integer;
1040 begin
1041 RecName := toLowerCase1251(RecName);
1042 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
1043 if TextNameHash.get(RecName, result) then
1044 begin
1045 // i found her!
1046 //e_LogWritefln('animated texture ''%s'' already loaded (%s)', [RecName, result]);
1047 exit;
1048 end;
1050 result := -1;
1052 //e_LogWritefln('*** Loading animated texture "%s"', [RecName]);
1054 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1055 if BadTextNameHash.get(RecName, f) then
1056 begin
1057 //e_WriteLog(Format('no animation texture %s (don''t worry)', [RecName]), MSG_NOTIFY);
1058 exit;
1059 end;
1061 // ×èòàåì WAD-ðåñóðñ àíèì.òåêñòóðû èç WAD'à â ïàìÿòü:
1062 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1063 if (WADName <> '') then addResToExternalResList(WADName);
1064 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
1066 WAD := TWADFile.Create();
1067 try
1068 WAD.ReadFile(WADName);
1069 if not WAD.GetResource(g_ExtractFilePathName(RecName), TextureWAD, ResLength, log) then
1070 begin
1071 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1072 if log and (not BadTextNameHash.get(RecName, f)) then
1073 begin
1074 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1075 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1076 end;
1077 BadTextNameHash.put(RecName, -1);
1078 exit;
1079 end;
1080 WAD.FreeWAD();
1082 // íåò, ýòî ñóïåðìåí!
1083 if not WAD.ReadMemory(TextureWAD, ResLength) then
1084 begin
1085 e_WriteLog(Format('Animated texture WAD file "%s" is invalid', [RecName]), TMsgType.Warning);
1086 BadTextNameHash.put(RecName, -1);
1087 exit;
1088 end;
1090 // ×èòàåì INI-ðåñóðñ àíèì. òåêñòóðû è çàïîìèíàåì åãî óñòàíîâêè:
1091 if not WAD.GetResource('TEXT/ANIM', TextData, ResLength) then
1092 begin
1093 e_WriteLog(Format('Animated texture file "%s" has invalid INI', [RecName]), TMsgType.Warning);
1094 BadTextNameHash.put(RecName, -1);
1095 exit;
1096 end;
1098 WAD.Free();
1099 WAD := nil;
1101 cfg := TConfig.CreateMem(TextData, ResLength);
1102 if cfg <> nil then
1103 begin
1104 SetLength(Textures, Length(Textures) + 1);
1105 Textures[High(Textures)].TextureName := RecName;
1106 Textures[High(Textures)].FullName := WadName + ':' + g_ExtractFilePathName(RecName);
1107 Textures[High(Textures)].Anim := True;
1108 Textures[High(Textures)].FramesCount := cfg.ReadInt('', 'framecount', 0);
1109 Textures[High(Textures)].Speed := cfg.ReadInt('', 'waitcount', 0);
1110 result := High(Textures);
1111 TextNameHash.put(RecName, result);
1112 cfg.Free();
1113 cfg := nil;
1114 end;
1115 finally
1116 WAD.Free();
1117 cfg.Free();
1118 if (TextureWAD <> nil) then FreeMem(TextureWAD);
1119 if (TextData <> nil) then FreeMem(TextData);
1120 end;
1121 end;
1123 procedure CreateItem(Item: TDynRecord);
1124 begin
1125 if g_Game_IsClient then Exit;
1127 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) and
1128 ByteBool(Item.Options and ITEM_OPTION_ONLYDM) then
1129 Exit;
1131 g_Items_Create(Item.X, Item.Y, Item.ItemType, ByteBool(Item.Options and ITEM_OPTION_FALL),
1132 gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF, GM_COOP]);
1133 end;
1135 procedure CreateArea(Area: TDynRecord);
1136 var
1137 a: Integer;
1138 id: DWORD = 0;
1139 begin
1140 case Area.AreaType of
1141 AREA_DMPOINT, AREA_PLAYERPOINT1, AREA_PLAYERPOINT2,
1142 AREA_REDTEAMPOINT, AREA_BLUETEAMPOINT:
1143 begin
1144 SetLength(RespawnPoints, Length(RespawnPoints)+1);
1145 with RespawnPoints[High(RespawnPoints)] do
1146 begin
1147 X := Area.X;
1148 Y := Area.Y;
1149 Direction := TDirection(Area.Direction);
1151 case Area.AreaType of
1152 AREA_DMPOINT: PointType := RESPAWNPOINT_DM;
1153 AREA_PLAYERPOINT1: PointType := RESPAWNPOINT_PLAYER1;
1154 AREA_PLAYERPOINT2: PointType := RESPAWNPOINT_PLAYER2;
1155 AREA_REDTEAMPOINT: PointType := RESPAWNPOINT_RED;
1156 AREA_BLUETEAMPOINT: PointType := RESPAWNPOINT_BLUE;
1157 end;
1158 end;
1159 end;
1161 AREA_REDFLAG, AREA_BLUEFLAG:
1162 begin
1163 if Area.AreaType = AREA_REDFLAG then a := FLAG_RED else a := FLAG_BLUE;
1165 if FlagPoints[a] <> nil then Exit;
1167 New(FlagPoints[a]);
1169 with FlagPoints[a]^ do
1170 begin
1171 X := Area.X-FLAGRECT.X;
1172 Y := Area.Y-FLAGRECT.Y;
1173 Direction := TDirection(Area.Direction);
1174 end;
1176 with gFlags[a] do
1177 begin
1178 case a of
1179 FLAG_RED: g_Frames_Get(id, 'FRAMES_FLAG_RED');
1180 FLAG_BLUE: g_Frames_Get(id, 'FRAMES_FLAG_BLUE');
1181 end;
1183 Animation := TAnimation.Create(id, True, 8);
1184 Obj.Rect := FLAGRECT;
1186 g_Map_ResetFlag(a);
1187 end;
1188 end;
1190 AREA_DOMFLAG:
1191 begin
1192 {SetLength(DOMFlagPoints, Length(DOMFlagPoints)+1);
1193 with DOMFlagPoints[High(DOMFlagPoints)] do
1194 begin
1195 X := Area.X;
1196 Y := Area.Y;
1197 Direction := TDirection(Area.Direction);
1198 end;
1200 g_Map_CreateFlag(DOMFlagPoints[High(DOMFlagPoints)], FLAG_DOM, FLAG_STATE_NORMAL);}
1201 end;
1202 end;
1203 end;
1205 function CreateTrigger (amapIdx: Integer; Trigger: TDynRecord; atpanid, atrigpanid: Integer): Integer;
1206 var
1207 _trigger: TTrigger;
1208 tp: TPanel;
1209 begin
1210 result := -1;
1211 if g_Game_IsClient and not (Trigger.TriggerType in [TRIGGER_SOUND, TRIGGER_MUSIC]) then Exit;
1213 with _trigger do
1214 begin
1215 mapId := Trigger.id;
1216 mapIndex := amapIdx;
1217 X := Trigger.X;
1218 Y := Trigger.Y;
1219 Width := Trigger.Width;
1220 Height := Trigger.Height;
1221 Enabled := Trigger.Enabled;
1222 TexturePanelGUID := atpanid;
1223 TriggerType := Trigger.TriggerType;
1224 ActivateType := Trigger.ActivateType;
1225 Keys := Trigger.Keys;
1226 trigPanelGUID := atrigpanid;
1227 // HACK: used in TPanel.CanChangeTexture. maybe there's a better way?
1228 if TexturePanelGUID <> -1 then
1229 begin
1230 tp := g_Map_PanelByGUID(TexturePanelGUID);
1231 if (tp <> nil) then tp.hasTexTrigger := True;
1232 end;
1233 end;
1235 result := Integer(g_Triggers_Create(_trigger, Trigger));
1236 end;
1238 procedure CreateMonster(monster: TDynRecord);
1239 var
1240 a: Integer;
1241 mon: TMonster;
1242 begin
1243 if g_Game_IsClient then Exit;
1245 if (gGameSettings.GameType = GT_SINGLE)
1246 or LongBool(gGameSettings.Options and GAME_OPTION_MONSTERS) then
1247 begin
1248 mon := g_Monsters_Create(monster.MonsterType, monster.X, monster.Y, TDirection(monster.Direction));
1250 if gTriggers <> nil then
1251 begin
1252 for a := 0 to High(gTriggers) do
1253 begin
1254 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1255 begin
1256 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1257 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1258 end;
1259 end;
1260 end;
1262 if monster.MonsterType <> MONSTER_BARREL then Inc(gTotalMonsters);
1263 end;
1264 end;
1266 procedure g_Map_ReAdd_DieTriggers();
1268 function monsDieTrig (mon: TMonster): Boolean;
1269 var
1270 a: Integer;
1271 //tw: TStrTextWriter;
1272 begin
1273 result := false; // don't stop
1274 mon.ClearTriggers();
1275 for a := 0 to High(gTriggers) do
1276 begin
1277 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1278 begin
1279 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1281 tw := TStrTextWriter.Create();
1282 try
1283 gTriggers[a].trigData.writeTo(tw);
1284 e_LogWritefln('=== trigger #%s ==='#10'%s'#10'---', [a, tw.str]);
1285 finally
1286 tw.Free();
1287 end;
1289 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1290 end;
1291 end;
1292 end;
1294 begin
1295 if g_Game_IsClient then Exit;
1297 g_Mons_ForEach(monsDieTrig);
1298 end;
1300 procedure mapCreateGrid ();
1301 var
1302 mapX0: Integer = $3fffffff;
1303 mapY0: Integer = $3fffffff;
1304 mapX1: Integer = -$3fffffff;
1305 mapY1: Integer = -$3fffffff;
1307 procedure calcBoundingBox (constref panels: TPanelArray);
1308 var
1309 idx: Integer;
1310 pan: TPanel;
1311 begin
1312 for idx := 0 to High(panels) do
1313 begin
1314 pan := panels[idx];
1315 if not pan.visvalid then continue;
1316 if (pan.Width < 1) or (pan.Height < 1) then continue;
1317 if (mapX0 > pan.x0) then mapX0 := pan.x0;
1318 if (mapY0 > pan.y0) then mapY0 := pan.y0;
1319 if (mapX1 < pan.x1) then mapX1 := pan.x1;
1320 if (mapY1 < pan.y1) then mapY1 := pan.y1;
1321 end;
1322 end;
1324 procedure addPanelsToGrid (constref panels: TPanelArray);
1325 var
1326 idx: Integer;
1327 pan: TPanel;
1328 newtag: Integer;
1329 begin
1330 //tag := panelTypeToTag(tag);
1331 for idx := 0 to High(panels) do
1332 begin
1333 pan := panels[idx];
1334 if not pan.visvalid then continue;
1335 if (pan.proxyId <> -1) then
1336 begin
1337 {$IF DEFINED(D2F_DEBUG)}
1338 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);
1339 {$ENDIF}
1340 continue;
1341 end;
1342 case pan.PanelType of
1343 PANEL_WALL: newtag := GridTagWall;
1344 PANEL_OPENDOOR, PANEL_CLOSEDOOR: newtag := GridTagDoor;
1345 PANEL_BACK: newtag := GridTagBack;
1346 PANEL_FORE: newtag := GridTagFore;
1347 PANEL_WATER: newtag := GridTagWater;
1348 PANEL_ACID1: newtag := GridTagAcid1;
1349 PANEL_ACID2: newtag := GridTagAcid2;
1350 PANEL_STEP: newtag := GridTagStep;
1351 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: newtag := GridTagLift;
1352 PANEL_BLOCKMON: newtag := GridTagBlockMon;
1353 else continue; // oops
1354 end;
1355 pan.tag := newtag;
1357 pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, newtag);
1358 // "enabled" flag has meaning only for doors and walls (engine assumes it); but meh...
1359 mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
1360 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
1362 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
1363 begin
1364 e_WriteLog(Format('INSERTED wall #%d(%d) enabled (%d)', [Integer(idx), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId])]), MSG_NOTIFY);
1365 end;
1367 {$ENDIF}
1368 end;
1369 end;
1371 begin
1372 mapGrid.Free();
1373 mapGrid := nil;
1375 calcBoundingBox(gWalls);
1376 calcBoundingBox(gRenderBackgrounds);
1377 calcBoundingBox(gRenderForegrounds);
1378 calcBoundingBox(gWater);
1379 calcBoundingBox(gAcid1);
1380 calcBoundingBox(gAcid2);
1381 calcBoundingBox(gSteps);
1382 calcBoundingBox(gLifts);
1383 calcBoundingBox(gBlockMon);
1385 e_LogWritefln('map dimensions: (%d,%d)-(%d,%d); editor size:(0,0)-(%d,%d)', [mapX0, mapY0, mapX1, mapY1, gMapInfo.Width, gMapInfo.Height]);
1387 if (mapX0 > 0) then mapX0 := 0;
1388 if (mapY0 > 0) then mapY0 := 0;
1390 if (mapX1 < gMapInfo.Width-1) then mapX1 := gMapInfo.Width-1;
1391 if (mapY1 < gMapInfo.Height-1) then mapY1 := gMapInfo.Height-1;
1393 mapGrid := TPanelGrid.Create(mapX0-128, mapY0-128, mapX1-mapX0+1+128*2, mapY1-mapY0+1+128*2);
1394 //mapGrid := TPanelGrid.Create(0, 0, gMapInfo.Width, gMapInfo.Height);
1396 addPanelsToGrid(gWalls);
1397 addPanelsToGrid(gRenderBackgrounds);
1398 addPanelsToGrid(gRenderForegrounds);
1399 addPanelsToGrid(gWater);
1400 addPanelsToGrid(gAcid1);
1401 addPanelsToGrid(gAcid2);
1402 addPanelsToGrid(gSteps);
1403 addPanelsToGrid(gLifts); // it doesn't matter which LIFT type is used here
1404 addPanelsToGrid(gBlockMon);
1406 mapGrid.dumpStats();
1408 g_Mons_InitTree(mapGrid.gridX0, mapGrid.gridY0, mapGrid.gridWidth, mapGrid.gridHeight);
1409 end;
1412 function g_Map_Load(Res: String): Boolean;
1413 const
1414 DefaultMusRes = 'Standart.wad:STDMUS\MUS1';
1415 DefaultSkyRes = 'Standart.wad:STDSKY\SKY0';
1416 type
1417 PTRec = ^TTRec;
1418 TTRec = record
1419 //TexturePanel: Integer;
1420 tnum: Integer;
1421 id: Integer;
1422 trigrec: TDynRecord;
1423 // texture pane;
1424 texPanelIdx: Integer;
1425 texPanel: TDynRecord;
1426 // "action" panel
1427 actPanelIdx: Integer;
1428 actPanel: TDynRecord;
1429 end;
1430 var
1431 WAD, TestWAD: TWADFile;
1432 //mapReader: TDynRecord = nil;
1433 mapTextureList: TDynField = nil; //TTexturesRec1Array; tagInt: texture index
1434 panels: TDynField = nil; //TPanelsRec1Array;
1435 items: TDynField = nil; //TItemsRec1Array;
1436 monsters: TDynField = nil; //TMonsterRec1Array;
1437 areas: TDynField = nil; //TAreasRec1Array;
1438 triggers: TDynField = nil; //TTriggersRec1Array;
1439 b, c, k: Integer;
1440 PanelID: DWORD;
1441 AddTextures: TAddTextureArray;
1442 TriggersTable: array of TTRec;
1443 FileName, mapResName, TexName, s: AnsiString;
1444 Data: Pointer;
1445 Len: Integer;
1446 ok, isAnim: Boolean;
1447 CurTex, ntn: Integer;
1448 rec, texrec: TDynRecord;
1449 pttit: PTRec;
1450 pannum, trignum, cnt, tgpid: Integer;
1451 stt: UInt64;
1452 moveSpeed{, moveStart, moveEnd}: TDFPoint;
1453 //moveActive: Boolean;
1454 pan: TPanel;
1455 mapOk: Boolean = false;
1456 usedTextures: THashStrInt = nil; // key: mapTextureList
1457 begin
1458 mapGrid.Free();
1459 mapGrid := nil;
1460 TestWAD := nil;
1461 Data := nil;
1463 //gCurrentMap.Free();
1464 //gCurrentMap := nil;
1466 panByGUID := nil;
1468 Result := False;
1469 gMapInfo.Map := Res;
1470 TriggersTable := nil;
1471 //mapReader := nil;
1473 sfsGCDisable(); // temporary disable removing of temporary volumes
1474 try
1475 // Çàãðóçêà WAD (åñëè ó íàñ íåò óæå çàãðóæåíîé êàðòû)
1476 if (gCurrentMap = nil) then
1477 begin
1478 FileName := g_ExtractWadName(Res);
1479 e_LogWritefln('Loading map WAD [%s] (res=[%s])', [FileName, Res], TMsgType.Notify);
1480 g_Game_SetLoadingText(_lc[I_LOAD_WAD_FILE], 0, False);
1482 WAD := TWADFile.Create();
1483 if not WAD.ReadFile(FileName) then
1484 begin
1485 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [FileName]));
1486 WAD.Free();
1487 Exit;
1488 end;
1490 if gTestMap <> '' then
1491 begin
1492 s := g_ExtractWadName(gTestMap);
1493 TestWAD := TWADFile.Create();
1494 if not TestWAD.ReadFile(s) then
1495 begin
1496 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_WAD], [s]));
1497 TestWAD.Free();
1498 TestWAD := nil;
1499 end;
1500 end;
1502 if TestWAD <> nil then
1503 begin
1504 mapResName := g_ExtractFileName(gTestMap);
1505 if not TestWAD.GetMapResource(mapResName, Data, Len) then
1506 begin
1507 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1508 Data := nil;
1509 end else
1510 e_WriteLog('Using test map: '+gTestMap, TMsgType.Notify);
1511 TestWAD.Free();
1512 TestWAD := nil;
1513 end;
1515 if Data = nil then
1516 begin
1517 //k8: why loader ignores path here?
1518 mapResName := g_ExtractFileName(Res);
1519 if not WAD.GetMapResource(mapResName, Data, Len) then
1520 begin
1521 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1522 WAD.Free();
1523 Exit;
1524 end;
1525 end;
1527 WAD.Free();
1529 if (Len < 4) then
1530 begin
1531 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1532 FreeMem(Data);
1533 exit;
1534 end;
1536 // Çàãðóçêà êàðòû:
1537 e_LogWritefln('Loading map: %s', [mapResName], TMsgType.Notify);
1538 g_Game_SetLoadingText(_lc[I_LOAD_MAP], 0, False);
1540 stt := getTimeMicro();
1542 try
1543 gCurrentMap := g_Map_ParseMap(Data, Len);
1544 except
1545 gCurrentMap.Free();
1546 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]));
1547 FreeMem(Data);
1548 gCurrentMapFileName := '';
1549 Exit;
1550 end;
1552 FreeMem(Data);
1554 if (gCurrentMap = nil) then
1555 begin
1556 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1557 gCurrentMapFileName := '';
1558 exit;
1559 end;
1560 end
1561 else
1562 begin
1563 stt := getTimeMicro();
1564 end;
1566 //gCurrentMap := mapReader;
1568 generateExternalResourcesList(gCurrentMap);
1569 mapTextureList := gCurrentMap['texture'];
1570 // get all other lists here too
1571 panels := gCurrentMap['panel'];
1572 triggers := gCurrentMap['trigger'];
1573 items := gCurrentMap['item'];
1574 areas := gCurrentMap['area'];
1575 monsters := gCurrentMap['monster'];
1577 // Çàãðóçêà îïèñàíèÿ êàðòû:
1578 e_WriteLog(' Reading map info...', TMsgType.Notify);
1579 g_Game_SetLoadingText(_lc[I_LOAD_MAP_HEADER], 0, False);
1581 with gMapInfo do
1582 begin
1583 Name := gCurrentMap.MapName;
1584 Description := gCurrentMap.MapDesc;
1585 Author := gCurrentMap.MapAuthor;
1586 MusicName := gCurrentMap.MusicName;
1587 SkyName := gCurrentMap.SkyName;
1588 Height := gCurrentMap.Height;
1589 Width := gCurrentMap.Width;
1590 end;
1592 // Çàãðóçêà òåêñòóð:
1593 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], 0, False);
1594 // Äîáàâëåíèå òåêñòóð â Textures[]:
1595 if (mapTextureList <> nil) and (mapTextureList.count > 0) then
1596 begin
1597 e_WriteLog(' Loading textures:', TMsgType.Notify);
1598 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], mapTextureList.count-1, False);
1600 // find used textures
1601 usedTextures := THashStrInt.Create();
1602 try
1603 if (panels <> nil) and (panels.count > 0) then
1604 begin
1605 for rec in panels do
1606 begin
1607 texrec := rec.TextureRec;
1608 if (texrec <> nil) then usedTextures.put(toLowerCase1251(texrec.Resource), 42);
1609 end;
1610 end;
1612 cnt := -1;
1613 for rec in mapTextureList do
1614 begin
1615 Inc(cnt);
1616 if not usedTextures.has(toLowerCase1251(rec.Resource)) then
1617 begin
1618 rec.tagInt := -1; // just in case
1619 e_LogWritefln(' Unused texture #%d: %s', [cnt, rec.Resource]);
1620 end
1621 else
1622 begin
1623 {$IF DEFINED(D2F_DEBUG_TXLOAD)}
1624 e_LogWritefln(' Loading texture #%d: %s', [cnt, rec.Resource]);
1625 {$ENDIF}
1626 //if g_Map_IsSpecialTexture(s) then e_WriteLog(' SPECIAL!', MSG_NOTIFY);
1627 if rec.Anim then
1628 begin
1629 // Àíèìèðîâàííàÿ òåêñòóðà
1630 ntn := CreateAnimTexture(rec.Resource, FileName, True);
1631 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_ANIM], [rec.Resource]));
1632 end
1633 else
1634 begin
1635 // Îáû÷íàÿ òåêñòóðà
1636 ntn := CreateTexture(rec.Resource, FileName, True);
1637 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_SIMPLE], [rec.Resource]));
1638 end;
1639 if (ntn < 0) then ntn := CreateNullTexture(rec.Resource);
1641 rec.tagInt := ntn; // remember texture number
1642 end;
1643 g_Game_StepLoading();
1644 end;
1645 finally
1646 usedTextures.Free();
1647 end;
1649 // set panel tagInt to texture index
1650 if (panels <> nil) then
1651 begin
1652 for rec in panels do
1653 begin
1654 texrec := rec.TextureRec;
1655 if (texrec = nil) then rec.tagInt := -1 else rec.tagInt := texrec.tagInt;
1656 end;
1657 end;
1658 end;
1661 // Çàãðóçêà òðèããåðîâ
1662 gTriggerClientID := 0;
1663 e_WriteLog(' Loading triggers...', TMsgType.Notify);
1664 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS], 0, False);
1666 // Çàãðóçêà ïàíåëåé
1667 e_WriteLog(' Loading panels...', TMsgType.Notify);
1668 g_Game_SetLoadingText(_lc[I_LOAD_PANELS], 0, False);
1670 // check texture numbers for panels
1671 if (panels <> nil) and (panels.count > 0) then
1672 begin
1673 for rec in panels do
1674 begin
1675 if (rec.tagInt < 0) then
1676 begin
1677 e_WriteLog('error loading map: invalid texture index for panel', TMsgType.Fatal);
1678 result := false;
1679 gCurrentMap.Free();
1680 gCurrentMap := nil;
1681 gCurrentMapFileName := '';
1682 exit;
1683 end;
1684 end;
1685 end;
1687 // Ñîçäàíèå òàáëèöû òðèããåðîâ (ñîîòâåòñòâèå ïàíåëåé òðèããåðàì)
1688 if (triggers <> nil) and (triggers.count > 0) then
1689 begin
1690 e_WriteLog(' Setting up trigger table...', TMsgType.Notify);
1691 //SetLength(TriggersTable, triggers.count);
1692 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS_TABLE], triggers.count-1, False);
1694 SetLength(TriggersTable, triggers.count);
1695 trignum := -1;
1696 for rec in triggers do
1697 begin
1698 Inc(trignum);
1699 pttit := @TriggersTable[trignum];
1700 pttit.trigrec := rec;
1701 // Ñìåíà òåêñòóðû (âîçìîæíî, êíîïêè)
1702 pttit.texPanelIdx := -1; // will be fixed later
1703 pttit.texPanel := rec.TexturePanelRec;
1704 // action panel
1705 pttit.actPanelIdx := -1;
1706 if (rec.trigRec <> nil) then pttit.actPanel := rec.trigRec.tgPanelRec else pttit.actPanel := nil;
1707 // set flag
1708 if (pttit.texPanel <> nil) then pttit.texPanel.userPanelTrigRef := true;
1709 if (pttit.actPanel <> nil) then pttit.actPanel.userPanelTrigRef := true;
1710 // update progress
1711 g_Game_StepLoading();
1712 end;
1713 end;
1715 // Ñîçäàåì ïàíåëè
1716 if (panels <> nil) and (panels.count > 0) then
1717 begin
1718 e_WriteLog(' Setting up trigger links...', TMsgType.Notify);
1719 g_Game_SetLoadingText(_lc[I_LOAD_LINK_TRIGGERS], panels.count-1, False);
1721 pannum := -1;
1722 for rec in panels do
1723 begin
1724 Inc(pannum);
1725 //e_LogWritefln('PANSTART: pannum=%s', [pannum]);
1726 texrec := nil;
1727 SetLength(AddTextures, 0);
1728 CurTex := -1;
1729 ok := false;
1731 if (mapTextureList <> nil) then
1732 begin
1733 texrec := rec.TextureRec;
1734 ok := (texrec <> nil);
1735 end;
1737 if ok then
1738 begin
1739 // Ñìîòðèì, ññûëàþòñÿ ëè íà ýòó ïàíåëü òðèããåðû.
1740 // Åñëè äà - òî íàäî ñîçäàòü åùå òåêñòóð
1741 ok := false;
1742 if (TriggersTable <> nil) and (mapTextureList <> nil) then
1743 begin
1744 if rec.userPanelTrigRef then
1745 begin
1746 // e_LogWritefln('trigref for panel %s', [pannum]);
1747 ok := True;
1748 end;
1749 end;
1750 end;
1752 if ok then
1753 begin
1754 // Åñòü ññûëêè òðèããåðîâ íà ýòó ïàíåëü
1755 s := texrec.Resource;
1757 // Ñïåö-òåêñòóðû çàïðåùåíû
1758 if g_Map_IsSpecialTexture(s) then
1759 begin
1760 ok := false
1761 end
1762 else
1763 begin
1764 // Îïðåäåëÿåì íàëè÷èå è ïîëîæåíèå öèôð â êîíöå ñòðîêè
1765 ok := g_Texture_NumNameFindStart(s);
1766 end;
1768 // Åñëè ok, çíà÷èò åñòü öèôðû â êîíöå.
1769 // Çàãðóæàåì òåêñòóðû ñ îñòàëüíûìè #
1770 if ok then
1771 begin
1772 k := NNF_NAME_BEFORE;
1773 // Öèêë ïî èçìåíåíèþ èìåíè òåêñòóðû
1774 while ok or (k = NNF_NAME_BEFORE) or (k = NNF_NAME_EQUALS) do
1775 begin
1776 k := g_Texture_NumNameFindNext(TexName);
1778 if (k = NNF_NAME_BEFORE) or (k = NNF_NAME_AFTER) then
1779 begin
1780 // Ïðîáóåì äîáàâèòü íîâóþ òåêñòóðó
1781 if texrec.Anim then
1782 begin
1783 // Íà÷àëüíàÿ - àíèìèðîâàííàÿ, èùåì àíèìèðîâàííóþ
1784 isAnim := True;
1785 //e_LogWritefln('000: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1786 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
1787 //e_LogWritefln('001: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1788 if not ok then
1789 begin
1790 // Íåò àíèìèðîâàííîé, èùåì îáû÷íóþ
1791 isAnim := False;
1792 //e_LogWritefln('002: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1793 ok := CreateTexture(TexName, FileName, False) >= 0;
1794 //e_LogWritefln('003: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1795 end;
1796 end
1797 else
1798 begin
1799 // Íà÷àëüíàÿ - îáû÷íàÿ, èùåì îáû÷íóþ
1800 isAnim := False;
1801 //e_LogWritefln('004: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1802 ok := CreateTexture(TexName, FileName, False) >= 0;
1803 //e_LogWritefln('005: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1804 if not ok then
1805 begin
1806 // Íåò îáû÷íîé, èùåì àíèìèðîâàííóþ
1807 isAnim := True;
1808 //e_LogWritefln('006: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1809 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
1810 //e_LogWritefln('007: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
1811 end;
1812 end;
1814 // Îíà ñóùåñòâóåò. Çàíîñèì åå ID â ñïèñîê ïàíåëè
1815 if ok then
1816 begin
1818 for c := 0 to High(Textures) do
1819 begin
1820 if (Textures[c].TextureName = TexName) then
1821 begin
1822 SetLength(AddTextures, Length(AddTextures)+1);
1823 AddTextures[High(AddTextures)].Texture := c;
1824 AddTextures[High(AddTextures)].Anim := isAnim;
1825 break;
1826 end;
1827 end;
1829 if (TextNameHash <> nil) and TextNameHash.get(toLowerCase1251(TexName), c) then
1830 begin
1831 SetLength(AddTextures, Length(AddTextures)+1);
1832 AddTextures[High(AddTextures)].Texture := c;
1833 AddTextures[High(AddTextures)].Anim := isAnim;
1834 end;
1835 end;
1836 end
1837 else
1838 begin
1839 if k = NNF_NAME_EQUALS then
1840 begin
1841 // Çàíîñèì òåêóùóþ òåêñòóðó íà ñâîå ìåñòî
1842 SetLength(AddTextures, Length(AddTextures)+1);
1843 AddTextures[High(AddTextures)].Texture := rec.tagInt; // internal texture number, not map index
1844 AddTextures[High(AddTextures)].Anim := texrec.Anim;
1845 CurTex := High(AddTextures);
1846 ok := true;
1847 end
1848 else // NNF_NO_NAME
1849 begin
1850 ok := false;
1851 end;
1852 end;
1853 end; // while ok...
1855 ok := true;
1856 end; // if ok - åñòü ñìåæíûå òåêñòóðû
1857 end; // if ok - ññûëàþòñÿ òðèããåðû
1859 if not ok then
1860 begin
1861 // Çàíîñèì òîëüêî òåêóùóþ òåêñòóðó
1862 SetLength(AddTextures, 1);
1863 AddTextures[0].Texture := rec.tagInt; // internal texture number, not map index
1864 AddTextures[0].Anim := false;
1865 if (texrec <> nil) then AddTextures[0].Anim := texrec.Anim;
1866 CurTex := 0;
1867 end;
1869 //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);
1871 //e_LogWritefln('PANADD: pannum=%s', [pannum]);
1873 // Ñîçäàåì ïàíåëü è çàïîìèíàåì åå GUID
1874 //e_LogWritefln('new panel; tcount=%s; curtex=%s', [Length(AddTextures), CurTex]);
1875 PanelID := CreatePanel(rec, AddTextures, CurTex);
1876 //e_LogWritefln('panel #%s of type %s got guid #%s', [pannum, rec.PanelType, PanelID]);
1877 rec.userPanelId := PanelID; // remember game panel id, we'll fix triggers later
1879 // setup lifts
1880 moveSpeed := rec.moveSpeed;
1881 //moveStart := rec.moveStart;
1882 //moveEnd := rec.moveEnd;
1883 //moveActive := rec['move_active'].value;
1884 if not moveSpeed.isZero then
1885 begin
1886 SetLength(gMovingWallIds, Length(gMovingWallIds)+1);
1887 gMovingWallIds[High(gMovingWallIds)] := PanelID;
1888 //e_LogWritefln('found moving panel ''%s'' (idx=%s; id=%s)', [rec.id, pannum, PanelID]);
1889 end;
1891 //e_LogWritefln('PANEND: pannum=%s', [pannum]);
1893 g_Game_StepLoading();
1894 end;
1895 end;
1897 // ×èíèì ID'û ïàíåëåé, êîòîðûå èñïîëüçóþòñÿ â òðèããåðàõ
1898 for b := 0 to High(TriggersTable) do
1899 begin
1900 if (TriggersTable[b].texPanel <> nil) then TriggersTable[b].texPanelIdx := TriggersTable[b].texPanel.userPanelId;
1901 if (TriggersTable[b].actPanel <> nil) then TriggersTable[b].actPanelIdx := TriggersTable[b].actPanel.userPanelId;
1902 end;
1904 // create map grid, init other grids (for monsters, for example)
1905 e_WriteLog('Creating map grid', TMsgType.Notify);
1906 mapCreateGrid();
1908 // Åñëè íå LoadState, òî ñîçäàåì òðèããåðû
1909 if (triggers <> nil) and (panels <> nil) and (not gLoadGameMode) then
1910 begin
1911 e_LogWritefln(' Creating triggers (%d)...', [triggers.count]);
1912 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_TRIGGERS], 0, False);
1913 // Óêàçûâàåì òèï ïàíåëè, åñëè åñòü
1914 trignum := -1;
1915 for rec in triggers do
1916 begin
1917 Inc(trignum);
1918 tgpid := TriggersTable[trignum].actPanelIdx;
1919 //e_LogWritefln('creating trigger #%s; texpantype=%s; shotpantype=%s (%d,%d)', [trignum, b, c, TriggersTable[trignum].texPanIdx, TriggersTable[trignum].ShotPanelIdx]);
1920 TriggersTable[trignum].tnum := trignum;
1921 TriggersTable[trignum].id := CreateTrigger(trignum, rec, TriggersTable[trignum].texPanelIdx, tgpid);
1922 end;
1923 end;
1925 //FIXME: use hashtable!
1926 for pan in panByGUID do
1927 begin
1928 if (pan.endPosTrigId >= 0) and (pan.endPosTrigId < Length(TriggersTable)) then
1929 begin
1930 pan.endPosTrigId := TriggersTable[pan.endPosTrigId].id;
1931 end;
1932 if (pan.endSizeTrigId >= 0) and (pan.endSizeTrigId < Length(TriggersTable)) then
1933 begin
1934 pan.endSizeTrigId := TriggersTable[pan.endSizeTrigId].id;
1935 end;
1936 end;
1938 // Çàãðóçêà ïðåäìåòîâ
1939 e_WriteLog(' Loading items...', TMsgType.Notify);
1940 g_Game_SetLoadingText(_lc[I_LOAD_ITEMS], 0, False);
1942 // Åñëè íå LoadState, òî ñîçäàåì ïðåäìåòû
1943 if (items <> nil) and not gLoadGameMode then
1944 begin
1945 e_WriteLog(' Spawning items...', TMsgType.Notify);
1946 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_ITEMS], 0, False);
1947 for rec in items do CreateItem(rec);
1948 end;
1950 // Çàãðóçêà îáëàñòåé
1951 e_WriteLog(' Loading areas...', TMsgType.Notify);
1952 g_Game_SetLoadingText(_lc[I_LOAD_AREAS], 0, False);
1954 // Åñëè íå LoadState, òî ñîçäàåì îáëàñòè
1955 if areas <> nil then
1956 begin
1957 e_WriteLog(' Creating areas...', TMsgType.Notify);
1958 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_AREAS], 0, False);
1959 for rec in areas do CreateArea(rec);
1960 end;
1962 // Çàãðóçêà ìîíñòðîâ
1963 e_WriteLog(' Loading monsters...', TMsgType.Notify);
1964 g_Game_SetLoadingText(_lc[I_LOAD_MONSTERS], 0, False);
1966 gTotalMonsters := 0;
1968 // Åñëè íå LoadState, òî ñîçäàåì ìîíñòðîâ
1969 if (monsters <> nil) and not gLoadGameMode then
1970 begin
1971 e_WriteLog(' Spawning monsters...', TMsgType.Notify);
1972 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_MONSTERS], 0, False);
1973 for rec in monsters do CreateMonster(rec);
1974 end;
1976 //gCurrentMap := mapReader; // this will be our current map now
1977 gCurrentMapFileName := Res;
1978 //mapReader := nil;
1980 // Çàãðóçêà íåáà
1981 if (gMapInfo.SkyName <> '') then
1982 begin
1983 e_WriteLog(' Loading sky: ' + gMapInfo.SkyName, TMsgType.Notify);
1984 g_Game_SetLoadingText(_lc[I_LOAD_SKY], 0, False);
1985 s := e_GetResourcePath(WadDirs, gMapInfo.SkyName, g_ExtractWadName(Res));
1986 if g_Texture_CreateWAD(BackID, s, gTextureFilter) then
1987 g_Game_SetupScreenSize
1988 else
1989 g_FatalError(Format(_lc[I_GAME_ERROR_SKY], [s]))
1990 end;
1992 // Çàãðóçêà ìóçûêè
1993 ok := False;
1994 if gMapInfo.MusicName <> '' then
1995 begin
1996 e_WriteLog(' Loading music: ' + gMapInfo.MusicName, TMsgType.Notify);
1997 g_Game_SetLoadingText(_lc[I_LOAD_MUSIC], 0, False);
1999 s := e_GetResourcePath(WadDirs, gMapInfo.MusicName, g_ExtractWadName(Res));
2000 if g_Sound_CreateWADEx(gMapInfo.MusicName, s, True) then
2001 ok := True
2002 else
2003 g_FatalError(Format(_lc[I_GAME_ERROR_MUSIC], [s]));
2004 end;
2006 // Îñòàëüíûå óñòàíâêè
2007 CreateDoorMap();
2008 CreateLiftMap();
2010 g_Items_Init();
2011 g_Weapon_Init();
2012 g_Monsters_Init();
2014 // Åñëè íå LoadState, òî ñîçäàåì êàðòó ñòîëêíîâåíèé:
2015 if not gLoadGameMode then g_GFX_Init();
2017 // Ñáðîñ ëîêàëüíûõ ìàññèâîâ:
2018 mapTextureList := nil;
2019 panels := nil;
2020 items := nil;
2021 areas := nil;
2022 triggers := nil;
2023 TriggersTable := nil;
2024 AddTextures := nil;
2026 // Âêëþ÷àåì ìóçûêó, åñëè ýòî íå çàãðóçêà:
2027 if ok and (not gLoadGameMode) then
2028 begin
2029 gMusic.SetByName(gMapInfo.MusicName);
2030 gMusic.Play();
2031 end
2032 else
2033 begin
2034 gMusic.SetByName('');
2035 end;
2037 stt := getTimeMicro()-stt;
2038 e_LogWritefln('map loaded in %s.%s milliseconds', [Integer(stt div 1000), Integer(stt mod 1000)]);
2039 mapOk := true;
2040 finally
2041 sfsGCEnable(); // enable releasing unused volumes
2042 //mapReader.Free();
2043 e_UnpressAllKeys; // why not?
2044 if not mapOk then
2045 begin
2046 gCurrentMap.Free();
2047 gCurrentMap := nil;
2048 gCurrentMapFileName := '';
2049 end;
2050 end;
2052 compactExtResList();
2053 e_WriteLog('Done loading map.', TMsgType.Notify);
2054 Result := True;
2055 end;
2058 function g_Map_GetMapInfo(Res: String): TMapInfo;
2059 var
2060 WAD: TWADFile;
2061 mapReader: TDynRecord;
2062 //Header: TMapHeaderRec_1;
2063 FileName: String;
2064 Data: Pointer;
2065 Len: Integer;
2066 begin
2067 FillChar(Result, SizeOf(Result), 0);
2068 FileName := g_ExtractWadName(Res);
2070 WAD := TWADFile.Create();
2071 if not WAD.ReadFile(FileName) then
2072 begin
2073 WAD.Free();
2074 Exit;
2075 end;
2077 //k8: it ignores path again
2078 if not WAD.GetMapResource(g_ExtractFileName(Res), Data, Len) then
2079 begin
2080 WAD.Free();
2081 Exit;
2082 end;
2084 WAD.Free();
2086 try
2087 mapReader := g_Map_ParseMap(Data, Len);
2088 except
2089 mapReader := nil;
2090 FreeMem(Data);
2091 exit;
2092 end;
2094 FreeMem(Data);
2096 if (mapReader = nil) then exit;
2098 if (mapReader.Width > 0) and (mapReader.Height > 0) then
2099 begin
2100 Result.Name := mapReader.MapName;
2101 Result.Description := mapReader.MapDesc;
2102 Result.Map := Res;
2103 Result.Author := mapReader.MapAuthor;
2104 Result.Height := mapReader.Height;
2105 Result.Width := mapReader.Width;
2106 end
2107 else
2108 begin
2109 g_Console_Add(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]), True);
2110 //ZeroMemory(@Header, SizeOf(Header));
2111 Result.Name := _lc[I_GAME_ERROR_MAP_SELECT];
2112 Result.Description := _lc[I_GAME_ERROR_MAP_SELECT];
2113 Result.Map := Res;
2114 Result.Author := '';
2115 Result.Height := 0;
2116 Result.Width := 0;
2117 end;
2119 mapReader.Free();
2120 end;
2122 function g_Map_GetMapsList(WADName: string): SSArray;
2123 var
2124 WAD: TWADFile;
2125 a: Integer;
2126 ResList: SSArray;
2127 begin
2128 Result := nil;
2129 WAD := TWADFile.Create();
2130 if not WAD.ReadFile(WADName) then
2131 begin
2132 WAD.Free();
2133 Exit;
2134 end;
2135 ResList := WAD.GetMapResources();
2136 if ResList <> nil then
2137 begin
2138 for a := 0 to High(ResList) do
2139 begin
2140 SetLength(Result, Length(Result)+1);
2141 Result[High(Result)] := ResList[a];
2142 end;
2143 end;
2144 WAD.Free();
2145 end;
2147 function g_Map_Exist(Res: string): Boolean;
2148 var
2149 WAD: TWADFile;
2150 FileName, mnn: string;
2151 ResList: SSArray;
2152 a: Integer;
2153 begin
2154 Result := False;
2156 FileName := addWadExtension(g_ExtractWadName(Res));
2158 WAD := TWADFile.Create;
2159 if not WAD.ReadFile(FileName) then
2160 begin
2161 WAD.Free();
2162 Exit;
2163 end;
2165 ResList := WAD.GetMapResources();
2166 WAD.Free();
2168 mnn := g_ExtractFileName(Res);
2169 if ResList <> nil then
2170 for a := 0 to High(ResList) do if StrEquCI1251(ResList[a], mnn) then
2171 begin
2172 Result := True;
2173 Exit;
2174 end;
2175 end;
2177 procedure g_Map_Free(freeTextures: Boolean=true);
2179 procedure FreePanelArray(var panels: TPanelArray);
2180 var
2181 i: Integer;
2183 begin
2184 if panels <> nil then
2185 begin
2186 for i := 0 to High(panels) do
2187 panels[i].Free();
2188 panels := nil;
2189 end;
2190 end;
2192 begin
2193 g_GFX_Free();
2194 g_Weapon_Free();
2195 g_Items_Free();
2196 g_Triggers_Free();
2197 g_Monsters_Free();
2199 RespawnPoints := nil;
2200 if FlagPoints[FLAG_RED] <> nil then
2201 begin
2202 Dispose(FlagPoints[FLAG_RED]);
2203 FlagPoints[FLAG_RED] := nil;
2204 end;
2205 if FlagPoints[FLAG_BLUE] <> nil then
2206 begin
2207 Dispose(FlagPoints[FLAG_BLUE]);
2208 FlagPoints[FLAG_BLUE] := nil;
2209 end;
2210 //DOMFlagPoints := nil;
2212 //gDOMFlags := nil;
2214 if (Length(gCurrentMapFileName) <> 0) then
2215 begin
2216 e_LogWritefln('g_Map_Free: previous map was ''%s''...', [gCurrentMapFileName]);
2217 end
2218 else
2219 begin
2220 e_LogWritefln('g_Map_Free: no previous map.', []);
2221 end;
2223 if freeTextures then
2224 begin
2225 e_LogWritefln('g_Map_Free: clearing textures...', []);
2226 Textures := nil;
2227 TextNameHash.Free();
2228 TextNameHash := nil;
2229 BadTextNameHash.Free();
2230 BadTextNameHash := nil;
2231 gCurrentMapFileName := '';
2232 gCurrentMap.Free();
2233 gCurrentMap := nil;
2234 end;
2236 panByGUID := nil;
2238 FreePanelArray(gWalls);
2239 FreePanelArray(gRenderBackgrounds);
2240 FreePanelArray(gRenderForegrounds);
2241 FreePanelArray(gWater);
2242 FreePanelArray(gAcid1);
2243 FreePanelArray(gAcid2);
2244 FreePanelArray(gSteps);
2245 FreePanelArray(gLifts);
2246 FreePanelArray(gBlockMon);
2247 gMovingWallIds := nil;
2249 if BackID <> DWORD(-1) then
2250 begin
2251 gBackSize.X := 0;
2252 gBackSize.Y := 0;
2253 e_DeleteTexture(BackID);
2254 BackID := DWORD(-1);
2255 end;
2257 g_Game_StopAllSounds(False);
2258 gMusic.FreeSound();
2259 g_Sound_Delete(gMapInfo.MusicName);
2261 gMapInfo.Name := '';
2262 gMapInfo.Description := '';
2263 gMapInfo.MusicName := '';
2264 gMapInfo.Height := 0;
2265 gMapInfo.Width := 0;
2267 gDoorMap := nil;
2268 gLiftMap := nil;
2269 end;
2271 procedure g_Map_Update();
2272 var
2273 a, d, j: Integer;
2274 m: Word;
2275 s: String;
2276 b: Byte;
2278 procedure UpdatePanelArray(var panels: TPanelArray);
2279 var
2280 i: Integer;
2282 begin
2283 for i := 0 to High(panels) do panels[i].Update();
2284 end;
2286 begin
2287 if g_dbgpan_mplat_step then g_dbgpan_mplat_active := true;
2289 UpdatePanelArray(gWalls);
2290 UpdatePanelArray(gRenderBackgrounds);
2291 UpdatePanelArray(gRenderForegrounds);
2292 UpdatePanelArray(gWater);
2293 UpdatePanelArray(gAcid1);
2294 UpdatePanelArray(gAcid2);
2295 UpdatePanelArray(gSteps);
2297 if g_dbgpan_mplat_step then begin g_dbgpan_mplat_step := false; g_dbgpan_mplat_active := false; end;
2299 if gGameSettings.GameMode = GM_CTF then
2300 begin
2301 for a := FLAG_RED to FLAG_BLUE do
2302 begin
2303 if not (gFlags[a].State in [FLAG_STATE_NONE, FLAG_STATE_CAPTURED]) then
2304 begin
2305 with gFlags[a] do
2306 begin
2307 if gFlags[a].Animation <> nil then gFlags[a].Animation.Update();
2309 m := g_Obj_Move(@Obj, True, True);
2311 if gTime mod (GAME_TICK*2) <> 0 then Continue;
2313 // Ñîïðîòèâëåíèå âîçäóõà
2314 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
2316 // Òàéìàóò ïîòåðÿííîãî ôëàãà, ëèáî îí âûïàë çà êàðòó
2317 if ((Count = 0) or ByteBool(m and MOVE_FALLOUT)) and g_Game_IsServer then
2318 begin
2319 g_Map_ResetFlag(a);
2320 gFlags[a].CaptureTime := 0;
2321 if a = FLAG_RED then
2322 s := _lc[I_PLAYER_FLAG_RED]
2323 else
2324 s := _lc[I_PLAYER_FLAG_BLUE];
2325 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
2327 if (((gPlayer1 <> nil) and (((gPlayer1.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer1.Team = TEAM_BLUE) and (a = FLAG_BLUE))))
2328 or ((gPlayer2 <> nil) and (((gPlayer2.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer2.Team = TEAM_BLUE) and (a = FLAG_BLUE))))) then
2329 b := 0
2330 else
2331 b := 1;
2333 if not sound_ret_flag[b].IsPlaying() then
2334 sound_ret_flag[b].Play();
2336 if g_Game_IsNet then
2337 MH_SEND_FlagEvent(FLAG_STATE_RETURNED, a, 0);
2338 Continue;
2339 end;
2341 if Count > 0 then Count -= 1;
2343 // Èãðîê áåðåò ôëàã
2344 if gPlayers <> nil then
2345 begin
2346 j := Random(Length(gPlayers)) - 1;
2347 for d := 0 to High(gPlayers) do
2348 begin
2349 Inc(j);
2350 if j > High(gPlayers) then j := 0;
2351 if gPlayers[j] <> nil then
2352 begin
2353 if gPlayers[j].alive and g_Obj_Collide(@Obj, @gPlayers[j].Obj) then
2354 begin
2355 if gPlayers[j].GetFlag(a) then Break;
2356 end;
2357 end;
2358 end;
2359 end;
2360 end;
2361 end;
2362 end;
2363 end;
2364 end;
2366 function g_Map_CollidePanelOld(X, Y: Integer; Width, Height: Word;
2367 PanelType: Word; b1x3: Boolean=false): Boolean;
2368 var
2369 a, h: Integer;
2370 begin
2371 Result := False;
2373 if WordBool(PanelType and PANEL_WALL) then
2374 if gWalls <> nil then
2375 begin
2376 h := High(gWalls);
2378 for a := 0 to h do
2379 if gWalls[a].Enabled and
2380 g_Collide(X, Y, Width, Height,
2381 gWalls[a].X, gWalls[a].Y,
2382 gWalls[a].Width, gWalls[a].Height) then
2383 begin
2384 Result := True;
2385 Exit;
2386 end;
2387 end;
2389 if WordBool(PanelType and PANEL_WATER) then
2390 if gWater <> nil then
2391 begin
2392 h := High(gWater);
2394 for a := 0 to h do
2395 if g_Collide(X, Y, Width, Height,
2396 gWater[a].X, gWater[a].Y,
2397 gWater[a].Width, gWater[a].Height) then
2398 begin
2399 Result := True;
2400 Exit;
2401 end;
2402 end;
2404 if WordBool(PanelType and PANEL_ACID1) then
2405 if gAcid1 <> nil then
2406 begin
2407 h := High(gAcid1);
2409 for a := 0 to h do
2410 if g_Collide(X, Y, Width, Height,
2411 gAcid1[a].X, gAcid1[a].Y,
2412 gAcid1[a].Width, gAcid1[a].Height) then
2413 begin
2414 Result := True;
2415 Exit;
2416 end;
2417 end;
2419 if WordBool(PanelType and PANEL_ACID2) then
2420 if gAcid2 <> nil then
2421 begin
2422 h := High(gAcid2);
2424 for a := 0 to h do
2425 if g_Collide(X, Y, Width, Height,
2426 gAcid2[a].X, gAcid2[a].Y,
2427 gAcid2[a].Width, gAcid2[a].Height) then
2428 begin
2429 Result := True;
2430 Exit;
2431 end;
2432 end;
2434 if WordBool(PanelType and PANEL_STEP) then
2435 if gSteps <> nil then
2436 begin
2437 h := High(gSteps);
2439 for a := 0 to h do
2440 if g_Collide(X, Y, Width, Height,
2441 gSteps[a].X, gSteps[a].Y,
2442 gSteps[a].Width, gSteps[a].Height) then
2443 begin
2444 Result := True;
2445 Exit;
2446 end;
2447 end;
2449 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then
2450 if gLifts <> nil then
2451 begin
2452 h := High(gLifts);
2454 for a := 0 to h do
2455 if ((WordBool(PanelType and (PANEL_LIFTUP)) and (gLifts[a].LiftType = LIFTTYPE_UP)) or
2456 (WordBool(PanelType and (PANEL_LIFTDOWN)) and (gLifts[a].LiftType = LIFTTYPE_DOWN)) or
2457 (WordBool(PanelType and (PANEL_LIFTLEFT)) and (gLifts[a].LiftType = LIFTTYPE_LEFT)) or
2458 (WordBool(PanelType and (PANEL_LIFTRIGHT)) and (gLifts[a].LiftType = LIFTTYPE_RIGHT))) and
2459 g_Collide(X, Y, Width, Height,
2460 gLifts[a].X, gLifts[a].Y,
2461 gLifts[a].Width, gLifts[a].Height) then
2462 begin
2463 Result := True;
2464 Exit;
2465 end;
2466 end;
2468 if WordBool(PanelType and PANEL_BLOCKMON) then
2469 if gBlockMon <> nil then
2470 begin
2471 h := High(gBlockMon);
2473 for a := 0 to h do
2474 if ( (not b1x3) or
2475 ((gBlockMon[a].Width + gBlockMon[a].Height) >= 64) ) and
2476 g_Collide(X, Y, Width, Height,
2477 gBlockMon[a].X, gBlockMon[a].Y,
2478 gBlockMon[a].Width, gBlockMon[a].Height) then
2479 begin
2480 Result := True;
2481 Exit;
2482 end;
2483 end;
2484 end;
2486 function g_Map_CollideLiquid_TextureOld(X, Y: Integer; Width, Height: Word): DWORD;
2487 var
2488 texid: DWORD;
2490 function checkPanels (constref panels: TPanelArray): Boolean;
2491 var
2492 a: Integer;
2493 begin
2494 result := false;
2495 if panels = nil then exit;
2496 for a := 0 to High(panels) do
2497 begin
2498 if g_Collide(X, Y, Width, Height, panels[a].X, panels[a].Y, panels[a].Width, panels[a].Height) then
2499 begin
2500 result := true;
2501 texid := panels[a].GetTextureID();
2502 exit;
2503 end;
2504 end;
2505 end;
2507 begin
2508 texid := LongWord(TEXTURE_NONE);
2509 result := texid;
2510 if not checkPanels(gWater) then
2511 if not checkPanels(gAcid1) then
2512 if not checkPanels(gAcid2) then exit;
2513 result := texid;
2514 end;
2517 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word; PanelType: Word; b1x3: Boolean): Boolean;
2518 const
2519 SlowMask = GridTagLift or GridTagBlockMon;
2521 function checker (pan: TPanel; tag: Integer): Boolean;
2522 begin
2524 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
2525 begin
2526 result := pan.Enabled;
2527 exit;
2528 end;
2531 if ((tag and GridTagLift) <> 0) then
2532 begin
2533 result :=
2534 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2535 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2536 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2537 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2538 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2539 exit;
2540 end;
2542 if ((tag and GridTagBlockMon) <> 0) then
2543 begin
2544 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2545 exit;
2546 end;
2548 // other shit
2549 //result := g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2550 result := true; // i found her!
2551 end;
2553 var
2554 tagmask: Integer = 0;
2555 mwit: PPanel;
2556 it: TPanelGrid.Iter;
2557 pan: TPanel;
2558 begin
2559 result := false;
2560 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
2561 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
2562 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
2563 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
2564 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
2565 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
2566 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
2568 if (tagmask = 0) then exit; // just in case
2570 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('*solids');
2571 if gdbg_map_use_accel_coldet then
2572 begin
2573 if ((tagmask and SlowMask) <> 0) then
2574 begin
2575 // slow
2576 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask);
2577 for mwit in it do
2578 begin
2579 pan := mwit^;
2580 if ((pan.tag and GridTagLift) <> 0) then
2581 begin
2582 result :=
2583 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2584 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2585 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2586 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2587 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2588 end
2589 else if ((pan.tag and GridTagBlockMon) <> 0) then
2590 begin
2591 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2592 end
2593 else
2594 begin
2595 // other shit
2596 result := true; // i found her!
2597 end;
2598 if (result) then break;
2599 end;
2600 end
2601 else
2602 begin
2603 // fast
2604 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask, false, true); // return first hit
2605 result := (it.length > 0);
2606 end;
2607 it.release();
2608 end
2609 else
2610 begin
2611 result := g_Map_CollidePanelOld(X, Y, Width, Height, PanelType, b1x3);
2612 end;
2613 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2614 end;
2617 // returns `true` if we need to stop
2618 function liquidChecker (pan: TPanel; var texid: DWORD; var cctype: Integer): Boolean; inline;
2619 begin
2620 result := false;
2621 //if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2)) = 0) then exit;
2622 // check priorities
2623 case cctype of
2624 0: if ((pan.tag and GridTagWater) = 0) then exit; // allowed: water
2625 1: if ((pan.tag and (GridTagWater or GridTagAcid1)) = 0) then exit; // allowed: water, acid1
2626 //2: if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2) = 0) then exit; // allowed: water, acid1, acid2
2627 end;
2628 // collision?
2629 //if not g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height) then exit;
2630 // yeah
2631 texid := pan.GetTextureID();
2632 // water? water has the highest priority, so stop right here
2633 if ((pan.tag and GridTagWater) <> 0) then begin cctype := 0; result := true; exit; end;
2634 // acid2?
2635 if ((pan.tag and GridTagAcid2) <> 0) then cctype := 2;
2636 // acid1?
2637 if ((pan.tag and GridTagAcid1) <> 0) then cctype := 1;
2638 end;
2640 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
2641 var
2642 cctype: Integer = 3; // priority: 0: water was hit, 1: acid1 was hit, 2: acid2 was hit; 3: nothing was hit
2643 mwit: PPanel;
2644 it: TPanelGrid.Iter;
2645 begin
2646 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('liquids');
2647 if gdbg_map_use_accel_coldet then
2648 begin
2649 result := LongWord(TEXTURE_NONE);
2650 it := mapGrid.forEachInAABB(X, Y, Width, Height, (GridTagWater or GridTagAcid1 or GridTagAcid2));
2651 for mwit in it do if (liquidChecker(mwit^, result, cctype)) then break;
2652 it.release();
2653 end
2654 else
2655 begin
2656 result := g_Map_CollideLiquid_TextureOld(X, Y, Width, Height);
2657 end;
2658 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2659 end;
2662 procedure g_Map_EnableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_EnableWallGUID(gWalls[ID].guid); end;
2663 procedure g_Map_DisableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_DisableWallGUID(gWalls[ID].guid); end;
2664 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer); begin if (ID < Length(gLifts)) then g_Map_SetLiftGUID(gLifts[ID].guid, t); end;
2667 procedure g_Map_EnableWallGUID (pguid: Integer);
2668 var
2669 pan: TPanel;
2670 begin
2671 //pan := gWalls[ID];
2672 pan := g_Map_PanelByGUID(pguid);
2673 if (pan = nil) then exit;
2674 if pan.Enabled and mapGrid.proxyEnabled[pan.proxyId] then exit;
2676 pan.Enabled := True;
2677 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, true);
2679 mapGrid.proxyEnabled[pan.proxyId] := true;
2680 //if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := true
2681 //else pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, GridTagDoor);
2683 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
2684 // mark platform as interesting
2685 pan.setDirty();
2687 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
2688 //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);
2689 {$ENDIF}
2690 end;
2693 procedure g_Map_DisableWallGUID (pguid: Integer);
2694 var
2695 pan: TPanel;
2696 begin
2697 //pan := gWalls[ID];
2698 pan := g_Map_PanelByGUID(pguid);
2699 if (pan = nil) then exit;
2700 if (not pan.Enabled) and (not mapGrid.proxyEnabled[pan.proxyId]) then exit;
2702 pan.Enabled := False;
2703 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, false);
2705 mapGrid.proxyEnabled[pan.proxyId] := false;
2706 //if (pan.proxyId >= 0) then begin mapGrid.removeBody(pan.proxyId); pan.proxyId := -1; end;
2708 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
2709 // mark platform as interesting
2710 pan.setDirty();
2712 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
2713 //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);
2714 {$ENDIF}
2715 end;
2718 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
2719 var
2720 tp: TPanel;
2721 begin
2722 tp := g_Map_PanelByGUID(pguid);
2723 if (tp = nil) then exit;
2724 tp.NextTexture(AnimLoop);
2725 if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelTexture(pguid, AnimLoop);
2726 end;
2729 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
2730 var
2731 pan: TPanel;
2732 begin
2733 //pan := gLifts[ID];
2734 pan := g_Map_PanelByGUID(pguid);
2735 if (pan = nil) then exit;
2736 if not pan.isGLift then exit;
2738 if ({gLifts[ID]}pan.LiftType = t) then exit; //!FIXME!TRIGANY!
2740 with {gLifts[ID]} pan do
2741 begin
2742 LiftType := t;
2744 g_Mark(X, Y, Width, Height, MARK_LIFT, false);
2745 //TODO: make separate lift tags, and change tag here
2747 case LiftType of
2748 LIFTTYPE_UP: g_Mark(X, Y, Width, Height, MARK_LIFTUP);
2749 LIFTTYPE_DOWN: g_Mark(X, Y, Width, Height, MARK_LIFTDOWN);
2750 LIFTTYPE_LEFT: g_Mark(X, Y, Width, Height, MARK_LIFTLEFT);
2751 LIFTTYPE_RIGHT: g_Mark(X, Y, Width, Height, MARK_LIFTRIGHT);
2752 end;
2754 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
2755 // mark platform as interesting
2756 pan.setDirty();
2757 end;
2758 end;
2761 function g_Map_GetPoint (PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
2762 var
2763 a: Integer;
2764 PointsArray: Array of TRespawnPoint;
2765 begin
2766 Result := False;
2767 SetLength(PointsArray, 0);
2769 if RespawnPoints = nil then
2770 Exit;
2772 for a := 0 to High(RespawnPoints) do
2773 if RespawnPoints[a].PointType = PointType then
2774 begin
2775 SetLength(PointsArray, Length(PointsArray)+1);
2776 PointsArray[High(PointsArray)] := RespawnPoints[a];
2777 end;
2779 if PointsArray = nil then
2780 Exit;
2782 RespawnPoint := PointsArray[Random(Length(PointsArray))];
2783 Result := True;
2784 end;
2786 function g_Map_GetPointCount(PointType: Byte): Word;
2787 var
2788 a: Integer;
2789 begin
2790 Result := 0;
2792 if RespawnPoints = nil then
2793 Exit;
2795 for a := 0 to High(RespawnPoints) do
2796 if RespawnPoints[a].PointType = PointType then
2797 Result := Result + 1;
2798 end;
2800 function g_Map_GetRandomPointType(): Byte;
2801 begin
2802 if RespawnPoints = nil then
2803 Result := 255
2804 else
2805 Result := RespawnPoints[Random(Length(RespawnPoints))].PointType;
2806 end;
2808 function g_Map_HaveFlagPoints(): Boolean;
2809 begin
2810 Result := (FlagPoints[FLAG_RED] <> nil) and (FlagPoints[FLAG_BLUE] <> nil);
2811 end;
2813 procedure g_Map_ResetFlag(Flag: Byte);
2814 begin
2815 with gFlags[Flag] do
2816 begin
2817 Obj.X := -1000;
2818 Obj.Y := -1000;
2819 Obj.Vel.X := 0;
2820 Obj.Vel.Y := 0;
2821 Direction := TDirection.D_LEFT;
2822 State := FLAG_STATE_NONE;
2823 if FlagPoints[Flag] <> nil then
2824 begin
2825 Obj.X := FlagPoints[Flag]^.X;
2826 Obj.Y := FlagPoints[Flag]^.Y;
2827 Direction := FlagPoints[Flag]^.Direction;
2828 State := FLAG_STATE_NORMAL;
2829 end;
2830 Count := -1;
2831 end;
2832 end;
2834 procedure g_Map_SaveState (st: TStream);
2835 var
2836 str: String;
2838 procedure savePanels ();
2839 var
2840 pan: TPanel;
2841 begin
2842 // Ñîõðàíÿåì ïàíåëè
2843 utils.writeInt(st, LongInt(Length(panByGUID)));
2844 for pan in panByGUID do pan.SaveState(st);
2845 end;
2847 procedure saveFlag (flag: PFlag);
2848 var
2849 b: Byte;
2850 begin
2851 utils.writeSign(st, 'FLAG');
2852 utils.writeInt(st, Byte(0)); // version
2853 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
2854 utils.writeInt(st, Byte(flag^.RespawnType));
2855 // Ñîñòîÿíèå ôëàãà
2856 utils.writeInt(st, Byte(flag^.State));
2857 // Íàïðàâëåíèå ôëàãà
2858 if flag^.Direction = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
2859 utils.writeInt(st, Byte(b));
2860 // Îáúåêò ôëàãà
2861 Obj_SaveState(st, @flag^.Obj);
2862 end;
2864 begin
2865 savePanels();
2867 // Ñîõðàíÿåì ìóçûêó
2868 utils.writeSign(st, 'MUSI');
2869 utils.writeInt(st, Byte(0));
2870 // Íàçâàíèå ìóçûêè
2871 assert(gMusic <> nil, 'g_Map_SaveState: gMusic = nil');
2872 if gMusic.NoMusic then str := '' else str := gMusic.Name;
2873 utils.writeStr(st, str);
2874 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
2875 utils.writeInt(st, LongWord(gMusic.GetPosition()));
2876 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
2877 utils.writeBool(st, gMusic.SpecPause);
2879 ///// Ñîõðàíÿåì êîëè÷åñòâî ìîíñòðîâ: /////
2880 utils.writeInt(st, LongInt(gTotalMonsters));
2881 ///// /////
2883 //// Ñîõðàíÿåì ôëàãè, åñëè ýòî CTF: /////
2884 if (gGameSettings.GameMode = GM_CTF) then
2885 begin
2886 // Ôëàã Êðàñíîé êîìàíäû
2887 saveFlag(@gFlags[FLAG_RED]);
2888 // Ôëàã Ñèíåé êîìàíäû
2889 saveFlag(@gFlags[FLAG_BLUE]);
2890 end;
2891 ///// /////
2893 ///// Ñîõðàíÿåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
2894 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
2895 begin
2896 // Î÷êè Êðàñíîé êîìàíäû
2897 utils.writeInt(st, SmallInt(gTeamStat[TEAM_RED].Goals));
2898 // Î÷êè Ñèíåé êîìàíäû
2899 utils.writeInt(st, SmallInt(gTeamStat[TEAM_BLUE].Goals));
2900 end;
2901 ///// /////
2902 end;
2905 procedure g_Map_LoadState (st: TStream);
2906 var
2907 dw: DWORD;
2908 str: String;
2909 boo: Boolean;
2911 procedure loadPanels ();
2912 var
2913 pan: TPanel;
2914 begin
2915 // Çàãðóæàåì ïàíåëè
2916 if (Length(panByGUID) <> utils.readLongInt(st)) then raise XStreamError.Create('invalid number of saved panels');
2917 for pan in panByGUID do
2918 begin
2919 pan.LoadState(st);
2920 if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
2921 end;
2922 end;
2924 procedure loadFlag (flag: PFlag);
2925 var
2926 b: Byte;
2927 begin
2928 // Ñèãíàòóðà ôëàãà
2929 if not utils.checkSign(st, 'FLAG') then raise XStreamError.Create('invalid flag signature');
2930 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid flag version');
2931 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
2932 flag^.RespawnType := utils.readByte(st);
2933 // Ñîñòîÿíèå ôëàãà
2934 flag^.State := utils.readByte(st);
2935 // Íàïðàâëåíèå ôëàãà
2936 b := utils.readByte(st);
2937 if (b = 1) then flag^.Direction := TDirection.D_LEFT else flag^.Direction := TDirection.D_RIGHT; // b = 2
2938 // Îáúåêò ôëàãà
2939 Obj_LoadState(@flag^.Obj, st);
2940 end;
2942 begin
2943 if (st = nil) then exit;
2945 ///// Çàãðóæàåì ñïèñêè ïàíåëåé: /////
2946 loadPanels();
2947 ///// /////
2949 // Îáíîâëÿåì êàðòó ñòîëêíîâåíèé è ñåòêó
2950 g_GFX_Init();
2951 //mapCreateGrid();
2953 ///// Çàãðóæàåì ìóçûêó: /////
2954 if not utils.checkSign(st, 'MUSI') then raise XStreamError.Create('invalid music signature');
2955 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid music version');
2956 // Íàçâàíèå ìóçûêè
2957 assert(gMusic <> nil, 'g_Map_LoadState: gMusic = nil');
2958 str := utils.readStr(st);
2959 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
2960 dw := utils.readLongWord(st);
2961 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
2962 boo := utils.readBool(st);
2963 // Çàïóñêàåì ýòó ìóçûêó
2964 gMusic.SetByName(str);
2965 gMusic.SpecPause := boo;
2966 gMusic.Play();
2967 gMusic.Pause(true);
2968 gMusic.SetPosition(dw);
2969 ///// /////
2971 ///// Çàãðóæàåì êîëè÷åñòâî ìîíñòðîâ: /////
2972 gTotalMonsters := utils.readLongInt(st);
2973 ///// /////
2975 //// Çàãðóæàåì ôëàãè, åñëè ýòî CTF: /////
2976 if (gGameSettings.GameMode = GM_CTF) then
2977 begin
2978 // Ôëàã Êðàñíîé êîìàíäû
2979 loadFlag(@gFlags[FLAG_RED]);
2980 // Ôëàã Ñèíåé êîìàíäû
2981 loadFlag(@gFlags[FLAG_BLUE]);
2982 end;
2983 ///// /////
2985 ///// Çàãðóæàåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
2986 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
2987 begin
2988 // Î÷êè Êðàñíîé êîìàíäû
2989 gTeamStat[TEAM_RED].Goals := utils.readSmallInt(st);
2990 // Î÷êè Ñèíåé êîìàíäû
2991 gTeamStat[TEAM_BLUE].Goals := utils.readSmallInt(st);
2992 end;
2993 ///// /////
2994 end;
2997 // trace liquid, stepping by `dx` and `dy`
2998 // return last seen liquid coords, and `false` if we're started outside of the liquid
2999 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
3000 const
3001 MaskLiquid = GridTagWater or GridTagAcid1 or GridTagAcid2;
3002 begin
3003 topx := x;
3004 topy := y;
3005 // started outside of the liquid?
3006 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then begin result := false; exit; end;
3007 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then begin result := false; exit; end;
3008 if (dx = 0) and (dy = 0) then begin result := false; exit; end; // sanity check
3009 result := true;
3010 while true do
3011 begin
3012 Inc(x, dx);
3013 Inc(y, dy);
3014 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then exit; // out of the water, just exit
3015 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then exit; // out of the water, just exit
3016 topx := x;
3017 topy := y;
3018 end;
3019 end;
3022 begin
3023 DynWarningCB := mapWarningCB;
3024 end.