Merge pull request #1 from simon987/master

getting up to date
This commit is contained in:
sg495 2018-01-03 13:04:59 +01:00 committed by GitHub
commit ba53212986
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
43 changed files with 707 additions and 414 deletions

View File

@ -1,5 +1,7 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.Memory; import net.simon987.server.assembly.Memory;
import net.simon987.server.game.*; import net.simon987.server.game.*;
@ -114,16 +116,41 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit, Pr
return json; return json;
} }
public static Cubot deserialize(JSONObject json) { @Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("i", getObjectId());
dbObject.put("t", ID);
dbObject.put("x", getX());
dbObject.put("y", getY());
dbObject.put("direction", getDirection().ordinal());
dbObject.put("heldItem", heldItem);
dbObject.put("hp", hp);
dbObject.put("action", lastAction.ordinal());
dbObject.put("holo", hologram);
dbObject.put("holoStr", hologramString);
dbObject.put("holoMode", lastHologramMode.ordinal());
dbObject.put("holoC", hologramColor);
dbObject.put("energy", energy);
if (parent != null) {
dbObject.put("parent", parent.getUsername()); //Only used client-side for now
}
return dbObject;
}
public static Cubot deserialize(DBObject obj) {
Cubot cubot = new Cubot(); Cubot cubot = new Cubot();
cubot.setObjectId((long) json.get("i")); cubot.setObjectId((long) obj.get("i"));
cubot.setX((int) (long) json.get("x")); cubot.setX((int) obj.get("x"));
cubot.setY((int) (long) json.get("y")); cubot.setY((int) obj.get("y"));
cubot.hp = (int) (long) json.get("hp"); cubot.hp = (int) obj.get("hp");
cubot.setDirection(Direction.getDirection((int) (long) json.get("direction"))); cubot.setDirection(Direction.getDirection((int) obj.get("direction")));
cubot.heldItem = (int) (long) json.get("heldItem"); cubot.heldItem = (int) obj.get("heldItem");
cubot.energy = (int) (long) json.get("energy"); cubot.energy = (int) obj.get("energy");
cubot.maxEnergy = GameServer.INSTANCE.getConfig().getInt("battery_max_energy"); cubot.maxEnergy = GameServer.INSTANCE.getConfig().getInt("battery_max_energy");
return cubot; return cubot;

View File

@ -1,9 +1,10 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import org.json.simple.JSONObject;
public class CubotBattery extends CpuHardware { public class CubotBattery extends CpuHardware {
@ -44,16 +45,19 @@ public class CubotBattery extends CpuHardware {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json; BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
} }
public static CubotBattery deserialize(JSONObject hwJSON) {
return new CubotBattery((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot"))); public static CubotBattery deserialize(DBObject obj) {
return new CubotBattery((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }
} }

View File

@ -1,11 +1,12 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import net.simon987.server.game.GameObject; import net.simon987.server.game.GameObject;
import net.simon987.server.game.Programmable; import net.simon987.server.game.Programmable;
import org.json.simple.JSONObject;
import java.awt.*; import java.awt.*;
import java.util.ArrayList; import java.util.ArrayList;
@ -123,15 +124,17 @@ public class CubotComPort extends CpuHardware {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json; BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
} }
public static CubotComPort deserialize(JSONObject json) { public static CubotComPort deserialize(DBObject obj) {
return new CubotComPort((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) json.get("cubot"))); return new CubotComPort((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }
} }

View File

@ -1,11 +1,12 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import net.simon987.server.game.Action; import net.simon987.server.game.Action;
import net.simon987.server.game.TileMap; import net.simon987.server.game.TileMap;
import org.json.simple.JSONObject;
public class CubotDrill extends CpuHardware { public class CubotDrill extends CpuHardware {
@ -62,15 +63,17 @@ public class CubotDrill extends CpuHardware {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json; BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
} }
public static CubotDrill deserialize(JSONObject hwJSON) { public static CubotDrill deserialize(DBObject obj) {
return new CubotDrill((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot"))); return new CubotDrill((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }
} }

View File

@ -1,9 +1,10 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import org.json.simple.JSONObject;
public class CubotFloppyDrive extends CpuHardware { public class CubotFloppyDrive extends CpuHardware {
@ -78,24 +79,26 @@ public class CubotFloppyDrive extends CpuHardware {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID); BasicDBObject dbObject = new BasicDBObject();
json.put("cubot", cubot.getObjectId());
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
if (floppyDisk != null) { if (floppyDisk != null) {
json.put("floppy", floppyDisk.serialise()); dbObject.put("floppy", floppyDisk.mongoSerialise());
} }
return json; return dbObject;
} }
public static CubotFloppyDrive deserialize(JSONObject hwJSON) { public static CubotFloppyDrive deserialize(DBObject obj) {
CubotFloppyDrive drive = new CubotFloppyDrive((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot"))); CubotFloppyDrive drive = new CubotFloppyDrive((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
if (hwJSON.containsKey("floppy")) { if (obj.containsField("floppy")) {
drive.floppyDisk = FloppyDisk.deserialise((JSONObject) hwJSON.get("floppy")); drive.floppyDisk = FloppyDisk.deserialise((DBObject) obj.get("floppy"));
} }
return drive; return drive;

View File

@ -1,9 +1,10 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import org.json.simple.JSONObject;
public class CubotHologram extends CpuHardware { public class CubotHologram extends CpuHardware {
@ -82,16 +83,19 @@ public class CubotHologram extends CpuHardware {
return HWID; return HWID;
} }
public static CubotHologram deserialize(JSONObject hwJSON) { public static CubotHologram deserialize(DBObject obj) {
return new CubotHologram((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot"))); return new CubotHologram((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json; BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
} }
} }

View File

@ -1,9 +1,10 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import org.json.simple.JSONObject;
public class CubotInventory extends CpuHardware { public class CubotInventory extends CpuHardware {
@ -49,17 +50,19 @@ public class CubotInventory extends CpuHardware {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject(); BasicDBObject dbObject = new BasicDBObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json; dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
} }
public static CubotInventory deserialize(JSONObject hwJSON) { public static CubotInventory deserialize(DBObject obj) {
return new CubotInventory((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot"))); return new CubotInventory((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }
} }

View File

@ -1,9 +1,10 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import org.json.simple.JSONObject;
public class CubotKeyboard extends CpuHardware { public class CubotKeyboard extends CpuHardware {
@ -52,16 +53,17 @@ public class CubotKeyboard extends CpuHardware {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject(); BasicDBObject dbObject = new BasicDBObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json; dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
} }
public static CubotKeyboard deserialize(JSONObject hwJSON) { public static CubotKeyboard deserialize(DBObject obj) {
return new CubotKeyboard((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot"))); return new CubotKeyboard((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }
} }

View File

@ -1,5 +1,7 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
@ -7,7 +9,6 @@ import net.simon987.server.game.Action;
import net.simon987.server.game.Attackable; import net.simon987.server.game.Attackable;
import net.simon987.server.game.GameObject; import net.simon987.server.game.GameObject;
import net.simon987.server.game.InventoryHolder; import net.simon987.server.game.InventoryHolder;
import org.json.simple.JSONObject;
import java.awt.*; import java.awt.*;
import java.util.ArrayList; import java.util.ArrayList;
@ -89,16 +90,17 @@ public class CubotLaser extends CpuHardware {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject(); BasicDBObject dbObject = new BasicDBObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json; dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
} }
public static CubotLaser deserialize(JSONObject hwJSON) { public static CubotLaser deserialize(DBObject obj) {
return new CubotLaser((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot"))); return new CubotLaser((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }
} }

View File

@ -1,5 +1,7 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
@ -80,8 +82,19 @@ public class CubotLeg extends CpuHardware implements JSONSerialisable {
return json; return json;
} }
public static CubotLeg deserialize(JSONObject hwJSON) { @Override
return new CubotLeg((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot"))); public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
}
public static CubotLeg deserialize(DBObject obj) {
return new CubotLeg((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }

View File

@ -1,5 +1,7 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Memory; import net.simon987.server.assembly.Memory;
@ -141,7 +143,18 @@ public class CubotLidar extends CpuHardware implements JSONSerialisable {
return json; return json;
} }
public static CubotLidar deserialize(JSONObject hwJSON) { @Override
return new CubotLidar((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot"))); public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
}
public static CubotLidar deserialize(DBObject obj) {
return new CubotLidar((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }
} }

View File

@ -1,5 +1,6 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.DBObject;
import net.simon987.cubotplugin.event.CpuInitialisationListener; import net.simon987.cubotplugin.event.CpuInitialisationListener;
import net.simon987.cubotplugin.event.UserCreationListener; import net.simon987.cubotplugin.event.UserCreationListener;
import net.simon987.server.ServerConfiguration; import net.simon987.server.ServerConfiguration;
@ -9,7 +10,6 @@ import net.simon987.server.io.CpuHardwareDeserializer;
import net.simon987.server.io.GameObjectDeserializer; import net.simon987.server.io.GameObjectDeserializer;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.ServerPlugin; import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public class CubotPlugin extends ServerPlugin implements GameObjectDeserializer, CpuHardwareDeserializer { public class CubotPlugin extends ServerPlugin implements GameObjectDeserializer, CpuHardwareDeserializer {
@ -23,9 +23,9 @@ public class CubotPlugin extends ServerPlugin implements GameObjectDeserializer,
} }
@Override @Override
public GameObject deserializeObject(JSONObject object) { public GameObject deserializeObject(DBObject object) {
int objType = (int) (long) object.get("t"); int objType = (int) object.get("t");
if (objType == Cubot.ID) { if (objType == Cubot.ID) {
@ -36,30 +36,30 @@ public class CubotPlugin extends ServerPlugin implements GameObjectDeserializer,
} }
@Override @Override
public CpuHardware deserializeHardware(JSONObject hwJson) { public CpuHardware deserializeHardware(DBObject obj) {
int hwid = (int) (long) hwJson.get("hwid"); int hwid = (int) obj.get("hwid");
switch (hwid) { switch (hwid) {
case CubotLeg.HWID: case CubotLeg.HWID:
return CubotLeg.deserialize(hwJson); return CubotLeg.deserialize(obj);
case CubotLaser.HWID: case CubotLaser.HWID:
return CubotLaser.deserialize(hwJson); return CubotLaser.deserialize(obj);
case CubotLidar.HWID: case CubotLidar.HWID:
return CubotLidar.deserialize(hwJson); return CubotLidar.deserialize(obj);
case CubotDrill.HWID: case CubotDrill.HWID:
return CubotDrill.deserialize(hwJson); return CubotDrill.deserialize(obj);
case CubotInventory.HWID: case CubotInventory.HWID:
return CubotInventory.deserialize(hwJson); return CubotInventory.deserialize(obj);
case CubotKeyboard.HWID: case CubotKeyboard.HWID:
return CubotKeyboard.deserialize(hwJson); return CubotKeyboard.deserialize(obj);
case CubotHologram.HWID: case CubotHologram.HWID:
return CubotHologram.deserialize(hwJson); return CubotHologram.deserialize(obj);
case CubotBattery.HWID: case CubotBattery.HWID:
return CubotBattery.deserialize(hwJson); return CubotBattery.deserialize(obj);
case CubotFloppyDrive.HWID: case CubotFloppyDrive.HWID:
return CubotFloppyDrive.deserialize(hwJson); return CubotFloppyDrive.deserialize(obj);
case CubotComPort.HWID: case CubotComPort.HWID:
return CubotComPort.deserialize(hwJson); return CubotComPort.deserialize(obj);
} }
return null; return null;

View File

@ -1,16 +1,17 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.assembly.Memory; import net.simon987.server.assembly.Memory;
import net.simon987.server.io.JSONSerialisable; import net.simon987.server.io.MongoSerialisable;
import org.json.simple.JSONObject;
/** /**
* Represents a floppy disk that is inside a floppy drive. * Represents a floppy disk that is inside a floppy drive.
* Floppies contains 80 tracks with 18 sectors per track. * Floppies contains 80 tracks with 18 sectors per track.
* That's 1440 sectors of 512 words. (total 1,474,560 bytes / 737,280 words / 1.44Mb) * That's 1440 sectors of 512 words. (total 1,474,560 bytes / 737,280 words / 1.44Mb)
*/ */
public class FloppyDisk implements JSONSerialisable { public class FloppyDisk implements MongoSerialisable {
/** /**
* Contents of the disk * Contents of the disk
@ -82,23 +83,22 @@ public class FloppyDisk implements JSONSerialisable {
} }
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
JSONObject json = new JSONObject(); dbObject.put("rwHeadTrack", rwHeadTrack);
json.put("rwHeadTrack", rwHeadTrack); dbObject.put("memory", memory.mongoSerialise());
json.put("memory", memory.serialise());
return json; return dbObject;
} }
public static FloppyDisk deserialise(JSONObject json) { public static FloppyDisk deserialise(DBObject obj) {
FloppyDisk floppyDisk = new FloppyDisk(); FloppyDisk floppyDisk = new FloppyDisk();
floppyDisk.rwHeadTrack = (int) (long) json.get("rwHeadTrack"); floppyDisk.rwHeadTrack = (int) obj.get("rwHeadTrack");
floppyDisk.memory = Memory.deserialize((JSONObject) json.get("memory")); floppyDisk.memory = Memory.deserialize((DBObject) obj.get("memory"));
return floppyDisk; return floppyDisk;
} }

View File

@ -9,6 +9,7 @@ import net.simon987.server.logging.LogManager;
import net.simon987.server.user.User; import net.simon987.server.user.User;
import java.awt.*; import java.awt.*;
import java.util.Random;
public class UserCreationListener implements GameEventListener { public class UserCreationListener implements GameEventListener {
@Override @Override
@ -25,9 +26,11 @@ public class UserCreationListener implements GameEventListener {
Cubot cubot = new Cubot(); Cubot cubot = new Cubot();
cubot.setWorld(GameServer.INSTANCE.getGameUniverse().getWorld( Random random = new Random();
GameServer.INSTANCE.getConfig().getInt("new_user_worldX"), int spawnX = GameServer.INSTANCE.getConfig().getInt("new_user_worldX") + random.nextInt(5);
GameServer.INSTANCE.getConfig().getInt("new_user_worldY"))); int spawnY = GameServer.INSTANCE.getConfig().getInt("new_user_worldY") + random.nextInt(5);
cubot.setWorld(GameServer.INSTANCE.getGameUniverse().getWorld(spawnX, spawnY, true));
cubot.getWorld().getGameObjects().add(cubot); cubot.getWorld().getGameObjects().add(cubot);
cubot.getWorld().incUpdatable(); cubot.getWorld().incUpdatable();

View File

@ -1,10 +1,10 @@
package net.simon987.mischwplugin; package net.simon987.mischwplugin;
import com.mongodb.BasicDBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import net.simon987.server.assembly.Util; import net.simon987.server.assembly.Util;
import org.json.simple.JSONObject;
public class Clock extends CpuHardware { public class Clock extends CpuHardware {
@ -28,15 +28,18 @@ public class Clock extends CpuHardware {
return HWID; return HWID;
} }
public static Clock deserialize(JSONObject hwJSON) { public static Clock deserialize() {
return new Clock(); return new Clock();
} }
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
return json; @Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
return dbObject;
} }
} }

View File

@ -1,12 +1,12 @@
package net.simon987.mischwplugin; package net.simon987.mischwplugin;
import com.mongodb.DBObject;
import net.simon987.mischwplugin.event.CpuInitialisationListener; import net.simon987.mischwplugin.event.CpuInitialisationListener;
import net.simon987.server.ServerConfiguration; import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.io.CpuHardwareDeserializer; import net.simon987.server.io.CpuHardwareDeserializer;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.ServerPlugin; import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public class MiscHWPlugin extends ServerPlugin implements CpuHardwareDeserializer { public class MiscHWPlugin extends ServerPlugin implements CpuHardwareDeserializer {
@ -19,14 +19,14 @@ public class MiscHWPlugin extends ServerPlugin implements CpuHardwareDeserialize
} }
@Override @Override
public CpuHardware deserializeHardware(JSONObject hwJson) { public CpuHardware deserializeHardware(DBObject hwJson) {
int hwid = (int) (long) hwJson.get("hwid"); int hwid = (int) hwJson.get("hwid");
switch (hwid) { switch (hwid) {
case RandomNumberGenerator.HWID: case RandomNumberGenerator.HWID:
return RandomNumberGenerator.deserialize(hwJson); return RandomNumberGenerator.deserialize();
case Clock.HWID: case Clock.HWID:
return Clock.deserialize(hwJson); return Clock.deserialize();
} }
return null; return null;

View File

@ -1,8 +1,8 @@
package net.simon987.mischwplugin; package net.simon987.mischwplugin;
import com.mongodb.BasicDBObject;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import org.json.simple.JSONObject;
import java.util.Random; import java.util.Random;
@ -31,14 +31,16 @@ public class RandomNumberGenerator extends CpuHardware {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
return json; BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
return dbObject;
} }
public static RandomNumberGenerator deserialize(JSONObject hwJSON) { public static RandomNumberGenerator deserialize() {
return new RandomNumberGenerator(); return new RandomNumberGenerator();
} }
} }

View File

@ -1,5 +1,8 @@
package net.simon987.npcplugin; package net.simon987.npcplugin;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.game.GameObject; import net.simon987.server.game.GameObject;
import net.simon987.server.game.Updatable; import net.simon987.server.game.Updatable;
@ -117,14 +120,34 @@ public class Factory extends GameObject implements Updatable {
return json; return json;
} }
public static Factory deserialise(JSONObject json) { @Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("i", getObjectId());
dbObject.put("x", getX());
dbObject.put("y", getY());
dbObject.put("t", ID);
BasicDBList tmpNpcArray = new BasicDBList();
for (NonPlayerCharacter npc : npcs) {
tmpNpcArray.add(npc.getObjectId());
}
dbObject.put("n", tmpNpcArray);
return dbObject;
}
public static Factory deserialise(DBObject obj) {
Factory factory = new Factory(); Factory factory = new Factory();
factory.setObjectId((long) json.get("i")); factory.setObjectId((long) obj.get("i"));
factory.setX((int) (long) json.get("x")); factory.setX((int) obj.get("x"));
factory.setY((int) (long) json.get("y")); factory.setY((int) obj.get("y"));
factory.tmpNpcArray = ((JSONArray) json.get("n")).toArray(); factory.tmpNpcArray = ((BasicDBList) obj.get("n")).toArray();
return factory; return factory;
} }

View File

@ -1,5 +1,7 @@
package net.simon987.npcplugin; package net.simon987.npcplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.game.Direction; import net.simon987.server.game.Direction;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
@ -58,16 +60,32 @@ public class HarvesterNPC extends NonPlayerCharacter {
return json; return json;
} }
public static HarvesterNPC deserialize(JSONObject json) { @Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("i", getObjectId());
dbObject.put("x", getX());
dbObject.put("y", getY());
dbObject.put("direction", getDirection().ordinal());
dbObject.put("hp", getHp());
// dbObject.put("energy", energy);
dbObject.put("action", getAction().ordinal());
dbObject.put("t", ID);
return dbObject;
}
public static HarvesterNPC deserialize(DBObject obj) {
HarvesterNPC npc = new HarvesterNPC(); HarvesterNPC npc = new HarvesterNPC();
npc.setObjectId((long) json.get("i")); npc.setObjectId((long) obj.get("i"));
npc.setX((int) (long) json.get("x")); npc.setX((int) obj.get("x"));
npc.setY((int) (long) json.get("y")); npc.setY((int) obj.get("y"));
npc.setHp((int) (long) json.get("hp")); npc.setHp((int) obj.get("hp"));
npc.setDirection(Direction.getDirection((int) (long) json.get("direction"))); npc.setDirection(Direction.getDirection((int) obj.get("direction")));
npc.energy = (int) (long) json.get("energy"); // npc.energy = (int) obj.get("energy");
npc.maxEnergy = GameServer.INSTANCE.getConfig().getInt("battery_max_energy"); // npc.maxEnergy = GameServer.INSTANCE.getConfig().getInt("battery_max_energy");
return npc; return npc;

View File

@ -1,5 +1,6 @@
package net.simon987.npcplugin; package net.simon987.npcplugin;
import com.mongodb.DBObject;
import net.simon987.npcplugin.event.CpuInitialisationListener; import net.simon987.npcplugin.event.CpuInitialisationListener;
import net.simon987.npcplugin.event.WorldCreationListener; import net.simon987.npcplugin.event.WorldCreationListener;
import net.simon987.server.ServerConfiguration; import net.simon987.server.ServerConfiguration;
@ -9,7 +10,6 @@ import net.simon987.server.io.CpuHardwareDeserializer;
import net.simon987.server.io.GameObjectDeserializer; import net.simon987.server.io.GameObjectDeserializer;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.ServerPlugin; import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
@ -32,28 +32,28 @@ public class NpcPlugin extends ServerPlugin implements GameObjectDeserializer, C
} }
@Override @Override
public GameObject deserializeObject(JSONObject json) { public GameObject deserializeObject(DBObject obj) {
int objType = (int) (long) json.get("t"); int objType = (int) obj.get("t");
if (objType == HarvesterNPC.ID) { if (objType == HarvesterNPC.ID) {
return HarvesterNPC.deserialize(json); return HarvesterNPC.deserialize(obj);
} else if (objType == Factory.ID) { } else if (objType == Factory.ID) {
return Factory.deserialise(json); return Factory.deserialise(obj);
} else if (objType == RadioTower.ID) { } else if (objType == RadioTower.ID) {
return RadioTower.deserialize(json); return RadioTower.deserialize(obj);
} }
return null; return null;
} }
@Override @Override
public CpuHardware deserializeHardware(JSONObject hwJson) { public CpuHardware deserializeHardware(DBObject obj) {
int hwid = (int) (long) hwJson.get("hwid"); int hwid = (int) obj.get("hwid");
switch (hwid) { switch (hwid) {
case RadioReceiverHardware.HWID: case RadioReceiverHardware.HWID:
return RadioReceiverHardware.deserialize(hwJson); return RadioReceiverHardware.deserialize(obj);
} }
return null; return null;

View File

@ -1,12 +1,13 @@
package net.simon987.npcplugin; package net.simon987.npcplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import net.simon987.server.assembly.Util; import net.simon987.server.assembly.Util;
import net.simon987.server.game.Action; import net.simon987.server.game.Action;
import net.simon987.server.game.ControllableUnit; import net.simon987.server.game.ControllableUnit;
import org.json.simple.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
@ -64,16 +65,19 @@ public class RadioReceiverHardware extends CpuHardware {
return HWID; return HWID;
} }
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json; @Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
} }
public static RadioReceiverHardware deserialize(JSONObject json) { public static RadioReceiverHardware deserialize(DBObject obj) {
return new RadioReceiverHardware((ControllableUnit) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) json.get("cubot"))); return new RadioReceiverHardware((ControllableUnit) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }
} }

View File

@ -1,5 +1,7 @@
package net.simon987.npcplugin; package net.simon987.npcplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.game.GameObject; import net.simon987.server.game.GameObject;
import net.simon987.server.game.Programmable; import net.simon987.server.game.Programmable;
import net.simon987.server.game.Updatable; import net.simon987.server.game.Updatable;
@ -65,12 +67,24 @@ public class RadioTower extends GameObject implements Programmable, Updatable {
} }
public static RadioTower deserialize(JSONObject json) { @Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("i", getObjectId());
dbObject.put("x", getX());
dbObject.put("y", getY());
dbObject.put("t", ID);
return dbObject;
}
public static RadioTower deserialize(DBObject obj) {
RadioTower tower = new RadioTower(); RadioTower tower = new RadioTower();
tower.setObjectId((long) json.get("i")); tower.setObjectId((long) obj.get("i"));
tower.setX((int) (long) json.get("x")); tower.setX((int) obj.get("x"));
tower.setY((int) (long) json.get("y")); tower.setY((int) obj.get("y"));
NpcPlugin.getRadioTowers().add(tower); NpcPlugin.getRadioTowers().add(tower);

View File

@ -1,5 +1,7 @@
package net.simon987.biomassplugin; package net.simon987.biomassplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.game.GameObject; import net.simon987.server.game.GameObject;
import net.simon987.server.game.InventoryHolder; import net.simon987.server.game.InventoryHolder;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
@ -40,6 +42,20 @@ public class BiomassBlob extends GameObject implements InventoryHolder {
return json; return json;
} }
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("t", ID);
dbObject.put("i", getObjectId());
dbObject.put("x", getX());
dbObject.put("y", getY());
dbObject.put("b", biomassCount);
return dbObject;
}
public int getBiomassCount() { public int getBiomassCount() {
return biomassCount; return biomassCount;
@ -57,15 +73,15 @@ public class BiomassBlob extends GameObject implements InventoryHolder {
// this.style = style; // this.style = style;
// } // }
public static BiomassBlob deserialize(JSONObject json) { public static BiomassBlob deserialize(DBObject obj) {
BiomassBlob biomassBlob = new BiomassBlob(); BiomassBlob biomassBlob = new BiomassBlob();
biomassBlob.setObjectId((long) json.get("i")); biomassBlob.setObjectId((long) obj.get("i"));
biomassBlob.setX((int) (long) json.get("x")); biomassBlob.setX((int) obj.get("x"));
biomassBlob.setY((int) (long) json.get("y")); biomassBlob.setY((int) obj.get("y"));
// biomassBlob.style = (int) (long) json.get("style"); // biomassBlob.style = (int) json.get("style");
biomassBlob.biomassCount = (int) (long) json.get("b"); biomassBlob.biomassCount = (int) obj.get("b");
return biomassBlob; return biomassBlob;
} }

View File

@ -1,5 +1,6 @@
package net.simon987.biomassplugin; package net.simon987.biomassplugin;
import com.mongodb.DBObject;
import net.simon987.biomassplugin.event.WorldCreationListener; import net.simon987.biomassplugin.event.WorldCreationListener;
import net.simon987.biomassplugin.event.WorldUpdateListener; import net.simon987.biomassplugin.event.WorldUpdateListener;
import net.simon987.server.ServerConfiguration; import net.simon987.server.ServerConfiguration;
@ -7,7 +8,6 @@ import net.simon987.server.game.GameObject;
import net.simon987.server.io.GameObjectDeserializer; import net.simon987.server.io.GameObjectDeserializer;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.ServerPlugin; import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public class BiomassPlugin extends ServerPlugin implements GameObjectDeserializer { public class BiomassPlugin extends ServerPlugin implements GameObjectDeserializer {
@ -21,9 +21,9 @@ public class BiomassPlugin extends ServerPlugin implements GameObjectDeserialize
} }
@Override @Override
public GameObject deserializeObject(JSONObject object) { public GameObject deserializeObject(DBObject object) {
int objType = (int) (long) object.get("t"); int objType = (int) object.get("t");
if (objType == BiomassBlob.ID) { if (objType == BiomassBlob.ID) {

View File

@ -109,6 +109,11 @@
<artifactId>commons-text</artifactId> <artifactId>commons-text</artifactId>
<version>1.2</version> <version>1.2</version>
</dependency> </dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies> </dependencies>

View File

@ -1,6 +1,8 @@
package net.simon987.server; package net.simon987.server;
import com.mongodb.*;
import net.simon987.server.assembly.exception.CancelledException;
import net.simon987.server.event.GameEvent; import net.simon987.server.event.GameEvent;
import net.simon987.server.event.GameEventDispatcher; import net.simon987.server.event.GameEventDispatcher;
import net.simon987.server.event.TickEvent; import net.simon987.server.event.TickEvent;
@ -10,23 +12,19 @@ import net.simon987.server.game.World;
import net.simon987.server.io.FileUtils; import net.simon987.server.io.FileUtils;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.PluginManager; import net.simon987.server.plugin.PluginManager;
import net.simon987.server.plugin.ServerPlugin;
import net.simon987.server.user.User; import net.simon987.server.user.User;
import net.simon987.server.webserver.SocketServer; import net.simon987.server.webserver.SocketServer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.net.UnknownHostException;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
public class GameServer implements Runnable { public class GameServer implements Runnable {
public final static GameServer INSTANCE = new GameServer(); public final static GameServer INSTANCE = new GameServer();
private final static String SAVE_JSON = "save.json";
private GameUniverse gameUniverse; private GameUniverse gameUniverse;
private GameEventDispatcher eventDispatcher; private GameEventDispatcher eventDispatcher;
private PluginManager pluginManager; private PluginManager pluginManager;
@ -157,13 +155,13 @@ public class GameServer implements Runnable {
//Save //Save
if (gameUniverse.getTime() % config.getInt("save_interval") == 0) { if (gameUniverse.getTime() % config.getInt("save_interval") == 0) {
save(new File("save.json")); save();
} }
// Clean up history files // Clean up history files
if(gameUniverse.getTime() % config.getInt("clean_interval") == 0) { if (gameUniverse.getTime() % config.getInt("clean_interval") == 0) {
FileUtils.cleanHistory(config.getInt("history_size")); FileUtils.cleanHistory(config.getInt("history_size"));
} }
socketServer.tick(); socketServer.tick();
@ -171,47 +169,106 @@ public class GameServer implements Runnable {
") updated"); ") updated");
} }
/** void load() {
* Save game universe to file in JSON format
*
* @param file JSON file to save
*/
public void save(File file) {
boolean dirExists = FileUtils.prepDirectory(FileUtils.DIR_PATH);
if (new File(new File(SAVE_JSON).getAbsolutePath()).exists() && dirExists) {
byte[] data = FileUtils.bytifyFile(new File(SAVE_JSON).toPath());
try {
FileUtils.writeSaveToZip(SAVE_JSON, data);
} catch (IOException e) {
System.out.println("Failed to write " + SAVE_JSON + " to zip file");
e.printStackTrace();
}
}
LogManager.LOGGER.info("Loading from MongoDB");
MongoClient mongo;
try { try {
FileWriter fileWriter = new FileWriter(file); mongo = new MongoClient("localhost", 27017);
JSONObject universe = gameUniverse.serialise(); DB db = mongo.getDB("mar");
JSONArray plugins = new JSONArray(); DBCollection worlds = db.getCollection("world");
DBCollection users = db.getCollection("user");
DBCollection server = db.getCollection("server");
for (ServerPlugin plugin : pluginManager.getPlugins()) { //Load worlds
plugins.add(plugin.serialise()); DBCursor cursor = worlds.find();
while (cursor.hasNext()) {
GameServer.INSTANCE.getGameUniverse().getWorlds().add(World.deserialize(cursor.next()));
} }
universe.put("plugins", plugins); //Load users
cursor = users.find();
while (cursor.hasNext()) {
try {
GameServer.INSTANCE.getGameUniverse().getUsers().add(User.deserialize(cursor.next()));
} catch (CancelledException e) {
e.printStackTrace();
}
}
fileWriter.write(universe.toJSONString()); //Load misc server info
fileWriter.close(); cursor = server.find();
if (cursor.hasNext()) {
DBObject serverObj = cursor.next();
gameUniverse.setTime((long) serverObj.get("time"));
gameUniverse.setNextObjectId((long) serverObj.get("nextObjectId"));
}
LogManager.LOGGER.info("Saved to file " + file.getName()); LogManager.LOGGER.info("Done loading! W:" + GameServer.INSTANCE.getGameUniverse().getWorlds().size() +
" | U:" + GameServer.INSTANCE.getGameUniverse().getUsers().size());
} catch (IOException e) { } catch (UnknownHostException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
private void save() {
LogManager.LOGGER.info("Saving to MongoDB | W:" + gameUniverse.getWorlds().size() + " | U:" + gameUniverse.getUsers().size());
MongoClient mongo;
try {
mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("mar");
db.dropDatabase(); //Todo: Update database / keep history instead of overwriting
DBCollection worlds = db.getCollection("world");
DBCollection users = db.getCollection("user");
DBCollection server = db.getCollection("server");
List<DBObject> worldDocuments = new ArrayList<>();
int perBatch = 35;
int insertedWorlds = 0;
ArrayList<World> worlds_ = new ArrayList<>(GameServer.INSTANCE.getGameUniverse().getWorlds());
for (World w : worlds_) {
worldDocuments.add(w.mongoSerialise());
insertedWorlds++;
if (worldDocuments.size() >= perBatch || insertedWorlds >= GameServer.INSTANCE.getGameUniverse().getWorlds().size()) {
worlds.insert(worldDocuments);
worldDocuments.clear();
}
}
List<DBObject> userDocuments = new ArrayList<>();
int insertedUsers = 0;
ArrayList<User> users_ = new ArrayList<>(GameServer.INSTANCE.getGameUniverse().getUsers());
for (User u : users_) {
insertedUsers++;
if (!u.isGuest()) {
userDocuments.add(u.mongoSerialise());
}
if (userDocuments.size() >= perBatch || insertedUsers >= GameServer.INSTANCE.getGameUniverse().getUsers().size()) {
users.insert(userDocuments);
userDocuments.clear();
}
}
BasicDBObject serverObj = new BasicDBObject();
serverObj.put("time", gameUniverse.getTime());
serverObj.put("nextObjectId", gameUniverse.getNextObjectId());
server.insert(serverObj);
LogManager.LOGGER.info("Done!");
} catch (UnknownHostException e) {
e.printStackTrace();
}
} }
public ServerConfiguration getConfig() { public ServerConfiguration getConfig() {

View File

@ -3,7 +3,6 @@ package net.simon987.server;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import net.simon987.server.webserver.SocketServer; import net.simon987.server.webserver.SocketServer;
import java.io.File;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
@ -14,16 +13,13 @@ public class Main {
LogManager.initialize(); LogManager.initialize();
ServerConfiguration config = new ServerConfiguration("config.properties"); ServerConfiguration config = new ServerConfiguration("config.properties");
//Load //Load
GameServer.INSTANCE.getGameUniverse().load(new File("save.json")); GameServer.INSTANCE.load();
SocketServer socketServer = new SocketServer(new InetSocketAddress(config.getString("webSocket_host"), SocketServer socketServer = new SocketServer(new InetSocketAddress(config.getString("webSocket_host"),
config.getInt("webSocket_port")), config); config.getInt("webSocket_port")), config);
GameServer.INSTANCE.setSocketServer(socketServer); GameServer.INSTANCE.setSocketServer(socketServer);
System.out.println(GameServer.INSTANCE.getGameUniverse().getWorld(0x7fff, 0x7fff));
(new Thread(socketServer)).start(); (new Thread(socketServer)).start();
(new Thread(GameServer.INSTANCE)).start(); (new Thread(GameServer.INSTANCE)).start();
} }

View File

@ -1,18 +1,18 @@
package net.simon987.server.assembly; package net.simon987.server.assembly;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.ServerConfiguration; import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.exception.CancelledException; import net.simon987.server.assembly.exception.CancelledException;
import net.simon987.server.assembly.instruction.*; import net.simon987.server.assembly.instruction.*;
import net.simon987.server.event.CpuInitialisationEvent; import net.simon987.server.event.CpuInitialisationEvent;
import net.simon987.server.event.GameEvent; import net.simon987.server.event.GameEvent;
import net.simon987.server.io.JSONSerialisable; import net.simon987.server.io.MongoSerialisable;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import net.simon987.server.user.User; import net.simon987.server.user.User;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
/** /**
@ -20,7 +20,7 @@ import java.util.HashMap;
* a Memory object and execute them. A CPU object holds registers objects & * a Memory object and execute them. A CPU object holds registers objects &
* a Memory object. * a Memory object.
*/ */
public class CPU implements JSONSerialisable { public class CPU implements MongoSerialisable {
/** /**
* *
@ -346,47 +346,47 @@ public class CPU implements JSONSerialisable {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
JSONObject json = new JSONObject(); dbObject.put("memory", memory.mongoSerialise());
json.put("memory", memory.serialise()); dbObject.put("registerSet", registerSet.mongoSerialise());
dbObject.put("codeSegmentOffset", codeSegmentOffset);
json.put("registerSet", registerSet.serialise()); BasicDBList hardwareList = new BasicDBList();
json.put("codeSegmentOffset", codeSegmentOffset);
JSONArray hardwareList = new JSONArray();
for (Integer address : attachedHardware.keySet()) { for (Integer address : attachedHardware.keySet()) {
CpuHardware hardware = attachedHardware.get(address); CpuHardware hardware = attachedHardware.get(address);
JSONObject serialisedHw = hardware.serialise(); BasicDBObject serialisedHw = hardware.mongoSerialise();
serialisedHw.put("address", address); serialisedHw.put("address", address);
hardwareList.add(serialisedHw); hardwareList.add(serialisedHw);
} }
json.put("hardware", hardwareList); dbObject.put("hardware", hardwareList);
return dbObject;
return json;
} }
public static CPU deserialize(JSONObject json, User user) throws CancelledException { public static CPU deserialize(DBObject obj, User user) throws CancelledException {
CPU cpu = new CPU(GameServer.INSTANCE.getConfig(), user); CPU cpu = new CPU(GameServer.INSTANCE.getConfig(), user);
cpu.codeSegmentOffset = (int) (long) json.get("codeSegmentOffset"); cpu.codeSegmentOffset = (int) obj.get("codeSegmentOffset");
JSONArray hardwareList = (JSONArray) json.get("hardware"); BasicDBList hardwareList = (BasicDBList) obj.get("hardware");
for (JSONObject serialisedHw : (ArrayList<JSONObject>) hardwareList) { for (Object serialisedHw : hardwareList) {
CpuHardware hw = CpuHardware.deserialize(serialisedHw); CpuHardware hardware = CpuHardware.deserialize((DBObject) serialisedHw);
hw.setCpu(cpu); hardware.setCpu(cpu);
cpu.attachHardware(hw, (int) (long) serialisedHw.get("address")); cpu.attachHardware(hardware, (int) ((BasicDBObject) serialisedHw).get("address"));
} }
cpu.memory = Memory.deserialize((JSONObject) json.get("memory")); cpu.memory = Memory.deserialize((DBObject) obj.get("memory"));
cpu.registerSet = RegisterSet.deserialize((JSONObject) json.get("registerSet")); cpu.registerSet = RegisterSet.deserialize((DBObject) obj.get("registerSet"));
return cpu; return cpu;

View File

@ -1,13 +1,13 @@
package net.simon987.server.assembly; package net.simon987.server.assembly;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.io.CpuHardwareDeserializer; import net.simon987.server.io.CpuHardwareDeserializer;
import net.simon987.server.io.JSONSerialisable; import net.simon987.server.io.MongoSerialisable;
import net.simon987.server.plugin.ServerPlugin; import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public abstract class CpuHardware implements JSONSerialisable { public abstract class CpuHardware implements MongoSerialisable {
CPU cpu; CPU cpu;
@ -26,12 +26,12 @@ public abstract class CpuHardware implements JSONSerialisable {
public abstract char getId(); public abstract char getId();
public static CpuHardware deserialize(JSONObject hwJson) { public static CpuHardware deserialize(DBObject obj) {
for (ServerPlugin plugin : GameServer.INSTANCE.getPluginManager().getPlugins()) { for (ServerPlugin plugin : GameServer.INSTANCE.getPluginManager().getPlugins()) {
if (plugin instanceof CpuHardwareDeserializer) { if (plugin instanceof CpuHardwareDeserializer) {
CpuHardware hw = ((CpuHardwareDeserializer) plugin).deserializeHardware(hwJson); CpuHardware hw = ((CpuHardwareDeserializer) plugin).deserializeHardware(obj);
if (hw != null) { if (hw != null) {
return hw; return hw;

View File

@ -1,8 +1,10 @@
package net.simon987.server.assembly; package net.simon987.server.assembly;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.io.JSONSerialisable; import net.simon987.server.io.MongoSerialisable;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
@ -20,7 +22,7 @@ import java.util.zip.InflaterOutputStream;
/** /**
* Represents the available memory for a CPU in the game universe * Represents the available memory for a CPU in the game universe
*/ */
public class Memory implements Target, JSONSerialisable { public class Memory implements Target, MongoSerialisable {
/** /**
@ -105,25 +107,54 @@ public class Memory implements Target, JSONSerialisable {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject(); BasicDBObject dbObject = new BasicDBObject();
try { try {
ByteArrayOutputStream stream = new ByteArrayOutputStream(); ByteArrayOutputStream stream = new ByteArrayOutputStream();
Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION, true); Deflater compressor = new Deflater(Deflater.BEST_SPEED, true);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compressor); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compressor);
deflaterOutputStream.write(getBytes()); deflaterOutputStream.write(getBytes());
deflaterOutputStream.close(); deflaterOutputStream.close();
byte[] compressedBytes = stream.toByteArray(); byte[] compressedBytes = stream.toByteArray();
json.put("zipBytes", new String(Base64.getEncoder().encode(compressedBytes))); dbObject.put("zipBytes", new String(Base64.getEncoder().encode(compressedBytes)));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return json; return dbObject;
}
public static Memory deserialize(DBObject obj) {
Memory memory = new Memory(0);
String zipBytesStr = (String) obj.get("zipBytes");
if (zipBytesStr != null) {
byte[] compressedBytes = Base64.getDecoder().decode((String) obj.get("zipBytes"));
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Inflater decompressor = new Inflater(true);
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(baos, decompressor);
inflaterOutputStream.write(compressedBytes);
inflaterOutputStream.close();
memory.setBytes(baos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
} else {
LogManager.LOGGER.severe("Memory was manually deleted");
memory = new Memory(GameServer.INSTANCE.getConfig().getInt("memory_size"));
}
return memory;
} }
public static Memory deserialize(JSONObject json) { public static Memory deserialize(JSONObject json) {

View File

@ -1,7 +1,10 @@
package net.simon987.server.assembly; package net.simon987.server.assembly;
import net.simon987.server.io.JSONSerialisable; import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.io.MongoSerialisable;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import org.json.simple.JSONArray; import org.json.simple.JSONArray;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
@ -12,7 +15,7 @@ import java.util.HashMap;
/** /**
* A set of registers for a CPU * A set of registers for a CPU
*/ */
public class RegisterSet implements Target, JSONSerialisable { public class RegisterSet implements Target, MongoSerialisable {
/** /**
* List of registers * List of registers
@ -142,8 +145,8 @@ public class RegisterSet implements Target, JSONSerialisable {
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONArray registers = new JSONArray(); BasicDBList registers = new BasicDBList();
for (Integer index : this.registers.keySet()) { for (Integer index : this.registers.keySet()) {
JSONObject register = new JSONObject(); JSONObject register = new JSONObject();
@ -154,10 +157,28 @@ public class RegisterSet implements Target, JSONSerialisable {
registers.add(register); registers.add(register);
} }
JSONObject json = new JSONObject(); BasicDBObject obj = new BasicDBObject();
json.put("registers", registers); obj.put("registers", registers);
return json; return obj;
}
public static RegisterSet deserialize(DBObject obj) {
RegisterSet registerSet = new RegisterSet();
BasicDBList registers = (BasicDBList) obj.get("registers");
for (Object sRegister : registers) {
Register register = new Register((String) ((DBObject) sRegister).get("name"));
register.setValue((int) ((DBObject) sRegister).get("value"));
registerSet.registers.put((int) ((DBObject) sRegister).get("index"), register);
}
return registerSet;
} }
public static RegisterSet deserialize(JSONObject json) { public static RegisterSet deserialize(JSONObject json) {

View File

@ -1,8 +1,10 @@
package net.simon987.server.game; package net.simon987.server.game;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.io.GameObjectDeserializer; import net.simon987.server.io.GameObjectDeserializer;
import net.simon987.server.io.JSONSerialisable; import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.io.MongoSerialisable;
import net.simon987.server.plugin.ServerPlugin; import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
@ -12,7 +14,7 @@ import java.awt.*;
* An INSTANCE of an object (e.g. a Tree, a character ...) inside the * An INSTANCE of an object (e.g. a Tree, a character ...) inside the
* game universe * game universe
*/ */
public abstract class GameObject implements JSONSerialisable { public abstract class GameObject implements JSONSerialisable, MongoSerialisable {
private boolean dead; private boolean dead;
/** /**
@ -76,9 +78,9 @@ public abstract class GameObject implements JSONSerialisable {
if (world.getX() == 0) { if (world.getX() == 0) {
//Warp around //Warp around
leftWorld = GameServer.INSTANCE.getGameUniverse().getWorld( leftWorld = GameServer.INSTANCE.getGameUniverse().getWorld(
GameServer.INSTANCE.getGameUniverse().getMaxWidth(), world.getY()); GameServer.INSTANCE.getGameUniverse().getMaxWidth(), world.getY(), true);
} else { } else {
leftWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX() - 1, world.getY()); leftWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX() - 1, world.getY(), true);
} }
if (leftWorld != null) { if (leftWorld != null) {
@ -95,9 +97,9 @@ public abstract class GameObject implements JSONSerialisable {
World rightWorld; World rightWorld;
if (world.getX() == GameServer.INSTANCE.getGameUniverse().getMaxWidth()) { if (world.getX() == GameServer.INSTANCE.getGameUniverse().getMaxWidth()) {
//Warp around //Warp around
rightWorld = GameServer.INSTANCE.getGameUniverse().getWorld(0, world.getY()); rightWorld = GameServer.INSTANCE.getGameUniverse().getWorld(0, world.getY(), true);
} else { } else {
rightWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX() + 1, world.getY()); rightWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX() + 1, world.getY(), true);
} }
if (rightWorld != null) { if (rightWorld != null) {
@ -115,9 +117,9 @@ public abstract class GameObject implements JSONSerialisable {
if (world.getY() == 0) { if (world.getY() == 0) {
//Warp around //Warp around
upWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(), upWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(),
GameServer.INSTANCE.getGameUniverse().getMaxWidth()); GameServer.INSTANCE.getGameUniverse().getMaxWidth(), true);
} else { } else {
upWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(), world.getY() - 1); upWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(), world.getY() - 1, true);
} }
if (upWorld != null) { if (upWorld != null) {
@ -134,9 +136,9 @@ public abstract class GameObject implements JSONSerialisable {
World downWorld; World downWorld;
if (world.getY() == GameServer.INSTANCE.getGameUniverse().getMaxWidth()) { if (world.getY() == GameServer.INSTANCE.getGameUniverse().getMaxWidth()) {
//Warp around //Warp around
downWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(), 0); downWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(), 0, true);
} else { } else {
downWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(), world.getY() + 1); downWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(), world.getY() + 1, true);
} }
@ -224,12 +226,12 @@ public abstract class GameObject implements JSONSerialisable {
return new JSONObject(); return new JSONObject();
} }
public static GameObject deserialize(JSONObject objJson) { public static GameObject deserialize(DBObject obj) {
//
for (ServerPlugin plugin : GameServer.INSTANCE.getPluginManager().getPlugins()) { for (ServerPlugin plugin : GameServer.INSTANCE.getPluginManager().getPlugins()) {
if (plugin instanceof GameObjectDeserializer) { if (plugin instanceof GameObjectDeserializer) {
GameObject object = ((GameObjectDeserializer) plugin).deserializeObject(objJson); GameObject object = ((GameObjectDeserializer) plugin).deserializeObject(obj);
if (object != null) { if (object != null) {
return object; return object;

View File

@ -6,20 +6,12 @@ import net.simon987.server.assembly.Assembler;
import net.simon987.server.assembly.AssemblyResult; import net.simon987.server.assembly.AssemblyResult;
import net.simon987.server.assembly.CPU; import net.simon987.server.assembly.CPU;
import net.simon987.server.assembly.exception.CancelledException; import net.simon987.server.assembly.exception.CancelledException;
import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import net.simon987.server.user.User; import net.simon987.server.user.User;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
public class GameUniverse implements JSONSerialisable { public class GameUniverse {
private ArrayList<World> worlds; private ArrayList<World> worlds;
private ArrayList<User> users; private ArrayList<User> users;
@ -27,7 +19,7 @@ public class GameUniverse implements JSONSerialisable {
private long time; private long time;
private int nextObjectId = 0; private long nextObjectId = 0;
private int maxWidth = 0xFFFF; private int maxWidth = 0xFFFF;
@ -44,7 +36,7 @@ public class GameUniverse implements JSONSerialisable {
return time; return time;
} }
public World getWorld(int x, int y) { public World getWorld(int x, int y, boolean createNew) {
for (World world : worlds) { for (World world : worlds) {
if (world.getX() == x && world.getY() == y) { if (world.getX() == x && world.getY() == y) {
@ -53,14 +45,16 @@ public class GameUniverse implements JSONSerialisable {
} }
if (x >= 0 && x <= maxWidth && y >= 0 && y <= maxWidth) { if (x >= 0 && x <= maxWidth && y >= 0 && y <= maxWidth) {
//World does not exist if (createNew) {
LogManager.LOGGER.severe("Trying to read a World that does not exist!"); //World does not exist
World world = createWorld(x, y);
worlds.add(world);
World world = createWorld(x, y); return world;
} else {
return null;
}
worlds.add(world);
return world;
} else { } else {
return null; return null;
} }
@ -145,7 +139,7 @@ public class GameUniverse implements JSONSerialisable {
* @param id id of the game object * @param id id of the game object
* @return GameObject, null if not found * @return GameObject, null if not found
*/ */
public GameObject getObject(int id) { public GameObject getObject(long id) {
// //
for (World world : worlds) { for (World world : worlds) {
@ -156,6 +150,7 @@ public class GameUniverse implements JSONSerialisable {
} }
} }
LogManager.LOGGER.severe("Couldn't find object: " + id);
return null; return null;
} }
@ -172,75 +167,6 @@ public class GameUniverse implements JSONSerialisable {
return users; return users;
} }
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
JSONArray worlds = new JSONArray();
ArrayList<World> worlds_ = new ArrayList<>(this.worlds);
for (World world : worlds_) {
worlds.add(world.serialise());
}
JSONArray users = new JSONArray();
ArrayList<User> users_ = new ArrayList<User>(this.users);
for (User user : users_) {
if (!user.isGuest()) {
users.add(user.serialise());
}
}
json.put("users", users);
json.put("worlds", worlds);
json.put("time", time);
json.put("nextObjectId", nextObjectId);
return json;
}
/**
* Load game universe from JSON save file
*
* @param file JSON save file
*/
public void load(File file) {
JSONParser parser = new JSONParser();
if (file.isFile()) {
try {
FileReader reader = new FileReader(file);
JSONObject universeJson = (JSONObject) parser.parse(reader);
time = (long) universeJson.get("time");
nextObjectId = (int) (long) universeJson.get("nextObjectId");
for (JSONObject worldJson : (ArrayList<JSONObject>) universeJson.get("worlds")) {
worlds.add(World.deserialize(worldJson));
}
for (JSONObject userJson : (ArrayList<JSONObject>) universeJson.get("users")) {
users.add(User.deserialize(userJson));
}
LogManager.LOGGER.info("Loaded " + worlds.size() + " worlds from file");
reader.close();
} catch (IOException | ParseException | CancelledException e) {
e.printStackTrace();
}
} else {
LogManager.LOGGER.severe("Couldn't load save file save.json, creating empty game universe.");
}
}
public long getNextObjectId() { public long getNextObjectId() {
return ++nextObjectId; return ++nextObjectId;
} }
@ -263,10 +189,17 @@ public class GameUniverse implements JSONSerialisable {
public void removeUser(User user) { public void removeUser(User user) {
users.remove(user); users.remove(user);
} }
public int getMaxWidth() { public int getMaxWidth() {
return maxWidth; return maxWidth;
} }
public void setTime(long time) {
this.time = time;
}
public void setNextObjectId(long nextObjectId) {
this.nextObjectId = nextObjectId;
}
} }

View File

@ -1,7 +1,11 @@
package net.simon987.server.game; package net.simon987.server.game;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.io.JSONSerialisable; import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.io.MongoSerialisable;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import java.awt.*; import java.awt.*;
@ -17,7 +21,7 @@ import java.util.zip.InflaterOutputStream;
/** /**
* A 2D map of Tile objects of size width*height * A 2D map of Tile objects of size width*height
*/ */
public class TileMap implements JSONSerialisable { public class TileMap implements JSONSerialisable, MongoSerialisable {
public static final int PLAIN_TILE = 0; public static final int PLAIN_TILE = 0;
public static final int WALL_TILE = 1; public static final int WALL_TILE = 1;
@ -52,6 +56,13 @@ public class TileMap implements JSONSerialisable {
tiles = new int[width][height]; tiles = new int[width][height];
} }
public TileMap(int[][] tiles) {
this.width = World.WORLD_SIZE;
this.height = World.WORLD_SIZE;
this.tiles = tiles;
}
/** /**
* Change the tile at a specified position * Change the tile at a specified position
* Sets the modified flag * Sets the modified flag
@ -128,11 +139,37 @@ public class TileMap implements JSONSerialisable {
return json; return json;
} }
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("tiles", tiles);
return dbObject;
}
public static TileMap deserialize(DBObject object) {
BasicDBList terrain = (BasicDBList) object.get("tiles");
int[][] tiles = new int[World.WORLD_SIZE][World.WORLD_SIZE];
for (int x = 0; x < World.WORLD_SIZE; x++) {
for (int y = 0; y < World.WORLD_SIZE; y++) {
tiles[x][y] = (int) ((BasicDBList) terrain.get(x)).get(y);
}
}
return new TileMap(tiles);
}
public static TileMap deserialize(JSONObject object) { public static TileMap deserialize(JSONObject object) {
TileMap tileMap = new TileMap(World.WORLD_SIZE, World.WORLD_SIZE); TileMap tileMap = new TileMap(World.WORLD_SIZE, World.WORLD_SIZE);
byte[] compressedBytes = Base64.getDecoder().decode((String) object.get("z")); byte[] compressedBytes = Base64.getDecoder().decode((String) object.get("z"));
try { try {

View File

@ -1,18 +1,20 @@
package net.simon987.server.game; package net.simon987.server.game;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.event.GameEvent; import net.simon987.server.event.GameEvent;
import net.simon987.server.event.WorldUpdateEvent; import net.simon987.server.event.WorldUpdateEvent;
import net.simon987.server.game.pathfinding.Pathfinder; import net.simon987.server.game.pathfinding.Pathfinder;
import net.simon987.server.io.JSONSerialisable; import net.simon987.server.io.MongoSerialisable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import java.awt.*; import java.awt.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Random; import java.util.Random;
public class World implements JSONSerialisable { public class World implements MongoSerialisable {
/** /**
* Size of the side of a world * Size of the side of a world
@ -111,24 +113,26 @@ public class World implements JSONSerialisable {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject();
JSONArray objects = new JSONArray(); BasicDBObject dbObject = new BasicDBObject();
BasicDBList objects = new BasicDBList();
ArrayList<GameObject> gameObjects_ = new ArrayList<>(gameObjects); ArrayList<GameObject> gameObjects_ = new ArrayList<>(gameObjects);
for (GameObject obj : gameObjects_) { for (GameObject obj : gameObjects_) {
objects.add(obj.serialise()); objects.add(obj.mongoSerialise());
} }
json.put("o", objects);
json.put("t", tileMap.serialise()); dbObject.put("objects", objects);
dbObject.put("terrain", tileMap.mongoSerialise());
json.put("x", x); dbObject.put("x", x);
json.put("y", y); dbObject.put("y", y);
json.put("u", updatable); dbObject.put("updatable", updatable);
return json;
return dbObject;
} }
@Override @Override
@ -150,21 +154,45 @@ public class World implements JSONSerialisable {
public static World deserialize(JSONObject json) { public static World deserialize(JSONObject json) {
World world = new World(); World world = new World();
world.x = (int) (long) json.get("x"); // world.x = (int) (long) json.get("x");
world.y = (int) (long) json.get("y"); // world.y = (int) (long) json.get("y");
world.updatable = (int) (long) json.get("u"); // world.updatable = (int) (long) json.get("u");
//
// world.tileMap = TileMap.deserialize((JSONObject) json.get("t"));
//
//
// for (JSONObject objJson : (ArrayList<JSONObject>) json.get("o")) {
//
// GameObject object = GameObject.deserialize(objJson);
//
// object.setWorld(world);
// world.gameObjects.add(object);
// }
world.tileMap = TileMap.deserialize((JSONObject) json.get("t")); return world;
}
for (JSONObject objJson : (ArrayList<JSONObject>) json.get("o")) { public static World deserialize(DBObject dbObject) {
GameObject object = GameObject.deserialize(objJson); World world = new World();
world.x = (int) dbObject.get("x");
world.y = (int) dbObject.get("y");
world.updatable = (int) dbObject.get("updatable");
world.tileMap = TileMap.deserialize((BasicDBObject) dbObject.get("terrain"));
BasicDBList objects = (BasicDBList) dbObject.get("objects");
for (Object obj : objects) {
GameObject object = GameObject.deserialize((DBObject) obj);
object.setWorld(world); object.setWorld(world);
world.gameObjects.add(object); world.gameObjects.add(object);
} }
return world; return world;
} }
/** /**

View File

@ -5,7 +5,6 @@ import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.exception.CancelledException; import net.simon987.server.assembly.exception.CancelledException;
import net.simon987.server.event.GameEvent; import net.simon987.server.event.GameEvent;
import net.simon987.server.event.WorldGenerationEvent; import net.simon987.server.event.WorldGenerationEvent;
import net.simon987.server.logging.LogManager;
import java.awt.*; import java.awt.*;
import java.util.HashMap; import java.util.HashMap;
@ -93,7 +92,6 @@ public class WorldGenerator {
* Create a randomly generated World * Create a randomly generated World
*/ */
public World generateWorld(int locX, int locY) throws CancelledException { public World generateWorld(int locX, int locY) throws CancelledException {
LogManager.LOGGER.info("Generating random world");
Random random = new Random(); Random random = new Random();
World world = generateEmptyWorld(locX, locY); World world = generateEmptyWorld(locX, locY);

View File

@ -1,10 +1,10 @@
package net.simon987.server.io; package net.simon987.server.io;
import com.mongodb.DBObject;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import org.json.simple.JSONObject;
public interface CpuHardwareDeserializer { public interface CpuHardwareDeserializer {
CpuHardware deserializeHardware(JSONObject hwJson); CpuHardware deserializeHardware(DBObject hwJson);
} }

View File

@ -1,10 +1,10 @@
package net.simon987.server.io; package net.simon987.server.io;
import com.mongodb.DBObject;
import net.simon987.server.game.GameObject; import net.simon987.server.game.GameObject;
import org.json.simple.JSONObject;
public interface GameObjectDeserializer { public interface GameObjectDeserializer {
GameObject deserializeObject(JSONObject object); GameObject deserializeObject(DBObject object);
} }

View File

@ -0,0 +1,9 @@
package net.simon987.server.io;
import com.mongodb.BasicDBObject;
public interface MongoSerialisable {
BasicDBObject mongoSerialise();
}

View File

@ -1,18 +1,19 @@
package net.simon987.server.user; package net.simon987.server.user;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CPU; import net.simon987.server.assembly.CPU;
import net.simon987.server.assembly.exception.CancelledException; import net.simon987.server.assembly.exception.CancelledException;
import net.simon987.server.event.GameEvent; import net.simon987.server.event.GameEvent;
import net.simon987.server.event.UserCreationEvent; import net.simon987.server.event.UserCreationEvent;
import net.simon987.server.game.ControllableUnit; import net.simon987.server.game.ControllableUnit;
import net.simon987.server.io.JSONSerialisable; import net.simon987.server.io.MongoSerialisable;
import org.json.simple.JSONObject;
/** /**
* Represents a User (or player) of the game * Represents a User (or player) of the game
*/ */
public class User implements JSONSerialisable { public class User implements MongoSerialisable {
private String username; private String username;
@ -39,33 +40,31 @@ public class User implements JSONSerialisable {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject(); BasicDBObject dbObject = new BasicDBObject();
json.put("username", username); dbObject.put("username", username);
json.put("code", userCode); dbObject.put("code", userCode);
json.put("controlledUnit", controlledUnit.getObjectId()); dbObject.put("controlledUnit", controlledUnit.getObjectId());
json.put("cpu", cpu.serialise()); dbObject.put("cpu", cpu.mongoSerialise());
return json;
return dbObject;
} }
public static User deserialize(JSONObject userJson) throws CancelledException { public static User deserialize(DBObject obj) throws CancelledException {
User user = new User((ControllableUnit) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) userJson.get("controlledUnit"))); User user = new User((ControllableUnit) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("controlledUnit")));
user.username = (String) userJson.get("username"); user.username = (String) obj.get("username");
user.userCode = (String) userJson.get("code"); user.userCode = (String) obj.get("code");
user.getControlledUnit().setParent(user); user.getControlledUnit().setParent(user);
user.cpu = CPU.deserialize((JSONObject) userJson.get("cpu"), user); user.cpu = CPU.deserialize((DBObject) obj.get("cpu"), user);
return user; return user;
} }
//---- //----
public String getUserCode() { public String getUserCode() {

View File

@ -15,7 +15,7 @@ public class ObjectsRequestHandler implements MessageHandler {
@Override @Override
public void handle(OnlineUser user, JSONObject json) { public void handle(OnlineUser user, JSONObject json) {
if (json.get("t").equals("object")) { if (json.get("t").equals("object")) {
LogManager.LOGGER.fine("(WS) Objects request from " + user.getUser().getUsername()); // LogManager.LOGGER.fine("(WS) Objects request from " + user.getUser().getUsername());
int x, y; int x, y;
try { try {
@ -26,7 +26,7 @@ public class ObjectsRequestHandler implements MessageHandler {
return; return;
} }
World world = GameServer.INSTANCE.getGameUniverse().getWorld(x, y); World world = GameServer.INSTANCE.getGameUniverse().getWorld(x, y, false);
if (world != null) { if (world != null) {
ArrayList<GameObject> gameObjects = world.getGameObjects(); ArrayList<GameObject> gameObjects = world.getGameObjects();

View File

@ -20,6 +20,7 @@ import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.security.KeyFactory; import java.security.KeyFactory;
@ -59,6 +60,7 @@ public class SocketServer extends WebSocketServer {
} }
setConnectionLostTimeout(120); setConnectionLostTimeout(120);
setReuseAddr(true); //To avoid BindException
database = new SocketServerDatabase(config); database = new SocketServerDatabase(config);
@ -145,10 +147,19 @@ public class SocketServer extends WebSocketServer {
@Override @Override
public void onError(WebSocket conn, Exception ex) { public void onError(WebSocket conn, Exception ex) {
LogManager.LOGGER.severe("an error occurred on connection " + conn + ": " + ex); if (ex instanceof BindException) {
userManager.remove(userManager.getUser(conn));
LogManager.LOGGER.severe("Address already in use");
System.exit(-1);
} else {
LogManager.LOGGER.severe("an error occurred on connection " + conn + ": " + ex);
userManager.remove(userManager.getUser(conn));
ex.printStackTrace();
}
ex.printStackTrace();
} }
@Override @Override

View File

@ -12,12 +12,12 @@ public class TerrainRequestHandler implements MessageHandler {
public void handle(OnlineUser user, JSONObject json) { public void handle(OnlineUser user, JSONObject json) {
if (json.get("t").equals("terrain") && json.containsKey("x") && json.containsKey("y")) { if (json.get("t").equals("terrain") && json.containsKey("x") && json.containsKey("y")) {
LogManager.LOGGER.fine("Terrain request from " + user.getUser().getUsername()); // LogManager.LOGGER.fine("Terrain request from " + user.getUser().getUsername());
World world; World world;
try { try {
world = GameServer.INSTANCE.getGameUniverse().getWorld( world = GameServer.INSTANCE.getGameUniverse().getWorld(
Long.valueOf((long) json.get("x")).intValue(), Long.valueOf((long) json.get("x")).intValue(),
Long.valueOf((long) json.get("y")).intValue()); Long.valueOf((long) json.get("y")).intValue(), false);
} catch (NullPointerException e) { } catch (NullPointerException e) {
LogManager.LOGGER.severe("FIXME: handle TerrainRequestHandler"); LogManager.LOGGER.severe("FIXME: handle TerrainRequestHandler");
return; return;
@ -38,11 +38,17 @@ public class TerrainRequestHandler implements MessageHandler {
} }
response.put("t", "terrain"); response.put("t", "terrain");
response.put("ok", true);
response.put("terrain", terrain); response.put("terrain", terrain);
user.getWebSocket().send(response.toJSONString()); user.getWebSocket().send(response.toJSONString());
} else { } else {
LogManager.LOGGER.severe("FIXME handle:TerrainRequestHandler"); //Uncharted World
JSONObject response = new JSONObject();
response.put("t", "terrain");
response.put("ok", false);
user.getWebSocket().send(response.toJSONString());
} }
} }
} }