package Hexel.chunk;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import Hexel.Hexel;
import Hexel.math.Vector3i;
public class ChunkFile {
private static final Object lock = new Object();
public static void save(Chunk chunk) {
if (!Hexel.session.save)
return;
synchronized (lock) {
Vector3i p = chunk.getXYZ();
File dir = new File(Hexel.workingDir, getFolder());
if (!dir.exists()) {
dir.mkdirs();
}
String path = getPath(p);
File file = new File(Hexel.workingDir, path);
try {
if (!file.exists() && !file.createNewFile()) {
System.out.println("Failed to create file!");
}
ObjectOutputStream out = new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(file)));
out.writeObject(chunk);
out.close();
} catch (IOException e) {
e.printStackTrace();
// System.exit(1);
}
chunk.modified = false;
}
}
public static Chunk load(Vector3i p) {
synchronized (lock) {
Chunk c = null;
try {
String path = getPath(p);
GZIPInputStream fileIn = new GZIPInputStream(new FileInputStream(new File(Hexel.workingDir, path)));
ObjectInputStream in = new ObjectInputStream(fileIn);
c = (Chunk) in.readObject();
in.close();
fileIn.close();
} catch (IOException e) {
System.out.println("Caught Exception reading chunk!");
e.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException e) {
System.out.println("Chunk class not found");
e.printStackTrace();
System.exit(1);
}
c.modified = false;
return c;
}
}
public static boolean has(Vector3i p) {
synchronized (lock) {
String path = getPath(p);
File f = new File(Hexel.workingDir, path);
return f.exists();
}
}
private static String getFolder() {
return Hexel.saveDir + "/" + Hexel.session.sessionId + "/chunks/";
}
private static String getFilename(Vector3i p) {
return p + ".ser";
}
private static String getPath(Vector3i p) {
return getFolder() + getFilename(p);
}
}