1 -- Prevent anyone else accessing those functions
2 local forceload_block = core.forceload_block
3 local forceload_free_block = core.forceload_free_block
4 core.forceload_block = nil
5 core.forceload_free_block = nil
7 local blocks_forceloaded
8 local blocks_temploaded = {}
9 local total_forceloaded = 0
11 local BLOCKSIZE = core.MAP_BLOCKSIZE
12 local function get_blockpos(pos)
14 x = math.floor(pos.x/BLOCKSIZE),
15 y = math.floor(pos.y/BLOCKSIZE),
16 z = math.floor(pos.z/BLOCKSIZE)}
19 -- When we create/free a forceload, it's either transient or persistent. We want
20 -- to add to/remove from the table that corresponds to the type of forceload, but
21 -- we also need the other table because whether we forceload a block depends on
23 -- This function returns the "primary" table we are adding to/removing from, and
25 local function get_relevant_tables(transient)
27 return blocks_temploaded, blocks_forceloaded
29 return blocks_forceloaded, blocks_temploaded
33 function core.forceload_block(pos, transient)
34 local blockpos = get_blockpos(pos)
35 local hash = core.hash_node_position(blockpos)
36 local relevant_table, other_table = get_relevant_tables(transient)
37 if relevant_table[hash] ~= nil then
38 relevant_table[hash] = relevant_table[hash] + 1
40 elseif other_table[hash] ~= nil then
41 relevant_table[hash] = 1
43 if total_forceloaded >= (tonumber(core.setting_get("max_forceloaded_blocks")) or 16) then
46 total_forceloaded = total_forceloaded+1
47 relevant_table[hash] = 1
48 forceload_block(blockpos)
53 function core.forceload_free_block(pos, transient)
54 local blockpos = get_blockpos(pos)
55 local hash = core.hash_node_position(blockpos)
56 local relevant_table, other_table = get_relevant_tables(transient)
57 if relevant_table[hash] == nil then return end
58 if relevant_table[hash] > 1 then
59 relevant_table[hash] = relevant_table[hash] - 1
60 elseif other_table[hash] ~= nil then
61 relevant_table[hash] = nil
63 total_forceloaded = total_forceloaded-1
64 relevant_table[hash] = nil
65 forceload_free_block(blockpos)
69 -- Keep the forceloaded areas after restart
70 local wpath = core.get_worldpath()
71 local function read_file(filename)
72 local f = io.open(filename, "r")
73 if f==nil then return {} end
74 local t = f:read("*all")
76 if t=="" or t==nil then return {} end
77 return core.deserialize(t) or {}
80 local function write_file(filename, table)
81 local f = io.open(filename, "w")
82 f:write(core.serialize(table))
86 blocks_forceloaded = read_file(wpath.."/force_loaded.txt")
87 for _, __ in pairs(blocks_forceloaded) do
88 total_forceloaded = total_forceloaded + 1
91 core.after(5, function()
92 for hash, _ in pairs(blocks_forceloaded) do
93 local blockpos = core.get_position_from_hash(hash)
94 forceload_block(blockpos)
98 core.register_on_shutdown(function()
99 write_file(wpath.."/force_loaded.txt", blocks_forceloaded)