diff --git a/Screeps/Commands.js b/Screeps/Commands.js new file mode 100644 index 0000000..ab1f36c --- /dev/null +++ b/Screeps/Commands.js @@ -0,0 +1,61 @@ + + +module.exports = { + setup(){ + global.fullReset = fullReset; + global.resetRooms = resetRooms; + global.resetStructures = resetStructures; + global.resetCreeps = resetCreeps; + global.resetConstruction = resetConstruction; + + global.buildRoads = buildRoads; + } +} + +function fullReset(){ + resetRooms(); + resetCreeps(); + resetStructures(); + resetConstruction(); + global.started = false; + global.compiled = false; + return "OK"; +} + +function resetRooms(){ + Object.values(Game.rooms).forEach(room => room.memory = {}); + return "OK"; +} + +function resetStructures(){ + Object.values(Game.structures).forEach(structure => structure.memory = {}); + return "OK"; +} + +function resetCreeps(){ + Object.values(Game.creeps).forEach(creep => creep.suicide()); + return "OK"; +} + +function resetConstruction(){ + Object.values(Game.rooms).forEach(room=>room.find(FIND_CONSTRUCTION_SITES).forEach(cs=>cs.remove())); + return "OK"; +} + +function buildRoads(){ + Object.values(Game.rooms).forEach(room=> + { + room.memory.layout.sources.forEach( + sId => { + const source = Game.getObjectById(sId); + var roads = []; + roads = roads.concat(source.pos.findPathTo(room.controller)); + roads.pop(); + roads = roads.concat(source.pos.findPathTo(room.find(FIND_MY_STRUCTURES, { filter:{ structureType:STRUCTURE_SPAWN }})[0])); + roads.pop(); + roads.forEach(tile => room.createConstructionSite(tile.x, tile.y, STRUCTURE_ROAD)); + } + ); + }); + return "OK"; +} \ No newline at end of file diff --git a/Screeps/CreepClass.js b/Screeps/CreepClass.js new file mode 100644 index 0000000..34f06f0 --- /dev/null +++ b/Screeps/CreepClass.js @@ -0,0 +1,45 @@ +const jobBuilder = require("JobBuilder"); +const jobCleaner = require("JobCleaner"); +const jobMiner = require("JobMiner"); +const jobSupplier = require("JobSupplier"); +const jobUpgrader = require("JobUpgrader"); + +module.exports = { + setup: function () { + Creep.prototype = _Creep.prototype; + global.Role = Role; + } +} + +const Role = { + BUILDER: 0, + CLEANER: 1, + MINER: 2, + SUPPLIER: 3, + UPGRADER: 4 +} + +class _Creep extends Creep { + begin(){ + if(!this.memory.job) this.memory.job = { role: Role.HARVESTER }; + switch (this.memory.job.role) { + case Role.BUILDER: jobBuilder.begin(this); break; + case Role.CLEANER: jobCleaner.begin(this); break; + case Role.MINER: jobMiner.begin(this); break; + case Role.SUPPLIER: jobSupplier.begin(this); break; + case Role.UPGRADER: jobUpgrader.begin(this); break; + } + this.memory.init = true; + } + + tick(){ + if(!this.memory.init) this.begin(); + switch (this.memory.job.role) { + case Role.BUILDER: jobBuilder.tick(this); break; + case Role.CLEANER: jobCleaner.tick(this); break; + case Role.MINER: jobMiner.tick(this); break; + case Role.SUPPLIER: jobSupplier.tick(this); break; + case Role.UPGRADER: jobUpgrader.tick(this); break; + } + } +} \ No newline at end of file diff --git a/Screeps/JobBuilder.js b/Screeps/JobBuilder.js new file mode 100644 index 0000000..3284f16 --- /dev/null +++ b/Screeps/JobBuilder.js @@ -0,0 +1,94 @@ +module.exports = { + begin(creep){ + if(!creep.memory.collecting) creep.memory.collecting = false; + if(!creep.memory.counter) creep.memory.counter = 0; + }, + + tick(creep){ + if(creep.memory.collecting) { + GetEnergy(creep); + energyFullCheck(creep); + } + else { + BuildOrRepair(creep); + energyEmptyCheck(creep); + } + } +} + +function GetEnergy(creep){ + if(!creep.memory.target) findEnergyTarget(creep); + const target = Game.getObjectById(creep.memory.target); + if(!target) creep.memory.target = undefined; + if(creep.pos.isNearTo(target)) { + if(!target.store) creep.pickup(target); + else creep.withdraw(target, RESOURCE_ENERGY); + } + else creep.moveTo(target); +} + +function energyFullCheck(creep){ + if(!creep.store.getFreeCapacity(RESOURCE_ENERGY)) { + creep.memory.collecting = false; + creep.memory.target = undefined; + } +} + +function BuildOrRepair(creep){ + if(!creep.memory.target) findBuildOrRepairTarget(creep); + if(!creep.memory.target) return; + const target = Game.getObjectById(creep.memory.target); + if(!target) { creep.memory.target = undefined; return; } + if(target.hits && target.hits === target.hitsMax) { creep.memory.target = undefined; return; } + if(creep.pos.isNearTo(target)) + if(!target.hits) creep.build(target); + else creep.repair(target); + else creep.moveTo(target); +} + +function energyEmptyCheck(creep){ + if(!creep.store.getUsedCapacity(RESOURCE_ENERGY)) { + creep.memory.collecting = true; + creep.memory.target = undefined; + } +} + +function findEnergyTarget(creep){ + var target; + if(creep.room.storage && creep.room.storage.store.getUsedCapacity(RESOURCE_ENERGY) > creep.store.getFreeCapacity(RESOURCE_ENERGY)) + target = creep.room.storage; + if(!target) target = creep.pos.findClosestByRange(FIND_STRUCTURES, { + filter: (st)=>{ + return st.structureType == STRUCTURE_CONTAINER && st.store.getUsedCapacity(RESOURCE_ENERGY) > creep.store.getFreeCapacity(RESOURCE_ENERGY); + }}); + + if(!target) target = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES, { + filter: (r)=>{ + return r.resourceType == RESOURCE_ENERGY && r.amount > creep.store.getFreeCapacity(RESOURCE_ENERGY); + }}); + if(!target) target = creep.pos.findClosestByRange(FIND_RUINS, { + filter: (r)=>{ + return r.store.getUsedCapacity(RESOURCE_ENERGY) > creep.store.getFreeCapacity(RESOURCE_ENERGY); + }}); + if(!target) target = creep.pos.findClosestByRange(FIND_TOMBSTONES, { + filter: (t)=>{ + return t.store.getUsedCapacity(RESOURCE_ENERGY) > creep.store.getFreeCapacity(RESOURCE_ENERGY); + }}); + + if(target) creep.memory.target = target.id; +} + +function findBuildOrRepairTarget(creep) { + var target; + switch (creep.memory.counter%2) { + case 0: target = creep.pos.findClosestByRange(FIND_MY_CONSTRUCTION_SITES); break; + case 1: target = creep.pos.findClosestByRange(FIND_STRUCTURES, { + filter:(s)=> { + return s.hits < s.hitsMax || + ((s.structureType === STRUCTURE_WALL || s.structureType === STRUCTURE_RAMPART) && s.hits < 100000 ); + }}); + break; + } + if(target) creep.memory.target = target.id; + creep.memory.counter++; +} \ No newline at end of file diff --git a/Screeps/JobCleaner.js b/Screeps/JobCleaner.js new file mode 100644 index 0000000..74d0c30 --- /dev/null +++ b/Screeps/JobCleaner.js @@ -0,0 +1,81 @@ +module.exports = { + begin(creep){ + if(!creep.memory.collecting) creep.memory.collecting = false; + }, + + tick(creep){ + if(creep.memory.collecting) { + searchForLooseEnergy(creep); + energyFullCheck(creep); + } + else { + DepositEnergy(creep); + energyEmptyCheck(creep); + } + } +} + +function searchForLooseEnergy(creep){ + if(!creep.memory.target) findLooseEnergyTarget(creep); + const target = Game.getObjectById(creep.memory.target); + if(!target) creep.memory.target = undefined; + if(creep.pos.isNearTo(target)) { + if(!target.store) creep.pickup(target); + else creep.withdraw(target, RESOURCE_ENERGY); + } + else creep.moveTo(target); +} + +function energyFullCheck(creep){ + if(!creep.store.getFreeCapacity(RESOURCE_ENERGY)) { + creep.memory.collecting = false; + creep.memory.target = undefined; + } +} + +function DepositEnergy(creep){ + if(!creep.memory.target) findDepositTarget(creep); + if(!creep.memory.target) return; + const target = Game.getObjectById(creep.memory.target); + if(target.store.getFreeCapacity(RESOURCE_ENERGY)==0) { creep.memory.target = undefined; creep.memory.counter++; } + if(creep.pos.isNearTo(target)) creep.transfer(target, RESOURCE_ENERGY); + else creep.moveTo(target); +} + +function energyEmptyCheck(creep){ + if(!creep.store.getUsedCapacity(RESOURCE_ENERGY)) { + creep.memory.collecting = true; + creep.memory.target = undefined; + } +} + +function findLooseEnergyTarget(creep){ + var target = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES, { + filter: (r)=>{ + return r.resourceType == RESOURCE_ENERGY && r.amount > creep.store.getFreeCapacity(RESOURCE_ENERGY); + }}); + if(!target) target = creep.pos.findClosestByRange(FIND_RUINS, { + filter: (r)=>{ + return r.store.getUsedCapacity(RESOURCE_ENERGY) > creep.store.getFreeCapacity(RESOURCE_ENERGY); + }}); + if(!target) target = creep.pos.findClosestByRange(FIND_TOMBSTONES, { + filter: (t)=>{ + return t.store.getUsedCapacity(RESOURCE_ENERGY) > creep.store.getFreeCapacity(RESOURCE_ENERGY); + }}); + if(target) creep.memory.target = target.id; +} + +function findDepositTarget(creep) { + var target = creep.pos.findClosestByRange(FIND_STRUCTURES, { + filter:(s)=> { + return s.structureType == STRUCTURE_CONTAINER + && s.store.getFreeCapacity(RESOURCE_ENERGY) > 1000; + }}); + if(!target) target = creep.pos.findClosestByRange(FIND_MY_STRUCTURES, { + filter:(s)=> { + return (s.structureType == STRUCTURE_SPAWN || s.structureType == STRUCTURE_EXTENSION) + && s.store.getFreeCapacity(RESOURCE_ENERGY) > 0; + }}); + if(!target) target = creep.room.storage; + if(target) creep.memory.target = target.id; +} \ No newline at end of file diff --git a/Screeps/JobMiner.js b/Screeps/JobMiner.js new file mode 100644 index 0000000..63c064f --- /dev/null +++ b/Screeps/JobMiner.js @@ -0,0 +1,25 @@ +module.exports = { + begin(creep){}, + + tick(creep){ + const source = Game.getObjectById(creep.memory.job.source); + if(!creep.pos.isNearTo(source)) { creep.moveTo(source); return; } + if(!(Game.time%100)) scanForContainer(creep, source); + moveToContainer(creep); + creep.harvest(source); + } +} + +function moveToContainer(creep){ + const container = Game.getObjectById(creep.memory.container); + if(!container) return; + if(container.pos.x === creep.pos.x && container.pos.y === creep.pos.y) return; + creep.moveTo(container); +} + +function scanForContainer(creep, source){ + const container = source.pos.findInRange(FIND_STRUCTURES, 1, { + filter:{structureType:STRUCTURE_CONTAINER} + })[0]; + if(container) creep.memory.container = container.id; +} \ No newline at end of file diff --git a/Screeps/JobSupplier.js b/Screeps/JobSupplier.js new file mode 100644 index 0000000..2a4b65a --- /dev/null +++ b/Screeps/JobSupplier.js @@ -0,0 +1,90 @@ +module.exports = { + begin(creep){ + if(!creep.memory.collecting) creep.memory.collecting = false; + }, + + tick(creep){ + if(creep.memory.collecting) { + withdrawEnergy(creep); + energyFullCheck(creep); + } + else { + transferEnergy(creep); + energyEmptyCheck(creep); + } + } +} + +function withdrawEnergy(creep){ + if(!creep.memory.target) findWithdrawTarget(creep); + const target = Game.getObjectById(creep.memory.target); + if(!target) creep.memory.target = undefined; + if(creep.pos.isNearTo(target)) { + if(!target.store) creep.pickup(target); + else creep.withdraw(target, RESOURCE_ENERGY); + } + else creep.moveTo(target); +} + +function energyFullCheck(creep){ + if(!creep.store.getFreeCapacity(RESOURCE_ENERGY)) { + creep.memory.collecting = false; + creep.memory.target = undefined; + } +} + +function transferEnergy(creep){ + if(!creep.memory.target) findTransferTarget(creep); + if(!creep.memory.target) return; + const target = Game.getObjectById(creep.memory.target); + if(target.store.getFreeCapacity(RESOURCE_ENERGY)==0) { creep.memory.target = undefined; creep.memory.counter++; } + if(creep.pos.isNearTo(target)) creep.transfer(target, RESOURCE_ENERGY); + else creep.moveTo(target); +} + +function energyEmptyCheck(creep){ + if(!creep.store.getUsedCapacity(RESOURCE_ENERGY)) { + creep.memory.collecting = true; + creep.memory.target = undefined; + } +} + +function findWithdrawTarget(creep){ + var target = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES, { + filter: (r)=>{ + return r.resourceType == RESOURCE_ENERGY && r.amount > creep.store.getFreeCapacity(RESOURCE_ENERGY); + }}); + if(!target) target = creep.pos.findClosestByRange(FIND_RUINS, { + filter: (r)=>{ + return r.store.getUsedCapacity(RESOURCE_ENERGY) > creep.store.getFreeCapacity(RESOURCE_ENERGY); + }}); + if(!target) target = creep.pos.findClosestByRange(FIND_TOMBSTONES, { + filter: (t)=>{ + return t.store.getUsedCapacity(RESOURCE_ENERGY) > creep.store.getFreeCapacity(RESOURCE_ENERGY); + }}); + if(!target) target = creep.pos.findClosestByRange(FIND_STRUCTURES, { + filter: (st)=>{ + return st.structureType == STRUCTURE_CONTAINER && st.store.getUsedCapacity(RESOURCE_ENERGY) > 1000; + }}); + if(target) creep.memory.target = target.id; +} + +function findTransferTarget(creep) { + var target = creep.pos.findClosestByRange(FIND_MY_STRUCTURES, { + filter:(s)=> { + return (s.structureType == STRUCTURE_EXTENSION) + && s.store.getFreeCapacity(RESOURCE_ENERGY) > 0; + }}); + if(!target) target = creep.pos.findClosestByRange(FIND_MY_STRUCTURES, { + filter:(s)=> { + return (s.structureType == STRUCTURE_SPAWN) + && s.store.getFreeCapacity(RESOURCE_ENERGY) > 0; + }}); + if(!target) target = creep.pos.findClosestByRange(FIND_STRUCTURES, { + filter:(s)=> { + return s.structureType == STRUCTURE_CONTAINER + && s.store.getFreeCapacity(RESOURCE_ENERGY) > 1000; + }}) + if(!target) target = creep.room.storage; + if(target) creep.memory.target = target.id; +} \ No newline at end of file diff --git a/Screeps/JobUpgrader.js b/Screeps/JobUpgrader.js new file mode 100644 index 0000000..b74a655 --- /dev/null +++ b/Screeps/JobUpgrader.js @@ -0,0 +1,28 @@ +module.exports = { + begin(creep){ + }, + + tick(creep){ + if(!creep.pos.isNearTo(creep.room.controller)) { creep.moveTo(creep.room.controller); return; } + if(creep.store.getUsedCapacity(RESOURCE_ENERGY) == 0) { getOrWaitForEnergy(creep); return; } + creep.upgradeController(creep.room.controller); + } +} + +function getOrWaitForEnergy(creep){ + if(!creep.memory.container) scanForContainer(creep); + if(creep.memory.container) getEnergyFromContainer(creep); +} + +function getEnergyFromContainer(creep){ + const container = Game.getObjectById(creep.memory.container); + if(creep.withdraw(container, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) creep.moveTo(container); +} + +// duplicate see miner +function scanForContainer(creep){ + const container = creep.room.controller.pos.findInRange(FIND_STRUCTURES, 1, { + filter:{structureType:STRUCTURE_CONTAINER} + })[0]; + if(container) creep.memory.container = container.id; +} \ No newline at end of file diff --git a/Screeps/Math.js b/Screeps/Math.js new file mode 100644 index 0000000..35b08c9 --- /dev/null +++ b/Screeps/Math.js @@ -0,0 +1,7 @@ +module.exports = { + clamp: function(v, min, max){ + if(vs.id); + room.memory.layout.containers = room.find(FIND_MY_STRUCTURES, {filter:{structureType:STRUCTURE_CONTAINER}}).map(c=>c.id); +} + +function jobScan(room){ + if(!room.memory.jobs) room.memory.jobs = [{role:Role.UPGRADER}] + .concat(Array(4).fill({role: Role.BUILDER})) + .concat(Array(2).fill({role: Role.SUPPLIER})) + .concat(room.memory.layout.sources.map(s=> {return {role: Role.MINER, source: s}})); +} + +function vacancyScan(room){ + const activeJobs = room.find(FIND_MY_CREEPS).map(creep=>creep.memory.job); + const jobs = room.memory.jobs.filter((j)=>{ + const index = activeJobs.findIndex(aj=> _.isEqual(aj,j)); + if(index < 0) return true; + activeJobs.splice(index,1); + return false; + }); + room.memory.vacancies = jobs; +} + diff --git a/Screeps/Structure.js b/Screeps/Structure.js new file mode 100644 index 0000000..f503a13 --- /dev/null +++ b/Screeps/Structure.js @@ -0,0 +1,21 @@ +const spawnClass = require("StructureSpawnClass"); + +module.exports = { + setup() { + spawnClass.setup(); + }, + + begin(structure){ + switch (structure.structureType) { + case STRUCTURE_SPAWN: structure.begin(); break; + default: break; + } + }, + + tick(structure){ + switch (structure.structureType) { + case STRUCTURE_SPAWN: structure.tick(); break; + default: break; + } + } +} \ No newline at end of file diff --git a/Screeps/StructureSpawnClass.js b/Screeps/StructureSpawnClass.js new file mode 100644 index 0000000..98babe3 --- /dev/null +++ b/Screeps/StructureSpawnClass.js @@ -0,0 +1,64 @@ +module.exports = { + setup: function () { StructureSpawn.prototype = _StructureSpawn.prototype; } +} + +class _StructureSpawn extends StructureSpawn { + begin(){ + if (!this.memory.creepCounter) this.memory.creepCounter = 0; + this.memory.init = true; + } + + tick(){ + if(!this.memory.init) this.begin(); + if(Game.time%100) return; + if(this.room.energyAvailable < 300) return; + const job = this.room.memory.vacancies.pop(); + if(job){ + const name = getJobName(job.role); + const body = getBodyByJob(job.role, this.room.energyAvailable); + if(this.createCreep(job, name, body) != OK) this.room.memory.vacancies.push(job); + } + } + + createCreep(job, name, body) { + const response = this.spawnCreep(body, name + ": " + this.memory.creepCounter, { + memory: { job: job } + }); + if (response == OK) this.memory.creepCounter++; + return response; + } +} + +function getJobName(role){ + switch (role) { + case Role.BUILDER: return "Bob"; + case Role.MINER: return "minny"; + case Role.SUPPLIER: return "Sully"; + case Role.UPGRADER: return "Uppa"; + } +} + +function getBodyByJob(role, energyAvailability){ + const body = []; + switch (role) { + case Role.BUILDER: body.push(WORK); energyAvailability -= 100; break; + case Role.UPGRADER: body.push(CARRY); body.push(MOVE); energyAvailability -= 100; break; + case Role.MINER: body.push(MOVE); energyAvailability -= 100; break; + } + + var unitEnergyCost = 0; + while(unitEnergyCost <= energyAvailability) { + switch (role) { + case Role.BUILDER: body.push(MOVE); body.push(CARRY); unitEnergyCost = 100; break; + case Role.UPGRADER: + case Role.MINER: + body.push(WORK); unitEnergyCost = 100; + if(role === Role.MINER && body.length > 5) energyAvailability = -1; + break; + case Role.SUPPLIER: body.push(CARRY); body.push(MOVE); unitEnergyCost = 100; break; + default: energyAvailability = -1; break; + } + energyAvailability -= unitEnergyCost; + } + return body; +} \ No newline at end of file diff --git a/Screeps/main.js b/Screeps/main.js new file mode 100644 index 0000000..e58dbac --- /dev/null +++ b/Screeps/main.js @@ -0,0 +1,44 @@ +const Commands = require("Commands"); +const CreepClass = require("CreepClass"); +const RoomClass = require("RoomClass"); +const Structure = require("Structure"); + +module.exports.loop = function () { + if(!global.compiled) onRecompile(); + else if (!global.started) onRestart(); + else onTick(); +} + +function onRecompile(){ + setupClasses(); + console.log("Script recompiled..."); + global.compiled = true; +} + +function onRestart(){ + Object.values(Game.rooms).forEach(room => room.begin()); + Object.values(Game.creeps).forEach(creep => creep.begin()); + Object.values(Game.structures).forEach(structure => Structure.begin(structure)); + global.started = true; +} + +function onTick(){ + Object.values(Game.rooms).forEach(room => room.tick()); + Object.values(Game.creeps).forEach(creep => creep.tick()); + Object.values(Game.structures).forEach(structure => Structure.tick(structure)); + if(!(Game.time % 100)) cleanUp(); +} + + +function setupClasses(){ + Commands.setup(); + CreepClass.setup(); + RoomClass.setup(); + Structure.setup(); +} + +function cleanUp(){ + Object.keys(Memory.rooms).forEach(roomName => { if(!Game.rooms[roomName]) Memory.rooms[roomName] = undefined; }); + Object.keys(Memory.creeps).forEach(creepName => { if(!Game.creeps[creepName]) Memory.creeps[creepName] = undefined; }); +} + diff --git a/dist/douwco_hivemind_loader.js b/dist/douwco_hivemind_loader.js index 8af5e7b..2fe446e 100644 --- a/dist/douwco_hivemind_loader.js +++ b/dist/douwco_hivemind_loader.js @@ -6,7 +6,7 @@ var Module = (function() { function(Module) { Module = Module || {}; -var Module=typeof Module!=="undefined"?Module:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function shell_read(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function readBinary(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function readAsync(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var STACK_ALIGN=16;function dynamicAlloc(size){var ret=HEAP32[DYNAMICTOP_PTR>>2];var end=ret+size+15&-16;HEAP32[DYNAMICTOP_PTR>>2]=end;return ret}function getNativeTypeSize(type){switch(type){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:{if(type[type.length-1]==="*"){return 4}else if(type[0]==="i"){var bits=Number(type.substr(1));assert(bits%8===0,"getNativeTypeSize invalid bits "+bits+", type "+type);return bits/8}else{return 0}}}}function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}function convertJsFunctionToWasm(func,sig){if(typeof WebAssembly.Function==="function"){var typeNames={"i":"i32","j":"i64","f":"f32","d":"f64"};var type={parameters:[],results:sig[0]=="v"?[]:[typeNames[sig[0]]]};for(var i=1;i>0]=value;break;case"i8":HEAP8[ptr>>0]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":tempI64=[value>>>0,(tempDouble=value,+Math_abs(tempDouble)>=1?tempDouble>0?(Math_min(+Math_floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math_ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[ptr>>2]=tempI64[0],HEAP32[ptr+4>>2]=tempI64[1];break;case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;default:abort("invalid type for setValue: "+type)}}var wasmMemory;var wasmTable=new WebAssembly.Table({"initial":537,"maximum":537+0,"element":"anyfunc"});var ABORT=false;var EXITSTATUS=0;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}function getCFunc(ident){var func=Module["_"+ident];assert(func,"Cannot call unknown function "+ident+", make sure it is exported");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={"string":function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},"array":function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string")return UTF8ToString(ret);if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}var UTF16Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-16le"):undefined;function UTF16ToString(ptr,maxBytesToRead){var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder){return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr))}else{var i=0;var str="";while(1){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0||i==maxBytesToRead/2)return str;++i;str+=String.fromCharCode(codeUnit)}}}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}var WASM_PAGE_SIZE=65536;function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var STACK_BASE=5297600,DYNAMIC_BASE=5297600,DYNAMICTOP_PTR=54560;var INITIAL_INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;if(Module["wasmMemory"]){wasmMemory=Module["wasmMemory"]}else{wasmMemory=new WebAssembly.Memory({"initial":INITIAL_INITIAL_MEMORY/WASM_PAGE_SIZE,"maximum":2147483648/WASM_PAGE_SIZE})}if(wasmMemory){buffer=wasmMemory.buffer}INITIAL_INITIAL_MEMORY=buffer.byteLength;updateGlobalBufferAndViews(buffer);HEAP32[DYNAMICTOP_PTR>>2]=DYNAMIC_BASE;function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){Module["dynCall_v"](func)}else{Module["dynCall_vi"](func,callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var Math_abs=Math.abs;var Math_ceil=Math.ceil;var Math_floor=Math.floor;var Math_min=Math.min;var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix="file://";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile="douwco_hivemind.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(){try{if(wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(wasmBinaryFile)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary()})}return new Promise(function(resolve,reject){resolve(getBinary())})}function createWasm(){var info={"env":asmLibraryArg,"wasi_snapshot_preview1":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiatedSource(output){receiveInstance(output["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync();return{}}var tempDouble;var tempI64;var ASM_CONSTS={6682:function($0){console.log("Undefined role for creep"+$0)},8564:function(){console.log("To much creeps in this room")},8613:function(){console.log("Creating a harvester")}};function _emscripten_asm_const_iii(code,sigPtr,argbuf){var args=readAsmConstArgs(sigPtr,argbuf);return ASM_CONSTS[code].apply(null,args)}__ATINIT__.push({func:function(){___wasm_call_ctors()}});function demangle(func){return func}function demangleAll(text){var regex=/\b_Z[\w\d_]+/g;return text.replace(regex,function(x){var y=demangle(x);return x===y?x:y+" ["+x+"]"})}function jsStackTrace(){var err=new Error;if(!err.stack){try{throw new Error}catch(e){err=e}if(!err.stack){return"(no stack trace available)"}}return err.stack.toString()}var ExceptionInfoAttrs={DESTRUCTOR_OFFSET:0,REFCOUNT_OFFSET:4,TYPE_OFFSET:8,CAUGHT_OFFSET:12,RETHROWN_OFFSET:13,SIZE:16};function ___cxa_allocate_exception(size){return _malloc(size+ExceptionInfoAttrs.SIZE)+ExceptionInfoAttrs.SIZE}function _atexit(func,arg){}function ___cxa_atexit(a0,a1){return _atexit(a0,a1)}function ExceptionInfo(excPtr){this.excPtr=excPtr;this.ptr=excPtr-ExceptionInfoAttrs.SIZE;this.set_type=function(type){HEAP32[this.ptr+ExceptionInfoAttrs.TYPE_OFFSET>>2]=type};this.get_type=function(){return HEAP32[this.ptr+ExceptionInfoAttrs.TYPE_OFFSET>>2]};this.set_destructor=function(destructor){HEAP32[this.ptr+ExceptionInfoAttrs.DESTRUCTOR_OFFSET>>2]=destructor};this.get_destructor=function(){return HEAP32[this.ptr+ExceptionInfoAttrs.DESTRUCTOR_OFFSET>>2]};this.set_refcount=function(refcount){HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=refcount};this.set_caught=function(caught){caught=caught?1:0;HEAP8[this.ptr+ExceptionInfoAttrs.CAUGHT_OFFSET>>0]=caught};this.get_caught=function(){return HEAP8[this.ptr+ExceptionInfoAttrs.CAUGHT_OFFSET>>0]!=0};this.set_rethrown=function(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+ExceptionInfoAttrs.RETHROWN_OFFSET>>0]=rethrown};this.get_rethrown=function(){return HEAP8[this.ptr+ExceptionInfoAttrs.RETHROWN_OFFSET>>0]!=0};this.init=function(type,destructor){this.set_type(type);this.set_destructor(destructor);this.set_refcount(0);this.set_caught(false);this.set_rethrown(false)};this.add_ref=function(){var value=HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2];HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=value+1};this.release_ref=function(){var prev=HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2];HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=prev-1;return prev===1}}var exceptionLast=0;function __ZSt18uncaught_exceptionv(){return __ZSt18uncaught_exceptionv.uncaught_exceptions>0}function ___cxa_throw(ptr,type,destructor){var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;if(!("uncaught_exception"in __ZSt18uncaught_exceptionv)){__ZSt18uncaught_exceptionv.uncaught_exceptions=1}else{__ZSt18uncaught_exceptionv.uncaught_exceptions++}throw ptr}function getShiftFromSize(size){switch(size){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+size)}}function embind_init_charCodes(){var codes=new Array(256);for(var i=0;i<256;++i){codes[i]=String.fromCharCode(i)}embind_charCodes=codes}var embind_charCodes=undefined;function readLatin1String(ptr){var ret="";var c=ptr;while(HEAPU8[c]){ret+=embind_charCodes[HEAPU8[c++]]}return ret}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var char_0=48;var char_9=57;function makeLegalFunctionName(name){if(undefined===name){return"_unknown"}name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return"_"+name}else{return name}}function createNamedFunction(name,body){name=makeLegalFunctionName(name);return new Function("body","return function "+name+"() {\n"+' "use strict";'+" return body.apply(this, arguments);\n"+"};\n")(body)}function extendError(baseErrorType,errorName){var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return this.name+": "+this.message}};return errorClass}var BindingError=undefined;function throwBindingError(message){throw new BindingError(message)}var InternalError=undefined;function throwInternalError(message){throw new InternalError(message)}function whenDependentTypesAreResolved(myTypes,dependentTypes,getTypeConverters){myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i>shift])},destructorFunction:null})}var emval_free_list=[];var emval_handle_array=[{},{value:undefined},{value:null},{value:true},{value:false}];function __emval_decref(handle){if(handle>4&&0===--emval_handle_array[handle].refcount){emval_handle_array[handle]=undefined;emval_free_list.push(handle)}}function count_emval_handles(){var count=0;for(var i=5;i>2])}function __embind_register_emval(rawType,name){name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(handle){var rv=emval_handle_array[handle].value;__emval_decref(handle);return rv},"toWireType":function(destructors,value){return __emval_register(value)},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:null})}function _embind_repr(v){if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}}function floatReadValueFromPointer(name,shift){switch(shift){case 2:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 3:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError("Unknown float type: "+name)}}function __embind_register_float(rawType,name,size){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(value){return value},"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}return value},"argPackAdvance":8,"readValueFromPointer":floatReadValueFromPointer(name,shift),destructorFunction:null})}function new_(constructor,argumentList){if(!(constructor instanceof Function)){throw new TypeError("new_ called with constructor type "+typeof constructor+" which is not a function")}var dummy=createNamedFunction(constructor.name||"unknownFunctionName",function(){});dummy.prototype=constructor.prototype;var obj=new dummy;var r=constructor.apply(obj,argumentList);return r instanceof Object?r:obj}function runDestructors(destructors){while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=false;for(var i=1;i0?", ":"")+argsListWired}invokerFnBody+=(returns?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i>2)+i])}return array}function replacePublicSymbol(name,value,numArguments){if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}}function embind__requireFunction(signature,rawFunction){signature=readLatin1String(signature);function makeDynCaller(dynCall){var args=[];for(var i=1;i>1]}:function readU16FromPointer(pointer){return HEAPU16[pointer>>1]};case 2:return signed?function readS32FromPointer(pointer){return HEAP32[pointer>>2]}:function readU32FromPointer(pointer){return HEAPU32[pointer>>2]};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_integer(primitiveType,name,size,minRange,maxRange){name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var shift=getShiftFromSize(size);var fromWireType=function(value){return value};if(minRange===0){var bitshift=32-8*size;fromWireType=function(value){return value<>>bitshift}}var isUnsignedType=name.indexOf("unsigned")!=-1;registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}if(valuemaxRange){throw new TypeError('Passing a number "'+_embind_repr(value)+'" from JS side to C/C++ side to an argument of type "'+name+'", which is outside the valid range ['+minRange+", "+maxRange+"]!")}return isUnsignedType?value>>>0:value|0},"argPackAdvance":8,"readValueFromPointer":integerReadValueFromPointer(name,shift,minRange!==0),destructorFunction:null})}function __embind_register_memory_view(rawType,dataTypeIndex,name){var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){handle=handle>>2;var heap=HEAPU32;var size=heap[handle];var data=heap[handle+1];return new TA(buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":8,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})}function __embind_register_std_string(rawType,name){name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var str;if(stdStringIsUTF8){var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr+4,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+4+i]=charCode}}else{for(var i=0;i>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":function(destructors,value){if(!(typeof value==="string")){throwBindingError("Cannot pass non-string to C++ string type "+name)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:function(ptr){_free(ptr)}})}function __embind_register_void(rawType,name){name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":function(){return undefined},"toWireType":function(destructors,o){return undefined}})}function requireHandle(handle){if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handle_array[handle].value}function requireRegisteredType(rawType,humanName){var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl}function __emval_as(handle,returnType,destructorsRef){handle=requireHandle(handle);returnType=requireRegisteredType(returnType,"emval::as");var destructors=[];var rd=__emval_register(destructors);HEAP32[destructorsRef>>2]=rd;return returnType["toWireType"](destructors,handle)}function __emval_allocateDestructors(destructorsRef){var destructors=[];HEAP32[destructorsRef>>2]=__emval_register(destructors);return destructors}var emval_symbols={};function getStringOrSymbol(address){var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}else{return symbol}}var emval_methodCallers=[];function __emval_call_method(caller,handle,methodName,destructorsRef,args){caller=emval_methodCallers[caller];handle=requireHandle(handle);methodName=getStringOrSymbol(methodName);return caller(handle,methodName,__emval_allocateDestructors(destructorsRef),args)}function __emval_call_void_method(caller,handle,methodName,args){caller=emval_methodCallers[caller];handle=requireHandle(handle);methodName=getStringOrSymbol(methodName);caller(handle,methodName,null,args)}function emval_get_global(){if(typeof globalThis==="object"){return globalThis}return function(){return Function}()("return this")()}function __emval_get_global(name){if(name===0){return __emval_register(emval_get_global())}else{name=getStringOrSymbol(name);return __emval_register(emval_get_global()[name])}}function __emval_addMethodCaller(caller){var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id}function __emval_lookupTypes(argCount,argTypes){var a=new Array(argCount);for(var i=0;i>2)+i],"parameter "+i)}return a}function __emval_get_method_caller(argCount,argTypes){var types=__emval_lookupTypes(argCount,argTypes);var retType=types[0];var signatureName=retType.name+"_$"+types.slice(1).map(function(t){return t.name}).join("_")+"$";var params=["retType"];var args=[retType];var argsList="";for(var i=0;i4){emval_handle_array[handle].refcount+=1}}function __emval_instanceof(object,constructor){object=requireHandle(object);constructor=requireHandle(constructor);return object instanceof constructor}function __emval_new_array(){return __emval_register([])}function __emval_new_cstring(v){return __emval_register(getStringOrSymbol(v))}function __emval_new_object(){return __emval_register({})}function __emval_run_destructors(handle){var destructors=emval_handle_array[handle].value;runDestructors(destructors);__emval_decref(handle)}function __emval_set_property(handle,key,value){handle=requireHandle(handle);key=requireHandle(key);value=requireHandle(value);handle[key]=value}function __emval_take_value(type,argv){type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](argv);return __emval_register(v)}function _abort(){abort()}function _emscripten_get_sbrk_ptr(){return 54560}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function _emscripten_get_heap_size(){return HEAPU8.length}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){requestedSize=requestedSize>>>0;var oldSize=_emscripten_get_heap_size();var PAGE_MULTIPLE=65536;var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}var minHeapSize=16777216;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(minHeapSize,requestedSize,overGrownHeapSize),PAGE_MULTIPLE));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var readAsmConstArgsArray=[];function readAsmConstArgs(sigPtr,buf){readAsmConstArgsArray.length=0;var ch;buf>>=2;while(ch=HEAPU8[sigPtr++]){var double=ch<105;if(double&&buf&1)buf++;readAsmConstArgsArray.push(double?HEAPF64[buf++>>1]:HEAP32[buf]);++buf}return readAsmConstArgsArray}embind_init_charCodes();BindingError=Module["BindingError"]=extendError(Error,"BindingError");InternalError=Module["InternalError"]=extendError(Error,"InternalError");init_emval();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");var ASSERTIONS=false;var asmLibraryArg={"__cxa_allocate_exception":___cxa_allocate_exception,"__cxa_atexit":___cxa_atexit,"__cxa_throw":___cxa_throw,"_embind_register_bool":__embind_register_bool,"_embind_register_emval":__embind_register_emval,"_embind_register_float":__embind_register_float,"_embind_register_function":__embind_register_function,"_embind_register_integer":__embind_register_integer,"_embind_register_memory_view":__embind_register_memory_view,"_embind_register_std_string":__embind_register_std_string,"_embind_register_std_wstring":__embind_register_std_wstring,"_embind_register_void":__embind_register_void,"_emval_as":__emval_as,"_emval_call_method":__emval_call_method,"_emval_call_void_method":__emval_call_void_method,"_emval_decref":__emval_decref,"_emval_get_global":__emval_get_global,"_emval_get_method_caller":__emval_get_method_caller,"_emval_get_property":__emval_get_property,"_emval_incref":__emval_incref,"_emval_instanceof":__emval_instanceof,"_emval_new_array":__emval_new_array,"_emval_new_cstring":__emval_new_cstring,"_emval_new_object":__emval_new_object,"_emval_run_destructors":__emval_run_destructors,"_emval_set_property":__emval_set_property,"_emval_take_value":__emval_take_value,"abort":_abort,"emscripten_asm_const_iii":_emscripten_asm_const_iii,"emscripten_get_sbrk_ptr":_emscripten_get_sbrk_ptr,"emscripten_memcpy_big":_emscripten_memcpy_big,"emscripten_resize_heap":_emscripten_resize_heap,"memory":wasmMemory,"table":wasmTable};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["__wasm_call_ctors"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["malloc"]).apply(null,arguments)};var _loop=Module["_loop"]=function(){return(_loop=Module["_loop"]=Module["asm"]["loop"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["__errno_location"]).apply(null,arguments)};var ___getTypeName=Module["___getTypeName"]=function(){return(___getTypeName=Module["___getTypeName"]=Module["asm"]["__getTypeName"]).apply(null,arguments)};var ___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=function(){return(___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=Module["asm"]["__embind_register_native_and_builtin_types"]).apply(null,arguments)};var _setThrew=Module["_setThrew"]=function(){return(_setThrew=Module["_setThrew"]=Module["asm"]["setThrew"]).apply(null,arguments)};var stackSave=Module["stackSave"]=function(){return(stackSave=Module["stackSave"]=Module["asm"]["stackSave"]).apply(null,arguments)};var stackRestore=Module["stackRestore"]=function(){return(stackRestore=Module["stackRestore"]=Module["asm"]["stackRestore"]).apply(null,arguments)};var stackAlloc=Module["stackAlloc"]=function(){return(stackAlloc=Module["stackAlloc"]=Module["asm"]["stackAlloc"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["free"]).apply(null,arguments)};var dynCall_ii=Module["dynCall_ii"]=function(){return(dynCall_ii=Module["dynCall_ii"]=Module["asm"]["dynCall_ii"]).apply(null,arguments)};var dynCall_vi=Module["dynCall_vi"]=function(){return(dynCall_vi=Module["dynCall_vi"]=Module["asm"]["dynCall_vi"]).apply(null,arguments)};var dynCall_v=Module["dynCall_v"]=function(){return(dynCall_v=Module["dynCall_v"]=Module["asm"]["dynCall_v"]).apply(null,arguments)};var dynCall_iiii=Module["dynCall_iiii"]=function(){return(dynCall_iiii=Module["dynCall_iiii"]=Module["asm"]["dynCall_iiii"]).apply(null,arguments)};var dynCall_iidiiii=Module["dynCall_iidiiii"]=function(){return(dynCall_iidiiii=Module["dynCall_iidiiii"]=Module["asm"]["dynCall_iidiiii"]).apply(null,arguments)};var dynCall_vii=Module["dynCall_vii"]=function(){return(dynCall_vii=Module["dynCall_vii"]=Module["asm"]["dynCall_vii"]).apply(null,arguments)};var dynCall_viiiiii=Module["dynCall_viiiiii"]=function(){return(dynCall_viiiiii=Module["dynCall_viiiiii"]=Module["asm"]["dynCall_viiiiii"]).apply(null,arguments)};var dynCall_viiiii=Module["dynCall_viiiii"]=function(){return(dynCall_viiiii=Module["dynCall_viiiii"]=Module["asm"]["dynCall_viiiii"]).apply(null,arguments)};var dynCall_viiii=Module["dynCall_viiii"]=function(){return(dynCall_viiii=Module["dynCall_viiii"]=Module["asm"]["dynCall_viiii"]).apply(null,arguments)};var __growWasmMemory=Module["__growWasmMemory"]=function(){return(__growWasmMemory=Module["__growWasmMemory"]=Module["asm"]["__growWasmMemory"]).apply(null,arguments)};var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0)return;function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}noExitRuntime=true;run(); +var Module=typeof Module!=="undefined"?Module:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function shell_read(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function readBinary(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function readAsync(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var STACK_ALIGN=16;function dynamicAlloc(size){var ret=HEAP32[DYNAMICTOP_PTR>>2];var end=ret+size+15&-16;HEAP32[DYNAMICTOP_PTR>>2]=end;return ret}function getNativeTypeSize(type){switch(type){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:{if(type[type.length-1]==="*"){return 4}else if(type[0]==="i"){var bits=Number(type.substr(1));assert(bits%8===0,"getNativeTypeSize invalid bits "+bits+", type "+type);return bits/8}else{return 0}}}}function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}function convertJsFunctionToWasm(func,sig){if(typeof WebAssembly.Function==="function"){var typeNames={"i":"i32","j":"i64","f":"f32","d":"f64"};var type={parameters:[],results:sig[0]=="v"?[]:[typeNames[sig[0]]]};for(var i=1;i>0]=value;break;case"i8":HEAP8[ptr>>0]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":tempI64=[value>>>0,(tempDouble=value,+Math_abs(tempDouble)>=1?tempDouble>0?(Math_min(+Math_floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math_ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[ptr>>2]=tempI64[0],HEAP32[ptr+4>>2]=tempI64[1];break;case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;default:abort("invalid type for setValue: "+type)}}var wasmMemory;var wasmTable=new WebAssembly.Table({"initial":555,"maximum":555+0,"element":"anyfunc"});var ABORT=false;var EXITSTATUS=0;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}function getCFunc(ident){var func=Module["_"+ident];assert(func,"Cannot call unknown function "+ident+", make sure it is exported");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={"string":function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},"array":function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string")return UTF8ToString(ret);if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}var UTF16Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf-16le"):undefined;function UTF16ToString(ptr,maxBytesToRead){var endPtr=ptr;var idx=endPtr>>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder){return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr))}else{var i=0;var str="";while(1){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0||i==maxBytesToRead/2)return str;++i;str+=String.fromCharCode(codeUnit)}}}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}var WASM_PAGE_SIZE=65536;function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var STACK_BASE=5299184,DYNAMIC_BASE=5299184,DYNAMICTOP_PTR=56144;var INITIAL_INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;if(Module["wasmMemory"]){wasmMemory=Module["wasmMemory"]}else{wasmMemory=new WebAssembly.Memory({"initial":INITIAL_INITIAL_MEMORY/WASM_PAGE_SIZE,"maximum":2147483648/WASM_PAGE_SIZE})}if(wasmMemory){buffer=wasmMemory.buffer}INITIAL_INITIAL_MEMORY=buffer.byteLength;updateGlobalBufferAndViews(buffer);HEAP32[DYNAMICTOP_PTR>>2]=DYNAMIC_BASE;function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){Module["dynCall_v"](func)}else{Module["dynCall_vi"](func,callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var Math_abs=Math.abs;var Math_ceil=Math.ceil;var Math_floor=Math.floor;var Math_min=Math.min;var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix="file://";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile="douwco_hivemind.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(){try{if(wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(wasmBinaryFile)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary()})}return new Promise(function(resolve,reject){resolve(getBinary())})}function createWasm(){var info={"env":asmLibraryArg,"wasi_snapshot_preview1":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiatedSource(output){receiveInstance(output["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync();return{}}var tempDouble;var tempI64;__ATINIT__.push({func:function(){___wasm_call_ctors()}});function demangle(func){return func}function demangleAll(text){var regex=/\b_Z[\w\d_]+/g;return text.replace(regex,function(x){var y=demangle(x);return x===y?x:y+" ["+x+"]"})}function jsStackTrace(){var err=new Error;if(!err.stack){try{throw new Error}catch(e){err=e}if(!err.stack){return"(no stack trace available)"}}return err.stack.toString()}var ExceptionInfoAttrs={DESTRUCTOR_OFFSET:0,REFCOUNT_OFFSET:4,TYPE_OFFSET:8,CAUGHT_OFFSET:12,RETHROWN_OFFSET:13,SIZE:16};function ___cxa_allocate_exception(size){return _malloc(size+ExceptionInfoAttrs.SIZE)+ExceptionInfoAttrs.SIZE}function _atexit(func,arg){}function ___cxa_atexit(a0,a1){return _atexit(a0,a1)}function ExceptionInfo(excPtr){this.excPtr=excPtr;this.ptr=excPtr-ExceptionInfoAttrs.SIZE;this.set_type=function(type){HEAP32[this.ptr+ExceptionInfoAttrs.TYPE_OFFSET>>2]=type};this.get_type=function(){return HEAP32[this.ptr+ExceptionInfoAttrs.TYPE_OFFSET>>2]};this.set_destructor=function(destructor){HEAP32[this.ptr+ExceptionInfoAttrs.DESTRUCTOR_OFFSET>>2]=destructor};this.get_destructor=function(){return HEAP32[this.ptr+ExceptionInfoAttrs.DESTRUCTOR_OFFSET>>2]};this.set_refcount=function(refcount){HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=refcount};this.set_caught=function(caught){caught=caught?1:0;HEAP8[this.ptr+ExceptionInfoAttrs.CAUGHT_OFFSET>>0]=caught};this.get_caught=function(){return HEAP8[this.ptr+ExceptionInfoAttrs.CAUGHT_OFFSET>>0]!=0};this.set_rethrown=function(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+ExceptionInfoAttrs.RETHROWN_OFFSET>>0]=rethrown};this.get_rethrown=function(){return HEAP8[this.ptr+ExceptionInfoAttrs.RETHROWN_OFFSET>>0]!=0};this.init=function(type,destructor){this.set_type(type);this.set_destructor(destructor);this.set_refcount(0);this.set_caught(false);this.set_rethrown(false)};this.add_ref=function(){var value=HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2];HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=value+1};this.release_ref=function(){var prev=HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2];HEAP32[this.ptr+ExceptionInfoAttrs.REFCOUNT_OFFSET>>2]=prev-1;return prev===1}}var exceptionLast=0;function __ZSt18uncaught_exceptionv(){return __ZSt18uncaught_exceptionv.uncaught_exceptions>0}function ___cxa_throw(ptr,type,destructor){var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;if(!("uncaught_exception"in __ZSt18uncaught_exceptionv)){__ZSt18uncaught_exceptionv.uncaught_exceptions=1}else{__ZSt18uncaught_exceptionv.uncaught_exceptions++}throw ptr}function getShiftFromSize(size){switch(size){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+size)}}function embind_init_charCodes(){var codes=new Array(256);for(var i=0;i<256;++i){codes[i]=String.fromCharCode(i)}embind_charCodes=codes}var embind_charCodes=undefined;function readLatin1String(ptr){var ret="";var c=ptr;while(HEAPU8[c]){ret+=embind_charCodes[HEAPU8[c++]]}return ret}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var char_0=48;var char_9=57;function makeLegalFunctionName(name){if(undefined===name){return"_unknown"}name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return"_"+name}else{return name}}function createNamedFunction(name,body){name=makeLegalFunctionName(name);return new Function("body","return function "+name+"() {\n"+' "use strict";'+" return body.apply(this, arguments);\n"+"};\n")(body)}function extendError(baseErrorType,errorName){var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return this.name+": "+this.message}};return errorClass}var BindingError=undefined;function throwBindingError(message){throw new BindingError(message)}var InternalError=undefined;function throwInternalError(message){throw new InternalError(message)}function whenDependentTypesAreResolved(myTypes,dependentTypes,getTypeConverters){myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i>shift])},destructorFunction:null})}var emval_free_list=[];var emval_handle_array=[{},{value:undefined},{value:null},{value:true},{value:false}];function __emval_decref(handle){if(handle>4&&0===--emval_handle_array[handle].refcount){emval_handle_array[handle]=undefined;emval_free_list.push(handle)}}function count_emval_handles(){var count=0;for(var i=5;i>2])}function __embind_register_emval(rawType,name){name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(handle){var rv=emval_handle_array[handle].value;__emval_decref(handle);return rv},"toWireType":function(destructors,value){return __emval_register(value)},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:null})}function _embind_repr(v){if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}}function floatReadValueFromPointer(name,shift){switch(shift){case 2:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 3:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError("Unknown float type: "+name)}}function __embind_register_float(rawType,name,size){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(value){return value},"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}return value},"argPackAdvance":8,"readValueFromPointer":floatReadValueFromPointer(name,shift),destructorFunction:null})}function new_(constructor,argumentList){if(!(constructor instanceof Function)){throw new TypeError("new_ called with constructor type "+typeof constructor+" which is not a function")}var dummy=createNamedFunction(constructor.name||"unknownFunctionName",function(){});dummy.prototype=constructor.prototype;var obj=new dummy;var r=constructor.apply(obj,argumentList);return r instanceof Object?r:obj}function runDestructors(destructors){while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=false;for(var i=1;i0?", ":"")+argsListWired}invokerFnBody+=(returns?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i>2)+i])}return array}function replacePublicSymbol(name,value,numArguments){if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}}function embind__requireFunction(signature,rawFunction){signature=readLatin1String(signature);function makeDynCaller(dynCall){var args=[];for(var i=1;i>1]}:function readU16FromPointer(pointer){return HEAPU16[pointer>>1]};case 2:return signed?function readS32FromPointer(pointer){return HEAP32[pointer>>2]}:function readU32FromPointer(pointer){return HEAPU32[pointer>>2]};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_integer(primitiveType,name,size,minRange,maxRange){name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var shift=getShiftFromSize(size);var fromWireType=function(value){return value};if(minRange===0){var bitshift=32-8*size;fromWireType=function(value){return value<>>bitshift}}var isUnsignedType=name.indexOf("unsigned")!=-1;registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":function(destructors,value){if(typeof value!=="number"&&typeof value!=="boolean"){throw new TypeError('Cannot convert "'+_embind_repr(value)+'" to '+this.name)}if(valuemaxRange){throw new TypeError('Passing a number "'+_embind_repr(value)+'" from JS side to C/C++ side to an argument of type "'+name+'", which is outside the valid range ['+minRange+", "+maxRange+"]!")}return isUnsignedType?value>>>0:value|0},"argPackAdvance":8,"readValueFromPointer":integerReadValueFromPointer(name,shift,minRange!==0),destructorFunction:null})}function __embind_register_memory_view(rawType,dataTypeIndex,name){var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){handle=handle>>2;var heap=HEAPU32;var size=heap[handle];var data=heap[handle+1];return new TA(buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":8,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})}function __embind_register_std_string(rawType,name){name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var str;if(stdStringIsUTF8){var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr+4,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+4+i]=charCode}}else{for(var i=0;i>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":function(destructors,value){if(!(typeof value==="string")){throwBindingError("Cannot pass non-string to C++ string type "+name)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:function(ptr){_free(ptr)}})}function __embind_register_void(rawType,name){name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":function(){return undefined},"toWireType":function(destructors,o){return undefined}})}function requireHandle(handle){if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handle_array[handle].value}function requireRegisteredType(rawType,humanName){var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl}function __emval_as(handle,returnType,destructorsRef){handle=requireHandle(handle);returnType=requireRegisteredType(returnType,"emval::as");var destructors=[];var rd=__emval_register(destructors);HEAP32[destructorsRef>>2]=rd;return returnType["toWireType"](destructors,handle)}function __emval_allocateDestructors(destructorsRef){var destructors=[];HEAP32[destructorsRef>>2]=__emval_register(destructors);return destructors}var emval_symbols={};function getStringOrSymbol(address){var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}else{return symbol}}var emval_methodCallers=[];function __emval_call_method(caller,handle,methodName,destructorsRef,args){caller=emval_methodCallers[caller];handle=requireHandle(handle);methodName=getStringOrSymbol(methodName);return caller(handle,methodName,__emval_allocateDestructors(destructorsRef),args)}function __emval_call_void_method(caller,handle,methodName,args){caller=emval_methodCallers[caller];handle=requireHandle(handle);methodName=getStringOrSymbol(methodName);caller(handle,methodName,null,args)}function emval_get_global(){if(typeof globalThis==="object"){return globalThis}return function(){return Function}()("return this")()}function __emval_get_global(name){if(name===0){return __emval_register(emval_get_global())}else{name=getStringOrSymbol(name);return __emval_register(emval_get_global()[name])}}function __emval_addMethodCaller(caller){var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id}function __emval_lookupTypes(argCount,argTypes){var a=new Array(argCount);for(var i=0;i>2)+i],"parameter "+i)}return a}function __emval_get_method_caller(argCount,argTypes){var types=__emval_lookupTypes(argCount,argTypes);var retType=types[0];var signatureName=retType.name+"_$"+types.slice(1).map(function(t){return t.name}).join("_")+"$";var params=["retType"];var args=[retType];var argsList="";for(var i=0;i4){emval_handle_array[handle].refcount+=1}}function __emval_instanceof(object,constructor){object=requireHandle(object);constructor=requireHandle(constructor);return object instanceof constructor}function __emval_new_array(){return __emval_register([])}function __emval_new_cstring(v){return __emval_register(getStringOrSymbol(v))}function __emval_new_object(){return __emval_register({})}function __emval_run_destructors(handle){var destructors=emval_handle_array[handle].value;runDestructors(destructors);__emval_decref(handle)}function __emval_set_property(handle,key,value){handle=requireHandle(handle);key=requireHandle(key);value=requireHandle(value);handle[key]=value}function __emval_take_value(type,argv){type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](argv);return __emval_register(v)}function _abort(){abort()}function _emscripten_get_sbrk_ptr(){return 56144}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function _emscripten_get_heap_size(){return HEAPU8.length}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){requestedSize=requestedSize>>>0;var oldSize=_emscripten_get_heap_size();var PAGE_MULTIPLE=65536;var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}var minHeapSize=16777216;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(minHeapSize,requestedSize,overGrownHeapSize),PAGE_MULTIPLE));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}embind_init_charCodes();BindingError=Module["BindingError"]=extendError(Error,"BindingError");InternalError=Module["InternalError"]=extendError(Error,"InternalError");init_emval();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");var ASSERTIONS=false;var asmLibraryArg={"__cxa_allocate_exception":___cxa_allocate_exception,"__cxa_atexit":___cxa_atexit,"__cxa_throw":___cxa_throw,"_embind_register_bool":__embind_register_bool,"_embind_register_emval":__embind_register_emval,"_embind_register_float":__embind_register_float,"_embind_register_function":__embind_register_function,"_embind_register_integer":__embind_register_integer,"_embind_register_memory_view":__embind_register_memory_view,"_embind_register_std_string":__embind_register_std_string,"_embind_register_std_wstring":__embind_register_std_wstring,"_embind_register_void":__embind_register_void,"_emval_as":__emval_as,"_emval_call_method":__emval_call_method,"_emval_call_void_method":__emval_call_void_method,"_emval_decref":__emval_decref,"_emval_get_global":__emval_get_global,"_emval_get_method_caller":__emval_get_method_caller,"_emval_get_property":__emval_get_property,"_emval_incref":__emval_incref,"_emval_instanceof":__emval_instanceof,"_emval_new_array":__emval_new_array,"_emval_new_cstring":__emval_new_cstring,"_emval_new_object":__emval_new_object,"_emval_run_destructors":__emval_run_destructors,"_emval_set_property":__emval_set_property,"_emval_take_value":__emval_take_value,"abort":_abort,"emscripten_get_sbrk_ptr":_emscripten_get_sbrk_ptr,"emscripten_memcpy_big":_emscripten_memcpy_big,"emscripten_resize_heap":_emscripten_resize_heap,"memory":wasmMemory,"table":wasmTable};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["__wasm_call_ctors"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["malloc"]).apply(null,arguments)};var _loop=Module["_loop"]=function(){return(_loop=Module["_loop"]=Module["asm"]["loop"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["__errno_location"]).apply(null,arguments)};var ___getTypeName=Module["___getTypeName"]=function(){return(___getTypeName=Module["___getTypeName"]=Module["asm"]["__getTypeName"]).apply(null,arguments)};var ___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=function(){return(___embind_register_native_and_builtin_types=Module["___embind_register_native_and_builtin_types"]=Module["asm"]["__embind_register_native_and_builtin_types"]).apply(null,arguments)};var _setThrew=Module["_setThrew"]=function(){return(_setThrew=Module["_setThrew"]=Module["asm"]["setThrew"]).apply(null,arguments)};var stackSave=Module["stackSave"]=function(){return(stackSave=Module["stackSave"]=Module["asm"]["stackSave"]).apply(null,arguments)};var stackRestore=Module["stackRestore"]=function(){return(stackRestore=Module["stackRestore"]=Module["asm"]["stackRestore"]).apply(null,arguments)};var stackAlloc=Module["stackAlloc"]=function(){return(stackAlloc=Module["stackAlloc"]=Module["asm"]["stackAlloc"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["free"]).apply(null,arguments)};var dynCall_ii=Module["dynCall_ii"]=function(){return(dynCall_ii=Module["dynCall_ii"]=Module["asm"]["dynCall_ii"]).apply(null,arguments)};var dynCall_vi=Module["dynCall_vi"]=function(){return(dynCall_vi=Module["dynCall_vi"]=Module["asm"]["dynCall_vi"]).apply(null,arguments)};var dynCall_v=Module["dynCall_v"]=function(){return(dynCall_v=Module["dynCall_v"]=Module["asm"]["dynCall_v"]).apply(null,arguments)};var dynCall_iiii=Module["dynCall_iiii"]=function(){return(dynCall_iiii=Module["dynCall_iiii"]=Module["asm"]["dynCall_iiii"]).apply(null,arguments)};var dynCall_iidiiii=Module["dynCall_iidiiii"]=function(){return(dynCall_iidiiii=Module["dynCall_iidiiii"]=Module["asm"]["dynCall_iidiiii"]).apply(null,arguments)};var dynCall_vii=Module["dynCall_vii"]=function(){return(dynCall_vii=Module["dynCall_vii"]=Module["asm"]["dynCall_vii"]).apply(null,arguments)};var dynCall_viiiiii=Module["dynCall_viiiiii"]=function(){return(dynCall_viiiiii=Module["dynCall_viiiiii"]=Module["asm"]["dynCall_viiiiii"]).apply(null,arguments)};var dynCall_viiiii=Module["dynCall_viiiii"]=function(){return(dynCall_viiiii=Module["dynCall_viiiii"]=Module["asm"]["dynCall_viiiii"]).apply(null,arguments)};var dynCall_viiii=Module["dynCall_viiii"]=function(){return(dynCall_viiii=Module["dynCall_viiii"]=Module["asm"]["dynCall_viiii"]).apply(null,arguments)};var __growWasmMemory=Module["__growWasmMemory"]=function(){return(__growWasmMemory=Module["__growWasmMemory"]=Module["asm"]["__growWasmMemory"]).apply(null,arguments)};var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0)return;function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}noExitRuntime=true;run(); return Module.ready diff --git a/dist/douwco_hivemind_module.wasm b/dist/douwco_hivemind_module.wasm index f2793af..df9b4a8 100644 Binary files a/dist/douwco_hivemind_module.wasm and b/dist/douwco_hivemind_module.wasm differ diff --git a/douwco_hivemind/include/Creeps/Creep.hpp b/douwco_hivemind/include/Creeps/Creep.hpp index d7269ef..4369015 100644 --- a/douwco_hivemind/include/Creeps/Creep.hpp +++ b/douwco_hivemind/include/Creeps/Creep.hpp @@ -2,9 +2,12 @@ #define DOUWCO_HIVEMIND_CREEP_HPP #include -#include -#include "Tools/JsonTool.hpp" -#include "Tools/PathTool.hpp" + +namespace Screeps{ + class RoomPosition; + class RoomObject; + class PathStep; +} namespace DouwcoHivemind { @@ -13,39 +16,26 @@ namespace DouwcoHivemind UNEMPLOYED, HARVESTER }; + class Creep { public: CreepRole role; std::string target_id; - std::vector path; protected: Screeps::Creep creep; JSON memory; public: - Creep(Screeps::Creep crp) : creep(crp), - memory(crp.memory()) - { - role = memory.contains("role") ? static_cast(memory["role"]) : CreepRole::UNEMPLOYED; - target_id = memory.contains("target_id") ? static_cast(memory["target_id"]) : std::string(); - path = memory.contains("path") ? unflattenPathSteps(jsonToVector(memory["path"])) : std::vector(); - } - virtual ~Creep() - { - memory["target_id"] = target_id; - memory["path"] = vectorToJson(flattenPathSteps(path)); - creep.setMemory(memory); - } - + Creep(Screeps::Creep crp); + virtual ~Creep(); virtual void loop() {} bool isNearTo(const Screeps::RoomPosition &pos, int dist); protected: void moveToTarget(int dist = 1); std::unique_ptr getRoomObjectTarget(); - bool isNearTo(const Screeps::RoomPosition &pos1, const Screeps::RoomPosition &pos2, int dist); }; } diff --git a/douwco_hivemind/include/Creeps/Harvester.hpp b/douwco_hivemind/include/Creeps/Harvester.hpp index 63ddd4c..8aa7006 100644 --- a/douwco_hivemind/include/Creeps/Harvester.hpp +++ b/douwco_hivemind/include/Creeps/Harvester.hpp @@ -1,10 +1,13 @@ #ifndef DOUWCO_HIVEMIND_HARVESTER_HPP #define DOUWCO_HIVEMIND_HARVESTER_HPP -#include #include "Creeps/Creep.hpp" +namespace { + class Creep; +} + namespace DouwcoHivemind { class HarvesterRole : public Creep @@ -14,17 +17,8 @@ namespace DouwcoHivemind int taskCounter; public: - HarvesterRole(Screeps::Creep crp) : Creep(crp) - { - harvesting = memory.contains("harvesting") ? static_cast(memory["harvesting"]) : false; - taskCounter = memory.contains("taskCounter") ? static_cast(memory["taskCounter"]) : 0; - } - - ~HarvesterRole() override - { - memory["harvesting"] = harvesting; - memory["taskCounter"] = taskCounter; - } + HarvesterRole(Screeps::Creep crp); + ~HarvesterRole() override; void loop() override; diff --git a/douwco_hivemind/include/Engine.hpp b/douwco_hivemind/include/Engine.hpp index 5a9ebf7..980a95c 100644 --- a/douwco_hivemind/include/Engine.hpp +++ b/douwco_hivemind/include/Engine.hpp @@ -2,20 +2,12 @@ #define DOUWCO_HIVEMIND_ENGINE_HPP #include -#include -#include -#include #include "Creeps/Creep.hpp" -#include "Creeps/Harvester.hpp" #include "Structures/Structure.hpp" -#include "Structures/Spawn.hpp" namespace DouwcoHivemind { - class Creep; - class Structure; - class Engine { private: @@ -23,50 +15,12 @@ namespace DouwcoHivemind std::vector> structures; public: - Engine() - { - ReadOutCreeps(); - ReadOutStructures(); - } - ~Engine() {} - - void loop() - { - for (auto &creep : creeps) - creep->loop(); - - for (auto &structure : structures) - structure->loop(); - } + Engine(); + void loop(); private: - void ReadOutCreeps() - { - auto src_creeps = Screeps::Game.creeps(); - for (auto &creep : src_creeps) - { - CreepRole role = creep.second.memory()["role"]; - switch (role) - { - case CreepRole::HARVESTER: - creeps.push_back(std::make_unique(creep.second)); - break; - case CreepRole::UNEMPLOYED: - default: - EM_ASM({console.log('Undefined role for creep' + $0)}, creep.first.c_str()); - break; - } - } - } - - void ReadOutStructures() - { - auto spawns = Screeps::Game.spawns(); - for (auto &spawn : spawns) - { - structures.push_back(std::make_unique(spawn.second)); - } - } + void ReadOutCreeps(); + void ReadOutStructures(); }; } diff --git a/douwco_hivemind/include/Rooms/Room.hpp b/douwco_hivemind/include/Rooms/Room.hpp new file mode 100644 index 0000000..0ef1f02 --- /dev/null +++ b/douwco_hivemind/include/Rooms/Room.hpp @@ -0,0 +1,15 @@ +#ifndef DOUWCO_HIVEMIND_ROOMS_HPP +#define DOUWCO_HIVEMIND_ROOMS_HPP + + +namespace DouwcoHivemind +{ + class Room + { + public: + Room(); + void loop(); + }; +} + +#endif // DOUWCO_HIVEMIND_ROOMS_HPP \ No newline at end of file diff --git a/douwco_hivemind/include/Tools/MeasureTool.hpp b/douwco_hivemind/include/Tools/MeasureTool.hpp new file mode 100644 index 0000000..ad3b29c --- /dev/null +++ b/douwco_hivemind/include/Tools/MeasureTool.hpp @@ -0,0 +1,19 @@ +#ifndef DOUWCO_HIVEMIND_MEASURE_TOOL_HPP +#define DOUWCO_HIVEMIND_MEASURE_TOOL_HPP + +#include + +namespace DouwcoHivemind +{ + static bool isNearTo(const Screeps::RoomPosition &pos1, const Screeps::RoomPosition &pos2, int dist) + { + int dx = pos1.x() - pos2.x(); + int dy = pos1.y() - pos2.y(); + int dist2 = dist * dist; + return dx * dx <= dist2 && + dy * dy <= dist2 && + pos1.roomName() == pos2.roomName(); + } +} // namespace Screeps + +#endif // DOUWCO_HIVEMIND_MEASURE_TOOL_HPP \ No newline at end of file diff --git a/douwco_hivemind/include/Tools/PathTool.hpp b/douwco_hivemind/include/Tools/PathTool.hpp index c70f161..c530879 100644 --- a/douwco_hivemind/include/Tools/PathTool.hpp +++ b/douwco_hivemind/include/Tools/PathTool.hpp @@ -6,7 +6,6 @@ namespace DouwcoHivemind { - static std::vector flattenPathSteps(const std::vector &pathSteps) { std::vector flattened; diff --git a/douwco_hivemind/src/Creep.cpp b/douwco_hivemind/src/Creep.cpp new file mode 100644 index 0000000..0fd0463 --- /dev/null +++ b/douwco_hivemind/src/Creep.cpp @@ -0,0 +1,139 @@ +#include + +#include +#include +#include +#include + +#include "Creeps/Creep.hpp" + +#include "Tools/JsonTool.hpp" +#include "Tools/PathTool.hpp" +#include "Tools/MeasureTool.hpp" + +DouwcoHivemind::Creep::Creep(Screeps::Creep crp) : creep(crp), + memory(crp.memory()) +{ + role = memory.contains("role") ? static_cast(memory["role"]) : CreepRole::UNEMPLOYED; + target_id = memory.contains("target_id") ? static_cast(memory["target_id"]) : std::string(); +} + +DouwcoHivemind::Creep::~Creep() +{ + memory["target_id"] = target_id; + creep.setMemory(memory); +} + +void DouwcoHivemind::Creep::moveToTarget(int dist) +{ + // Is move required? + auto target = getRoomObjectTarget(); + if (isNearTo(target->pos(), dist)) + { + memory.erase("path"); + return; + } + + // Is wating? + if (memory.contains("wait") && memory["wait"] > 0) + { + memory["wait"] = memory["wait"].get() - 1; + creep.say("Waiting.."); + return; + } + + // Is there a path to walk? + if (!memory.contains("path") || memory["path"].empty()) + { + creep.say("Searching route!"); + auto target_pos = target->pos(); + auto path = creep.room().findPath(creep.pos(), target_pos); + auto last = path.back(); + if (last.x - target_pos.x() > dist || last.y - target_pos.y() > dist) + { + creep.say("No possible path"); + memory["wait"] = rand() % 20; + return; + } + memory["path"] = vectorToJson(flattenPathSteps(path)); + } + + // JS::console.log(std::string("creep pos: [") + + // std::to_string(creep.pos().x()) + + // std::string(",") + + // std::to_string(creep.pos().y()) + + // std::string("]")); + + // Get step from memory + int pathStepData[5] = {0}; + if (memory["path"].size() > 5) + { + for (int i = 0; i < 5; i++) + { + pathStepData[i] = memory["path"][i]; + } + } + else + { + memory.erase("path"); + return; + } + + // Is the move of last tick executed? + int x = creep.pos().x(); + int y = creep.pos().y(); + + auto step = Screeps::PathStep(pathStepData[0], pathStepData[1], pathStepData[2], pathStepData[3], pathStepData[4]); + + if (memory.contains("last_pos")) + { + int last_x = memory["last_pos"]["x"]; + int last_y = memory["last_pos"]["y"]; + memory.erase("last_pos"); + if (x == last_x && y == last_y) + { + creep.say("I'm stuck!"); + memory["wait"] = rand() % 5; + return; + } + } + + // Is the creep on the place intended by the path? + if (!(x == step.x - step.dx && y == step.y - step.dy)) + { + creep.say("I'm lost!"); + memory["wait"] = rand() % 5; + memory.erase("path"); + return; + } + + // Lets move forward + int resp = creep.move(step.direction); + if (resp == Screeps::OK) + { + memory["last_pos"]["x"] = x; + memory["last_pos"]["y"] = y; + + for (int i = 0; i < 5; i++) + { + memory["path"].erase(0); + } + } +} + +std::unique_ptr DouwcoHivemind::Creep::getRoomObjectTarget() +{ + // Check if game can find target + auto roomObj = Screeps::Game.getObjectById(target_id); + if (!roomObj) + { + JS::console.log(creep.name() + ": Game can\'t find target id"); + return nullptr; + } + return std::move(roomObj); +} + +bool DouwcoHivemind::Creep::isNearTo(const Screeps::RoomPosition &pos, int dist) +{ + return DouwcoHivemind::isNearTo(creep.pos(), pos, dist); +} \ No newline at end of file diff --git a/douwco_hivemind/src/Engine.cpp b/douwco_hivemind/src/Engine.cpp new file mode 100644 index 0000000..3e344e5 --- /dev/null +++ b/douwco_hivemind/src/Engine.cpp @@ -0,0 +1,48 @@ +#include + +#include "Engine.hpp" + +#include "Creeps/Harvester.hpp" +#include "Structures/Spawn.hpp" + +DouwcoHivemind::Engine::Engine() +{ + ReadOutCreeps(); + ReadOutStructures(); +} + +void DouwcoHivemind::Engine::loop() +{ + for (auto &creep : creeps) + creep->loop(); + + for (auto &structure : structures) + structure->loop(); +} + +void DouwcoHivemind::Engine::ReadOutCreeps() +{ + auto src_creeps = Screeps::Game.creeps(); + for (auto &creep : src_creeps) + { + CreepRole role = creep.second.memory()["role"]; + switch (role) + { + case CreepRole::HARVESTER: + creeps.push_back(std::make_unique(creep.second)); + break; + case CreepRole::UNEMPLOYED: + default: + break; + } + } +} + +void DouwcoHivemind::Engine::ReadOutStructures() +{ + auto spawns = Screeps::Game.spawns(); + for (auto &spawn : spawns) + { + structures.push_back(std::make_unique(spawn.second)); + } +} \ No newline at end of file diff --git a/douwco_hivemind/src/harvester.cpp b/douwco_hivemind/src/Harvester.cpp similarity index 93% rename from douwco_hivemind/src/harvester.cpp rename to douwco_hivemind/src/Harvester.cpp index 1fd562e..b8b719b 100644 --- a/douwco_hivemind/src/harvester.cpp +++ b/douwco_hivemind/src/Harvester.cpp @@ -18,6 +18,18 @@ #include "Creeps/Harvester.hpp" +DouwcoHivemind::HarvesterRole::HarvesterRole(Screeps::Creep crp) : Creep(crp) +{ + harvesting = memory.contains("harvesting") ? static_cast(memory["harvesting"]) : false; + taskCounter = memory.contains("taskCounter") ? static_cast(memory["taskCounter"]) : 0; +} + +DouwcoHivemind::HarvesterRole::~HarvesterRole() +{ + memory["harvesting"] = harvesting; + memory["taskCounter"] = taskCounter; +} + void DouwcoHivemind::HarvesterRole::loop() { if (harvesting) diff --git a/douwco_hivemind/src/loop.cpp b/douwco_hivemind/src/Loop.cpp similarity index 100% rename from douwco_hivemind/src/loop.cpp rename to douwco_hivemind/src/Loop.cpp diff --git a/douwco_hivemind/src/spawn.cpp b/douwco_hivemind/src/Spawn.cpp similarity index 62% rename from douwco_hivemind/src/spawn.cpp rename to douwco_hivemind/src/Spawn.cpp index 91bb011..508efa4 100644 --- a/douwco_hivemind/src/spawn.cpp +++ b/douwco_hivemind/src/Spawn.cpp @@ -1,9 +1,5 @@ -#include -#include #include #include -#include -#include #include "Creeps/Creep.hpp" #include "Structures/Spawn.hpp" @@ -13,16 +9,14 @@ void DouwcoHivemind::Spawn::loop() int creepcount = spawn.room().find(Screeps::FIND_MY_CREEPS).size(); if (creepcount > 10) { - EM_ASM({ console.log('To much creeps in this room'); }); return; } - EM_ASM({ console.log('Creating a harvester'); }); JSON opts; opts["memory"]["role"] = CreepRole::HARVESTER; int resp = spawn.spawnCreep( - {"work", "carry", "move"}, + {"work", "work", "carry", "move"}, "harvester" + std::to_string(Screeps::Game.time()), opts); } \ No newline at end of file diff --git a/douwco_hivemind/src/creep.cpp b/douwco_hivemind/src/creep.cpp deleted file mode 100644 index ab7b516..0000000 --- a/douwco_hivemind/src/creep.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include - -#include -#include -#include - -#include "Creeps/Creep.hpp" - -void DouwcoHivemind::Creep::moveToTarget(int dist) -{ - auto target = getRoomObjectTarget(); - - if (isNearTo(target->pos(), dist)) - return; - - if (path.size() == 0){ - path = creep.room().findPath(creep.pos(), target->pos()); - std::reverse(path.begin(), path.end()); - } - - JS::console.log(std::string("creep pos: [") + - std::to_string(creep.pos().x()) + - std::string(",") + - std::to_string(creep.pos().y()) + - std::string("]")); - - auto step = path.back(); - path.pop_back(); - - if (creep.pos().x() == step.x - step.dx && creep.pos().y() == step.y - step.dy) - { - int resp = creep.move(step.direction); - if(resp != Screeps::ERR_INVALID_ARGS) return; - } - - path.clear(); -} - -std::unique_ptr DouwcoHivemind::Creep::getRoomObjectTarget() -{ - // Check if game can find target - auto roomObj = Screeps::Game.getObjectById(target_id); - if (!roomObj) - { - JS::console.log(creep.name() + ": Game can\'t find target id"); - return nullptr; - } - return std::move(roomObj); -} - -bool DouwcoHivemind::Creep::isNearTo(const Screeps::RoomPosition &pos, int dist) -{ - return isNearTo(creep.pos(), pos, dist); -} - -bool DouwcoHivemind::Creep::isNearTo(const Screeps::RoomPosition &pos1, const Screeps::RoomPosition &pos2, int dist) -{ - int dx = pos1.x() - pos2.x(); - int dy = pos1.y() - pos2.y(); - int dist2 = dist * dist; - return dx * dx <= dist2 && - dy * dy <= dist2 && - pos1.roomName() == pos2.roomName(); -} \ No newline at end of file