city-generation/Game/Assets/Scripts/Model/Map.cs

158 lines
4.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace TransportGame.Model
{
[XmlRoot("map")]
public class Map
{
private float[,] grid;
/// <summary>
/// Gets or sets the water level
/// </summary>
[XmlElement("waterLevel")]
public float WaterLevel { get; set; }
/// <summary>
/// Gets or sets the biome
/// </summary>
[XmlElement("biome")]
public Biome Biome { get; set; }
/// <summary>
/// Gets the heights array in range [0,1]
/// </summary>
[XmlIgnore()]
public float[,] Heights
{
get
{
return grid;
}
}
/// <summary>
/// Gets or sets the heights as raw bytes
/// </summary>
/// <remarks>
/// Bytes are stored as such:
///
/// Offset Size Content
/// ------------------------
/// 0 4 Width
/// 4 8 Height
/// 8 var 32bit floating point values
///
/// </remarks>
[XmlElement("heights")]
public byte[] HeightsRaw
{
get
{
List<byte> bytes = new List<byte>();
bytes.AddRange(BitConverter.GetBytes(Width));
bytes.AddRange(BitConverter.GetBytes(Height));
for (int x = 0; x < Width; x++)
for (int y = 0; y < Height; y++)
bytes.AddRange(BitConverter.GetBytes(grid[x, y]));
return bytes.ToArray();
}
set
{
int pos = 0;
int w = BitConverter.ToInt32(value, pos); pos += sizeof(int);
int h = BitConverter.ToInt32(value, pos); pos += sizeof(int);
grid = new float[w, h];
for (int x = 0; x < w; x++)
for (int y = 0; y < h; y++)
{
grid[x, y] = BitConverter.ToSingle(value, pos);
pos += sizeof(float);
}
}
}
/// <summary>
/// Initializes the map
/// </summary>
/// <remarks>
/// Warning: heights array will be null.
/// </remarks>
public Map()
{
}
/// <summary>
/// Initializes the map
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
public Map(int width, int height)
{
grid = new float[width, height];
}
/// <summary>
/// Gets or sets the cell at specified position in range [0, Biome.Height]
/// </summary>
/// <param name="x">X</param>
/// <param name="y">Y</param>
/// <returns>Cell</returns>
[XmlIgnore]
public float this[int x, int y]
{
get
{
return grid[x, y] * Biome.Height;
}
set
{
grid[x, y] = value / Biome.Height;
}
}
/// <summary>
/// Gets width of map
/// </summary>
[XmlIgnore]
public int Width { get { return grid.GetLength(0); } }
/// <summary>
/// Gets height of map
/// </summary>
[XmlIgnore]
public int Height { get { return grid.GetLength(1); } }
/// <summary>
/// Returns true if specified cell is a water cell
/// </summary>
/// <param name="x">X</param>
/// <param name="y">Y</param>
/// <returns></returns>
public bool IsWater(int x, int y)
{
return this[x, y] <= WaterLevel;
}
/// <summary>
/// Returns true if given coordinates is inside the map
/// </summary>
/// <param name="x">X</param>
/// <param name="y">Y</param>
/// <returns>True if coordinates are inside the map</returns>
public bool IsInside(int x, int y)
{
return x >= 0 && y >= 0 && x < Width && y < Height;
}
}
}