Permalink
Browse files

mapgen-load and save-map plugins

  • Loading branch information...
1 parent 4238a8f commit 08e5fcd5d36c428b43d378963289a07be62fc8e4 @deoxxa committed Nov 9, 2012
Showing with 63 additions and 1 deletion.
  1. +2 −1 .gitignore
  2. 0 map/.gitkeep
  3. +27 −0 plugins/mapgen-load.js
  4. +23 −0 plugins/save-map.js
  5. +11 −0 server.example.js
View
@@ -1,2 +1,3 @@
/node_modules
-/config.json
+/config.json
+/map
View
No changes.
View
@@ -0,0 +1,27 @@
+var path = require("path"),
+ fs = require("fs");
+
+var MapgenLoad = module.exports = function MapgenLoad(location) {
+ this.location = location;
+};
+
+MapgenLoad.prototype.modify = function modify(chunk, cb) {
+ var k = [chunk.x.toString(36), chunk.z.toString(36)].join(":"),
+ file = path.join(this.location, Buffer(k).toString("base64"));
+
+ fs.exists(file, function(exists) {
+ if (!exists) {
+ return cb(null, chunk);
+ }
+
+ fs.readFile(file, function(err, data) {
+ if (err) {
+ return cb(err);
+ }
+
+ data.copy(chunk.data);
+
+ return cb(true, chunk);
+ });
+ });
+};
View
@@ -0,0 +1,23 @@
+var path = require("path"),
+ fs = require("fs");
+
+module.exports = function(location) {
+ return function(game) {
+ var save_interval = setInterval(function() {
+ Object.keys(game.map.chunks).forEach(function(k) {
+ if (!game.map.chunks[k].dirty) { return; }
+
+ console.log("Saving chunk " + k);
+
+ fs.writeFile(path.join(location, Buffer(k).toString("base64")), game.map.chunks[k].data, function(err) {
+ if (err) {
+ console.warn(err);
+ return;
+ }
+
+ game.map.chunks[k].dirty = false;
+ });
+ });
+ }, 10000);
+ };
+};
View
@@ -31,6 +31,12 @@ var Map = require("./lib/map");
var map = new Map();
+// The `MapgenLoad` plugin loads existing map data from disk. The argument given
+// to it is the directory to store map data in.
+var MapgenLoad = require("./plugins/mapgen-load"),
+ mapgen_load = new MapgenLoad(__dirname + "/map");
+map.add_generator(mapgen_load.modify.bind(mapgen_load));
+
// The `MapgenSimplex` plugin generates pseudorandom terrain using an algorithm
// related to _Perlin Noise_, [Simplex Noise](http://en.wikipedia.org/wiki/Simplex_noise).
// The argument you see here is the "seed" value.
@@ -125,6 +131,11 @@ game.use(RespawnPlugin());
var DespawnPlugin = require("./plugins/despawn");
game.use(DespawnPlugin());
+// This plugin saves the map to disk every now and then, if it's changed. The
+// argument given to it is the directory in which to save the map data.
+var SaveMapPlugin = require("./plugins/save-map");
+game.use(SaveMapPlugin(__dirname + "/map"));
+
// The server object is basically a wrapper around `net.Server` that constructs
// `Client` objects as they connect.

0 comments on commit 08e5fcd

Please sign in to comment.