Files
LonaRPG-Online-Games/ModScripts/999999999999_ClanEstate.rb
T
2026-10-29 21:59:06 +04:00

2051 lines
86 KiB
Ruby
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# encoding: UTF-8
# ClanEstate client 1.4.4 FIXED — passport service is a top-level guild-worker action.
module MPClanEstate
VERSION = '1.4.4-guild-passport-menu'
CLAN_CHEST_BOX_ID = 65_532
ERRORS = {
'access_denied'=>'Нет доступа к этому клановому дому.',
'not_in_estate'=>'Вы не относитесь к этому клановому дому.',
'clan_frozen'=>'Клан заморожен до оплаты штрафа.',
'creator_only'=>'Менять интерьер может только создатель клана или администрация.',
'slaves_only'=>'Грядками могут пользоваться только рабы клана.',
'not_your_crop'=>'Эту грядку обрабатывает другой раб.',
'not_ready'=>'Урожай ещё не созрел.',
'stock_empty'=>'В клановом сундуке не хватает предметов.',
'withdrawal_forbidden'=>'Этот предмет или количество вам сейчас недоступны.',
'not_enough_items'=>'У вас не хватает предметов.',
'child_forbidden'=>'Ребёнка нельзя поместить в клановый сундук.',
'apply_pending_inventory'=>'Сначала дождитесь подтверждения предыдущей выдачи.',
'visit_banker'=>'Для этого нужно находиться у банкира.',
'visit_guild_employee'=>'Передать раба клану можно только у работника гильдии.',
'not_your_slave'=>'Можно передать клану только собственного раба.',
'passport_pending'=>'Паспорт раба ещё не подтверждён сервером.',
'slave_already_assigned'=>'Этот раб уже закреплён за кланом.',
'passport_not_with_owner'=>'Паспорт раба сейчас не находится у владельца.',
'passport_mismatch'=>'Данные паспорта не совпали. Обновите состояние и повторите.',
'already_have_passport'=>'У вас уже есть оригинальный паспорт.',
'passport_requested'=>'Заявление уже подано. Дождитесь срока выдачи.',
'passport_not_ready'=>'Срок выдачи паспорта ещё не наступил.',
'passport_in_custody'=>'Паспорт находится у владельца раба. Его вернут после освобождения.',
'slave_documents_forbidden'=>'Я не могу восстановить ваши документы, пока вы находитесь в рабстве у игрока или клана. Сначала получите освобождение.',
'reputation_is_average'=>'Репутация клана рассчитывается автоматически по участникам.',
'clock_not_ready'=>'Серверное игровое время ещё не готово.',
'stale_request'=>'Запрос устарел. Состояние будет обновлено.',
'revision_changed'=>'Состояние изменилось. Дождитесь синхронизации.',
'estate_busy'=>'Клановый дом временно занят обработкой запроса. Повторите через несколько секунд.'
}
@queue = []
@state = {}
class << self
attr_reader :state
attr_accessor :home_kind
attr_accessor :return_point
def install
return true if @installed
return false unless defined?(NoerHomeGarden) && WebSocket.respond_to?(:noerhome_estate_parse_without_private_home)
WebSocket.singleton_class.prepend(PreserveInventory)
WebSocket.singleton_class.prepend(Network)
# Multiplayer's generic portal synchronizer assumes numeric map ids.
# NoerHome uses string/path tag-map ids, which the portal layer coerces
# to 0 and then blocks/rewrites the transfer. Bypass that layer for any
# NoerHome/NoerHomeOut destination (private house OR clan estate).
# ClanEstate still publishes the virtual room with map:<virtual> after
# the local tag map has finished loading when a clan house is active.
WebSocket.singleton_class.prepend(PortalBypass) if WebSocket.respond_to?(:portal_on_reserve_transfer)
Game_Actor.prepend(LevelRewards)
Game_Party.prepend(PassportLock)
Game_Interpreter.prepend(Menus)
Game_Interpreter.prepend(MapTravel)
Game_Player.prepend(ReturnPoint)
Game_Player.prepend(LocalNpcInteractionPriority)
Scene_ItemStorage.prepend(StorageLock)
Scene_TradeStorage.prepend(StorageLock)
Window_ChoiceList.prepend(ChestChoiceCancelPriority) if defined?(Window_ChoiceList)
Scene_Map.prepend(PursuitView)
MPSlavePatrolReturn.singleton_class.prepend(Patrol)
MPClanGuild.singleton_class.prepend(GuildMenu)
NoerHomeEstate.singleton_class.prepend(EstateHome)
NoerHomeGarden.singleton_class.prepend(Garden)
NoerHomeDecor.singleton_class.prepend(SharedAmenities) if defined?(NoerHomeDecor)
NoerHomeDecorEditor.singleton_class.prepend(EditorPermission) if defined?(NoerHomeDecorEditor)
@installed=true
end
# Ruby modules survive Scene_Title -> New Game inside the same process.
# The game objects do not. Reset only ClanEstate's transient network state
# when a fresh Game_Party/Game_Player pair appears, otherwise a request/state
# from the previous session can block the first estate action of the new game.
def ensure_game_session
return false unless defined?($game_party) && $game_party && defined?($game_player) && $game_player
key=[$game_party.object_id,$game_player.object_id]
return false if @game_session_key==key
@game_session_key=key
@hello_at=nil
@request=nil
@request_op=nil
@request_context=nil
@request_started_at=nil
@sent_at=nil
@sequence=0
@document_check_result=nil
@state={}
@home_kind=nil
@return_point=nil
@applied_revision=nil
@deferred_state=nil
@worker_dialogue_queue=[]
@worker_dialogue_fiber=nil
@menu_fiber=nil
@queue.clear
true
rescue => e
puts "[ClanEstate session reset] #{e.class}: #{e.message}"
false
end
def active?; @home_kind && @state['clan'].to_i > 0; end
def virtual_map_id(kind=@home_kind)
clan=@state['clan'].to_i
return 0 if clan<=0
1_000_000_000 + clan*2 + (kind.to_s=='yard' ? 1 : 0)
rescue
0
end
# Keep a tiny routing marker separate from the volatile estate payload.
# The normal disconnect path clears @state/@home_kind before Save14 can make
# its final cloud commit. Without this marker map_packet_for_server falls
# back to the local NoerHome map id, which is the PRIVATE-home room. The
# server then stores that id in player_live_state and the next login appears
# in the private house even though the slave logged out from the clan estate.
#
# @resume_clan/@resume_kind survive only as routing metadata. They are also
# copied into the cloud stats snapshot, so even a hard reconnect can restore
# the clan room before the first estate state refresh arrives.
def remember_estate_route(kind=@home_kind, clan=nil)
k=kind.to_s
return false unless k=='house' || k=='yard'
cid=(clan || (@state && @state['clan'])).to_i
return false if cid<=0
@resume_clan=cid
@resume_kind=k
true
rescue
false
end
def clear_estate_route
@resume_clan=nil
@resume_kind=nil
true
end
def resume_clan_id
@resume_clan.to_i
rescue
0
end
def resume_kind
k=@resume_kind.to_s
(k=='house' || k=='yard') ? k : ''
rescue
''
end
def resume_virtual_map_id(kind=nil)
cid=resume_clan_id
k=(kind || resume_kind).to_s
return 0 if cid<=0 || (k!='house' && k!='yard')
1_000_000_000 + cid*2 + (k=='yard' ? 1 : 0)
rescue
0
end
def local_estate_kind(map_id=nil)
return '' unless defined?(NoerHomeEstate)
id=map_id.nil? ? (($game_map.map_id rescue 0).to_i) : map_id.to_i
NoerHomeEstate.home_kind_for_local(id).to_s
rescue
''
end
def worker_context?; @worker_context_depth.to_i > 0; end
def with_worker_context
@worker_context_depth = @worker_context_depth.to_i + 1
yield
ensure
@worker_context_depth = [@worker_context_depth.to_i - 1, 0].max
end
def queue_worker_dialogue(text)
@worker_dialogue_queue ||= []
@worker_dialogue_queue << text.to_s
end
def update_worker_dialogue
if @worker_dialogue_fiber && @worker_dialogue_fiber.alive?
@worker_dialogue_fiber.resume
return
end
@worker_dialogue_fiber=nil
text=(@worker_dialogue_queue ||= []).shift
return if text.to_s.empty?
@worker_dialogue_fiber=Fiber.new do
interpreter=Game_Interpreter.new
begin
interpreter.send(:call_msg,"\\CBmp[GuildEmpolyee,20]\\c[4]Работник:\\C[0] #{text}")
ensure
restore_worker_view(interpreter)
end
end
@worker_dialogue_fiber.resume
rescue FiberError
@worker_dialogue_fiber=nil
rescue => e
@worker_dialogue_fiber=nil
puts "[ClanEstate worker dialogue] #{e.class}: #{e.message}"
end
def restore_worker_view(interpreter=nil)
target=interpreter
target=$game_map.interpreter if !target && defined?($game_map) && $game_map && $game_map.respond_to?(:interpreter)
target.send(:cam_center,0) if target && target.respond_to?(:cam_center,true)
target.send(:portrait_hide) if target && target.respond_to?(:portrait_hide,true)
$game_temp.choice=-1 if defined?($game_temp) && $game_temp
true
rescue => e
puts "[ClanEstate worker cleanup] #{e.class}: #{e.message}"
false
end
# Guild mission persistence is owned by 14_autosave. Do not perform a
# second immediate sync_state here: the employee script is already wrapped
# in one atomic quest transaction and will commit the final story/inventory
# state once, after all dialogue/reward mutations are complete.
def save_guild_progress
if defined?(MP_Save14) && MP_Save14.respond_to?(:quest_commit)
return MP_Save14.quest_commit('guild_worker')
end
if defined?(MPCloudOnlySave) && MPCloudOnlySave.respond_to?(:request)
MPCloudOnlySave.request('guild_worker_progress', 0)
return true
end
false
rescue => e
puts "[ClanEstate guild save] #{e.class}: #{e.message}"
false
end
def capture_home_return_point
if defined?($game_map) && $game_map && $game_map.respond_to?(:isOverMap) && $game_map.isOverMap
map_id=$game_map.map_id.to_i
x=$game_player.x.to_i
y=$game_player.y.to_i
direction=$game_player.direction.to_i
# The in-memory return point is lost on reconnect. The door then uses
# LastOverMap, which still points at the previous location.
if defined?(WebSocket) && WebSocket.respond_to?(:capture_overmap_location)
WebSocket.capture_overmap_location(map_id, x, y, "clan_house_door")
elsif defined?($story_stats) && $story_stats
$story_stats["OverMapID"]=map_id
$story_stats["LastOverMapX"]=x
$story_stats["LastOverMapY"]=y
end
return [map_id,x,y,direction]
end
if defined?($story_stats) && $story_stats
map_id=$story_stats['OverMapID'].to_i
x=$story_stats['LastOverMapX'].to_i
y=$story_stats['LastOverMapY'].to_i
direction=(defined?($game_player) && $game_player ? $game_player.direction.to_i : 2)
return [map_id,x,y,direction] if map_id>0
end
if defined?($game_map) && $game_map && defined?($game_player) && $game_player
return [$game_map.map_id.to_i,$game_player.x.to_i,$game_player.y.to_i,$game_player.direction.to_i]
end
nil
rescue
nil
end
def chest_choice_active?; @chest_choice_depth.to_i > 0; end
def with_chest_choices
@chest_choice_depth = @chest_choice_depth.to_i + 1
yield
ensure
@chest_choice_depth = [@chest_choice_depth.to_i - 1, 0].max
end
def slave?; @state['slave'].is_a?(Hash); end
def clan_slave?
slave? || @state['clan_slave'] == true
rescue
slave?
end
# Interaction permissions must not depend on the full estate payload being
# committed to the local inventory yet. During fresh-game bootstrap the
# server can already authoritatively mark the player as a clan slave while
# BankGuard still delays inventory application.
def garden_slave_access?
return true if clan_slave?
begin
return true if defined?($story_stats) && $story_stats && $story_stats['MPClanEstateSlave'].to_i > 0
rescue
end
false
rescue
false
end
def player_slave_for_documents?
begin
return true if defined?($story_stats) && $story_stats && $story_stats['MPClanEstateSlave'].to_i > 0
rescue
end
return true if clan_slave?
begin
return true if defined?($game_player) && $game_player && $game_player.respond_to?(:player_slave?) && $game_player.player_slave?
rescue
end
begin
if defined?(MPSlavePatrolReturn) && MPSlavePatrolReturn.respond_to?(:active_local_contract?)
return true if MPSlavePatrolReturn.active_local_contract?
end
rescue
end
begin
if defined?($story_stats) && $story_stats
owner=$story_stats['SlaveOwner'].to_s
contract_id=$story_stats['MPPlayerSlaveContract'].to_i
return true if contract_id>0 && owner.index('MP:')==0
end
rescue
end
begin
return true if defined?(WebSocket) && WebSocket.respond_to?(:mp_player_owned?) && WebSocket.mp_player_owned?
rescue
end
begin
if defined?(WebSocket) && WebSocket.respond_to?(:slave_active_contract)
contract=WebSocket.slave_active_contract('slave')
return true if contract && contract[:status].to_s=='ACTIVE'
end
rescue
end
false
rescue
clan_slave?
end
def authoritative_document_slave_status(timeout_frames=180)
return true if player_slave_for_documents?
return nil unless defined?(WebSocket) && WebSocket.connected?
@document_check_result = :waiting
WebSocket.send_line('ce_doc_check')
timeout_frames.to_i.times do
result=@document_check_result
if result != :waiting
@document_check_result=nil
return nil if result==:unknown
return !!result
end
Fiber.yield
end
@document_check_result=nil
nil
rescue => e
@document_check_result=nil
puts "[ClanEstate document check] #{e.class}: #{e.message}"
nil
end
def incite_map_npcs_against_player
return 0 unless defined?($game_map) && $game_map && defined?($game_player) && $game_player
events=[]
begin
raw=$game_map.events
events.concat(raw.respond_to?(:values) ? raw.values : Array(raw)) if raw
rescue
end
begin
raw=$game_map.npcs
events.concat(raw.respond_to?(:values) ? raw.values : Array(raw)) if raw
rescue
end
events=events.compact.uniq.reject do |event|
begin
event.equal?($game_player) || !!event.instance_variable_get(:@net_player_id)
rescue
false
end
end
begin
if defined?(MPSlaveEscapeAction) && MPSlaveEscapeAction.respond_to?(:force_witness_attack)
return MPSlaveEscapeAction.force_witness_attack(events,$game_player).to_i
end
rescue
end
target=($game_player.actor rescue nil)
skill=(defined?($data_arpgskills) && $data_arpgskills ? $data_arpgskills['BasicNormal'] : nil) rescue nil
return 0 unless target && skill
count=0
events.each do |event|
begin
next if event.respond_to?(:erased) && event.erased
next if event.respond_to?(:deleted?) && event.deleted?
next if event.respond_to?(:opacity) && event.opacity.to_i<255
rescue
end
actor=(event.actor rescue nil)
next unless actor && actor.respond_to?(:set_aggro)
next if (actor.action_state rescue nil)==:death
next if actor.respond_to?(:is_object) && actor.is_object
begin
actor.set_aggro(target,skill,1800)
event.turn_toward_character($game_player) if event.respond_to?(:turn_toward_character)
count+=1
rescue
end
end
count
rescue
0
end
def editable?; active? && @state['can_edit'] && !@state['frozen']; end
def enqueue(text); @queue << text; end
def bank_ready?
!defined?(MPBankGuard) || MPBankGuard.ready?
rescue
true
end
def merge_routing_state(value)
return unless value.is_a?(Hash)
@state ||= {}
# These fields are interaction/visual metadata only. They are safe to
# consume immediately, even while generic cloud bootstrap or BankGuard
# intentionally delays the inventory delta contained in the same ce_state.
# Without this, 1.2.5 could enter the estate early but show an empty
# "Взять разрешённое" list and an unusable garden until a later sync.
%w[profile clan clan_name creator clan_slave slave house_map yard_map can_edit frozen
fine fine_due reputation decor plots chest locked clock last_request passport_due
owned_slaves pursuit].each do |key|
@state[key]=value[key] if value.key?(key)
end
true
rescue
false
end
def defer_state(value)
return unless value.is_a?(Hash)
merge_routing_state(value)
current=@deferred_state
if !current.is_a?(Hash) || value['revision'].to_i >= current['revision'].to_i
@deferred_state=value
end
true
end
def flush_deferred_state
return false unless bank_ready?
value=@deferred_state
return false unless value.is_a?(Hash)
@deferred_state=nil
apply_state(value)
true
rescue => e
@deferred_state=value
puts "[ClanEstate deferred state] #{e.class}: #{e.message}"
false
end
def notify(text, context=nil)
if context=='guild_worker' || worker_context?
queue_worker_dialogue(text)
else
NoerHomeEstate.notify(text)
end
end
def error_text(code)
ERRORS[code.to_s] || code.to_s.tr('_',' ')
end
def pass_active?(value=@state)
bond=value.is_a?(Hash) ? value['slave'] : nil
bond.is_a?(Hash) && bond['passUntil'].to_i > value['clock'].to_i
end
def game_days(units)
value=[units.to_i,0].max
(value + 1) / 2
end
def slave_status_text
bond=@state['slave']
return 'Вы не закреплены за кланом как раб.' unless bond.is_a?(Hash)
clock=@state['clock'].to_i
if bond['passUntil'].to_i > clock
pass="пропуск активен, осталось #{game_days(bond['passUntil'].to_i-clock)} дн."
else
pass="следующий пропуск через #{game_days(bond['nextPass'].to_i-clock)} дн."
end
"План урожая: #{bond['cropValue'].to_i}/4000. Прошлый период: #{bond['previousCropValue'].to_i}/4000. #{pass} Неоплаченных зарплат: #{bond['unpaidWages'].to_i}. Штраф за побеги: #{bond['escapeDebt'].to_i} зарплат."
end
def notify_pass_start(previous,value)
return unless value.is_a?(Hash) && value['slave'].is_a?(Hash)
return unless previous.is_a?(Hash) && previous['profile'].to_i==value['profile'].to_i && previous['slave'].is_a?(Hash)
if !pass_active?(previous) && pass_active?(value)
notify("Выдан пропуск на свободное перемещение на #{game_days(value['slave']['passUntil'].to_i-value['clock'].to_i)} игровых суток.")
end
end
def send_action(op, data = {})
# Interaction can happen on the first playable frames of a brand-new game,
# before the regular ClanEstate tick has observed the new game objects.
ensure_game_session
frame=Graphics.frame_count
if @request
age=frame-@request_started_at.to_i
if age < 600
notify('Дождитесь ответа сервера.')
return false
end
# Never let one lost estate reply block every later action forever.
@request=nil;@request_op=nil;@request_context=nil;@request_started_at=nil
end
bootstrap_enter=(op.to_s=='enter' && !@state['profile'])
unless @state['profile'] || bootstrap_enter
notify('Данные клана ещё загружаются.')
return false
end
# Enter must never be blocked just because ce_state/BankGuard is still
# bootstrapping. Seed the request id from wall-clock milliseconds when no
# authoritative last_request is available, so the server still sees a
# strictly newer id after reconnect.
seed = bootstrap_enter ? (Time.now.to_f*1000).to_i : 0
@sequence = [@sequence.to_i, @state['last_request'].to_i, seed].max + 1
# Do not inject a generic sync_state immediately before ce_action. The
# server may reject that sync_state with revision_changed while the estate
# action is already in flight; older clients then mistook the unrelated
# ce_error for the action response and cleared @request. Save14 already
# owns normal cloud persistence, while ce_result performs the inventory ACK
# after authoritative estate mutations.
flush_deferred_state if bank_ready? && @deferred_state
payload = WebSocket._live_sync_blob_from_object(data.merge('op' => op), nil, 'clan_estate')
@request = "ce_action:#{@sequence}:#{payload}"
@request_op = op.to_s
@request_context = worker_context? ? 'guild_worker' : nil
@sent_at = frame
@request_started_at = frame
WebSocket.send_line(@request)
true
end
def request_pending?; !!@request; end
def request_op; @request_op.to_s; end
def resolve_item(name)
return MPPlayerDocuments.from_name(name) if name.start_with?(MPPlayerDocuments::PREFIX)
$data_ItemName[name]
end
def item_key(item)
who = MPPlayerDocuments.owner(item)
who ? MPPlayerDocuments.stable_name(who) : item.item_name
end
def child_item?(item)
object = item.is_a?(String) ? resolve_item(item.to_s) : item
return false if object.nil?
# This is the game's own semantic definition used by the rebirth scan.
object.type_tag.to_s == 'Child' || (object.type_tag.to_s == 'Key' && object.type.to_s == 'Baby')
rescue
false
end
# Apply only the inventory targets confirmed by a ClanEstate ce_result.
# This is intentionally narrower than apply_state: chest transfer ACKs must be
# visible immediately even if BankGuard is temporarily delaying unrelated estate
# state. The targets are absolute quantities, so applying them again later via
# apply_state is idempotent.
def apply_confirmed_chest_inventory(value)
return false unless value.is_a?(Hash) && value['inventory'].is_a?(Hash)
changed=false
value['inventory'].each do |name,quantity|
item=resolve_item(name.to_s)
next unless item
target=quantity.to_i
current=$game_party.item_number(item).to_i
next if current==target
@applying=true
begin
$game_party.gain_item(item,target-current)
changed=true
ensure
@applying=false
end
end
changed
rescue => e
puts "[ClanEstate chest inventory] #{e.class}: #{e.message}"
false
end
def soup_item_name?(name)
name.to_s.start_with?('ItemSop')
end
# Client-side mirror of the server's aggregate ration counters. It does not
# grant access by itself; it only prevents stale storage UI from allowing a
# second click after the daily category limit has already been consumed.
def slave_withdraw_remaining(item_name)
return nil unless clan_slave?
bond=@state['slave']
return nil unless bond.is_a?(Hash)
name=item_name.to_s
if name=='ItemBread'
return [2-bond['breadTaken'].to_i,0].max
elsif soup_item_name?(name)
prev=bond['previousCropValue'].to_i
limit = prev < 4000 ? 0 : (prev > 4000 ? 2 : 1)
return [limit-bond['soupTaken'].to_i,0].max
end
nil
rescue
nil
end
def setup_chest_box
return false unless defined?(Storage_Boxes_Setting) && defined?($game_boxes) && $game_boxes
title = clan_slave? ? 'Клановый сундук — доступно рабу' : 'Клановый сундук'
Storage_Boxes_Setting::BOXES[CLAN_CHEST_BOX_ID] = {
:name=>title, :size=>0, :open_sound=>nil, :close_sound=>nil
}
true
rescue => e
puts "[ClanEstate chest setup] #{e.class}: #{e.message}"
false
end
def chest_fingerprint
chest=@state['chest']
return '' unless chest.is_a?(Hash)
chest.keys.sort.map{|k| "#{k}=#{chest[k].to_i}"}.join('|') + "|slave=#{clan_slave? ? 1 : 0}"
rescue
''
end
def sync_chest_box(force=false)
return false unless setup_chest_box
fp=chest_fingerprint
return false if !force && fp==@chest_box_fingerprint
box={}
(@state['chest']||{}).each do |name,count|
next if count.to_i<=0
item=resolve_item(name.to_s)
if item
box[item]=box.fetch(item,0)+count.to_i
else
puts "[ClanEstate chest] unknown item #{name}"
end
end
$game_boxes.write_box(CLAN_CHEST_BOX_ID,box)
@chest_box_fingerprint=fp
true
rescue => e
puts "[ClanEstate chest sync] #{e.class}: #{e.message}"
false
end
def refresh_open_chest_ui
sync_chest_box(true)
if defined?(Scene_ClanEstateStorage) && SceneManager.scene_is?(Scene_ClanEstateStorage)
scene=SceneManager.scene
scene.ce_server_refresh if scene.respond_to?(:ce_server_refresh)
return true
end
false
rescue => e
puts "[ClanEstate chest refresh] #{e.class}: #{e.message}"
false
end
def launch_chest_scene
setup_chest_box
sync_chest_box(true)
return true if refresh_open_chest_ui
SceneManager.goto(Scene_ClanEstateStorage)
SceneManager.scene.prepare(CLAN_CHEST_BOX_ID) if SceneManager.scene.respond_to?(:prepare)
true
end
def open_chest_scene
return notify('Сундук доступен только внутри кланового дома.') unless active? && @home_kind.to_s=='house'
# 1.3.3: chest_open MUST be a real server action.
# The server repairs/migrates the assigned slave's daily food/work allowance
# immediately before it builds the authoritative filtered chest view.
# ce_hello is intentionally NOT enough for this path.
@open_chest_after_refresh=false
ok=send_action('chest_open')
puts "[ClanEstate chest] chest_open requested" if ok
ok
rescue => e
@open_chest_after_refresh=false
puts "[ClanEstate chest open] #{e.class}: #{e.message}"
notify('Не удалось открыть клановый сундук.')
false
end
def apply_state(value)
return unless value.is_a?(Hash) && $game_party
@sequence = [@sequence.to_i,value['last_request'].to_i].max
revision = value['revision'].to_i
current = $game_party.instance_variable_get(:@clan_estate_revision).to_i
# Estate metadata (clan id, slave bond, map ids, permissions) must never be
# discarded just because the locally persisted inventory revision is newer.
# A stale inventory payload is skipped below, but the authoritative estate
# routing/status still has to refresh after reconnect.
stale_inventory = revision < current
previous=@state
@state = value
begin
if defined?($story_stats) && $story_stats && value.key?('clan_slave')
was_clan_slave = (previous.is_a?(Hash) && (previous['clan_slave'] == true || previous['slave'].is_a?(Hash))) || $story_stats['MPClanEstateSlave'].to_i > 0
clan_slave_now = (value['clan_slave'] == true)
$story_stats['MPClanEstateSlave'] = clan_slave_now ? 1 : 0
if clan_slave_now
clan_id = value['clan'].to_i
$story_stats['MPClanEstateClan'] = clan_id
# The personal MP contract is intentionally closed after transfer to
# the estate. The persisted clan bond is now the authority, so rebuild
# gameplay slave markers whenever estate state is restored.
$story_stats['Captured'] = 1
$story_stats['SlaveOwner'] = "CLAN:#{clan_id}" if clan_id > 0
$story_stats['MPPlayerSlaveOrigin'] = 'clan_estate'
begin
WebSocket.slave_apply_brand_only(false) if defined?(WebSocket) && WebSocket.respond_to?(:slave_apply_brand_only)
rescue
end
elsif was_clan_slave
$story_stats['MPClanEstateClan'] = 0
begin
personal = defined?(WebSocket) && WebSocket.respond_to?(:slave_active_contract) ? WebSocket.slave_active_contract('slave') : nil
personal_active = personal && personal[:status].to_s == 'ACTIVE'
if !personal_active && $story_stats['SlaveOwner'].to_s.start_with?('CLAN:')
$story_stats['SlaveOwner'] = 0
$story_stats['Captured'] = 0
$story_stats['OverMapForceTrans'] = 0
changed = WebSocket.slave_clear_local_marks_and_bondage if defined?(WebSocket) && WebSocket.respond_to?(:slave_clear_local_marks_and_bondage)
WebSocket.slave_sync_inventory('clan_slave_release') if changed && WebSocket.respond_to?(:slave_sync_inventory)
end
rescue
end
end
end
rescue
end
notify_pass_start(previous,value)
earned=$game_party.instance_variable_get(:@clan_estate_earned).to_i
$game_party.instance_variable_set(:@clan_estate_earned,[earned,value['earned_floor'].to_i].max)
if !stale_inventory && (value['force_inventory'] || revision != current || (value['inventory'].is_a?(Hash) && !value['inventory'].empty? && !@applied_revision))
items = value['inventory'] || {}
items.each do |name, quantity|
item = resolve_item(name)
raise "Не найден предмет кланового склада: #{name}" unless item
@applying = true
begin
$game_party.gain_item(item, quantity.to_i - $game_party.item_number(item))
ensure
@applying = false
end
end
actor = $game_player.actor
reward_total = value['skill_total'].to_i
applied = $game_party.instance_variable_get(:@clan_estate_skill_total).to_i
applied=[applied,value['skill_baseline'].to_i].max if value.key?('skill_baseline')
actor.trait_point += reward_total - applied if reward_total > applied
$game_party.instance_variable_set(:@clan_estate_skill_total, [reward_total, applied].max)
$game_party.instance_variable_set(:@clan_estate_revision, revision)
@applied_revision = revision
# Never send an inventory ACK while a ce_action request is pending.
# A sync error has no ce_action request id, so interleaving it with an
# estate action used to clear the wrong request and desynchronise access.
if @request
@inventory_ack_pending = true
else
WebSocket.live_sync_send_now('cloud_clan_estate_apply', true, false)
@inventory_ack_pending = false
end
end
NoerHomeEstate.bump_visual_revision if active?
end
def enter(value)
state=value['state']
if state.is_a?(Hash)
bank_ready? ? apply_state(state) : defer_state(state)
end
# ce_enter also carries the resolved clan explicitly. Merge it immediately
# so map_packet_for_server can compute the virtual room even while the full
# inventory state is intentionally deferred behind BankGuard.
@state['clan']=value['clan'].to_i if value['clan'].to_i>0
reason=value['reason']
notify({'assigned'=>'Вы направлены в клановый дом.', 'pass_expired'=>'Пропуск закончился. Вас возвращают в клановый дом.', 'collectors'=>'Коллекторы поймали вас. Штраф: 10 зарплат.'}[reason]) if reason
@home_kind = value['kind'] == 'yard' ? 'yard' : 'house'
remember_estate_route(@home_kind, @state['clan'])
# A clan house behaves like a normal tag-map house. Even when opened
# through the guild worker inside the Hot Barrel, its door exits to the
# last OverMap position instead of returning inside the tavern.
@return_point=capture_home_return_point
tag = @home_kind == 'yard' ? 'NoerHomeOut' : 'NoerHome'
xy = @home_kind == 'yard' ? [27,29] : [34,33]
$game_player.reserve_transfer(NoerHomeEstate.map_key(tag), xy[0], xy[1], 2)
SceneManager.goto(Scene_Map) unless SceneManager.scene_is?(Scene_Map)
end
def tick
update_worker_dialogue
unless WebSocket.connected?
# Preserve only the clan-room identity until Save14's final disconnect
# snapshot/map preflight has run. The full estate state remains volatile.
# This is what prevents a clan slave from being persisted as if the local
# NoerHome map were their private house.
begin
kind=local_estate_kind
remember_estate_route(kind, @state['clan']) unless kind.empty?
rescue
end
@hello_at = nil; @request = nil; @request_op = nil; @request_context = nil; @request_started_at = nil; @document_check_result = nil; @state = {}; @home_kind = nil; @applied_revision = nil; @deferred_state=nil; @game_session_key=nil; @open_chest_after_refresh=false
return
end
return unless $game_party && $game_player
ensure_game_session
frame = Graphics.frame_count
# Do NOT gate the ClanEstate control queue behind bootstrap_sync_unlocked?.
# A brand-new game can already be interactive while the generic cloud
# bootstrap is still locked. In that window the server may answer ce_enter,
# and leaving it queued forever is exactly what caused the first entry to
# show "Дождитесь ответа сервера" until returning to the title screen.
bootstrap_ready = begin
!WebSocket.respond_to?(:bootstrap_sync_unlocked?) || WebSocket.bootstrap_sync_unlocked?
rescue
true
end
# ce_hello is lightweight and its estate routing reply is safe before the
# generic bootstrap finishes. Inventory application remains deferred below.
if !@hello_at || frame - @hello_at >= 300
WebSocket.send_line('ce_hello'); @hello_at = frame
end
ready=bank_ready? && bootstrap_ready
while (message = @queue.shift)
command, payload = message.split(':',2)
decoded = WebSocket.bootstrap_decode_json_blob(payload)
case command
when 'ce_state'
ready ? apply_state(decoded) : defer_state(decoded)
if @open_chest_after_refresh
@open_chest_after_refresh=false
launch_chest_scene
end
when 'ce_doc_status'
if decoded.is_a?(Hash) && decoded['unknown']
@document_check_result=:unknown
elsif decoded.is_a?(Hash)
@document_check_result=(decoded['slave']==true)
begin
if defined?($story_stats) && $story_stats && decoded.key?('clan_slave')
$story_stats['MPClanEstateSlave']=decoded['clan_slave'] ? 1 : 0
end
rescue
end
else
@document_check_result=:unknown
end
when 'ce_result'
context=@request_context
completed_op=decoded['op'].to_s
@sequence = [@sequence.to_i,decoded['request'].to_i].max
@request = nil
@request_op = nil
@request_context = nil
@request_started_at = nil
state=decoded['state']
# Chest visibility is safe routing/UI metadata and must update immediately;
# inventory deltas inside the same state still stay deferred behind BankGuard.
if state.is_a?(Hash)
if completed_op=='chest_open'
# Keep inventory application behind BankGuard, but merge safe routing/UI
# metadata (including the freshly repaired filtered chest) immediately.
defer_state(state)
puts "[ClanEstate chest] repaired view=#{(@state['chest']||{}).inspect}"
launch_chest_scene
elsif completed_op=='deposit' || completed_op=='withdraw'
# Storage must react on the server ACK itself. Apply the exact confirmed
# inventory targets immediately, then merge the authoritative filtered
# chest and refresh both panes before any background/deferred state work.
# This removes the old "закрыл сундук — только тогда применилось" effect.
merge_routing_state(state)
inventory_changed=apply_confirmed_chest_inventory(state)
if ready
apply_state(state)
else
defer_state(state)
# Even while unrelated estate state is deferred, the server requires
# this just-confirmed inventory target to be echoed before the next
# deposit/withdraw. This is not a second mutation, only its ACK.
if inventory_changed && defined?(WebSocket) && WebSocket.respond_to?(:live_sync_send_now)
unlocked = !WebSocket.respond_to?(:bootstrap_sync_unlocked?) || WebSocket.bootstrap_sync_unlocked?
if unlocked
if @request
@inventory_ack_pending = true
else
WebSocket.live_sync_send_now('cloud_clan_estate_apply', true, false)
@inventory_ack_pending = false
end
end
end
end
refresh_open_chest_ui
else
ready ? apply_state(state) : defer_state(state)
end
end
# A slave's allowed chest view is dynamic. After a confirmed transfer,
# ask the server for a fresh filtered view so food/seed deposited or
# withdrawn in this same open session appears without closing the chest.
if (completed_op=='deposit' || completed_op=='withdraw') && clan_slave? && !request_pending?
send_action('chest_open')
end
notify('Заявление принято. Паспорт будет готов через 21 игровой день.',context) if completed_op=='passport_request'
notify('Ваш оригинальный паспорт восстановлен и выдан вам.',context) if completed_op=='passport_collect'
when 'ce_enter'
@request = nil
@request_op = nil
@request_context = nil
@request_started_at = nil
enter(decoded)
when 'ce_error'
code=decoded['error'].to_s
# revision_changed / inventory_not_applied / skills_not_applied are
# emitted by ClanEstate's sync_state validator, not by ce_action.
# They have no action request id. Never clear an in-flight estate
# request because of one of these background sync responses.
if %w[revision_changed inventory_not_applied skills_not_applied].include?(code)
puts "[ClanEstate sync] #{code}; refreshing authoritative estate state"
refresh_state
@inventory_ack_pending = true if code!='revision_changed'
else
context=@request_context
failed_op=@request_op.to_s
@request = nil
@request_op = nil
@request_context = nil
@request_started_at = nil
@open_chest_after_refresh=false if failed_op=='chest_open'
text=error_text(code)
notify(context=='guild_worker' ? text : "Клан: #{text}",context)
end
end
end
flush_deferred_state if ready && @deferred_state
if @inventory_ack_pending && !@request && ready && defined?(WebSocket) && WebSocket.respond_to?(:live_sync_send_now)
begin
WebSocket.live_sync_send_now('cloud_clan_estate_apply', true, false)
@inventory_ack_pending=false
rescue => e
puts "[ClanEstate inventory ack] #{e.class}: #{e.message}"
end
end
if @request && frame - @request_started_at.to_i >= 600
context=@request_context
op=@request_op
@request=nil;@request_op=nil;@request_context=nil;@request_started_at=nil
refresh_state
notify(op=='enter' ? 'Клановый дом не ответил вовремя. Запрос сброшен, попробуйте войти ещё раз.' : 'Сервер не ответил вовремя. Запрос сброшен, повторите действие.',context)
elsif @request && frame - @sent_at >= 180
@sent_at = frame;WebSocket.send_line(@request)
end
rescue => e
@request = nil
@request_op = nil
@request_context = nil
@request_started_at = nil
puts "[ClanEstate] #{e.class}: #{e.message}"
end
def local_clan_id
direct=@state['clan'].to_i
return direct if direct>0
if defined?(WebSocket) && WebSocket.respond_to?(:clan_info)
info=WebSocket.clan_info
if info.is_a?(Hash)
value=(info[:id] || info['id']).to_i
return value if value>0
end
end
0
rescue
0
end
def local_clan_name
state_name=(@state && @state['clan_name']).to_s.strip
return state_name unless state_name.empty?
return '' unless defined?(WebSocket) && WebSocket.respond_to?(:clan_display_name)
WebSocket.clan_display_name.to_s.strip
rescue
''
end
def player_slave_owner_name
if defined?(WebSocket) && WebSocket.respond_to?(:slave_active_contract)
contract=WebSocket.slave_active_contract('slave')
if contract.is_a?(Hash)
%w[owner_nick ownerNick owner].each do |key|
value=(contract[key] || contract[key.to_sym]).to_s.strip rescue ''
return value unless value.empty?
end
end
end
if defined?($story_stats) && $story_stats
value=$story_stats['MPPlayerSlaveOwnerNick'].to_s.strip
return value unless value.empty?
end
''
rescue
''
end
def player_slave_label?
return false if clan_slave?
if defined?(WebSocket)
return true if WebSocket.respond_to?(:mp_player_owned?) && WebSocket.mp_player_owned?
if WebSocket.respond_to?(:slave_active_contract)
contract=WebSocket.slave_active_contract('slave')
return true if contract.is_a?(Hash)
end
end
if defined?($story_stats) && $story_stats
return true if $story_stats['SlaveOwner'].to_s.start_with?('MP:')
return true if $story_stats['MPPlayerSlaveContract'].to_i > 0
end
if defined?($game_player) && $game_player && $game_player.respond_to?(:player_slave?)
return true if $game_player.player_slave?
end
false
rescue
false
end
def slave_role_label
if clan_slave?
clan_name=local_clan_name
clan_id=local_clan_id.to_i
return "Раб клана #{clan_name}" unless clan_name.empty?
return clan_id>0 ? "Раб клана ##{clan_id}" : 'Раб клана'
end
if player_slave_label?
owner_name=player_slave_owner_name
return "Раб игрока #{owner_name}" unless owner_name.empty?
return 'Раб игрока'
end
nil
rescue
'Раб'
end
def refresh_state
return false unless WebSocket.respond_to?(:connected?) && WebSocket.connected?
WebSocket.send_line('ce_hello')
@hello_at=Graphics.frame_count
true
rescue
false
end
def request_menu
return if @menu_fiber && @menu_fiber.alive?
@menu_fiber = Fiber.new { Game_Interpreter.new.clan_estate_menu }
end
def update_menu
return if @resuming_menu
@resuming_menu = true
begin
@menu_fiber.resume if @menu_fiber && @menu_fiber.alive?
ensure
@resuming_menu = false
end
end
end
# Preserve physical restraints removed by legacy multiplayer slavery. Capture the
# whole equipped quantity so duplicate items in different slots are not lost.
def self.preserve_removed_equipment
actor = $game_player.actor if defined?($game_player) && $game_player
return yield unless actor && $game_party
before = Hash.new(0)
actor.equips.compact.each { |item| before[item] += 1 }
inventory = before.keys.to_h { |item| [item, $game_party.item_number(item)] }
result = yield
after = Hash.new(0)
actor.equips.compact.each { |item| after[item] += 1 }
before.each do |item, count|
removed = [count - after[item], 0].max
missing = inventory[item] + removed - $game_party.item_number(item)
$game_party.gain_item(item, missing) if removed > 0 && missing > 0
end
result
end
module PreserveInventory
def slave_apply_force_work(contract_id,owner_profile,owner_nick,origin,work_key,allow_transfer=true)
if MPClanEstate.slave?
result=super(contract_id,owner_profile,owner_nick,origin,work_key,false)
$story_stats['OverMapForceTrans']=0
return result
end
super
end
def slave_apply_brand_only(sync_inventory = true)
# The base slavery script periodically verifies the slave brand. The old
# wrapper queued an inventory sync on EVERY verification, even when the
# actor/equipment was unchanged. While enslaved that happens forever and
# creates needless sync/serialization work. Sync only after a real change.
result = MPClanEstate.preserve_removed_equipment { super(false) }
slave_sync_inventory('clan_slave_brand_preserve') if sync_inventory && result
result
end
def slave_clear_local_marks_and_bondage
MPClanEstate.preserve_removed_equipment { super }
end
end
module Network
def parse(message)
if message.to_s.start_with?('bootstrap_map:','bootstrap_state:')
fields=message.split(':',-1)
remote=fields[1].to_i
if remote>=1_000_000_000
clan=(remote-1_000_000_000)/2
kind=(remote-1_000_000_000).odd? ? 'yard' : 'house'
MPClanEstate.state.merge!('clan'=>clan,'house_map'=>1_000_000_000+clan*2,'yard_map'=>1_000_000_001+clan*2)
MPClanEstate.home_kind=kind
MPClanEstate.remember_estate_route(kind, clan)
fields[1]=(kind=='yard' ? NoerHomeEstate.local_yard_id : NoerHomeEstate.local_house_id).to_s
message=fields.join(':')
elsif message.to_s.start_with?('bootstrap_map:')
# A genuine non-estate bootstrap is authoritative: do not let a route
# marker from a previous character/session hijack an ordinary map.
MPClanEstate.home_kind=nil
MPClanEstate.clear_estate_route
end
end
if message.to_s.start_with?('ce_')
MPClanEstate.enqueue(message.to_s.strip);return
end
super
end
def apply_bootstrap_state(value)
result=super
if result && value.is_a?(Hash) && !value['server_spawn_only']
stats=value['stats_json'].is_a?(Hash) ? value['stats_json'] : bootstrap_decode_json_blob(value['stats_blob'])
if stats.is_a?(Hash)
['revision','earned','skill_total'].each do |key|
$game_party.instance_variable_set("@clan_estate_#{key}",stats["clan_estate_#{key}"].to_i)
end
resume_clan=stats['clan_estate_resume_clan'].to_i
resume_kind=stats['clan_estate_resume_kind'].to_s
if resume_clan>0 && (resume_kind=='house' || resume_kind=='yard')
MPClanEstate.state.merge!('clan'=>resume_clan,'house_map'=>1_000_000_000+resume_clan*2,'yard_map'=>1_000_000_001+resume_clan*2)
MPClanEstate.home_kind=resume_kind
MPClanEstate.remember_estate_route(resume_kind,resume_clan)
# Repair old saves made before 1.4.3: they may bootstrap the physical
# NoerHome map id (private-home namespace) even though the cloud stats
# prove the player logged out inside a clan estate. Re-advertise the
# correct virtual clan room immediately; no transfer is needed because
# house/yard use the same local tag map.
begin
local_kind=MPClanEstate.local_estate_kind
if !local_kind.empty? && local_kind==resume_kind
virtual=MPClanEstate.resume_virtual_map_id(resume_kind)
send_line("map:#{virtual}") if virtual>0 && respond_to?(:send_line)
end
rescue => e
puts "[ClanEstate resume bootstrap] #{e.class}: #{e.message}"
end
end
end
end
result
end
def _live_sync_collect_stats(actor)
out=super
out['clan_estate_revision']=$game_party.instance_variable_get(:@clan_estate_revision).to_i
out['clan_estate_earned']=$game_party.instance_variable_get(:@clan_estate_earned).to_i
out['clan_estate_skill_total']=$game_party.instance_variable_get(:@clan_estate_skill_total).to_i
# Persist the virtual-room identity together with the player snapshot.
# This survives process restarts and also repairs legacy snapshots that
# accidentally stored the physical/private NoerHome map id.
cid=MPClanEstate.resume_clan_id
kind=MPClanEstate.resume_kind
if cid>0 && !kind.empty?
out['clan_estate_resume_clan']=cid
out['clan_estate_resume_kind']=kind
else
out.delete('clan_estate_resume_clan') if out.respond_to?(:delete)
out.delete('clan_estate_resume_kind') if out.respond_to?(:delete)
end
out
end
end
module LevelRewards
def level_up
before=trait_point
result=super
earned=trait_point-before
if earned>0 && $game_party
total=$game_party.instance_variable_get(:@clan_estate_earned).to_i
$game_party.instance_variable_set(:@clan_estate_earned,total+earned)
end
result
end
end
module PassportLock
def gain_item(item,amount=1,include_equip=false)
if amount<0 && !MPClanEstate.instance_variable_get(:@applying)
object=item.is_a?(String) ? $data_ItemName[item] : item
if object
minimum=(MPClanEstate.state['locked']||{})[MPClanEstate.item_key(object)].to_i
if minimum>0 && item_number(object)+amount<minimum
MPClanEstate.notify('Эти документы хранятся до освобождения пленника.')
return
end
end
end
super
end
end
module StorageLock
def can_move_item_to_box?(item)
if item && MPClanEstate.child_item?(item)
SndLib.sys_buzzer
MPClanEstate.notify('Ребёнка нельзя поместить в клановый сундук.')
return false
end
if item && (MPClanEstate.state['locked']||{})[MPClanEstate.item_key(item)].to_i>0
SndLib.sys_buzzer
return false
end
super
end
end
module Patrol
def active_local_contract?; MPClanEstate.slave? ? false : super; end
end
module MapTravel
def change_map_overmap_force_point_trans(*args)
return if MPClanEstate.slave?
super
end
end
module ReturnPoint
def reserve_transfer(map_id,x,y,d=2,*rest)
if MPClanEstate.active?
house=(NoerHomeEstate.local_house_id rescue -1).to_i
yard=(NoerHomeEstate.local_yard_id rescue -1).to_i
leaving=[house,yard].include?($game_map.map_id.to_i)
# Tag-map transitions use string keys ("NoerHome"/"NoerHomeOut"), so
# map_id.to_i becomes 0. Treat both local numeric ids and tag keys as
# internal house<->yard travel; only a real external destination should
# consume the captured OverMap return point.
target_kind=(NoerHomeEstate.home_target_kind(map_id) rescue '').to_s
point=MPClanEstate.return_point
if leaving && target_kind.empty? && point.is_a?(Array) && point.length>=4
map_id,x,y,d=point[0].to_i,point[1].to_i,point[2].to_i,point[3].to_i
MPClanEstate.home_kind=nil
MPClanEstate.return_point=nil
MPClanEstate.clear_estate_route
end
end
super(map_id,x,y,d,*rest)
end
end
# Remote players are represented as map events. When one stands on the
# player's tile, the engine normally starts that event before checking the
# local NPC in front. Temporarily make remote-player events non-triggering
# whenever a real local action event is available at the interaction point.
module LocalNpcInteractionPriority
def check_action_event(chkItemsPick=false)
return super unless clan_estate_local_action_available?
remote_events=($game_map.events.values rescue []).select{|event|event.instance_variable_get(:@net_player_id)}
saved=remote_events.map{|event|[event,event.instance_variable_get(:@trigger)]}
remote_events.each{|event|event.instance_variable_set(:@trigger,-1)}
super
ensure
saved.each{|event,trigger|event.instance_variable_set(:@trigger,trigger)} if defined?(saved) && saved
end
def clan_estate_local_action_available?
return false unless $game_map
x1=$game_map.round_x_with_direction(@x,@direction)
y1=$game_map.round_y_with_direction(@y,@direction)
here=($game_map.events_xy(@x,@y) rescue [])
front=($game_map.events_xy(x1,y1) rescue [])
return true if here.any?{|event|clan_estate_local_trigger?(event,[0],false)}
return true if front.any?{|event|clan_estate_local_trigger?(event,[0,1,2],true)}
if $game_map.counter?(x1,y1)
x2=$game_map.round_x_with_direction(x1,@direction)
y2=$game_map.round_y_with_direction(y1,@direction)
beyond=($game_map.events_xy(x2,y2) rescue [])
return true if beyond.any?{|event|clan_estate_local_trigger?(event,[0,1,2],true)}
end
false
rescue
false
end
def clan_estate_local_trigger?(event,triggers,normal)
return false unless event
return false if event.instance_variable_get(:@net_player_id)
event.trigger_in?(triggers) && event.normal_priority? == normal && checkNpcAbleTrigger(event)
rescue
false
end
end
module PursuitView
def update(*args)
result=super
pursuit=MPClanEstate.state['pursuit']
if pursuit && $game_map.isOverMap
unless @clan_collector
@clan_collector=Sprite.new
@clan_collector.bitmap=Bitmap.new(140,48)
@clan_collector.bitmap.font.size=18
@clan_collector.bitmap.font.color=Color.new(255,100,80)
@clan_collector.bitmap.draw_text(0,0,140,24,'Коллекторы',1)
@clan_collector.bitmap.fill_rect(63,27,14,19,Color.new(200,50,35))
@clan_collector.ox=70;@clan_collector.oy=48;@clan_collector.z=180
end
@clan_collector.x=$game_map.adjust_x(pursuit[0])*32+16
@clan_collector.y=$game_map.adjust_y(pursuit[1])*32+32
@clan_collector.visible=true
elsif @clan_collector
@clan_collector.visible=false
end
result
end
def terminate(*args)
if @clan_collector
@clan_collector.bitmap.dispose;@clan_collector.dispose;@clan_collector=nil
end
super
end
end
module PortalBypass
def portal_on_reserve_transfer(src_map,event_id,dst_map,x,y,dir,fade)
begin
# Личный дом и клановый двор/дом — оба tag-map ("NoerHome"/"NoerHomeOut").
# Generic portal делает dst_map.to_i => 0 и вешает переход (чёрный экран).
if defined?(NoerHomeEstate)
kind = NoerHomeEstate.home_target_kind(dst_map).to_s
unless kind.empty?
# Drop any stale generic-portal wait/cache created by an earlier
# broken home attempt. The local tag-map transfer itself was
# already reserved by Game_Player#reserve_transfer before this hook.
clear_portal_wait if respond_to?(:clear_portal_wait)
if respond_to?(:portal_key) && instance_variable_defined?(:@portal_routes)
routes = instance_variable_get(:@portal_routes)
key = portal_key(src_map, event_id)
routes.delete(key) if routes.respond_to?(:delete)
end
return nil
end
end
rescue => e
puts "[NoerHome portal bypass] #{e.class}: #{e.message}"
end
super
end
end
module EstateHome
def house_bought?; MPClanEstate.active? ? true : super; end
def own_home_context?; MPClanEstate.active? ? MPClanEstate.editable? : super; end
def guest_context?; MPClanEstate.active? ? !MPClanEstate.editable? : super; end
def current_home_kind; MPClanEstate.active? ? MPClanEstate.home_kind : super; end
def decor_blob; MPClanEstate.active? ? MPClanEstate.state['decor'].to_s : super; end
def set_decor_blob(value)
return super unless MPClanEstate.active?
return false unless MPClanEstate.editable?
MPClanEstate.send_action('decor', 'decor'=>value.to_s)
end
def sync_to_server(*args); MPClanEstate.active? ? false : super; end
def transfer_allowed?(map_id); MPClanEstate.active? ? true : super; end
def prepare_home_transfer(kind)
return super unless MPClanEstate.active?
MPClanEstate.home_kind=kind
MPClanEstate.remember_estate_route(kind)
super
end
def after_map_setup(map_id=nil)
# If full estate state was cleared during a disconnect but we are still on
# the physical house/yard map, keep publishing the remembered virtual clan
# room. This prevents a final autosave from becoming a private-home save.
kind=home_kind_for_local($game_map.map_id)
if MPClanEstate.active?
if kind.empty?
MPClanEstate.home_kind=nil
MPClanEstate.clear_estate_route
return
end
MPClanEstate.home_kind=kind
MPClanEstate.remember_estate_route(kind)
send_line(map_packet_for_server($game_map.map_id))
return
end
if !kind.empty? && MPClanEstate.resume_clan_id>0 && MPClanEstate.resume_kind==kind
send_line(map_packet_for_server($game_map.map_id))
return
end
super
end
def map_packet_for_server(map_id)
kind=home_kind_for_local(map_id)
return super if kind.empty?
if MPClanEstate.active?
MPClanEstate.remember_estate_route(kind)
# Compute the virtual room id from the authoritative clan id instead of
# trusting an optional/stale map field. This prevents accidental "map:"
# packets after reconnect and keeps every client in the same clan room.
virtual=MPClanEstate.virtual_map_id(kind)
return "map:#{virtual}" if virtual.to_i>0
end
# Disconnect-safe fallback: @state/@home_kind may already be cleared while
# Save14 is still performing the final map preflight/cloud commit.
if MPClanEstate.resume_clan_id>0 && MPClanEstate.resume_kind==kind
virtual=MPClanEstate.resume_virtual_map_id(kind)
return "map:#{virtual}" if virtual.to_i>0
end
super
end
end
module Garden
def own_yard?
return super unless MPClanEstate.active?
MPClanEstate.home_kind=='yard' && MPClanEstate.garden_slave_access?
end
def decode
return super unless MPClanEstate.active?
out={}
(MPClanEstate.state['plots']||{}).each do |slot,p|
crop=NoerHomeGarden::CROPS.find{|_,cfg|cfg[:item]==p['crop']}
next unless crop
out[slot.to_i]={:crop=>crop[0],:watered=>p['watered'],:day=>p['planted'].to_i,:farmer=>p['farmer'].to_i}
end
out
end
# The original NoerHome garden matures on the NEXT dateAmt unit:
# stage 3 when watered && today > planted_day
# ClanEstate server base used EstateRules::DAY (2 units) for harvest, which
# doubled the original garden wait. The server compatibility plugin shipped
# with this client translates only harvest validation back to the original
# one-unit rule; wages/passes/fines keep their existing DAY=2 semantics.
#
# The live server time packet is authoritative. @last_server_date is the
# integer dateAmt unit; @last_server_total is the current 0...steps phase.
def clan_server_now
begin
if defined?(WebSocket)
raw = WebSocket.instance_variable_get(:@last_server_date) rescue nil
return raw.to_i if !raw.nil? && raw.to_i > 0
end
rescue
end
begin
if defined?($game_date) && $game_date && $game_date.respond_to?(:dateAmt)
raw = $game_date.dateAmt.to_i
return raw if raw > 0
end
rescue
end
(MPClanEstate.state['clock'] || 0).to_i
rescue
0
end
# If WorldState was restarted behind the persisted ClanEstate clock, rebase
# only the DISPLAYED planting timestamp to the live clock. The companion
# server plugin performs the same rebase before harvest validation.
def clan_effective_planted(data)
planted = data ? data[:day].to_i : 0
now = clan_server_now
begin
estate_clock = (MPClanEstate.state['clock'] || 0).to_i
if planted > now && estate_clock > now
shift = estate_clock - now
planted = [planted - shift, 0].max
end
rescue
end
planted
rescue
data ? data[:day].to_i : 0
end
def clan_growth_remaining(data)
return 0 unless data
planted = clan_effective_planted(data)
[1 - (clan_server_now - planted), 0].max
rescue
1
end
def clan_harvest_ready?(data)
!!data && !!data[:watered] && clan_growth_remaining(data) <= 0
rescue
false
end
def clan_server_phase
total = 0.0
steps = 100.0
begin
if defined?(WebSocket)
raw_total = WebSocket.instance_variable_get(:@last_server_total) rescue nil
raw_steps = WebSocket.instance_variable_get(:@steps_per_cycle) rescue nil
total = raw_total.to_f unless raw_total.nil?
steps = raw_steps.to_f if !raw_steps.nil? && raw_steps.to_f > 0.0
end
rescue
end
total %= steps if steps > 0.0
[total, steps]
rescue
[0.0, 100.0]
end
def clan_growth_seconds_remaining(data)
return 0 unless data
now = clan_server_now
planted = clan_effective_planted(data)
target = planted + 1
units = target - now
return 0 if units <= 0
phase, steps = clan_server_phase
# Client sends time_init rate=1.0, so one cycle step is one real second.
seconds = ((units - 1) * steps) + (steps - phase)
[seconds.ceil, 0].max
rescue
0
end
def clan_growth_text(data)
sec = clan_growth_seconds_remaining(data)
return 'Урожай созрел.' if sec <= 0
if sec >= 60
m = sec / 60
s = sec % 60
"Созревает — примерно #{m}:#{format('%02d', s)}"
else
"Созревает — примерно #{sec} сек."
end
rescue
'Урожай созревает.'
end
def stage_for(data)
return super unless MPClanEstate.active?
return 0 unless data
return 3 if clan_harvest_ready?(data)
data[:watered] ? 2 : 1
end
def clan_bed_density(crop)
crop.to_s=='tomato' ? 2 : 4
end
def plant(slot,crop)
return super unless MPClanEstate.active?
MPClanEstate.send_action('plant','slot'=>slot,'item'=>NoerHomeGarden::CROPS.fetch(crop.to_s)[:item])
end
def water(slot); MPClanEstate.active? ? MPClanEstate.send_action('water','slot'=>slot) : super; end
def harvest(slot)
return super unless MPClanEstate.active?
data=decode[slot.to_i]
return false unless data
unless data[:watered]
MPClanEstate.notify('Сначала полейте грядку.')
return false
end
unless clan_harvest_ready?(data)
MPClanEstate.notify(clan_growth_text(data))
return false
end
MPClanEstate.send_action('harvest','slot'=>slot)
end
# Clan plots are server-owned. Hide the fake local clear action.
def clear(slot); MPClanEstate.active? ? false : super; end
end
module SharedAmenities
def own_house?
return super unless MPClanEstate.active?
MPClanEstate.home_kind=='house' && !MPClanEstate.state['frozen']
end
def open_storage
return super unless MPClanEstate.active?
Game_Interpreter.new.clan_estate_chest
end
def save_placements(rows)
return false if MPClanEstate.active? && !MPClanEstate.editable?
super
end
def reset_placements
return super unless MPClanEstate.active?
return false unless MPClanEstate.editable?
NoerHomeEstate.set_decor_blob('')
end
# Estate furnishings are configured by the creator; the personal-house
# buy/refund wallet must not run against asynchronous shared estate state.
def item_price(item);MPClanEstate.active? ? 0 : super;end
def apply_price_delta(*args);MPClanEstate.active? ? MPClanEstate.editable? : super;end
end
# The engine checks OK before Cancel in Window_ChoiceList. Some keyboard
# layouts report ESC as both commands for one frame, which used to execute
# the highlighted chest operation. Clan chest dialogs always consume Cancel
# first, including the amount selector.
module ChestChoiceCancelPriority
def process_handling
if MPClanEstate.chest_choice_active? && open? && active
cancel_pressed = Input.trigger?(:B) || WolfPad.trigger?(:X_LINK)
return process_cancel if cancel_enabled? && cancel_pressed
end
super
end
end
module EditorPermission
def start
return false if MPClanEstate.active? && !MPClanEstate.editable?
super
end
end
module Menus
# LonaRPG passes every choice label through Text#[], where an ASCII colon
# means "translation_file:translation_id". ClanEstate labels are already
# localized/raw text, so sanitize colons before the engine sees them. This
# also protects dynamic clan names, nicknames and item labels containing ':'.
def clan_estate_pick_rows(rows, target = nil)
safe_rows = rows.map do |row|
copy = row.dup
copy[0] = copy[0].to_s.gsub(':', ':')
copy
end
picked=noerhome_pick_rows(safe_rows, target)
# NoerHome's sheet picker returns false for ESC. Normalize it to the
# same explicit cancel value used by every ClanEstate menu so it can
# never reach to_i or be mistaken for the highlighted action.
picked.nil? || picked==false ? 'cancel' : picked
end
def noerhome_garden_menu(slot)
return super unless MPClanEstate.active?
state=NoerHomeGarden.decode
data=state[slot.to_i]
if data.nil?
rows=[]
NoerHomeGarden::CROPS.each do |crop,cfg|
density = NoerHomeGarden.respond_to?(:clan_bed_density) ? NoerHomeGarden.clan_bed_density(crop) : (crop.to_s=='tomato' ? 2 : 4)
rows << ["Посадить #{cfg[:title]} — грядка на #{density} растения (есть x#{NoerHomeGarden.item_count(cfg[:item])})",crop]
end
rows << ['Отмена','cancel']
picked=clan_estate_pick_rows(rows)
NoerHomeGarden.plant(slot,picked) if NoerHomeGarden::CROPS[picked.to_s]
return true
end
rows=[]
if data[:watered]
if NoerHomeGarden.clan_harvest_ready?(data)
rows << ['Собрать урожай','harvest']
else
rows << [NoerHomeGarden.clan_growth_text(data),'wait']
end
else
rows << ['Полить','water']
end
rows << ['Отмена','cancel']
picked=clan_estate_pick_rows(rows)
NoerHomeGarden.harvest(slot) if picked=='harvest'
NoerHomeGarden.water(slot) if picked=='water'
if picked=='wait'
MPClanEstate.notify(NoerHomeGarden.clan_growth_text(data))
end
true
rescue => e
puts "[ClanEstate garden menu] #{e.class}: #{e.message}"
false
end
def noerhome_decor_menu(*args)
if MPClanEstate.active? && !MPClanEstate.editable?
MPClanEstate.notify('Менять интерьер может только создатель клана или администрация.')
return false
end
super
end
def command_355
if MPClanEstate.active? && @list[@index].parameters[0].to_s.strip == 'SceneManager.goto(Scene_NoerHomeStorage)'
@index += 1 while next_event_code == 655
clan_estate_chest
return true
end
super
end
def clan_estate_enter_own_home
# Do not block the door on ce_state. The plugin can resolve both an
# ordinary clan member and an assigned clan slave directly from profile.
# A background hello still refreshes the full estate state/inventory.
MPClanEstate.refresh_state
clan=MPClanEstate.local_clan_id.to_i
data={'kind'=>'house'}
data['clan']=clan if clan>0
MPClanEstate.send_action('enter',data)
true
end
def noerhome_overmap_house_menu
# ClanEstate is shown even before the estate state arrives. Selecting it
# now enters the current clan's house immediately, with no ID/submenu step.
clan_name=MPClanEstate.local_clan_name
clan_label=clan_name.empty? ? 'Клановый дом' : "Клановый дом — #{clan_name}"
picked=clan_estate_pick_rows([[clan_label,'clan'],['Личный дом и гости','personal'],['Отмена','cancel']])
return clan_estate_enter_own_home if picked=='clan'
return super if picked=='personal'
true
end
def load_script(path)
guild_worker_path=(path=='Data/HCGframes/event/NoerTavernGuildEmpolyee.rb')
if path=='Data/HCGframes/event/NoerBankMaani.rb' && MPClanEstate.state['clan'].to_i>0
loop do
picked=clan_estate_pick_rows([['Частный клиент','bank'],['Юр. лицо','legal'],['Отмена','cancel']])
# Обычные банковские услуги игры.
break if picked=='bank'
return if picked!='legal'
# Отдельное меню операций клана.
loop do
fine=MPClanEstate.state['fine'].to_i
legal=clan_estate_pick_rows([["Штраф клана: #{fine} золота — оплатить со счёта клана",'fine'],['Внести золото на счёт клана','fund'],['Назад','back']])
if legal=='fine'
MPClanEstate.send_action('pay_fine')
return
elsif legal=='fund'
qty=clan_estate_pick_rows([['1 золотая','1'],['2 золотых','2'],['Назад','0']]).to_i
if qty>0
MPClanEstate.send_action('fund','amount'=>qty)
return
end
else
break
end
end
end
end
if guild_worker_path
begin
result=super
MPClanEstate.save_guild_progress
result
ensure
MPClanEstate.restore_worker_view(self)
end
else
super
end
end
def clan_estate_passport
# Ask the plugin directly. This check is independent from a pending house
# request and verifies both ordinary player slavery and clan slavery.
status=MPClanEstate.authoritative_document_slave_status
if status==true
call_msg("\\CBmp[GuildEmpolyee,20]\\c[4]Работник:\\C[0] Я не могу восстановить ваши документы, пока вы находитесь в рабстве у игрока или клана. Сначала получите освобождение.")
MPClanEstate.incite_map_npcs_against_player
return
elsif status.nil?
call_msg("\\CBmp[GuildEmpolyee,20]\\c[4]Работник:\\C[0] Не удалось проверить ваш статус на сервере. Попробуйте ещё раз через несколько секунд.")
return
end
due=MPClanEstate.state.fetch('passport_due',-1).to_i
clock=MPClanEstate.state['clock'].to_i
if due<0
picked=clan_estate_pick_rows([['Подать заявление — выдача через 21 игровой день','request'],['Отмена','cancel']])
MPClanEstate.send_action('passport_request') if picked=='request'
elsif clock>=due
picked=clan_estate_pick_rows([['Забрать готовый паспорт','collect'],['Отмена','cancel']])
MPClanEstate.send_action('passport_collect') if picked=='collect'
else
call_msg("\\CBmp[GuildEmpolyee,20]\\c[4]Работник:\\C[0] Паспорт ещё не готов. До выдачи осталось #{((due-clock)/2.0).ceil} игровых дней.")
end
end
def clan_estate_assign
rows=(MPClanEstate.state['owned_slaves']||[]).map{|c|[c['nick'].to_s,c['contract'].to_s]}
rows << ['Отмена','0']
picked=clan_estate_pick_rows(rows).to_i
MPClanEstate.send_action('assign','contract'=>picked) if picked>0
end
def clan_estate_menu
# Clan actions always target the clan the current player actually belongs
# to. Internal estate IDs are never shown as a choice to the player.
clan=MPClanEstate.state['clan'].to_i
if clan<=0 && !MPClanEstate.clan_slave?
MPClanEstate.notify('Вы не состоите в клане.')
return
end
rows=[['Клановый дом','house'],['Двор и огород','yard']]
rows << ['Статус раба','status'] if MPClanEstate.clan_slave?
rows << ["Репутация клана: #{MPClanEstate.state['reputation'].to_i}",'info']
rows << ['Отмена','cancel']
picked=clan_estate_pick_rows(rows)
if picked=='status'
MPClanEstate.notify(MPClanEstate.slave_status_text)
elsif picked=='info'
fine=MPClanEstate.state['fine'].to_i
text="Репутация клана: #{MPClanEstate.state['reputation'].to_i}."
text += fine>0 ? " Штраф: #{fine} золотых." : ' Штрафов нет.'
text += ' Клан заморожен.' if MPClanEstate.state['frozen']
MPClanEstate.notify(text)
elsif ['house','yard'].include?(picked)
data={'kind'=>picked}
data['clan']=clan if clan>0
MPClanEstate.send_action('enter',data)
end
end
def clan_estate_chest
MPClanEstate.open_chest_scene
end
end
module GuildMenu
def open(interpreter=nil)
return super unless interpreter
unless defined?(WebSocket) && WebSocket.instance_variable_get(:@connected)
WebSocket.clan_notify('Нет соединения с сервером.',true) if defined?(WebSocket)
return
end
MPClanEstate.refresh_state
rows=[['Список кланов','list'],['Мой клан','mine'],['Создать клан','create']]
if MPClanEstate.state['clan'].to_i>0
rows << ['Выйти из клана','leave']
rows << ['Управление кланом на сайте','site']
rows << ['Клановый дом','home']
rows << ['Передать своего раба клану','assign']
end
rows << ['Отмена','cancel']
picked=interpreter.clan_estate_pick_rows(rows)
case picked
when 'list';WebSocket.clan_request_list
when 'mine';WebSocket.clan_request_me
when 'create'
name=MPClanGuild.default_clan_name
WebSocket.clan_notify("Создаю «#{name}». Стоимость: 15 Монет III. Для своего названия: /clan create Название | Тег")
WebSocket.clan_create_with_fee(name,MPClanGuild.default_clan_tag(name),'')
when 'leave';WebSocket.clan_leave
when 'site';WebSocket.clan_notify('Переименование, описание, роли и удаление клана доступны в личном кабинете на сайте.')
when 'home';MPClanEstate.with_worker_context{interpreter.clan_estate_enter_own_home}
when 'assign';MPClanEstate.with_worker_context{interpreter.clan_estate_assign}
end
end
end
module Frame
def update(*args)
result=super
if MPClanEstate.install
MPClanEstate.tick
MPClanEstate.update_menu
end
result
end
end
end
# Clan chest uses the same two-column storage scene as the normal bank, but every
# transfer remains server-authoritative. The right pane is built only from the
# filtered `chest` map sent by ClanEstate, so slaves never receive hidden stock.
# Unlike a normal storage box, the clan chest title intentionally hides the
# stock weight/value/count summary ("w / p / xN") and shows only its name.
if defined?(Window_BoxTitle)
class Window_ClanEstateBoxTitle < Window_BoxTitle
def draw_box_amount(draw_maximum)
# Clan chest: keep the header clean. Counts remain visible on item rows.
end
end
end
if defined?(Scene_ItemStorage)
class Scene_ClanEstateStorage < Scene_ItemStorage
def prepare(box_id=MPClanEstate::CLAN_CHEST_BOX_ID, taking=false)
super(MPClanEstate::CLAN_CHEST_BOX_ID, taking)
end
def start
MPClanEstate.setup_chest_box
MPClanEstate.sync_chest_box(true)
@ce_chest_fp=MPClanEstate.chest_fingerprint
@ce_last_refresh=Graphics.frame_count
super
begin
# Replace only the right clan-chest title window. Normal bank/storage
# windows keep their stock weight/value/count summary unchanged.
if defined?(Window_ClanEstateBoxTitle) && @box_title
@box_title.dispose rescue nil
@box_title = Window_ClanEstateBoxTitle.new(
Graphics.width/2,
Storage_Boxes_Setting::BOXES[MPClanEstate::CLAN_CHEST_BOX_ID][:name],
MPClanEstate::CLAN_CHEST_BOX_ID
)
end
# The base storage scene labels the left pane with menu:Box/Body ("Лона").
# For multiplayer clan storage it must show the actual logged-in nickname.
nick = defined?(WebSocket) && WebSocket.respond_to?(:local_nickname) ? WebSocket.local_nickname.to_s.strip : ''
unless nick.empty? || !@bag_title
@bag_title.instance_variable_set(:@title,nick)
@bag_title.refresh
end
rescue => e
puts "[ClanEstate chest title] #{e.class}: #{e.message}"
end
end
def update
fp=MPClanEstate.chest_fingerprint
if fp!=@ce_chest_fp
@ce_chest_fp=fp
if MPClanEstate.sync_chest_box(true)
refresh
end
end
frame=Graphics.frame_count
if frame-@ce_last_refresh.to_i>=300
@ce_last_refresh=frame
MPClanEstate.refresh_state
end
super
end
def update_item_selection
if MPClanEstate.request_pending?
# Do not let the player close the window in the tiny interval between
# click and authoritative server ACK. Otherwise the transfer is applied
# correctly on Scene_Map and visually looks like it happened only because
# the chest was closed. The normal request timeout still releases this.
if Input.trigger?(:B) || WolfPad.trigger?(:X_LINK) || (Mouse.enable? && Input.trigger?(:MX_LINK))
SndLib.sys_buzzer
end
return
end
super
end
def ce_server_refresh
MPClanEstate.sync_chest_box(true)
@ce_chest_fp=MPClanEstate.chest_fingerprint
refresh
@bag_window.refresh if @bag_window && @bag_window.respond_to?(:refresh)
@box_window.refresh if @box_window && @box_window.respond_to?(:refresh)
@bag_title.refresh if @bag_title && @bag_title.respond_to?(:refresh)
@box_title.refresh if @box_title && @box_title.respond_to?(:refresh)
true
rescue => e
puts "[ClanEstate chest scene refresh] #{e.class}: #{e.message}"
false
end
def move_item(val=nil)
if @box_window.active
item=@box_window.item
return SndLib.sys_buzzer if item.nil? || @box_window.index<0
available=$game_boxes.item_number(item,@box_id).to_i
key=MPClanEstate.item_key(item)
qty = val=='max' ? available : (val.is_a?(Numeric) ? [available,val.to_i].min : 1)
ration=MPClanEstate.slave_withdraw_remaining(key)
qty=[qty,ration].min unless ration.nil?
if qty<=0
MPClanEstate.notify('Дневной лимит этого типа припасов уже выбран.') if MPClanEstate.clan_slave?
return SndLib.sys_buzzer
end
if MPClanEstate.send_action('withdraw','item'=>key,'amount'=>qty)
SndLib.sys_equip(80,140)
end
elsif @bag_window.active
item=@bag_window.item
return SndLib.sys_buzzer if item.nil? || @bag_window.index<0 || !@bag_window.enable?(item)
if MPClanEstate.child_item?(item)
MPClanEstate.notify('Ребёнка нельзя поместить в клановый сундук.')
return SndLib.sys_buzzer
end
key=MPClanEstate.item_key(item)
if (MPClanEstate.state['locked']||{})[key].to_i>0
return SndLib.sys_buzzer
end
available=$game_party.item_number(item).to_i
qty = val=='max' ? available : (val.is_a?(Numeric) ? [available,val.to_i].min : 1)
return SndLib.sys_buzzer if qty<=0
if MPClanEstate.send_action('deposit','item'=>key,'amount'=>qty)
SndLib.sys_equip
end
else
SndLib.sys_buzzer
end
end
end
end
# The clan house reuses a physical NoerHome map, whose ordinary nap event can
# roll hostile bandits. In a valid clan-house session expose no nap event to
# the local sleep command, making it take the normal `handleNap` branch. Yard,
# ordinary houses and every non-clan map retain their original encounter logic.
if defined?(Game_Map)
module ClanEstateProtectedNap
def napEventId
if defined?(MPClanEstate) && MPClanEstate.active? && MPClanEstate.home_kind.to_s == 'house'
return nil
end
super
end
end
Game_Map.prepend(ClanEstateProtectedNap) unless Game_Map.ancestors.include?(ClanEstateProtectedNap)
end
# Clan garden beds are physically 2x2 tiles. The stock NoerHome renderer
# draws one crop sprite at the bed origin; for clan farming that looked like one
# lonely plant in a large bed. Keep the server's one-cycle-per-bed rules intact,
# but render a full bed: 4 potato/carrot plants or 2 tomato plants.
if defined?(Spriteset_Map)
module ClanEstateDenseGardenSprites
def refresh_noerhome_estate_sprites
result=super
begin
active = defined?(MPClanEstate) && MPClanEstate.active? && defined?(NoerHomeGarden) && NoerHomeGarden.visible_yard?
unless active
@clan_estate_density_signature=nil
return result
end
sig=@noerhome_estate_signature
return result if @clan_estate_density_signature==sig
@clan_estate_density_signature=sig
state=NoerHomeGarden.decode
coords=NoerHomeGarden.plots
state.each do |index,data|
xy=coords[index.to_i]
next unless xy && data
crop=data[:crop].to_s
offsets = crop=='tomato' ? [[1,0]] : [[1,0],[0,1],[1,1]]
stage=NoerHomeGarden.stage_for(data)
opacity = stage>=3 ? 255 : (stage==2 ? 210 : 160)
offsets.each do |dx,dy|
make_noerhome_sprite(NoerHomeGarden.crop_image_path(crop),xy[0]+dx,xy[1]+dy,74,opacity)
end
end
update_noerhome_estate_sprites
rescue => e
puts "[ClanEstate garden sprites] #{e.class}: #{e.message}"
end
result
end
end
Spriteset_Map.prepend(ClanEstateDenseGardenSprites)
end
# Clan-slave display in the character main-stats panel.
# 1.3.5: do NOT replace the normal Lona title ("Простолюдинка", etc.).
# Clan slaves use the same title rendering as every other player. Their bond
# is shown only in the ordinary clan row as "Раб клана: <название>".
if defined?(Menu_MainStats)
class Menu_MainStats < Menu_ContentBase
unless method_defined?(:clan_estate_make_menu_hash_without_slave_clan_row)
alias clan_estate_make_menu_hash_without_slave_clan_row make_menu_hash
end
def make_menu_hash
data = clan_estate_make_menu_hash_without_slave_clan_row
begin
return data unless defined?(MPClanEstate) && MPClanEstate.respond_to?(:clan_slave?) && MPClanEstate.clan_slave?
clan_name = MPClanEstate.respond_to?(:local_clan_name) ? MPClanEstate.local_clan_name.to_s.strip : ''
if clan_name.empty? && MPClanEstate.respond_to?(:local_clan_id)
clan_id = MPClanEstate.local_clan_id.to_i
clan_name = "##{clan_id}" if clan_id > 0
end
label = 'Раб клана: '
value = clan_name.to_s
# Russian-font main stats returns [label_hash, value_hash].
if data.is_a?(Array) && data[0].is_a?(Hash) && data[1].is_a?(Hash)
data[0]['clan'] = [157 + 7, 12 * 17, 220, 60, label]
data[1]['clan'] = [157 + 7, 12 * 17, 220, 60, (' ' * label.length) + value, 0]
elsif data.is_a?(Hash)
# Fallback for the stock/non-split stats renderer.
text = value.empty? ? 'Раб клана' : "Раб клана: #{value}"
data['clan'] = [157 + 8, 60 + 85, 240, 60, text, 0]
end
rescue => e
puts "[ClanEstate] slave clan row failed: #{e.class}: #{e.message}"
end
data
end
end
end
Graphics.singleton_class.prepend(MPClanEstate::Frame)
# Live UI для кланового сундука (патч из 29_live_esc_menu — класс уже определён).
begin
MPLiveEscMenu.install_clan_chest_live! if defined?(MPLiveEscMenu) && MPLiveEscMenu.respond_to?(:install_clan_chest_live!)
rescue => e
puts "[ClanEstate] live chest install: #{e.class}: #{e.message}" rescue nil
end