# encoding: UTF-8 # Client bridge for the standalone LonaPaletteSync server plugin. # Wire rows: enabled,h,s,v,skin_mode,sample_r,sample_g,sample_b module LonaPaletteStudio WIRE_VERSION = 1 unless const_defined?(:WIRE_VERSION) WIRE_FIELDS_PER_PROFILE = 8 unless const_defined?(:WIRE_FIELDS_PER_PROFILE) WIRE_MAX_BYTES = 8192 unless const_defined?(:WIRE_MAX_BYTES) def self.wire_payload(state_hash = nil) current_state = state_hash || state rows = PROFILE_KEYS.map do |profile_key| profile = profile_for(profile_key, current_state) sample = profile_sample_rgb(profile) || [-1, -1, -1] mode = profile_key.to_s == "skin" && normalize_skin_color_mode(profile["mode"]) == "solid" ? 1 : 0 [ clamp(profile["enabled"].to_i, 0, 1), clamp(profile["h"].to_f.round, 0, 359), clamp(profile["s"].to_f.round, 0, 255), clamp(profile["v"].to_f.round, 0, 255), mode, clamp(sample[0].to_i, -1, 255), clamp(sample[1].to_i, -1, 255), clamp(sample[2].to_i, -1, 255) ].join(",") end payload = WIRE_VERSION.to_s + "|" + rows.join(";") payload.bytesize <= WIRE_MAX_BYTES ? payload : nil rescue => e log_exception("wire_payload failed", e) nil end def self.state_from_wire(payload) text = payload.to_s return nil if text.empty? || text.bytesize > WIRE_MAX_BYTES return nil if text.include?("\n") || text.include?("\r") || text.include?(":") prefix = WIRE_VERSION.to_s + "|" return nil unless text.start_with?(prefix) rows = text[prefix.length..-1].to_s.split(";", -1) return nil unless rows.length == PROFILE_KEYS.length decoded = default_state PROFILE_KEYS.each_with_index do |profile_key, index| fields = rows[index].to_s.split(",", -1) return nil unless fields.length == WIRE_FIELDS_PER_PROFILE return nil unless fields.all? { |field| field =~ /\A-?\d{1,6}\z/ } values = fields.map { |field| field.to_i } return nil unless values[0].between?(0, 1) return nil unless values[1].between?(0, 359) return nil unless values[2].between?(0, 255) && values[3].between?(0, 255) return nil unless values[4].between?(0, 1) return nil unless values[5..7].all? { |value| value.between?(-1, 255) } no_sample = values[5..7].all? { |value| value == -1 } full_sample = values[5..7].all? { |value| value >= 0 } return nil unless no_sample || full_sample profile = decoded[profile_key] profile["enabled"] = values[0] profile["h"] = values[1].to_f profile["s"] = values[2].to_f profile["v"] = values[3].to_f profile["mode"] = values[4] == 1 ? "solid" : "gradient" if profile_key.to_s == "skin" if gear_profile?(profile_key) profile["sample_r"] = values[5] profile["sample_g"] = values[6] profile["sample_b"] = values[7] end end normalize_pending_state!(decoded) rescue => e log_exception("state_from_wire failed", e) nil end end module WebSocket @lps_remote_states ||= {} @lps_remote_payloads ||= {} @lps_last_request_at ||= 0.0 @lps_server_mode ||= nil @lps_deferred_self_payload ||= nil def self.lps_remote_states @lps_remote_states ||= {} end def self.lps_remote_palette_state(player_id) lps_remote_states[player_id.to_i] rescue nil end def self.lps_render_state_for_character(character) return nil if character.nil? player_id = 0 begin if character.instance_variable_defined?(:@net_player_id) player_id = character.instance_variable_get(:@net_player_id).to_i end rescue player_id = 0 end # Male-grab receiver proxy is a local Game_Event stand-in for a NetPlayer. # It has no @net_player_id, but @mp_male_target is the remote pid whose # Palette Studio skin must be applied (else default/uncolored Lona). if player_id <= 0 begin if character.instance_variable_get(:@mp_male_receiver_proxy) player_id = character.instance_variable_get(:@mp_male_target).to_i end rescue player_id = 0 end end return nil if player_id <= 0 # No network palette means the normal engine path. Avoid allocating all 52 # default profiles every time a remote CHS bitmap is rebuilt. lps_remote_palette_state(player_id) rescue nil end def self.lps_remote_payloads @lps_remote_payloads ||= {} end def self.lps_apply_remote_payload(player_id, payload) pid = player_id.to_i return false if pid <= 0 payload_text = payload.to_s # Snapshots are legitimately repeated after map changes. Rebuilding the CHS # for an identical palette is pure work and previously flushed every cached # bitmap in the game. return true if lps_remote_payloads[pid] == payload_text state_hash = LonaPaletteStudio.state_from_wire(payload_text) return false if state_hash.nil? lps_remote_states[pid] = state_hash lps_remote_payloads[pid] = payload_text lps_invalidate_remote_character(pid) true end def self.lps_clear_remote_palette(player_id) pid = player_id.to_i lps_remote_payloads.delete(pid) changed = !lps_remote_states.delete(pid).nil? lps_invalidate_remote_character(pid) if changed changed rescue false end def self.lps_invalidate_remote_character(player_id) pid = player_id.to_i players = instance_variable_get(:@players) rescue nil character = players[pid] if players.respond_to?(:[]) begin character.instance_variable_set(:@chs_need_update, true) unless character.nil? rescue end # Also refresh male-grab receiver proxy stand-in for this pid. begin proxies = instance_variable_get(:@mp_male_receiver_proxies) proxy = proxies[pid] if proxies.is_a?(Hash) proxy.instance_variable_set(:@chs_need_update, true) if proxy rescue end rescue => e LonaPaletteStudio.log_exception("remote CHS invalidation failed pid=#{player_id}", e) end def self.lps_applying_server_state? !!@lps_applying_server_state end def self.lps_apply_self_payload(payload) payload_text = payload.to_s state_hash = LonaPaletteStudio.state_from_wire(payload_text) return false if state_hash.nil? unless LonaPaletteStudio.story_storage @lps_deferred_self_payload = payload_text return false end # The server sends the owner's state again on map/snapshot requests. Do not # refresh all live portraits when the local state is already identical. current_payload = LonaPaletteStudio.wire_payload rescue nil return true if current_payload == payload_text @lps_applying_server_state = true begin LonaPaletteStudio.apply_pending_state!(state_hash) @lps_deferred_self_payload = nil true ensure @lps_applying_server_state = false end rescue => e LonaPaletteStudio.log_exception("self palette apply failed", e) false end def self.lps_try_apply_deferred_self payload = @lps_deferred_self_payload payload.nil? ? false : lps_apply_self_payload(payload) end def self.lps_send_packet(packet) return 0 unless respond_to?(:lps_network_send_line_without_palette) lps_network_send_line_without_palette(packet) rescue => e LonaPaletteStudio.log_exception("network send failed", e) 0 end def self.lps_request_palette(force = false) return 0 unless instance_variable_get(:@connected) now = Time.now.to_f return 0 if !force && now - @lps_last_request_at.to_f < 0.75 @lps_last_request_at = now lps_send_packet("lps_req") end def self.lps_publish_local_state return 0 if lps_applying_server_state? payload = LonaPaletteStudio.wire_payload return 0 if payload.nil? lps_send_packet("lps_set:" + payload) end def self.lps_handle_packet(line) case line when /\Alps_cap:1:(db|memory)\z/ @lps_server_mode = $1.to_s true when /\Alps_self:(.+)\z/ lps_apply_self_payload($1.to_s) true when /\Alps_state:(\d+):(.+)\z/ lps_apply_remote_payload($1.to_i, $2.to_s) true when /\Alps_clear:(\d+)\z/ lps_clear_remote_palette($1.to_i) true when /\Alps_missing\z/ if LonaPaletteStudio.story_storage lps_publish_local_state else @lps_publish_when_ready = true end true when /\Alps_ack\z/ true when /\Alps_error:(.+)\z/ LonaPaletteStudio.audit_error("server palette error=#{$1}") true else false end end end class << LonaPaletteStudio unless method_defined?(:lps_network_apply_pending_state_without_sync!) alias_method :lps_network_apply_pending_state_without_sync!, :apply_pending_state! end def apply_pending_state!(pending_state) result = lps_network_apply_pending_state_without_sync!(pending_state) if defined?(WebSocket) && WebSocket.respond_to?(:lps_publish_local_state) && !WebSocket.lps_applying_server_state? WebSocket.lps_publish_local_state end result end end if defined?(WebSocket) && WebSocket.respond_to?(:parse) && WebSocket.respond_to?(:send_line) module WebSocket class << self unless method_defined?(:lps_network_parse_without_palette) alias_method :lps_network_parse_without_palette, :parse end unless method_defined?(:lps_network_send_line_without_palette) alias_method :lps_network_send_line_without_palette, :send_line end def parse(message) line = message.to_s.strip return if lps_handle_packet(line) result = lps_network_parse_without_palette(message) case line when /\Aauth_ok:/ lps_request_palette(false) when /\Async_unlocked\z/ lps_try_apply_deferred_self if @lps_publish_when_ready && LonaPaletteStudio.story_storage @lps_publish_when_ready = false lps_publish_local_state end lps_request_palette(false) when /\Aquit:(\d+)/ lps_clear_remote_palette($1.to_i) end result end def send_line(packet) line = packet.to_s result = lps_network_send_line_without_palette(packet) lps_request_palette(true) if line =~ /\Amap:-?\d+\s*\z/ result end end end end if defined?(Sprite_Character) && Sprite_Character.method_defined?(:set_character_bitmap) class Sprite_Character < Sprite_Base unless method_defined?(:lps_network_set_character_bitmap_without_palette) alias_method :lps_network_set_character_bitmap_without_palette, :set_character_bitmap end def set_character_bitmap(*args) state_hash = nil remote_character = false begin if @character remote_character = @character.instance_variable_defined?(:@net_player_id) # Receiver proxy must be treated as remote for palette bypass / # remote-state lookup (same as NetPlayer under the stand-in). begin remote_character = true if @character.instance_variable_get(:@mp_male_receiver_proxy) rescue end end state_hash = WebSocket.lps_render_state_for_character(@character) if defined?(WebSocket) rescue state_hash = nil end # Important: nil for a remote player means "this player has no palette", # not "use my local palette". The Lona_CHS_Part hook is global, so the # unwrapped engine path would otherwise recolor them with the viewer's state. if remote_character && state_hash.nil? return LonaPaletteStudio.without_palette_rendering do lps_network_set_character_bitmap_without_palette(*args) end end return lps_network_set_character_bitmap_without_palette(*args) if state_hash.nil? LonaPaletteStudio.with_render_state(state_hash) do lps_network_set_character_bitmap_without_palette(*args) end end end end