Files
LonaRPG-Online-Games/ModScripts/_Mods/LonaCraft/Scripts/80_CraftScene.rb
T
2026-10-29 21:59:06 +04:00

1176 lines
40 KiB
Ruby

#==============================================================================
# LonaCraft - 80_CraftScene.rb
# What it does:
# * Scene_LonaCraft: the crafting screen, built on the storage-box scene
# (Data/Scripts/Frames/203_Storage Boxes.rb, Scene_ItemStorage): two title
# windows on top, two panes below, keyboard + mouse, left with
# SceneManager.goto(Scene_Map) like the storage box (the game's
# SceneManager.call/return pop a debug msgbox, 6_SceneManager.rb:91-102).
# Left - recipe list of ONE station (LonaCraft.open_craft_scene(station);
# the left title shows the station's name), grouped Processing /
# Weapons / Ammo / Armour / Furniture / Decorations. Rows the
# player cannot afford are dimmed; rows above the player's
# effective skill are left out of the list (CraftUI::HIDE_LOCKED;
# with it false they are shown dimmed and marked Locked, and
# try_craft buzzes and blinks the skill line).
# Right - details of the selected recipe: output (with the amount made),
# materials have/need (red when short; need = what the open
# station really takes, Recipes.inputs_at, so by hand it is the
# bench amount x1.25 rounded up, with a note in the Materials
# line; the list's dimming uses the same amounts), skill needed vs the
# player's, the five tier chances (after the station's and the
# recipe's tier cap, Recipes.tier_cap), and for gear what Common
# gives.
# Confirm (OK key or left click on a row) crafts; Cancel / Esc / right
# click / the "Cancel" label leaves (to the main menu when it was opened
# from there, else to the map).
# * Recipes come from LonaCraft::Recipes.all (Scripts/55_Recipes.rb). The
# Process list of Scripts/30_Process.rb is folded into the Processing group:
# a Process row is added only when Recipes did not build it (Recipes.
# process_key_known?) and no Recipes entry makes the same output from the
# same inputs, so Config/Recipes.json changes win. Process recipes keep their own rules
# (1 STA each, any plant for the "*plant" input, no roll, no exp).
# * LonaCraft.open_craft_scene(station, back) opens the screen (the main
# menu's crafting with :hand and back = :menu; the station furniture with
# its station, Scripts/90_Furniture.rb).
# * Crash trace (with "debug"; 05_Config.rb LonaCraft.trace, added
# 2026-10-06 after two RGSS301.dll access violations, offset 0x00111a1c,
# in this screen): one line per step to UserData/LonaCraft_trace.log,
# flushed and closed each time: every window and contents Bitmap.new
# (size, failsafe address flag), row builds, list rows drawn, list /
# detail / title refreshes, cursor, page, hover, keys, crafts, the result
# popup, start / post_start / terminate with memory, an "alive" line every
# 300 frames, Ruby errors caught by data_call or raised in a frame.
# Text keys: LonaCraft:Craft:<key> in Text/<lang>/Craft.txt.
# Stores nothing itself; every data-layer call is wrapped so an error there
# prints to the console instead of crashing the game.
#==============================================================================
module LonaCraft
# Shared font profile for every custom LonaCraft bitmap/window. RUS2 uses
# the same sharp menu face as the rest of the game's mod UI.
def self.ui_font_name
begin
if defined?(MPSafeFont) && MPSafeFont.respond_to?(:rus2_active?) && MPSafeFont.rus2_active?
name = MPSafeFont.rus2_font(:MENU_L, :TITLE_MENU, :CHOICE)
return name if name && Font.exist?(name)
end
rescue
end
value = Font.default_name rescue "VL Gothic"
value = value[0] if value.is_a?(Array)
value.to_s.empty? ? "VL Gothic" : value.to_s
rescue
"VL Gothic"
end
def self.apply_ui_font(bitmap)
return if bitmap.nil? || !bitmap.respond_to?(:font) || bitmap.font.nil?
bitmap.font.name = ui_font_name
bitmap.font.bold = true
bitmap.font.shadow = false
bitmap.font.outline = false
end
# station: :hand, :carpentry, :furnace, :anvil or :tailor (Stations in
# 55_Recipes.rb; "pot" counts as :hand); the screen lists only that
# station's recipes. back: :map (default) or :menu, where leaving goes.
def self.open_craft_scene(station = :hand, back = :map)
station = defined?(LonaCraft::Stations) ? LonaCraft::Stations.normalize(station) : nil
@craft_station = station || :hand
@craft_back = back == :menu ? :menu : :map
p "LonaCraft Craft: open #{@craft_station} (back to #{@craft_back})"
LonaCraft.trace{ "open_craft_scene station #{@craft_station} back #{@craft_back} from #{SceneManager.scene.class}, goto Scene_LonaCraft" }
SceneManager.goto(Scene_LonaCraft)
LonaCraft.trace("open_craft_scene goto done")
end
# Station of the crafting screen that is (or was last) open
def self.craft_station
@craft_station || :hand
end
# Where the crafting screen goes when it is left: :map or :menu
def self.craft_back
@craft_back || :map
end
#--------------------------------------------------------------------------
# One craftable row. kind is :recipe (a LonaCraft::Recipes object in
# source) or :process_list (an entry of PROCESS_RECIPES in source).
#--------------------------------------------------------------------------
class CraftEntry
attr_reader :kind, :source, :output_name, :output_qty, :inputs, :skill_req, :group, :fixed_tier
def initialize(kind, source, output_name, output_qty, inputs, skill_req, group, fixed_tier)
@kind = kind
@source = source
@output_name = output_name
@output_qty = output_qty.to_i < 1 ? 1 : output_qty.to_i
@inputs = inputs.is_a?(Hash) ? inputs : {}
@skill_req = skill_req.to_i
@group = group
@fixed_tier = fixed_tier
end
def output_item
$data_ItemName[@output_name]
end
end
#--------------------------------------------------------------------------
# Helpers shared by the crafting windows and scene.
#--------------------------------------------------------------------------
module CraftUI
GROUPS = [:process, :weapon, :ammo, :armor, :building, :furniture, :decoration]
GROUP_KEYS = {
:process => "Group/Processing",
:weapon => "Group/Weapons",
:ammo => "Group/Ammo",
:armor => "Group/Armour",
:building => "Group/Building",
:furniture => "Group/Furniture",
:decoration => "Group/Decorations"
}
def self.text(key)
$game_text["LonaCraft:Craft:#{key}"]
end
def self.group_label(group)
text(GROUP_KEYS[group] || GROUP_KEYS[:process])
end
# Runs the block; on any error prints it and returns +default+.
def self.data_call(default)
begin
yield
rescue => e
p "LonaCraft craft screen: #{e.class} #{e.message}"
LonaCraft.trace_error("craft screen data_call", e)
default
end
end
def self.fibre_key
LonaCraft.const_defined?(:FIBRE) ? LonaCraft::FIBRE : nil
end
#----------------------------------------------------------------------
# Recipe list
#----------------------------------------------------------------------
def self.group_of(obj)
return :weapon if obj.is_a?(RPG::Weapon)
return :armor if obj.is_a?(RPG::Armor)
:process
end
def self.station_name(station)
text("Station/#{station}")
end
def self.build_entries(station = LonaCraft.craft_station)
list = []
recipes = []
if defined?(LonaCraft::Recipes)
recipes = data_call([]) { LonaCraft::Recipes.for_station(station).to_a }
end
recipes.each{|recipe|
entry = data_call(nil) {
obj = $data_ItemName[recipe.output]
if obj.nil?
nil
else
case recipe.category.to_s
when "process" then group = :process
when "furniture" then group = :furniture
when "decoration" then group = :decoration
when "ammo" then group = :ammo
when "building" then group = :building
else group = group_of(obj)
end
CraftEntry.new(:recipe, recipe, recipe.output, recipe.amount, recipe.inputs, recipe.skill_req, group, recipe.fixed_tier)
end
}
list << entry if entry
}
# Fallback for PROCESS rows the recipe list does not have (e.g. its
# build failed); rows it has, Config/Recipes.json changes included,
# are left to it.
if LonaCraft.const_defined?(:PROCESS_RECIPES)
LonaCraft::PROCESS_RECIPES.each{|recipe|
out_name, out_qty = recipe[2].first
next if out_name.nil? || $data_ItemName[out_name].nil?
next if defined?(LonaCraft::Recipes) && LonaCraft::Recipes.respond_to?(:process_key_known?) && LonaCraft::Recipes.process_key_known?(recipe[0])
next if defined?(LonaCraft::Stations) && !LonaCraft::Stations.for_process(recipe[0]).include?(station)
in_keys = recipe[1].keys.map{|k| k.to_s }.sort
next if list.any?{|e| e.output_name == out_name && e.inputs.keys.map{|k| k.to_s }.sort == in_keys }
list << CraftEntry.new(:process_list, recipe, out_name, out_qty, recipe[1], 0, :process, 1)
}
end
list
end
# Owner option (2026-10-06): recipes above the player's effective skill
# are left out of the list instead of being shown dimmed and Locked.
HIDE_LOCKED = true
# [[:header, group], [:entry, CraftEntry], ...] in group order,
# sorted by skill requirement inside a group (stable). With HIDE_LOCKED
# only recipes the player's skill allows are listed (the Locked path
# below stays for HIDE_LOCKED = false).
def self.build_rows
LonaCraft.trace{ "build_rows begin station #{LonaCraft.craft_station}" }
list = build_entries
rows = []
GROUPS.each{|group|
members = []
list.each_with_index{|entry, i| members << [entry, i] if entry.group == group }
next if members.empty?
members = members.select{|pair| skill_ok?(pair[0]) } if HIDE_LOCKED
next if members.empty?
members = members.sort_by{|pair| [pair[0].skill_req, pair[1]] }
rows << [:header, group]
members.each{|pair| rows << [:entry, pair[0]] }
}
LonaCraft.trace{ "build_rows end #{list.size} entries, #{rows.size} rows (skill #{skill_effective})" }
rows
end
#----------------------------------------------------------------------
# Player state
#----------------------------------------------------------------------
def self.skill_effective
return 0 unless defined?(LonaCraft::Skill)
data_call(0) { LonaCraft::Skill.effective.to_i }
end
def self.skill_level
return 0 unless defined?(LonaCraft::Skill)
data_call(0) { LonaCraft::Skill.level.to_i }
end
def self.skill_exp
return 0 unless defined?(LonaCraft::Skill)
data_call(0) { LonaCraft::Skill.exp.to_i }
end
def self.skill_ok?(entry)
entry.skill_req <= skill_effective
end
def self.have_count(name)
if !fibre_key.nil? && name == fibre_key
return LonaCraft.respond_to?(:fibre_total) ? LonaCraft.fibre_total : 0
end
obj = $data_ItemName[name]
return 0 if obj.nil?
$game_party.item_number(obj).to_i
end
# {item_name => count} the open station takes for +entry+: the recipe's
# inputs times the station's cost, rounded up per input
# (Recipes.inputs_at / scale_inputs, 55_Recipes.rb); the entry's own
# inputs when that is not available.
def self.entry_inputs(entry)
station = LonaCraft.craft_station
if defined?(LonaCraft::Recipes) && LonaCraft::Recipes.respond_to?(:inputs_at)
res = data_call(nil) {
if entry.kind == :recipe
LonaCraft::Recipes.inputs_at(entry.source, station)
else
LonaCraft::Recipes.scale_inputs(entry.inputs, station)
end
}
return res if res.is_a?(Hash)
end
entry.inputs
end
# The station's cost multiplier when above 1 (1.25), else nil
def self.cost_factor(station = LonaCraft.craft_station)
return nil unless defined?(LonaCraft::Stations) && LonaCraft::Stations.respond_to?(:cost)
mult = data_call(1.0) { LonaCraft::Stations.cost(station).to_f }
mult > 1.0 ? mult : nil
end
# 1.25 => "1.25", 2.0 => "2"
def self.factor_text(mult)
mult == mult.to_i ? mult.to_i.to_s : mult.round(2).to_s
end
# "By hand, materials x1.25" (Label/CostNote); nil when the station costs the bench amounts
def self.cost_note(station = LonaCraft.craft_station)
mult = cost_factor(station)
return nil if mult.nil?
fmt = text("Label/CostNote").to_s
return nil if fmt.empty?
data_call(nil) { sprintf(fmt, station_name(station).to_s, factor_text(mult)) }
end
def self.affordable?(entry)
if entry.kind == :recipe
return data_call(false) { LonaCraft::Recipes.affordable?(entry.source, LonaCraft.craft_station) ? true : false }
end
missing(entry).empty?
end
# {item_name => shortfall}
def self.missing(entry)
return {} if LonaCraft::Debug.free? # D2 god mode: nothing missing
if entry.kind == :recipe
res = data_call(nil) { LonaCraft::Recipes.missing(entry.source, LonaCraft.craft_station) }
return res if res.is_a?(Hash)
end
out = {}
entry_inputs(entry).each{|name, qty|
short = qty.to_i - have_count(name)
out[name] = short if short > 0
}
out
end
# [icon_index or nil, display name] for an input
def self.input_icon_and_name(name)
if !fibre_key.nil? && name == fibre_key
obj = nil
if LonaCraft.respond_to?(:fibre_owned)
owned = LonaCraft.fibre_owned
obj = owned.first[0] unless owned.empty?
end
if obj.nil? && LonaCraft.respond_to?(:fibre_items)
first = LonaCraft.fibre_items.first
obj = $data_ItemName[first] if first
end
return [obj ? obj.icon_index : nil, text("Label/Fibre")]
end
obj = $data_ItemName[name]
return [nil, name.to_s] if obj.nil?
[obj.icon_index, $game_text[obj.name]]
end
#----------------------------------------------------------------------
# Tiers
#----------------------------------------------------------------------
def self.tier_chances(entry)
if entry.fixed_tier
tier = entry.fixed_tier.to_i
tier = 1 if tier < 1 || tier > 5
out = [0, 0, 0, 0, 0]
out[tier - 1] = 100
return cap_chances(out, tier_cap(entry))
end
res = nil
if defined?(LonaCraft::Skill)
res = data_call(nil) { LonaCraft::Skill.tier_chances(entry.skill_req) }
end
return [100, 0, 0, 0, 0] unless res.is_a?(Array) && res.length == 5
cap_chances(res.map{|v| v.to_f }, tier_cap(entry))
end
# Best tier the entry can give at the open station (Recipes.tier_cap), nil = no cap
def self.tier_cap(entry)
return nil unless entry.kind == :recipe && defined?(LonaCraft::Recipes) && LonaCraft::Recipes.respond_to?(:tier_cap)
data_call(nil) { LonaCraft::Recipes.tier_cap(entry.source, LonaCraft.craft_station) }
end
# Every chance above +cap+ is added to the cap tier (what the roll gives).
def self.cap_chances(out, cap)
return out if cap.nil? || cap.to_i >= 5
cap = cap.to_i < 1 ? 1 : cap.to_i
extra = 0
cap.upto(4){|i|
extra += out[i]
out[i] = 0
}
out[cap - 1] += extra
out
end
def self.tier_color(tier)
return 0 unless defined?(LonaCraft::Tiers)
data_call(0) { LonaCraft::Tiers.tier_color(tier).to_i }
end
def self.tier_name(tier)
return tier.to_s unless defined?(LonaCraft::Tiers)
data_call(tier.to_s) { LonaCraft::Tiers.tier_name(tier).to_s }
end
#----------------------------------------------------------------------
# Gear summary: [atk, def] added by the base (Common) item, read from
# its already-loaded effects (no load_additional_data call).
#----------------------------------------------------------------------
def self.base_stats(obj)
effects = obj.instance_variable_get(:@lona_effect)
return [0.0, 0.0] unless effects.is_a?(Array)
atk = 0.0
dfn = 0.0
effects.each{|eff|
next unless eff.respond_to?(:attr) && eff.respond_to?(:adjust)
next unless eff.type.to_s == "+"
case eff.attr.to_s
when "atk_plus" then atk += eff.adjust.to_f
when "def_plus" then dfn += eff.adjust.to_f
end
}
[atk, dfn]
end
def self.signed_number(value)
num = value == value.to_i ? value.to_i : value.round(1)
num > 0 ? "+#{num}" : num.to_s
end
#----------------------------------------------------------------------
# Crafting. Returns [item, tier] or nil.
#----------------------------------------------------------------------
def self.craft(entry)
return process_craft(entry.source, entry_inputs(entry)) if entry.kind == :process_list
res = data_call(nil) { LonaCraft::Recipes.craft(entry.source, nil, LonaCraft.craft_station) }
return nil unless res.is_a?(Array) && res[0]
item = res[0]
item = $data_ItemName[item] if item.is_a?(String)
return nil if item.nil?
tier = res[1]
tier = data_call(1) { LonaCraft::Tiers.tier_of(item).to_i } if tier.nil? && defined?(LonaCraft::Tiers)
tier = 1 if tier.nil? || tier.to_i < 1
[item, tier.to_i]
end
# Same rules as Game_Interpreter#lonacraft_process_run (30_Process.rb),
# without the map popups (this runs inside the crafting scene).
# inputs: what the open station takes (entry_inputs)
def self.process_craft(recipe, inputs = nil)
inputs ||= recipe[1]
# D2 god mode: no inputs taken, no stamina (process_affordable? asks Recipes.affordable?)
free = LonaCraft::Debug.free?
inputs = {} if free
return nil unless LonaCraft.process_affordable?(recipe)
return nil unless inputs.all?{|name, qty| have_count(name) >= qty.to_i }
fibre = fibre_key
picked = nil
inputs.each{|name, qty|
next if fibre.nil? || name != fibre
picked = LonaCraft.pick_fibre(qty)
return nil if picked.empty?
}
$game_player.actor.sta -= LonaCraft::PROCESS_STA_COST unless LonaCraft::Debug.god?
picked.each{|obj, amount| $game_party.lose_item(obj, amount) } if picked
inputs.each{|name, qty|
next if !fibre.nil? && name == fibre
obj = $data_ItemName[name]
$game_party.lose_item(obj, qty) if obj
}
out = nil
recipe[2].each{|name, qty|
obj = $data_ItemName[name]
next if obj.nil?
$game_party.gain_item(obj, qty)
out = obj if out.nil?
}
out ? [out, 1] : nil
end
end
#--------------------------------------------------------------------------
# Crash trace for the crafting windows (05_Config.rb LonaCraft.trace): each
# contents Bitmap.new (Window_Base#create_contents, also run by every list
# refresh) gets a line before and one after with its size and the game's
# failsafe flag (5100_LonaBitmapChanger_hugememmonkeyfix.rb).
#--------------------------------------------------------------------------
module CraftTraceContents
def create_contents
LonaCraft.trace{ "#{self.class} create_contents #{contents_width}x#{contents_height} begin" }
super
LonaCraft.trace_bitmap("#{self.class} contents", contents)
end
end
end
#==============================================================================
# Title bar above each pane (same size and place as Window_BoxTitle).
# kind :list -> "Recipes" + effective skill
# kind :info -> "Details" + level/exp + a clickable "Cancel"
#==============================================================================
class Window_LonaCraftTitle < Window_Base
include LonaCraft::CraftTraceContents
def initialize(x, kind)
@kind = kind
@cancel_rect = nil
super(x, 0, Graphics.width / 2, fitting_height(1))
refresh
end
def cancel_hit?
return false if @cancel_rect.nil?
Mouse.within?(@cancel_rect) ? true : false
end
def refresh
LonaCraft.trace{ "title #{@kind} refresh begin" }
ui = LonaCraft::CraftUI
contents.clear
LonaCraft.apply_ui_font(contents)
contents.font.size = Font.default_size
cw = contents.width
change_color(normal_color)
if @kind == :list
title = ui.station_name(LonaCraft.craft_station).to_s
title = ui.text("Head/Recipes").to_s if title.empty?
draw_text(0, 0, cw, line_height, title)
contents.font.size = 16
draw_text(0, 0, cw, line_height, "#{ui.text("Label/Skill")} #{ui.skill_effective}", 2)
else
draw_text(0, 0, cw, line_height, ui.text("Head/Details"))
contents.font.size = 16
draw_text(0, 0, cw, line_height, "#{ui.text("Label/Level")} #{ui.skill_level} #{ui.text("Label/Exp")} #{ui.skill_exp}", 1)
label = ui.text("Label/Cancel")
tw = text_size(label).width + 4
change_color(system_color)
draw_text(cw - tw, 0, tw, line_height, label, 2)
@cancel_rect = Rect.new(self.x + standard_padding + cw - tw, self.y + standard_padding, tw, line_height)
end
LonaCraft.trace{ "title #{@kind} refresh end" }
end
end
#==============================================================================
# Left pane: the recipe list. Header rows cannot be selected.
#==============================================================================
class Window_LonaCraftList < Window_Selectable
include LonaCraft::CraftTraceContents
# Hard cap on listed rows: the contents bitmap is rows x line_height high
# (create_contents), so a runaway recipe list can never ask RGSS for a
# giant Bitmap. Real lists are far below it (hand ~15, a bench ~150).
MAX_ROWS = 400
def initialize(x, y, width, height)
@rows = []
super(x, y, width, height)
refresh
end
def set_rows(rows)
@rows = rows || []
if @rows.size > MAX_ROWS
p "LonaCraft Craft: #{@rows.size} rows, only the first #{MAX_ROWS} are listed"
LonaCraft.trace{ "list #{@rows.size} rows cut to #{MAX_ROWS}" }
@rows = @rows[0, MAX_ROWS]
end
refresh
select_first
end
def item_max
@rows ? @rows.size : 0
end
def selectable?(i)
return false if i.nil? || i < 0
row = @rows[i]
!row.nil? && row[0] == :entry
end
def entry
return nil if @index.nil? || @index < 0
row = @rows[@index]
(row && row[0] == :entry) ? row[1] : nil
end
#--------------------------------------------------------------------------
# Cursor movement that skips header rows
#--------------------------------------------------------------------------
def next_selectable(from, step, wrap)
return nil if item_max < 1
i = from
item_max.times{
i += step
if i < 0 || i >= item_max
return nil unless wrap
i = i % item_max
end
return i if selectable?(i)
}
nil
end
def select_first
i = next_selectable(-1, 1, false)
i ? select(i) : unselect
end
def cursor_down(wrap = false)
i = next_selectable(@index, 1, wrap)
select(i) if i
end
def cursor_up(wrap = false)
i = next_selectable(@index, -1, wrap)
select(i) if i
end
def cursor_pagedown
LonaCraft.trace{ "page down from #{@index}" }
super
fix_selection(1)
end
def cursor_pageup
LonaCraft.trace{ "page up from #{@index}" }
super
fix_selection(-1)
end
def fix_selection(step)
return if @index < 0 || selectable?(@index)
i = next_selectable(@index, step, false)
i = next_selectable(@index, -step, false) if i.nil?
select(i) if i
end
# Keep a group's header in view when its first recipe is selected.
def ensure_cursor_visible
super
if @index > 0 && !selectable?(@index - 1) && row - 1 < top_row
self.top_row = row - 1
end
end
#--------------------------------------------------------------------------
# Drawing (sizes as Window_ItemList#draw_item: name 20, numbers 16)
#--------------------------------------------------------------------------
def refresh
LonaCraft.trace{ "list refresh begin #{@rows.size} rows" }
create_contents
LonaCraft.apply_ui_font(contents)
draw_all_items
if @rows.empty?
contents.font.outline = false
contents.font.size = 16
change_color(normal_color, false)
draw_text(4, 0, contents.width - 8, line_height, LonaCraft::CraftUI.text("Msg/NoRecipes"))
end
LonaCraft.trace("list refresh end")
end
def draw_item(index)
row = @rows[index]
return if row.nil?
LonaCraft.trace{ "list draw row #{index} #{row[0] == :header ? "header #{row[1]}" : row[1].output_name}" }
ui = LonaCraft::CraftUI
rect = item_rect(index)
contents.font.outline = false
if row[0] == :header
contents.font.size = 18
change_color(system_color)
draw_text(rect.x + 4, rect.y, rect.width - 8, rect.height, ui.group_label(row[1]))
contents.fill_rect(rect.x + 4, rect.y + rect.height - 2, rect.width - 8, 1, system_color)
return
end
entry = row[1]
obj = entry.output_item
return if obj.nil?
skill_ok = ui.skill_ok?(entry)
enabled = skill_ok && ui.affordable?(entry)
contents.font.size = 16
if skill_ok
label = "#{ui.text("Label/Skill")} #{entry.skill_req}"
else
label = "#{ui.text("Label/Locked")} #{entry.skill_req}"
end
right_w = text_size(label).width + 8
if skill_ok
change_color(normal_color, enabled)
else
change_color(knockout_color, false)
end
draw_text(rect.x, rect.y, rect.width - 4, rect.height, label, 2)
qty_text = entry.output_qty > 1 ? "x#{entry.output_qty}" : ""
qty_w = qty_text.empty? ? 0 : text_size(qty_text).width + 6
name_w = rect.width - 8 - 24 - right_w - qty_w
name_w = 24 if name_w < 24
unless qty_text.empty?
change_color(normal_color, enabled)
draw_text(rect.x + 8 + 24 + name_w, rect.y, qty_w, rect.height, qty_text)
end
contents.font.size = 20
draw_item_name(obj, rect.x + 8, rect.y, enabled, name_w)
end
end
#==============================================================================
# Right pane: details of the selected recipe.
#==============================================================================
class Window_LonaCraftDetail < Window_Base
include LonaCraft::CraftTraceContents
FLASH_FRAMES = 48
def initialize(x, y, width, height)
@entry = nil
@flash = 0
@flash_kind = nil
super(x, y, width, height)
refresh
end
def set_entry(entry)
@entry = entry
@flash = 0
@flash_kind = nil
refresh
end
# kind :materials or :skill. Blinks the short rows red for a moment.
def flash(kind)
@flash_kind = kind
@flash = FLASH_FRAMES
refresh
end
def update
super
if @flash > 0
@flash -= 1
refresh if @flash % 8 == 0
end
end
def flash_on?(kind)
@flash > 0 && @flash_kind == kind && (@flash / 8) % 2 == 1
end
def flash_color
Color.new(255, 40, 40, 90)
end
def refresh
LonaCraft.trace{ "detail refresh begin #{@entry ? @entry.output_name : "none"}#{@flash > 0 ? " flash #{@flash_kind} #{@flash}" : ""}" }
refresh_body
LonaCraft.trace("detail refresh end")
end
def refresh_body
contents.clear
LonaCraft.apply_ui_font(contents)
return if @entry.nil?
ui = LonaCraft::CraftUI
entry = @entry
obj = entry.output_item
return if obj.nil?
cw = contents.width
y = 0
# Output
contents.font.size = 20
draw_item_name(obj, 0, y, true, cw - 24)
if entry.output_qty > 1
contents.font.size = 16
change_color(normal_color)
draw_text(0, y, cw - 2, line_height, "x#{entry.output_qty}", 2)
end
y += line_height
# Materials
contents.font.size = 16
change_color(system_color)
draw_text(0, y, cw, 20, ui.text("Label/Materials"))
draw_text(0, y, cw - 2, 20, "#{ui.text("Label/Have")}/#{ui.text("Label/Need")}", 2)
note = ui.cost_note
unless note.nil?
head_w = text_size(ui.text("Label/Materials").to_s).width + 12
have_w = text_size("#{ui.text("Label/Have")}/#{ui.text("Label/Need")}").width + 12
contents.font.size = 14
change_color(normal_color, false)
draw_text(head_w, y, cw - head_w - have_w, 20, note, 1)
contents.font.size = 16
end
y += 20
missing = ui.missing(entry)
inputs = ui.entry_inputs(entry)
row_h = inputs.size > 4 ? 20 : 24
inputs.each{|name, qty|
have = ui.have_count(name)
short = missing.has_key?(name)
contents.fill_rect(0, y, cw, row_h, flash_color) if short && flash_on?(:materials)
icon, label = ui.input_icon_and_name(name)
draw_icon(icon, 4, y + (row_h - 24) / 2) if icon
contents.font.size = 16
change_color(normal_color)
draw_text(32, y, cw - 32 - 72, row_h, label)
change_color(short ? knockout_color : normal_color)
draw_text(0, y, cw - 2, row_h, "#{have}/#{qty}", 2)
y += row_h
}
# Skill
y += 4
eff = ui.skill_effective
skill_ok = entry.skill_req <= eff
contents.fill_rect(0, y, cw, line_height, flash_color) if !skill_ok && flash_on?(:skill)
contents.font.size = 16
change_color(system_color)
draw_text(0, y, cw, line_height, ui.text("Label/Skill"))
change_color(skill_ok ? normal_color : knockout_color)
skill_text = "#{ui.text("Label/Need")} #{entry.skill_req} #{ui.text("Label/You")} #{eff} (#{ui.text("Label/Level")} #{ui.skill_level})"
draw_text(0, y, cw - 2, line_height, skill_text, 2)
y += line_height
# Tier chances: a bar, tier names, percentages
change_color(system_color)
draw_text(0, y, cw, 20, ui.text("Label/TierChance"))
y += 20
chances = ui.tier_chances(entry)
total = 0.0
chances.each{|v| total += v if v > 0 }
total = 100.0 if total <= 0
bar_w = cw - 4
contents.fill_rect(2, y, bar_w, 8, gauge_back_color)
bx = 2
last = nil
chances.each_with_index{|v, i| last = i if v > 0 }
chances.each_with_index{|v, i|
next if v <= 0
w = i == last ? (2 + bar_w - bx) : (bar_w * v / total).round
contents.fill_rect(bx, y, w, 8, text_color(ui.tier_color(i + 1))) if w > 0
bx += w
}
y += 10
col_w = cw / 5
contents.font.size = 14
5.times{|i|
change_color(text_color(ui.tier_color(i + 1)), chances[i] > 0)
draw_text(i * col_w, y, col_w, 16, ui.tier_name(i + 1), 1)
}
y += 16
contents.font.size = 16
5.times{|i|
change_color(text_color(ui.tier_color(i + 1)), chances[i] > 0)
draw_text(i * col_w, y, col_w, 18, "#{chances[i].round}%", 1)
}
y += 20
# Gear: what Common gives
return unless obj.is_a?(RPG::EquipItem)
y += 2
stats = ui.base_stats(obj)
parts = []
parts << "#{ui.text("Label/Atk")} #{ui.signed_number(stats[0])}" if stats[0] != 0
parts << "#{ui.text("Label/Def")} #{ui.signed_number(stats[1])}" if stats[1] != 0
contents.font.size = 16
unless parts.empty?
change_color(normal_color)
draw_text(0, y, cw, 20, "#{ui.text("Label/GearCommon")} #{parts.join(" ")}")
y += 20
end
change_color(normal_color, false)
draw_text(0, y, cw, 20, ui.text("Label/GearScale"))
end
end
#==============================================================================
# Result popup in the middle of the screen. Closed by any confirm/cancel.
#==============================================================================
class Window_LonaCraftResult < Window_Base
include LonaCraft::CraftTraceContents
def initialize(item, tier, message = nil)
@item = item
@tier = tier
@message = message
w = Graphics.width / 2 + 64
h = fitting_height(@message ? 1 : 3)
super((Graphics.width - w) / 2, (Graphics.height - h) / 2, w, h)
self.z = 200
refresh
end
def refresh
ui = LonaCraft::CraftUI
contents.clear
LonaCraft.apply_ui_font(contents)
contents.font.size = 20
cw = contents.width
if @message || @item.nil?
change_color(normal_color)
draw_text(0, 0, cw, line_height, @message.to_s, 1)
return
end
change_color(system_color)
draw_text(0, 0, cw, line_height, ui.text("Label/Crafted"), 1)
name = $game_text[@item.name].to_s
tw = text_size(name).width
x = (cw - tw - 28) / 2
x = 0 if x < 0
draw_icon(@item.icon_index, x, line_height)
change_color(normal_color)
draw_text(x + 28, line_height, cw - x - 28, line_height, name)
change_color(text_color(ui.tier_color(@tier)))
draw_text(0, line_height * 2, cw, line_height, ui.tier_name(@tier), 1)
end
end
#==============================================================================
# Scene_LonaCraft
#==============================================================================
class Scene_LonaCraft < Scene_MenuBase
# Scene_ItemStorage defines this too (203_Storage Boxes.rb:489).
def hud
end
def start
LonaCraft.trace{ "scene start begin, #{LonaCraft.trace_mem(true)}" }
super
LonaCraft.trace_bitmap("scene background (snapshot)", @background_sprite ? @background_sprite.bitmap : nil, false)
LonaCraft.trace{ "graphics #{Graphics.width}x#{Graphics.height} rate #{Graphics.frame_rate} frame #{Graphics.frame_count}; font #{Font.default_name.inspect} size #{Font.default_size} bold #{Font.default_bold} outline #{Font.default_outline}" }
@saved_hud_hide = $hudForceHide
@saved_balloon_hide = $balloonForceHide
LonaCraft.trace("se openChest")
SndLib.openChest
create_windows
LonaCraft.trace("scene start end")
end
# The screen transition (Scene_Base#post_start -> perform_transition ->
# Graphics.transition(10), then Input.update). The owner's third silent
# crash (2026-10-07 07:59, RGSS301.dll+0x111a1c, access violation, the same
# offset as the two before) fell between "post_start begin" and "post_start
# end": inside the engine's 10-frame fade, the first time this screen is
# drawn. The fade is replaced by an instant cut (Graphics.transition(0),
# what Scene_Map does after a black screen): the windows are drawn once
# instead of blended ten times. TRANSITION_FRAMES = 10 brings the fade back.
TRANSITION_FRAMES = 0
def perform_transition
LonaCraft.trace{ "viewport guard: #{LonaCraft::ViewportGuard.stats}" } if defined?(LonaCraft::ViewportGuard)
LonaCraft.trace{ "transition #{TRANSITION_FRAMES} frames begin" }
Graphics.transition(TRANSITION_FRAMES)
LonaCraft.trace("transition end")
end
def post_start
LonaCraft.trace("post_start begin (transition, then Input.update)")
super
LonaCraft.trace("post_start end")
end
# Crash trace: makes a window (the block) with a line before and after.
def traced_window(label)
LonaCraft.trace{ "window #{label} new begin" }
win = yield
LonaCraft.trace{ "window #{label} #{win.class} x #{win.x} y #{win.y} w #{win.width} h #{win.height} contents #{win.contents.width}x#{win.contents.height} font #{win.contents.font.name.inspect} #{win.contents.font.size}" }
win
end
def create_windows
@list_title = traced_window("list_title"){ Window_LonaCraftTitle.new(0, :list) }
@info_title = traced_window("info_title"){ Window_LonaCraftTitle.new(Graphics.width / 2, :info) }
y = @list_title.height
@list_window = traced_window("list"){ Window_LonaCraftList.new(0, y, Graphics.width / 2, Graphics.height - y) }
@detail_window = traced_window("detail"){ Window_LonaCraftDetail.new(Graphics.width / 2, y, Graphics.width - Graphics.width / 2, Graphics.height - y) }
@result_window = nil
@shown_index = nil
rows = LonaCraft::CraftUI.build_rows
# Console breadcrumb (owner's hang report 2026-10-06): the rows were built.
p "LonaCraft Craft: #{LonaCraft.craft_station} #{rows.size} rows"
LonaCraft.trace{ "set_rows #{rows.size} begin" }
@list_window.set_rows(rows)
LonaCraft.trace{ "set_rows end, index #{@list_window.index}" }
@list_window.activate
sync_detail
end
def update
super
unless @first_frame_logged
@first_frame_logged = true
p "LonaCraft Craft: first frame"
LonaCraft.trace{ "first frame, #{LonaCraft.trace_mem}" }
end
if @result_window
update_result
return
end
sync_detail
acted = update_item_selection
return if acted || SceneManager.scene != self
mouse_input
sync_detail
end
def sync_detail
return if @shown_index == @list_window.index
LonaCraft.trace{ e = @list_window.entry; "index #{@shown_index.inspect} -> #{@list_window.index} #{e ? e.output_name : "none"}" }
@shown_index = @list_window.index
@detail_window.set_entry(@list_window.entry)
end
def refresh_all
LonaCraft.trace("refresh_all begin")
@list_window.refresh
@detail_window.refresh
@list_title.refresh
@info_title.refresh
LonaCraft.trace("refresh_all end")
end
#--------------------------------------------------------------------------
# Keyboard / gamepad (same keys as Scene_ItemStorage#update_item_selection)
#--------------------------------------------------------------------------
def update_item_selection
if Input.trigger?(:B) || WolfPad.trigger?(:X_LINK) || (Mouse.enable? && Input.trigger?(:MX_LINK))
LonaCraft.trace("input cancel (B, pad X or right click)")
exit_scene
return true
elsif Input.trigger?(:C) || WolfPad.trigger?(:Z_LINK)
LonaCraft.trace("input confirm (C or pad Z)")
try_craft
return true
end
false
end
def exit_scene
LonaCraft.trace{ "exit_scene se closeChest, goto #{LonaCraft.craft_back == :menu ? "Scene_Menu" : "Scene_Map"}" }
SndLib.closeChest
if LonaCraft.craft_back == :menu
SceneManager.goto(Scene_Menu)
else
SceneManager.goto(Scene_Map)
end
LonaCraft.trace("exit_scene goto done")
end
def try_craft
ui = LonaCraft::CraftUI
entry = @list_window.entry
LonaCraft.trace{ "craft attempt #{entry ? "#{entry.output_name} (#{entry.kind}, index #{@list_window.index})" : "with no recipe selected"}" }
return SndLib.sys_buzzer if entry.nil?
unless ui.skill_ok?(entry)
LonaCraft.trace("craft blocked: skill")
SndLib.sys_buzzer
@detail_window.flash(:skill)
return
end
unless ui.affordable?(entry)
LonaCraft.trace("craft blocked: materials")
SndLib.sys_buzzer
@detail_window.flash(:materials)
return
end
if entry.kind == :process_list && $game_player.actor.sta <= 0
LonaCraft.trace("craft blocked: stamina")
SndLib.sys_buzzer
open_result(nil, nil, ui.text("Msg/NoStamina"))
return
end
LonaCraft.trace("craft call begin")
result = ui.craft(entry)
LonaCraft.trace{ result ? "craft call end: #{result[0].name} tier #{result[1]}" : "craft call end: failed" }
refresh_all
if result.nil?
SndLib.sys_buzzer
open_result(nil, nil, ui.text("Msg/Failed"))
return
end
LonaCraft.trace("se WoodenBuild")
SndLib.WoodenBuild
open_result(result[0], result[1], nil)
end
#--------------------------------------------------------------------------
# Result popup
#--------------------------------------------------------------------------
def open_result(item, tier, message)
LonaCraft.trace{ "result popup open: #{item ? "#{item.name} tier #{tier}" : message.to_s}" }
@list_window.deactivate
@result_window = traced_window("result"){ Window_LonaCraftResult.new(item, tier, message) }
end
def update_result
close = Input.trigger?(:C) || Input.trigger?(:B) || WolfPad.trigger?(:Z_LINK) || WolfPad.trigger?(:X_LINK)
close = true if Mouse.enable? && (Input.trigger?(:MZ_LINK) || Input.trigger?(:MX_LINK))
return unless close
LonaCraft.trace("result popup close, dispose begin")
SndLib.play_cursor
@result_window.dispose
@result_window = nil
@list_window.activate
LonaCraft.trace("result popup disposed")
end
#--------------------------------------------------------------------------
# Mouse: hover selects a recipe, left click crafts it, right click leaves
# (handled with :B above), click on "Cancel" leaves. Row rectangles as in
# Scene_ItemStorage#mouse_input_result.
#--------------------------------------------------------------------------
def mouse_input
return Mouse.ForceIdle if Input.MouseWheelForceIdle?
return if !Mouse.enable?
if Input.trigger?(:MZ_LINK) && @info_title.cancel_hit?
LonaCraft.trace("mouse click on Cancel")
return exit_scene
end
return unless Mouse.within?(@list_window)
hit = list_index_under_mouse
if hit && hit != @list_window.index && @list_window.selectable?(hit)
LonaCraft.trace{ "hover select #{hit} (from #{@list_window.index}), se cursor" }
@list_window.select(hit)
SndLib.play_cursor
end
return unless Input.trigger?(:MZ_LINK)
LonaCraft.trace{ "mouse click row #{hit.inspect}" }
return SndLib.sys_buzzer if hit.nil? || !@list_window.selectable?(hit)
sync_detail
try_craft
end
def list_index_under_mouse
w = @list_window
top = w.y + w.standard_padding
bottom = w.y + w.height - w.padding_bottom
w.item_max.times{|i|
rect = w.item_rect(i)
rect.x += w.x + w.standard_padding - w.ox
rect.y += w.y + w.standard_padding - w.oy
if !w.viewport.nil?
rect.x += w.viewport.rect.x - w.viewport.ox
rect.y += w.viewport.rect.y - w.viewport.oy
end
next if rect.y + rect.height <= top || rect.y >= bottom
return i if Mouse.within?(rect)
}
nil
end
def terminate
LonaCraft.trace{ "scene terminate begin (freeze, dispose windows and background), #{LonaCraft.trace_mem(true)}" }
super
$hudForceHide = @saved_hud_hide
$balloonForceHide = @saved_balloon_hide
LonaCraft.trace{ "scene terminate end, next #{SceneManager.scene.class}" }
end
end
#==============================================================================
# Crash trace safety net (05_Config.rb LonaCraft.trace): an "alive" line
# with memory every TRACE_ALIVE_FRAMES frames while the screen runs, so a
# crash while idle still shows the screen was alive; a Ruby error raised in
# a frame is traced, then goes on to the game's error box as before.
#==============================================================================
class Scene_LonaCraft
TRACE_ALIVE_FRAMES = 300
unless method_defined?(:lonacraft_trace_update)
alias_method :lonacraft_trace_update, :update
end
def update
@lonacraft_trace_frames = (@lonacraft_trace_frames || 0) + 1
if @lonacraft_trace_frames % TRACE_ALIVE_FRAMES == 0
LonaCraft.trace{ "alive frame #{@lonacraft_trace_frames}, index #{@list_window ? @list_window.index : "?"}, #{LonaCraft.trace_mem}" }
end
lonacraft_trace_update
rescue Exception => e
LonaCraft.trace_error("Scene_LonaCraft#update frame #{@lonacraft_trace_frames}", e)
raise
end
end