diff --git a/FS25_ADSmartPickup/adNet.lua b/FS25_ADSmartPickup/adNet.lua index 0d47639..6cc677b 100644 --- a/FS25_ADSmartPickup/adNet.lua +++ b/FS25_ADSmartPickup/adNet.lua @@ -18,6 +18,8 @@ local function encodeValue(value, out, seen) out[#out + 1] = "s" .. #value .. ":" .. value elseif kind == "table" then if seen[value] then error("ADNet.encode: cyklisk tabel") end + -- et objekt (køretøj, placeable, klasse-instans) har en metatabel: det må aldrig sendes ved en fejl + if getmetatable(value) ~= nil then error("ADNet.encode: objekt (tabel med metatabel) kan ikke sendes") end seen[value] = true out[#out + 1] = "T" for key, item in pairs(value) do diff --git a/FS25_ADSmartPickup/adSmartPickup.lua b/FS25_ADSmartPickup/adSmartPickup.lua index 1a31e46..5b8295b 100644 --- a/FS25_ADSmartPickup/adSmartPickup.lua +++ b/FS25_ADSmartPickup/adSmartPickup.lua @@ -2137,6 +2137,8 @@ function ADSmartPickup:update(dt) if ADRunsController ~= nil and ADRunsController.adoptLoadedThrottled ~= nil then pcall(ADRunsController.adoptLoadedThrottled, getAutoDriveEnv(), dt) end + -- multiplayer etape 2c: konfigurationen til klienterne (kun i et MP-spil) + if ADSync ~= nil and ADSync.serverTick ~= nil then pcall(ADSync.serverTick, dt) end local ok, err = pcall(restoreStoppedVehicles) if not ok then Logging.warning(ADSmartPickup.LOG_PREFIX .. "kunne ikke gendanne varevalg: %s", tostring(err)) diff --git a/FS25_ADSmartPickup/adSync.lua b/FS25_ADSmartPickup/adSync.lua new file mode 100644 index 0000000..b8365c3 --- /dev/null +++ b/FS25_ADSmartPickup/adSync.lua @@ -0,0 +1,200 @@ +-- AD Sync +-- Multiplayer etape 2c (plan docs/superpowers/plans/2026-10-25-adsmartpickup-multiplayer.md): modulernes +-- konfiguration spejles fra serveren til klienterne. Hver sektion har collect (serveren: den tilstand, der sendes) og +-- apply (klienten: læg den modtagne tilstand ind). Serveren sammenligner hver SYNC_MS den kodede tekst med den sidst +-- sendte og sender kun ændrede sektioner; en spiller, der tilslutter sig, får alle. Kernen er ren (testes uden spillet). + +ADSync = {} + +ADSync.SYNC_MS = 2000 +ADSync.CHUNK_SIZE = 6000 -- tegn pr. event (konservativt; streamWriteString's grænse er ukendt — review 2a) +local LOG_PREFIX = "ADSmartPickup: " + +function ADSync.new(sections, chunkSize) + return {sections = sections, chunkSize = chunkSize or ADSync.CHUNK_SIZE, lastSent = {}, versions = {}, + assembly = ADNet.newAssembly(), byName = {}} +end + +local function packetsFor(sync, name, text) + local version = (sync.versions[name] or 0) + 1 + sync.versions[name] = version + local chunks = ADNet.split(ADNet.toWire(text), sync.chunkSize) + local packets = {} + for index, data in ipairs(chunks) do + packets[#packets + 1] = {section = name, version = version, index = index, total = #chunks, data = data} + end + return packets +end + +-- Kodet tekst pr. sektion; en sektion, der fejler, springes over (og logges én gang pr. fejltekst). +local function collectTexts(sync) + local texts = {} + for _, section in ipairs(sync.sections) do + local ok, text = pcall(function() return ADNet.encode(section.collect()) end) + if ok then + texts[section.name] = text + elseif sync.loggedError ~= tostring(text) and Logging ~= nil then + sync.loggedError = tostring(text) + Logging.warning(LOG_PREFIX .. "multiplayer-synk af %s fejlede: %s", section.name, tostring(text)) + end + end + return texts +end + +-- Serveren: pakker for de sektioner, der har ændret sig siden sidst. +function ADSync.collectChanged(sync) + local packets = {} + local texts = collectTexts(sync) + for _, section in ipairs(sync.sections) do + local text = texts[section.name] + if text ~= nil and text ~= sync.lastSent[section.name] then + sync.lastSent[section.name] = text + for _, packet in ipairs(packetsFor(sync, section.name, text)) do packets[#packets + 1] = packet end + end + end + return packets +end + +-- Serveren: alle sektioner (til en spiller, der tilslutter sig). Rører IKKE lastSent: pakkerne går kun til den nye +-- spiller, så en ændring, de andre endnu ikke har fået, skal stadig broadcastes ved næste tick (review H1). +function ADSync.collectAll(sync) + local packets = {} + local texts = collectTexts(sync) + for _, section in ipairs(sync.sections) do + local text = texts[section.name] + if text ~= nil then + for _, packet in ipairs(packetsFor(sync, section.name, text)) do packets[#packets + 1] = packet end + end + end + return packets +end + +-- Klienten: én pakke; når sektionen er samlet, anvendes den. Fejl (ødelagt pakke, ukendt sektion) vælter intet. +function ADSync.receive(sync, packet) + local text = ADNet.addChunk(sync.assembly, packet.section, packet.version, packet.index, packet.total, packet.data) + if text == nil then return false end + local section = nil + for _, candidate in ipairs(sync.sections) do if candidate.name == packet.section then section = candidate end end + if section == nil then return false end + local ok, err = pcall(function() section.apply(ADNet.decode(ADNet.fromWire(text))) end) + if not ok and Logging ~= nil then Logging.warning(LOG_PREFIX .. "multiplayer-synk: %s kunne ikke anvendes: %s", packet.section, tostring(err)) end + return ok +end + +---------------------------------------------------------------- spillet + +-- Modulernes konfiguration (etape 2c). Kun rene data (ingen køretøjs-objekter — ADNet afviser dem). +local function fieldsCollect() + local state = ADFieldJobs.state + return {fields = state.fields, fleet = state.fleet, fleetMode = state.fleetMode, excluded = state.excluded, + manual = state.manual, playerTrips = state.playerTrips, paused = state.paused, resumed = state.resumed} +end + +local function fieldsApply(value) + local state = ADFieldJobs.state + for _, key in ipairs({"fields", "fleet", "excluded", "manual", "playerTrips", "resumed"}) do state[key] = value[key] or {} end + state.fleetMode = value.fleetMode or "all" + state.paused = value.paused == true +end + +function ADSync.gameSections() + return { + {name = "RUNS", collect = function() return ADRunsController.store end, + apply = function(value) ADRunsController.store = value end}, + {name = "FIELDS", collect = fieldsCollect, apply = fieldsApply}, + {name = "NAMES", collect = function() return ADNames.byId end, apply = function(value) ADNames.byId = value end}, + {name = "SETTINGS", collect = function() return ADSettings.snapshot() end, apply = function(value) ADSettings.restore(value) end}, + {name = "SELLBLOCK", collect = function() return ADSellBlock.blocked end, apply = function(value) ADSellBlock.blocked = value or {} end}, + {name = "LOCKS", collect = function() return ADLivestock.locks end, apply = function(value) ADLivestock.locks = value or {} end}, + {name = "SILOCFG", collect = function() return ADFieldSiloConfig.toRecord(ADFieldSilos.config) end, + apply = function(value) ADFieldSilos.config = ADFieldSiloConfig.fromRecord(value) end}, + {name = "CHAINSTATE", collect = function() return ADChain.state end, apply = function(value) ADChain.state = value end}, + } +end + +-- Kun i et multiplayer-spil (singleplayer er helt uberørt). +local function isMultiplayer() + local info = g_currentMission ~= nil and g_currentMission.missionDynamicInfo or nil + return info ~= nil and info.isMultiplayer == true +end + +ADSync.sinceMs = 0 +local loggedSizes, loggedTickError = false, nil +function ADSync.serverTick(dt) + if g_server == nil or not isMultiplayer() or ADSyncEvent == nil then return end + ADSync.sinceMs = ADSync.sinceMs + (dt or 0) + if ADSync.sinceMs < ADSync.SYNC_MS then return end + ADSync.sinceMs = 0 + local ok, err = pcall(function() + ADSync.game = ADSync.game or ADSync.new(ADSync.gameSections()) + local packets = ADSync.collectChanged(ADSync.game) + if not loggedSizes and #packets > 0 then + -- én gang: hvor store sektionerne er (review M2: mål trafikken in-game) + loggedSizes = true + local sizes = {} + for name, text in pairs(ADSync.game.lastSent) do sizes[#sizes + 1] = string.format("%s %d", name, #text) end + table.sort(sizes) + Logging.info(LOG_PREFIX .. "multiplayer-synk: sektioner (tegn) %s", table.concat(sizes, ", ")) + end + for _, packet in ipairs(packets) do g_server:broadcastEvent(ADSyncEvent.new(packet)) end + end) + if not ok and loggedTickError ~= tostring(err) then + loggedTickError = tostring(err) + Logging.warning(LOG_PREFIX .. "multiplayer-synk fejlede: %s", tostring(err)) + end +end + +if Class ~= nil and Event ~= nil and InitEventClass ~= nil then + ADSyncEvent = {} + local ADSyncEvent_mt = Class(ADSyncEvent, Event) + InitEventClass(ADSyncEvent, "ADSyncEvent") + + function ADSyncEvent.emptyNew() return Event.new(ADSyncEvent_mt) end + + function ADSyncEvent.new(packet) + local self = ADSyncEvent.emptyNew() + self.packet = packet + return self + end + + function ADSyncEvent:writeStream(streamId, connection) + local p = self.packet + streamWriteString(streamId, p.section) + streamWriteInt32(streamId, p.version) + streamWriteUInt16(streamId, p.index) + streamWriteUInt16(streamId, p.total) + streamWriteString(streamId, p.data) + end + + function ADSyncEvent:readStream(streamId, connection) + local section = streamReadString(streamId) + local version = streamReadInt32(streamId) + local index = streamReadUInt16(streamId) + local total = streamReadUInt16(streamId) + self.packet = {section = section, version = version, index = index, total = total, data = streamReadString(streamId)} + self:run(connection) + end + + -- Kun server -> klient: en klient anvender serverens tilstand + function ADSyncEvent:run(connection) + -- kun en ren klient anvender: værten (og singleplayer) har selv sandheden (review H2) + if g_server ~= nil or not connection:getIsServer() then return end + ADSync.client = ADSync.client or ADSync.new(ADSync.gameSections()) + ADSync.receive(ADSync.client, self.packet) + end + + -- En spiller, der tilslutter sig, får alle sektioner (samme krog som Courseplays CpJoinEvent). + if FSBaseMission ~= nil and FSBaseMission.onConnectionFinishedLoading ~= nil then + FSBaseMission.onConnectionFinishedLoading = Utils.appendedFunction(FSBaseMission.onConnectionFinishedLoading, + function(_, connection) + -- kun i multiplayer (singleplayer har også en lokal forbindelse — review H2) + if connection == nil or g_server == nil or not isMultiplayer() then return end + if connection.getIsLocal ~= nil and connection:getIsLocal() then return end + local ok, err = pcall(function() + ADSync.game = ADSync.game or ADSync.new(ADSync.gameSections()) + for _, packet in ipairs(ADSync.collectAll(ADSync.game)) do connection:sendEvent(ADSyncEvent.new(packet)) end + end) + if not ok then Logging.warning(LOG_PREFIX .. "multiplayer-synk ved tilslutning fejlede: %s", tostring(err)) end + end) + end +end diff --git a/FS25_ADSmartPickup/modDesc.xml b/FS25_ADSmartPickup/modDesc.xml index f4b5a61..2d05f68 100644 --- a/FS25_ADSmartPickup/modDesc.xml +++ b/FS25_ADSmartPickup/modDesc.xml @@ -43,6 +43,7 @@ Menu: ESC-menuen, siden "Smart Pickup". Statusvindue: numpad *. Kræver AutoDriv +