Files
LonaRPG-Online-Games/ModScripts/99999999999999999999_PlayerPresenceVersionGate.rb
T

741 lines
24 KiB
Ruby
Raw Normal View History

2026-10-29 21:59:06 +04:00
# encoding: UTF-8
#==============================================================================
# PlayerPresenceVersionGate 1.0.8 BLACK-DIALOG-BACKGROUND
#------------------------------------------------------------------------------
# Separate client feature:
# - pause/chat icon above remote players' heads
# - hard game-build gate using Game.ini -> Title=LonaRPG Online B.x.x.x
#
# Assets expected:
# Graphics/Online/status_pause.png
# Graphics/Online/status_chat.png
#
# Server peer:
# 00000_PlayerPresenceVersionGate-1.0.2.jar # server protocol unchanged
#==============================================================================
module MPPlayerPresenceVersionGate
CLIENT_PATCH_VERSION = "1.0.8"
# Mobile builds may not expose Game.ini. Change this by hand together with
# server game-version.txt whenever the public game build changes.
FALLBACK_GAME_VERSION = "B.0.10.8.8.7"
TITLE_PREFIX = "LonaRPG Online"
ICON_DIR = "Graphics/Online/"
ICON_FILES = {
"pause" => "status_pause",
"chat" => "status_chat"
}
STATUS_GAP = 2
STATUS_ICON_SIZE = 16
STATUS_ICON_OUTLINE = 1
STATUS_HEARTBEAT_FRAMES = 180
UPDATE_URL = "https://lonarpg.online/Download/"
@custom_version_ok = false
@custom_version_sent = false
@blocked = false
@blocked_need = ""
@blocked_have = ""
@last_local_state = nil
@last_state_send_frame = -99_999
@remote_states = {}
@missing_asset_warned = {}
def self.frame
Graphics.frame_count.to_i
rescue
0
end
def self.reset_connection_state
@custom_version_ok = false
@custom_version_sent = false
@last_local_state = nil
@last_state_send_frame = -99_999
@remote_states = {}
# @blocked intentionally stays true once a mismatched build is rejected.
true
rescue
false
end
def self.custom_version_ok?
!!@custom_version_ok
rescue
false
end
def self.blocked?
!!@blocked
rescue
false
end
def self.read_game_ini_text
path = File.expand_path("Game.ini", Dir.pwd.to_s)
raw = File.binread(path)
begin
if raw.bytesize >= 2 && raw.getbyte(0) == 0xFF && raw.getbyte(1) == 0xFE
return raw.byteslice(2, raw.bytesize - 2).force_encoding("UTF-16LE").encode("UTF-8", :invalid => :replace, :undef => :replace, :replace => "")
elsif raw.bytesize >= 2 && raw.getbyte(0) == 0xFE && raw.getbyte(1) == 0xFF
return raw.byteslice(2, raw.bytesize - 2).force_encoding("UTF-16BE").encode("UTF-8", :invalid => :replace, :undef => :replace, :replace => "")
end
rescue
end
begin
text = raw.dup
text.force_encoding("UTF-8") if text.respond_to?(:force_encoding)
return text.encode("UTF-8", "UTF-8", :invalid => :replace, :undef => :replace, :replace => "")
rescue
begin
return raw.force_encoding("Windows-1251").encode("UTF-8", :invalid => :replace, :undef => :replace, :replace => "")
rescue
return raw.to_s
end
end
rescue => e
puts "[PRESENCE/GATE] Game.ini read failed: #{e.class}: #{e.message}" rescue nil
""
end
def self.game_title
text = read_game_ini_text
text.each_line do |line|
if line.to_s =~ /^\s*Title\s*=\s*(.*?)\s*$/i
return $1.to_s.strip
end
end
""
rescue
""
end
def self.client_game_version
title = game_title.to_s.strip
unless title.empty?
if title =~ /^#{Regexp.escape(TITLE_PREFIX)}\s+(.+)$/i
version = $1.to_s.strip
return version unless version.empty?
else
# Preserve desktop compatibility with custom Title values.
return title
end
end
fallback = FALLBACK_GAME_VERSION.to_s.strip
puts "[PRESENCE/GATE] Game.ini unavailable/Title missing; using RB fallback build=#{fallback.inspect}" rescue nil
fallback
rescue => e
fallback = FALLBACK_GAME_VERSION.to_s.strip rescue ""
puts "[PRESENCE/GATE] version fallback after #{e.class}: #{e.message}; build=#{fallback.inspect}" rescue nil
fallback
end
def self.send_build_version
return false unless defined?(WebSocket)
return false unless WebSocket.respond_to?(:connected?) && WebSocket.connected?
version = client_game_version
puts "[PRESENCE/GATE] client build=#{version.inspect} Game.ini Title=#{game_title.inspect} fallback=#{FALLBACK_GAME_VERSION.inspect}" rescue nil
result = WebSocket.send_line("client_build:#{wire_safe(version)}")
ok = !result.nil? && result.to_i >= 0
@custom_version_sent = ok
puts "[PRESENCE/GATE] client_build send failed result=#{result.inspect}" unless ok rescue nil
ok
rescue => e
@custom_version_sent = false
puts "[PRESENCE/GATE] build send failed: #{e.class}: #{e.message}" rescue nil
false
end
def self.wire_safe(value)
value.to_s.gsub(/[\r\n\0:]/, "_").strip[0, 96]
rescue
""
end
def self.on_builtin_version_ok
return if blocked?
send_build_version unless @custom_version_sent
rescue
end
def self.on_custom_version_ok(server_version)
return if blocked?
@custom_version_ok = true
puts "[PRESENCE/GATE] version accepted #{server_version}" rescue nil
rescue
end
def self.block_version!(need, have)
return true if @blocked
@blocked = true
@custom_version_ok = false
@blocked_need = need.to_s.strip
@blocked_have = have.to_s.strip
puts "[PRESENCE/GATE] BLOCKED need=#{@blocked_need.inspect} have=#{@blocked_have.inspect}" rescue nil
begin
if defined?(MPConnectStatus)
MPConnectStatus.instance_variable_set(:@manual_disconnect, true)
end
rescue
end
# The cloud bootstrap progress sprite is global and survives a scene
# switch. Remove it before taking the dialog background snapshot.
dismiss_loading_ui
Graphics.update rescue nil
# Put the unskippable scene first. A later socket close must not be able
# to send the player back to the title/loading scene.
ensure_blocked_scene
begin
WebSocket.disconnect if defined?(WebSocket) && WebSocket.respond_to?(:connected?) && WebSocket.connected?
rescue
end
true
rescue => e
puts "[PRESENCE/GATE] block failed: #{e.class}: #{e.message}" rescue nil
false
end
def self.ensure_blocked_scene
return false unless @blocked
return false unless defined?(SceneManager) && defined?(Scene_MPGameVersionBlocked)
current = SceneManager.scene rescue nil
return true if current && current.is_a?(Scene_MPGameVersionBlocked)
SceneManager.snapshot_for_background(false) rescue nil
SceneManager.goto(Scene_MPGameVersionBlocked)
true
rescue => e
puts "[PRESENCE/GATE] blocked scene failed: #{e.class}: #{e.message}" rescue nil
false
end
def self.blocked_need
@blocked_need.to_s
rescue
""
end
def self.blocked_have
@blocked_have.to_s
rescue
""
end
def self.dismiss_loading_ui
if defined?(MPGameLoadProgress) && MPGameLoadProgress.respond_to?(:dispose)
MPGameLoadProgress.dispose
end
if defined?(System_NotificationOverlay) && System_NotificationOverlay.respond_to?(:dispose)
System_NotificationOverlay.dispose
end
true
rescue => e
puts "[PRESENCE/GATE] loading overlay cleanup failed: #{e.class}: #{e.message}" rescue nil
false
end
# The version lock protects the running online session, but the player must
# still be able to leave its explanatory dialog through an explicit choice.
def self.leave_blocked_screen!
@blocked = false
@blocked_need = ""
@blocked_have = ""
@custom_version_ok = false
@custom_version_sent = false
true
rescue
false
end
def self.open_update_page
Thread.new { system("start #{UPDATE_URL}") }
true
rescue => e
puts "[PRESENCE/GATE] update page open failed: #{e.class}: #{e.message}" rescue nil
false
end
def self.normalize_state(value)
s = value.to_s.downcase.strip
return "pause" if s == "pause"
return "chat" if s == "chat"
"none"
rescue
"none"
end
def self.receive_remote_state(pid, state)
player_id = pid.to_i
return if player_id <= 0
state = normalize_state(state)
if state == "none"
@remote_states.delete(player_id)
else
@remote_states[player_id] = state
end
true
rescue
false
end
def self.remote_state(pid)
@remote_states[pid.to_i].to_s
rescue
""
end
def self.clear_remote_states
@remote_states = {}
rescue
end
def self.chat_open?
defined?(MPChat) && MPChat.respond_to?(:active?) && MPChat.active?
rescue
false
end
def self.menu_open?
return false unless defined?(SceneManager)
scene = SceneManager.scene rescue nil
return false if scene.nil?
return false if defined?(Scene_MPGameVersionBlocked) && scene.is_a?(Scene_MPGameVersionBlocked)
return true if defined?(Scene_Menu) && scene.is_a?(Scene_Menu)
return true if defined?(Scene_MenuBase) && scene.is_a?(Scene_MenuBase)
false
rescue
false
end
def self.desired_local_state
return "none" if blocked?
return "chat" if chat_open?
return "pause" if menu_open?
"none"
rescue
"none"
end
def self.can_send_ui_state?
return false unless custom_version_ok?
return false unless defined?(WebSocket)
WebSocket.respond_to?(:connected?) && WebSocket.connected?
rescue
false
end
def self.send_ui_state(state, force=false)
return false unless can_send_ui_state?
state = normalize_state(state)
now = frame
changed = (@last_local_state.to_s != state)
due = (now - @last_state_send_frame.to_i) >= STATUS_HEARTBEAT_FRAMES
return false unless force || changed || due
WebSocket.send_line("ui_state:#{state}")
@last_local_state = state
@last_state_send_frame = now
true
rescue
false
end
def self.tick
if blocked?
ensure_blocked_scene
return
end
send_ui_state(desired_local_state, false)
rescue
end
def self.icon_source_bitmap(state)
state = normalize_state(state)
name = ICON_FILES[state]
return nil if name.nil?
@icon_source_cache ||= {}
return @icon_source_cache[state] if @icon_source_cache.has_key?(state)
bitmap = nil
begin
bitmap = Cache.load_bitmap(ICON_DIR, name)
rescue
begin
bitmap = Bitmap.new("#{ICON_DIR}#{name}.png")
rescue => e
unless @missing_asset_warned[state]
@missing_asset_warned[state] = true
puts "[PRESENCE] missing #{ICON_DIR}#{name}.png (#{e.class}: #{e.message})" rescue nil
end
bitmap = nil
end
end
@icon_source_cache[state] = bitmap
bitmap
rescue
nil
end
# The source PNG may be any size. Render a fixed 16x16 nearest-neighbour
# pixel icon with a 1px black outline, matching the nickname emoji scale.
# This avoids huge 64/128px status art covering half the screen.
def self.icon_bitmap(state)
state = normalize_state(state)
return nil unless state == "pause" || state == "chat"
@icon_cache ||= {}
return @icon_cache[state] if @icon_cache[state]
src = icon_source_bitmap(state)
return nil if src.nil? || src.width.to_i <= 0 || src.height.to_i <= 0
icon_size = STATUS_ICON_SIZE.to_i
pad = STATUS_ICON_OUTLINE.to_i
out_size = icon_size + pad * 2
out = Bitmap.new(out_size, out_size)
scaled = Bitmap.new(icon_size, icon_size)
# Explicit nearest-neighbour sampling keeps deliberate pixel art crisp.
0.upto(icon_size - 1) do |y|
sy = [(y * src.height.to_i / icon_size), src.height.to_i - 1].min
0.upto(icon_size - 1) do |x|
sx = [(x * src.width.to_i / icon_size), src.width.to_i - 1].min
px = src.get_pixel(sx, sy)
scaled.set_pixel(x, y, px) if px
end
end
black = Color.new(0, 0, 0, 255)
if pad > 0
0.upto(icon_size - 1) do |y|
0.upto(icon_size - 1) do |x|
px = scaled.get_pixel(x, y)
next if px.nil? || px.alpha.to_i <= 0
(-pad).upto(pad) do |oy|
(-pad).upto(pad) do |ox|
next if ox == 0 && oy == 0
tx = x + pad + ox
ty = y + pad + oy
next if tx < 0 || ty < 0 || tx >= out_size || ty >= out_size
out.set_pixel(tx, ty, black)
end
end
end
end
end
out.blt(pad, pad, scaled, scaled.rect)
scaled.dispose rescue nil
@icon_cache[state] = out
out
rescue => e
scaled.dispose rescue nil
puts "[PRESENCE] icon resize failed #{state}: #{e.class}: #{e.message}" rescue nil
nil
end
end
#==============================================================================
# In-world version-block dialog. It deliberately uses the same Window_Message
# and Teller portrait machinery as the normal death scene.
#==============================================================================
class Scene_MPGameVersionBlocked < Scene_Base
def start
MPPlayerPresenceVersionGate.dismiss_loading_ui
super
create_version_background
create_version_dialog
end
def create_version_background
@version_background = Sprite.new
@version_background.z = 0
@version_background_bitmap = Bitmap.new(Graphics.width, Graphics.height)
@version_background_bitmap.fill_rect(
0, 0, Graphics.width, Graphics.height, Color.new(0, 0, 0, 255)
)
@version_background.bitmap = @version_background_bitmap
rescue => e
puts "[PRESENCE/GATE] blocked background failed: #{e.class}: #{e.message}" rescue nil
end
def create_version_dialog
@version_choice = nil
@message_window = Window_Message.new
$game_message.clear
$game_message.background = 0
$game_message.position = 2
need = MPPlayerPresenceVersionGate.blocked_need
have = MPPlayerPresenceVersionGate.blocked_have
need = "неизвестно" if need.nil? || need.empty?
have = "неизвестно" if have.nil? || have.empty?
$game_message.add("\\ph\\SETpl[TellerNormal]\\SETpr[nil]\\c[4]Гадалка:\\C[0] Увы...\\n Нити судьбы изменились, и эта версия игры больше не ведёт в мир LonaRPG Online.\f" +
"\\SETpl[TellerConfused]\\c[4]Гадалка:\\C[0] Миру требуется версия \\C[6]#{need}\\C[0].\\n У тебя установлена версия \\C[6]#{have}\\C[0].\f" +
"\\SETpl[TellerOkay]\\c[4]Гадалка:\\C[0] Хочешь перейти на сайт и скачать обновление?")
$game_message.choices.push("Перейти на сайт LonaRPG Online")
$game_message.choices.push("Выйти в главное меню")
$game_message.choice_cancel_type = 0
$game_message.choice_proc = Proc.new { |index| @version_choice = index.to_i }
rescue => e
puts "[PRESENCE/GATE] blocked dialog failed: #{e.class}: #{e.message}" rescue nil
end
def update
super
$game_portraits.update if defined?($game_portraits) && $game_portraits
finish_version_dialog if !@version_choice.nil? && !$game_message.busy?
end
def finish_version_dialog
choice = @version_choice
@version_choice = nil
MPPlayerPresenceVersionGate.open_update_page if choice == 0
$game_message.clear rescue nil
$game_portraits.hide_all_portraits(true) rescue nil
MPPlayerPresenceVersionGate.leave_blocked_screen!
SceneManager.goto(Scene_MapTitle)
rescue => e
puts "[PRESENCE/GATE] blocked dialog exit failed: #{e.class}: #{e.message}" rescue nil
end
def terminate
@version_background.dispose if @version_background && !@version_background.disposed? rescue nil
@version_background_bitmap.dispose if @version_background_bitmap && !@version_background_bitmap.disposed? rescue nil
super
end
end
#==============================================================================
# While the dialog is open, unrelated network callbacks may not navigate away
# from it. The dialog's own explicit choices release the lock first.
#==============================================================================
if defined?(SceneManager)
module SceneManager
class << self
unless method_defined?(:mp_presence_gate_goto_without_version_lock)
alias mp_presence_gate_goto_without_version_lock goto
def goto(scene_class)
if defined?(MPPlayerPresenceVersionGate) && MPPlayerPresenceVersionGate.blocked? &&
defined?(Scene_MPGameVersionBlocked) && scene_class != Scene_MPGameVersionBlocked
scene_class = Scene_MPGameVersionBlocked
end
mp_presence_gate_goto_without_version_lock(scene_class)
end
end
if method_defined?(:call) && !method_defined?(:mp_presence_gate_call_without_version_lock)
alias mp_presence_gate_call_without_version_lock call
def call(scene_class)
if defined?(MPPlayerPresenceVersionGate) && MPPlayerPresenceVersionGate.blocked? &&
defined?(Scene_MPGameVersionBlocked)
return goto(Scene_MPGameVersionBlocked)
end
mp_presence_gate_call_without_version_lock(scene_class)
end
end
if method_defined?(:return) && !method_defined?(:mp_presence_gate_return_without_version_lock)
alias mp_presence_gate_return_without_version_lock return
def return
if defined?(MPPlayerPresenceVersionGate) && MPPlayerPresenceVersionGate.blocked? &&
defined?(Scene_MPGameVersionBlocked)
return goto(Scene_MPGameVersionBlocked)
end
mp_presence_gate_return_without_version_lock
end
end
end
end
end
#==============================================================================
# Network gate and remote UI status parser.
#------------------------------------------------------------------------------
# Mobile hardening:
# - uses prepend instead of another alias chain for WebSocket.parse/connect/
# disconnect;
# - is idempotent when the file is evaluated more than once;
# - catches a legacy recursive parser chain instead of killing mkxp-z with
# SystemStackError. The alias wrappers in this package are also guarded
# against double evaluation, so this rescue is only the final safety net.
#==============================================================================
if defined?(WebSocket)
module MPPlayerPresenceVersionGateWebSocketPatch
def parse(msg)
line = msg.to_s.strip
# IMPORTANT: do not let the normal parser see version_ok yet.
# Its normal action is to authenticate and begin bootstrap immediately.
if line == "version_ok" && !MPPlayerPresenceVersionGate.custom_version_ok?
MPPlayerPresenceVersionGate.on_builtin_version_ok
return
end
if line =~ /^client_build_ok(?::(.*))?$/
server_version = $1.to_s
MPPlayerPresenceVersionGate.on_custom_version_ok(server_version)
# Release the original multiplayer handshake only after our build gate.
super("version_ok")
MPPlayerPresenceVersionGate.send_ui_state(MPPlayerPresenceVersionGate.desired_local_state, true)
return
end
if line =~ /^client_build_bad:([^:]*)(?::(.*))?$/
need = $1.to_s
have = $2.to_s
MPPlayerPresenceVersionGate.block_version!(need, have)
return
end
if line =~ /^player_ui_status:(\d+):(none|pause|chat)$/
MPPlayerPresenceVersionGate.receive_remote_state($1.to_i, $2)
return
end
super(msg)
rescue SystemStackError => e
# Android/mobile mkxp-z has a noticeably smaller usable Ruby stack than
# desktop. A stale/double-loaded legacy alias wrapper must not take down
# the whole client. Log once per process and drop only the bad packet.
unless instance_variable_defined?(:@mp_presence_stack_guard_reported) && @mp_presence_stack_guard_reported
@mp_presence_stack_guard_reported = true
begin
puts "[PRESENCE/GATE] blocked recursive WebSocket.parse chain: #{e.class}: #{e.message} packet=#{line.inspect}"
rescue
end
end
nil
end
def connect(*args, &block)
MPPlayerPresenceVersionGate.reset_connection_state
super(*args, &block)
end
def disconnect(*args, &block)
MPPlayerPresenceVersionGate.clear_remote_states
super(*args, &block)
end
end
begin
sc = WebSocket.singleton_class
unless sc.ancestors.include?(MPPlayerPresenceVersionGateWebSocketPatch)
sc.prepend(MPPlayerPresenceVersionGateWebSocketPatch)
end
rescue => e
puts "[PRESENCE/GATE] WebSocket prepend failed: #{e.class}: #{e.message}" rescue nil
end
end
#==============================================================================
# Local scene/chat state heartbeat.
#==============================================================================
class Scene_Base
unless method_defined?(:mp_presence_gate_update_without_tick)
alias mp_presence_gate_update_without_tick update
end
def update(*args, &block)
mp_presence_gate_update_without_tick(*args, &block)
MPPlayerPresenceVersionGate.tick if defined?(MPPlayerPresenceVersionGate)
end
end
#==============================================================================
# Remote overhead icon. Independent of nick style/VIP/custom emojis.
#==============================================================================
class Sprite_Character < Sprite_Base
unless method_defined?(:mp_presence_gate_update_without_status_icon)
alias mp_presence_gate_update_without_status_icon update
end
def update(*args, &block)
mp_presence_gate_update_without_status_icon(*args, &block)
mp_presence_gate_update_status_icon
end
def mp_presence_gate_remote_pid
return 0 unless @character
return 0 unless @character.instance_variable_defined?(:@net_player_id)
@character.instance_variable_get(:@net_player_id).to_i
rescue
0
end
def mp_presence_gate_dispose_status_icon
begin
@mp_presence_status_sprite.dispose if @mp_presence_status_sprite && !@mp_presence_status_sprite.disposed?
rescue
end
@mp_presence_status_sprite = nil
@mp_presence_status_value = nil
rescue
end
def mp_presence_gate_update_status_icon
pid = mp_presence_gate_remote_pid
if pid <= 0
mp_presence_gate_dispose_status_icon if @mp_presence_status_sprite
return
end
state = MPPlayerPresenceVersionGate.remote_state(pid).to_s
unless state == "pause" || state == "chat"
mp_presence_gate_dispose_status_icon if @mp_presence_status_sprite
return
end
bitmap = MPPlayerPresenceVersionGate.icon_bitmap(state)
if bitmap.nil?
mp_presence_gate_dispose_status_icon if @mp_presence_status_sprite
return
end
if @mp_presence_status_sprite.nil? || (@mp_presence_status_sprite.respond_to?(:disposed?) && @mp_presence_status_sprite.disposed?)
@mp_presence_status_sprite = Sprite.new(self.viewport)
@mp_presence_status_value = nil
end
if @mp_presence_status_value.to_s != state || @mp_presence_status_sprite.bitmap != bitmap
@mp_presence_status_sprite.bitmap = bitmap
@mp_presence_status_sprite.ox = bitmap.width / 2
@mp_presence_status_sprite.oy = bitmap.height
@mp_presence_status_value = state
end
top_y = self.y - self.height
begin
# Put the status centered above the nickname when a nickname is present.
# It is never placed before/after the nickname text.
if @mp_nick_sprite && @mp_nick_sprite.bitmap && @mp_nick_sprite.visible
nick_top = @mp_nick_sprite.y - @mp_nick_sprite.bitmap.height
top_y = [top_y, nick_top].min
end
rescue
end
@mp_presence_status_sprite.x = self.x
@mp_presence_status_sprite.y = top_y - MPPlayerPresenceVersionGate::STATUS_GAP
@mp_presence_status_sprite.z = self.z + 30
@mp_presence_status_sprite.visible = self.visible
rescue
mp_presence_gate_dispose_status_icon
end
unless method_defined?(:mp_presence_gate_dispose_without_status_icon)
alias mp_presence_gate_dispose_without_status_icon dispose
end
def dispose(*args, &block)
mp_presence_gate_dispose_status_icon
mp_presence_gate_dispose_without_status_icon(*args, &block)
end
end
puts "[PRESENCE/GATE] client #{MPPlayerPresenceVersionGate::CLIENT_PATCH_VERSION} loaded; build=#{MPPlayerPresenceVersionGate.client_game_version.inspect}" rescue nil