-- netplay.lua (14/10/2026) : jeu en ligne a deux, commun a tous les jeux. -- -- Principe ("lockstep") : chaque joueur fait tourner son propre emulateur. -- A chaque image, on envoie l'etat de SA manette (lue sur le port 1) a -- l'autre joueur, et on applique les deux manettes, joueur 1 et joueur 2, -- avec INPUT_DELAY images de retard pour absorber le trajet internet. Les -- deux jeux recoivent exactement les memes entrees : ils restent identiques. -- -- Liaison avec BizHawkNetplay.exe (ExternalTools) par memoire partagee : -- BizHawkNetplay_FromNet (lue) : "ROLE", "STATUS", messages du programme -- ("P id texte") puis l'instantane de l'autre joueur ; -- BizHawkNetplay_ToNet (ecrite) : notre instantane, a savoir -- "I premiere_image hex,hex,..." (fenetre de nos manettes) et nos -- messages de controle "C id texte". -- -- Depart identique : l'hote sauvegarde (netplay\sync.State), le programme -- envoie le fichier, l'invite le charge ; l'hote recharge aussi le sien pour -- que les deux passent par les memes evenements de chargement. -- -- Controle : toutes les HASH_INTERVAL images, empreinte de la RAM echangee ; -- en cas de difference, resynchronisation automatique par l'hote. -- -- Branchement dans un jeu : dofile(ce fichier), netplay_init(dossier racine -- BizHawk avec "\" final), puis netplay_before_frame() juste avant chaque -- emu.frameadvance(). Sans BizHawkNetplay.exe, rien ne change (verifie -- seulement une fois par seconde si le programme est apparu). local NP = {} NP.INPUT_DELAY = 3 NP.WINDOW = 30 NP.HASH_INTERVAL = 120 -- Releve hexadecimal de la RAM a chaque controle (diagnostic seulement : -- couteux, provoquait des a-coups du son toutes les 2 s). NP.DEBUG_DUMPS = false -- 14/10 : releves de RAM imposes aux memes images de la session 1 sur les -- deux PC (diagnostic). 20/10 : desactive (vide). NP.FIXED_DUMPS = {} NP.SPIN_MS = 40 -- 14/10 (idee utilisateur) : vitesse commune reglee sur le PC le plus lent. -- Toutes les SPEED_WINDOW images, l'hote compte les images ou il a du -- attendre le partenaire : au-dela de SPEED_WAIT_HIGH, les deux emulateurs -- passent a la vitesse reellement atteinte moins SPEED_MARGIN % ; sous -- SPEED_WAIT_LOW, on remonte de SPEED_STEP %. Plus d'a-coups (l'hote ne -- fonce plus pour s'arreter ensuite), donc un son regulier. -- 14/10 : DESACTIVE apres essai (musique externe decalee par rapport au jeu, -- son de BizHawk hache en dessous de 100 %). NP.SPEED_ADAPT = false NP.SPEED_WINDOW = 1200 NP.SPEED_WAIT_HIGH = 60 NP.SPEED_WAIT_LOW = 6 NP.SPEED_MARGIN = 3 NP.SPEED_STEP = 3 NP.SPEED_MIN = 50 NP.MAP_SIZE = 16384 NP.FROM = "BizHawkNetplay_FromNet" NP.TO = "BizHawkNetplay_ToNet" local BUTTONS = { GEN = { "Up", "Down", "Left", "Right", "A", "B", "C", "Start", "X", "Y", "Z", "Mode" }, SNES = { "Up", "Down", "Left", "Right", "Select", "Start", "Y", "B", "X", "A", "L", "R" }, NES = { "Up", "Down", "Left", "Right", "Select", "Start", "B", "A" }, } local state = "off" -- off | waiting | syncing | playing local root = "" local role = nil local netframe = 0 local local_inputs = {} local remote_inputs = {} local controls = {} -- nos messages : { id, texte, image d'envoi } local next_control_id = 1 local seen_peer_controls = {} local seen_program_controls = {} local my_hashes = {} local peer_hashes = {} local last_probe = -9999 local last_status = nil local wait_announced = false -- Session : numero de la synchronisation en cours (choisi par l'hote, -- annonce dans SAVE_READY). Les manettes d'une autre session sont ignorees. local stats = { start = nil, wait = 0, frames = 0, cost = 0 } local resync_at = nil local speed = { value = 100, start = nil, frames = 0, waited = 0 } local function set_speed(value) speed.value = value pcall(client.speedmode, value) end local session = 0 local state_arrived = false local announced_start = false local dumps = 0 local applied_local = nil -- 14/10 : emu.yield() rend la main SANS mettre l'emulation en pause : le jeu -- continuait sans les manettes du partenaire pendant chaque attente (depart -- avant la connexion, desynchronisation toutes les 2 s). Toute attente met -- donc l'emulateur en pause, relachee a la fin de netplay_before_frame. local paused_by_netplay = false local function hold() if not paused_by_netplay then client.pause() paused_by_netplay = true end emu.yield() end local function release() if paused_by_netplay then client.unpause() paused_by_netplay = false end end -- Journal du script (netplay\netplay_lua_log.txt) : etapes de la -- synchronisation, pour comprendre un blocage. local function nlog(text) local f = io.open(root .. "netplay" .. string.char(92) .. "netplay_lua_log.txt", "a") if f then f:write(os.date("%H:%M:%S"), " image=", tostring(emu.framecount()), " ", tostring(role), " ", text, string.char(10)) f:close() end end local function speak(text) if nvda_speak_interrupt then nvda_speak_interrupt(text) elseif nvda_speak then nvda_speak(text) end end local function buttons() return BUTTONS[emu.getsystemid()] or BUTTONS.GEN end -- 14/10 : la memoire partagee peut etre lue PENDANT qu'elle est ecrite -- (message a moitie ancien / a moitie nouveau : bouton faux, jeux qui -- divergent au hasard). Chaque message finit par "E somme" ; un message -- dont la somme ne correspond pas est ignore et relu ensuite. local function checksum(text) local sum = 0 for i = 1, #text do sum = (sum + text:byte(i)) % 65521 end return sum end local function seal(body) return body .. "\nE " .. checksum(body) end local function unseal(text) local body, sum = text:match("^(.*)\nE (%d+)$") if not body or checksum(body) ~= tonumber(sum) then return nil end return body end local function read_inbox() local ok, head = pcall(comm.mmfRead, NP.FROM, 8) if not ok or not head then return nil end local nl = head:find("\n", 1, true) if not nl then return nil end local length = tonumber(head:sub(1, nl - 1)) if not length or nl + length > NP.MAP_SIZE then return nil end local ok2, raw = pcall(comm.mmfRead, NP.FROM, nl + length) if not ok2 or not raw then return nil end return unseal(raw:sub(nl + 1, nl + length)) end local function write_outbox() local parts = {} local first = netframe + NP.INPUT_DELAY - NP.WINDOW + 1 if first < 0 then first = 0 end local values = {} for f = first, netframe + NP.INPUT_DELAY do values[#values + 1] = local_inputs[f] or "0" end parts[#parts + 1] = "I " .. session .. " " .. first .. " " .. table.concat(values, ",") for _, c in ipairs(controls) do parts[#parts + 1] = "C " .. c.id .. " " .. c.text end local body = seal(table.concat(parts, "\n")) pcall(comm.mmfWrite, NP.TO, #body .. "\n" .. body) end local function send_control(text) controls[#controls + 1] = { id = next_control_id, text = text, frame = emu.framecount() } next_control_id = next_control_id + 1 while #controls > 12 do table.remove(controls, 1) end write_outbox() end -- Analyse de l'instantane recu : manettes, messages de l'autre joueur et du -- programme. Renvoie le statut de connexion. local function process_inbox(on_control) local text = read_inbox() if not text then return nil end local status = nil local program_messages = {} for line in text:gmatch("[^\n]+") do local key, rest = line:match("^(%S+) (.*)$") if key == "ROLE" then role = rest elseif key == "STATUS" then status = rest elseif key == "I" then local sess, first, list = rest:match("^(%d+) (%d+) (.*)$") if first and tonumber(sess) == session then local f = tonumber(first) for value in list:gmatch("[^,]+") do if remote_inputs[f] == nil then remote_inputs[f] = value end f = f + 1 end end elseif key == "C" or key == "P" then local id, body = rest:match("^(%d+) (.*)$") local seen = key == "C" and seen_peer_controls or seen_program_controls if id and not seen[id] then seen[id] = true -- 14/10 : messages du programme ("P", ex. STATE_ARRIVED) traites -- APRES ceux de l'autre joueur ("C", ex. SAVE_READY) : sinon -- SAVE_READY, lu ensuite, effacait l'arrivee de la partie. if on_control then if key == "P" then program_messages[#program_messages + 1] = body else on_control(key, body) end end end end end if on_control then for _, body in ipairs(program_messages) do on_control("P", body) end end return status end local function encode_local() -- 14/10 : getimmediate renvoie la manette AVEC nos forcages de l'image -- precedente. joypad.set({}) les retire et relit la manette physique -- (JoypadApi.Set : UnSet de chaque bouton, puis LatchFromPhysical). -- 14/10 : seulement le joueur 1 (la manette locale y est branchee) : -- deux fois moins de relectures de la manette par BizHawk. joypad.set({}, 1) local pad = joypad.getimmediate() or {} local value = 0 for i, name in ipairs(buttons()) do if pad["P1 " .. name] then value = value + 2 ^ (i - 1) end end return string.format("%x", value) end -- 14/10 : joypad.set(table) parcourt TOUS les boutons de la console et -- RETIRE le forcage de ceux absents de la table (JoypadApi.Set). Deux appels -- separes (joueur 1 puis joueur 2) annulaient donc le forcage du joueur 1 : -- la manette locale du joueur 1 repassait directement (les deux personnages -- bougeaient chez l'invite, et l'hote jouait sans le retard commun). Les -- deux joueurs sont donc forces en UN seul appel. local function apply_both(hex1, hex2) local set = {} for player, hex in ipairs({ hex1, hex2 }) do local value = tonumber(hex or "0", 16) or 0 for i, name in ipairs(buttons()) do set["P" .. player .. " " .. name] = math.floor(value / 2 ^ (i - 1)) % 2 == 1 end end joypad.set(set) end local function memory_hash() local ok, h = pcall(memory.hash_region, 0, mainmemory.getcurrentmemorydomainsize(), mainmemory.getname()) return ok and h or "?" end local function reset_session() netframe = 0 local_inputs = {} remote_inputs = {} my_hashes = {} peer_hashes = {} wait_announced = false end -- Controles communs : empreintes, demandes de resynchronisation, et -- depart d'une nouvelle synchronisation (cote invite). local function handle_common(kind, body) local hsession, hframe, hash = body:match("^H (%d+) (%d+) (%S+)$") if kind == "C" and hframe then if tonumber(hsession) == session then peer_hashes[tonumber(hframe)] = hash end return true end if kind == "C" and body == "RESYNC" and role == "host" then resync_at = resync_at or (netframe + 90) return true end local new_speed = body:match("^SPEED (%d+)$") if kind == "C" and new_speed then if role ~= "host" then set_speed(tonumber(new_speed)) nlog("vitesse " .. new_speed .. " %") end return true end local new_session = body:match("^SAVE_READY (%d+)$") if kind == "C" and new_session then nlog("recu SAVE_READY " .. new_session .. " etat=" .. state) end if kind == "P" and body == "STATE_ARRIVED" then nlog("recu STATE_ARRIVED") end if kind == "C" and new_session and role ~= "host" and not (state == "playing" and tonumber(new_session) == session) then session = tonumber(new_session) state_arrived = false if state == "playing" then state = "waiting" end return true end if kind == "P" and body == "STATE_ARRIVED" then state_arrived = true return true end return false end -- Depart synchronise. L'hote sauvegarde puis attend LOADED ; l'invite -- attend STATE_ARRIVED, charge, puis annonce LOADED. local function sync_start() nlog("debut synchronisation") local path = root .. "netplay\\sync.State" reset_session() if role == "host" then if not announced_start then speak("Netplay : synchronisation avec ton partenaire.") end session = session + 1 savestate.save(path, true) savestate.load(path, true) send_control("SAVE_READY " .. session) local loaded = false local waited = 0 while not loaded do local status = process_inbox(function(kind, body) if not handle_common(kind, body) and kind == "C" and body == "LOADED " .. session then loaded = true end end) if status ~= "connecte" then state = "waiting"; return end hold() end else if not announced_start then speak("Netplay : reception de la partie de l'hote.") end while not state_arrived do local status = process_inbox(handle_common) if status ~= "connecte" then state = "waiting"; return end hold() end state_arrived = false savestate.load(path, true) send_control("LOADED " .. session) nlog("partie chargee, LOADED " .. session .. " envoye") end reset_session() state = "playing" nlog("depart session " .. session) if not announced_start then announced_start = true speak("Netplay : partie synchronisee, c'est parti.") end end -- A appeler juste avant chaque emu.frameadvance(). local first_call = true local function before_frame_body() -- 14/10 (idee utilisateur) : si le netplay est lance avec le jeu, on -- attend la connexion du partenaire AVANT la premiere image. Les deux -- jeux et les scripts d'accessibilite partent alors du meme point, tout -- neufs des deux cotes (sinon l'historique des scripts de l'hote, -- absent chez l'invite, peut faire diverger les parties). if first_call then first_call = false if process_inbox(handle_common) then -- 14/10 : traiter (ne pas jeter) les messages deja arrives speak("Netplay : en attente du partenaire avant de lancer le jeu.") while true do local status = process_inbox(handle_common) if status == "connecte" then break end hold() end state = "syncing" sync_start() return end end if state == "off" then if emu.framecount() - last_probe < 60 and emu.framecount() >= last_probe then return end last_probe = emu.framecount() local status = process_inbox(handle_common) if status then state = "waiting" speak("Netplay actif, en attente du partenaire.") end return end if state == "waiting" then local status = process_inbox(handle_common) if status ~= last_status then last_status = status end if status == "connecte" then state = "syncing" sync_start() end return end if state ~= "playing" then return end -- Notre manette pour l'image netframe + INPUT_DELAY. local cost_start = os.clock() local_inputs[netframe + NP.INPUT_DELAY] = encode_local() local_inputs[netframe - NP.WINDOW * 2] = nil write_outbox() -- Attendre la manette de l'autre joueur pour cette image. local cost_before_wait = os.clock() - cost_start local waited = 0 local wait_start = os.clock() if netframe >= NP.INPUT_DELAY and remote_inputs[netframe] == nil then speed.waited = speed.waited + 1 local deadline = os.clock() + NP.SPIN_MS / 1000 repeat process_inbox(handle_common) until remote_inputs[netframe] ~= nil or state ~= "playing" or os.clock() > deadline end while state == "playing" and netframe >= NP.INPUT_DELAY and remote_inputs[netframe] == nil do local status = process_inbox(handle_common) if status ~= "connecte" then state = "waiting" speak("Netplay : partenaire deconnecte. Tu continues seul.") set_speed(100) nlog("partenaire deconnecte") return end if remote_inputs[netframe] ~= nil then break end waited = waited + 1 if waited == 300 and not wait_announced then wait_announced = true speak("Netplay : en attente du partenaire.") end hold() end if waited == 0 then process_inbox(handle_common) end -- Resynchronisation demandee pendant l'attente : ne pas avancer. if state ~= "playing" then return end stats.wait = stats.wait + (os.clock() - wait_start) local cost_after = os.clock() stats.frames = stats.frames + 1 if stats.start == nil then stats.start = os.time() end if role == "host" and NP.SPEED_ADAPT then speed.frames = speed.frames + 1 if speed.start == nil then speed.start = os.time() end if speed.frames >= NP.SPEED_WINDOW then local elapsed = math.max(1, os.time() - speed.start) local fps = NP.SPEED_WINDOW / elapsed local target = speed.value if speed.waited > NP.SPEED_WAIT_HIGH then target = math.floor(fps * 100 / 60) - NP.SPEED_MARGIN elseif speed.waited < NP.SPEED_WAIT_LOW and speed.value < 100 then target = speed.value + NP.SPEED_STEP end target = math.max(NP.SPEED_MIN, math.min(100, target)) if target ~= speed.value then set_speed(target) send_control("SPEED " .. target) nlog(string.format("vitesse %d %% (%.0f images/s, %d images attendues)", target, fps, speed.waited)) end speed.start = os.time(); speed.frames = 0; speed.waited = 0 end end -- 20/10 : plus de releve de vitesse toutes les 600 images (diagnostic). if stats.frames >= 600 then stats.start = os.time(); stats.wait = 0; stats.frames = 0; stats.cost = 0 end local mine = local_inputs[netframe] or "0" local theirs = remote_inputs[netframe] or "0" applied_local = mine if role == "host" then apply_both(mine, theirs) else apply_both(theirs, mine) end remote_inputs[netframe - NP.WINDOW * 2] = nil -- Controle de synchronisation. if session == 1 and NP.FIXED_DUMPS[netframe] then local ok, bytes = pcall(mainmemory.read_bytes_as_array, 0, mainmemory.getcurrentmemorydomainsize()) if ok and bytes then local hex = {} for i = 0, #bytes do hex[#hex + 1] = string.format("%02X", bytes[i] or 0) end local out = io.open(root .. "netplay" .. string.char(92) .. "fixe_" .. (role or "?") .. "_" .. netframe .. ".txt", "w") if out then out:write(table.concat(hex)); out:close() end nlog("releve fixe image " .. netframe) end end if netframe > 0 and netframe % NP.HASH_INTERVAL == 0 then my_hashes[netframe] = memory_hash() -- Copie hexadecimale de la RAM pour le diagnostic de desynchronisation. if NP.DEBUG_DUMPS and dumps < 3 then my_dumps = my_dumps or {} local ok, bytes = pcall(mainmemory.read_bytes_as_array, 0, mainmemory.getcurrentmemorydomainsize()) if ok and bytes then my_dumps[netframe] = bytes end end send_control("H " .. session .. " " .. netframe .. " " .. my_hashes[netframe]) end for f, h in pairs(peer_hashes) do if my_hashes[f] then if my_hashes[f] ~= h then nlog("difference a l'image " .. f) if dumps < 3 and my_dumps and my_dumps[f] then dumps = dumps + 1 local out = io.open(root .. "netplay" .. string.char(92) .. "ram_" .. (role or "?") .. "_" .. f .. ".txt", "w") if out then local bytes = my_dumps[f] local hex = {} for i = 0, #bytes do hex[#hex + 1] = string.format("%02X", bytes[i] or 0) end out:write(table.concat(hex)) out:close() end end if role == "host" then resync_at = resync_at or (netframe + 90) else -- L'invite continue : l'hote declenchera la resynchronisation -- (s'arreter ici bloquerait l'hote en attente de nos manettes). send_control("RESYNC") end end peer_hashes[f] = nil my_hashes[f] = nil if my_dumps then my_dumps[f] = nil end end end stats.cost = stats.cost + cost_before_wait + (os.clock() - cost_after) netframe = netframe + 1 if resync_at and netframe >= resync_at then resync_at = nil state = "waiting" end end function netplay_before_frame() local ok, err = pcall(before_frame_body) release() if not ok then print("netplay : " .. tostring(err)) state = "off" end end function netplay_init(root_dir) root = root_dir or "" state = "off" last_probe = -9999 end function netplay_active() return state ~= "off" end -- 19/10 : manette appliquee a NOTRE personnage a la derniere image (avec le -- retard commun), au format de joypad.get(1) : { Up = true, ... }. nil hors -- partie en ligne : le jeu lit alors directement la manette locale. function netplay_local_pad() if state ~= "playing" or applied_local == nil then return nil end local value = tonumber(applied_local, 16) or 0 local pad = {} for i, name in ipairs(buttons()) do pad[name] = math.floor(value / 2 ^ (i - 1)) % 2 == 1 end return pad end