Reorganizes Project (#41)

This commit is contained in:
Kamron Batman 2019-08-02 18:13:40 -07:00 committed by GitHub
parent 08bf44af9a
commit 3614a66aee
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3499 changed files with 79 additions and 55 deletions

View file

@ -0,0 +1,390 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Server.Items;
using Server.Mobiles;
namespace Server.Regions
{
public abstract class SpawnDefinition
{
public abstract ISpawnable Spawn(SpawnEntry entry);
public abstract bool CanSpawn(params Type[] types);
public static SpawnDefinition GetSpawnDefinition(XmlElement xml)
{
switch (xml.Name)
{
case "object":
{
Type type = null;
if (!Region.ReadType(xml, "type", ref type))
return null;
if (typeof(Mobile).IsAssignableFrom(type)) return SpawnMobile.Get(type);
if (typeof(Item).IsAssignableFrom(type)) return SpawnItem.Get(type);
Console.WriteLine("Invalid type '{0}' in a SpawnDefinition", type.FullName);
return null;
}
case "group":
{
string group = null;
if (!Region.ReadString(xml, "name", ref group))
return null;
if (!SpawnGroup.Table.TryGetValue(group, out SpawnGroup def))
{
Console.WriteLine("Could not find group '{0}' in a SpawnDefinition", group);
return null;
}
return def;
}
case "treasureChest":
{
int itemID = 0xE43;
Region.ReadInt32(xml, "itemID", ref itemID, false);
BaseTreasureChest.TreasureLevel level = BaseTreasureChest.TreasureLevel.Level2;
Region.ReadEnum(xml, "level", ref level, false);
return new SpawnTreasureChest(itemID, level);
}
default:
{
return null;
}
}
}
}
public abstract class SpawnType : SpawnDefinition
{
private bool m_Init;
protected SpawnType(Type type)
{
Type = type;
m_Init = false;
}
public Type Type{ get; }
public abstract int Height{ get; }
public abstract bool Land{ get; }
public abstract bool Water{ get; }
protected void EnsureInit()
{
if (m_Init)
return;
Init();
m_Init = true;
}
protected virtual void Init()
{
}
public override ISpawnable Spawn(SpawnEntry entry)
{
Region region = entry.Region;
Map map = region.Map;
Point3D loc = entry.RandomSpawnLocation(Height, Land, Water);
if (loc == Point3D.Zero)
return null;
return Construct(entry, loc, map);
}
protected abstract ISpawnable Construct(SpawnEntry entry, Point3D loc, Map map);
public override bool CanSpawn(params Type[] types)
{
for (int i = 0; i < types.Length; i++)
if (types[i] == Type)
return true;
return false;
}
}
public class SpawnMobile : SpawnType
{
private static Dictionary<Type, SpawnMobile> m_Table = new Dictionary<Type, SpawnMobile>();
private bool m_Land;
private bool m_Water;
public SpawnMobile(Type type) : base(type)
{
}
public override int Height => 16;
public override bool Land
{
get
{
EnsureInit();
return m_Land;
}
}
public override bool Water
{
get
{
EnsureInit();
return m_Water;
}
}
public static SpawnMobile Get(Type type)
{
if (!m_Table.TryGetValue(type, out SpawnMobile sm))
m_Table[type] = sm = new SpawnMobile(type);
return sm;
}
protected override void Init()
{
Mobile mob = (Mobile)Activator.CreateInstance(Type);
m_Land = !mob.CantWalk;
m_Water = mob.CanSwim;
mob.Delete();
}
protected override ISpawnable Construct(SpawnEntry entry, Point3D loc, Map map)
{
Mobile mobile = CreateMobile();
if (mobile is BaseCreature creature)
{
creature.Home = entry.HomeLocation;
creature.HomeMap = map;
creature.RangeHome = entry.HomeRange;
}
if (entry.Direction != SpawnEntry.InvalidDirection)
mobile.Direction = entry.Direction;
mobile.OnBeforeSpawn(loc, map);
mobile.MoveToWorld(loc, map);
mobile.OnAfterSpawn();
return mobile;
}
protected virtual Mobile CreateMobile()
{
return (Mobile)Activator.CreateInstance(Type);
}
}
public class SpawnItem : SpawnType
{
private static Dictionary<Type, SpawnItem> m_Table = new Dictionary<Type, SpawnItem>();
protected int m_Height;
protected SpawnItem(Type type) : base(type)
{
}
public override int Height
{
get
{
EnsureInit();
return m_Height;
}
}
public override bool Land => true;
public override bool Water => false;
public static SpawnItem Get(Type type)
{
if (!m_Table.TryGetValue(type, out SpawnItem si))
m_Table[type] = si = new SpawnItem(type);
return si;
}
protected override void Init()
{
Item item = (Item)Activator.CreateInstance(Type);
m_Height = item.ItemData.Height;
item.Delete();
}
protected override ISpawnable Construct(SpawnEntry entry, Point3D loc, Map map)
{
Item item = CreateItem();
item.OnBeforeSpawn(loc, map);
item.MoveToWorld(loc, map);
item.OnAfterSpawn();
return item;
}
protected virtual Item CreateItem()
{
return (Item)Activator.CreateInstance(Type);
}
}
public class SpawnTreasureChest : SpawnItem
{
public SpawnTreasureChest(int itemID, BaseTreasureChest.TreasureLevel level) : base(typeof(BaseTreasureChest))
{
ItemID = itemID;
Level = level;
}
public int ItemID{ get; }
public BaseTreasureChest.TreasureLevel Level{ get; }
protected override void Init()
{
m_Height = TileData.ItemTable[ItemID & TileData.MaxItemValue].Height;
}
protected override Item CreateItem()
{
return new BaseTreasureChest(ItemID, Level);
}
}
public class SpawnGroupElement
{
public SpawnGroupElement(SpawnDefinition spawnDefinition, int weight)
{
SpawnDefinition = spawnDefinition;
Weight = weight;
}
public SpawnDefinition SpawnDefinition{ get; }
public int Weight{ get; }
}
public class SpawnGroup : SpawnDefinition
{
private int m_TotalWeight;
static SpawnGroup()
{
string path = Path.Combine(Core.BaseDirectory, "Data/SpawnDefinitions.xml");
if (!File.Exists(path))
return;
try
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc["spawnDefinitions"];
if (root == null)
return;
foreach (XmlElement xmlDef in root.SelectNodes("spawnGroup"))
{
string name = null;
if (!Region.ReadString(xmlDef, "name", ref name))
continue;
List<SpawnGroupElement> list = new List<SpawnGroupElement>();
foreach (XmlNode node in xmlDef.ChildNodes)
{
if (node is XmlElement el)
{
SpawnDefinition def = GetSpawnDefinition(el);
if (def == null)
continue;
int weight = 1;
Region.ReadInt32(el, "weight", ref weight, false);
SpawnGroupElement groupElement = new SpawnGroupElement(def, weight);
list.Add(groupElement);
}
}
SpawnGroupElement[] elements = list.ToArray();
SpawnGroup group = new SpawnGroup(name, elements);
Register(group);
}
}
catch (Exception ex)
{
Console.WriteLine("Could not load SpawnDefinitions.xml: " + ex.Message);
}
}
public SpawnGroup(string name, SpawnGroupElement[] elements)
{
Name = name;
Elements = elements;
m_TotalWeight = 0;
for (int i = 0; i < elements.Length; i++)
m_TotalWeight += elements[i].Weight;
}
public static Dictionary<string, SpawnGroup> Table{ get; } = new Dictionary<string, SpawnGroup>();
public string Name{ get; }
public SpawnGroupElement[] Elements{ get; }
public static void Register(SpawnGroup group)
{
if (Table.ContainsKey(group.Name))
Console.WriteLine("Warning: Double SpawnGroup name '{0}'", group.Name);
else
Table[group.Name] = group;
}
public override ISpawnable Spawn(SpawnEntry entry)
{
int index = Utility.Random(m_TotalWeight);
for (int i = 0; i < Elements.Length; i++)
{
SpawnGroupElement element = Elements[i];
if (index < element.Weight)
return element.SpawnDefinition.Spawn(entry);
index -= element.Weight;
}
return null;
}
public override bool CanSpawn(params Type[] types)
{
for (int i = 0; i < Elements.Length; i++)
if (Elements[i].SpawnDefinition.CanSpawn(types))
return true;
return false;
}
}
}

View file

@ -0,0 +1,435 @@
using System;
using System.Collections.Generic;
using Server.Commands;
using Server.Mobiles;
namespace Server.Regions
{
public class SpawnEntry : ISpawner
{
public static readonly TimeSpan DefaultMinSpawnTime = TimeSpan.FromMinutes(2.0);
public static readonly TimeSpan DefaultMaxSpawnTime = TimeSpan.FromMinutes(5.0);
public static readonly Direction InvalidDirection = Direction.Running;
private static List<IEntity> m_RemoveList;
private DateTime m_NextSpawn;
private Timer m_SpawnTimer;
public SpawnEntry(int id, BaseRegion region, Point3D home, int range, Direction direction,
SpawnDefinition definition, int max, TimeSpan minSpawnTime, TimeSpan maxSpawnTime)
{
ID = id;
Region = region;
HomeLocation = home;
HomeRange = range;
Direction = direction;
Definition = definition;
SpawnedObjects = new List<ISpawnable>();
Max = max;
MinSpawnTime = minSpawnTime;
MaxSpawnTime = maxSpawnTime;
Running = false;
if (Table.ContainsKey(id))
Console.WriteLine("Warning: double SpawnEntry ID '{0}'", id);
else
Table[id] = this;
}
public static Dictionary<int, SpawnEntry> Table{ get; } = new Dictionary<int, SpawnEntry>();
// When a creature's AI is deactivated (PlayerRangeSensitive optimization) does it return home?
public bool ReturnOnDeactivate => true;
// Are unlinked and untamed creatures removed after 20 hours?
public bool RemoveIfUntamed => true;
public int ID{ get; }
public BaseRegion Region{ get; }
public Direction Direction{ get; }
public SpawnDefinition Definition{ get; }
public List<ISpawnable> SpawnedObjects{ get; }
public int Max{ get; private set; }
public TimeSpan MinSpawnTime{ get; }
public TimeSpan MaxSpawnTime{ get; }
public bool Running{ get; private set; }
public bool Complete => SpawnedObjects.Count >= Max;
public bool Spawning => Running && !Complete;
// Are creatures unlinked on taming (true) or should they also go out of the region (false)?
public bool UnlinkOnTaming => false;
Region ISpawner.Region => Region;
public Point3D HomeLocation{ get; }
public int HomeRange{ get; }
void ISpawner.Remove(ISpawnable spawn)
{
SpawnedObjects.Remove(spawn);
CheckTimer();
}
public Point3D RandomSpawnLocation(int spawnHeight, bool land, bool water)
{
return Region.RandomSpawnLocation(spawnHeight, land, water, HomeLocation, HomeRange);
}
public void Start()
{
if (Running)
return;
Running = true;
CheckTimer();
}
public void Stop()
{
if (!Running)
return;
Running = false;
CheckTimer();
}
private void Spawn()
{
ISpawnable spawn = Definition.Spawn(this);
if (spawn != null)
Add(spawn);
}
private void Add(ISpawnable spawn)
{
SpawnedObjects.Add(spawn);
spawn.Spawner = this;
if (spawn is BaseCreature creature)
creature.RemoveIfUntamed = RemoveIfUntamed;
}
private TimeSpan RandomTime()
{
int min = (int)MinSpawnTime.TotalSeconds;
int max = (int)MaxSpawnTime.TotalSeconds;
int rand = Utility.RandomMinMax(min, max);
return TimeSpan.FromSeconds(rand);
}
private void CheckTimer()
{
if (Spawning)
{
if (m_SpawnTimer == null)
{
TimeSpan time = RandomTime();
m_SpawnTimer = Timer.DelayCall(time, TimerCallback);
m_NextSpawn = DateTime.UtcNow + time;
}
}
else if (m_SpawnTimer != null)
{
m_SpawnTimer.Stop();
m_SpawnTimer = null;
}
}
private void TimerCallback()
{
int amount = Math.Max((Max - SpawnedObjects.Count) / 3, 1);
for (int i = 0; i < amount; i++)
Spawn();
m_SpawnTimer = null;
CheckTimer();
}
public void DeleteSpawnedObjects()
{
InternalDeleteSpawnedObjects();
Running = false;
CheckTimer();
}
private void InternalDeleteSpawnedObjects()
{
foreach (ISpawnable spawnable in SpawnedObjects)
{
spawnable.Spawner = null;
bool uncontrolled = !(spawnable is BaseCreature) || !((BaseCreature)spawnable).Controlled;
if (uncontrolled)
spawnable.Delete();
}
SpawnedObjects.Clear();
}
public void Respawn()
{
InternalDeleteSpawnedObjects();
for (int i = 0; !Complete && i < Max; i++)
Spawn();
Running = true;
CheckTimer();
}
public void Delete()
{
Max = 0;
InternalDeleteSpawnedObjects();
if (m_SpawnTimer != null)
{
m_SpawnTimer.Stop();
m_SpawnTimer = null;
}
if (Table.TryGetValue(ID, out SpawnEntry entry) && entry == this)
Table.Remove(ID);
}
public void Serialize(GenericWriter writer)
{
writer.Write(SpawnedObjects.Count);
for (int i = 0; i < SpawnedObjects.Count; i++)
writer.Write(SpawnedObjects[i].Serial);
writer.Write(Running);
if (m_SpawnTimer != null)
{
writer.Write(true);
writer.WriteDeltaTime(m_NextSpawn);
}
else
{
writer.Write(false);
}
}
public void Deserialize(GenericReader reader, int version)
{
int count = reader.ReadInt();
for (int i = 0; i < count; i++)
{
if (World.FindEntity(reader.ReadUInt()) is ISpawnable spawnableEntity)
Add(spawnableEntity);
}
Running = reader.ReadBool();
if (reader.ReadBool())
{
m_NextSpawn = reader.ReadDeltaTime();
if (Spawning)
{
m_SpawnTimer?.Stop();
TimeSpan delay = m_NextSpawn - DateTime.UtcNow;
m_SpawnTimer = Timer.DelayCall(delay > TimeSpan.Zero ? delay : TimeSpan.Zero, TimerCallback);
}
}
CheckTimer();
}
public static void Remove(GenericReader reader, int version)
{
int count = reader.ReadInt();
for (int i = 0; i < count; i++)
{
IEntity entity = World.FindEntity(reader.ReadUInt());
if (entity != null)
{
if (m_RemoveList == null)
m_RemoveList = new List<IEntity>();
m_RemoveList.Add(entity);
}
}
reader.ReadBool(); // m_Running
if (reader.ReadBool())
reader.ReadDeltaTime(); // m_NextSpawn
}
public static void Initialize()
{
if (m_RemoveList != null)
{
foreach (IEntity ent in m_RemoveList) ent.Delete();
m_RemoveList = null;
}
SpawnPersistence.EnsureExistence();
CommandSystem.Register("RespawnAllRegions", AccessLevel.Administrator, RespawnAllRegions_OnCommand);
CommandSystem.Register("RespawnRegion", AccessLevel.GameMaster, RespawnRegion_OnCommand);
CommandSystem.Register("DelAllRegionSpawns", AccessLevel.Administrator, DelAllRegionSpawns_OnCommand);
CommandSystem.Register("DelRegionSpawns", AccessLevel.GameMaster, DelRegionSpawns_OnCommand);
CommandSystem.Register("StartAllRegionSpawns", AccessLevel.Administrator, StartAllRegionSpawns_OnCommand);
CommandSystem.Register("StartRegionSpawns", AccessLevel.GameMaster, StartRegionSpawns_OnCommand);
CommandSystem.Register("StopAllRegionSpawns", AccessLevel.Administrator, StopAllRegionSpawns_OnCommand);
CommandSystem.Register("StopRegionSpawns", AccessLevel.GameMaster, StopRegionSpawns_OnCommand);
}
private static BaseRegion GetCommandData(CommandEventArgs args)
{
Mobile from = args.Mobile;
Region reg;
if (args.Length == 0)
{
reg = from.Region;
}
else
{
string name = args.GetString(0);
if (!from.Map.Regions.TryGetValue(name, out reg))
{
from.SendMessage("Could not find region '{0}'.", name);
return null;
}
}
if (reg is BaseRegion br && br.Spawns != null)
return br;
from.SendMessage("There are no spawners in region '{0}'.", reg);
return null;
}
[Usage("RespawnAllRegions")]
[Description("Respawns all regions and sets the spawners as running.")]
private static void RespawnAllRegions_OnCommand(CommandEventArgs args)
{
foreach (SpawnEntry entry in Table.Values)
entry.Respawn();
args.Mobile.SendMessage("All regions have respawned.");
}
[Usage("RespawnRegion [<region name>]")]
[Description("Respawns the region in which you are (or that you provided) and sets the spawners as running.")]
private static void RespawnRegion_OnCommand(CommandEventArgs args)
{
BaseRegion region = GetCommandData(args);
if (region == null)
return;
for (int i = 0; i < region.Spawns.Length; i++)
region.Spawns[i].Respawn();
args.Mobile.SendMessage("Region '{0}' has respawned.", region);
}
[Usage("DelAllRegionSpawns")]
[Description("Deletes all spawned objects of every regions and sets the spawners as not running.")]
private static void DelAllRegionSpawns_OnCommand(CommandEventArgs args)
{
foreach (SpawnEntry entry in Table.Values)
entry.DeleteSpawnedObjects();
args.Mobile.SendMessage("All region spawned objects have been deleted.");
}
[Usage("DelRegionSpawns [<region name>]")]
[Description(
"Deletes all spawned objects of the region in which you are (or that you provided) and sets the spawners as not running.")]
private static void DelRegionSpawns_OnCommand(CommandEventArgs args)
{
BaseRegion region = GetCommandData(args);
if (region == null)
return;
for (int i = 0; i < region.Spawns.Length; i++)
region.Spawns[i].DeleteSpawnedObjects();
args.Mobile.SendMessage("Spawned objects of region '{0}' have been deleted.", region);
}
[Usage("StartAllRegionSpawns")]
[Description("Sets the region spawners of all regions as running.")]
private static void StartAllRegionSpawns_OnCommand(CommandEventArgs args)
{
foreach (SpawnEntry entry in Table.Values)
entry.Start();
args.Mobile.SendMessage("All region spawners have started.");
}
[Usage("StartRegionSpawns [<region name>]")]
[Description("Sets the region spawners of the region in which you are (or that you provided) as running.")]
private static void StartRegionSpawns_OnCommand(CommandEventArgs args)
{
BaseRegion region = GetCommandData(args);
if (region == null)
return;
for (int i = 0; i < region.Spawns.Length; i++)
region.Spawns[i].Start();
args.Mobile.SendMessage("Spawners of region '{0}' have started.", region);
}
[Usage("StopAllRegionSpawns")]
[Description("Sets the region spawners of all regions as not running.")]
private static void StopAllRegionSpawns_OnCommand(CommandEventArgs args)
{
foreach (SpawnEntry entry in Table.Values)
entry.Stop();
args.Mobile.SendMessage("All region spawners have stopped.");
}
[Usage("StopRegionSpawns [<region name>]")]
[Description("Sets the region spawners of the region in which you are (or that you provided) as not running.")]
private static void StopRegionSpawns_OnCommand(CommandEventArgs args)
{
BaseRegion region = GetCommandData(args);
if (region == null)
return;
for (int i = 0; i < region.Spawns.Length; i++)
region.Spawns[i].Stop();
args.Mobile.SendMessage("Spawners of region '{0}' have stopped.", region);
}
}
}

View file

@ -0,0 +1,63 @@
namespace Server.Regions
{
[TypeAlias("Server.Regions.SpawnPersistance")]
public class SpawnPersistence : Item
{
private static SpawnPersistence m_Instance;
private SpawnPersistence() : base(1)
{
Movable = false;
}
public SpawnPersistence(Serial serial) : base(serial)
{
m_Instance = this;
}
public SpawnPersistence Instance => m_Instance;
public override string DefaultName => "Region spawn persistence - Internal";
public static void EnsureExistence()
{
if (m_Instance == null)
m_Instance = new SpawnPersistence();
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.WriteEncodedInt(0); // version
writer.Write(SpawnEntry.Table.Values.Count);
foreach (SpawnEntry entry in SpawnEntry.Table.Values)
{
writer.Write(entry.ID);
entry.Serialize(writer);
}
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadEncodedInt();
int count = reader.ReadInt();
for (int i = 0; i < count; i++)
{
int id = reader.ReadInt();
SpawnEntry entry = SpawnEntry.Table[id];
if (entry != null)
entry.Deserialize(reader, version);
else
SpawnEntry.Remove(reader, version);
}
}
}
}