Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The serializer, unit base, and some tile fix attempts. #41

Merged
merged 3 commits into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 174 additions & 0 deletions Backend/Serializer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

/*
*
* Todo: Complex types like lists and such. Right now it only will save the basic types and strings.
*
*
*/


namespace JuniorProject.Backend
{
public abstract class Serializable
{

public abstract int fieldCount { get; } //If -1, ignore.

public unsafe byte[] SerializeField<T>(T objectToSerialize) where T : unmanaged
{

byte[] field = new byte[sizeof(T)];
byte* p = (byte*)&objectToSerialize;
for (int i = 0; i < field.Length; i++)
{
field[i] = *p++;
}
return field;
}

public unsafe byte[] SerializeField(string stringToSerialize)
{
byte[] field = new byte[stringToSerialize.Length + 1];
for (int i = 1; i < stringToSerialize.Length + 1; i++)
{
field[i] = (byte)stringToSerialize[i - 1];
}
field[0] = (byte)stringToSerialize.Length; //This is for correct string formatting for BinaryReader.ReadString.
return field;
}

public abstract void SerializeFields(List<byte[]> serializedFields);
public abstract void Deserialize(BinaryReader reader);

public List<byte[]> Serialize()
{
List<byte[]> fields = new List<byte[]>();
SerializeFields(fields);
if (fields.Count == 0)
{
Debug.Print($"{this} was passed into Serialization, but there were no fields saved.");
}
return fields;
}
}

class Serializer
{
Dictionary<Type, List<Serializable>> objectList = new Dictionary<Type, List<Serializable>>();
string file_location;


public Serializer(string file_location)
{
this.file_location = file_location;
}


public void SaveObject(Serializable objectToSerialize)
{
Type objectType = objectToSerialize.GetType();
if (!objectList.ContainsKey(objectType))
{
objectList[objectType] = new List<Serializable>();
}
objectList[objectType].Add(objectToSerialize);
}

public void Save()
{
FileStream fileStream = File.OpenWrite(file_location);
fileStream.Flush(true);
BinaryWriter writer = new BinaryWriter(fileStream, Encoding.ASCII, false);

int typeCount = objectList.Count;
Dictionary<Type, int> fieldCounts = new Dictionary<Type, int>();

foreach (Type type in objectList.Keys)
{
fieldCounts[type] = objectList[type][0].fieldCount;
}

if (typeCount == 0)
{
Debug.Print("Save was called without any objects to be saved.");
return;
}

writer.Write(typeCount); //Save type count.
foreach (KeyValuePair<Type, int> fieldCount in fieldCounts)
{
writer.Write(fieldCount.Key.ToString()); //Write the type.
writer.Write(objectList[fieldCount.Key].Count); //Write how many there are.
writer.Write(fieldCount.Value); //Write how many fields each object should have.
}

foreach (Type type in objectList.Keys)
{
foreach (Serializable serializable in objectList[type])
{
List<byte[]> fields = serializable.Serialize();
foreach (byte[] field in fields)
{
writer.Write(field);
}
}
}
fileStream.Close();
}

public Dictionary<Type, List<Serializable>> Load()
{
objectList = new Dictionary<Type, List<Serializable>>();
FileStream fileStream = File.OpenRead(file_location);
BinaryReader reader = new BinaryReader(fileStream);

int typeCount = reader.ReadInt32(); //Load type count;
if (typeCount == 0)
{
Debug.Print($"{file_location} is an empty file, nothing loaded.");
return new Dictionary<Type, List<Serializable>>();
}

Dictionary<Type, int> objectCounts = new Dictionary<Type, int>();
Dictionary<Type, int> fieldCounts = new Dictionary<Type, int>();

for (int i = 0; i < typeCount; i++)
{
string typeString = reader.ReadString(); //Load type.
Type? type = Type.GetType(typeString);
if (type == null)
{
Debug.Print($"{typeString} was read in as a type from {file_location}, however, that type does not exist.");
return new Dictionary<Type, List<Serializable>>();
}
objectList.Add(type, new List<Serializable>());
objectCounts.Add(type, reader.ReadInt32()); //Load the object count.
fieldCounts.Add(type, reader.ReadInt32()); //load the object field count.
}

foreach (Type type in objectList.Keys)
{
for (int i = 0; i < objectCounts[type]; i++)
{
Serializable serializable = (Serializable)Activator.CreateInstance(type);
if (serializable.fieldCount != fieldCounts[type] && (serializable.fieldCount != -1 && fieldCounts[type] != -1))
{
Debug.Print($"The type [{type.Name}] tried to be loaded from {file_location} with {serializable.fieldCount} fields, " +
$"however, the file has {fieldCounts[type]} fields.");
return new Dictionary<Type, List<Serializable>>();
}
serializable.Deserialize(reader);
objectList[type].Add(serializable);
}
}
return objectList;

}



}
}
20 changes: 0 additions & 20 deletions Backend/Unit.cs

This file was deleted.

45 changes: 40 additions & 5 deletions Backend/WorldData/Map.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Data.SQLite;
using System.Diagnostics;
using System.Drawing;
using System.IO;

namespace JuniorProject.Backend.WorldData
{
Expand All @@ -12,7 +13,7 @@

public class TerrainData
{
public string name;

Check warning on line 16 in Backend/WorldData/Map.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable field 'name' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the field as nullable.
public Color tileColor;
public int movementCost;
public float heightMin;
Expand All @@ -28,11 +29,36 @@
float[,] heightMap;


public class Tile
public class Tile : Serializable
{
public Dictionary<string, float> terrainPercentages = new Dictionary<string, float>();
public int movementCost;

public override int fieldCount { get { return -1; } }

public override void Deserialize(BinaryReader reader)
{
movementCost = reader.ReadInt32();
int terrainPercentagesCount = reader.ReadInt32();
for (int i = 0; i < terrainPercentagesCount; i++)
{
terrainPercentages.Add(reader.ReadString(), reader.ReadSingle());
}
}

public override void SerializeFields(List<byte[]> serializedFields)
{
serializedFields.Add(SerializeField(movementCost));
serializedFields.Add(SerializeField(terrainPercentages.Count));
foreach (KeyValuePair<string, float> percentage in terrainPercentages)
{
serializedFields.Add(SerializeField(percentage.Key));
serializedFields.Add(SerializeField(percentage.Value));
}
}
}


const int TILE_SIZE = 20;
int mapHeight, mapWidth;
Tile[,] tiles;
Expand All @@ -41,9 +67,6 @@
return tiles[x, y];
}




public Map()
{
Debug.Print("Loading Terrain Data...");
Expand All @@ -57,6 +80,17 @@

~Map() { }

public void SaveMap(Serializer serializable)
{
for (int tileX = 0; tileX < mapWidth; tileX++)
{
for (int tileY = 0; tileY < mapHeight; tileY++)
{
serializable.SaveObject(getTile(tileX, tileY));
}
}
}

void LoadTerrain()
{
SQLiteDataReader results = DatabaseManager.ReadDB("SELECT * FROM Terrain;");
Expand Down Expand Up @@ -172,7 +206,7 @@
if (tileX * TILE_SIZE + x > MAP_PIXEL_WIDTH) continue;
if (tileY * TILE_SIZE + y > MAP_PIXEL_HEIGHT) continue;

string landType = terrainMap[x, y].landType;
string landType = terrainMap[x, y].name;
if (landTypes.ContainsKey(landType))
{
landTypes[landType]++;
Expand All @@ -191,6 +225,7 @@
tile.terrainPercentages.Add(landType, relativePercentage);
}
tile.movementCost = movementCostTotal / (TILE_SIZE * TILE_SIZE);
tiles[tileX, tileY] = tile;
}
}
}
Expand Down
45 changes: 45 additions & 0 deletions Backend/WorldData/Unit.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@



using System.IO;

namespace JuniorProject.Backend.WorldData
{
class Unit : Serializable
{
struct UnitTemplate //The template of the unit, the type if you will.
{
public string name;
public string description;
public int maxHealth;
}

UnitTemplate unitType;
public int health;


Map.Tile pos;

public override int fieldCount
{
get { return 2; }
}

public Unit()
{

}

public override void SerializeFields(List<byte[]> serializedFields)
{
serializedFields.Add(SerializeField(health));
serializedFields.Add(SerializeField("12345"));
}

public override void Deserialize(BinaryReader reader)
{
health = reader.ReadInt32();
string r = reader.ReadString();
}
}
}
28 changes: 27 additions & 1 deletion Backend/WorldData/World.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,40 @@ namespace JuniorProject.Backend.WorldData
class World
{
Map map;
List<Unit> units = new List<Unit>();

public World()
{
map = new Map();
ClientCommunicator.RegisterAction("RegenerateWorld", map.GenerateWorld);
ClientCommunicator.RegisterAction("SaveWorld", map.SaveImage);
ClientCommunicator.RegisterAction("SaveWorld", SaveWorld);
ClientCommunicator.RegisterData<Bitmap>("WorldImage", map.worldImage);
ClientCommunicator.RegisterData<World>("World", map);

units.Add(new Unit());
units.Add(new Unit());
units.Add(new Unit());
units.Add(new Unit());
units.Add(new Unit());
units.Add(new Unit());

}

public void SaveWorld()
{
map.SaveImage();
Serializer serializer = new Serializer("LocalData\\Savetest.chs");
Debug.Print("Saving units...");
foreach (Unit unit in units)
{
serializer.SaveObject(unit);
}
Debug.Print("Saving tiles...");
map.SaveMap(serializer);

Debug.Print("Writing to file...");
serializer.Save();
Debug.Print("Saved!");
}

}
Expand Down
Binary file modified LocalData/Map.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,6 @@
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ProjectDir" xml:space="preserve">
<value>E:\repos\JuniorProjectTeamB\</value>
<value>C:\Users\wythe\Desktop\JuniorProject\</value>
</data>
</root>
Loading