DEADSOFTWARE

bye-bye, bineditor, we won't miss you
[d2df-sdl.git] / src / game / g_monsters.pas
index ae4389c98ab48bb4b9c79c15ab9d8607de8967c2..2d6daf6c9de719bd9fed2b43f9c8025dfa9ec14c 100644 (file)
@@ -21,8 +21,10 @@ unit g_monsters;
 interface
 
 uses
+  SysUtils, Classes,
+  mempool,
   g_basic, e_graphics, g_phys, g_textures, g_grid,
-  g_saveload, BinEditor, g_panel, xprofiler;
+  g_saveload, g_panel, xprofiler;
 
 const
   MONSTATE_SLEEP  = 0;
@@ -38,15 +40,17 @@ const
   MONSTATE_REVIVE = 10;
   MONSTATE_RUNOUT = 11;
 
+{ in mapdef now
   BH_NORMAL   = 0;
   BH_KILLER   = 1;
   BH_MANIAC   = 2;
   BH_INSANE   = 3;
   BH_CANNIBAL = 4;
   BH_GOOD     = 5;
+}
 
 type
-  TMonster = Class (TObject)
+  TMonster = class(TPoolObject)
   private
     FMonsterType: Byte;
     FUID: Word;
@@ -87,14 +91,24 @@ type
     FDieTriggers: Array of Integer;
     FSpawnTrigger: Integer;
 
+    mNeedSend: Boolean; // for network
+
+    mEDamageType: Integer;
+
     procedure Turn();
     function findNewPrey(): Boolean;
     procedure ActivateTriggers();
 
+    procedure setGameX (v: Integer); inline;
+    procedure setGameY (v: Integer); inline;
+
+    procedure doDamage (v: Integer);
+
   public
     FNoRespawn: Boolean;
     FFireTime: Integer;
     trapCheckFrameId: DWord; // for `g_weapons.CheckTrap()`
+    mplatCheckFrameId: LongWord;
 
     constructor Create(MonsterType: Byte; aID: Integer; ForcedUID: Integer = -1);
     destructor Destroy(); override;
@@ -102,7 +116,7 @@ type
     function Collide(Panel: TPanel): Boolean; overload;
     function Collide(X, Y: Integer): Boolean; overload;
     function TeleportTo(X, Y: Integer; silent: Boolean; dir: Byte): Boolean;
-    function Live(): Boolean;
+    function alive(): Boolean;
     procedure SetHealth(aH: Integer);
     procedure Push(vx, vy: Integer);
     function Damage(aDamage: Word; VelX, VelY: Integer; SpawnerUID: Word; t: Byte): Boolean;
@@ -121,8 +135,8 @@ type
     procedure AddTrigger(t: Integer);
     procedure ClearTriggers();
     procedure Respawn();
-    procedure SaveState(var Mem: TBinMemoryWriter);
-    procedure LoadState(var Mem: TBinMemoryReader);
+    procedure SaveState (st: TStream);
+    procedure LoadState (st: TStream);
     procedure SetState(State: Byte; ForceAnim: Byte = 255);
     procedure MakeBloodVector(Count: Word; VelX, VelY: Integer);
     procedure MakeBloodSimple(Count: Word);
@@ -135,15 +149,21 @@ type
 
     procedure positionChanged (); //WARNING! call this after monster position was changed, or coldet will not work right!
 
+    procedure setPosition (ax, ay: Integer; callPosChanged: Boolean=true); inline;
+    procedure moveBy (dx, dy: Integer); inline;
+
     procedure getMapBox (out x, y, w, h: Integer); inline;
 
+    // get-and-clear
+    function gncNeedSend (): Boolean; inline;
+    procedure setDirty (); inline; // why `dirty`? 'cause i may introduce property `needSend` later
+
   public
     property Obj: TObj read FObj;
 
     property proxyId: Integer read mProxyId;
     property arrIdx: Integer read mArrIdx;
 
-  published
     property MonsterType: Byte read FMonsterType;
     property MonsterHealth: Integer read FHealth write FHealth;
     property MonsterAmmo: Integer read FAmmo write FAmmo;
@@ -159,8 +179,8 @@ type
     property UID: Word read FUID write FUID;
     property SpawnTrigger: Integer read FSpawnTrigger write FSpawnTrigger;
 
-    property GameX: Integer read FObj.X write FObj.X;
-    property GameY: Integer read FObj.Y write FObj.Y;
+    property GameX: Integer read FObj.X write setGameX;
+    property GameY: Integer read FObj.Y write setGameY;
     property GameVelX: Integer read FObj.Vel.X write FObj.Vel.X;
     property GameVelY: Integer read FObj.Vel.Y write FObj.Vel.Y;
     property GameAccelX: Integer read FObj.Accel.X write FObj.Accel.X;
@@ -168,6 +188,36 @@ type
     property GameDirection: TDirection read FDirection write FDirection;
 
     property StartID: Integer read FStartID;
+
+  published
+    property eMonsterType: Byte read FMonsterType;
+    property eMonsterHealth: Integer read FHealth write FHealth;
+    property eMonsterAmmo: Integer read FAmmo write FAmmo;
+    property eMonsterTargetUID: Word read FTargetUID write FTargetUID;
+    property eMonsterTargetTime: Integer read FTargetTime write FTargetTime;
+    property eMonsterBehaviour: Byte read FBehaviour write FBehaviour;
+    property eMonsterSleep: Integer read FSleep write FSleep;
+    property eMonsterState: Byte read FState write FState;
+    property eMonsterRemoved: Boolean read FRemoved;
+    property eMonsterPain: Integer read FPain write FPain;
+    property eMonsterAnim: Byte read FCurAnim;
+
+    property eUID: Word read FUID;
+    property eSpawnTrigger: Integer read FSpawnTrigger;
+
+    property eGameX: Integer read FObj.X write setGameX;
+    property eGameY: Integer read FObj.Y write setGameY;
+    property eGameVelX: Integer read FObj.Vel.X write FObj.Vel.X;
+    property eGameVelY: Integer read FObj.Vel.Y write FObj.Vel.Y;
+    property eGameAccelX: Integer read FObj.Accel.X write FObj.Accel.X;
+    property eGameAccelY: Integer read FObj.Accel.Y write FObj.Accel.Y;
+    property eGameDirection: TDirection read FDirection write FDirection;
+
+    property eStartID: Integer read FStartID;
+
+    // set this before assigning something to `eDamage`
+    property eDamageType: Integer read mEDamageType write mEDamageType;
+    property eDamage: Integer write doDamage;
   end;
 
 
@@ -185,11 +235,18 @@ procedure g_Monsters_Draw ();
 procedure g_Monsters_DrawHealth ();
 function  g_Monsters_ByUID (UID: Word): TMonster;
 procedure g_Monsters_killedp ();
-procedure g_Monsters_SaveState (var Mem: TBinMemoryWriter);
-procedure g_Monsters_LoadState (var Mem: TBinMemoryReader);
-function  g_Monsters_GetIDByName (name: String): Integer;
-function  g_Monsters_GetNameByID (MonsterType: Byte): String;
-function  g_Monsters_GetKilledBy (MonsterType: Byte): String;
+procedure g_Monsters_SaveState (st: TStream);
+procedure g_Monsters_LoadState (st: TStream);
+
+function g_Mons_SpawnAt (monType: Integer; x, y: Integer; dir: TDirection=D_LEFT): TMonster; overload;
+function g_Mons_SpawnAt (const typeName: AnsiString; x, y: Integer; dir: TDirection=D_LEFT): TMonster; overload;
+
+function g_Mons_TypeLo (): Integer; inline;
+function g_Mons_TypeHi (): Integer; inline;
+
+function g_Mons_TypeIdByName (const name: AnsiString): Integer;
+function g_Mons_NameByTypeId (monType: Integer): AnsiString;
+function g_Mons_GetKilledByTypeId (monType: Integer): AnsiString;
 
 
 type
@@ -211,7 +268,8 @@ function g_Mons_ForEachAlive (cb: TEachMonsterCB): Boolean;
 function g_Mons_ForEachAt (x, y: Integer; width, height: Integer; cb: TEachMonsterCB): Boolean;
 function g_Mons_ForEachAliveAt (x, y: Integer; width, height: Integer; cb: TEachMonsterCB): Boolean;
 
-function g_Mons_getNewTrapFrameId (): DWord;
+function g_Mons_getNewTrapFrameId (): DWord; inline;
+function g_Mons_getNewMPlatFrameId (): LongWord; inline;
 
 
 type
@@ -250,10 +308,11 @@ var
 implementation
 
 uses
-  e_log, g_main, g_sound, g_gfx, g_player, g_game,
+  e_log, e_texture, g_main, g_sound, g_gfx, g_player, g_game,
   g_weapons, g_triggers, MAPDEF, g_items, g_options,
-  g_console, g_map, Math, SysUtils, g_menu, wadreader,
-  g_language, g_netmsg, idpool;
+  g_console, g_map, Math, g_menu, wadreader,
+  g_language, g_netmsg, idpool, utils, xstreams;
+
 
 
 // ////////////////////////////////////////////////////////////////////////// //
@@ -286,7 +345,8 @@ end;
 
 // ////////////////////////////////////////////////////////////////////////// //
 var
-  monCheckTrapLastFrameId: DWord;
+  monCheckTrapLastFrameId: DWord = 0;
+  monCheckMPlatLastFrameId: LongWord = 0;
 
 
 procedure TMonster.getMapBox (out x, y, w, h: Integer); inline;
@@ -297,6 +357,10 @@ begin
   h := FObj.Rect.Height;
 end;
 
+function TMonster.gncNeedSend (): Boolean; inline; begin result := mNeedSend; mNeedSend := false; end;
+
+procedure TMonster.setDirty (); inline; begin mNeedSend := true; end;
+
 
 // ////////////////////////////////////////////////////////////////////////// //
 function g_Mons_AlongLine (x0, y0, x1, y1: Integer; cb: TMonsAlongLineCB; log: Boolean=false): TMonster;
@@ -317,6 +381,7 @@ begin
   {$ENDIF}
   if (mProxyId = -1) then
   begin
+    //mNeedSend := true;
     mProxyId := monsGrid.insertBody(self, FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, FObj.Rect.Width, FObj.Rect.Height);
     {$IF DEFINED(D2F_DEBUG_MONS_MOVE)}
     monsGrid.getBodyXY(mProxyId, x, y);
@@ -330,6 +395,7 @@ begin
 
     if (w <> nw) or (h <> nh) then
     begin
+      //mNeedSend := true;
       {$IF DEFINED(D2F_DEBUG_MONS_MOVE)}
       e_WriteLog(Format('monster #%d:(%u): resized; mProxyid=%d; gx=%d; gy=%d', [mArrIdx, UID, mProxyId, x-monsGrid.gridX0, y-monsGrid.gridY0]), MSG_NOTIFY);
       {$ENDIF}
@@ -337,6 +403,7 @@ begin
     end
     else if (x <> nx) or (y <> ny) then
     begin
+      //mNeedSend := true;
       {$IF DEFINED(D2F_DEBUG_MONS_MOVE)}
       e_WriteLog(Format('monster #%d:(%u): updating grid; mProxyid=%d; gx=%d; gy=%d', [mArrIdx, UID, mProxyId, x-monsGrid.gridX0, y-monsGrid.gridY0]), MSG_NOTIFY);
       {$ENDIF}
@@ -543,6 +610,7 @@ const
   MAX_SOUL = 512; // Îãðàíè÷åíèå Lost_Soul'îâ
 
 
+// ////////////////////////////////////////////////////////////////////////// //
 var
   gMonsters: array of TMonster;
   uidMap: array [0..65535] of TMonster; // monster knows it's index
@@ -558,12 +626,12 @@ begin
 end;
 
 
-function g_Mons_getNewTrapFrameId (): DWord;
+function g_Mons_getNewTrapFrameId (): DWord; inline;
 var
   f: Integer;
 begin
   Inc(monCheckTrapLastFrameId);
-  if monCheckTrapLastFrameId = 0 then
+  if (monCheckTrapLastFrameId = 0) then
   begin
     // wraparound
     monCheckTrapLastFrameId := 1;
@@ -576,6 +644,24 @@ begin
 end;
 
 
+function g_Mons_getNewMPlatFrameId (): LongWord; inline;
+var
+  f: Integer;
+begin
+  Inc(monCheckMPlatLastFrameId);
+  if (monCheckMPlatLastFrameId = 0) then
+  begin
+    // wraparound
+    monCheckMPlatLastFrameId := 1;
+    for f := 0 to High(gMonsters) do
+    begin
+      if (gMonsters[f] <> nil) then gMonsters[f].mplatCheckFrameId := 0;
+    end;
+  end;
+  result := monCheckMPlatLastFrameId;
+end;
+
+
 var
   pt_x: Integer = 0;
   pt_xs: Integer = 1;
@@ -962,6 +1048,7 @@ begin
   freeInds := TIdPool.Create();
   clearUidMap();
   monCheckTrapLastFrameId := 0;
+  monCheckMPlatLastFrameId := 0;
 end;
 
 procedure g_Monsters_FreeData();
@@ -1202,6 +1289,7 @@ begin
   gMonsters := nil;
   clearUidMap();
   monCheckTrapLastFrameId := 0;
+  monCheckMPlatLastFrameId := 0;
 end;
 
 
@@ -1371,126 +1459,164 @@ begin
   result := uidMap[UID];
 end;
 
-procedure g_Monsters_SaveState(var Mem: TBinMemoryWriter);
+procedure g_Monsters_SaveState (st: TStream);
 var
   count, i: Integer;
-  b: Byte;
 begin
-// Ñ÷èòàåì êîëè÷åñòâî ñóùåñòâóþùèõ ìîíñòðîâ:
+  // Ñ÷èòàåì êîëè÷åñòâî ñóùåñòâóþùèõ ìîíñòðîâ
   count := 0;
-  if (gMonsters <> nil) then
+  for i := 0 to High(gMonsters) do
   begin
-    for i := 0 to High(gMonsters) do
-    begin
-      if (gMonsters[i] <> nil) then
-      begin
-        if (gMonsters[i].FMonsterType <> MONSTER_NONE) then count += 1;
-      end;
-    end;
+    if (gMonsters[i] <> nil) and (gMonsters[i].FMonsterType <> MONSTER_NONE) then count += 1;
   end;
 
-  Mem := TBinMemoryWriter.Create((count+1) * 350);
-
-// Ñîõðàíÿåì èíôîðìàöèþ öåëåóêàçàòåëÿ:
-  Mem.WriteInt(pt_x);
-  Mem.WriteInt(pt_xs);
-  Mem.WriteInt(pt_y);
-  Mem.WriteInt(pt_ys);
+  // Ñîõðàíÿåì èíôîðìàöèþ öåëåóêàçàòåëÿ
+  utils.writeInt(st, LongInt(pt_x));
+  utils.writeInt(st, LongInt(pt_xs));
+  utils.writeInt(st, LongInt(pt_y));
+  utils.writeInt(st, LongInt(pt_ys));
 
-// Êîëè÷åñòâî ìîíñòðîâ:
-  Mem.WriteInt(count);
+  // Êîëè÷åñòâî ìîíñòðîâ
+  utils.writeInt(st, LongInt(count));
 
-  if count = 0 then
-    Exit;
+  if (count = 0) then exit;
 
-// Ñîõðàíÿåì ìîíñòðîâ:
+  // Ñîõðàíÿåì ìîíñòðîâ
   for i := 0 to High(gMonsters) do
   begin
-    if (gMonsters[i] <> nil) then
+    if (gMonsters[i] <> nil) and (gMonsters[i].FMonsterType <> MONSTER_NONE) then
     begin
-      if (gMonsters[i].FMonsterType <> MONSTER_NONE) then
-      begin
-        // Òèï ìîíñòðà:
-        b := gMonsters[i].MonsterType;
-        Mem.WriteByte(b);
-        // Ñîõðàíÿåì äàííûå ìîíñòðà:
-        gMonsters[i].SaveState(Mem);
-      end;
+      // Òèï ìîíñòðà
+      utils.writeInt(st, Byte(gMonsters[i].MonsterType));
+      // Ñîõðàíÿåì äàííûå ìîíñòðà:
+      gMonsters[i].SaveState(st);
     end;
   end;
 end;
 
-procedure g_Monsters_LoadState(var Mem: TBinMemoryReader);
+
+procedure g_Monsters_LoadState (st: TStream);
 var
   count, a: Integer;
   b: Byte;
   mon: TMonster;
 begin
-  if Mem = nil then exit;
+  assert(st <> nil);
 
   g_Monsters_Free(false);
 
   // Çàãðóæàåì èíôîðìàöèþ öåëåóêàçàòåëÿ
-  Mem.ReadInt(pt_x);
-  Mem.ReadInt(pt_xs);
-  Mem.ReadInt(pt_y);
-  Mem.ReadInt(pt_ys);
+  pt_x := utils.readLongInt(st);
+  pt_xs := utils.readLongInt(st);
+  pt_y := utils.readLongInt(st);
+  pt_ys := utils.readLongInt(st);
 
   // Êîëè÷åñòâî ìîíñòðîâ
-  Mem.ReadInt(count);
+  count := utils.readLongInt(st);
 
-  if count = 0 then exit;
+  if (count = 0) then exit;
+  if (count < 0) or (count > 1024*1024) then raise XStreamError.Create('invalid monster count');
 
   // Çàãðóæàåì ìîíñòðîâ
   for a := 0 to count-1 do
   begin
     // Òèï ìîíñòðà
-    Mem.ReadByte(b);
+    b := utils.readByte(st);
     // Ñîçäàåì ìîíñòðà
     mon := g_Monsters_Create(b, 0, 0, D_LEFT);
-    if mon = nil then raise EBinSizeError.Create('g_Monsters_LoadState: ID = -1 (Can''t create)');
+    if (mon = nil) then raise XStreamError.Create('g_Monsters_LoadState: ID = -1 (can''t create)');
     // Çàãðóæàåì äàííûå ìîíñòðà
-    mon.LoadState(Mem);
+    mon.LoadState(st);
+  end;
+end;
+
+
+// ////////////////////////////////////////////////////////////////////////// //
+function g_Mons_SpawnAt (monType: Integer; x, y: Integer; dir: TDirection=D_LEFT): TMonster; overload;
+begin
+  result := nil;
+  if (monType >= MONSTER_DEMON) and (monType <= MONSTER_MAN) then
+  begin
+    result := g_Monsters_Create(monType, x, y, dir);
   end;
 end;
 
-function g_Monsters_GetIDByName(name: String): Integer;
+
+function g_Mons_SpawnAt (const typeName: AnsiString; x, y: Integer; dir: TDirection=D_LEFT): TMonster; overload;
+begin
+  result := g_Mons_SpawnAt(g_Mons_TypeIdByName(typeName), x, y, dir);
+end;
+
+
+
+// ////////////////////////////////////////////////////////////////////////// //
+function g_Mons_TypeLo (): Integer; inline; begin result := Low(MONSTERTABLE); end;
+function g_Mons_TypeHi (): Integer; inline; begin result := High(MONSTERTABLE); end;
+
+
+function g_Mons_TypeIdByName (const name: String): Integer;
 var
   i: Integer;
 begin
-  name := UpperCase(name);
   i := MONSTER_DEMON;
   while (i <= MONSTER_MAN) do
   begin
-    if name = MONSTERTABLE[i].Name then
+    if (CompareText(name, MONSTERTABLE[i].Name) = 0) then
     begin
-      Result := i;
-      Exit;
+      result := i;
+      exit;
     end;
     Inc(i);
   end;
-
-  Result := -1;
+  result := -1;
+  // HACK!
+  if (CompareText(name, 'zombie') = 0) then result := MONSTER_ZOMBY;
 end;
 
-function g_Monsters_GetNameByID(MonsterType: Byte): String;
+
+function g_Mons_NameByTypeId (monType: Integer): AnsiString;
 begin
-  if MonsterType in [MONSTER_DEMON..MONSTER_MAN] then
-    Result := MONSTERTABLE[MonsterType].Name
+  if (monType >= MONSTER_DEMON) and (monType <= MONSTER_MAN) then
+    result := MONSTERTABLE[monType].Name
   else
-    Result := '?';
+    result := '?';
 end;
 
-function g_Monsters_GetKilledBy(MonsterType: Byte): String;
+
+function g_Mons_GetKilledByTypeId (monType: Integer): AnsiString;
 begin
-  if MonsterType in [MONSTER_DEMON..MONSTER_MAN] then
-    Result := KilledByMonster[MonsterType]
+  if (monType >= MONSTER_DEMON) and (monType <= MONSTER_MAN) then
+    Result := KilledByMonster[monType]
   else
     Result := '?';
 end;
 
+
+// ////////////////////////////////////////////////////////////////////////// //
 { T M o n s t e r : }
 
+procedure TMonster.setGameX (v: Integer); inline; begin FObj.X := v; positionChanged(); end;
+procedure TMonster.setGameY (v: Integer); inline; begin FObj.Y := v; positionChanged(); end;
+
+procedure TMonster.setPosition (ax, ay: Integer; callPosChanged: Boolean=true); inline; begin FObj.X := ax; FObj.Y := ay; if callPosChanged then positionChanged(); end;
+
+procedure TMonster.moveBy (dx, dy: Integer); inline;
+begin
+  if (dx <> 0) or (dy <> 0) then
+  begin
+    FObj.X += dx;
+    FObj.Y += dy;
+    positionChanged();
+  end;
+end;
+
+procedure TMonster.doDamage (v: Integer);
+begin
+  if (v <= 0) then exit;
+  if (v > 32767) then v := 32767;
+  Damage(v, 0, 0, 0, mEDamageType);
+end;
+
 procedure TMonster.ActionSound();
 begin
   case FMonsterType of
@@ -1679,8 +1805,8 @@ begin
   FObj.Accel.X := 0;
   FObj.Accel.Y := 0;
   FDirection := FStartDirection;
-  GameX := FStartX;
-  GameY := FStartY;
+  {GameX}FObj.X := FStartX;
+  {GameY}FObj.Y := FStartY;
   FObj.Rect := MONSTERTABLE[FMonsterType].Rect;
   FHealth := MONSTERTABLE[FMonsterType].Health;
   FAmmo := 0;
@@ -1736,10 +1862,13 @@ begin
   FFireTime := 0;
   FFirePainTime := 0;
   FFireAttacker := 0;
+  mEDamageType := HIT_SOME;
 
   mProxyId := -1;
   mArrIdx := -1;
   trapCheckFrameId := 0;
+  mplatCheckFrameId := 0;
+  mNeedSend := false;
 
   if FMonsterType in [MONSTER_ROBO, MONSTER_BARREL] then
     FBloodKind := BLOOD_SPARKS
@@ -1937,9 +2066,10 @@ begin
         it := g_Items_Create(FObj.X + (FObj.Rect.Width div 2),
                              FObj.Y + (FObj.Rect.Height div 2),
                              c, True, False);
+        g_Items_SetDrop(it); // mark it as monster drop
         g_Obj_Push(g_Items_ObjByIdx(it), (FObj.Vel.X div 2)-3+Random(7),
                                         (FObj.Vel.Y div 2)-Random(4));
-        positionChanged(); // this updates spatial accelerators
+        //positionChanged(); // this updates spatial accelerators
         if g_Game_IsServer and g_Game_IsNet then
           MH_SEND_ItemSpawn(True, it);
       end;
@@ -1991,7 +2121,7 @@ begin
   Result := False;
   if g_Game_IsClient then
     Exit;
-  if not Live then
+  if not alive then
     Exit;
 
   if FHealth < FMaxHealth then
@@ -2055,6 +2185,7 @@ begin
                       o.Y+o.Rect.Y+o.Rect.Height-128, M_NONE);
 
 // Íå â îáëàñòè ðèñîâàíèÿ íå ðåñóåì:
+//FIXME!
   if (g_dbg_scale = 1.0) then
   begin
     if not g_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y, FObj.Rect.Width, FObj.Rect.Height,
@@ -2318,7 +2449,7 @@ begin
      (FObj.X > gMapInfo.Width+1000) or (FObj.Y < -1000) then
   begin
     FRemoved := True;
-    if Live and (gLMSRespawn = LMS_RESPAWN_NONE) then
+    if alive and (gLMSRespawn = LMS_RESPAWN_NONE) then
     begin
       Inc(gCoopMonstersKilled);
       if g_Game_IsNet then
@@ -2481,7 +2612,7 @@ begin
         // Åñëè åñòü èãðîê ðÿäîì, ïðîñûïàåìñÿ è èäåì ê íåìó:
           if (gPlayers <> nil) then
             for a := 0 to High(gPlayers) do
-              if (gPlayers[a] <> nil) and (gPlayers[a].Live)
+              if (gPlayers[a] <> nil) and (gPlayers[a].alive)
               and (not gPlayers[a].NoTarget) and (gPlayers[a].FMegaRulez[MR_INVIS] < gTime) then
                 with gPlayers[a] do
                   if g_Look(@FObj, @Obj, FDirection) then
@@ -2499,7 +2630,7 @@ begin
         // Åñëè åñòü ïîäõîäÿùèé ìîíñòð ðÿäîì:
           if gMonsters <> nil then
             for a := 0 to High(gMonsters) do
-              if (gMonsters[a] <> nil) and (gMonsters[a].Live) and
+              if (gMonsters[a] <> nil) and (gMonsters[a].alive) and
                  (gMonsters[a].FUID <> FUID) then
               begin
                 // Ìàíüÿêè íàïàäàþò íà âñåõ ìîíñòðîâ, êðîìå äðóçåé
@@ -2701,7 +2832,7 @@ begin
               if b > 1 then b := b * (Random(8 div b) + 1);
               for a := 0 to High(gGibs) do
               begin
-                if gGibs[a].Live and
+                if gGibs[a].alive and
                    g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y+FObj.Rect.Height-4,
                                  FObj.Rect.Width, 8, @gGibs[a].Obj) and (Random(3) = 0) then
                 begin
@@ -3533,7 +3664,7 @@ begin
               if b > 1 then b := b * (Random(8 div b) + 1);
               for a := 0 to High(gGibs) do
               begin
-                if gGibs[a].Live and
+                if gGibs[a].alive and
                    g_Obj_Collide(FObj.X+FObj.Rect.X, FObj.Y+FObj.Rect.Y+FObj.Rect.Height-4,
                                  FObj.Rect.Width, 8, @gGibs[a].Obj) and (Random(3) = 0) then
                 begin
@@ -3985,7 +4116,7 @@ begin
   if (gPlayers <> nil) and (FBehaviour <> BH_INSANE) and
   (FBehaviour <> BH_CANNIBAL) and (FBehaviour <> BH_GOOD) then
     for a := 0 to High(gPlayers) do
-      if (gPlayers[a] <> nil) and (gPlayers[a].Live)
+      if (gPlayers[a] <> nil) and (gPlayers[a].alive)
       and (not gPlayers[a].NoTarget) and (gPlayers[a].FMegaRulez[MR_INVIS] < gTime) then
       begin
         if g_Look(@FObj, @gPlayers[a].Obj, FDirection) then
@@ -4005,7 +4136,7 @@ begin
   // Êèëëåðû è äîáðûå íå òðîãàþò ìîíñòðîâ
   if (gMonsters <> nil) and (FBehaviour <> BH_KILLER) and (FBehaviour <> BH_GOOD) then
     for a := 0 to High(gMonsters) do
-      if (gMonsters[a] <> nil) and (gMonsters[a].Live) and
+      if (gMonsters[a] <> nil) and (gMonsters[a].alive) and
          (gMonsters[a].FUID <> FUID) then
       begin
         if (FBehaviour = BH_CANNIBAL) and (gMonsters[a].FMonsterType <> FMonsterType) then
@@ -4258,7 +4389,7 @@ begin
   Result := True;
 end;
 
-function TMonster.Live(): Boolean;
+function TMonster.alive(): Boolean;
 begin
   Result := (FState <> MONSTATE_DIE) and (FState <> MONSTATE_DEAD) and (FHealth > 0);
 end;
@@ -4281,187 +4412,170 @@ begin
   WakeUpSound();
 end;
 
-procedure TMonster.SaveState(var Mem: TBinMemoryWriter);
+procedure TMonster.SaveState (st: TStream);
 var
   i: Integer;
-  sig: DWORD;
   b: Byte;
   anim: Boolean;
 begin
-  if Mem = nil then
-    Exit;
-
-// Ñèãíàòóðà ìîíñòðà:
-  sig := MONSTER_SIGNATURE; // 'MONS'
-  Mem.WriteDWORD(sig);
-// UID ìîíñòðà:
-  Mem.WriteWord(FUID);
-// Íàïðàâëåíèå:
-  if FDirection = D_LEFT then
-    b := 1
-  else // D_RIGHT
-    b := 2;
-  Mem.WriteByte(b);
-// Íàäî ëè óäàëèòü åãî:
-  Mem.WriteBoolean(FRemoved);
-// Îñòàëîñü çäîðîâüÿ:
-  Mem.WriteInt(FHealth);
-// Ñîñòîÿíèå:
-  Mem.WriteByte(FState);
-// Òåêóùàÿ àíèìàöèÿ:
-  Mem.WriteByte(FCurAnim);
-// UID öåëè:
-  Mem.WriteWord(FTargetUID);
-// Âðåìÿ ïîñëå ïîòåðè öåëè:
-  Mem.WriteInt(FTargetTime);
-// Ïîâåäåíèå ìîíñòðà:
-  Mem.WriteByte(FBehaviour);
-// Ãîòîâíîñòü ê âûñòðåëó:
-  Mem.WriteInt(FAmmo);
-// Áîëü:
-  Mem.WriteInt(FPain);
-// Âðåìÿ îæèäàíèÿ:
-  Mem.WriteInt(FSleep);
-// Îçâó÷èâàòü ëè áîëü:
-  Mem.WriteBoolean(FPainSound);
-// Áûëà ëè àòàêà âî âðåìÿ àíèìàöèè àòàêè:
-  Mem.WriteBoolean(FWaitAttackAnim);
-// Íàäî ëè ñòðåëÿòü íà ñëåäóþùåì øàãå:
-  Mem.WriteBoolean(FChainFire);
-// Ïîäëåæèò ëè ðåñïàâíó:
-  Mem.WriteBoolean(FNoRespawn);
-// Êîîðäèíàòû öåëè:
-  Mem.WriteInt(tx);
-  Mem.WriteInt(ty);
-// ID ìîíñòðà ïðè ñòàðòå êàðòû:
-  Mem.WriteInt(FStartID);
-// Èíäåêñ òðèããåðà, ñîçäàâøåãî ìîíñòðà:
-  Mem.WriteInt(FSpawnTrigger);
-// Îáúåêò ìîíñòðà:
-  Obj_SaveState(@FObj, Mem);
-// Åñòü ëè àíèìàöèÿ îãíÿ êîëäóíà:
-  anim := vilefire <> nil;
-  Mem.WriteBoolean(anim);
-// Åñëè åñòü - ñîõðàíÿåì:
-  if anim then
-    vilefire.SaveState(Mem);
-// Àíèìàöèè:
+  assert(st <> nil);
+
+  // Ñèãíàòóðà ìîíñòðà:
+  utils.writeSign(st, 'MONS');
+  utils.writeInt(st, Byte(0)); // version
+  // UID ìîíñòðà:
+  utils.writeInt(st, Word(FUID));
+  // Íàïðàâëåíèå
+  if FDirection = D_LEFT then b := 1 else b := 2; // D_RIGHT
+  utils.writeInt(st, Byte(b));
+  // Íàäî ëè óäàëèòü åãî
+  utils.writeBool(st, FRemoved);
+  // Îñòàëîñü çäîðîâüÿ
+  utils.writeInt(st, LongInt(FHealth));
+  // Ñîñòîÿíèå
+  utils.writeInt(st, Byte(FState));
+  // Òåêóùàÿ àíèìàöèÿ
+  utils.writeInt(st, Byte(FCurAnim));
+  // UID öåëè
+  utils.writeInt(st, Word(FTargetUID));
+  // Âðåìÿ ïîñëå ïîòåðè öåëè
+  utils.writeInt(st, LongInt(FTargetTime));
+  // Ïîâåäåíèå ìîíñòðà
+  utils.writeInt(st, Byte(FBehaviour));
+  // Ãîòîâíîñòü ê âûñòðåëó
+  utils.writeInt(st, LongInt(FAmmo));
+  // Áîëü
+  utils.writeInt(st, LongInt(FPain));
+  // Âðåìÿ îæèäàíèÿ
+  utils.writeInt(st, LongInt(FSleep));
+  // Îçâó÷èâàòü ëè áîëü
+  utils.writeBool(st, FPainSound);
+  // Áûëà ëè àòàêà âî âðåìÿ àíèìàöèè àòàêè
+  utils.writeBool(st, FWaitAttackAnim);
+  // Íàäî ëè ñòðåëÿòü íà ñëåäóþùåì øàãå
+  utils.writeBool(st, FChainFire);
+  // Ïîäëåæèò ëè ðåñïàâíó
+  utils.writeBool(st, FNoRespawn);
+  // Êîîðäèíàòû öåëè
+  utils.writeInt(st, LongInt(tx));
+  utils.writeInt(st, LongInt(ty));
+  // ID ìîíñòðà ïðè ñòàðòå êàðòû
+  utils.writeInt(st, LongInt(FStartID));
+  // Èíäåêñ òðèããåðà, ñîçäàâøåãî ìîíñòðà
+  utils.writeInt(st, LongInt(FSpawnTrigger));
+  // Îáúåêò ìîíñòðà
+  Obj_SaveState(st, @FObj);
+  // Åñòü ëè àíèìàöèÿ îãíÿ êîëäóíà
+  anim := (vilefire <> nil);
+  utils.writeBool(st, anim);
+  // Åñëè åñòü - ñîõðàíÿåì:
+  if anim then vilefire.SaveState(st);
+  // Àíèìàöèè
   for i := ANIM_SLEEP to ANIM_PAIN do
   begin
-  // Åñòü ëè ëåâàÿ àíèìàöèÿ:
-    anim := FAnim[i, D_LEFT] <> nil;
-    Mem.WriteBoolean(anim);
-  // Åñëè åñòü - ñîõðàíÿåì:
-    if anim then
-      FAnim[i, D_LEFT].SaveState(Mem);
-  // Åñòü ëè ïðàâàÿ àíèìàöèÿ:
-    anim := FAnim[i, D_RIGHT] <> nil;
-    Mem.WriteBoolean(anim);
-  // Åñëè åñòü - ñîõðàíÿåì:
-    if anim then
-      FAnim[i, D_RIGHT].SaveState(Mem);
+    // Åñòü ëè ëåâàÿ àíèìàöèÿ
+    anim := (FAnim[i, D_LEFT] <> nil);
+    utils.writeBool(st, anim);
+    // Åñëè åñòü - ñîõðàíÿåì
+    if anim then FAnim[i, D_LEFT].SaveState(st);
+    // Åñòü ëè ïðàâàÿ àíèìàöèÿ
+    anim := (FAnim[i, D_RIGHT] <> nil);
+    utils.writeBool(st, anim);
+    // Åñëè åñòü - ñîõðàíÿåì
+    if anim then FAnim[i, D_RIGHT].SaveState(st);
   end;
 end;
 
 
-procedure TMonster.LoadState(var Mem: TBinMemoryReader);
+procedure TMonster.LoadState (st: TStream);
 var
   i: Integer;
-  sig: DWORD;
   b: Byte;
   anim: Boolean;
 begin
-  if Mem = nil then
-    Exit;
+  assert(st <> nil);
 
-// Ñèãíàòóðà ìîíñòðà:
-  Mem.ReadDWORD(sig);
-  if sig <> MONSTER_SIGNATURE then // 'MONS'
-  begin
-    raise EBinSizeError.Create('TMonster.LoadState: Wrong Monster Signature');
-  end;
+  // Ñèãíàòóðà ìîíñòðà:
+  if not utils.checkSign(st, 'MONS') then raise XStreamError.Create('invalid monster signature');
+  if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid monster version');
   if (uidMap[FUID] <> nil) and (uidMap[FUID] <> self) then raise Exception.Create('internal error in monster loader (0)');
   uidMap[FUID] := nil;
-// UID ìîíñòðà:
-  Mem.ReadWord(FUID);
+  // UID ìîíñòðà:
+  FUID := utils.readWord(st);
   //if (arrIdx = -1) then raise Exception.Create('internal error in monster loader');
   if (uidMap[FUID] <> nil) then raise Exception.Create('internal error in monster loader (1)');
   uidMap[FUID] := self;
-// Íàïðàâëåíèå:
-  Mem.ReadByte(b);
-  if b = 1 then
-    FDirection := D_LEFT
-  else // b = 2
-    FDirection := D_RIGHT;
-// Íàäî ëè óäàëèòü åãî:
-  Mem.ReadBoolean(FRemoved);
-// Îñòàëîñü çäîðîâüÿ:
-  Mem.ReadInt(FHealth);
-// Ñîñòîÿíèå:
-  Mem.ReadByte(FState);
-// Òåêóùàÿ àíèìàöèÿ:
-  Mem.ReadByte(FCurAnim);
-// UID öåëè:
-  Mem.ReadWord(FTargetUID);
-// Âðåìÿ ïîñëå ïîòåðè öåëè:
-  Mem.ReadInt(FTargetTime);
-// Ïîâåäåíèå ìîíñòðà:
-  Mem.ReadByte(FBehaviour);
-// Ãîòîâíîñòü ê âûñòðåëó:
-  Mem.ReadInt(FAmmo);
-// Áîëü:
-  Mem.ReadInt(FPain);
-// Âðåìÿ îæèäàíèÿ:
-  Mem.ReadInt(FSleep);
-// Îçâó÷èâàòü ëè áîëü:
-  Mem.ReadBoolean(FPainSound);
-// Áûëà ëè àòàêà âî âðåìÿ àíèìàöèè àòàêè:
-  Mem.ReadBoolean(FWaitAttackAnim);
-// Íàäî ëè ñòðåëÿòü íà ñëåäóþùåì øàãå:
-  Mem.ReadBoolean(FChainFire);
-// Ïîäëåæèò ëè ðåñïàâíó
-  Mem.ReadBoolean(FNoRespawn);
-// Êîîðäèíàòû öåëè:
-  Mem.ReadInt(tx);
-  Mem.ReadInt(ty);
-// ID ìîíñòðà ïðè ñòàðòå êàðòû:
-  Mem.ReadInt(FStartID);
-// Èíäåêñ òðèããåðà, ñîçäàâøåãî ìîíñòðà:
-  Mem.ReadInt(FSpawnTrigger);
-// Îáúåêò ìîíñòðà:
-  Obj_LoadState(@FObj, Mem);
-// Åñòü ëè àíèìàöèÿ îãíÿ êîëäóíà:
-  Mem.ReadBoolean(anim);
-// Åñëè åñòü - çàãðóæàåì:
+  // Íàïðàâëåíèå
+  b := utils.readByte(st);
+  if b = 1 then FDirection := D_LEFT else FDirection := D_RIGHT; // b = 2
+  // Íàäî ëè óäàëèòü åãî
+  FRemoved := utils.readBool(st);
+  // Îñòàëîñü çäîðîâüÿ
+  FHealth := utils.readLongInt(st);
+  // Ñîñòîÿíèå
+  FState := utils.readByte(st);
+  // Òåêóùàÿ àíèìàöèÿ
+  FCurAnim := utils.readByte(st);
+  // UID öåëè
+  FTargetUID := utils.readWord(st);
+  // Âðåìÿ ïîñëå ïîòåðè öåëè
+  FTargetTime := utils.readLongInt(st);
+  // Ïîâåäåíèå ìîíñòðà
+  FBehaviour := utils.readByte(st);
+  // Ãîòîâíîñòü ê âûñòðåëó
+  FAmmo := utils.readLongInt(st);
+  // Áîëü
+  FPain := utils.readLongInt(st);
+  // Âðåìÿ îæèäàíèÿ
+  FSleep := utils.readLongInt(st);
+  // Îçâó÷èâàòü ëè áîëü
+  FPainSound := utils.readBool(st);
+  // Áûëà ëè àòàêà âî âðåìÿ àíèìàöèè àòàêè
+  FWaitAttackAnim := utils.readBool(st);
+  // Íàäî ëè ñòðåëÿòü íà ñëåäóþùåì øàãå
+  FChainFire := utils.readBool(st);
+  // Ïîäëåæèò ëè ðåñïàâíó
+  FNoRespawn := utils.readBool(st);
+  // Êîîðäèíàòû öåëè
+  tx := utils.readLongInt(st);
+  ty := utils.readLongInt(st);
+  // ID ìîíñòðà ïðè ñòàðòå êàðòû
+  FStartID := utils.readLongInt(st);
+  // Èíäåêñ òðèããåðà, ñîçäàâøåãî ìîíñòðà
+  FSpawnTrigger := utils.readLongInt(st);
+  // Îáúåêò ìîíñòðà
+  Obj_LoadState(@FObj, st);
+  // Åñòü ëè àíèìàöèÿ îãíÿ êîëäóíà
+  anim := utils.readBool(st);
+  // Åñëè åñòü - çàãðóæàåì:
   if anim then
   begin
     Assert(vilefire <> nil, 'TMonster.LoadState: no vilefire anim');
-    vilefire.LoadState(Mem);
+    vilefire.LoadState(st);
   end;
-// Àíèìàöèè:
+  // Àíèìàöèè
   for i := ANIM_SLEEP to ANIM_PAIN do
   begin
-  // Åñòü ëè ëåâàÿ àíèìàöèÿ:
-    Mem.ReadBoolean(anim);
-  // Åñëè åñòü - çàãðóæàåì:
+    // Åñòü ëè ëåâàÿ àíèìàöèÿ
+    anim := utils.readBool(st);
+    // Åñëè åñòü - çàãðóæàåì
     if anim then
     begin
-      Assert(FAnim[i, D_LEFT] <> nil,
-        'TMonster.LoadState: no '+IntToStr(i)+'_left anim');
-      FAnim[i, D_LEFT].LoadState(Mem);
+      Assert(FAnim[i, D_LEFT] <> nil, 'TMonster.LoadState: no '+IntToStr(i)+'_left anim');
+      FAnim[i, D_LEFT].LoadState(st);
     end;
-  // Åñòü ëè ïðàâàÿ àíèìàöèÿ:
-     Mem.ReadBoolean(anim);
-  // Åñëè åñòü - çàãðóæàåì:
+    // Åñòü ëè ïðàâàÿ àíèìàöèÿ
+     anim := utils.readBool(st);
+    // Åñëè åñòü - çàãðóæàåì
     if anim then
     begin
-      Assert(FAnim[i, D_RIGHT] <> nil,
-        'TMonster.LoadState: no '+IntToStr(i)+'_right anim');
-      FAnim[i, D_RIGHT].LoadState(Mem);
+      Assert(FAnim[i, D_RIGHT] <> nil, 'TMonster.LoadState: no '+IntToStr(i)+'_right anim');
+      FAnim[i, D_RIGHT].LoadState(st);
     end;
   end;
 end;
 
+
 procedure TMonster.ActivateTriggers();
 var
   a: Integer;
@@ -4566,7 +4680,7 @@ begin
   for idx := 0 to High(gMonsters) do
   begin
     mon := gMonsters[idx];
-    if (mon <> nil) and mon.Live then
+    if (mon <> nil) and mon.alive then
     begin
       result := cb(mon);
       if result then exit;
@@ -4579,7 +4693,7 @@ function g_Mons_IsAnyAliveAt (x, y: Integer; width, height: Integer): Boolean;
 
   function monsCollCheck (mon: TMonster; atag: Integer): Boolean;
   begin
-    result := mon.Live;// and g_Obj_Collide(x, y, width, height, @mon.Obj));
+    result := mon.alive;// and g_Obj_Collide(x, y, width, height, @mon.Obj));
   end;
 
 var
@@ -4597,7 +4711,7 @@ begin
     for idx := 0 to High(gMonsters) do
     begin
       mon := gMonsters[idx];
-      if (mon <> nil) and mon.Live then
+      if (mon <> nil) and mon.alive then
       begin
         if g_Obj_Collide(x, y, width, height, @mon.Obj) then
         begin
@@ -4632,7 +4746,7 @@ begin
     for idx := 0 to High(gMonsters) do
     begin
       mon := gMonsters[idx];
-      if (mon <> nil) and mon.Live then
+      if (mon <> nil) and mon.alive then
       begin
         if g_Obj_Collide(x, y, width, height, @mon.Obj) then
         begin
@@ -4650,8 +4764,8 @@ function g_Mons_ForEachAliveAt (x, y: Integer; width, height: Integer; cb: TEach
   function monsCollCheck (mon: TMonster; atag: Integer): Boolean;
   begin
     //result := false;
-    //if mon.Live and g_Obj_Collide(x, y, width, height, @mon.Obj) then result := cb(mon);
-    if mon.Live then result := cb(mon) else result := false;
+    //if mon.alive and g_Obj_Collide(x, y, width, height, @mon.Obj) then result := cb(mon);
+    if mon.alive then result := cb(mon) else result := false;
   end;
 
 var
@@ -4676,7 +4790,7 @@ begin
     for idx := 0 to High(gMonsters) do
     begin
       mon := gMonsters[idx];
-      if (mon <> nil) and mon.Live then
+      if (mon <> nil) and mon.alive then
       begin
         if g_Obj_Collide(x, y, width, height, @mon.Obj) then
         begin