Rename inventory_sync to player_sync

The plugin syncs more than inventories now (settings, appearance, recipe
notifications), so name it for what it does. The package becomes
@clusterio/plugin-player_sync and every inventory_sync identifier follows.

A migration entrypoint renames the inventory_sync config fields, including
load_plugin, and the inventory view permission. The plugin moves
inventories.json in the database directory to player_sync.json and
storage.inventory_sync in saves to storage.player_sync itself, and closes
dialogs left open under the old GUI names on startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-10-14 16:37:12 +00:00
1 parent e455d17bb7
commit 8363c5f0ef
39 files changed
+331 -177

No files matched your search

@@ -0,0 +1,30 @@
local compat = require("modules/clusterio/compat")
local keys = {
"show_alert_gui",
"show_controller_gui",
"show_crafting_queue",
"show_entity_info",
"show_entity_tooltip",
"show_hotkey_suggestions",
"show_map_view_options",
"show_minimap",
"show_quickbar",
"show_rail_block_visualisation",
"show_research_info",
"show_shortcut_bar",
"show_side_menu",
"show_tool_bar",
"update_entity_selection",
}
if compat.version_ge("2.0.22") then
keys[#keys + 1] = "show_surface_list"
end
if compat.version_ge("2.1.7") then
keys[#keys + 1] = "hide_tall_entities"
keys[#keys + 1] = "show_pins_gui"
end
return keys
@@ -0,0 +1,11 @@
local inventories = {
-- Armor must be before main or the sync will fail when the inventory
-- bonus slots from the armor are in use.
armor = defines.inventory.character_armor,
main = defines.inventory.character_main,
guns = defines.inventory.character_guns,
ammo = defines.inventory.character_ammo,
trash = defines.inventory.character_trash,
}
return inventories
@@ -0,0 +1,25 @@
local compat = require("modules/clusterio/compat")
local keys = {
"character_crafting_speed_modifier",
"character_mining_speed_modifier",
"character_additional_mining_categories",
"character_running_speed_modifier",
"character_build_distance_bonus",
"character_item_drop_distance_bonus",
"character_reach_distance_bonus",
"character_resource_reach_distance_bonus",
"character_item_pickup_distance_bonus",
"character_loot_pickup_distance_bonus",
"character_inventory_slots_bonus",
"character_trash_slot_count_bonus",
"character_maximum_following_robot_count_bonus",
"character_health_bonus",
"allow_dispatching_robots",
}
if compat.version_le("1.1.110") then
keys[#keys + 1] = "character_personal_logistic_requests_enabled"
end
return keys
@@ -0,0 +1,77 @@
local progress_dialog = require("modules/player_sync/gui/progress_dialog")
local ensure_character = require("modules/player_sync/ensure_character")
local restore_position = require("modules/player_sync/restore_position")
local get_script_data = require("modules/player_sync/get_script_data")
local function download_inventory(player_name, data, number, total)
local player = game.get_player(player_name)
if player == nil then
rcon.print("Player " .. player_name .. " does not exist")
return
end
local script_data = get_script_data()
local record = script_data.active_downloads[player_name]
if record == nil then
rcon.print("No active download is in progress for " .. player_name)
return
end
local player_record = script_data.players[player_name]
if record.restart then
rcon.print("Restarting outdated download")
player_sync.initiate_inventory_download(player, player_record, record.generation)
return
end
if total == 0 then
-- Download was requested but the player had no data stored.
log("ERROR: Player sync failed, got empty player data for " .. player.name .. " from the controller")
player.print("ERROR: Player sync failed, got empty player data from the controller")
progress_dialog.remove(player)
-- Give the player a character and pretend that's the synced player data
ensure_character(player)
-- Restore player position and driving state
restore_position(record, player)
script_data.active_downloads[player_name] = nil
player_record.dirty = player.connected
player_record.sync = true
player_record.generation = record.generation
return
end
record.data = record.data .. data
-- Show progress in console
-- player.print("Downloaded "..(number + 1).."/"..total.." parts")
if number ~= total then
-- Show progress in GUI
progress_dialog.display(player, number, total)
-- Update activity to indicate this session is still going
record.last_active = game.ticks_played
return
end
-- Download is complete
progress_dialog.remove(player)
-- Remove download session and store finished download
script_data.active_downloads[player_name] = nil
script_data.finished_downloads[player_name] = record
local ticks = game.ticks_played - record.started
player.print("Imported player data in " .. ticks .. " ticks")
log("Imported player data for " .. player_name .. " in " .. ticks .. " ticks")
if player.connected then
player_sync.finish_download(player, record)
end
end
return download_inventory
@@ -0,0 +1,12 @@
-- Ensures that the given player has a character if one doesn't exist
local function ensure_character(player)
if not player.character and not player.ticks_to_respawn then
if player.controller_type ~= defines.controllers.ghost then
player.set_controller({ type = defines.controllers.ghost })
end
player.ticks_to_respawn = 0
player.ticks_to_respawn = nil
end
end
return ensure_character
@@ -0,0 +1,28 @@
local compat = require("modules/clusterio/compat")
--- @param no_early_return boolean? True to always setup data
return function(no_early_return)
local player_sync = compat.script_data.player_sync
if player_sync and not no_early_return then
return player_sync
end
-- migrate: inventory_sync was renamed to player_sync in 2.0.0-alpha.28
if not player_sync and compat.script_data.inventory_sync then
player_sync = compat.script_data.inventory_sync
compat.script_data.inventory_sync = nil
end
player_sync = player_sync or {}
player_sync.players = player_sync.players or {}
player_sync.players_waiting_for_acquire = player_sync.players_waiting_for_acquire or {}
player_sync.players_in_cutscene_to_sync = player_sync.players_in_cutscene_to_sync or {}
player_sync.failed_deserialization = player_sync.failed_deserialization or {}
player_sync.active_downloads = player_sync.active_downloads or {}
player_sync.finished_downloads = player_sync.finished_downloads or {}
player_sync.active_uploads = player_sync.active_uploads or {}
compat.script_data.player_sync = player_sync
return player_sync
end
@@ -0,0 +1,151 @@
local ensure_character = require("modules/player_sync/ensure_character")
local get_script_data = require("modules/player_sync/get_script_data")
local dialog_failed_download = {}
--- @param player LuaPlayer
--- @param acquire_response table
function dialog_failed_download.create(player, acquire_response)
if player.gui.screen.dialog_failed_download then
player.gui.screen.dialog_failed_download.destroy()
end
local frame = player.gui.screen.add {
name = "dialog_failed_download",
type = "frame",
direction = "vertical",
}
local titlebar = frame.add {
type = "flow",
}
titlebar.drag_target = frame
local title_caption = "Player sync download failed"
if acquire_response.status == "busy" then
title_caption = "Inventory is in use on " .. acquire_response.message
end
local title = titlebar.add {
type = "label",
style = "frame_title",
caption = title_caption,
}
title.drag_target = frame
local filler = titlebar.add {
type = "empty-widget",
style = "draggable_space_header",
}
filler.style.horizontally_stretchable = true
filler.style.right_margin = 4
filler.style.height = 24
filler.drag_target = frame
local content = frame.add {
name = "player_sync_failed_download_content",
type = "frame",
direction = "vertical",
style = "inside_shallow_frame_with_padding",
}
content.style.width = 400
local reason
if acquire_response.status == "timeout" then
reason = "Timed out fetching inventory from the controller."
elseif acquire_response.status == "busy" then
reason =
"Your synced inventory is in in use on " .. acquire_response.message .. ". " ..
"If you are logged in there you will have to log out there before you can sync the inventory here. " ..
"If you just logged out from there it might take some time before the inventory is available."
elseif acquire_response.status == "error" then
reason = "Error fetching inventory from the controller: " .. acquire_response.message .. "."
else
reason = "Unknown status " .. acquire_response.status .. " fetching inventory from the controller."
end
local p1 = content.add {
type = "label",
caption = reason
}
p1.style.single_line = false
local p2 = content.add {
type = "label",
caption =
"You may choose to retry fetching the inventory or play with a temporary inventory which will be merged " ..
"with your synced inventory the next time you join this server."
,
}
p2.style.single_line = false
p2.style.top_margin = 8
local dialog_row = frame.add {
type = "flow",
}
dialog_row.style.top_margin = 8
dialog_row.drag_target = frame
local abort = dialog_row.add {
name = "player_sync_failed_download_abort",
type = "button",
style = "back_button",
caption = "Use temporary inventory",
tooltip = "Items you obtain here will be merged with your synced inventory the next time you join this server.",
}
local dialog_filler = dialog_row.add {
type = "empty-widget",
style = "draggable_space_header",
}
dialog_filler.style.horizontally_stretchable = true
dialog_filler.style.right_margin = 4
dialog_filler.style.height = 28
dialog_filler.drag_target = frame
local retry = dialog_row.add {
name = "player_sync_failed_download_retry",
type = "button",
style = "forward_button",
caption = "Retry",
}
frame.force_auto_center()
player.opened = frame
end
dialog_failed_download.events = {
[defines.events.on_gui_click] = function(event)
if not event.element.valid then
return
end
if event.element.name == "player_sync_failed_download_abort" then
-- Give the player a character and let them play with that
local player = assert(game.get_player(event.player_index))
ensure_character(player)
local player_sync = get_script_data()
player.gui.screen.dialog_failed_download.destroy()
player_sync.players[player.name].dirty = true
player_sync.players[player.name].sync = false
elseif event.element.name == "player_sync_failed_download_retry" then
-- Retry acquiring the player from the controller
local player = assert(game.get_player(event.player_index))
player_sync.acquire(player)
player.gui.screen.dialog_failed_download.destroy()
end
end,
[defines.events.on_player_left_game] = function(event)
local player = assert(game.get_player(event.player_index))
if player.gui.screen.dialog_failed_download then
player.gui.screen.dialog_failed_download.destroy()
end
end,
}
return dialog_failed_download
@@ -0,0 +1,108 @@
-- Show inventory download progressbar
local progress_dialog = {}
--- @param player LuaPlayer
--- @param progress number
--- @param total number
function progress_dialog.create(player, progress, total)
local frame = player.gui.screen.add {
name = "player_sync_progress",
type = "frame",
direction = "vertical",
}
local titlebar = frame.add {
type = "flow",
}
titlebar.drag_target = frame
local title = titlebar.add {
type = "label",
style = "frame_title",
caption = "Player sync",
}
title.drag_target = frame
local filler = titlebar.add {
type = "empty-widget",
style = "draggable_space_header",
}
filler.style.horizontally_stretchable = true
filler.style.right_margin = 4
filler.style.height = 24
filler.drag_target = frame
local content = frame.add {
name = "player_sync_progress_dialog_content",
type = "frame",
direction = "vertical",
style = "inside_shallow_frame_with_padding",
}
content.style.width = 400
local p1 = content.add {
type = "label",
caption = "Downloading inventory chunk " .. progress .. " / " .. total,
}
p1.style.single_line = false
p1.style.bottom_margin = 8
local progressbar = content.add {
type = "progressbar",
value = progress / total,
}
progressbar.style.width = 376 -- inside_shallow_frame_with_padding has 12px padding on each side
frame.force_auto_center()
player.opened = frame
end
--- @param player LuaPlayer
function progress_dialog.remove(player)
if player.gui.screen.player_sync_progress then
player.gui.screen.player_sync_progress.destroy()
end
end
--- @param player LuaPlayer
--- @param progress number
--- @param total number
function progress_dialog.update(player, progress, total)
-- Be defensive here in case an old GUI is present
local frame = player.gui.screen.player_sync_progress
if not frame then
return false
end
local content = frame.player_sync_progress_dialog_content
if not content then
return false
end
local p1 = content.children[1]
if not p1 or p1.type ~= "label" then
return false
end
local progressbar = content.children[2]
if not progressbar or progressbar.type ~= "progressbar" then
return false
end
p1.caption = "Downloading inventory chunk " .. progress .. " / " .. total
progressbar.value = progress / total
return true
end
--- @param player LuaPlayer
--- @param progress number
--- @param total number
function progress_dialog.display(player, progress, total)
if not progress_dialog.update(player, progress, total) then
progress_dialog.remove(player)
progress_dialog.create(player, progress, total)
end
end
return progress_dialog
+4
View File
@@ -0,0 +1,4 @@
{
"name": "player_sync",
"load": ["player_sync.lua", "gui/dialog_failed_download.lua"]
}
+533
View File
@@ -0,0 +1,533 @@
--[[
Player Sync
When a player leaves the game, serialize the player state and upload it to the controller.
When a player joins the game, request the player data from controller and deserialize the player state from it.
]]
local compat = require("modules/clusterio/compat")
local clusterio_api = require("modules/clusterio/api")
local download_inventory = require("modules/player_sync/download_inventory")
local serialize = require("modules/player_sync/serialize")
local restore_position = require("modules/player_sync/restore_position")
local get_script_data = require("modules/player_sync/get_script_data")
local progress_dialog = require("modules/player_sync/gui/progress_dialog")
local dialog_failed_download = require("modules/player_sync/gui/dialog_failed_download")
local v2_remote_controller = compat.version_ge("2.0.0")
local recipe_notifications_api = compat.version_ge("2.0.67")
-- Returns true if the player is currently in a cutscene
local function is_in_cutscene(player)
return player.controller_type == defines.controllers.cutscene
end
-- Create player record for bookkeeping
local function create_player(player, dirty)
local script_data = get_script_data(true) -- no early return to support loading from single player
script_data.players[player.name] = {
dirty = dirty, -- Player inventory has changes that should be persisted
sync = false, -- Player inventory is synced from the controller
generation = 0,
}
end
-- Remove all stored player data by this module
local function remove_player(player)
local script_data = get_script_data()
script_data.players_waiting_for_acquire[player.name] = nil
script_data.players_in_cutscene_to_sync[player.name] = nil
script_data.failed_deserialization[player.name] = nil
script_data.active_downloads[player.name] = nil
script_data.finished_downloads[player.name] = nil
script_data.active_uploads[player.name] = nil
script_data.players[player.name] = nil
end
player_sync = {}
-- This function is called by instance.js as /sc player_sync.download_inventory("danielv", Escaped JSON string, package_number, total_packages_count) with data from the controller
player_sync.download_inventory = download_inventory
-- This function is called internally when a player leaves the game to
-- serialize the player for upload.
function player_sync.serialize_player(player, player_record)
-- Editor mode is not supported.
if player.controller_type == defines.controllers.editor then
player.toggle_map_editor()
end
if player.controller_type == defines.controllers.editor then
error("Unable to switch out of editor mode")
return
end
-- mod-compat: Exit Space Exploration satellite view to restore the real character
if remote.interfaces["space-exploration"] then
local status, result = pcall(function()
if remote.call("space-exploration", "remote_view_is_active", { player = player }) then
remote.call("space-exploration", "remote_view_stop", { player = player })
end
end)
if not status then
log("ERROR: Exiting remote view failed for " .. player.name .. ": " .. result)
player.print("ERROR: Exiting remote view failed: " .. result)
end
end
local failed_deserialization = get_script_data().failed_deserialization[player.name] or {}
local serialized_player = serialize.serialize_player(player, failed_deserialization)
serialized_player.generation = player_record.generation
return serialized_player
end
function player_sync.deserialize_player(player, finished_record)
-- Editor mode is not supported.
if player.controller_type == defines.controllers.editor then
player.toggle_map_editor()
end
if player.controller_type == defines.controllers.editor then
error("Unable to switch out of editor mode")
return
end
-- Stash temporary inventory if it exists
local stashed_corpse
local script_data = get_script_data()
local player_record = script_data.players[player.name]
if player_record.dirty and player.character then
local character = player.character
local surface = character.surface
local position = character.position
local corpse_name = character.prototype.character_corpse.name
player.character = nil
character.die()
stashed_corpse = surface.find_entity(corpse_name, position)
end
-- Deserialize downloaded player data
local serialized_player = compat.json_to_table(finished_record.data)
assert(type(serialized_player) == "table", "wrong type for serialized_player")
script_data.failed_deserialization[player.name] = serialize.deserialize_player(player, serialized_player)
-- Restore player position and driving state
restore_position(player, finished_record)
-- Transfer items from stashed inventory
if stashed_corpse then
local stash = stashed_corpse.get_inventory(defines.inventory.character_corpse)
if player.character then
local main = player.character.get_main_inventory()
for i = 1, #stash do
-- Try transferring a stack
local source = stash[i]
if source and source.valid_for_read then
local target = main.find_empty_stack()
if not target then
break
end
target.transfer_stack(source)
end
end
end
if stash.is_empty() then
stashed_corpse.destroy()
else
player.print(
"Your temporary inventory did not fit into your synced one and the remaining items have " ..
"been placed in a corpse below you."
)
end
end
end
player_sync.events = {}
player_sync.events[clusterio_api.events.on_server_startup] = function(event)
local script_data = get_script_data(true)
script_data.players_waiting_for_acquire = {}
script_data.players_in_cutscene_to_sync = {}
for _, player in pairs(game.players) do
if not script_data.players[player.name] then
create_player(player, true)
end
-- migrate: dialogs created before inventory_sync was renamed to player_sync
local screen = player.gui.screen
if screen.inventory_sync_progress then
screen.inventory_sync_progress.destroy()
end
if screen.dialog_failed_download and screen.dialog_failed_download.inventory_sync_failed_download_content then
screen.dialog_failed_download.destroy()
end
end
end
-- Cleanup
player_sync.events[defines.events.on_pre_player_removed] = function(event)
remove_player(game.get_player(event.player_index))
end
player_sync.events[defines.events.on_player_created] = function(event)
create_player(game.get_player(event.player_index), false)
end
function player_sync.acquire(player)
local script_data = get_script_data()
script_data.players_waiting_for_acquire[player.name] = {
start_tick = game.ticks_played,
}
clusterio_api.send_json("player_sync_acquire", {
player_name = player.name,
})
end
function player_sync.check_players_waiting_for_acquire()
local script_data = get_script_data()
for player_name, record in pairs(script_data.players_waiting_for_acquire) do
-- Check if the acquire player request timed out
if game.ticks_played > record.start_tick + 600 then
player_sync.acquire_response(compat.table_to_json({
status = "timeout",
player_name = player_name,
}))
end
end
end
function player_sync.acquire_response(data)
local script_data = get_script_data()
local response = assert(compat.json_to_table(data))
if not script_data.players_waiting_for_acquire[response.player_name] then
clusterio_api.send_json("player_sync_release", { player_name = response.player_name })
return
end
script_data.players_waiting_for_acquire[response.player_name] = nil
local player = game.get_player(response.player_name)
if is_in_cutscene(player) then
response.player = player
script_data.players_in_cutscene_to_sync[response.player_name] = response
else
player_sync.sync_player(response)
end
end
function player_sync.check_players_in_cutscene()
local script_data = get_script_data()
for player_name, response in pairs(script_data.players_in_cutscene_to_sync) do
if not is_in_cutscene(response.player) then
script_data.players_in_cutscene_to_sync[player_name] = nil
player_sync.sync_player(response)
end
end
end
function player_sync.sync_player(acquire_response)
local player = assert(game.get_player(acquire_response.player_name))
-- Editor mode is not supported.
if player.controller_type == defines.controllers.editor then
player.toggle_map_editor()
end
if player.controller_type == defines.controllers.editor then
log("ERROR: Player sync failed, unable to switch " .. player.name .. " out of editor mode")
player.print("ERROR: Player sync failed, unable to switch out of editor mode")
return
end
local script_data = get_script_data()
local finished_record = script_data.finished_downloads[acquire_response.player_name]
if finished_record then
if acquire_response.status == "acquired" and finished_record.generation == acquire_response.generation then
player_sync.finish_download(player, finished_record)
return
end
-- The acquisition either failed or the current finished download is
-- stale, delete it and try downloading it again.
script_data.finished_downloads[acquire_response.player_name] = nil
end
local download_record = script_data.active_downloads[acquire_response.player_name]
if download_record then
-- Ignore the response if it affirms the current active download
if acquire_response.status == "acquired" and download_record.generation == acquire_response.generation then
game.print("Continuing active download")
return
end
-- This is the excaptional case where a long download started from
-- the previous time the player joined is still ongoing and we just
-- received a message saying that it's not valid any more.
if acquire_response.status == "error" or acquire_response.status == "timeout" then
-- Let the current download finish or fail on its own, we may end up
-- duplicating items or giving the player a stale inventory here
-- but it's better than throwing away all the downloaded data.
return
end
if acquire_response.status == "acquired" then
-- The stored data on the controller has changed since the
-- download was started. Restart it.
game.print("Restarting download")
download_record.restart = true
return
end
if acquire_response.status == "busy" then
-- Somehow another instance has claimed the player while we're
-- downloading it. Abort it and send failure to the player.
script_data.active_downloads[acquire_response.player_name] = nil
end
end
local player_record = script_data.players[acquire_response.player_name]
if acquire_response.status ~= "acquired" then
if player_record.sync and not player_record.dirty then
if player.controller_type == defines.controllers.character then
local character = player.character
player.set_controller({ type = defines.controllers.spectator })
if character then character.destroy() end
end
player_record.sync = false
end
dialog_failed_download.create(player, acquire_response)
return
end
if
acquire_response.has_data
and (not player_record.sync or acquire_response.generation > player_record.generation)
then
player_sync.initiate_inventory_download(player, player_record, acquire_response.generation)
else
if acquire_response.generation == 0 then
player.print(
"Your inventory will be automatically synchronized between servers in this cluster. " ..
"To improve sync performance, please avoid storing large blueprints in your inventory.",
{0.75, 0.75, 1}
)
end
player_record.sync = true
player_record.dirty = true
end
end
function player_sync.finish_download(player, finished_record)
local script_data = get_script_data()
script_data.finished_downloads[player.name] = nil
local player_record = script_data.players[player.name]
local status, result = xpcall(player_sync.deserialize_player, debug.traceback, player, finished_record)
if not status then
log("ERROR: Deserializing player " .. player.name .. " failed: " .. result)
player.print("ERROR: Deserializing player data failed: " .. result)
-- Treat this as a temporary inventory so the incomplete state is not uploaded over the synced data
player_record.dirty = true
player_record.sync = false
return
end
player_record.dirty = true
player_record.sync = true
player_record.generation = finished_record.generation
end
-- Download inventory from controller
player_sync.events[defines.events.on_player_joined_game] = function(event)
local player = assert(game.get_player(event.player_index))
local script_data = get_script_data()
if not game.is_multiplayer() then
return player.print("Player sync deactivated: game is single player")
end
-- Send acquire request even if an active download is currently in progress
player_sync.acquire(player)
-- Clear active upload if it exists
script_data.active_uploads[player.name] = nil
end
player_sync.on_nth_tick = {}
player_sync.on_nth_tick[33] = function(event)
-- Periodically check players currently in the process of syncing
player_sync.check_players_waiting_for_acquire()
player_sync.check_players_in_cutscene()
player_sync.check_active_downloads()
player_sync.check_active_uploads()
end
player_sync.events[defines.events.on_cutscene_waypoint_reached] = function(event)
player_sync.check_players_in_cutscene()
end
player_sync.events[defines.events.on_cutscene_cancelled] = function(event)
player_sync.check_players_in_cutscene()
end
-- Upload inventory when a player leaves the game. Triggers on restart after crash if player was online during crash.
player_sync.events[defines.events.on_pre_player_left_game] = function(event)
-- for some reason, on_pre_player_left_game gets called before on_server_startup so script_data isn't ready yet
if not compat.script_data.player_sync then
log("ERROR: script data for player sync is not defined")
return
end
local script_data = get_script_data()
local player = assert(game.get_player(event.player_index))
local player_record = script_data.players[player.name]
-- If player has an active download release our acquisition but let the download continue
if script_data.active_downloads[player.name] then
clusterio_api.send_json("player_sync_release", { player_name = player.name })
return
end
if not player_record.dirty or not player_record.sync then
-- Nothing to upload, release the acquisition so other instances are not blocked
clusterio_api.send_json("player_sync_release", { player_name = player.name })
return
end
player_record.generation = player_record.generation + 1
local status, result = xpcall(player_sync.serialize_player, debug.traceback, player, player_record)
if not status then
log("ERROR: Serializing player " .. player.name .. " failed: " .. result)
player.print("ERROR: Serializing player data failed: " .. result)
return
end
script_data.active_uploads[player.name] = {
serialized = result,
last_attempt = game.ticks_played,
timeout = math.random(600, 1200), -- Start with 10-20 seconds for the timeout
}
clusterio_api.send_json("player_sync_upload", result)
end
-- Invoked by the instance code to confirm the controller has received the uploaded data
function player_sync.confirm_upload(player_name, generation)
local player = game.get_player(player_name)
if not player or player.connected then
log("no player, or player connected")
return
end
local script_data = get_script_data()
local player_record = script_data.players[player.name]
if not player_record or player_record.generation ~= generation then
return
end
if not player_record.dirty then
log("ERROR: Received upload confirmation for " .. player_name .. " without the dirty flag")
end
if not player_record.sync then
log("ERROR: Received upload confirmation for " .. player_name .. " without the sync flag")
end
log("Confirmed upload of " .. player_name)
script_data.active_uploads[player_name] = nil
player_record.dirty = false
end
function player_sync.initiate_inventory_download(player, player_record, generation)
player.print("Initiating inventory download...")
local record = {
started = game.ticks_played,
last_active = game.ticks_played,
generation = generation,
data = ""
}
local script_data = get_script_data()
script_data.active_downloads[player.name] = record
-- The plugin only sends back what differs from the current notification state
local recipe_notifications
if recipe_notifications_api then
recipe_notifications = serialize.serialize_crafting_notifications(player)
end
clusterio_api.send_json("player_sync_download", {
player_name = player.name,
recipe_notifications = recipe_notifications,
})
-- If this is a synced player turn them into a spectator while the
-- player data is downloading
if player_record.sync then
-- Store original position to teleport back to
if v2_remote_controller then
record.surface = player.physical_surface
record.position = player.physical_position
else
record.surface = player.surface
record.position = player.position
end
if player.driving then
record.vehicle = player.vehicle
end
local character = player.character
player.set_controller({ type = defines.controllers.spectator })
if character ~= nil then character.destroy() end
-- Indicate this state shouldn't be persisted
player_record.dirty = false
end
progress_dialog.display(player, 0, 1)
end
function player_sync.check_active_downloads()
-- Used for detecting the inventory download failing, like when the map is saved and
-- re-loaded in the middle of a download. The player will be returned to a playable state.
local script_data = get_script_data()
for player_name, record in pairs(script_data.active_downloads) do
if record.last_active <= game.ticks_played - 600 then
script_data.active_downloads[player_name] = nil
local player = game.get_player(player_name)
if player then
log("ERROR: Inventory download failed for " .. player_name)
if player.connected then
-- Show GUI with option to retry or abort download
dialog_failed_download.create(player, {
player_name = player_name,
status = "error",
message = "Inventory download failed",
})
end
end
end
end
end
function player_sync.check_active_uploads()
local script_data = get_script_data()
for player_name, record in pairs(script_data.active_uploads) do
if record.last_attempt + record.timeout < game.ticks_played then
local player_record = script_data.players[player_name]
local player = game.get_player(player_name)
if not player_record or not player then
script_data.active_uploads[player_name] = nil
else
log("Retrying upload for " .. player_name)
record.last_attempt = game.ticks_played
record.timeout = math.random(record.timeout, record.timeout * 2)
clusterio_api.send_json("player_sync_upload", record.serialized)
end
end
end
end
return player_sync
@@ -0,0 +1,38 @@
local compat = require("modules/clusterio/compat")
local can_enter_vehicle = {
[defines.controllers.character] = true,
[defines.controllers.god] = true,
[defines.controllers.editor] = true,
}
if defines.controllers.remote then
-- Does not exist in 1.1, so we need this nil check
can_enter_vehicle[defines.controllers.remote] = true
end
local v2_surface_platform = compat.version_ge("2.0.0")
--- @param player LuaPlayer
--- @param record table
return function(player, record)
if record.vehicle and record.vehicle.valid and can_enter_vehicle[player.controller_type] then
player.teleport(record.vehicle.position, record.vehicle.surface)
player.driving = true
-- Teleport to safe location if unable to enter vehicle
local character = player.character
if not player.driving and character and player.controller_type == defines.controllers.character then
local safe_position = record.vehicle.surface.find_non_colliding_position(
character.name, player.position, 32, 1/8
)
if safe_position then
player.teleport(safe_position, player.surface)
end
end
elseif v2_surface_platform and record.surface and record.surface.platform and can_enter_vehicle[player.controller_type] then
player.enter_space_platform(record.surface.platform)
elseif record.surface and record.position then
player.teleport(record.position, record.surface)
end
end
+886
View File
@@ -0,0 +1,886 @@
local compat = require("modules/clusterio/compat")
local clusterio_serialize = require("modules/clusterio/serialize")
local character_inventories = require("modules/player_sync/define_player_inventories")
local character_stat_keys = require("modules/player_sync/define_player_stat_keys")
local game_view_settings_keys = require("modules/player_sync/define_game_view_settings")
local serialize = {}
local v2_logistic_api = compat.version_ge("2.0.0")
local v2_storage_api = compat.version_ge("2.0.0")
local v2_remote_controller = compat.version_ge("2.0.0")
local v2_space_platform = compat.version_ge("2.0.0")
local v2_exit_remote_view = compat.version_ge("2.0.56")
local recipe_notifications_api = compat.version_ge("2.0.67")
local v2_0_quick_bar_api = compat.version_ge("2.0.0")
local v2_1_quick_bar_api = compat.version_ge("2.1.0")
function serialize.serialize_inventories(source, inventories)
local serialized = {}
for name, index in pairs(inventories) do
local inventory = source.get_inventory(index)
if inventory ~= nil then
serialized[name] = clusterio_serialize.serialize_inventory(inventory)
end
end
return serialized
end
function serialize.deserialize_inventories(destination, serialized, inventories)
for name, index in pairs(inventories) do
local inventory = destination.get_inventory(index)
if inventory ~= nil and serialized[name] ~= nil then
inventory.clear()
clusterio_serialize.deserialize_inventory(inventory, serialized[name])
end
end
end
-- Characters are serialized into a table with the following fields:
-- character_crafting_speed_modifier
-- character_mining_speed_modifier
-- character_additional_mining_categories
-- character_running_speed_modifier
-- character_build_distance_bonus
-- character_item_drop_distance_bonus
-- character_reach_distance_bonus
-- character_resource_reach_distance_bonus
-- character_item_pickup_distance_bonus
-- character_loot_pickup_distance_bonus
-- character_inventory_slots_bonus
-- character_trash_slot_count_bonus
-- character_maximum_following_robot_count_bonus
-- character_health_bonus
-- character_personal_logistic_requests_enabled
-- allow_dispatching_robots
-- inhibit_movement_bonus (optional, from the armor equipment grid)
-- inventories: table of character inventory name to inventory content
function serialize.serialize_character(character)
local serialized = { }
-- Serialize character stats
for _, key in pairs(character_stat_keys) do
serialized[key] = character[key]
end
-- Serialize character inventories
serialized.inventories = serialize.serialize_inventories(character, character_inventories)
-- Serialize armor grid state
local grid = character.grid
if grid then
serialized.inhibit_movement_bonus = grid.inhibit_movement_bonus
end
return serialized
end
function serialize.deserialize_character(character, serialized)
-- Deserialize character stats
for _, key in pairs(character_stat_keys) do
character[key] = serialized[key]
end
-- Deserialize character inventories
serialize.deserialize_inventories(character, serialized.inventories, character_inventories)
-- Deserialize armor grid state, the grid exists after the armor inventory is restored
local grid = character.grid
if grid and serialized.inhibit_movement_bonus ~= nil then
grid.inhibit_movement_bonus = serialized.inhibit_movement_bonus
end
end
-- Personal logistic slots is a table mapping string indexes to a table with the following fields:
-- name
-- min
-- max
function serialize.serialize_personal_logistic_slots(player)
-- Check if logistics technology is researched
local force = player.force
if not force.technologies["logistic-robotics"] or not force.technologies["logistic-robotics"].researched then
return nil
end
if v2_logistic_api then
local logistic_point = player.get_requester_point()
if logistic_point == nil then
return nil
end
local serialized = {
enabled = logistic_point.enabled,
trash_not_requested = logistic_point.trash_not_requested,
sections = {},
}
for i = 1, logistic_point.sections_count do
local section = logistic_point.get_section(i)
serialized.sections[i] = {
group = section.group,
active = section.active,
multiplier = section.multiplier,
filters = section.filters,
}
end
return serialized
end
local serialized = nil
-- Serialize personal logistic slots
local last_valid = 0
for i = 1, 65536 do
local slot = player.get_personal_logistic_slot(i)
if slot.name then
last_valid = i
if not serialized then
serialized = {}
end
serialized[tostring(i)] = {
name = slot.name,
min = slot.min,
max = slot.max,
}
-- Stop after 100 empty slots
elseif last_valid + 100 <= i then
break
end
end
return serialized
end
function serialize.deserialize_personal_logistic_slots(player, serialized)
if not serialized then
return
end
-- Check if logistics technology is researched
local force = player.force
if not force.technologies["logistic-robotics"] or not force.technologies["logistic-robotics"].researched then
return
end
-- Load personal logistic slots
if v2_logistic_api then
local logistic_point = player.get_requester_point()
if logistic_point == nil then
return
end
-- Remove old sections up to section_count
for i = logistic_point.sections_count, 1, -1 do
logistic_point.remove_section(i)
end
-- If this is an array instead of a table, migrate to v2 format
if serialized[1] ~= nil then
local section = logistic_point.add_section()
for i, slot in pairs(serialized) do
section.set_slot(i, {
value = {
name = slot.name,
quality = "normal",
},
min = slot.min,
max = slot.max,
})
end
else
-- Regular 2.0+ deserialization
logistic_point.enabled = serialized.enabled
logistic_point.trash_not_requested = serialized.trash_not_requested
for i, section in pairs(serialized.sections) do
local sec = logistic_point.add_section()
sec.active = section.active
sec.multiplier = section.multiplier
if section.group ~= "" then -- "" is the default group name, which is truthy
-- Named groups get added with name only - this avoids overwriting existing groups on the server
sec.group = section.group
else
-- Unnamed groups get added with filters
sec.filters = section.filters
end
end
end
else
for i, slot in pairs(serialized) do
if slot ~= nil then
player.set_personal_slogistic_slot(tonumber(i), slot)
end
end
end
end
-- name is a custom type where quality is "normal" and comparator is "=" (most common case)
--- @alias QuickBarSlotEncoded.name string
--- @alias QuickBarSlotEncoded.filter { t: "f", n: string, q: string, c: string }
--- @alias QuickBarSlotEncoded QuickBarSlotEncoded.name | QuickBarSlotEncoded.filter
--- @param filter ItemFilter
--- @return QuickBarSlotEncoded
local function serialize_filter(filter)
if filter.quality == "normal" and filter.comparator == "=" then
return filter.name --[[@as string]]
end
return {
t = "f",
n = filter.name --[[@as string]],
q = filter.quality --[[@as string]],
c = filter.comparator --[[@as string]],
}
end
--- @param slot QuickBarSlot | ItemFilter | LuaItemPrototype
--- @return QuickBarSlotEncoded | nil
function serialize.serialize_quick_bar_slot(slot)
if v2_1_quick_bar_api then
-- 2.1 has a dedicated type for quick bar slots
--- @cast slot QuickBarSlot
if slot.type == "filter" then
return serialize_filter(slot.filter)
end
print("Warning: Unsupported quick bar slot type '" .. slot.type .. "'")
return nil
end
if v2_0_quick_bar_api then
-- 2.0 gives us an item filter which supports quality
--- @cast slot -QuickBarSlot, -LuaItemPrototype
return serialize_filter(slot)
end
-- pre 2.0 quality did not exist
--- @cast slot LuaItemPrototype
return slot.name
end
--- @param entry string | QuickBarSlotEncoded
--- @return QuickBarSlot | ItemWithQualityID | nil
function serialize.deserialize_quick_bar_slot(entry)
if v2_1_quick_bar_api then
-- Return a quick bar slot
if type(entry) == "string" then
return {
type = "filter",
filter = {
name = entry,
quality = "normal",
comparator = "=",
},
}
end
if entry.t == "f" then
return {
type = "filter",
filter = {
name = entry.n,
quality = entry.q,
comparator = entry.c,
},
} --[[@as QuickBarSlot]]
end
print("Warning: Unsupported serialized quick bar slot type '" .. tostring(entry.t) .. "'")
return nil
end
if v2_0_quick_bar_api then
-- Return a ItemIDAndQualityIDPair (member of ItemWithQualityID)
if type(entry) == "string" then
return {
name = entry,
quality = "normal",
}
end
-- entry.t == "f" is only remaining case for 2.0
return {
name = entry.n,
quality = entry.q,
}
end
-- Return a string (member of ItemPrototypeIdentification)
-- Pre 2.0 this was the only method of encoding used
return entry --[[@as string]]
end
--- @param player LuaPlayer
--- @return table<string, QuickBarSlotEncoded>?
function serialize.serialize_quick_bar(player)
local serialized
local width = v2_1_quick_bar_api and player.quick_bar_width
for i = 1, 100 do
local slot
if v2_1_quick_bar_api then
local page = math.floor((i - 1) / width) + 1
local page_slot = ((i - 1) % width) + 1
slot = player.get_quick_bar_slot(page, page_slot)
else
--- @diagnostic disable-next-line: missing-parameter
slot = player.get_quick_bar_slot(i)
end
if slot ~= nil then
local entry = serialize.serialize_quick_bar_slot(slot)
if entry ~= nil then
serialized = serialized or {}
serialized[tostring(i)] = entry
end
end
end
return serialized
end
--- @param player LuaPlayer
--- @param serialized table<string, string | QuickBarSlotEncoded>?
function serialize.deserialize_quick_bar(player, serialized)
if not serialized then
return
end
local width = v2_1_quick_bar_api and player.quick_bar_width
for i = 1, 100 do
local entry = serialized[tostring(i)]
if entry ~= nil then
local slot = serialize.deserialize_quick_bar_slot(entry)
if slot ~= nil then
if v2_1_quick_bar_api then
local page = math.floor((i - 1) / width) + 1
local page_slot = ((i - 1) % width) + 1
player.set_quick_bar_slot(page, page_slot, slot)
else
--- @diagnostic disable-next-line: param-type-mismatch
player.set_quick_bar_slot(i, slot)
end
end
end
end
end
-- Crafting queue is a table with the following fields:
-- crafting_queue
-- ingredients
function serialize.serialize_crafting_queue(player)
local crafting_queue = {}
-- Give player some more inventory space to avoid duplicating items
player.character_inventory_slots_bonus = player.character_inventory_slots_bonus + 1000
-- Save current items
local inventory = player.character.get_main_inventory()
local old_items = inventory.get_contents()
local crafting_queue_progress = player.crafting_queue_progress
-- Cancel old crafts to get the items back
while player.crafting_queue_size > 0 do
local old_queue = player.crafting_queue
-- Cancel craft
player.cancel_crafting {
index = 1,
count = 1,
}
local rightmost_right_index = 0 -- 0 indexed since it is subtractive in a 1 indexed language
local new_queue = player.crafting_queue
while
new_queue ~= nil and
new_queue[#new_queue - rightmost_right_index] ~= nil and
new_queue[#new_queue - rightmost_right_index].count >= old_queue[#old_queue - rightmost_right_index].count
do
rightmost_right_index = rightmost_right_index + 1
end
local oldItem = old_queue[#old_queue - rightmost_right_index]
local newItem = nil
if new_queue ~= nil then
newItem = new_queue[#new_queue - rightmost_right_index]
end
-- Figure out how many items to add to queue
local added = oldItem.count
if newItem ~= nil then
added = oldItem.count - newItem.count
if oldItem.recipe ~= newItem.recipe then
log("ERROR: Old item "..oldItem.recipe.." is not equal "..newItem.recipe)
end
end
-- If the last item we added was of the same type, merge them in the queue
if #crafting_queue > 0 and crafting_queue[#crafting_queue].recipe == oldItem.recipe then
crafting_queue[#crafting_queue].count = crafting_queue[#crafting_queue].count + added
else
-- If the last item was of a different type, add a new item to the queue
table.insert(crafting_queue, {
recipe = oldItem.recipe,
count = added,
})
end
-- game.print("Saved craft "..oldItem.recipe)
end
local difference = {}
if v2_storage_api then
-- Find amount of items added and remove from inventory
local new_items = inventory.get_contents()
-- Build map of old counts by item name and quality
local old_counts = {}
for _, item in ipairs(old_items) do
local key = item.name .. ":" .. item.quality
old_counts[key] = (old_counts[key] or 0) + item.count
end
-- Compare with new items to find differences
for _, item in ipairs(new_items) do
local key = item.name .. ":" .. item.quality
local old_count = old_counts[key] or 0
local diff = item.count - old_count
if diff > 0 then
-- We don't have to worry about quality because quality can't be handcrafted
local ingredient = {
name = item.name,
count = diff
}
inventory.remove(ingredient)
table.insert(difference, ingredient)
end
end
else
-- Find amount of items added and remove from inventory
local new_items = inventory.get_contents()
for k,v in pairs(new_items) do
local old_count = old_items[k]
local diff = v
if old_count ~= nil then
diff = diff - old_count
end
if diff > 0 then
local ingredient = {
name = k,
count = diff,
}
inventory.remove(ingredient)
table.insert(difference, ingredient)
end
end
end
-- Remove extra inventory slots
player.character_inventory_slots_bonus = player.character_inventory_slots_bonus - 1000
local serialized = {
crafting_queue = crafting_queue,
crafting_queue_progress = crafting_queue_progress,
ingredients = difference,
}
-- Restore the crafting queue that was just destructively serialized
serialize.deserialize_crafting_queue(player, serialized)
return serialized
end
function serialize.deserialize_crafting_queue(player, serialized)
local inventory = player.character.get_main_inventory()
-- Give player some more inventory space to avoid duplicating items
player.character_inventory_slots_bonus = player.character_inventory_slots_bonus + 1000
-- Add items to inventory
for _, item in pairs(serialized.ingredients) do
inventory.insert(item)
end
-- Load crafting queue
for _, queueItem in pairs(serialized.crafting_queue) do
-- Start crafting (consume items)
player.begin_crafting {
count = queueItem.count,
recipe = queueItem.recipe,
-- silent = true, -- Fail silently if items are missing
}
end
-- Remove extra inventory slots
player.character_inventory_slots_bonus = player.character_inventory_slots_bonus - 1000
-- Set progress of current craft
player.crafting_queue_progress = serialized.crafting_queue_progress
end
---@param player LuaPlayer
---@param failed string[]?
---@return string?
function serialize.serialize_crafting_notifications(player, failed)
-- Get all unlocked recipes
local recipes = {}
for _, recipe in pairs(player.force.recipes) do
if recipe.enabled and not recipe.hidden then
recipes[recipe.name] = true
end
end
-- Remove those with notifications
for _, recipe in pairs(player.get_recipe_notifications()) do
recipes[recipe.name] = nil
end
-- Convert to a list of names, including previously failed recipes if any
local recipe_names = {}
for _, name in ipairs(failed or {}) do
recipe_names[#recipe_names + 1] = name
end
for name in pairs(recipes) do
recipe_names[#recipe_names + 1] = name
end
return helpers.encode_string(helpers.table_to_json(recipe_names))
end
--- @class CraftingNotificationDelta
--- @field add string[]? Recipes cleared elsewhere that still have a notification here
--- @field remove string[]? Recipes with a notification elsewhere that are cleared here
--- @param player LuaPlayer
--- @param serialized string Encoded delta against the state sent with the download request
--- @return string[]? failed Recipe names that do not exist
function serialize.deserialize_crafting_notifications(player, serialized)
--- @type CraftingNotificationDelta
local delta = helpers.json_to_table(assert(helpers.decode_string(serialized)))
assert(type(delta) == "table", "wrong type decoded from json_to_table")
-- Recipes which can have a notification on this server
local enabled = {}
for _, recipe in pairs(player.force.recipes) do
if recipe.enabled and not recipe.hidden then
enabled[recipe.name] = true
end
end
-- Clear notifications the player has cleared elsewhere, this means "add seen notification"
local failed = {}
for _, recipe_name in pairs(delta.add or {}) do
if enabled[recipe_name] then
player.clear_recipe_notification(recipe_name)
else
failed[#failed + 1] = recipe_name -- Recipe does not exist on this server
end
end
-- Add notifications the player has elsewhere, this means "remove seen notification"
for _, recipe_name in pairs(delta.remove or {}) do
if enabled[recipe_name] then
player.add_recipe_notification(recipe_name)
end
end
return next(failed) and failed or nil
end
local controller_to_name = {}
for name, value in pairs(defines.controllers) do
controller_to_name[value] = name
end
--- @class SerializedPlayerData
--- @field generation number
--- @field name string
--- @field controller string
--- @field color Color
--- @field chat_color Color
--- @field tag string
--- @field force string
--- @field cheat_mode boolean
--- @field flashlight boolean
--- @field shortcuts table<string, boolean>?
--- @field game_view_settings table<string, boolean>?
--- @field ticks_to_respawn number
--- @field character table<string, any>?
--- @field inventories table<string, table>?
--- @field hotbar table<string, string>?
--- @field quick_bar table<string, QuickBarSlotEncoded>?
--- @field personal_logistic_slots table?
--- @field crafting_queue table?
--- @field recipe_notifications string?
--- @param player LuaPlayer
--- @return table<string, boolean>
function serialize.serialize_shortcuts(player)
local shortcuts = {}
for name, prototype in pairs(compat.prototypes.shortcut) do
if prototype.toggleable then
shortcuts[name] = player.is_shortcut_toggled(name)
end
end
return shortcuts
end
--- @param player LuaPlayer
--- @param serialized table<string, boolean>
function serialize.deserialize_shortcuts(player, serialized)
local shortcut_prototypes = compat.prototypes.shortcut
for name, toggled in pairs(serialized) do
local prototype = shortcut_prototypes[name]
if prototype and prototype.toggleable then
player.set_shortcut_toggled(name, toggled)
end
end
end
--- @param player LuaPlayer
--- @return table<string, boolean>
function serialize.serialize_game_view_settings(player)
local settings = player.game_view_settings
local serialized = {}
for _, key in pairs(game_view_settings_keys) do
serialized[key] = settings[key]
end
return serialized
end
--- @param player LuaPlayer
--- @param serialized table<string, boolean>
function serialize.deserialize_game_view_settings(player, serialized)
local settings = player.game_view_settings
for _, key in pairs(game_view_settings_keys) do
if serialized[key] ~= nil then
settings[key] = serialized[key]
end
end
end
--- @param player LuaPlayer
--- @param failed_deserialization FailedDeserializationPlayerData
--- @return SerializedPlayerData
function serialize.serialize_player(player, failed_deserialization)
--- @type SerializedPlayerData
local serialized = {
generation = 0, -- Gets replaced later
controller = controller_to_name[player.controller_type],
name = player.name,
color = player.color,
chat_color = player.chat_color,
tag = player.tag,
force = player.force.name,
cheat_mode = player.cheat_mode,
flashlight = player.is_flashlight_enabled(),
shortcuts = serialize.serialize_shortcuts(player),
game_view_settings = serialize.serialize_game_view_settings(player),
ticks_to_respawn = player.ticks_to_respawn,
}
-- In 2.0 we want to sync the physical controller to ignore remote view
if v2_remote_controller then
serialized.controller = controller_to_name[player.physical_controller_type]
end
-- For the waiting to respawn state the inventory logistic requests and filters are hidden on the player
if player.controller_type == defines.controllers.ghost and player.ticks_to_respawn then
player.ticks_to_respawn = nil -- Respawn now
serialized.personal_logistic_slots = serialize.serialize_personal_logistic_slots(player)
serialized.inventories = serialize.serialize_inventories(player, character_inventories)
-- Go back to waiting for respawn
local character = player.character
player.ticks_to_respawn = serialized.ticks_to_respawn
if character and character.valid then
character.destroy()
end
end
-- Serialize character
if player.character then
serialized.character = serialize.serialize_character(player.character)
serialized.personal_logistic_slots = serialize.serialize_personal_logistic_slots(player)
end
-- Serialize non-character inventories
if player.controller_type == defines.controllers.god
or v2_remote_controller and player.physical_controller_type == defines.controllers.god
then
serialized.inventories = serialize.serialize_inventories(player, { main = defines.inventory.god_main })
end
-- Serialize quick bar
serialized.quick_bar = serialize.serialize_quick_bar(player)
-- Serialize crafting queue
if player.character then
serialized.crafting_queue = serialize.serialize_crafting_queue(player)
end
-- Serialize recipe notifications
if recipe_notifications_api then
serialized.recipe_notifications = serialize.serialize_crafting_notifications(player, failed_deserialization.recipe_notifications)
end
return serialized
end
--- Find a surface characters can exist on, used when the player is on a space platform surface
--- @param platform LuaSpacePlatform
--- @return LuaSurface
local function find_planet_surface(platform)
local location = platform.space_location
local planet = location and game.planets[location.name]
if planet and planet.surface then
return planet.surface
end
for _, surface in pairs(game.surfaces) do
if not surface.platform then
return surface
end
end
error("No surface found which can hold a character")
end
--- Ensure a player has a character, works from any controller type
--- @param player LuaPlayer
--- @return LuaEntity
local function ensure_character(player)
-- Do nothing if the player has a valid character
local character = player.character
if character and character.valid then
return character
end
-- Exit remote view before switching controllers, this can fail if the player is on a platform
if v2_exit_remote_view and player.controller_type == defines.controllers.remote then
player.exit_remote_view()
end
-- Switch to god controller if create_character would fail
if player.controller_type ~= defines.controllers.god then
player.set_controller{ type = defines.controllers.god }
end
-- Characters can not be created on platform surfaces, restore_position will move them back into the hub
local surface = player.surface
if v2_space_platform and surface.platform then
local planet_surface = find_planet_surface(surface.platform)
local force = player.force --[[@as LuaForce]]
player.teleport(force.get_spawn_position(planet_surface), planet_surface)
end
-- Create and return the character
if not player.create_character() then
error(string.format(
"Failed to create character (controller: %s, physical: %s, surface: %s, connected: %s, driving: %s)",
controller_to_name[player.controller_type],
v2_remote_controller and controller_to_name[player.physical_controller_type] or "n/a",
player.surface.name, tostring(player.connected), tostring(player.driving)
))
end
return assert(player.character)
end
--- @class FailedDeserializationPlayerData
--- @field recipe_notifications string[]?
--- @param player LuaPlayer
--- @param serialized SerializedPlayerData
--- @return FailedDeserializationPlayerData?
function serialize.deserialize_player(player, serialized)
local failed_deserialization = {}
local target_controller = defines.controllers[serialized.controller]
if player.controller_type ~= target_controller or serialized.controller == "ghost" then
if serialized.controller == "character" then
-- Create a character but do not destroy an existing one
ensure_character(player)
if player.controller_type ~= target_controller then
player.set_controller{ type = target_controller }
end
elseif serialized.controller == "ghost" then
-- Ghost state stores hidden logistic and filters which are only accessible in the character controller
local character = ensure_character(player)
if serialized.personal_logistic_slots then
serialize.deserialize_personal_logistic_slots(player, serialized.personal_logistic_slots)
end
if serialized.inventories then
serialize.deserialize_inventories(player, serialized.inventories, character_inventories)
end
if serialized.ticks_to_respawn then
player.ticks_to_respawn = serialized.ticks_to_respawn
else
-- We have to set ticks to respawn to save the hidden state into the player but we
-- can't unset tick_to_respawn by setting it back to nil as that triggers a respawn.
player.ticks_to_respawn = 0
player.set_controller{ type = defines.controllers.god }
player.set_controller{ type = defines.controllers.ghost }
end
if character and character.valid then
character.destroy()
end
elseif serialized.controller ~= "remote" then
-- All other controllers should not have a character
local character = player.character
if character and character.valid then
character.destroy()
end
if player.controller_type ~= target_controller then
player.set_controller{ type = target_controller }
end
else
error("Remote should not be 'serialized.controller'")
end
end
player.color = serialized.color
player.chat_color = serialized.chat_color
player.tag = serialized.tag
player.force = serialized.force
player.cheat_mode = serialized.cheat_mode
if serialized.flashlight then
player.enable_flashlight()
else
player.disable_flashlight()
end
if serialized.shortcuts then
serialize.deserialize_shortcuts(player, serialized.shortcuts)
end
if serialized.game_view_settings then
serialize.deserialize_game_view_settings(player, serialized.game_view_settings)
end
-- Deserialize character
if player.character then
serialize.deserialize_character(player.character, serialized.character)
serialize.deserialize_personal_logistic_slots(player, serialized.personal_logistic_slots)
end
-- Deserialize non-character inventories
if player.controller_type == defines.controllers.god then
serialize.deserialize_inventories(player, serialized.inventories, { main = defines.inventory.god_main })
end
-- Deserialize quick bar (named hotbar in old data)
serialize.deserialize_quick_bar(player, serialized.quick_bar or serialized.hotbar)
-- Deserialize crafting queue
if player.character and serialized.crafting_queue then
serialize.deserialize_crafting_queue(player, serialized.crafting_queue)
end
-- Deserialize recipe notifications
if recipe_notifications_api and serialized.recipe_notifications then
failed_deserialization.recipe_notifications =
serialize.deserialize_crafting_notifications(player, serialized.recipe_notifications)
end
return next(failed_deserialization) and failed_deserialization or nil
end
return serialize