minetest/builtin/game/forceloading.lua

80 lines
2.1 KiB
Lua
Raw Normal View History

2014-01-11 17:54:00 +01:00
-- Prevent anyone else accessing those functions
2014-04-28 03:02:48 +02:00
local forceload_block = core.forceload_block
local forceload_free_block = core.forceload_free_block
core.forceload_block = nil
core.forceload_free_block = nil
2014-01-11 17:54:00 +01:00
local blocks_forceloaded
local total_forceloaded = 0
local BLOCKSIZE = 16
local function get_blockpos(pos)
return {
x = math.floor(pos.x/BLOCKSIZE),
y = math.floor(pos.y/BLOCKSIZE),
z = math.floor(pos.z/BLOCKSIZE)}
end
2014-04-28 03:02:48 +02:00
function core.forceload_block(pos)
2014-01-11 17:54:00 +01:00
local blockpos = get_blockpos(pos)
2014-04-28 03:02:48 +02:00
local hash = core.hash_node_position(blockpos)
2014-01-11 17:54:00 +01:00
if blocks_forceloaded[hash] ~= nil then
blocks_forceloaded[hash] = blocks_forceloaded[hash] + 1
return true
else
2014-04-28 03:02:48 +02:00
if total_forceloaded >= (tonumber(core.setting_get("max_forceloaded_blocks")) or 16) then
2014-01-11 17:54:00 +01:00
return false
end
total_forceloaded = total_forceloaded+1
blocks_forceloaded[hash] = 1
forceload_block(blockpos)
return true
end
end
2014-04-28 03:02:48 +02:00
function core.forceload_free_block(pos)
2014-01-11 17:54:00 +01:00
local blockpos = get_blockpos(pos)
2014-04-28 03:02:48 +02:00
local hash = core.hash_node_position(blockpos)
2014-01-11 17:54:00 +01:00
if blocks_forceloaded[hash] == nil then return end
if blocks_forceloaded[hash] > 1 then
blocks_forceloaded[hash] = blocks_forceloaded[hash] - 1
else
total_forceloaded = total_forceloaded-1
blocks_forceloaded[hash] = nil
forceload_free_block(blockpos)
end
end
-- Keep the forceloaded areas after restart
2014-04-28 03:02:48 +02:00
local wpath = core.get_worldpath()
2014-01-11 17:54:00 +01:00
local function read_file(filename)
local f = io.open(filename, "r")
if f==nil then return {} end
local t = f:read("*all")
f:close()
if t=="" or t==nil then return {} end
return core.deserialize(t) or {}
2014-01-11 17:54:00 +01:00
end
local function write_file(filename, table)
local f = io.open(filename, "w")
2014-04-28 03:02:48 +02:00
f:write(core.serialize(table))
2014-01-11 17:54:00 +01:00
f:close()
end
blocks_forceloaded = read_file(wpath.."/force_loaded.txt")
for _, __ in pairs(blocks_forceloaded) do
total_forceloaded = total_forceloaded + 1
end
2014-04-28 03:02:48 +02:00
core.after(5, function()
2014-01-11 17:54:00 +01:00
for hash, _ in pairs(blocks_forceloaded) do
2014-04-28 03:02:48 +02:00
local blockpos = core.get_position_from_hash(hash)
2014-01-11 17:54:00 +01:00
forceload_block(blockpos)
end
end)
2014-04-28 03:02:48 +02:00
core.register_on_shutdown(function()
2014-01-11 17:54:00 +01:00
write_file(wpath.."/force_loaded.txt", blocks_forceloaded)
end)