2024-04-06 19:09:54 +02:00
|
|
|
local storage = minetest.get_mod_storage()
|
|
|
|
local mod = mcl_minecarts
|
|
|
|
|
2024-04-07 14:27:53 +02:00
|
|
|
-- Imports
|
|
|
|
local CART_BLOCK_SIZE = mod.CART_BLOCK_SIZE
|
|
|
|
|
2024-04-06 19:09:54 +02:00
|
|
|
local cart_data = {}
|
|
|
|
local cart_data_fail_cache = {}
|
2024-04-07 14:27:53 +02:00
|
|
|
local cart_ids = storage:get_keys()
|
2024-04-06 19:09:54 +02:00
|
|
|
|
2024-04-07 14:27:53 +02:00
|
|
|
local function get_cart_data(uuid)
|
2024-04-06 19:09:54 +02:00
|
|
|
if cart_data[uuid] then return cart_data[uuid] end
|
|
|
|
if cart_data_fail_cache[uuid] then return nil end
|
|
|
|
|
|
|
|
local data = minetest.deserialize(storage:get_string("cart-"..uuid))
|
|
|
|
if not data then
|
|
|
|
cart_data_fail_cache[uuid] = true
|
|
|
|
return nil
|
2024-04-08 21:38:13 +02:00
|
|
|
else
|
|
|
|
-- Repair broken data
|
|
|
|
if not data.distance then data.distance = 0 end
|
|
|
|
if data.distance == 0/0 then data.distance = 0 end
|
|
|
|
if data.distance == -0/0 then data.distance = 0 end
|
|
|
|
data.dir = vector.new(data.dir)
|
|
|
|
data.connected_at = vector.new(data.connected_at)
|
2024-04-06 19:09:54 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
cart_data[uuid] = data
|
|
|
|
return data
|
|
|
|
end
|
2024-04-07 14:27:53 +02:00
|
|
|
mod.get_cart_data = get_cart_data
|
|
|
|
|
|
|
|
-- Preload all cart data into memory
|
|
|
|
for _,id in pairs(cart_ids) do
|
|
|
|
local uuid = string.sub(id,6)
|
|
|
|
get_cart_data(uuid)
|
|
|
|
end
|
|
|
|
|
2024-04-06 19:09:54 +02:00
|
|
|
local function save_cart_data(uuid)
|
|
|
|
if not cart_data[uuid] then return end
|
|
|
|
storage:set_string("cart-"..uuid,minetest.serialize(cart_data[uuid]))
|
|
|
|
end
|
|
|
|
mod.save_cart_data = save_cart_data
|
|
|
|
|
|
|
|
function mod.update_cart_data(data)
|
|
|
|
local uuid = data.uuid
|
|
|
|
cart_data[uuid] = data
|
|
|
|
cart_data_fail_cache[uuid] = nil
|
|
|
|
save_cart_data(uuid)
|
|
|
|
end
|
|
|
|
function mod.destroy_cart_data(uuid)
|
|
|
|
storage:set_string("cart-"..uuid,"")
|
|
|
|
cart_data[uuid] = nil
|
|
|
|
cart_data_fail_cache[uuid] = true
|
|
|
|
end
|
|
|
|
|
2024-04-09 22:52:11 +02:00
|
|
|
function mod.carts()
|
|
|
|
return pairs(cart_data)
|
|
|
|
end
|
|
|
|
|
2024-04-07 14:27:53 +02:00
|
|
|
function mod.find_carts_by_block_map(block_map)
|
|
|
|
local cart_list = {}
|
|
|
|
for _,data in pairs(cart_data) do
|
|
|
|
if data and data.connected_at then
|
|
|
|
local pos = mod.get_cart_position(data)
|
|
|
|
local block = vector.floor(vector.divide(pos,CART_BLOCK_SIZE))
|
|
|
|
if block_map[vector.to_string(block)] then
|
|
|
|
cart_list[#cart_list + 1] = data
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
return cart_list
|
|
|
|
end
|
|
|
|
|
2024-04-09 22:52:11 +02:00
|
|
|
minetest.register_on_shutdown(function()
|
|
|
|
for uuid,_ in pairs(cart_data) do
|
|
|
|
save_cart_data(uuid)
|
|
|
|
end
|
|
|
|
end)
|