Merged researchSync

This commit is contained in:
Danielv123 committed 2018-04-11 15:20:15 +02:00
commit 3af343c5a0
31 files changed
+2152 -393

No files matched your search

+7 -3
View File
@@ -23,9 +23,9 @@ coverage
# Compiled binary addons (http://nodejs.org/api/addons.html) # Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release build/Release
# Dependency directory node_modules/*
# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git !node_modules/_app
node_modules
Factorio* Factorio*
/factorio /factorio
/instances /instances
@@ -34,6 +34,10 @@ Factorio*
database/items.db database/items.db
config.json config.json
package-lock.json package-lock.json
mod_cache.json
static/pictures/spritesheet.js
static/pictures/spritesheet.png
static/external
# weird pattern to ignore sharedPlugins except not ignore some core modules # weird pattern to ignore sharedPlugins except not ignore some core modules
!sharedPlugins/ !sharedPlugins/
+112 -76
View File
@@ -12,9 +12,11 @@ const _ = require('underscore');
const deepmerge = require("deepmerge"); const deepmerge = require("deepmerge");
const getMac = require('getmac').getMac; const getMac = require('getmac').getMac;
const rmdirSync = require('rmdir-sync'); const rmdirSync = require('rmdir-sync');
const ioClient = require("socket.io-client");
// internal libraries // internal libraries
const objectOps = require("./lib/objectOps.js"); const objectOps = require("./lib/objectOps.js");
const fileOps = require("./lib/fileOps.js"); const fileOps = require("_app/fileOps");
const stringUtils = require("./lib/stringUtils.js"); const stringUtils = require("./lib/stringUtils.js");
const modManager = require("./lib/manager/modManager.js"); const modManager = require("./lib/manager/modManager.js");
const configManager = require("./lib/manager/configManager.js"); const configManager = require("./lib/manager/configManager.js");
@@ -77,7 +79,9 @@ if (!command || command == "help" || command == "--help") {
console.error("node client.js list"); console.error("node client.js list");
console.error("node client.js delete [instance]"); console.error("node client.js delete [instance]");
console.error("To download the latest version of the Clusterio lua mod, do"); console.error("To download the latest version of the Clusterio lua mod, do");
console.error("node client.js download"); console.error("node client.js manage shared mods download clusterio");
console.error("For more management options, do");
console.error("node client.js manage");
process.exit(1); process.exit(1);
} else if (command == "list") { } else if (command == "list") {
let instanceNames = fileOps.getDirectoriesSync("./instances/"); let instanceNames = fileOps.getDirectoriesSync("./instances/");
@@ -128,7 +132,7 @@ if (!command || command == "help" || command == "--help") {
//const fullUsage = 'node client.js manage [instance, "shared"] ["mods", "config"] ...'; //const fullUsage = 'node client.js manage [instance, "shared"] ["mods", "config"] ...';
function usage(instance, tool, action){ function usage(instance, tool, action){
if(tool && tool == "mods"){ if(tool && tool == "mods"){
console.log('node client.js manage '+instance+' '+tool+' ["list", "search", "update"]'); console.log('node client.js manage '+instance+' '+tool+' ["list", "search", "add", "remove", "update"]');
} else if(tool && tool == "config") { } else if(tool && tool == "config") {
console.log('node client.js manage '+instance+' '+tool+' ["list", "edit"]'); console.log('node client.js manage '+instance+' '+tool+' ["list", "edit"]');
} else { } else {
@@ -144,6 +148,10 @@ if (!command || command == "help" || command == "--help") {
modManager.listMods(instance); modManager.listMods(instance);
} else if(action == "search"){ } else if(action == "search"){
modManager.findMods(process.argv[6]); modManager.findMods(process.argv[6]);
} else if(action == "add" || action == "download"){
modManager.addMod(process.argv[6], instance);
} else if(action == "remove" || action == "rm" || action == "delete"){
modManager.removeMod(process.argv[6], instance);
} else if(action == "update"){ } else if(action == "update"){
modManager.updateAllMods(); modManager.updateAllMods();
} else { } else {
@@ -224,8 +232,8 @@ write-data=__PATH__executable__/../../../instances/" + instance + "\r\n\
// this line is probably not needed anymore but Im not gonna remove it // this line is probably not needed anymore but Im not gonna remove it
fs.copySync('sharedMods', instancedirectory + "/mods"); fs.copySync('sharedMods', instancedirectory + "/mods");
let instconf = { let instconf = {
"factorioPort": process.env.FACTORIOPORT | Math.floor(Math.random() * 65535), "factorioPort": process.env.FACTORIOPORT || Math.floor(Math.random() * 65535),
"clientPort": process.env.RCONPORT | Math.floor(Math.random() * 65535), "clientPort": process.env.RCONPORT || Math.floor(Math.random() * 65535),
"clientPassword": Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8), "clientPassword": Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8),
} }
console.log("Clusterio | Created instance with settings:") console.log("Clusterio | Created instance with settings:")
@@ -409,6 +417,16 @@ write-data=__PATH__executable__/../../../instances/" + instance + "\r\n\
// ensure instancemanagement only ever runs once // ensure instancemanagement only ever runs once
_.once(instanceManagement); _.once(instanceManagement);
function instanceManagement() { function instanceManagement() {
/* Open websocket connection to master */
var socket = ioClient("http://"+config.masterIP+":"+config.masterPort);
socket.on("hello", data => {
console.log("SOCKET | registering slave!");
socket.emit("registerSlave", {
instanceID: instanceconfig.unique,
});
setInterval(B=> socket.emit("heartbeat"), 10000);
});
console.log("Started instanceManagement();"); console.log("Started instanceManagement();");
// load plugins and execute onLoad event // load plugins and execute onLoad event
let pluginDirectories = fileOps.getDirectoriesSync("./sharedPlugins/"); let pluginDirectories = fileOps.getDirectoriesSync("./sharedPlugins/");
@@ -448,21 +466,27 @@ function instanceManagement() {
fs.writeFileSync(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, ""); fs.writeFileSync(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, "");
} }
global.subscribedFiles[pluginConfig.scriptOutputFileSubscription] = true; global.subscribedFiles[pluginConfig.scriptOutputFileSubscription] = true;
console.log("Clusterio | Registered file subscription on "+instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription);
fs.watch(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, fileChangeHandler);
// run once in case a plugin wrote out information before the plugin loaded fully
fileChangeHandler(false, pluginConfig.scriptOutputFileSubscription);
fs.watch(instancedirectory + "/script-output/" + pluginConfig.scriptOutputFileSubscription, function (eventType, filename) { // send file contents to plugin for processing
if (filename == null) return; function fileChangeHandler(eventType, filename) {
// get array of lines in file if(filename != null){
let stuff = fs.readFileSync(instancedirectory + "/script-output/" + filename, "utf8").split("\n"); // get array of lines in file
// if you found anything, reset the file let stuff = fs.readFileSync(instancedirectory + "/script-output/" + filename, "utf8").split("\n");
if (stuff[0]) { // if you found anything, reset the file
fs.writeFileSync(instancedirectory + "/script-output/" + filename, ""); if (stuff[0]) {
} fs.writeFileSync(instancedirectory + "/script-output/" + filename, "");
for (let i = 0; i < stuff.length; i++) { }
if (stuff[i]) { for(let i = 0; i < stuff.length; i++) {
plugins[I].scriptOutput(stuff[i]); if(stuff[i]) {
plugins[I].scriptOutput(stuff[i]);
}
} }
} }
}); }
} }
console.log("Clusterio | Loaded plugin " + pluginDirectories[i]); console.log("Clusterio | Loaded plugin " + pluginDirectories[i]);
} else if(pluginConfig.binary != "nodePackage"){ } else if(pluginConfig.binary != "nodePackage"){
@@ -565,7 +589,8 @@ function instanceManagement() {
playerCount: instanceInfo.playerCount || 0, playerCount: instanceInfo.playerCount || 0,
instanceName: instance, instanceName: instance,
} }
getMac(function (err, mac) {
function callback(err, mac) {
if (err) { if (err) {
console.log("##### getMac crashed, but we don't really give a shit because we are probably closing down #####"); console.log("##### getMac crashed, but we don't really give a shit because we are probably closing down #####");
} else { } else {
@@ -581,7 +606,12 @@ function instanceManagement() {
} }
}); });
} }
}); }
if(global.mac){
callback(undefined, global.mac);
} else {
getMac(callback);
}
},1000)}); },1000)});
} }
}); });
@@ -777,7 +807,7 @@ function instanceManagement() {
messageInterface("/silent-command remote.call('clusterio', 'importMany', '" + sadas + "')"); messageInterface("/silent-command remote.call('clusterio', 'importMany', '" + sadas + "')");
sadas = null; sadas = null;
} }
}, 3000); }, 1000);
// COMBINATOR SIGNALS --------------------------------------------------------- // COMBINATOR SIGNALS ---------------------------------------------------------
// get inventory from Master and RCON it to our slave // get inventory from Master and RCON it to our slave
setInterval(function () { setInterval(function () {
@@ -786,6 +816,7 @@ function instanceManagement() {
console.log("Unable to get JSON master/api/inventory, master might be unaccessible"); console.log("Unable to get JSON master/api/inventory, master might be unaccessible");
} else if (response && response.body) { } else if (response && response.body) {
// Take the inventory we (hopefully) got and turn it into the format LUA accepts // Take the inventory we (hopefully) got and turn it into the format LUA accepts
if(Buffer.isBuffer(response.body)) {console.log(response.body.toString("utf-8")); throw new Error();} // We are probably contacting the wrong webserver
try { try {
var inventory = JSON.parse(response.body); var inventory = JSON.parse(response.body);
} catch (e){ } catch (e){
@@ -804,63 +835,67 @@ function instanceManagement() {
} }
}); });
}, 1000); }, 1000);
// REMOTE SIGNALLING // Make sure world has its worldID
// send any signals the slave has been told to send setTimeout(function(){
setInterval(function () { messageInterface("/silent-command remote.call('clusterio','setWorldID',"+instanceconfig.unique+")")
// Fetch combinator signals from the server }, 20000);
needle.post(config.masterIP + ":" + config.masterPort + '/api/readSignal', { /* REMOTE SIGNALLING
since: lastSignalCheck * send any signals the slave has been told to send
}, function (err, response, body) { * Fetch combinator signals from the server
if (response && response.body) { */
if(typeof response.body == "string") response.body = JSON.parse(response.body); socket.on("processCombinatorSignal", circuitFrameWithMeta => {
// Take the new combinator frames and compress them so we can use a single command if(circuitFrameWithMeta && typeof circuitFrameWithMeta == "object" && circuitFrameWithMeta.frame && Array.isArray(circuitFrameWithMeta.frame)){
let frameset = []; messageInterface("/silent-command remote.call('clusterio', 'receiveFrame', '"+JSON.stringify(circuitFrameWithMeta.frame)+"')");
for (let i = 0; i < response.body.length; i++) {
frameset[i] = response.body[i].frame;
}
// console.log(frameset);
// Send all our compressed frames
messageInterface("/silent-command remote.call('clusterio', 'receiveMany', '" + JSON.stringify(frameset) + "')");
}
});
// after fetching all the latest frames, we take a timestamp. During the next iteration, we fetch all frames submitted after this.
lastSignalCheck = Date.now();
// get outbound frames from file and send to master
// get array of lines in file, each line should correspond to a JSON encoded frame
let signals = fs.readFileSync(instancedirectory + "/script-output/txbuffer.txt", "utf8").split("\n");
// if we actually got anything from the file, proceed and reset file
if (signals[0]) {
fs.writeFileSync(instancedirectory + "/script-output/txbuffer.txt", "");
// loop through all our frames
for (let i = 0; i < signals.length; i++) {
(function (i) {
if (signals[i]) {
// signals[i] is a JSON array called a "frame" of signals. We timestamp it for storage on master
// then we unpack and RCON in this.frame to the game later.
let framepart = JSON.parse(signals[i]);
let doneframe = {
time: Date.now(),
frame: framepart, // thats our array of objects(single signals);
}
// console.log(doneframe);
needle.post(config.masterIP + ":" + config.masterPort + '/api/setSignal', doneframe, function (err, response, body) {
if (response && response.body) {
// In the future we might be interested in whether or not we actually manage to send it, but honestly I don't care.
}
});
}
})(i);
}
} }
}, 1000); });
// get outbound frames from file and send to master
// get array of lines in file, each line should correspond to a JSON encoded frame
let signals = fs.readFileSync(instancedirectory + "/script-output/txbuffer.txt", "utf8").split("\n");
// if we actually got anything from the file, proceed and reset file
let readingTxBufferSoon = false;
let txBufferClearCounter = 0;
fs.watch(instancedirectory + "/script-output/txbuffer.txt", "utf-8", (eventType, filename) => {
if(!readingTxBufferSoon){ // use a 100ms delay to avoid messing with rapid sequential writes from factorio (I think that might be a problem maybe?)
readingTxBufferSoon = true;
setTimeout(()=>{
txBufferClearCounter++;
fs.readFile(instancedirectory + "/script-output/txbuffer.txt", "utf-8", (err, signals) => {
signals = signals.split("\n");
if (signals[0]) {
//if(txBufferClearCounter > 500){
fs.writeFileSync(instancedirectory + "/script-output/txbuffer.txt", "");
// txBufferClearCounter = 0;
//}
// loop through all our frames
for (let i = 0; i < signals.length; i++) {
if (signals[i] && objectOps.isJSON(signals[i])) {
// signals[i] is a JSON array called a "frame" of signals. We timestamp it for storage on master
// then we unpack and RCON in this.frame to the game later.
let framepart = JSON.parse(signals[i]);
let doneframe = {
time: Date.now(),
frame: framepart, // thats our array of objects(single signals);
}
// send to master using socket.io, opened at the top of instanceManagement()
socket.emit("combinatorSignal", doneframe);
} else {
// console.log("Invalid jsony: "+typeof signals[i])
}
}
}
});
readingTxBufferSoon = false;
},100);
}
});
} // END OF INSTANCE START --------------------------------------------------------------------- } // END OF INSTANCE START ---------------------------------------------------------------------
// string, function // string, function
// returns [{modName:string,hash:string}, ... ] // returns [{modName:string,hash:string}, ... ]
function hashMods(instanceName, callback) { function hashMods(instanceName, callback) {
if(!callback) { if(!callback) {
throw "ERROR in function hashMods NO CALLBACK" throw new Error("ERROR in function hashMods NO CALLBACK");
} }
function callback2(hash, modName){ function callback2(hash, modName){
hashedMods[hashedMods.length] = { hashedMods[hashedMods.length] = {
@@ -868,22 +903,23 @@ function hashMods(instanceName, callback) {
hash: hash, hash: hash,
} }
// check if this callback has ran once for each mod // check if this callback has ran once for each mod
if(hashedMods.length == /*mods.length*/ + instanceMods.length) { if(hashedMods.length == instanceMods.length) {
callback(hashedMods); callback(hashedMods);
} }
//console.log(modname); //console.log(modname);
} }
let hashedMods = []; let hashedMods = [];
var i = 0;
/*let mods = fs.readdirSync("./sharedMods/")*/ /*let mods = fs.readdirSync("./sharedMods/")*/
let instanceMods = fs.readdirSync("./instances/"+instanceName+"/mods/"); let instanceMods = fs.readdirSync("./instances/"+instanceName+"/mods/");
if(instanceMods.length == 0){
for(o=0;o<instanceMods.length;o++) { callback({}); // there are no mods installed, return an empty object
}
for(let o=0;o<instanceMods.length;o++) {
if(path.extname(instanceMods[o]) != ".zip") { if(path.extname(instanceMods[o]) != ".zip") {
instanceMods.splice(instanceMods.indexOf(instanceMods[o]), 1); // remove element from array instanceMods.splice(instanceMods.indexOf(instanceMods[o]), 1); // remove element from array, we can't hash unzipped mods
} }
} }
for(i=0; i<instanceMods.length; i++){ for(let i=0; i<instanceMods.length; i++){
let path = "./instances/"+instanceName+"/mods/"+instanceMods[i]; let path = "./instances/"+instanceName+"/mods/"+instanceMods[i];
let name = instanceMods[i]; let name = instanceMods[i];
let options = { let options = {
+49
View File
@@ -0,0 +1,49 @@
var forge = require("node-forge");
forge.options.usePureJavaScript = true;
var fs = require("fs");
var mkdirp = require("mkdirp");
var pki = forge.pki;
var rsa = forge.pki.rsa;
var startTime, endTime;
module.exports = function({
bits = 2048,
certificatePath = "database/certificate",
doLogging = false,
} = {}){
function log(t){
if(doLogging) console.log("lib/generateSSLcert.js | "+t);
}
log("Generating SSL certificate with "+bits+" bits at "+certificatePath);
startTime = Date.now();
var keypair = rsa.generateKeyPair({bits: bits, e: 0x10001});
endTime = Date.now();
log("Generated 2048bit keypair in: "+(endTime-startTime)+" ms");
startTime = Date.now();
var cert = pki.createCertificate();
cert.publicKey = keypair.publicKey;
cert.serialNumber = "01";
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date(Date.now()+(1000*60*60*24*365)); // valid for one year
// self-sign certificate
cert.sign(keypair.privateKey);
// Convert certificate to pem type and write it to a file
if(certificatePath[certificatePath.length-1] != "/") certificatePath += "/";
if(!fs.existsSync(certificatePath)) {
mkdirp.sync(certificatePath);
console.log("Created directory: "+certificatePath);
}
fs.writeFileSync(certificatePath+ "cert.key", pki.privateKeyToPem(keypair.privateKey));
fs.writeFileSync(certificatePath+ "cert.crt", pki.certificateToPem(cert));
endTime = Date.now();
log("Generated certificate in: "+(endTime-startTime)+" ms");
}
+25
View File
@@ -0,0 +1,25 @@
var assert = require("assert");
var fs = require("fs");
var fileOps = require("_app/fileOps");
var generateSSLcert = require("./generateSSLcert.js")
describe("generateSSLcert.js(options)", ()=>{
it("Creates a folder with a .crt and .key file in it", ()=>{
let certPath = "lib/certTestPlsDelete";
assert(!fs.existsSync(certPath)); // if it already exsits, the test might pass because of leftover data (which is bad)
generateSSLcert({
// bits:512, // supported, but I just use the default of 2048 for this test
certificatePath:certPath,
doLogging: false,
});
assert(fs.existsSync(certPath));
assert(fs.existsSync(certPath+"/cert.key")); // private key
assert(fs.existsSync(certPath+"/cert.crt")); // certificate file
// remove certificates and data from the test
fileOps.deleteFolderRecursiveSync(certPath);
}).timeout(10000);
});
+1 -1
View File
@@ -1,4 +1,4 @@
const fileOps = require("./fileOps.js"); const fileOps = require("_app/fileOps");
module.exports = { module.exports = {
sync: function(){ sync: function(){
+117 -22
View File
@@ -6,12 +6,23 @@ Provides tools to manage mods in a clusterio install
const rightpad = require("right-pad"); const rightpad = require("right-pad");
const asTable = require("as-table").configure({delimiter: ' | '}); const asTable = require("as-table").configure({delimiter: ' | '});
const moment = require("moment"); const moment = require("moment");
const syncRequest = require("sync-request");
const fs = require("fs");
const https = require('follow-redirects').https;
const factorioAPI = require("node-factorio-api"); const factorioAPI = require("node-factorio-api");
const fileOps = require("./../fileOps.js"); const sLog = require("single-line-log").stdout;
const fileOps = require("_app/fileOps");
const config = require("./../../config"); const config = require("./../../config");
const instances = require("./../getInstances.js").sync(); const instances = require("./../getInstances.js").sync();
function ellipse(str, max){
return str.length > (max - 3) ? str.substring(0,max-3) + '...' : str;
}
// https://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript
function formatBytes(a,b){if(0==a)return"0 Bytes";var c=1024,d=b||2,e=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],f=Math.floor(Math.log(a)/Math.log(c));return parseFloat((a/Math.pow(c,f)).toFixed(d))+" "+e[f]};
/** /**
Lists mods for an instance as a table. Warning, handles printing internally. Lists mods for an instance as a table. Warning, handles printing internally.
@param {string} instance - Name of the instance or "shared" @param {string} instance - Name of the instance or "shared"
@@ -25,14 +36,13 @@ modManager.listMods("shared");
*/ */
module.exports.listMods = function(instance){ module.exports.listMods = function(instance){
if(instance && instances.includes(instance)){ if(instance && instances.includes(instance)){
factorioAPI.init(false, 'instances/'+instance+'/instanceMods', 'instances/'+instance+'/saves', '0.15.37'); factorioAPI.init(false, 'instances/'+instance+'/instanceMods', 'instances/'+instance+'/saves', '0.16.15');
console.log("Authenticating to factorio.com...")
factorioAPI.authenticate({ factorioAPI.authenticate({
username: config.username, username: config.username,
token: config.token, token: config.token,
require_ownership: false require_ownership: false
}).then(token => { }).then(token => {
console.log("Currently installed:"); console.log("* Currently installed:");
factorioAPI.readModZips().then(list => { factorioAPI.readModZips().then(list => {
console.log(asTable(list.map(mod => { console.log(asTable(list.map(mod => {
return { return {
@@ -44,26 +54,25 @@ module.exports.listMods = function(instance){
} }
}))); })));
}); });
// Deactivated due to bug in node-factorio-api, see https://github.com/Danacus/node-factorio-api/issues/2 // Had issues earlier due to bug in node-factorio-api, see https://github.com/Danacus/node-factorio-api/issues/2
// bug is resolved, thanks to @Danacus and @brotherpot // bug is resolved, thanks to @Danacus and @brotherpot
/*factorioAPI.getModsFromSaves().then(list => { factorioAPI.getModsFromSaves().then(list => {
console.log("Mods used in save:"); console.log("* Mods used in save:");
console.log(JSON.stringify(list))
console.log(asTable(list[0].mods)) console.log(asTable(list[0].mods))
});*/ });
}).catch(reason => { }).catch(reason => {
console.log("Failed to authenticate to factorio.com! Please check your connection and the username+token used for authentication in config.json"); console.log("Failed to authenticate to factorio.com! Please check your connection and the username+token used for authentication in config.json");
}); });
} else { } else {
// list shared mods in /sharedMods/ // list shared mods in /sharedMods/
factorioAPI.init(false, 'sharedMods/', '', '0.15.37'); factorioAPI.init(false, 'sharedMods/', '', '0.16.15');
console.log("Authenticating to factorio.com...")
factorioAPI.authenticate({ factorioAPI.authenticate({
username: config.username, username: config.username,
token: config.token, token: config.token,
require_ownership: false require_ownership: false
}).then(() => { }).then(() => {
console.log("Mods shared by all instances:") console.log("\r\n")
console.log("* Mods shared by all instances:")
factorioAPI.getInstalledMods().then(mods => { factorioAPI.getInstalledMods().then(mods => {
console.log(asTable(mods)); console.log(asTable(mods));
}); });
@@ -85,20 +94,16 @@ the results to console as a neat looking table
*/ */
module.exports.findMods = function(searchTerm){ module.exports.findMods = function(searchTerm){
factorioAPI.init(false); factorioAPI.init(false);
console.log("Authenticating to factorio.com...")
factorioAPI.authenticate({ factorioAPI.authenticate({
username: config.username, username: config.username,
token: config.token, token: config.token,
require_ownership: false require_ownership: false
}).then(token => { }).then(token => {
factorioAPI.searchMods( factorioAPI.searchMods(searchTerm).then(mods => {
{q: searchTerm, order: 'top', page_size: 20} console.log(asTable(mods.reverse().map(mod => {
).then(body => {
let mods = body.results;
console.log(asTable(mods.map(mod => {
return { return {
title:mod.title, title:ellipse(mod.title, 50),
name:mod.name, name:ellipse(mod.name, 30),
downloads:mod.downloads_count, downloads:mod.downloads_count,
updated: moment(mod.updated_at).format("DD.MM.YY"), updated: moment(mod.updated_at).format("DD.MM.YY"),
owner:mod.owner, owner:mod.owner,
@@ -109,9 +114,99 @@ module.exports.findMods = function(searchTerm){
}); });
} }
module.exports.addMod = function(term, instance){
if(instance == "shared"){ // modDirectory has to end in /
var modDirectory = "sharedMods/";
} else {
var modDirectory = "instances/"+instance+"/instanceMods/";
}
if(term && term.length > 0){
if(term.includes("mods.factorio.com/mods/")){ // https://mods.factorio.com/mods/Danielv123/ChooChoo
// treat it as a link download
factorioAPI.init(false, modDirectory, "", "0.16.15");
factorioAPI.authenticate({
username: config.username,
token: config.token,
require_ownership: false
}).then(() => {
factorioAPI.searchMods(term.split("/")[term.split("/").length-1]).then(body => {
console.log("Im gonna download: "+body[0].name);
factorioAPI.downloadMod(body[0]).then(()=>{
console.log("Mod downloaded");
});
});
});
} else if(term.includes("github.com")){ // https://github.com/Danielv123/factorioClusterioMod
// treat it as a github releases download
let apiURL = "https://api.github.com/repos/" + term.split("/")[3] + "/" + term.split("/")[4] + "/releases"; // https://api.github.com/repos/Danielv123/factorioClusterioMod/releases
let res = syncRequest('GET', apiURL, {"headers":{"User-Agent":"Fuck you for requiring user agents!"}});
let url = JSON.parse(res.getBody())[0].assets[0].browser_download_url;
let name = JSON.parse(res.getBody())[0].assets[0].name;
if(url) {
console.log("Downloading " + url);
let file = fs.createWriteStream(modDirectory + name);
let bytesDownloaded = 0;
let downloadStartTime = Date.now();
https.get(url, function(response) {
let bytesToDownload = response.headers['content-length'];
response.pipe(file);
response.on("data", chunk => {
bytesDownloaded += chunk.length;
let downloadTimeElapsed = Date.now() - downloadStartTime;
let bytesPerSecond = bytesDownloaded / (downloadTimeElapsed/1000);
let timeToComplete = Math.floor((bytesToDownload - bytesDownloaded)/bytesPerSecond);
sLog("Downloading "+name+" "+(bytesDownloaded/bytesToDownload*100).toPrecision(3)+"% ("+formatBytes(bytesDownloaded)+" / "+formatBytes(bytesToDownload)+")\r\n"+
"about "+timeToComplete+" seconds remaining ("+formatBytes(bytesPerSecond)+"/s)");
}).on("end", x => {
sLog.clear();
console.log(" Downloaded in "+moment.utc(moment.duration(Date.now()-downloadStartTime).as('milliseconds')).format('mm:ss')); // because sLog.clear() doesn't seem to do the job of ending the line properly
});
});
}
} else {
// treat it as a search and download the top result
factorioAPI.init(false, modDirectory, "", "0.16.15");
factorioAPI.authenticate({
username: config.username,
token: config.token,
require_ownership: false
}).then(() => {
factorioAPI.searchMods(term).then(body => {
console.log("Im gonna download: "+body[0].name);
factorioAPI.downloadMod(body[0]).then(()=>{
console.log("Mod downloaded");
});
});
});
}
}
}
module.exports.removeMod = function removeMod(term, instance, force = false){
if(instance == "shared"){ // modDirectory has to end in /
var modDirectory = "sharedMods/";
} else {
var modDirectory = "instances/"+instance+"/instanceMods/";
}
if(term && typeof term == "string" && term.length > 0){
let mods = fs.readdirSync(modDirectory);
let modsMatchingFilter = mods.filter(mod => mod.toLowerCase().includes(term.toLowerCase()));
if(modsMatchingFilter.length < 1){
console.log("No mods found matching search");
} else if(modsMatchingFilter.length == 1){
console.log("Deleting "+modsMatchingFilter[0]);
fs.unlinkSync(modDirectory+modsMatchingFilter[0]);
console.log("Deleted.");
} else if(modsMatchingFilter.length > 1){
console.log("Found multiple mods, not doing anything");
modsMatchingFilter.forEach(mod => console.log(mod));
}
}
}
// 'https://api.github.com/repos/Danielv123/factorioClusterioMod/releases' // 'https://api.github.com/repos/Danielv123/factorioClusterioMod/releases'
/** /**
Download mod from github repo by looking for the first binary download in Download mod from github repo by looking for the first binary download in
the latest release, saving it to /sharedMods the latest release, saving it to /sharedMods
@param {string} url a github repo URL, for example https://api.github.com/repos/Danielv123/factorioClusterioMod/releases. Must link to /releases @param {string} url a github repo URL, for example https://api.github.com/repos/Danielv123/factorioClusterioMod/releases. Must link to /releases
+125 -7
View File
@@ -1,18 +1,136 @@
var mkdirp = require("mkdirp"); var mkdirp = require("mkdirp");
var http = require('http');
var https = require('https');
var fs = require('fs');
var modManager = require("./manager/modManager.js");
modManager.addMod("clusterio", "shared");
function makeDirectory(path){
return new Promise((resolve, reject) => {
mkdirp(path, function(err){
if(err){
console.error("Unable to mkdirp "+path);
console.error(err);
resolve(false);
} else {
console.log("mkdirp "+path);
resolve(true);
}
});
});
}
function download(url, file, callback){
return new Promise((resolve, reject) => {
let pathArray = file.split("/");
pathArray.pop(); // remove filename from the end
if(pathArray.length >= 1){
// this might be an invalid path!
fs.stat(pathArray.join("/"), (err, stat) => {
if(err){
makeDirectory(pathArray.join("/")).then(()=>{
doDownload(url, file, callback);
});
} else {
doDownload(url, file, callback);
}
});
} else {
doDownload(url, file, callback);
}
function doDownload(url, file, callback){
var writeStream = fs.createWriteStream(file);
let protocol = http;
if(url.split(":")[0] == "https") protocol = https;
var request = protocol.get(url, function(response) {
response.pipe(writeStream);
response.on("end", () => {
if(callback && typeof callback == "function") callback(file);
console.log("Downloaded "+file+" from "+url);
resolve();
});
});
}
});
}
var directories = [ var directories = [
"database/linvodb", "database/linvodb",
"sharedMods", "sharedMods",
"instances", "instances",
]; ];
let downloadList = [
{
url: "http://fbpviewer.trakos.pl/images/spritesheet.json",
file: "static/pictures/spritesheet.js",
callback: function(file){
fs.writeFileSync("static/pictures/spritesheet.js", "export default\n"+fs.readFileSync("static/pictures/spritesheet.js"));
},
},
{
url: "http://fbpviewer.trakos.pl/images/spritesheet.png",
file: "static/pictures/spritesheet.png",
},
{
url: "https://code.jquery.com/jquery.js",
file: "static/external/jquery.js",
},
{
url: "https://code.jquery.com/ui/1.12.1/jquery-ui.js",
file: "static/external/jquery-ui.js",
},
{
url: "https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.js",
file: "static/external/canvasjs.js",
},
{
url: "https://momentjs.com/downloads/moment.min.js",
file: "static/external/moment.min.js",
},
{
url: "https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js",
file: "static/external/mousetrap.min.js",
},
{
url: "https://fonts.googleapis.com/css?family=Roboto",
file: "static/external/css/Roboto.css",
},
{
url: "https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js",
file: "static/external/socket.io.js",
},
]
directories.forEach(path => { // initiate folder creations and downloads
mkdirp("database/linvodb", function(err){ processMkdirRecursive(processDownloadRecursive);
if(err){ function processMkdirRecursive(callback){
console.error("Unable to mkdirp "+path); let item = directories.shift();
console.error(err); makeDirectory(item).then(()=>{
if(directories.length == 0){
if(callback) callback();
} else { } else {
console.log("mkdirp "+path); processMkdirRecursive(callback);
} }
}); });
}) }
function processDownloadRecursive(callback){
let item = downloadList.shift();
download(item.url, item.file, item.callback).then(()=>{
if(downloadList.length == 0){
if(callback) callback();
} else {
processDownloadRecursive(callback);
}
});
}
// generate SSL certificates if they are missing
if(!fs.existsSync("database/certificates") || !fs.existsSync("database/certificates/cert.crt") || !fs.existsSync("database/certificates/cert.key")){
var generateSSLcert = require("./generateSSLcert.js");
generateSSLcert({
certificatePath: "database/certificates",
doLogging: true,
});
}
+161 -24
View File
@@ -63,6 +63,49 @@ app.use(express.static('static'));
// mod downloads // mod downloads
app.use(express.static(masterModFolder)); app.use(express.static(masterModFolder));
// set up logging software
const prometheusPrefix = "clusterio_";
const Prometheus = require('prom-client');
Prometheus.collectDefaultMetrics({ timeout: 10000 }); // collects RAM usage etc every 10 s
const httpRequestDurationMilliseconds = new Prometheus.Histogram({
name: prometheusPrefix+'http_request_duration_ms',
help: 'Duration of HTTP requests in ms',
labelNames: ['route'],
// buckets for response time from 0.1ms to 500ms
buckets: [0.10, 5, 15, 50, 100, 200, 300, 400, 500]
});
const endpointHitCounter = new Prometheus.Gauge({
name: prometheusPrefix+'endpoint_hit_gauge',
help: "How many requests a particular endpoint has gotten",
labelNames: ['route'],
});
const prometheusConnectedInstancesCounter = new Prometheus.Gauge({
name: prometheusPrefix+'connected_instaces_gauge',
help: "How many instances are currently connected to this master server",
});
const prometheusWsUsageCounter = new Prometheus.Counter({
name: prometheusPrefix+'websocket_usage_counter',
help: 'Websocket traffic',
labelNames: ["connectionType"],
});
setInterval(()=>{
let numberOfActiveSlaves = 0;
for(let instance in slaves){
if(Date.now() - Number(slaves[instance].time) < 1000 * 30) numberOfActiveSlaves++;
}
prometheusConnectedInstancesCounter.set(numberOfActiveSlaves);
},10000);
/**
Prometheus metrics endpoint. Returns performance and usage metrics in a prometheus readable format.
*/
app.get('/metrics', (req, res) => {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
res.set('Content-Type', Prometheus.register.contentType);
res.end(Prometheus.register.metrics());
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
});
// set up database // set up database
var Datastore = require('nedb'); var Datastore = require('nedb');
db = {}; db = {};
@@ -145,6 +188,8 @@ process.on('SIGINT', function () {
// world ID management // world ID management
// slaves post here to tell the server they exist // slaves post here to tell the server they exist
app.post("/api/getID", function(req,res) { app.post("/api/getID", function(req,res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
// request.body should be an object // request.body should be an object
// {rconPort, rconPassword, serverPort, mac, time} // {rconPort, rconPassword, serverPort, mac, time}
// time us a unix timestamp we can use to check for how long the server has been unresponsive // time us a unix timestamp we can use to check for how long the server has been unresponsive
@@ -163,9 +208,12 @@ app.post("/api/getID", function(req,res) {
} }
console.log("Slave registered: " + slaves[req.body.unique].mac + " : " + slaves[req.body.unique].serverPort+" at " + slaves[req.body.unique].publicIP + " with name " + slaves[req.body.unique].instanceName); console.log("Slave registered: " + slaves[req.body.unique].mac + " : " + slaves[req.body.unique].serverPort+" at " + slaves[req.body.unique].publicIP + " with name " + slaves[req.body.unique].instanceName);
} }
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
}); });
app.post("/api/editSlaveMeta", function(req,res) { app.post("/api/editSlaveMeta", function(req,res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
// request.body should be an object // request.body should be an object
// {instanceID, pass, meta:{x,y,z}} // {instanceID, pass, meta:{x,y,z}}
@@ -181,6 +229,7 @@ app.post("/api/editSlaveMeta", function(req,res) {
res.send("ERROR: Invalid instanceID or password") res.send("ERROR: Invalid instanceID or password")
} }
} }
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
}); });
app.post("/api/getSlaveMeta", function (req, res) { app.post("/api/getSlaveMeta", function (req, res) {
@@ -206,6 +255,8 @@ app.post("/api/getSlavesMeta", function (req, res) {
// mod management // mod management
// should handle uploading and checking if mods are uploaded // should handle uploading and checking if mods are uploaded
app.post("/api/checkMod", function(req,res) { app.post("/api/checkMod", function(req,res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
let files = fs.readdirSync(masterModFolder); let files = fs.readdirSync(masterModFolder);
let found = false; let found = false;
files.forEach(file => { files.forEach(file => {
@@ -220,25 +271,31 @@ app.post("/api/checkMod", function(req,res) {
res.send("found"); res.send("found");
} }
res.end(); res.end();
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
}); });
app.post("/api/uploadMod", function(req,res) { app.post("/api/uploadMod", function(req,res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
if (!req.files) { if (!req.files) {
res.send('No files were uploaded.'); res.send('No files were uploaded.');
return; return;
} else { } else {
console.log(req.files.file); console.log(req.files.file);
req.files.file.mv('./database/masterMods/'+req.files.file.name, function(err) { req.files.file.mv('./database/masterMods/'+req.files.file.name, function(err) {
if (err) { if (err) {
res.status(500).send(err); res.status(500).send(err);
} else { } else {
res.send('File uploaded!'); res.send('File uploaded!');
console.log("Uploaded mod: " + req.files.file.name); console.log("Uploaded mod: " + req.files.file.name);
} }
}); httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
});
} }
}); });
// endpoint for getting information about all our slaves // endpoint for getting information about all our slaves
app.get("/api/slaves", function(req, res) { app.get("/api/slaves", function(req, res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
let copyOfSlaves = JSON.parse(JSON.stringify(slaves)); let copyOfSlaves = JSON.parse(JSON.stringify(slaves));
@@ -247,6 +304,7 @@ app.get("/api/slaves", function(req, res) {
copyOfSlaves[key].rconPassword = "hidden"; copyOfSlaves[key].rconPassword = "hidden";
} }
res.send(copyOfSlaves); res.send(copyOfSlaves);
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
}); });
var recievedItemStatisticsBySlaveID = {}; var recievedItemStatisticsBySlaveID = {};
var sentItemStatisticsBySlaveID = {}; var sentItemStatisticsBySlaveID = {};
@@ -268,6 +326,8 @@ POST endpoint for storing items in master's inventory.
@returns {string} status either "success" or "failure" @returns {string} status either "success" or "failure"
*/ */
app.post("/api/place", function(req, res) { app.post("/api/place", function(req, res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
let x; let x;
@@ -318,6 +378,7 @@ app.post("/api/place", function(req, res) {
} else { } else {
res.send("failure"); res.send("failure");
} }
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
}); });
/** /**
POST endpoint to remove items from DB when client orders items. POST endpoint to remove items from DB when client orders items.
@@ -332,6 +393,8 @@ POST endpoint to remove items from DB when client orders items.
*/ */
_doleDivisionFactor = {}; //If the server regularly can't fulfill requests, this number grows until it can. Then it slowly shrinks back down. _doleDivisionFactor = {}; //If the server regularly can't fulfill requests, this number grows until it can. Then it slowly shrinks back down.
app.post("/api/remove", function(req, res) { app.post("/api/remove", function(req, res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
const doleDivisionRetardation = 10; //lower rates will equal more dramatic swings const doleDivisionRetardation = 10; //lower rates will equal more dramatic swings
const maxDoleDivision = 250; //a higher cap will divide the store more ways, but will take longer to recover as supplies increase const maxDoleDivision = 250; //a higher cap will divide the store more ways, but will take longer to recover as supplies increase
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "*");
@@ -382,10 +445,12 @@ app.post("/api/remove", function(req, res) {
sentItemStatisticsBySlaveID[object.instanceID] = sentItemStatistics; sentItemStatisticsBySlaveID[object.instanceID] = sentItemStatistics;
} }
res.send({count: object.count, name: object.name}); res.send({count: object.count, name: object.name});
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
} else { } else {
// if we didn't have enough, attempt giving out a smaller amount next time // if we didn't have enough, attempt giving out a smaller amount next time
_doleDivisionFactor[object.name] = Math.min(maxDoleDivision, Math.max((_doleDivisionFactor[object.name]||0)||1, 1) * 2); _doleDivisionFactor[object.name] = Math.min(maxDoleDivision, Math.max((_doleDivisionFactor[object.name]||0)||1, 1) * 2);
res.send({name:object.name, count:0}); res.send({name:object.name, count:0});
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
//console.log('failure out of ' + object.name + " | " + object.count + " from " + object.instanceID + " ("+object.instanceName+")"); //console.log('failure out of ' + object.name + " | " + object.count + " from " + object.instanceID + " ("+object.instanceName+")");
} }
} }
@@ -403,8 +468,11 @@ Gives no response
@param {number} circuitFrame.time @param {number} circuitFrame.time
*/ */
app.post("/api/setSignal", function(req,res) { app.post("/api/setSignal", function(req,res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
if(typeof req.body == "object" && req.body.time){ if(typeof req.body == "object" && req.body.time){
db.signals.insert(req.body); db.signals.insert(req.body);
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
// console.log("signal set"); // console.log("signal set");
} }
}); });
@@ -417,12 +485,15 @@ POST endpoint to read database of circuit signals sent to master
@returns {object} circuitFrame @returns {object} circuitFrame
*/ */
app.post("/api/readSignal", function(req,res) { app.post("/api/readSignal", function(req,res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
// request.body should be an object // request.body should be an object
// {since:UNIXTIMESTAMP,} // {since:UNIXTIMESTAMP,}
// we should send an array of all signals since then // we should send an array of all signals since then
db.signals.find({time:{$gte: req.body.since}}, function (err, docs) { db.signals.find({time:{$gte: req.body.since}}, function (err, docs) {
// $gte means greater than or equal to, meaning we only get entries newer than the timestamp // $gte means greater than or equal to, meaning we only get entries newer than the timestamp
res.send(docs); res.send(docs);
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
// console.log(docs); // console.log(docs);
}); });
}); });
@@ -436,6 +507,8 @@ GET endpoint to read the masters current inventory of items.
*/ */
// endpoint for getting an inventory of what we got // endpoint for getting an inventory of what we got
app.get("/api/inventory", function(req, res) { app.get("/api/inventory", function(req, res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// Check it and send it // Check it and send it
@@ -446,6 +519,7 @@ app.get("/api/inventory", function(req, res) {
} }
} }
res.send(JSON.stringify(inventory)); res.send(JSON.stringify(inventory));
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
}); });
/** /**
GET endpoint to read the masters inventory as an object with key:value pairs GET endpoint to read the masters inventory as an object with key:value pairs
@@ -456,10 +530,13 @@ GET endpoint to read the masters inventory as an object with key:value pairs
@returns {object} JSON {"iron-plate":100, "copper-plate":5} @returns {object} JSON {"iron-plate":100, "copper-plate":5}
*/ */
app.get("/api/inventoryAsObject", function(req, res) { app.get("/api/inventoryAsObject", function(req, res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// Check it and send it // Check it and send it
res.send(JSON.stringify(db.items)); res.send(JSON.stringify(db.items));
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
}); });
// post flowstats here for production graphs // post flowstats here for production graphs
@@ -476,6 +553,8 @@ course the timeSeries data.
@returns {string} failure @returns {string} failure
*/ */
app.post("/api/logStats", function(req,res) { app.post("/api/logStats", function(req,res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
if(typeof req.body == "object" && req.body.instanceID && req.body.timestamp && req.body.data) { if(typeof req.body == "object" && req.body.instanceID && req.body.timestamp && req.body.data) {
if(Number(req.body.timestamp) != NaN){ if(Number(req.body.timestamp) != NaN){
req.body.timestamp = Number(req.body.timestamp); req.body.timestamp = Number(req.body.timestamp);
@@ -492,6 +571,7 @@ app.post("/api/logStats", function(req,res) {
} else { } else {
res.send("failure"); res.send("failure");
} }
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
}); });
// {instanceID: string, fromTime: Date, toTime, Date} // {instanceID: string, fromTime: Date, toTime, Date}
/** /**
@@ -505,6 +585,8 @@ graphs and other IO statistics.
@returns {object} - with statistics @returns {object} - with statistics
*/ */
app.post("/api/getStats", function(req,res) { app.post("/api/getStats", function(req,res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
if(typeof req.body == "string"){ if(typeof req.body == "string"){
req.body = JSON.parse(req.body); req.body = JSON.parse(req.body);
} }
@@ -563,6 +645,7 @@ app.post("/api/getStats", function(req,res) {
} }
} }
} }
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
}); });
/** /**
@@ -578,6 +661,8 @@ making up about 92% of the response body weight.)
@returns {object[]} timeseries where each entry is a set point in time. @returns {object[]} timeseries where each entry is a set point in time.
*/ */
app.post("/api/getTimelineStats", function(req,res) { app.post("/api/getTimelineStats", function(req,res) {
endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
console.log(req.body); console.log(req.body);
if(typeof req.body == "object" && req.body.instanceID) { if(typeof req.body == "object" && req.body.instanceID) {
// if not specified, get stats for last 24 hours // if not specified, get stats for last 24 hours
@@ -616,6 +701,7 @@ app.post("/api/getTimelineStats", function(req,res) {
}); });
res.send(docs); res.send(docs);
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
}); });
} }
}); });
@@ -628,9 +714,13 @@ GET endpoint. Returns factorio's base locale as a JSON object.
@returns {object{}} 2 deep nested object with base game factorio locale as key:value pairs @returns {object{}} 2 deep nested object with base game factorio locale as key:value pairs
*/ */
app.get("/api/getFactorioLocale", function(req,res){ app.get("/api/getFactorioLocale", function(req,res){
getFactorioLocale.asObject(config.factorioDirectory, "en", (err, factorioLocale) => res.send(factorioLocale)); endpointHitCounter.labels(req.route.path).inc();
let reqStartTime = Date.now();
getFactorioLocale.asObject(config.factorioDirectory, "en", (err, factorioLocale) => {
res.send(factorioLocale);
httpRequestDurationMilliseconds.labels(req.route.path).observe(Date.now()-reqStartTime);
});
}); });
var server = require("http").Server(app); var server = require("http").Server(app);
server.listen(config.masterPort || 8080, function () { server.listen(config.masterPort || 8080, function () {
console.log("Listening on port %s...", server.address().port); console.log("Listening on port %s...", server.address().port);
@@ -673,53 +763,100 @@ class mapRequester {
this.lastBeat = Date.now(); this.lastBeat = Date.now();
this.socket.on("heartbeat", () => { this.socket.on("heartbeat", () => {
prometheusWsUsageCounter.labels('heartbeat').inc();
// we aren't ready to die yet apparently // we aren't ready to die yet apparently
this.lastBeat = Date.now(); this.lastBeat = Date.now();
}); });
this.socket.on("requestChunk", loc => { this.socket.on("requestChunk", loc => {
prometheusWsUsageCounter.labels('requestChunk').inc();
loc.requesterID = this.requesterID; loc.requesterID = this.requesterID;
let instanceID = loc.instanceID || this.instanceID; let instanceID = loc.instanceID || this.instanceID;
if(slaveMappers[instanceID] && typeof loc.x == "number" && typeof loc.y == "number"){ if(slaveMappers[instanceID] && typeof loc.x == "number" && typeof loc.y == "number"){
slaveMappers[instanceID].socket.emit("getChunk", loc) slaveMappers[instanceID].socket.emit("getChunk", loc);
} }
}); });
this.socket.on("requestEntity", req => { this.socket.on("requestEntity", req => {
prometheusWsUsageCounter.labels('requestEntity').inc();
req.requesterID = this.requesterID; req.requesterID = this.requesterID;
let instanceID = req.instanceID || this.instanceID; let instanceID = req.instanceID || this.instanceID;
if(slaveMappers[instanceID] && typeof req.x == "number" && typeof req.y == "number"){ if(slaveMappers[instanceID] && typeof req.x == "number" && typeof req.y == "number"){
slaveMappers[instanceID].socket.emit("getEntity", req) slaveMappers[instanceID].socket.emit("getEntity", req);
}
});
this.socket.on("placeEntity", req => {
prometheusWsUsageCounter.labels('placeEntity').inc();
req.requesterID = this.requesterID;
let instanceID = req.instanceID || this.instanceID;
if(slaveMappers[instanceID]){
slaveMappers[instanceID].socket.emit("placeEntity", req);
}
});
}
}
/* Websockets for send and recieve combinators */
var wsSlaves = {};
class wsSlave {
constructor(instanceID, socket){
this.instanceID = instanceID;
this.socket = socket;
this.lastBeat = Date.now();
this.socket.on("heartbeat", () => {
prometheusWsUsageCounter.labels('heartbeat').inc();
this.lastBeat = Date.now();
});
this.socket.on("combinatorSignal", circuitFrameWithMeta => {
prometheusWsUsageCounter.labels('combinatorSignal').inc();
if(circuitFrameWithMeta && typeof circuitFrameWithMeta == "object"){
Object.keys(wsSlaves).forEach(instanceID => {
wsSlaves[instanceID].socket.emit("processCombinatorSignal", circuitFrameWithMeta);
});
} }
}); });
} }
} }
io.on('connection', function (socket) { io.on('connection', function (socket) {
// cleanup dead sockets from disconnected people // cleanup dead sockets from disconnected people
Object.keys(mapRequesters).forEach(requesterName => { let terminatedConnections = 0;
let requester = mapRequesters[requesterName]; let currentConnections = Object.keys(mapRequesters).length + Object.keys(slaveMappers).length + Object.keys(wsSlaves).length;
if(requester.lastBeat < (Date.now() - 30000)){ [mapRequesters, slaveMappers, wsSlaves].forEach(list => {
console.log("remoteMap | There are currently "+Object.keys(mapRequesters).length+" map requesters, deleting one on timeout"); Object.keys(list).forEach(connectionID => {
delete mapRequesters[requesterName]; // we have to use the full name here or we will only kill the pointer let connection = list[connectionID];
} if(connection.lastBeat < (Date.now() - 30000)){
}); terminatedConnections++;
Object.keys(slaveMappers).forEach(mapperName => { delete list[connectionID];
let mapper = slaveMappers[mapperName]; }
if(mapper.lastBeat < (Date.now() - 30000)){ });
console.log("remoteMap | There are currently "+Object.keys(slaveMappers).length+" mappers, deleting one on timeout");
delete slaveMappers[mapperName]; // we have to use the full name here or we will only kill the pointer
}
}); });
if(terminatedConnections > 0) console.log("SOCKET | There are currently "+currentConnections+" websocket connections, deleting "+terminatedConnections+" on timeout");
// tell our friend that we are listening
socket.emit('hello', { hello: 'world' }); socket.emit('hello', { hello: 'world' });
/* initial processing for remoteMap */
socket.on('registerSlaveMapper', function (data) { socket.on('registerSlaveMapper', function (data) {
prometheusWsUsageCounter.labels('registerSlaveMapper').inc();
slaveMappers[data.instanceID] = new slaveMapper(data.instanceID, socket); slaveMappers[data.instanceID] = new slaveMapper(data.instanceID, socket);
console.log("remoteMap | SOCKET registered map provider for "+data.instanceID); console.log("remoteMap | SOCKET registered map provider for "+data.instanceID);
}); });
socket.on('registerMapRequester', function(data){ socket.on('registerMapRequester', function(data){
// data {instanceID:""} // data {instanceID:""}
prometheusWsUsageCounter.labels('registerMapRequester').inc();
let requesterID = Math.random().toString(); let requesterID = Math.random().toString();
mapRequesters[requesterID] = new mapRequester(requesterID, socket, data.instanceID); mapRequesters[requesterID] = new mapRequester(requesterID, socket, data.instanceID);
socket.emit("mapRequesterReady", true); socket.emit("mapRequesterReady", true);
console.log("remoteMap | SOCKET registered map requester for "+data.instanceID); console.log("remoteMap | SOCKET registered map requester for "+data.instanceID);
}); });
/* Websockets for send and recieve combinators */
socket.on("registerSlave", function(data) {
prometheusWsUsageCounter.labels('registerSlave').inc();
if(data && data.instanceID){
wsSlaves[data.instanceID] = new wsSlave(data.instanceID, socket);
console.log("SOCKET | Created new wsSlave: "+ data.instanceID);
}
});
}); });
module.exports = app; module.exports = app;
+3 -1
View File
@@ -35,6 +35,7 @@ describe('Master server endpoint testing', function() {
}); });
// describe("#GET /api/") // describe("#GET /api/")
parallel("#GET static website data", function() { parallel("#GET static website data", function() {
this.timeout(6000);
it("sends some HTML when accessing /", function(done){ it("sends some HTML when accessing /", function(done){
this.timeout(6000); this.timeout(6000);
request(app).get("/").end(function(err,res){ request(app).get("/").end(function(err,res){
@@ -80,7 +81,8 @@ describe('Master server endpoint testing', function() {
request(app).get("/remoteMap").end(function(err,res){ request(app).get("/remoteMap").end(function(err,res){
assert.equal(res.statusCode, 200); assert.equal(res.statusCode, 200);
validateHTML(res.text).then(result => { validateHTML(res.text).then(result => {
assert(result.messages.length === 0, "there are HTML errors on the page, please fix: "+JSON.stringify(result.messages)); // there should be 1 error regarding complaining about me using ES6 modules before they are fully supported
assert(result.messages.length === 1, "there are HTML errors on the page, please fix: "+JSON.stringify(result.messages));
done(); done();
}); });
}); });
+168
View File
@@ -0,0 +1,168 @@
/**
class factorioServer
This class has the responsiblity of :
* spawning a factorio server
* Handling input via stdin or RCON
*/
const fs = require("fs");
const child_process = require("child_process");
const path = require("path");
const mkdirp = require("mkdirp");
const appRootPath = require("app-root-path");
const fileOps = require("_app/fileOps");
module.exports = class factorioServer {
constructor({
factorioDirectory = "factorio",
instanceDirectory = "instances/data",
instanceName = "Default server name",
factorioPort = Math.floor(Math.random() * 65535),
serversettings = {},
onProgress = function(type, a, b, c){
if(type == "progress") console.log("Progress: ",a," of ",b," unit: ",c);
if(type == "log") console.log(a);
},
} = {}){
this.factorioDirectory = factorioDirectory;
this.instanceDirectory = instanceDirectory;
this.instanceName = instanceName;
this.factorioPort = factorioPort;
this.serversettings = Object.assign({
"name": "Clusterio instance: " + this.instanceName,
"description": "Public factorio server running clusterio",
"tags": ["clusterio"],
"max_players": "20",
"visibility": "public",
"username": "",
"token": "",
"game_password": "",
"verify_user_identity": true,
"admins": ["Danielv123"],
"allow_commands": true,
"autosave_interval": 10,
"autosave_slots": 5,
"afk_autokick_interval": 0,
"auto_pause": false,
}, serversettings);
this.onProgress = (type, a, b, c) => {
if(typeof onProgress == "function") onProgress(type, a, b, c);
};
}
async initialize(){
if(!await this.isValidInstance()){
await this.createInstance();
}
return true;
}
async createInstance(path = this.instanceDirectory){
if(await this.isValidInstance(path)){
throw new Error("Instance already exists!");
}
// create folders
let folders = [
"/script-output/",
"/saves/",
"/mods/",
"/instanceMods/",
];
mkdirp.sync(path);
folders.forEach(folder => mkdirp.sync(path + folder));
// create files
let files = [
{name: "/script-output/output.txt", content: ""},
{name: "/script-output/orders.txt", content: ""},
{name: "/script-output/txbuffer.txt", content: ""},
{name: "/config.ini", content: "[path]\r\n\ read-data=__PATH__executable__/../../data\r\n\ write-data=__PATH__executable__/../../../" + this.instanceDirectory + "\r\n\ "},
{name: "/config.json", content: JSON.stringify({
factorioPort: this.factorioPort,
clientPassword: Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8),
}, null, 4)},
{name: "/server-settings.json", content: JSON.stringify(this.serversettings, null, 4)},
];
files.forEach(file => {
fs.writeFile(path + file.name, file.content, doneWritingHandler);
// console.log("Created: ",path+file.name);
});
let filesToWrite = files.length;
function doneWritingHandler(){
if(!--filesToWrite){
return path;
}
}
}
async deleteInstance(path = this.instanceDirectory){
if(await this.isValidInstance(path)){
await fileOps.deleteFolderRecursive(path);
return true;
} else {
return false;
}
}
isValidInstance(path = this.instanceDirectory){
return new Promise((resolve, reject) => {
fs.stat(path, (err, stat) => {
if(err){
// console.log(err)
resolve(false);
} else {
// the instance folder exists, do some more checks
fs.readdir(path, (err, files) => {
if(files && Array.isArray(files)){
let foldersThatShouldBeThere = [
"script-output",
"saves",
"mods",
"instanceMods",
];
let instanceValidity = true;
foldersThatShouldBeThere.forEach(folder => {
if(!files.includes(folder)){
instanceValidity = false;
}
});
resolve(instanceValidity);
}
});
}
});
});
}
createMap(name = "map.zip"){
return new Promise((resolve, reject) => {
this.isValidInstance().then(isValid => {
if(!isValid){
return createInstance();
}
}).then(()=>{
this.onProgress("log", "Starting map creation");
// console.log(this.factorioDirectory + '/bin/x64/factorio')
let proc = child_process.spawn(
path.join(this.factorioDirectory, 'bin', 'x64', 'factorio'), [
'-c', path.join(this.instanceDirectory,'config.ini'),
'--create', path.join(this.instanceDirectory, 'saves',name),
'--server-settings', path.join(this.instanceDirectory, 'server-settings.json'),
],{
cwd:process.cwd(),
}
);
// console.log(proc.stdout.toString("utf8"));
proc.stdout.on("data", data => this.onProgress("log", data.toString("utf8")));
proc.on("close", code => {
this.onProgress("log", "Map created! "+code);
resolve();
});
});
});
}
}
+114
View File
@@ -0,0 +1,114 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const appRootPath = require("app-root-path");
const parallel = require("mocha.parallel");
const mkdirp = require("mkdirp");
const factorioServer = require("./index.js");
describe("class factorioServer/index.js", ()=>{
it("is a class (or at least a function)", ()=>{
assert.equal(typeof factorioServer, "function");
});
describe(".deleteInstance(instanceName)", ()=>{
it("deletes an instance, defaulting to the classes instanceDirectory", async () => {
let server = new factorioServer({
instanceDirectory: path.resolve(__dirname, "_testData_deleteInstance"),
instanceName: "Unit testing instance",
});
await server.initialize();
await server.deleteInstance();
assert.equal(await server.isValidInstance(), false);
return true;
});
});
describe(".isValidInstance(instanceName)", ()=>{
it("tells us whether an instance exists or not", async () => {
let server = new factorioServer({
instanceDirectory: path.join(__dirname, "_testData_isValidInstance"),
instanceName: "Unit testing instance",
});
await server.deleteInstance();
let status = await server.isValidInstance();
assert.equal(status, false);
let x = await server.initialize(); // creates our instance
let status2 = await server.isValidInstance();
assert.equal(status2, true);
await server.deleteInstance(); // clean up folder
return true;
});
it("does not get tricked by an empty folder", async () => {
let server = new factorioServer({
instanceDirectory: path.join(__dirname, "_testData_isValidInstance_2"),
instanceName: "Unit testing instance",
});
assert.equal(await server.isValidInstance(), false);
mkdirp.sync(path.join(__dirname, "_testData_isValidInstance_2")); // create empty folder simulating instance
assert.equal(await server.isValidInstance(), false);
await server.initialize(); // create a proper instance
assert.equal(await server.isValidInstance(), true);
await server.deleteInstance(); // delete the instance and ensure we see that it is in fact deleted
assert.equal(await server.isValidInstance(), false);
return true;
}).timeout(5000);
});
describe(".initialize()", ()=>{
it("creates an instance", done => {
let server = new factorioServer({
instanceDirectory: path.resolve(__dirname, "_testData_initialize"),
instanceName: "Unit testing instance",
});
server.initialize().then(()=>{
return server.deleteInstance();
}).then(() => {
done();
}).catch(e => console.log(e));
});
});
describe(".createMap(mapName.zip)", ()=>{
it("creates a map file as instanceDirectory/saves/map.zip", async function(){
this.timeout(20000); // these test often takes a lot of time in the map creation step (4500 ms on i3 dev system)
let relativePath = __dirname.replace(appRootPath, "").substr(1);
let server = new factorioServer({
instanceDirectory: path.join(relativePath, "_testData_createMap"),
instanceName: "Unit testing instance",
onProgress: false,
});
await server.initialize();
let maps = fs.readdirSync(path.join(relativePath, "_testData_createMap", "saves"));
assert.equal(maps.length, 0);
await server.createMap();
let maps2 = fs.readdirSync(path.join(relativePath, "_testData_createMap", "saves"));
assert(maps2.includes("map.zip"));
await server.deleteInstance();
return true;
});
it("supports custom filenames", async function(){
this.timeout(20000);
let relativePath = __dirname.replace(appRootPath, "").substr(1);
let server = new factorioServer({
instanceDirectory: path.join(relativePath, "_testData_createMap_2"),
instanceName: "Unit testing instance",
onProgress: false,
});
await server.initialize();
let maps = fs.readdirSync(path.join(relativePath, "_testData_createMap_2", "saves"));
assert.equal(maps.length, 0);
await server.createMap("mapWithCustomName.zip");
let maps2 = fs.readdirSync(path.join(relativePath, "_testData_createMap_2", "saves"));
assert(maps2.includes("mapWithCustomName.zip"));
await server.deleteInstance();
return true;
});
});
});
+47 -6
View File
@@ -1,5 +1,5 @@
var fs = require("fs"); const fs = require("fs");
var path = require("path"); const path = require("path");
// gets newest file in a directory // gets newest file in a directory
// dir is directory // dir is directory
@@ -70,10 +70,51 @@ var deleteFolderRecursiveSync = function(path) {
return false; return false;
} }
}; };
var deleteFolderRecursive = function(path){
return new Promise((resolve, reject) => {
fs.readdir(path, (err, files) => {
if(err){
reject(err);
} else {
let thingsToDelete = files.length;
files.forEach(file => {
let curPath = path + "/" + file;
fs.stat(curPath, (err, stat) => {
if(!err){
if(stat.isDirectory()){
// recurse
deleteFolderRecursive(curPath).then(() => {
whenFilesDeleted();
}).catch(e => console.log(e));
} else {
fs.unlink(curPath, () => {
// console.log("Deleted "+curPath);
whenFilesDeleted();
});
}
} else {
resolve(false);
}
});
});
whenFilesDeleted();
function whenFilesDeleted(){
if(!thingsToDelete--){// var-- instead of --var because we are calling the function once too much and need the delay
fs.rmdir(path, () => {
resolve();
// console.log("Deleted "+path);
});
}
}
}
});
});
}
module.exports = { module.exports = {
getNewestFile:getNewestFile, getNewestFile,
getDirectoriesSync:getDirectoriesSync, getDirectoriesSync,
deleteFolderRecursiveSync:deleteFolderRecursiveSync, deleteFolderRecursiveSync,
getFileNamesSync:getFileNamesSync, deleteFolderRecursive,
getFileNamesSync,
} }
+48 -26
View File
@@ -1,30 +1,32 @@
var assert = require('assert'); const assert = require('assert');
var fileOps = require('./fileOps'); const fs = require('fs');
var fs = require('fs'); const path = require('path');
const fileOps = require('./fileOps');
// create folders for testing // create folders for testing
function setupTestingEnv(){ function setupTestingEnv(){
if (!fs.existsSync("database")){ if (!fs.existsSync(path.resolve(__dirname, "database"))){
fs.mkdirSync("database"); fs.mkdirSync(path.resolve(__dirname, "database"));
} }
if (!fs.existsSync("lib/test")){ if (!fs.existsSync(path.resolve(__dirname, "test"))){
fs.mkdirSync("lib/test"); fs.mkdirSync(path.resolve(__dirname, "test"));
} }
if (!fs.existsSync("lib/test/folder")){ if (!fs.existsSync(path.resolve(__dirname, "test/folder"))){
fs.mkdirSync("lib/test/folder"); fs.mkdirSync(path.resolve(__dirname, "test/folder"));
} }
if (!fs.existsSync("lib/test/another folder")){ if (!fs.existsSync(path.resolve(__dirname, "test/another folder"))){
fs.mkdirSync("lib/test/another folder"); fs.mkdirSync(path.resolve(__dirname, "test/another folder"));
} }
if (!fs.existsSync("lib/test/file.txt")){ if (!fs.existsSync(path.resolve(__dirname, "test/file.txt"))){
fs.writeFileSync("lib/test/file.txt", "contents"); fs.writeFileSync(path.resolve(__dirname, "test/file.txt"), "contents");
} }
if (!fs.existsSync("lib/test/another file.txt")){ if (!fs.existsSync(path.resolve(__dirname, "test/another file.txt"))){
fs.writeFileSync("lib/test/another file.txt", "more contents"); fs.writeFileSync(path.resolve(__dirname, "test/another file.txt"), "more contents");
} }
// we need this xfile to test a branch in fileOps.getNewestFile()s propagation // we need this xfile to test a branch in fileOps.getNewestFile()s propagation
if (!fs.existsSync("lib/test/xfile.txt")){ if (!fs.existsSync(path.resolve(__dirname, "test/xfile.txt"))){
fs.writeFileSync("lib/test/xfile.txt", "contents"); fs.writeFileSync(path.resolve(__dirname, "test/xfile.txt"), "contents");
} }
} }
setupTestingEnv(); setupTestingEnv();
@@ -32,7 +34,7 @@ setupTestingEnv(); // run twice to get branch coverage
describe("fileOps.js", function(){ describe("fileOps.js", function(){
describe("fileOps.getDirectoriesSync()", function(){ describe("fileOps.getDirectoriesSync()", function(){
it("gets an array of directory names from a path", function(){ it("gets an array of directory names from a path", function(){
let directories = fileOps.getDirectoriesSync("lib/test"); let directories = fileOps.getDirectoriesSync(path.resolve(__dirname, "test"));
// because there are no arrays for some reason // because there are no arrays for some reason
assert(typeof directories == "object"); assert(typeof directories == "object");
@@ -41,7 +43,7 @@ describe("fileOps.js", function(){
assert(directories[0] == "another folder" && directories[1] == "folder"); assert(directories[0] == "another folder" && directories[1] == "folder");
}); });
it("does not return any filenames", function(){ it("does not return any filenames", function(){
let directories = fileOps.getDirectoriesSync("lib/test"); let directories = fileOps.getDirectoriesSync(path.resolve(__dirname, "test"));
// this is a function to return directories, not files. So yeah. // this is a function to return directories, not files. So yeah.
assert(!directories.includes("file.txt") && !directories.includes("another file.txt")); assert(!directories.includes("file.txt") && !directories.includes("another file.txt"));
@@ -54,7 +56,7 @@ describe("fileOps.js", function(){
}); });
describe("fileOps.getFileNamesSync(path)", function(){ describe("fileOps.getFileNamesSync(path)", function(){
it("gets names of files in directory", function(){ it("gets names of files in directory", function(){
let files = fileOps.getFileNamesSync("lib/test"); let files = fileOps.getFileNamesSync(path.resolve(__dirname, "test"));
assert(files.length > 0); assert(files.length > 0);
assert(files.includes("file.txt") && files.includes("another file.txt")); assert(files.includes("file.txt") && files.includes("another file.txt"));
}); });
@@ -66,24 +68,24 @@ describe("fileOps.js", function(){
}); });
describe("fileOps.getNewestFile()", function(){ describe("fileOps.getNewestFile()", function(){
it("gets the newest file in a directory async", function(done){ it("gets the newest file in a directory async", function(done){
fileOps.getNewestFile("lib/test/", fileOps.getFileNamesSync("lib/test"), function(err, newest){ fileOps.getNewestFile(path.resolve(__dirname, "test/"), fileOps.getFileNamesSync(path.resolve(__dirname, "test")), function(err, newest){
assert(newest && typeof newest.file == "string"); assert(newest && typeof newest.file == "string");
done(); done();
}); });
}); });
it("throws if callback is missing", function(){ it("throws if callback is missing", function(){
assert.throws(function(){ assert.throws(function(){
fileOps.getNewestFile("lib/test", fileOps.getFileNamesSync("lib/test")); fileOps.getNewestFile("test", fileOps.getFileNamesSync(path.resolve(__dirname, "test")));
}, Error); }, Error);
}); });
it("executes callback(err) if no files are provided", function(done){ it("executes callback(err) if no files are provided", function(done){
fileOps.getNewestFile("lib/test", [], function(err, newest){ fileOps.getNewestFile(path.resolve(__dirname, "test"), [], function(err, newest){
assert(err && typeof err == "object"); assert(err && typeof err == "object");
done(); done();
}); });
}); });
it("executes callback(err) if launched without a directory", function(done){ it("executes callback(err) if launched without a directory", function(done){
fileOps.getNewestFile("", fileOps.getFileNamesSync("lib/test"), function(err, newest){ fileOps.getNewestFile("", fileOps.getFileNamesSync(path.resolve(__dirname, "test")), function(err, newest){
assert(err); assert(err);
done(); done();
}); });
@@ -98,9 +100,9 @@ describe("fileOps.js", function(){
}); });
describe("fileOps.deleteFolderRecursiveSync(path)", function(){ describe("fileOps.deleteFolderRecursiveSync(path)", function(){
it("deletes a folder and all files and folders in it", function(){ it("deletes a folder and all files and folders in it", function(){
let x = fileOps.deleteFolderRecursiveSync("lib/test"); let x = fileOps.deleteFolderRecursiveSync(path.resolve(__dirname, "test"));
assert.throws(function(){ assert.throws(function(){
fs.statSync("lib/test"); fs.statSync(path.resolve(__dirname, "test"));
}, Error); }, Error);
assert(x); assert(x);
// give it some extra time because its sometimes very slow // give it some extra time because its sometimes very slow
@@ -110,4 +112,24 @@ describe("fileOps.js", function(){
assert(!x); assert(!x);
}); });
}); });
describe("fileOps.deleteFolderRecursive(path)", function(){
it("deletes a folder and all files and folders in it, just like sync version", async function(){
setupTestingEnv();
assert(fs.statSync(path.resolve(__dirname, "test")));
let x = await fileOps.deleteFolderRecursive(path.resolve(__dirname, "test"));
assert.throws(function(){
fs.statSync(path.resolve(__dirname, "test"));
}, Error);
assert(x === undefined, "Promise version of this function does not have a return value upon success");
return true;
}).timeout(5000);
it("throws like a promise does if you give it an invalid path", async function(){
let x = await fileOps.deleteFolderRecursive("Look this path is fake!")
.catch(e => {
assert(e);
assert.equal(e.code, "ENOENT");
return true;
});
});
});
}); });
+2
View File
@@ -0,0 +1,2 @@
const fileOps = require("./fileOps");
module.exports = fileOps;
+16 -12
View File
@@ -5,9 +5,9 @@
"repository": "https://github.com/Danielv123/factorioClusterio", "repository": "https://github.com/Danielv123/factorioClusterio",
"main": "master.js", "main": "master.js",
"scripts": { "scripts": {
"test": "./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha -- \"./{,!(node_modules)/**/}*.spec.js\" -R spec || echo .", "test": "./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha -- \"./{{,node_modules/_app/**/},!(node_modules)/**/}*.spec.js\" -R spec || echo .",
"start": "echo Run node client.js start [instance] to start slaves && node master.js", "start": "echo Run node client.js start [instance] to start slaves && node master.js",
"cover": "./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha -- \"./{,!(node_modules)/**/}*.spec.js\" -R spec || echo . && codecov -t f7b38085-36eb-4d72-84e6-64721910171e", "cover": "./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha -- \"./{{,node_modules/_app/**/},!(node_modules)/**/}*.spec.js\" -R spec || echo . && codecov -t f7b38085-36eb-4d72-84e6-64721910171e",
"docs": "documentation build index.js --config documentation.yml -f html -o docs", "docs": "documentation build index.js --config documentation.yml -f html -o docs",
"livedocs": "documentation serve --watch *.js lib/** --config documentation.yml", "livedocs": "documentation serve --watch *.js lib/** --config documentation.yml",
"install": "node lib/npmPostinstall.js" "install": "node lib/npmPostinstall.js"
@@ -18,6 +18,7 @@
"author": "Danielv123", "author": "Danielv123",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"app-root-path": "^2.0.1",
"as-table": "^1.0.31", "as-table": "^1.0.31",
"averaged-timeseries": "^1.4.0", "averaged-timeseries": "^1.4.0",
"body-parser": "^1.18.2", "body-parser": "^1.18.2",
@@ -26,39 +27,42 @@
"ejs": "^2.5.7", "ejs": "^2.5.7",
"express": "^4.16.2", "express": "^4.16.2",
"express-fileupload": "0.0.6", "express-fileupload": "0.0.6",
"follow-redirects": "^1.2.5", "follow-redirects": "^1.4.1",
"fs-extra": "^1.0.0", "fs-extra": "^1.0.0",
"getmac": "^1.2.1", "getmac": "^1.4.0",
"hash-files": "^1.1.1", "hash-files": "^1.1.1",
"html5-validator": "^1.0.6", "html5-validator": "^1.0.7",
"ini": "^1.3.4", "ini": "^1.3.5",
"leveldown": "^1.9.0", "leveldown": "^1.9.0",
"linvodb3": "^3.25.0", "linvodb3": "^3.25.1",
"luamin": "^1.0.4", "luamin": "^1.0.4",
"mkdirp": "^0.5.1", "mkdirp": "^0.5.1",
"mkdirp-promise": "^5.0.1", "mkdirp-promise": "^5.0.1",
"moment": "^2.19.1", "moment": "^2.20.1",
"ncp": "^2.0.0", "ncp": "^2.0.0",
"nedb": "^1.8.0", "nedb": "^1.8.0",
"needle": "^1.1.0", "needle": "^1.1.0",
"node-factorio-api": "^0.1.28", "node-factorio-api": "^0.3.1-alpha",
"node-forge": "^0.7.1",
"prom-client": "^10.2.3",
"node-lua": "^1.0.4", "node-lua": "^1.0.4",
"request": "^2.83.0", "request": "^2.83.0",
"right-pad": "^1.0.1", "right-pad": "^1.0.1",
"rmdir-sync": "^1.0.1", "rmdir-sync": "^1.0.1",
"simple-rcon": "^0.3.1", "simple-rcon": "^0.3.1",
"single-line-log": "^1.1.2",
"socket.io": "^2.0.4", "socket.io": "^2.0.4",
"socket.io-client": "^2.0.4", "socket.io-client": "^2.0.4",
"sync-request": "^4.0.1", "sync-request": "^4.0.1",
"underscore": "^1.8.3" "underscore": "^1.8.3"
}, },
"devDependencies": { "devDependencies": {
"documentation": "^5.3.3", "documentation": "^5.4.0",
"istanbul": "^0.4.5", "istanbul": "^0.4.5",
"mocha": "^3.5.3", "mocha": "^3.5.3",
"mocha-sinon": "^2.0.0", "mocha-sinon": "^2.0.0",
"mocha.parallel": "^0.15.3", "mocha.parallel": "^0.15.5",
"nock": "^9.0.27", "nock": "^9.1.6",
"sinon": "^2.4.1", "sinon": "^2.4.1",
"supertest": "^3.0.0" "supertest": "^3.0.0"
} }
+1 -1
View File
@@ -12,7 +12,7 @@ describe("remoteMap/chunkStore.js", () => {
it("is a constructor", ()=>{ it("is a constructor", ()=>{
assert.equal(typeof chunkStore, "function"); assert.equal(typeof chunkStore, "function");
// create a new store and elevate it // create a new store and elevate it
store = new chunkStore("910239"/* instanceID, use defaults for the rest */); store = new chunkStore("910239"/* instanceID, use defaults for the rest */, undefined, "./database/unitTests/chunkStore/");
assert.equal(store.name, "910239"); assert.equal(store.name, "910239");
}); });
it("allows you to store the locations of entities", done => { it("allows you to store the locations of entities", done => {
+55 -16
View File
@@ -22,22 +22,33 @@
-- DEALINGS IN THE SOFTWARE. -- DEALINGS IN THE SOFTWARE.
function write_file(data) function write_file(data)
if must_write_initstuff then stringsToWriteNextTick = stringsToWriteNextTick .. data .. '\n'
must_write_initstuff = false -- game.write_file("remoteMap.txt", data, true)
writeout_initial_stuff()
end
game.write_file("remoteMap.txt", data, true)
end end
function dump_cached_writes()
game.write_file("remoteMap.txt", stringsToWriteNextTick, true)
end
function complain(text) function complain(text)
print(text) if false then -- only print during development
game.forces["player"].print(text) print(text)
game.forces["player"].print(text)
end
end end
local todo_next_tick = {} local todo_next_tick = {}
must_write_initstuff = true
function on_tick(event) function on_tick(event)
dump_cached_writes()
stringsToWriteNextTick = ''
if must_write_initstuff then
must_write_initstuff = false
log("I must write init stuff!")
writeout_initial_stuff()
end
if #todo_next_tick > 0 then if #todo_next_tick > 0 then
print("on_tick executing "..#todo_next_tick.." stored callbacks") complain("on_tick executing "..#todo_next_tick.." stored callbacks")
for _,func in ipairs(todo_next_tick) do for _,func in ipairs(todo_next_tick) do
func() func()
end end
@@ -45,26 +56,50 @@ function on_tick(event)
end end
end end
function writeout_initial_stuff()
log("Writing out initial stuff...")
writeout_objects(game.surfaces['nauvis'], {left_top={x=-64,y=-64},right_bottom={x=64,y=64}})
end
function writeout_objects(surface, area) function writeout_objects(surface, area)
--if my_client_id ~= 1 then return end --if my_client_id ~= 1 then return end
header = "objects "..area.left_top.x..","..area.left_top.y..";"..area.right_bottom.x..","..area.right_bottom.y..": "
line = ''
for idx, ent in pairs(surface.find_entities(area)) do for idx, ent in pairs(surface.find_entities(area)) do
if area.left_top.x <= ent.position.x and ent.position.x < area.right_bottom.x and area.left_top.y <= ent.position.y and ent.position.y < area.right_bottom.y then if area.left_top.x <= ent.position.x and ent.position.x < area.right_bottom.x and area.left_top.y <= ent.position.y and ent.position.y < area.right_bottom.y then
if ent.prototype.collision_mask ~= nil and ent.prototype.collision_mask['player-layer'] then if ent.prototype.collision_mask ~= nil and ent.prototype.collision_mask['player-layer'] then
line = line .. ent.name.." "..ent.position.x.." "..ent.position.y.."\n" -- line = line .. ent.name.." "..ent.position.x.." "..ent.position.y.."\n"
-- local line = ent.name..","..ent.position.x..","..ent.position.y
-- if ent.supports_direction then
-- line = line .. ",rot="..ent.direction
-- end
-- write_file(line)
on_some_entity_created(nil, ent)
end end
end end
end end
write_file(line)
--write_file(header..table.concat(lines,"").."\n") --write_file(header..table.concat(lines,"").."\n")
--write_file(table.concat(lines,"").."\n") --write_file(table.concat(lines,"").."\n")
line=nil
end end
function on_chunk_generated(event)
local area = event.area
local surface = event.surface
--print("chunk generated at ("..area.left_top.x..","..area.left_top.y..") -- ("..area.right_bottom.x..","..area.right_bottom.y..")")
function on_some_entity_created(event) if surface ~= game.surfaces['nauvis'] then -- we only support one surface
local ent = event.entity or event.created_entity or nil return
end
-- writeout_resources(surface, area)
writeout_objects(surface, area)
-- writeout_tiles(surface, area)
end
function on_some_entity_created(event, entp)
local ent
if entp then
ent = entp
else
ent = event.entity or event.created_entity or nil
end
if ent == nil then if ent == nil then
complain("wtf, on_some_entity_created has nil entity") complain("wtf, on_some_entity_created has nil entity")
return return
@@ -73,6 +108,7 @@ function on_some_entity_created(event)
if ent.supports_direction then if ent.supports_direction then
entityData = entityData .. ",rot="..ent.direction entityData = entityData .. ",rot="..ent.direction
end end
-- log(entityData)
write_file(entityData) write_file(entityData)
--writeout_objects(ent.surface, {left_top={x=math.floor(ent.position.x), y=math.floor(ent.position.y)}, right_bottom={x=math.floor(ent.position.x)+1, y=math.floor(ent.position.y)+1}}) --writeout_objects(ent.surface, {left_top={x=math.floor(ent.position.x), y=math.floor(ent.position.y)}, right_bottom={x=math.floor(ent.position.x)+1, y=math.floor(ent.position.y)+1}})
--complain("on_some_entity_created: "..ent.name.." at "..ent.position.x..","..ent.position.y) --complain("on_some_entity_created: "..ent.name.." at "..ent.position.x..","..ent.position.y)
@@ -95,12 +131,15 @@ function on_some_entity_deleted(event)
end end
script.on_event(defines.events.on_tick, on_tick) script.on_event(defines.events.on_tick, on_tick)
script.on_event(defines.events.on_chunk_generated, on_chunk_generated)
script.on_event(defines.events.on_biter_base_built, on_some_entity_created) --entity script.on_event(defines.events.on_biter_base_built, on_some_entity_created) --entity
script.on_event(defines.events.on_built_entity, on_some_entity_created) --created_entity script.on_event(defines.events.on_built_entity, on_some_entity_created) --created_entity
script.on_event(defines.events.on_robot_built_entity, on_some_entity_created) --created_entity script.on_event(defines.events.on_robot_built_entity, on_some_entity_created) --created_entity
script.on_event(defines.events.on_player_rotated_entity, on_some_entity_created) --created_entity
script.on_event(defines.events.on_entity_died, on_some_entity_deleted) --entity script.on_event(defines.events.on_entity_died, on_some_entity_deleted) --entity
script.on_event(defines.events.on_player_mined_entity, on_some_entity_deleted) --entity script.on_event(defines.events.on_player_mined_entity, on_some_entity_deleted) --entity
script.on_event(defines.events.on_robot_mined_entity, on_some_entity_deleted) --entity script.on_event(defines.events.on_robot_mined_entity, on_some_entity_deleted) --entity
script.on_event(defines.events.on_resource_depleted, on_some_entity_deleted) --entity script.on_event(defines.events.on_resource_depleted, on_some_entity_deleted) --entity
@@ -0,0 +1,5 @@
/c
local toDelete = game.surfaces[1].find_entities({{3,7},{4,8}})
for i, entity in pairs(toDelete) do
entity.die()
end
+46 -10
View File
@@ -13,8 +13,8 @@ class remoteMap {
// initialize chunk database // initialize chunk database
this.chunkMap = new chunkStore(this.config.unique, 64, "./database/chunkStore/"); this.chunkMap = new chunkStore(this.config.unique, 64, "./database/chunkStore/");
this.chunkMap.onEntityChange(entity => { this.chunkMap.onEntityChange(entity => {
console.log("Entity changed: ") // this.messageInterface("Entity changed: ")
console.log(entity); // this.messageInterface(entity);
// check valid coordinates (dunno what could go wrong, but can never be too sure) // check valid coordinates (dunno what could go wrong, but can never be too sure)
if(entity && entity.x !== undefined && !isNaN(Number(entity.x)) && entity.y !== undefined && !isNaN(Number(entity.y))){ if(entity && entity.x !== undefined && !isNaN(Number(entity.x)) && entity.y !== undefined && !isNaN(Number(entity.y))){
this.socket.emit("sendEntity", entity); this.socket.emit("sendEntity", entity);
@@ -31,7 +31,7 @@ class remoteMap {
},10000); },10000);
}); });
this.socket.on("getChunk", req => { this.socket.on("getChunk", req => {
console.log("getChunk is not supported!"); this.messageInterface("getChunk is not supported!");
/*this.chunkMap.getChunk(req.x, req.y).then(chunk => { /*this.chunkMap.getChunk(req.x, req.y).then(chunk => {
chunk.requesterID = req.requesterID; chunk.requesterID = req.requesterID;
this.socket.emit("sendChunk", chunk); this.socket.emit("sendChunk", chunk);
@@ -51,17 +51,54 @@ class remoteMap {
this.messageInterface("socket.getEntity triggered called with invalid parameters"); this.messageInterface("socket.getEntity triggered called with invalid parameters");
} }
}); });
// both placing and deleting entities via the web interface
this.socket.on("placeEntity", req => {
// game.player.surface.create_entity{name="small-ship-wreck", position={game.player.position.x-2, game.player.position.y+1}, direction=..., force=...}
this.messageInterface("placing "+JSON.stringify(req));
if(req.name && typeof req.name == "string" && req.position && !isNaN(Number(req.position.x)) && !isNaN(Number(req.position.y))){
if(req.name == "deleted"){ // {{'+req.position.x+','+req.position.y+'},{'+req.position.x+','+req.position.y+'}}
// delete entity from game world using LUA command
this.messageInterface('/silent-command local toDelete = game.surfaces[1].find_entities({{'+req.position.x+','+req.position.y+'},{'+(req.position.x+1)+','+(req.position.y+1)+'}}) for i, entity in pairs(toDelete) do entity.die() end');
// this position is now empty, delete whatever was there from DB
this.deleteEntity(req.position.x, req.position.y);
} else {
let command = '/silent-command game.surfaces[1].create_entity{name="'+req.name+'", position={'+Number(req.position.x)+', '+Number(req.position.y)+'}, force="neutral"'
if(req.direction) command += ', direction='+req.direction;
command += '}';
this.messageInterface(command); // execute command
// add entity to the chunkStore database because create_entity does not trigger any events
let name = req.name;
let entity = {name};
if(typeof req.direction == "string"){
entity.rot = req.direction;
}
this.addEntity(req.position.x, req.position.y, entity);
}
}
});
this.messageInterface("/silent-command game.print('"+moduleConfig.name+" version "+moduleConfig.version+" enabled')"); this.messageInterface("/silent-command game.print('"+moduleConfig.name+" version "+moduleConfig.version+" enabled')");
} }
addEntity(x,y,entity){ // add entity to database
this.chunkMap.setEntity(Number(x), Number(y), entity).then(data => {
this.messageInterface("Added "+entity.name+" to data "+Number(x)+", "+Number(y));
}).catch((err)=>this.messageInterface(err));
}
deleteEntity(x,y){ // remove entity from database
// this position is now empty, delete whatever was there from DB
this.chunkMap.setEntity(x, y, "delete this entity").then(() => {
this.messageInterface("Deleted entity at "+x+", "+y);
}).catch((err)=>this.messageInterface(err));
}
scriptOutput(data){ scriptOutput(data){
if(data){ if(data){
this.messageInterface(data); this.messageInterface(data);
// express-transport-belt,-35.5,-14.5,[...] // express-transport-belt,-35.5,-14.5,[...]
data = data.split(","); data = data.split(",");
if(data && data[0] == undefined){ if(data && data[0] == undefined){
console.log("empty: "); this.messageInterface("empty: ");
console.log(data); this.messageInterface(data);
return return
} }
let name = data[0]; let name = data[0];
@@ -70,9 +107,7 @@ class remoteMap {
if(xPos && yPos && name){ if(xPos && yPos && name){
if(name == "deleted"){ if(name == "deleted"){
// this position is now empty, delete whatever was there from DB // this position is now empty, delete whatever was there from DB
this.chunkMap.setEntity(xPos, yPos, "delete this entity").then(() => { this.deleteEntity(xPos, yPos);
this.messageInterface("Deleted data "+xPos+", "+yPos);
}).catch((err)=>this.messageInterface(err));
} else { } else {
let entity = {name}; let entity = {name};
for(let i = 3; i < data.length; i++){ for(let i = 3; i < data.length; i++){
@@ -82,9 +117,10 @@ class remoteMap {
} }
} }
// save this entity in the database // save this entity in the database
this.chunkMap.setEntity(xPos, yPos, entity).then(data => { this.addEntity(xPos, yPos, entity);
/* this.chunkMap.setEntity(xPos, yPos, entity).then(data => {
this.messageInterface("Added "+name+" to data "+xPos+", "+yPos); this.messageInterface("Added "+name+" to data "+xPos+", "+yPos);
}).catch((err)=>this.messageInterface(err)); }).catch((err)=>this.messageInterface(err)); */
} }
} }
+2 -2
View File
@@ -2,10 +2,10 @@
{ {
"name": "remoteMap", "name": "remoteMap",
"title": "Clusterio remote map", "title": "Clusterio remote map",
"version": "2.0.0", "version": "2.2.0",
"date": "18-11-2017", "date": "18-11-2017",
"author": "Danielv123", "author": "Danielv123",
"dependencies": ["base >= 0.15"], "dependencies": ["base >= 0.15"],
"factorio_version": "0.16", "factorio_version": "0.16",
"description": "Clusterio plugin for external mapping and possibly building?" "description": "Clusterio plugin for mapping and building through the browser. No more need to start game, download and catching up for every game, also mobile factorio confirmed?"
} }
+6 -6
View File
@@ -1,9 +1,9 @@
<title>Clusterio</title> <title>Clusterio</title>
<link rel="stylesheet" type="text/css" href="style.css"> <link rel="stylesheet" type="text/css" href="style.css">
<script src="https://code.jquery.com/jquery.js"></script> <script src="external/jquery.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="external/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.js"></script> <script src="external/canvasjs.js"></script>
<script src="http://momentjs.com/downloads/moment.min.js"></script> <script src="external/moment.min.js"></script>
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js"></script> <script src="external/mousetrap.min.js"></script>
<script src="main.js"></script> <script src="main.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <link href="external/css/Roboto.css" rel="stylesheet">
+355
View File
@@ -0,0 +1,355 @@
import spritesheetJson from "./../pictures/spritesheet.js";
export var entityDrawRules = {
"big-electric-pole": {
sizeInTiles: {
x:2,
y:2,
},
positionOffset: {
x:-1,
y:-1,
}
},
"accumulator": {
spritesheet: spritesheetJson.frames["images/factorio/entity/accumulator/accumulator.png"],
sizeInTiles: {
x:3.5,
y:3.5,
},
positionOffset: {
x:-1,
y:-2,
}
},
"centrifuge": {
spritesheet: spritesheetJson.frames["images/factorio/entity/centrifuge/centrifuge-A.png.0"],
sizeInTiles: {
x:4,
y:4,
},
positionOffset: {
x:-1.5,
y:-1,
},
},
"stone-furnace": {
spritesheet: spritesheetJson.frames["images/factorio/entity/stone-furnace/stone-furnace.png"],
sizeInTiles: {
x:3,
y:2.2,
},
positionOffset: {
x:-0.9,
y:-1,
},
},
"steel-furnace": {
spritesheet: spritesheetJson.frames["images/factorio/entity/steel-furnace/steel-furnace.png"],
sizeInTiles: {
x:2.5,
y:2.5,
},
positionOffset: {
x:-1.2,
y:-1.1,
},
},
"roboport": {
spritesheet: spritesheetJson.frames["images/factorio/entity/roboport/roboport-base.png"],
sizeInTiles: {
x:5,
y:4.5,
},
positionOffset: {
x:-2,
y:-2.2,
},
},
"substation": {
spritesheet: spritesheetJson.frames["images/factorio/entity/substation/substation.png.0"],
sizeInTiles: {
x:3,
y:3,
},
positionOffset: {
x:-1,
y:-1.8,
},
},
"big-electric-pole": {
spritesheet: spritesheetJson.frames["images/factorio/entity/big-electric-pole/big-electric-pole.png.0"],
sizeInTiles: {
x:5,
y:5,
},
positionOffset: {
x:-1,
y:-3.5,
},
},
"electric-mining-drill": {
spritesheet: [{
spritesheet: spritesheetJson.frames["images/factorio/entity/electric-mining-drill/electric-mining-drill-N.png.0"],
},{
spritesheet: spritesheetJson.frames["images/factorio/entity/electric-mining-drill/electric-mining-drill-E.png.0"],
},{
spritesheet: spritesheetJson.frames["images/factorio/entity/electric-mining-drill/electric-mining-drill-S.png.0"],
},{
spritesheet: spritesheetJson.frames["images/factorio/entity/electric-mining-drill/electric-mining-drill-W.png.0"],
},
],
sizeInTiles: {
x:3,
y:3,
},
positionOffset: {
x:-1,
y:-1,
},
},
"straight-rail": {
sizeInTiles: {
x:2,
y:2,
},
positionOffset: {
x:-1,
y:-1,
}
},
};
let template3x3entity = {
sizeInTiles: {
x:3,
y:3,
},
positionOffset: {
x:-1,
y:-1,
},
};
for(let i = 1; i <= 3; i++){
let name = "assembling-machine-"+i;
// entityDrawRules[name] =
entityDrawRules[name] = {
spritesheet: spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png.0"],
sizeInTiles: {
x:3.9,
y:3.9,
},
positionOffset: {
x:-1.4,
y:-1.2,
},
}
// template3x3entity;
};
entityDrawRules["radar"] = {
spritesheet: [],
sizeInTiles: {
x:4,
y:4,
},
positionOffset: {
x:-0.8,
y:-1.7,
},
}
for(let i = 0; i < 64; i++){
// animate the radar
entityDrawRules.radar.spritesheet.push({spritesheet: spritesheetJson.frames["images/factorio/entity/radar/radar.png."+i]});
}
["beacon", "electric-furnace"].forEach(name => {
entityDrawRules[name] = template3x3entity;
});
entityDrawRules["lab"] = {
spritesheet: spritesheetJson.frames["images/factorio/entity/lab/lab.png.0"],
sizeInTiles: {
x:3.5,
y:3,
},
positionOffset: {
x:-1,
y:-0.9,
},
}
entityDrawRules["chemical-plant"] = {
spritesheet: [{
spritesheet: spritesheetJson.frames["images/factorio/entity/chemical-plant/chemical-plant.png.0"],
sizeInTiles: {
x:3.5,
y:3.5,
},
positionOffset: {
x:-1.3,
y:-1,
},
},{
spritesheet: spritesheetJson.frames["images/factorio/entity/chemical-plant/chemical-plant.png.1"],
sizeInTiles: {
x:3.7,
y:4,
},
positionOffset: {
x:-1.3,
y:-1.5,
},
},{
spritesheet: spritesheetJson.frames["images/factorio/entity/chemical-plant/chemical-plant.png.2"],
sizeInTiles: {
x:3.5,
y:3.2,
},
positionOffset: {
x:-1.3,
y:-1,
},
},{
spritesheet: spritesheetJson.frames["images/factorio/entity/chemical-plant/chemical-plant.png.3"],
sizeInTiles: {
x:3.7,
y:3.6,
},
positionOffset: {
x:-1.45,
y:-1.3,
},
},
],
};
[{name: "solar-panel", ref:"images/factorio/entity/solar-panel/solar-panel.png"}].forEach(ent => {
entityDrawRules[ent.name] = {
spritesheet: spritesheetJson.frames[ent.ref],
sizeInTiles: {
x:3,
y:3,
},
positionOffset: {
x:-1,
y:-1,
},
}
});
["transport-belt", "fast-transport-belt", "express-transport-belt"].forEach(name => {
entityDrawRules[name] = {
spritesheet: [{
spritesheet: [ // Up
// spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png.0"], // 0 to 31
],
sizeInTiles: {
x:1.2,y:1.4,
},
positionOffset: {
x:-0.1,y:-0,
}
},{
spritesheet: [ // Right
// spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png.0"], // 0 to 31
],
sizeInTiles: {
x:1.2,y:1.4,
},
positionOffset: {
x:-0.1,y:-0.2,
}
},{
spritesheet: [ // Down
// spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png.27"], // 32 to 63
],
flip: "y",
sizeInTiles: {
x:1.3,y:1.6,
},
positionOffset: {
x:-0.15,y:-1.6,
}
},{
spritesheet: [ // Left
// spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png.27"], // 32 to 63
],
flip: "x",
sizeInTiles: {
x:1.3,y:1.6,
},
positionOffset: {
x:-1.35,y:-0.25,
}
}],
}
for(let i = 0; i < 16; i++){
if(name == "transport-belt"){
entityDrawRules[name].spritesheet[3].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+i]);
entityDrawRules[name].spritesheet[2].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+(i+16)]);
entityDrawRules[name].spritesheet[1].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+i]);
entityDrawRules[name].spritesheet[0].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+(i+16)]);
} else {
entityDrawRules[name].spritesheet[3].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+i]);
entityDrawRules[name].spritesheet[2].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+(i+32)]);
entityDrawRules[name].spritesheet[1].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+i]);
entityDrawRules[name].spritesheet[0].spritesheet.push(spritesheetJson.frames["images/factorio/entity/"+name+"/"+name+".png."+(i+32)]);
}
}
});
["splitter", "fast-splitter", "express-splitter"].forEach(splitter => {
entityDrawRules[splitter] = {
rotOffset:180,
}
});
["underground-belt", "fast-underground-belt", "express-underground-belt"].forEach(underneathie => {
entityDrawRules[underneathie] = {
rotOffset: 270,
}
});
["inserter", "fast-inserter", "stack-inserter", "filter-inserter", "burner-inserter", 'long-handed-inserter', 'stack-filter-inserter'].forEach(inserter => {
entityDrawRules[inserter] = {
rotOffset:90,
}
});
entityDrawRules["oil-refinery"] = {
spritesheet: [
{
spritesheet: spritesheetJson.frames["images/factorio/entity/oil-refinery/oil-refinery.png.0"],
}, {
spritesheet: spritesheetJson.frames["images/factorio/entity/oil-refinery/oil-refinery.png.1"],
}, {
spritesheet: spritesheetJson.frames["images/factorio/entity/oil-refinery/oil-refinery.png.2"],
}, {
spritesheet: spritesheetJson.frames["images/factorio/entity/oil-refinery/oil-refinery.png.3"],
}],
}
// correct image size for the oil refinery frames (same for all of them on this one)
entityDrawRules["oil-refinery"].spritesheet.forEach(object => {
object.sizeInTiles = {
x:10,
y:7.5,
}
object.positionOffset = {
x:-2,
y:-2.7,
}
});
// tree sizes
["tree-02",
"tree-02-red",
"tree-03",
"tree-04",
"tree-05",
"tree-07",
"tree-09",
"tree-09-brown",
"tree-09-red"].forEach(tree => {
entityDrawRules[tree] = {
sizeInTiles: {
x: 3,
y: 4,
},
positionOffset: {
x: -0.6,
y: -2.6,
}
}
});
+53
View File
@@ -0,0 +1,53 @@
export function getParameterByName(name, url) {
if(!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if(!results) return null;
if(!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// ctx, entityImages[name].img, xPos, yPos, size.x, size.y, rotation, sprWidth, sprHeight, offLeft, offTop
export function drawImageWithRotation(ctx, image, x, y, w, h, degrees, sprWidth, sprHeight, offLeft, offTop, flipX, flipY){
ctx.save();
ctx.translate(x+w/2, y+h/2);
ctx.rotate(degrees*Math.PI/180.0);
ctx.translate(-x-w/2, -y-h/2);
if(flipX) {
x -= x*2+sprWidth;
ctx.scale(-1, 1);
}
if(flipY){
y -= y*2+sprHeight;
ctx.scale(1, -1);
}
if(isImageOk(image) && sprWidth != undefined && sprHeight != undefined && offLeft != undefined && offTop != undefined){
// console.log(sprWidth+" "+sprHeight+" "+offLeft+" "+offTop+" "+w+" "+h)
ctx.drawImage(image, offLeft, offTop, sprWidth, sprHeight, x, y, w, h);
} else if(isImageOk(image)){
ctx.drawImage(image, x, y, w, h);
} else {
// console.log("Image is not OK! "+image.src);
}
ctx.restore();
}
export function isImageOk(img) {
// During the onload event, IE correctly identifies any images that
// weren't downloaded as not complete. Others should too. Gecko-based
// browsers act like NS4 in that they report this incorrectly.
if (!img.complete) {
return false;
}
// However, they do have two very useful properties: naturalWidth and
// naturalHeight. These give the true size of the image. If it failed
// to load, either of these should be zero.
if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
return false;
}
// No other way of checking: assume it's ok.
return true;
}
+15 -3
View File
@@ -169,7 +169,7 @@ $.getJSON("/api/getFactorioLocale", (locale) => {
// image data // image data
// key is the name of the item in the database, value is the name of the image on wiki.factorio.com/images/* // key is the name of the item in the database, value is the name of the image on wiki.factorio.com/images/*
// this list has to include all entities that doesn't just follow the simple capitalize first letter convention // this list has to include all entities that doesn't just follow the simple capitalize first letter convention
/* Notice: All icon images hosted on this Wiki have been renamed to use their in-game names, with underscores. If your external tool references these icons, please correct your links. */ /* Notice from bilka: All icon images hosted on this Wiki have been renamed to use their in-game names, with underscores. If your external tool references these icons, please correct your links. */
var imagedata = { var imagedata = {
"put-combinator": "Decider_combinator", "put-combinator": "Decider_combinator",
"smart-train-stop": "Train_stop", "smart-train-stop": "Train_stop",
@@ -177,6 +177,19 @@ var imagedata = {
"solar-panel-equipment": "Portable_solar_panel", "solar-panel-equipment": "Portable_solar_panel",
"diesel-locomotive": "Locomotive", // pre 0.15 loco name "diesel-locomotive": "Locomotive", // pre 0.15 loco name
"small-lamp": "Lamp", "small-lamp": "Lamp",
"tree-02": "Green_tree",
"tree-02-red": "Green_tree",
"tree-03": "Green_tree",
"tree-04": "Green_tree",
"tree-05": "Green_tree",
"tree-07": "Green_tree",
"tree-09": "Green_tree",
"tree-09-brown": "Green_tree",
"tree-09-red": "Green_tree",
"dead-tree-desert": "Dead_tree_desert",
"sand-rock-big": "Rock_big",
// "biter-spawner" missing, but can't find png for it on wiki
// "spitter-spawner"
} }
@@ -199,6 +212,5 @@ var imagelinks = {
"piercing-shotgun-shell": "/pictures/piercing_shotgun_shells.png", "piercing-shotgun-shell": "/pictures/piercing_shotgun_shells.png",
"energy-shield-mk2-equipment": "/pictures/Energy_shield_MK2.png", "energy-shield-mk2-equipment": "/pictures/Energy_shield_MK2.png",
"battery-mk2-equipment": "/pictures/Battery_MK2.png", "battery-mk2-equipment": "/pictures/Battery_MK2.png",
"personal-roboport-mk2-equipment": "/pictures/Personal_roboport_MK2.png" "personal-roboport-mk2-equipment": "/pictures/Personal_roboport_MK2.png",
} }
+8 -2
View File
@@ -33,6 +33,8 @@ function getParameterByName(name, url) {
/// code below here /// code below here
// declaring globals
var chartsByID = {};
// update the online indicator dot // update the online indicator dot
setInterval(function(){ setInterval(function(){
getJSON("/api/slaves", function(err, slaveData){ getJSON("/api/slaves", function(err, slaveData){
@@ -201,6 +203,7 @@ function makeTerminal(){
myTerminal.input('',handleTerminalInput); myTerminal.input('',handleTerminalInput);
} }
} }
if(localStorage.terminalMinimized == "true")minimizeTerminal(true);
function minimizeTerminal(instant){ function minimizeTerminal(instant){
localStorage.terminalMinimized = true; localStorage.terminalMinimized = true;
$('#terminal').draggable('disable'); $('#terminal').draggable('disable');
@@ -239,6 +242,10 @@ function maximizeTerminal(instant){
// ID of slave, ID of canvasjs div without # // ID of slave, ID of canvasjs div without #
function makeGraph(instanceID, selector) { function makeGraph(instanceID, selector) {
let chartIgnoreList = [
"water",
"steam"
]
post("api/getStats", {instanceID: instanceID}, function(data){ post("api/getStats", {instanceID: instanceID}, function(data){
//console.log("Building chart " + instanceID + " with this data:") //console.log("Building chart " + instanceID + " with this data:")
//console.log(data) //console.log(data)
@@ -250,7 +257,7 @@ function makeGraph(instanceID, selector) {
} }
let chartData = []; let chartData = [];
for(let o = 0; o < itemNames.length; o++) { for(let o = 0; o < itemNames.length; o++) {
if(itemNames[o] != "water"){ if(!chartIgnoreList.includes(itemNames[o])){
chartData[chartData.length] = generateLineChartArray(data, itemNames[o]); chartData[chartData.length] = generateLineChartArray(data, itemNames[o]);
} }
} }
@@ -289,7 +296,6 @@ function generateLineChartArray(data, nameKey) {
return xyz; return xyz;
} }
var chartsByID = {};
function drawChart(selector, chartData, title) { function drawChart(selector, chartData, title) {
// selector is ID of element, ex "chartContainer" or "-123199123" // selector is ID of element, ex "chartContainer" or "-123199123"
console.log(chartData) console.log(chartData)
Binary file not shown.

After

Width:  |  Height:  |  Size: 968 KiB

+17 -5
View File
@@ -1,16 +1,28 @@
<!doctype HTML> <!doctype HTML>
<head> <head>
<%- include("head.html") %> <%- include("head.html") %>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script> <script src="external/socket.io.js"></script>
<script src="remoteMap.js"></script> <script type="module" src="remoteMap.js"></script>
</head> </head>
<body> <body>
<%- include("sidebar.html") %> <%- include("sidebar.html") %>
<div id="body"> <div id="body">
<h2>remoteMap</h2> <h2>remoteMap</h2>
<canvas id="remoteMap" width="1024" height="1024" style="border:1px solid #000000;"> <div id="remoteMapContainer" style="float:left">
<canvas class="remoteMap" id="remoteMapBackground" width="512" height="512" style="border:1px solid #000000;position:absolute;"></canvas>
</canvas> <canvas class="remoteMap" id="remoteMap" width="512" height="512" style="border:1px solid #000000;position:absolute;"></canvas>
<canvas class="remoteMap" id="remoteMapSelection" width="512" height="512" style="border:1px solid #000000;position:absolute;"></canvas>
</div>
<div id="remoteMapItemSelector" style="float:left">
<!-- Generated by script, don't edit -->
</div>
<div id="remoteMapSettings" style="float:left">
<p>Map size: <input type="number" id="mapSize" style="color:black;"> (default 32)</p>
<p>Tile size: <input type="number" id="tileSize" style="color:black;"> (default 8)</p>
<p>FPS: <input type="number" id="fpsCounter" style="color:black;"></p>
<p>Pause when window is deselected (saves CPU) <input type="checkbox" id="pauseOnBlur"></p>
<p>Movement speed: <input type="number" id="movementSpeed" style="color:black;"> (default 0.2)</p>
</div>
</div> </div>
</body> </body>
+498 -164
View File
@@ -1,14 +1,92 @@
function getParameterByName(name, url) { /**
if (!url) url = window.location.href; Javascript to download and render a map of a factorio world from an instance using websockets and canvas
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), It is its responsibility to handle:
results = regex.exec(url); * Display settings
if (!results) return null; * Ordering of canvases
if (!results[2]) return ''; * Querying slaves through master for map info
return decodeURIComponent(results[2].replace(/\+/g, " ")); * Drawing of sprites defined in external files to canvas
* Handling input for placing/removing items
* Transmitting item placements/removals through master
That is way too much for one file, so to anyone reading this:
This file is horribly written and documented.
I am sorry. Drawing code is at the bottom, good luck.
If you have questions and wish to contact me, my name
is Danielv123 on Github, Discord and esperNet #factorio
*/
console.log(":)")
/// ES6 imports
// rules for how entities are drawn (sizes, offset etc)
import {entityDrawRules} from "./lib/entityDrawRules.js";
import {getParameterByName, drawImageWithRotation, isImageOk} from "./lib/utility.js";
import spritesheetJson from "./pictures/spritesheet.js";
import {itemSelector} from "./remoteMap/itemSelection.js";
var global = {};
var itemSelectorGUI = new itemSelector("#remoteMapItemSelector", [
{name:"stone-furnace"},
{name:"accumulator"},
{name:"electric-furnace"},
{name:"inserter"},
{name:"express-transport-belt"},
]);
if(!localStorage.remoteMapConfig || localStorage.remoteMapConfig == "[object Object]"){
localStorage.remoteMapConfig = JSON.stringify({
mapSize: 32,
tileSize: 8,
movementSpeed: 0.2,
});
} }
var socket = io.connect('http://localhost:8080'); var remoteMapConfig = JSON.parse(localStorage.remoteMapConfig);
// Handle config changes through UI buttons
(function(){
let selectMapSize = document.querySelector("#mapSize");
let selectTileSize = document.querySelector("#tileSize");
if(selectMapSize && selectTileSize){
selectMapSize.value = Number(remoteMapConfig.mapSize) || 32;
selectTileSize.value = Number(remoteMapConfig.tileSize) || 8;
selectMapSize.onchange = function(){
let config = JSON.parse(localStorage.remoteMapConfig);
config.mapSize = Number(selectMapSize.value);
localStorage.remoteMapConfig = JSON.stringify(config);
console.log("Config updated: "+localStorage.remoteMapConfig);
}
selectTileSize.onchange = function(){
let config = JSON.parse(localStorage.remoteMapConfig);
config.tileSize = Number(selectTileSize.value);
localStorage.remoteMapConfig = JSON.stringify(config);
console.log("Config updated: "+localStorage.remoteMapConfig);
}
}
let pauseOnBlur = document.querySelector("#pauseOnBlur");
if(pauseOnBlur){
pauseOnBlur.checked = localStorage.remoteMapPauseOnBlur || true;
pauseOnBlur.onchange = function(){
localStorage.remoteMapPauseOnBlur = pauseOnBlur.checked;
}
}
let movementSpeed = document.querySelector("#movementSpeed");
if(movementSpeed){
movementSpeed.value = Number(remoteMapConfig.movementSpeed) || 0.2;
movementSpeed.onchange = function(){
let config = JSON.parse(localStorage.remoteMapConfig);
config.movementSpeed = Number(movementSpeed.value);
localStorage.remoteMapConfig = JSON.stringify(config);
console.log("Config updated: "+localStorage.remoteMapConfig);
// also update config live
remoteMapConfig.movementSpeed = config.movementSpeed;
}
}
})();
var socket = io.connect(document.location.origin);
socket.on('hello', function (data) { socket.on('hello', function (data) {
console.log(data); console.log(data);
socket.emit("registerMapRequester", {instanceID: getParameterByName("instanceID")}); socket.emit("registerMapRequester", {instanceID: getParameterByName("instanceID")});
@@ -16,15 +94,23 @@ socket.on('hello', function (data) {
setInterval(()=>{ setInterval(()=>{
socket.emit("heartbeat"); // send our heartbeat to prevent being assumed dead socket.emit("heartbeat"); // send our heartbeat to prevent being assumed dead
},10000); },10000);
requestMapDraw(); // load important images then proceed with rendering (and loading more images)
global.spritesheet = new Image();
global.spritesheet.onload = function(){
global.grassBackground = new Image();
global.grassBackground.onload = function(){
requestMapDraw();
}
global.grassBackground.src = "/pictures/grass-1.png";
}
global.spritesheet.src = "/pictures/spritesheet.png";
}); });
socket.on("displayChunk", function(chunk){ socket.on("displayChunk", function(chunk){
console.log(chunk); console.log("displayChunk triggered but I can't draw chunks");
drawChunk(chunk, ctx);
}); });
socket.on("displayEntity", function(entity){ socket.on("displayEntity", function(entity){
console.log("Displaying entity "+JSON.stringify(entity)); // console.log("Displaying entity "+JSON.stringify(entity));
drawEntity(entity); drawEntity(entity);
}); });
}); });
@@ -32,128 +118,144 @@ socket.on('hello', function (data) {
function requestChunk(x,y){ function requestChunk(x,y){
socket.emit('requestChunk', {x:x, y:y, instanceID: getParameterByName("instanceID")}); socket.emit('requestChunk', {x:x, y:y, instanceID: getParameterByName("instanceID")});
} }
setTimeout(function(){ (function(){
canvas = document.getElementById("remoteMap"); let remoteMapLayers = document.querySelectorAll(".remoteMap");
ctx = canvas.getContext("2d"); remoteMapLayers.forEach(layer => {
ctx.font = "30px Arial"; layer.addEventListener('contextmenu', event => event.preventDefault());
ctx.fillText("Hello World",10,50); layer.width = remoteMapConfig.tileSize * remoteMapConfig.mapSize;
layer.height = remoteMapConfig.tileSize * remoteMapConfig.mapSize;
var img = new Image(); });
img.onload = function() { ["width", "height"].forEach(style => document.querySelector("#remoteMapContainer").style[style] = remoteMapConfig.tileSize * remoteMapConfig.mapSize + "px");
ctx.drawImage(img, 0, 0, 32, 32); })();
}; const canvas = document.querySelector("#remoteMap");
img.src = 'https://wiki.factorio.com/images/Lab.png'; const ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
}, 1); ctx.fillText("Use WASD to navigate.",10,50);
entityImages = {};
/*
entityImages["express-transport-belt"] = new Image();
entityImages["express-transport-belt"].src = 'https://wiki.factorio.com/images/Express_transport_belt.png';
*/
const selectionCanvas = document.querySelector("#remoteMapSelection");
const selectionCtx = selectionCanvas.getContext("2d");
selectionCtx.font = "30px Arial";
selectionCtx.fillText("Selection layer",10,50);
const backgroundCanvas = document.querySelector("#remoteMapBackground");
const backgroundCtx = backgroundCanvas.getContext("2d");
// map view position, top left corner (or another corner?) // map view position, top left corner (or another corner?)
playerPosition = { window.playerPosition = {
x:0, x:0,
y:0, y:0,
} }
window.cachePosition = {
x:0,
y:0,
};
function requestMapDraw(){ function requestMapDraw(){
let xLow = Math.floor(playerPosition.x % 16); let xLow = Math.floor(cachePosition.x % remoteMapConfig.tileSize);
let yLow = Math.floor(playerPosition.y % 16); let yLow = Math.floor(cachePosition.y % remoteMapConfig.tileSize);
let xHigh = xLow+64; let xHigh = xLow+remoteMapConfig.mapSize;
let yHigh = yLow+64; let yHigh = yLow+remoteMapConfig.mapSize;
for(let x = xLow; x < xHigh; x++){ for(let x = xLow; x < xHigh; x++){
for(let y = yLow; y < yHigh; y++){ for(let y = yLow; y < yHigh; y++){
socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")}); socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")});
} }
} }
} }
function drawImageWithRotation(ctx, image, x, y, w, h, degrees){
ctx.save(); document.addEventListener('keydown', keyDownHandler, false);
ctx.translate(x+w/2, y+h/2); document.addEventListener('keyup', keyUpHandler, false);
ctx.rotate(degrees*Math.PI/180.0); var rightPressed = false;
ctx.translate(-x-w/2, -y-h/2); var leftPressed = false;
ctx.drawImage(image, x, y, w, h); var upPressed = false;
ctx.restore(); var downPressed = false;
function keyDownHandler(event) {
if(event.keyCode == 39 || event.keyCode == 68) {
rightPressed = true;
}
else if(event.keyCode == 37 || event.keyCode == 65) {
leftPressed = true;
}
if(event.keyCode == 40 || event.keyCode == 83) {
downPressed = true;
}
else if(event.keyCode == 38 || event.keyCode == 87) {
upPressed = true;
}
}
function keyUpHandler(event) {
if(event.keyCode == 39 || event.keyCode == 68) {
rightPressed = false;
}
else if(event.keyCode == 37 || event.keyCode == 65) {
leftPressed = false;
}
if(event.keyCode == 40 || event.keyCode == 83) {
downPressed = false;
}
else if(event.keyCode == 38 || event.keyCode == 87) {
upPressed = false;
}
} }
Mousetrap.bind("s", e => { var entityCache = new Array(remoteMapConfig.mapSize);
console.log("s");
cache.walkUp();
playerPosition.y += 16;
clear();drawFromCache();
});
Mousetrap.bind("d", e => {
console.log("d");
cache.walkLeft();
playerPosition.x += 16;
clear();drawFromCache();
});
Mousetrap.bind("w", e => {
console.log("w");
cache.walkDown();
playerPosition.y -= 16;
clear();drawFromCache();
});
Mousetrap.bind("a", e => {
console.log("a");
cache.walkRight();
playerPosition.x -= 16;
clear();drawFromCache();
});
entityCache = new Array(64);
// populate cache with arrays of arrays // populate cache with arrays of arrays
for(let i = 0; i < 64; i++){ for(let i = 0; i < remoteMapConfig.mapSize; i++){
entityCache[i] = new Array(64); entityCache[i] = new Array(remoteMapConfig.mapSize);
for(let o = 0; o < 64; o++){ for(let o = 0; o < remoteMapConfig.mapSize; o++){
entityCache[i][o] = " "; entityCache[i][o] = " ";
} }
} }
cache = { // cache navigation functions, for panning (walking, if you will)
walkUp: function walkUp(){ const cache = {
for(let i = 0; i < 64; i++){ walkDown: function walkUp(){
cachePosition.y += remoteMapConfig.tileSize;
for(let i = 0; i < remoteMapConfig.mapSize; i++){
entityCache[i].shift(); // remove leftmost entry entityCache[i].shift(); // remove leftmost entry
entityCache[i].push(" "); // add new entry on the right entityCache[i].push(" "); // add new entry on the right
// get data from slaveMapper // get data from slaveMapper
let x = playerPosition.x/16 + i; let x = cachePosition.x/remoteMapConfig.tileSize + i;
let y = playerPosition.y/16+64; let y = cachePosition.y/remoteMapConfig.tileSize+remoteMapConfig.mapSize-1;
socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")}); socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")});
} }
}, },
walkDown: function walkDown(){ walkUp: function walkDown(){
for(let i = 0; i < 64; i++){ cachePosition.y -= remoteMapConfig.tileSize;
for(let i = 0; i < remoteMapConfig.mapSize; i++){
entityCache[i].pop(); // remove rightmost entry entityCache[i].pop(); // remove rightmost entry
entityCache[i].unshift(" "); // add new entry on the left entityCache[i].unshift(" "); // add new entry on the left
// get data from slaveMapper // get data from slaveMapper
let x = playerPosition.x/16 + i; let x = cachePosition.x/remoteMapConfig.tileSize + i;
let y = playerPosition.y/16; let y = cachePosition.y/remoteMapConfig.tileSize;
socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")}); socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")});
} }
}, },
walkLeft: function walkLeft(){ walkLeft: function walkLeft(){
cachePosition.x += remoteMapConfig.tileSize;
entityCache.shift(); entityCache.shift();
entityCache.push(new Array(64)); entityCache.push(new Array(remoteMapConfig.mapSize));
// get data from slaveMapper // get data from slaveMapper
// fill in a row on the right side of the screen, that is the bottom of the 1st level array // fill in a row on the right side of the screen, that is the bottom of the 1st level array
for(let i = 0; i < 64; i++){ for(let i = 0; i < remoteMapConfig.mapSize; i++){
let x = playerPosition.x/16 + 64; let x = cachePosition.x/remoteMapConfig.tileSize + remoteMapConfig.mapSize - 1;
let y = playerPosition.y/16 + i; let y = cachePosition.y/remoteMapConfig.tileSize + i;
socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")}); socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")});
} }
}, },
walkRight: function walkRight(){ walkRight: function walkRight(){
cachePosition.x -= remoteMapConfig.tileSize;
entityCache.pop(); entityCache.pop();
entityCache.unshift(new Array(64)); entityCache.unshift(new Array(remoteMapConfig.mapSize));
// get data from slaveMapper // get data from slaveMapper
// fill a row on the left side of the screen, that is the top column // fill a row on the left side of the screen, that is the top column
for(let i = 0; i < 64; i++){ for(let i = 0; i < remoteMapConfig.mapSize; i++){
let x = playerPosition.x/16; let x = cachePosition.x/remoteMapConfig.tileSize;
let y = playerPosition.y/16 + i; let y = cachePosition.y/remoteMapConfig.tileSize + i;
socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")}); socket.emit("requestEntity", {x, y, instanceID: getParameterByName("instanceID")});
} }
} }
} }
function drawFromCache(){ function drawFromCache(){
clear();
let startTime = Date.now()
entityCache.forEach(row => { entityCache.forEach(row => {
row.forEach(doc => { row.forEach(doc => {
if(doc && typeof doc == "object"){ if(doc && typeof doc == "object"){
@@ -162,29 +264,314 @@ function drawFromCache(){
}); });
}); });
} }
window.requestAnimationFrame(renderLoop);
var fpsTimings = {
lastFrame: Date.now(),
averageLength: 60,
sum:0,
counter: document.querySelector("#fpsCounter"),
}
var isPaused = false;
window.onblur = function() {
if(localStorage.remoteMapPauseOnBlur == "true"){
isPaused = true;
console.log("paused");
}
}
window.onfocus = function() {
if(isPaused){
isPaused = false;
console.log("unpaused");
window.requestAnimationFrame(renderLoop);
}
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
window.mousePos = {};
selectionCanvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(selectionCanvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
window.mousePos.x = mousePos.x;
window.mousePos.y = mousePos.y;
}, false);
selectionCanvas.addEventListener("mousedown", function(evt) {
if(evt.which === 1) window.mousePos.clicked = true;
if(evt.which === 3) window.mousePos.rightClicked = true;
// place item in world by sending it with websockets and shit
let tileSize = remoteMapConfig.tileSize;
let entity = {
name: itemSelectorGUI.getItem().name,
position:{
x: Math.floor((playerPosition.x + window.mousePos.x) / tileSize),
y: Math.floor((playerPosition.y + window.mousePos.y) / tileSize),
},
direction: itemSelectorGUI.getItem().direction.toString(),
};
if(evt.which === 1){ // left click to place
console.log(JSON.stringify(entity));
socket.emit("placeEntity", entity);
} else if(evt.which === 3){ // right click to delete
entity.name = "deleted";
socket.emit("placeEntity", entity)
}
// console.log(entity);
});
selectionCanvas.addEventListener("mouseup", function(evt) {
if(evt.which === 1) window.mousePos.clicked = false;
if(evt.which === 3) window.mousePos.rightClicked = false;
});
function renderLoop(){
// render game canvas
let newTimestamp = Date.now();
fpsTimings.sum = fpsTimings.sum / fpsTimings.averageLength * (fpsTimings.averageLength - 1);
let timeSinceLastFrame;
fpsTimings.sum += timeSinceLastFrame = newTimestamp - fpsTimings.lastFrame;
fpsTimings.counter.value = (1000 / (fpsTimings.sum / fpsTimings.averageLength)).toPrecision(4);
fpsTimings.lastFrame = newTimestamp;
if(!isPaused){
let moveSpeed = Number(remoteMapConfig.movementSpeed);
let movement = moveSpeed * timeSinceLastFrame;
// handle movement and requesting new entities
if(upPressed){
console.log("w");
playerPosition.y -= movement;
if(Math.abs((playerPosition.y-cachePosition.y)/remoteMapConfig.tileSize) > 1){
for(let i = 0; i < Math.floor(Math.abs((playerPosition.y-cachePosition.y)/remoteMapConfig.tileSize)); i++){
cache.walkUp();
}
}
}
if(leftPressed){
console.log("a");
playerPosition.x -= movement;
if(Math.abs((playerPosition.x-cachePosition.x)/remoteMapConfig.tileSize) > 1){
for(let i = 0; i < Math.floor(Math.abs((playerPosition.x-cachePosition.x)/remoteMapConfig.tileSize)); i++){
cache.walkRight();
}}
}
if(downPressed){
console.log("s");
playerPosition.y += movement;
if(Math.abs((playerPosition.y-cachePosition.y)/remoteMapConfig.tileSize) > 1){
for(let i = 0; i < Math.floor(Math.abs((playerPosition.y-cachePosition.y)/remoteMapConfig.tileSize)); i++){
cache.walkDown();
}}
}
if(rightPressed){
console.log("d");
let oldPos = playerPosition.x;
playerPosition.x += movement;
if(Math.abs((playerPosition.x-cachePosition.x)/remoteMapConfig.tileSize) > 1){
for(let i = 0; i < Math.floor(Math.abs((playerPosition.x-cachePosition.x)/remoteMapConfig.tileSize)); i++){
cache.walkLeft();
}}
}
// draw map
drawFromCache();
// queue next tick
window.requestAnimationFrame(renderLoop);
}
// render selection canvas
let mousePosition = window.mousePos;
if(mousePosition && mousePosition.x){
// make a box around the mouse cursor
selectionCtx.beginPath();
selectionCtx.lineWidth = remoteMapConfig.tileSize / 16;
selectionCtx.strokeStyle="yellow";
if(mousePosition.clicked) selectionCtx.strokeStyle = "red";
if(mousePosition.rightClicked) selectionCtx.strokeStyle = "blue";
let tileSize = remoteMapConfig.tileSize
let halfTile = tileSize / 2;
let tilePosition = { // position in world coordinates (same as used by factorio)
x: Math.floor((playerPosition.x + mousePosition.x) / tileSize),
y: Math.floor((playerPosition.y + mousePosition.y) / tileSize),
}
// Long thing to correct for offset between playerPosition, cachePosition (tile grid) and mouse position and draw the box so it aligns with tiles.
selectionCtx.rect(tilePosition.x * tileSize - playerPosition.x, tilePosition.y * tileSize - playerPosition.y, tileSize, tileSize);
selectionCtx.stroke();
}
// render background canvas
let dw = 1024 / 32 * remoteMapConfig.tileSize;
let dh = 64 / 32 * remoteMapConfig.tileSize;
// 0-dw and x < ?? + dw is to make sure we draw well outside the canvas on both sides to avoid ugly gfx
for(let x = 0-dw; x < remoteMapConfig.tileSize * remoteMapConfig.mapSize + dw; x += dw){
for(let y = 0-dh; y < remoteMapConfig.tileSize * remoteMapConfig.mapSize + dh; y += dh){
let dx = x - playerPosition.x % dw;
let dy = y - playerPosition.y % dh;
if(global.grassBackground && isImageOk(global.grassBackground)) backgroundCtx.drawImage(global.grassBackground, 0, 64, 1024, 64, dx, dy, dw, dh);
}
}
}
var entityImages = {}; // cache to store images and details about entities, populated by drawEntity();
window.logEntCache = function(){console.log(entityCache)}
function drawEntity(entity, dontCache){ function drawEntity(entity, dontCache){
if(entity.x && entity.y){ if(entity.x !== undefined && entity.y !== undefined){
if(!dontCache){ if(!dontCache){
// cache entity for later draws (like panning) // cache entity for later draws (like panning)
if(entity.x - playerPosition.x/16 >= 0 && entity.x - playerPosition.x/16 < 64 && entity.y - playerPosition.y/16 >= 0 && entity.y - playerPosition.y/16 < 64){ if(entity.x - cachePosition.x/remoteMapConfig.tileSize >= 0 && entity.x - cachePosition.x/remoteMapConfig.tileSize < remoteMapConfig.mapSize && entity.y - cachePosition.y/remoteMapConfig.tileSize >= 0 && entity.y - cachePosition.y/remoteMapConfig.tileSize < remoteMapConfig.mapSize){
if(entity.entity){ if(entity.entity){
entityCache[entity.x - playerPosition.x/16][entity.y - playerPosition.y/16] = entity; entityCache[entity.x - cachePosition.x/remoteMapConfig.tileSize][entity.y - cachePosition.y/remoteMapConfig.tileSize] = entity;
} else { } else {
// delete this entity because we just heard the tile is empty and stuff // delete this entity because we just heard the tile is empty and stuff
entityCache[entity.x - playerPosition.x/16][entity.y - playerPosition.y/16] = " "; entityCache[entity.x - cachePosition.x/remoteMapConfig.tileSize][entity.y - cachePosition.y/remoteMapConfig.tileSize] = " ";
} }
} }
} }
if(entity.entity && entity.entity.name && typeof entity.entity.name == "string"){ if(entity.entity && entity.entity.name && typeof entity.entity.name == "string"){
let name = entity.entity.name; let name = entity.entity.name;
if(!entityImages[name]){ if(!entityImages[name]){
console.log("Downloading image "+name);
// download the entityImages and add stuff to queue // download the entityImages and add stuff to queue
entityImages[name] = {}; entityImages[name] = {
entityImages[name].img = new Image(); img: new Image(),
entityImages[name].queue = []; queue: [],
entityImages[name].queue.push(entity); loaded: false,
entityImages[name].loaded = false; };
entityImages[name].img.onload = function(){ entityImages[name].draw = function(entity){
if(this.loaded){
let name = entity.entity.name;
let image, sprWidth, sprHeight, offLeft, offTop, size, offsetX, offsetY;
let flipX = false, flipY = false;
let rotation = 0;
// check hardcoded entity draw rules for specifics (otherwise draw icon as 1x1 entity with rotation if specified)
if(entityDrawRules[name] && (entityDrawRules[name].positionOffset || entityDrawRules[name].spritesheet)){
let rules = entityDrawRules[name]
if(rules.positionOffset){
offsetX = rules.positionOffset.x;
offsetY = rules.positionOffset.y;
}
if(rules.sizeInTiles){
size = {
x: remoteMapConfig.tileSize * rules.sizeInTiles.x,
y: remoteMapConfig.tileSize * rules.sizeInTiles.y,
};
}
if(rules.spritesheet && Array.isArray(rules.spritesheet)){
let dir = Number(entity.entity.rot || 0);
// 2 animated sprites, we will need to flip it for rotations.
if(rules.spritesheet.length == 2){
let spritesheetAnim = dir / 2 % 2;
let animationStage = Math.floor(Date.now()/16) % rules.spritesheet[spritesheetAnim].spritesheet.length;
try{
sprWidth = rules.spritesheet[spritesheetAnim].spritesheet[animationStage].frame.w;
sprHeight = rules.spritesheet[spritesheetAnim].spritesheet[animationStage].frame.h;
offLeft = rules.spritesheet[spritesheetAnim].spritesheet[animationStage].frame.x;
offTop = rules.spritesheet[spritesheetAnim].spritesheet[animationStage].frame.y;
} catch(e){
// console.log(name)
// console.log(rules.spritesheet[spritesheetAnim].spritesheet)
}
image = global.spritesheet;
// handle rotation (not handled by generic handler because we have to do flips and special stuff)
if(dir == 4){
// rotation = (dir/2)*90
// console.log("rotating")
flipY = true;
} else if(dir == 6){
flipX = true;
// rotation = ((dir+2)/2)*90+180 // this formula is terrible, don't try to repair, there is no sense to it
}
if(rules.spritesheet[spritesheetAnim].positionOffset){
offsetX = rules.spritesheet[spritesheetAnim].positionOffset.x;
offsetY = rules.spritesheet[spritesheetAnim].positionOffset.y;
}
if(rules.spritesheet[spritesheetAnim].sizeInTiles){
size = {
x: remoteMapConfig.tileSize * rules.spritesheet[spritesheetAnim].sizeInTiles.x,
y: remoteMapConfig.tileSize * rules.spritesheet[spritesheetAnim].sizeInTiles.y,
};
}
} else {
// correct for whether we have 1, 4 or 8 directions
let spriteSheetRotIndex = dir / (8 / rules.spritesheet.length);
if(rules.spritesheet.length > 8) {
// apparently this entity has more than 8 directions. That isn't supported.
// therefore we can conclude that they are instead intended as animation frames.
// That is why we treat them as animation frames.
spriteSheetRotIndex = Math.floor(Date.now()/32) % rules.spritesheet.length;
} else if(rules.spritesheet[spriteSheetRotIndex].spritesheet.length){
var animationStage = Math.floor(Date.now()/16) % rules.spritesheet[spriteSheetRotIndex].spritesheet.length;
var usesAnimation = true;
} else {
var usesAnimation = false;
}
if(usesAnimation){
try{
sprWidth = rules.spritesheet[spriteSheetRotIndex].spritesheet[animationStage].frame.w;
sprHeight = rules.spritesheet[spriteSheetRotIndex].spritesheet[animationStage].frame.h;
offLeft = rules.spritesheet[spriteSheetRotIndex].spritesheet[animationStage].frame.x;
offTop = rules.spritesheet[spriteSheetRotIndex].spritesheet[animationStage].frame.y;
}catch(e){} // TODO throws error due to yellow belt rendering
} else {
sprWidth = rules.spritesheet[spriteSheetRotIndex].spritesheet.frame.w;
sprHeight = rules.spritesheet[spriteSheetRotIndex].spritesheet.frame.h;
offLeft = rules.spritesheet[spriteSheetRotIndex].spritesheet.frame.x;
offTop = rules.spritesheet[spriteSheetRotIndex].spritesheet.frame.y;
}
image = global.spritesheet;
if(rules.spritesheet[spriteSheetRotIndex].positionOffset){
offsetX = rules.spritesheet[spriteSheetRotIndex].positionOffset.x;
offsetY = rules.spritesheet[spriteSheetRotIndex].positionOffset.y;
}
if(rules.spritesheet[spriteSheetRotIndex].sizeInTiles){
size = {
x: remoteMapConfig.tileSize * rules.spritesheet[spriteSheetRotIndex].sizeInTiles.x,
y: remoteMapConfig.tileSize * rules.spritesheet[spriteSheetRotIndex].sizeInTiles.y,
};
}
if(rules.spritesheet[spriteSheetRotIndex].flip){
let flip = rules.spritesheet[spriteSheetRotIndex].flip;
if(flip == "x") flipX = true;
if(flip == "y") flipY = true;
}
}
} else if(rules.spritesheet){
sprWidth = rules.spritesheet.frame.w;
sprHeight = rules.spritesheet.frame.h;
offLeft = rules.spritesheet.frame.x;
offTop = rules.spritesheet.frame.y;
image = global.spritesheet;
}
} else {
offsetX = 0, offsetY = 0;
size = {
x:remoteMapConfig.tileSize, y: remoteMapConfig.tileSize,
};
}
let xPos = ((entity.x + offsetX) * remoteMapConfig.tileSize) - playerPosition.x;
let yPos = ((entity.y + offsetY) * remoteMapConfig.tileSize) - playerPosition.y;
if(entity.entity.rot && !isNaN(Number(entity.entity.rot)) && !(entityDrawRules[name] && Array.isArray(entityDrawRules[name].spritesheet))){
let rules = entityDrawRules[name];
if(rules && rules.rotOffset){
rotation = ((entity.entity.rot * 45) + entityDrawRules[name].rotOffset);
} else {
rotation = entity.entity.rot * 45;
}
}
if(!image) image = entityImages[name].img;
// if(name == "oil-refinery") console.log(offsetX)
drawImageWithRotation(ctx, image, xPos, yPos, size.x, size.y, rotation%360, sprWidth, sprHeight, offLeft, offTop, flipX, flipY);
//console.log("Drawing "+name+" at X: "+xPos+", Y: "+yPos+" with with rotation "+rotation);
} else {
// we are waiting for the image to load, push the task to our queue. It will be processed once the image loads.
this.queue.push(entity);
}
}
let imageLoaded = function(){
// process queue and display // process queue and display
console.log("Image loaded!"); console.log("Image loaded!");
entityImages[name].loaded = true; entityImages[name].loaded = true;
@@ -193,82 +580,29 @@ function drawEntity(entity, dontCache){
}); });
entityImages[name].queue = []; entityImages[name].queue = [];
} }
entityImages[name].draw = function(entity){ entityImages[name].queue.push(entity);
if(this.loaded){ entityImages[name].img.onload = imageLoaded()
let name = entity.entity.name;
let xPos = (entity.x * 16) - playerPosition.x; if(entityDrawRules[name] && entityDrawRules[name].spritesheet){
let yPos = (entity.y * 16) - playerPosition.y; // imageLoaded();
let rotation = 0; } else entityImages[name].img.src = getImageFromName(name);
if(entity.entity.rot && !isNaN(Number(entity.entity.rot))){
rotation = entity.entity.rot * 45;
}
drawImageWithRotation(ctx, entityImages[name].img, xPos, yPos, 16, 16, rotation);
//console.log("Drawing "+name+" at X: "+xPos+", Y: "+yPos);
} else {
this.queue.push(entity);
}
}
entityImages[name].img.src = getImageFromName(name);
} else { } else {
// console.log("Already got image, drawing")
entityImages[name].draw(entity); entityImages[name].draw(entity);
} }
} else { } else {
// we got an empty coordinate pair, that usually means this tile was occupied before but is empty now // we got an empty coordinate pair, that usually means this tile was occupied before but is empty now
console.log("Clearing at X: "+entity.x+", Y: "+entity.y); console.log("Clearing at X: "+entity.x+", Y: "+entity.y);
ctx.clearRect(entity.x * 16, entity.y * 16, 16, 16); ctx.clearRect((entity.x + playerPosition.x/remoteMapConfig.tileSize) * remoteMapConfig.tileSize, (entity.y + playerPosition.y/remoteMapConfig.tileSize) * remoteMapConfig.tileSize, remoteMapConfig.tileSize, remoteMapConfig.tileSize);
} }
} else { } else {
throw new Error("drawEntity on entity without x and y coordinates") console.log(entity);
throw new Error("drawEntity on entity without x and y coordinates");
} }
} }
function drawChunk(chunk, ctx){
Object.keys(chunk.dataObject).forEach(xValue => {
let xRow = chunk.dataObject[xValue];
Object.keys(xRow).forEach(yValue => {
let yCell = xRow[yValue];
if(yCell && yCell.name && yCell.name){
let img = new Image();
let xPos = (xValue*16)+(chunk.position.x*64*16)+(64*16*3);
let yPos = (yValue*16)+(chunk.position.y*64*16)+(64*16);
img.onload = function() {
ctx.drawImage(img, xPos, yPos, 16, 16);
console.log("X: "+xPos+", Y: "+yPos);
};
img.src = getImageFromName(yCell.name);
//img.src = entityImages[yCell.name].src;
}
});
});
}
function clear(){ function clear(){
ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.clearRect(0, 0, canvas.width, canvas.height);
selectionCtx.clearRect(0, 0, selectionCanvas.width, selectionCanvas.height);
backgroundCtx.clearRect(0, 0, backgroundCanvas.width, backgroundCanvas.height);
} }
// setInterval(()=>console.log(entityDrawRules),5000);
/*
/// ZOOMING AND PANNING COPY PASTA ===============================================
// View parameters
var xleftView = 0;
var ytopView = 0;
var widthViewOriginal = 1.0; //actual width and height of zoomed and panned display
var heightViewOriginal = 1.0;
var widthView = widthViewOriginal; //actual width and height of zoomed and panned display
var heightView = heightViewOriginal;
window.addEventListener("load",setup,false);
function setup() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
widthCanvas = canvas.width;
heightCanvas = canvas.height;
canvas.addEventListener("dblclick", handleDblClick, false); // dblclick to zoom in at point, shift dblclick to zoom out.
canvas.addEventListener("mousedown", handleMouseDown, false); // click and hold to pan
canvas.addEventListener("mousemove", handleMouseMove, false);
canvas.addEventListener("mouseup", handleMouseUp, false);
canvas.addEventListener("mousewheel", handleMouseWheel, false); // mousewheel duplicates dblclick function
canvas.addEventListener("DOMMouseScroll", handleMouseWheel, false); // for Firefox
draw();
}*/
+85
View File
@@ -0,0 +1,85 @@
export class itemSelector {
constructor(containerSelector, entities){
this.containerSelector = containerSelector;
this.container = document.querySelector(containerSelector);
if(!this.container) throw new Error("Could not find container "+container);
this.entities = entities;
this.direction = 0;
// populate container
let cont = this.container;
let HTML = "";
HTML += "<div class='header'>";
HTML += "<h2>Item selection</h2>";
HTML += "</div>";
HTML += "<div class='itemSelector'>";
HTML += "<span>Name: </span>";
HTML += "<select class='blackText'>";
this.entities.forEach(entity => HTML += "<option value='"+entity.name+"'>"+entity.name+"</option>");
HTML += "</select>";
HTML += "</div>";
// direction selector
HTML += "<div id='directionSelector'>";
HTML += "<h2>Direction: </h2>";
HTML += "<h2 id='directionDisplay'>"+this.directionToCardinal(0)+"</h2>"
HTML += "<p>Press R to rotate</p>";
HTML += "</div>";
// write styles
let styles = {
".header > h2":{
color:"white",
},
".blackText":{
color:"black",
},
".blackText > option":{
color:"black",
}
}
// turn style object into style tag
HTML += "<style>";
for(let style in styles){
HTML += containerSelector+" "+style+"{";
for(let styleName in styles[style]){
let styleValue = styles[style][styleName];
HTML += styleName+":"+styleValue+";";
}
HTML += "}";
}
cont.innerHTML += HTML + "</style>";
// handle direction keyboard event
Mousetrap.bind('r', ()=>this.rotate());
}
directionToCardinal(dir){
if(dir == 0){
return "north";
} else if(dir == 1){
return "north-east";
} else if(dir == 2){
return "east";
} else if(dir == 3){
return "south-east";
} else if(dir == 4){
return "south";
} else if(dir == 5){
return "south-west";
} else if(dir == 6){
return "west";
} else if(dir == 7){
return "north-west";
}
}
rotate(){
this.direction = (this.direction + 2) % 8;
// update display
document.querySelector("#directionDisplay").innerHTML = this.directionToCardinal(this.direction);
}
getItem(){
let name = document.querySelector(this.containerSelector+" > .itemSelector > select").value;
let direction = this.direction;
return {name, direction};
}
}
+8 -6
View File
@@ -19,12 +19,14 @@ setTimeout(function() {
// detect if remoteMap mod is installed, if it is we want to show the link for it // detect if remoteMap mod is installed, if it is we want to show the link for it
let hasRemoteMap = false; let hasRemoteMap = false;
slaveData[key].mods.forEach(mod => { if(slaveData[key].mods){ // not all instances have mods apparently
console.log(mod.modName); slaveData[key].mods.forEach(mod => {
if(mod.modName.includes("remoteMap")){ console.log(mod.modName);
hasRemoteMap = true; // we are still doing the logic on the outside, in case there are multiple instances of remoteMap installed.... if(mod.modName.includes("remoteMap")){
} hasRemoteMap = true; // we are still doing the logic on the outside, in case there are multiple instances of remoteMap installed....
}); }
});
}
if(hasRemoteMap){ if(hasRemoteMap){
HTML += "<a href='/remoteMap?instanceID="+slaveData[key].unique+"'>Remote map</a>" HTML += "<a href='/remoteMap?instanceID="+slaveData[key].unique+"'>Remote map</a>"
} }
+3
View File
@@ -271,4 +271,7 @@ input:checked + .slider:before {
-webkit-transform: translateX(26px); -webkit-transform: translateX(26px);
-ms-transform: translateX(26px); -ms-transform: translateX(26px);
transform: translateX(26px); transform: translateX(26px);
}
canvas {
-webkit-transform:translateZ(0)
} }