<?xml version='1.0' encoding='utf-8'?>
<CheatTable CheatEngineTableVersion="45">
  <CheatEntries>
    <CheatEntry>
      <ID>1</ID>
      <Description>"[ATTACH / ALL OFF] OPGG.exe"</Description>
      <Color>00A5FF</Color>
      <VariableType>Auto Assembler Script</VariableType>
      <AssemblerScript>

{ Game   : ONE PIECE: Grand Gourmet / ONE PIECE 海のごちそうレストラン
  Author  : Black_wolf
  CheatVer:1.1.1-001-010

  Memo: ゲームバージョンは ver. 1.1.1
        ゲームエンジンは Unity IL2CPP
        GameAssembly.dll のPEタイムスタンプ: 0x6AE9E392（2026/11/03 13:37:22 UTC）
        Steam Build ID: 26406937

	なんか建物建てようとしたら一覧から建物なくなったりバグも多い
	すぐにバージョンアップ来そうだよね...
	
	ver. 1.0.5 から ver. 1.0.7に上がった
	あほほどあったバグは多少は直ったのかな

	診断機能をつけた。
}

[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.disableAll(memrec) end)
{$asm}
[DISABLE]
</AssemblerScript>
    </CheatEntry>
    <CheatEntry>
      <ID>2</ID>
      <Description>"0. Settings / README"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>3</ID>
          <Description>"Language"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>FFFF00</Color>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>4</ID>
              <Description>"English (default)"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.setLang('en') end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>5</ID>
              <Description>"Japanese / 日本語"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.setLang('ja') end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>6</ID>
          <Description>"README"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>FFFF00</Color>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>7</ID>
              <Description>"Target: ver. 1.1.1 / OPGG.exe x86 / Cheat Engine 7.5+"</Description>
              <Options moManualExpandCollapse="1" />
              <Color>FFFF00</Color>
              <GroupHeader>1</GroupHeader>
              <CheatEntries />
            </CheatEntry>
            <CheatEntry>
              <ID>8</ID>
              <Description>"Load a save, attach at the top, double-click values to edit; check value rows to freeze."</Description>
              <Options moManualExpandCollapse="1" />
              <Color>FFFF00</Color>
              <GroupHeader>1</GroupHeader>
              <CheatEntries />
            </CheatEntry>
            <CheatEntry>
              <ID>9</ID>
              <Description>"Editors: check, choose a name, edit the child value rows. Uncheck to clear."</Description>
              <Options moManualExpandCollapse="1" />
              <Color>FFFF00</Color>
              <GroupHeader>1</GroupHeader>
              <CheatEntries />
            </CheatEntry>
            <CheatEntry>
              <ID>10</ID>
              <Description>"Back up saves before editing. Unlocks and achievement requests are not undone by All OFF."</Description>
              <Options moManualExpandCollapse="1" />
              <Color>FFFF00</Color>
              <GroupHeader>1</GroupHeader>
              <CheatEntries />
            </CheatEntry>
            <CheatEntry>
              <ID>11</ID>
              <Description>"Game speed affects the entire game and animations. Disable resets to 1x."</Description>
              <Options moManualExpandCollapse="1" />
              <Color>FFFF00</Color>
              <GroupHeader>1</GroupHeader>
              <CheatEntries />
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>20</ID>
          <Description>"Diagnostics"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>FFFF00</Color>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>21</ID>
              <Description>"Lua Engine"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.openLuaEngine(true) end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>22</ID>
              <Description>"Signature self-test (all code features OFF)"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.scanSelfTest() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>23</ID>
              <Description>"Connection / current values"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.statusReport() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>25</ID>
              <Description>"Check versions / write access / copy result"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.checkCompatibility() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>100</ID>
      <Description>"01. Gameplay"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>101</ID>
          <Description>"Berry (check to freeze)"</Description>
          <VariableType>8 Bytes</VariableType>
          <Address>0</Address>
        </CheatEntry>
        <CheatEntry>
          <ID>102</ID>
          <Description>"Pirate coins (check to freeze)"</Description>
          <VariableType>4 Bytes</VariableType>
          <Address>0</Address>
        </CheatEntry>
        <CheatEntry>
          <ID>103</ID>
          <Description>"Hearts (check to freeze)"</Description>
          <VariableType>4 Bytes</VariableType>
          <Address>0</Address>
        </CheatEntry>
        <CheatEntry>
          <ID>104</ID>
          <Description>"Reputation - current sea"</Description>
          <VariableType>4 Bytes</VariableType>
          <Address>0</Address>
        </CheatEntry>
        <CheatEntry>
          <ID>105</ID>
          <Description>"Reputation EXP - current sea"</Description>
          <VariableType>4 Bytes</VariableType>
          <Address>0</Address>
        </CheatEntry>
        <CheatEntry>
          <ID>106</ID>
          <Description>"Hearts earned - current sea"</Description>
          <VariableType>4 Bytes</VariableType>
          <Address>0</Address>
        </CheatEntry>
        <CheatEntry>
          <ID>107</ID>
          <Description>"Force a banquet"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.forceBanquet() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>108</ID>
          <Description>"Hospitality / request dishes: always pass"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.feature('guestPass',true,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.feature('guestPass',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>602</ID>
          <Description>"Customers: full stamina"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.feature('customerStamina',true,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.feature('customerStamina',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>603</ID>
          <Description>"Characters: prevent sickness / injury"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.feature('health',true,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.feature('health',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>200</ID>
      <Description>"02. Player / characters"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>201</ID>
          <Description>"Player editor (newcomer)"</Description>
          <Color>FFFF00</Color>
          <Options moManualExpandCollapse="1" />
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.userRun(function() OPGG.player(memrec) end,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.clearChildren(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>202</ID>
          <Description>"Character editor (search)"</Description>
          <Color>FFFF00</Color>
          <Options moManualExpandCollapse="1" />
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.userRun(function() OPGG.characters(memrec) end,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.clearChildren(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>203</ID>
          <Description>"Customer editor (game list)"</Description>
          <Color>FFFF00</Color>
          <Options moManualExpandCollapse="1" />
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.userRun(function() OPGG.customers(memrec) end,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.clearChildren(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>204</ID>
          <Description>"All customers below LV30: LV29 (1 EXP to LV30)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.allCustomersLevel29() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>205</ID>
          <Description>"All customers below LV100: LV99 (1 EXP to LV100)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.allCustomersLevel99() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>206</ID>
          <Description>"Yagara Bull status editor"</Description>
          <Color>FFFF00</Color>
          <Options moManualExpandCollapse="1" />
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.userRun(function() OPGG.yagaraburuEditor(memrec) end,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.clearChildren(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>300</ID>
      <Description>"03. Items"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>301</ID>
          <Description>"Edit quantities / freeze (by category)"</Description>
          <Color>FFFF00</Color>
          <Options moManualExpandCollapse="1" />
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.userRun(function() OPGG.inventory(memrec) end,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.clearChildren(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>302</ID>
          <Description>"Add items (category / multiple items / quantity)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.addItem() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>400</ID>
      <Description>"04. Build"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>401</ID>
          <Description>"Build / cooking: no items required / no cost"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.feature('freeBuild',true,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.feature('freeBuild',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>402</ID>
          <Description>"Instant construction"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.feature('instantBuild',true,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.feature('instantBuild',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>403</ID>
          <Description>"Unconditional ship expansion"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.feature('ship',true,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.feature('ship',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>500</ID>
      <Description>"05. World"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>501</ID>
          <Description>"Freeze clock / date"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.feature('clock',true,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.feature('clock',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>502</ID>
          <Description>"Game speed (check: set / uncheck: 1x)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.userRun(function() OPGG.changeSpeed(memrec) end,memrec)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if OPGG then OPGG.feature('speed',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>503</ID>
          <Description>"Hour"</Description>
          <VariableType>4 Bytes</VariableType>
          <Address>0</Address>
        </CheatEntry>
        <CheatEntry>
          <ID>504</ID>
          <Description>"Clock frame"</Description>
          <VariableType>4 Bytes</VariableType>
          <Address>0</Address>
        </CheatEntry>
        <CheatEntry>
          <ID>505</ID>
          <Description>"Year / day counter"</Description>
          <VariableType>4 Bytes</VariableType>
          <Address>0</Address>
        </CheatEntry>
        <CheatEntry>
          <ID>506</ID>
          <Description>"Month / period counter"</Description>
          <VariableType>4 Bytes</VariableType>
          <Address>0</Address>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>600</ID>
      <Description>"06. Other"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>601</ID>
          <Description>"Unlock ALL Steam achievements"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
OPGG.oneShot(memrec,function() OPGG.achievements(true) end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
  </CheatEntries>
  <UserdefinedSymbols />
  <LuaScript>-- Restore an earlier instance before replacing its state.
if OPGG then
  if OPGG.timer then OPGG.timer.Enabled=false end
  -- Older versions may retain wrappers for records deleted by loadTable.
  -- Compare against current records without dereferencing the stale wrapper.
  if OPGG.rows then
    local al=getAddressList()
    for id,row in pairs(OPGG.rows) do
      local current=al.getMemoryRecordByID(id)
      if not current or current~=row.mr then OPGG.rows[id]=nil end
    end
  end
  if OPGG.stop then
    local ok,e=pcall(OPGG.stop,OPGG.alive and OPGG.alive())
    if not ok then error(e) end
  end
end
local OPGG={}
--[[ =====================================================================================
  GameTemplate.CT  -  Cheat Engine table common framework  (namespace: OPGG)
  Target : Cheat Engine 7.5+ (64-bit)
  Layout : [ATTACH / ALL OFF]  -&gt;  0. Settings &amp; README  -&gt;  1..N game categories
  Colors : expandable group = 0xFFFF00 (cyan, BGR) / script = 0x00A5FF (orange, BGR) / value row = none
  IDs    : 1 = ATTACH, 2 = "0." top group, 3..99 = inside "0.", category N uses N*100 .. N*100+99
  How to adapt to a new game: edit only the blocks marked  [GAME]  (search for "[GAME]").
  Rename the namespace OPGG -&gt; e.g. HV / DQM4 by a whole-word replace of "OPGG" and "gt" symbol prefix if wanted.
===================================================================================== ]]
OPGG = OPGG or {}
local OPGG = OPGG

----------------------------------------------------------------- [GAME] basic settings
OPGG.TAG      = 'OPGG'              -- log prefix: [OPGG] ...
OPGG.TITLE    = 'Game Template'   -- game title (for messages)
OPGG.EXE      = 'Game.exe'        -- process name
OPGG.MODULE   = 'Game.exe'        -- module that holds the game code (Unity IL2CPP: GameAssembly.dll / UE: *-Win64-Shipping.exe)
OPGG.GAMEVER  = '1.0.0'           -- game version this table was made for
OPGG.BUILD    = nil               -- {ts=0x6AB5FE0B, size=0x6637000}: PE timestamp + module size of that build (nil = no check)
OPGG.TICK_MS  = 500               -- background timer interval (ms)
OPGG.lang     = OPGG.lang or 'en'   -- default language: 'en' / 'ja'

----------------------------------------------------------------- common constants (do not change)
OPGG.C_GROUP  = 0xFFFF00          -- cyan   (BGR): expandable groups
OPGG.C_SCRIPT = 0x00A5FF          -- orange (BGR): scripts
OPGG.ID_ATTACH = 1
OPGG.ID_TOP0   = 2
-- shared memory page (allocated near OPGG.MODULE at attach, registered as CE symbols)
--   gtFlags +000..0FF : feature flag bytes (hook code reads [gtFlags+n])
--   gtVars  +100..1FF : parameters (value rows / hook code)
--   gtPtrs  +200..3FF : pointer slots, 8 bytes each (pointer value rows "[gtPtrs+n]+offset")


----------------------------------------------------------------- [GAME] AOB signatures
-- name = { p='AOB pattern', off=offset of the hook site from the match start, len=bytes overwritten by the hook (&gt;=5),
--          mod='module' (optional, default OPGG.MODULE) }
-- The resolved address is registered as CE symbol  gtA_&lt;name&gt;  (use it in hook scripts and value rows).


----------------------------------------------------------------- [GAME] hooks
-- Full Auto Assembler script with [ENABLE] and [DISABLE].
-- Placeholders: $SITE = gtA_&lt;sig&gt; symbol, $ORIG = "db .." of the original bytes (read before patching), $NOP = padding nops.


----------------------------------------------------------------- [GAME] parameter defaults (gtVars)


----------------------------------------------------------------- [GAME] features
-- key = { hooks={'hookName',...}, flag=n (byte gtFlags+n), task=function() (timer, while on),
--         on=function(), off=function() }


----------------------------------------------------------------- [GAME] pointer slots (gtPtrs), refreshed by the timer
-- slot index -&gt; function returning an address (or nil). Value rows use "[gtPtrs+slot*8]+offset".


----------------------------------------------------------------- [GAME] called once per attach (after init)


----------------------------------------------------------------- [GAME] record names (ID -&gt; {en, ja})
-- OPGG.NAMES is generated together with the record tree (see the end of this script).

--=====================================================================================
--  COMMON PART  (no change needed per game)
--=====================================================================================
      -- resolved signature addresses
   -- unresolved signatures


OPGG.dyn    = OPGG.dyn or {}    -- dynamic records {mr,en,ja}
OPGG.suffix = OPGG.suffix or {} -- record ID -&gt; text appended to its name

----------------------------------------------------------------- helpers

local function ri(a) if not a or a==0 then return nil end local v=readInteger(a) if v and v&gt;=0x80000000 then v=v-0x100000000 end return v end


function OPGG.T(en,ja) if OPGG.lang=='ja' then return ja or en end return en end
function OPGG.msg(en,ja) print('['..OPGG.TAG..'] '..OPGG.T(en,ja)) end
function OPGG.err(en,ja) error(OPGG.T(en,ja),0) end
local function hex(n) return string.format('%X',n) end

function OPGG.mod(name) return getAddressSafe(name or OPGG.MODULE) end
function OPGG.modSize(name) local ok,s=pcall(getModuleSize,name or OPGG.MODULE) return ok and s or nil end





----------------------------------------------------------------- one-shot / user action
-- Run user actions; log failures without opening a dialog.

function OPGG.oneShot(mr, fn)
  OPGG.userRun(fn,mr)
  local t=createTimer(nil,false) t.Interval=150
  t.OnTimer=function(tt) tt.destroy() pcall(function() mr.Active=false end) end
  t.Enabled=true
end

-- Modal editor actions must run after the AA record has finished activating.
OPGG.uiActions={};OPGG.uiActionBusy=false
function OPGG.deferEditorAction(mr,fn)
  local id=mr.ID
  if OPGG.uiActions[id] then return end
  local session,pid=OPGG.session,OPGG.pid;local attempts=0;local running=false
  local timer=createTimer(nil,false);timer.Interval=50
  OPGG.uiActions[id]=timer
  local function finish(t)
    t.Enabled=false;if OPGG.uiActions[id]==t then OPGG.uiActions[id]=nil end;t.destroy()
  end
  local callbackRunning=false
  local function perform(t)
    if running then return end
    local current=getAddressList().getMemoryRecordByID(id)
    if _G[OPGG.TAG]~=OPGG or not current or current~=mr or session~=OPGG.session or pid~=OPGG.pid then finish(t);return end
    attempts=attempts+1
    local ok,processing=pcall(function()return current.AsyncProcessing end)
    if ok and processing then
      if attempts&gt;=200 then finish(t);OPGG.noteOnce('editor-busy:'..id,OPGG.T('Editor activation is still processing; no change was made.','エディタの有効化処理が終わらないため変更しませんでした。'))end
      return
    end
    current.Active=false
    if current.Active then
      if attempts&gt;=200 then finish(t);OPGG.noteOnce('editor-off:'..id,OPGG.T('Editor activation did not finish; no change was made.','エディタの有効化処理が終わらないため変更しませんでした。'))end
      return
    end
    t.Enabled=false
    if OPGG.uiActionBusy then finish(t); OPGG.noteOnce('editor-dialog-busy',OPGG.T('Close the current editor dialog first.','開いているエディタの入力画面を先に閉じてください。'));return end
    if OPGG.recordStatus[id]==false then finish(t);OPGG.noteOnce('editor-unavailable:'..id,OPGG.T('This editor is unavailable.','このエディタは使用できません。'));return end
    -- Keep the callback owner alive throughout the modal message loop.
    running=true;OPGG.uiActionBusy=true
    local success,e=pcall(OPGG.userRun,fn)
    OPGG.uiActionBusy=false;running=false
    finish(t)
    if _G[OPGG.TAG]==OPGG then pcall(OPGG.updateLevelDisplays) end
    if not success then OPGG.noteOnce('editor-action:'..id,e) end
  end
  timer.OnTimer=function(t)
    if callbackRunning then return end
    callbackRunning=true
    local ok,e=pcall(perform,t)
    callbackRunning=false
    if not ok then
      -- Failures before the action starts must release its pending slot too.
      pcall(function()t.Enabled=false end)
      if OPGG.uiActions[id]==t then OPGG.uiActions[id]=nil end
      if running then OPGG.uiActionBusy=false;running=false end
      pcall(function()t.destroy()end)
      OPGG.noteOnce('editor-callback:'..id,e)
    end
  end
  timer.Enabled=true
end

----------------------------------------------------------------- attach / init


-- attach CE to the game; returns true when the opened process changed

-- state of an old process: drop it without touching the new one

function OPGG.checkBuild()
  if not OPGG.BUILD then return true end
  local m=OPGG.mod(); local lf=ri(m+0x3C); local ts=lf and readInteger(m+lf+8)
  local sz=OPGG.modSize()
  if ts~=OPGG.BUILD.ts or (OPGG.BUILD.size and sz~=OPGG.BUILD.size) then
    OPGG.msg(('WARNING: different game build (timestamp %s, size %s). Made for v%s. Features whose code is not found are disabled.'):format(hex(ts or 0),hex(sz or 0),OPGG.GAMEVER),
           ('警告: 対応ビルドと異なります（タイムスタンプ %s、サイズ %s）。対応バージョンは v%s です。コードが見つからない機能は無効になります。'):format(hex(ts or 0),hex(sz or 0),OPGG.GAMEVER))
    return false
  end
  return true
end


----------------------------------------------------------------- AOB resolver (synchronous aobscanregion)







----------------------------------------------------------------- hook manager



----------------------------------------------------------------- features


----------------------------------------------------------------- timer (pointer slots, tasks, process watch)



----------------------------------------------------------------- ATTACH / ALL OFF


----------------------------------------------------------------- UI helpers

function OPGG.askInt(title, prompt, def, lo, hi)
  local s=inputQuery(title, prompt, tostring(def or 0)); if not s then return nil end
  local v=tonumber(s)
  if not v or v%1~=0 or (lo and v&lt;lo) or (hi and v&gt;hi) then OPGG.err('Invalid number: '..s,'不正な数値です: '..s) end
  return v
end
-- dynamic records (lists built at run time)

function OPGG.addHdr(parent, en, ja)
  local m=getAddressList().createMemoryRecord()
  m.IsGroupHeader=true m.Description=OPGG.T(en,ja) m.Color=OPGG.C_GROUP m.appendToEntry(parent) m.DontSave=true
  OPGG.dyn[#OPGG.dyn+1]={mr=m,id=m.ID,en=en,ja=ja} return m
end
function OPGG.addRec(parent, en, ja, addr, vt)
  local m=getAddressList().createMemoryRecord()
  m.Description=OPGG.T(en,ja) m.Type=vt or vtDword m.Address=addr m.appendToEntry(parent) m.DontSave=true
  OPGG.dyn[#OPGG.dyn+1]={mr=m,id=m.ID,en=en,ja=ja} return m
end

----------------------------------------------------------------- language
function OPGG.applyLang()
  local al=getAddressList()
  for i=0,al.Count-1 do
    local m=al.getMemoryRecord(i); local n=OPGG.NAMES[m.ID]
    if n then local d=(OPGG.lang=='ja') and n[2] or n[1]
      if OPGG.suffix[m.ID] then d=d..' : '..OPGG.suffix[m.ID] end
      m.Description=d end
  end
  local keep={}
  for _,e in ipairs(OPGG.dyn) do
    local mr=e.id and al.getMemoryRecordByID(e.id)
    if mr and mr==e.mr then mr.Description=OPGG.T(e.en,e.ja);keep[#keep+1]=e end
  end
  OPGG.dyn=keep
end


----------------------------------------------------------------- diagnostics
-- Lua Engine window: record ID 13 is a toggle (check = open / uncheck = close)
function OPGG.luaEngine() local ok,f=pcall(getLuaEngine) if ok then return f end end
function OPGG.openLuaEngine(quiet)
  local f=OPGG.luaEngine()
  if f then pcall(function() f.show() end) pcall(function() f.bringToFront() end) end
  if not quiet then OPGG.msg('Lua Engine opened. Messages of this table are printed here.','Lua Engineを開きました。このテーブルのメッセージはここに表示されます。') end
end





----------------------------------------------------------------- [GAME] actions (examples)

   -- {id, en, ja}



----------------------------------------------------------------- initial layout: only "0." expanded
function OPGG.initCollapse()
  local al=getAddressList()
  for i=0,al.Count-1 do
    local m=al.getMemoryRecord(i)
    if m.Count&gt;0 then
      local opt='' pcall(function() opt=tostring(m.Options) end)
      if not opt:find('moHideChildren') then
        local inZero=false local p=m
        while p do if p.ID==OPGG.ID_TOP0 then inZero=true break end p=p.Parent end
        pcall(function() m.Collapsed = not inZero end)
      end
    end
  end
end





OPGG.NAMES={[1]={'[ATTACH / ALL OFF] OPGG.exe','【アタッチ／一括解除】OPGG.exe'},[2]={'0. Settings / README','0. 設定・説明'},[3]={'Language','言語設定'},[4]={'English (default)','English（既定）'},[5]={'Japanese / 日本語','日本語 / Japanese'},[6]={'README','はじめに'},[7]={'Target: ver. 1.1.1 / OPGG.exe x86 / Cheat Engine 7.5+','対象: ver. 1.1.1 / OPGG.exe x86 / Cheat Engine 7.5以降'},[8]={'Load a save, attach at the top, double-click values to edit; check value rows to freeze.','セーブをロードし先頭から接続。値をダブルクリックで変更、値行のチェックで固定。'},[9]={'Editors: check, choose a name, edit the child value rows. Uncheck to clear.','エディタ: チェック→名前を選択→子の値を編集。解除で一覧を削除。'},[10]={'Back up saves before editing. Unlocks and achievement requests are not undone by All OFF.','編集前にセーブをバックアップ。一括解除では変更値・解放済み実績は元に戻りません。'},[11]={'Game speed affects the entire game and animations. Disable resets to 1x.','ゲーム速度はゲーム全体とアニメーションに適用。解除で1倍に戻ります。'},[20]={'Diagnostics','診断'},[21]={'Lua Engine','Lua Engine'},[22]={'Signature self-test (all code features OFF)','シグネチャ検査（コード機能を全解除して実行）'},[23]={'Connection / current values','接続情報・現在値'},[25]={'Check versions / write access / copy result','バージョン・書込確認／結果コピー'},[100]={'01. Gameplay','01. 便利機能'},[101]={'Berry (check to freeze)','ベリー（チェックで固定）'},[102]={'Pirate coins (check to freeze)','コイン（チェックで固定）'},[103]={'Hearts (check to freeze)','ハート（チェックで固定）'},[104]={'Reputation - current sea','評判・現在の海'},[105]={'Reputation EXP - current sea','評判経験値・現在の海'},[106]={'Hearts earned - current sea','獲得ハート・現在の海'},[107]={'Force a banquet','強制的に宴を開始'},[108]={'Hospitality / request dishes: always pass','おもてなし・要望料理：必ず合格'},[602]={'Customers: full stamina','お客様の体力を維持'},[603]={'Characters: prevent sickness / injury','キャラクターの病気・負傷を解消し続ける'},[200]={'02. Player / characters','02. プレイヤー'},[201]={'Player editor (newcomer)','プレイヤーエディタ（新人）'},[202]={'Character editor (search)','キャラクターエディタ（検索）'},[203]={'Customer editor (game list)','お客様エディタ（ゲーム内一覧）'},[204]={'All customers below LV30: LV29 (1 EXP to LV30)','全お客様LV29（LV30以上は除外／残り経験値1）'},[205]={'All customers below LV100: LV99 (1 EXP to LV100)','全お客様LV99（LV100以上は除外／残り経験値1）'},[206]={'Yagara Bull status editor','ヤガラブルのステータスエディタ'},[300]={'03. Items','03. アイテム'},[301]={'Edit quantities / freeze (by category)','個数変更・固定（カテゴリ別）'},[302]={'Add items (category / multiple items / quantity)','アイテム追加（カテゴリ・複数品目・個数）'},[400]={'04. Build','04. ビルド'},[401]={'Build / cooking: no items required / no cost','建築・料理：アイテム必要なし・費用なし'},[402]={'Instant construction','即ビルド'},[403]={'Unconditional ship expansion','船の無条件拡張'},[500]={'05. World','05. ワールド'},[501]={'Freeze clock / date','時刻・日付を固定'},[502]={'Game speed (check: set / uncheck: 1x)','ゲーム速度（チェックで倍率設定／解除で1倍）'},[503]={'Hour','時刻'},[504]={'Clock frame','時計フレーム'},[505]={'Year / day counter','年・日カウンター'},[506]={'Month / period counter','月・期間カウンター'},[600]={'06. Other','06. その他'},[601]={'Unlock ALL Steam achievements','Steam実績全解除'}}
OPGG.PATCHDEF={['chipCost']={['pattern']='55 8B EC 80 3D ?? ?? ?? ?? 00 53 56 8B 75 08 57 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 04 C6 05 ?? ?? ?? ?? 01 8B 46 08 85 C0 74 ?? 8B 80 B4 00 00 00 85 C0 74 ?? 83 78 0C 00 76 ?? 8B 58 10',['offset']=0,['patch']='31 C0 C3'},['archCost']={['pattern']='55 8B EC 80 3D ?? ?? ?? ?? 00 53 56 8B 75 08 57 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 04 C6 05 ?? ?? ?? ?? 01 8B 46 08 85 C0 74 ?? 8B 40 5C 85 C0 74 ?? 83 78 0C 00 76 ?? 8B 58 10 8B 46 08',['offset']=0,['patch']='31 C0 C3'},['empty']={['pattern']='55 8B EC 8B 4D 08 8B 41 08 85 C0 74 ?? 80 B8 A8 00 00 00 00 75 ?? 32 C0 5D C3 83 79 0C 00 0F 9E C0 5D C3 E9 ?? ?? ?? ?? CC CC CC CC CC CC CC CC 55 8B EC 80 3D ?? ?? ?? ?? 00 8B 45 08 56',['offset']=0,['patch']='31 C0 C3'},['construct']={['pattern']='55 8B EC 80 3D ?? ?? ?? ?? 00 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 04 C6 05 ?? ?? ?? ?? 01 56 8B 75 08 57 6A 00 6A 0E 8B 7E 14 E8 ?? ?? ?? ?? 8B C8 83 C4 08 85 C9 74 ?? 8D 47 01 99',['offset']=0,['patch']='8B 44 24 04 C7 40 08 03 00 00 00 C3'},['TouchEvent_Build_4']={['pattern']='?? 83 78 0C 00 7E ?? 6A 00 6A FF 50 E8 ?? ?? ?? ?? 83 C4 0C 47 8B C7 E9 ?? ?? ?? ?? 83 7E 0C 00 0F 84 ?? ?? ?? ?? 83 7E 0C 01 8B 83 B8 00 00 00 89 45 F8 74 ?? 85 C0 0F 84 ?? ?? ?? ?? 6A 00',['offset']=12,['patch']='90 90 90 90 90'},['_buildArchitecture_5']={['pattern']='C0 0F 84 ?? ?? ?? ?? 6A 00 6A FF 50 E8 ?? ?? ?? ?? FF 35 ?? ?? ?? ?? E8 ?? ?? ?? ?? 8B F0 6A 00 56 E8 ?? ?? ?? ?? 83 C4 18 8B 83 80 01 00 00 85 C0 0F 84 ?? ?? ?? ?? 85 F6 0F 84 ?? ?? ?? ??',['offset']=12,['patch']='90 90 90 90 90'},['archStock']={['pattern']='00 85 C0 0F 84 ?? ?? ?? ?? 39 78 ?? 0F 84 ?? ?? ?? ?? 57 50 E8 ?? ?? ?? ?? 8B 4B 50 83 C4 08 8B F8 89 7D E8 85 C9 0F 84 ?? ?? ?? ?? 6A 00 51 E8 ?? ?? ?? ?? 8B F0 8B CA 8B C7 83 C4 08 99 3B CA',['offset']=12,['patch']='90 90 90 90 90 90'},['clock']={['pattern']='55 8B EC 51 53 57 8B 7D 08 33 DB 53 57 E8 ?? ?? ?? ?? 8B 4F 68 83 C4 08 89 45 FC 85 C9 0F 84 ?? ?? ?? ?? 8B 49 10 85 C9 0F 84 ?? ?? ?? ?? 83 79 0C 06 0F 86 ?? ?? ?? ?? FF 41 28 8B 47 68 85 C0',['offset']=0,['patch']='31 C0 C3'},['AppType']={['pattern']='68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ??',['offset']=0,['patch']='',['cellOffset']=1},['TrophyType']={['pattern']='80 3D ?? ?? ?? ?? 00 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 08 C6 05 ?? ?? ?? ?? 01 A1 ?? ?? ?? ?? 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? A1 ?? ?? ?? ?? 83 C4 04 8B 40 5C 80 78 6B 00 74 ?? 8B 0D ?? ?? ?? ?? 83 79 74 00 75 ?? 51 E8 ?? ?? ?? ?? 8B 0D ?? ?? ?? ?? 83 C4 04 8B 41 5C 80 78 19 00 74 ?? 83 79 74 00 75 ?? 51 E8 ?? ?? ?? ?? 8B 0D ?? ?? ?? ??',['offset']=0,['patch']='',['cellOffset']=20},['TrophyUnlock']={['pattern']='55 8B EC 51 80 3D ?? ?? ?? ?? 00 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 10 C6 05 ?? ?? ?? ?? 01 A1 ?? ?? ?? ?? C6 45 FF 00 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? 83 C4 04 56 6A 00 E8 ?? ?? ?? ??',['offset']=0,['patch']=''},['cookConsume']={['pattern']='83 C4 0C 85 C0 0F 84 ?? ?? ?? ?? 6A 00 6A FF 50 E8 ?? ?? ?? ?? 8B 47 08 46 83 C4 0C 8B CE 85 C0 0F 84 ?? ?? ?? ?? EB ?? 8B 47 08 85 C0 0F 84 ?? ?? ?? ?? 8B 40 50 85 C0 0F 84 ?? ?? ?? ??',['offset']=16,['patch']='90 90 90 90 90'},['cookSeasoningConsume']={['pattern']='85 C9 74 ?? 8B 89 BC 18 00 00 6A 00 F7 D9 51 50 E8 ?? ?? ?? ?? 83 C4 0C FF 35 ?? ?? ?? ?? 8B 5F 08 8B 77 0C E8 ?? ?? ?? ?? 6A 00 6A 00 6A 00 56 8B F8 6A 00 57 E8 ?? ?? ?? ?? 83 C4 1C 85 DB',['offset']=16,['patch']='90 90 90 90 90'},['cookAvailable']={['pattern']='55 8B EC 8B 45 0C 85 C0 74 ?? 80 78 0C 00 74 ?? 83 78 10 00 7F ?? 8B 48 08 85 C9 74 ?? 80 79 60 00 74 ?? 8B 40 08 85 C0 74 ?? 80 78 4C 00 0F 94 C0 5D C3 32 C0 5D C3 E9 ?? ?? ?? ?? CC CC CC CC',['offset']=16,['patch']='EB 11 90 90 90 90'},['cookSeasoningAvailable']={['pattern']='85 C9 74 ?? 80 79 4C 00 74 ?? 80 78 0C 00 74 ?? 83 78 10 00 0F 9F C0 5D C3 32 C0 5D C3 E9 ?? ?? ?? ?? CC 55 8B EC 56 8B 75 0C 85 F6 74 ?? 80 7E 24 00 75 ?? 8B 46 1C 85 C0 74 ?? 6A 00 6A 02 50',['offset']=16,['patch']='B0 01 90 90 90 90 90'},['cookGrayStock']={['pattern']='08 85 C0 74 ?? 80 78 ?? 00 BE 01 00 00 00 75 ?? 83 7D F4 00 0F B6 DB 0F 44 DE 8B 97 D8 18 00 00 85 D2 74 ?? 8B 8F DC 18 00 00 3B 4A 0C 0F B6 C3 0F 4E C6 5F 5E 5B 8B E5 5D C3 E8 ?? ?? ?? ??',['offset']=16,['patch']='90 90 90 90 90 90 90 90 90 90'},['cookSelectStock']={['pattern']='C0 0F 84 ?? ?? ?? ?? 3B 78 0C 0F 83 ?? ?? ?? ?? 83 7C B8 10 00 7E ?? 8B 86 D8 18 00 00 85 C0 0F 84 ?? ?? ?? ?? FF 35 ?? ?? ?? ?? 52 50 E8 ?? ?? ?? ?? 6A 00 56 E8 ?? ?? ?? ?? 6A 00 56',['offset']=16,['patch']='90 90 90 90 90 90 90'},['speedScheduler']={['pattern']='F3 0F 5A C0 F2 0F 2C C0 3B F0 0F 4C F0 89 75 E8 8D 75 08 C7 45 98 00 00 00 00 89 75 9C 8B 45 08 57 C6 45 FC 07 89 78 14 8B 45 08 83 C0 14 50 E8 ?? ?? ?? ?? 83 C4 08 33 C9 89 4D E0 3B 4D E8 0F 8D ?? ?? ?? ?? 85 C9 74 ?? 8B 45 08 C6 80 A0 00 00 00 01 6A 00 E8 ?? ?? ?? ?? 83 C4 04 85 C0',['offset']=16,['patch']=''},['DataType']={['pattern']='A1 ?? ?? ?? ?? 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? A1 ?? ?? ?? ?? 83 C4 04 8B 40 5C 8B 00 85 C0 74 ?? 8B 80 9C 00 00 00 C3 E9 ?? ?? ?? ?? CC CC CC CC CC 80 3D ?? ?? ?? ?? 00 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 04 C6 05 ?? ?? ?? ?? 01 A1 ?? ?? ?? ?? 83 78 74 00 75 ?? 50',['offset']=0,['patch']='',['cellOffset']=1},['AddRealizedDream']={['pattern']='55 8B EC 80 3D ?? ?? ?? ?? 00 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 08 C6 05 ?? ?? ?? ?? 01 6A 00 FF 75 10 FF 75 0C FF 75 08 E8 ?? ?? ?? ?? 83 C4 10 84 C0 75 ?? 56 FF 35 ?? ?? ?? ?? E8 ?? ?? ?? ?? 8B F0 6A 00 56 E8 ?? ?? ?? ?? 83 C4 0C 85 F6 74 ?? 6A 00',['offset']=0,['patch']=''},['RealizeDream']={['pattern']='55 8B EC 83 EC 0C 80 3D ?? ?? ?? ?? 00 0F 85 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 3C C6 05 ?? ?? ?? ?? 01 53 56 FF 35 ?? ?? ?? ?? E8 ?? ?? ?? ??',['offset']=0,['patch']=''},['CharacterAddItem']={['pattern']='55 8B EC 6A FF 68 ?? ?? ?? ?? 64 A1 00 00 00 00 50 64 89 25 00 00 00 00 83 EC 58 80 3D ?? ?? ?? ?? 00 53 56 57 89 65 F0 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 18 C6 05 ?? ?? ?? ?? 01 8B 75 08 0F 57 C0 0F 11 45 BC 0F 11 45 AC 85 F6 0F 84 ?? ?? ?? ?? 8B 46 48 85 C0 0F 84 ?? ?? ?? ?? FF 35 ?? ?? ?? ?? FF 75 0C 50 E8 ?? ?? ?? ?? A1 ?? ?? ?? ?? 83 C4 0C C6 45 EF 00 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? A1 ?? ?? ?? ?? 83 C4 04 8B 40 5C 8B 40 0C 85 C0 0F 84 ?? ?? ?? ?? 8B 80 D8 00 00 00 85 C0 0F 84 ?? ?? ?? ?? FF 35 ?? ?? ?? ?? 50 8D 45 CC 50 E8 ?? ?? ?? ?? 8D 7D BC C7 45 DC 00 00 00 00 83 C4 0C 89 7D E0 0F 10 00 0F 11 45 BC C7 45 FC 00 00 00 00 C6 45 FC 01 66 90 FF 35 ?? ?? ?? ?? 8D 45 BC 50 E8 ?? ?? ?? ?? 83 C4 08 84 C0 0F 84 ?? ?? ?? ?? 8B 45 C8 85 C0 0F 84 ?? ?? ?? ?? 8B 4E 08 8B 50 0C 85 C9 0F 84 ?? ?? ?? ?? 3B 51 08 0F 84 ?? ?? ?? ?? 8B 80 D0 00 00 00 85 C0 0F 84 ?? ?? ?? ?? FF 35 ?? ?? ?? ?? 50 8D 45 9C 50 E8 ?? ?? ?? ?? 8D 75 AC C7 45 D4 00 00 00 00 83 C4 0C 89 75 D8 0F 10 00 0F 11 45 AC C6 45 FC 03 FF 35 ?? ?? ?? ?? 8D 45 AC 50 E8 ?? ?? ?? ?? 83 C4 08 84 C0 74 ?? 8B 45 B8 85 C0 0F 84 ?? ?? ?? ?? 8B 4D 08 8B 50 0C 8B 49 08 85 C9 0F 84 ?? ?? ?? ?? 3B 51 08 75 ?? 6A 00 FF 75 0C 50 E8 ?? ?? ?? ?? 83 C4 0C C6 45 EF 01 C6 45 FC 01 FF 35 ?? ?? ?? ?? 56 E8 ?? ?? ?? ?? 83 C4 08 EB ?? C6 45 FC 01 FF 35 ?? ?? ?? ?? 56 E8 ?? ?? ?? ?? 83 C4 08 C6 45 FC 01 EB ?? 8B 45 E8 8B 00 89 45 D4 B8 ?? ?? ?? ?? C3 C7 45 FC 01 00 00 00 FF 35 ?? ?? ?? ?? FF 75 D8 E8 ?? ?? ?? ?? 8B 45 D4 83 C4 08 85 C0 75 ?? 8B 7D E0 80 7D EF 00 8B 75 08 0F 84 ?? ?? ?? ?? EB ?? 6A 00 FF 75 0C 50 E8 ?? ?? ?? ?? 83 C4 0C C7 45 FC FF FF FF FF FF 35 ?? ?? ?? ?? 57 E8 ?? ?? ?? ?? 83 C4 08 8B 4D F4 5F 5E 64 89 0D 00 00 00 00 5B 8B E5 5D C3 8B 45 E4 8B 00 89 45 DC B8 ?? ?? ?? ?? C3 C7 45 FC FF FF FF FF FF 35 ?? ?? ?? ?? FF 75 E0 E8 ?? ?? ?? ?? 8B 45 DC 83 C4 08 85 C0 74 ?? 50 E8 ?? ?? ?? ?? E8 ?? ?? ?? ?? 50 E8 ?? ?? ?? ?? CC CC 55 8B EC 8B 45 08 8B 48 08 85 C9 74 ??',['offset']=0,['patch']=''},['CharacterSetItem']={['pattern']='55 8B EC 51 80 3D ?? ?? ?? ?? 00 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 1C C6 05 ?? ?? ?? ?? 01 53 56 FF 35 ?? ?? ?? ?? E8 ?? ?? ?? ?? 8B D8 6A 00 53 E8 ?? ?? ?? ?? 83 C4 0C 85 DB 0F 84 ?? ?? ?? ?? 8B 4D 0C 8D 43 08 51 50 89 4B 08 E8 ?? ?? ?? ?? 8B 45 10 50 89 43 0C 8D 43 0C 50 E8 ?? ?? ?? ?? 8B 75 08 8D 43 10 56 50 89 73 10 E8 ?? ?? ?? ?? 8B 43 08',['offset']=0,['patch']=''},['TreasureAddHaveNum']={['pattern']='55 8B EC 80 3D ?? ?? ?? ?? 00 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 04 C6 05 ?? ?? ?? ?? 01 53 56 8B 75 08 57 8B 7D 0C 85 FF 7E ?? 85 F6 74 ?? 80 7E 0C 00 75 ?? C6 46 0C 01 8B 46 10 89 45 0C 8B 46 08 85 C0 74 ?? 80 B8 8C 00 00 00 00 BB E7 03 00 00 A1 ?? ?? ?? ?? B9 01 00 00 00 0F 45 D9 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? 83 C4 04 8B 45 0C 6A 00 53 03 C7 6A 00 50 E8 ?? ?? ?? ??',['offset']=0,['patch']=''},['ShipExpansionFind']={['pattern']='55 8B EC 80 3D ?? ?? ?? ?? 00 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 04 C6 05 ?? ?? ?? ?? 01 56 8B 75 08 80 7E 0C 00 75 ?? C6 46 0C 01 A1 ?? ?? ?? ?? 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? A1 ?? ?? ?? ?? 83 C4 04 8B 40 5C 8B 40 0C 85 C0 74 ?? 6A 00 50 E8 ?? ?? ?? ?? 83 C4 08 85 C0 74 ??',['offset']=0,['patch']=''},['ShipRequestFind']={['pattern']='55 8B EC 80 3D ?? ?? ?? ?? 00 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 10 C6 05 ?? ?? ?? ?? 01 56 8B 75 08 80 7E 0C 00 0F 85 ?? ?? ?? ?? A1 ?? ?? ?? ?? 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? A1 ?? ?? ?? ?? 83 C4 04 8B 40 5C 8B 40 0C 85 C0 0F 84 ?? ?? ?? ?? 6A 00 50 E8 ?? ?? ?? ?? 83 C4 08 84 C0',['offset']=0,['patch']=''},['FeverStart']={['pattern']='8B 47 50 8B 40 68 8B 40 10 C7 80 C0 00 00 00 09 00 00 00 8B 47 50 85 C0 0F 84 ?? ?? ?? ?? 8B 40 68 85 C0 0F 84 ?? ?? ?? ?? 8B 40 10 85 C0 0F 84 ?? ?? ?? ?? 83 78 0C 2D 0F 86 ?? ?? ?? ?? C7 80 C4 00 00 00 00 00 00 00 8B 47 50 85 C0 0F 84 ?? ?? ?? ?? 8B 40 68 85 C0 0F 84 ?? ?? ?? ?? 8B 40 10 89 45 E8 8B 47 50 8B 40 68 8B 40 10 85 C0 0F 84 ?? ?? ?? ?? 83 78 0C 2E 0F 86 ?? ?? ?? ?? 8B 0D ?? ?? ?? ?? 8B B0 C8 00 00 00 46 83 79 74 00 75 ?? 51 E8 ?? ?? ?? ?? 83 C4 04 6A 00 68 E7 03 00 00 56 E8 ?? ?? ?? ?? 8B C8 83 C4 0C 8B 45 E8 83 78 0C 2E 0F 86 ?? ?? ?? ?? 89 88 C8 00 00 00 FF 35 ?? ?? ?? ?? E8 ?? ?? ?? ?? 8B F0 6A 00 56 E8 ?? ?? ?? ?? 6A 00 56 57 E8 ?? ?? ?? ?? 83 C4 18',['offset']=0,['patch']=''},['inviteJudge']={['pattern']='8B 45 14 83 FF 4B 50 0F 9D C1 89 7B 04 88 4B 08 8D 4B 0C 51 89 43 0C E8 ?? ?? ?? ?? 83 C4 10 8B C3 5F 5E 5B 8B E5 5D C3',['offset']=7,['patch']='B1 01 90'},['invitePass']={['pattern']='56 8B 75 08 80 7E 14 00 8B 46 1C 75 ?? 85 C0 0F 84 ?? ?? ?? ?? 8B 40 08 85 C0 0F 84 ?? ?? ?? ?? 6A 00 50 E8 ?? ?? ?? ?? 83 C4 08 5E 8B E5 5D C3 85 C0 0F 84 ?? ?? ?? ?? 8B 40 08 85 C0 0F 84 ?? ?? ?? ?? 6A 00 50 E8 ?? ?? ?? ??',['offset']=11,['patch']='EB'},['YagaraFeed']={['pattern']='55 8B EC 83 EC 10 80 3D ?? ?? ?? ?? 00 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 14 C6 05 ?? ?? ?? ?? 01 53 8B 5D 08 8B 4B 18 85 C9 0F 84 ?? ?? ?? ?? 8B 43 1C 3B 41 0C',['offset']=0,['patch']=''},['atelierInstant']={['pattern']='8B 40 3C 85 C0 0F 84 ?? ?? ?? ?? 83 78 0C 00 0F 86 ?? ?? ?? ?? 8B 40 10 39 47 14 0F 8C ?? ?? ?? ?? 8B 47 10 48 C7 47 14 00 00 00 00 89 47 10 85 C0 0F 8F ?? ?? ?? ?? 66 C7 47 0C 01 00',['offset']=24,['patch']='C7 47 10 01 00 00 00 90 90'},['atelierGate']={['pattern']='6A 00 50 E8 ?? ?? ?? ?? 83 C4 08 84 C0 0F 84 ?? ?? ?? ?? 83 7F 10 00 0F 8E ?? ?? ?? ?? FF 47 14 6A 00 E8 ?? ?? ?? ?? 83 C4 04 85 C0 0F 84 ?? ?? ?? ?? 8B 40 08 85 C0 0F 84 ?? ?? ?? ?? 8B 40 3C 85 C0 0F 84 ?? ?? ?? ?? 83 78 0C 00 0F 86 ?? ?? ?? ?? 8B 40 10 39 47 14 0F 8C ?? ?? ?? ??',['offset']=13,['patch']='90 90 90 90 90 90'},['AtelierFrame']={['pattern']='55 8B EC 6A FF 68 ?? ?? ?? ?? 64 A1 00 00 00 00 50 64 89 25 00 00 00 00 83 EC 28 80 3D ?? ?? ?? ?? 00 53 56 57 89 65 F0 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 14 C6 05 ?? ?? ?? ?? 01 A1 ?? ?? ?? ?? 0F 57 C0 0F 11 45 CC 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? A1 ?? ?? ?? ?? 83 C4 04 8B 40 5C 8B 40 0C 85 C0 0F 84 ?? ?? ?? ?? 8B 80 30 01 00 00 85 C0 0F 84 ?? ?? ?? ?? FF 35 ?? ?? ?? ?? 50 8D 45 DC 50 E8 ?? ?? ?? ?? 8D 75 CC 83 C4 0C 0F 10 00',['offset']=0,['patch']=''},['AppTypeGet']={['pattern']='80 3D ?? ?? ?? ?? 00 75 ?? 68 ?? ?? ?? ?? E8 ?? ?? ?? ?? 83 C4 04 C6 05 ?? ?? ?? ?? 01 8B 0D ?? ?? ?? ?? 83 79 74 00 75 ?? 51 E8 ?? ?? ?? ?? 8B 0D ?? ?? ?? ?? 83 C4 04 8B 41 5C 83 38 00 75 ?? 56 51 E8 ?? ?? ?? ?? 8B F0 6A 00 56 E8 ?? ?? ?? ?? A1 ?? ?? ?? ?? 83 C4 0C 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? A1 ?? ?? ?? ?? 83 C4 04 8B 40 5C 56 89 30 A1 ?? ?? ?? ?? FF 70 5C E8 ?? ?? ?? ??',['offset']=0,['patch']='',['cellOffset']=10},['CharacterExpRule']={['pattern']='55 8B EC 8B 4D 08 8B 41 ?? 85 C0 74 ?? 83 78 ?? 00 74 ?? 83 78 ?? ?? 74 ?? 8B 41 ?? 85 C0 74 ?? 8B 40 ?? 5D C3 B8 ?? ?? ?? ?? 5D C3 8B 41 ?? 85 C0 74 ?? 8B 40 ?? 5D C3 E9 ?? ?? ?? ??',['offset']=0,['patch']=''},['deliveryPass']={['pattern']='55 8B EC 56 8B 75 08 8B 8E ?? ?? ?? ?? 85 C9 74 ?? FF 71 14 0F B6 86 ?? ?? ?? ?? 50 FF 71 20 8B 41 0C FF D0 83 C4 0C 6A 00 56 E8 ?? ?? ?? ?? 83 C4 08 5E 5D C3',['offset']=20,['patch']='B8 01 00 00 00 90 90'},['deliveryFilter']={['pattern']='55 8B EC 8B 45 08 8B 40 08 85 C0 74 ?? 8B 48 08 8B 45 0C 85 C0 74 ?? 6A 00 51 50 E8 ?? ?? ?? ?? 83 C4 0C 85 C0 0F 9F C0 5D C3',['offset']=37,['patch']='B0 01 90'},['deliveryLevel']={['pattern']='55 8B EC 56 8B 75 08 8B 46 08 85 C0 74 ?? 8B 4D 0C 85 C9 74 ?? 6A 00 FF 70 08 51 E8 ?? ?? ?? ?? 8B 4E 08 83 C4 0C 5E 85 C9 74 ?? 8B 49 08 85 C9 74 ?? 3B 41 74 0F 9D C0 5D C3',['offset']=53,['patch']='B0 01 90'},['deliveryUIRecipe']={['pattern']='8B 7D 08 80 7D EF 00 0F 94 C0 88 87 ?? ?? ?? ?? FF 35 ?? ?? ?? ?? 8B BF ?? ?? ?? ??',['offset']=7,['patch']='30 C0 90'},['deliveryUICount']={['pattern']='8B 7D 08 3B 41 70 7D ?? C6 87 ?? ?? ?? ?? 01 A1 ?? ?? ?? ?? 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? 83 C4 04',['offset']=3,['patch']='83 F8 01'},['deliveryExecCount']={['pattern']='83 78 10 0B 75 ?? 8B 83 ?? ?? ?? ?? 85 C0 0F 84 ?? ?? ?? ?? 8B 4E 08 8B 40 0C 3B 41 70 0F 8C ?? ?? ?? ?? A1 ?? ?? ?? ?? 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? 83 C4 04 6A 00 6A 15 E8 ?? ?? ?? ?? 83 C4 08',['offset']=26,['patch']='83 F8 01'},['deliveryExecMenu']={['pattern']='6A 00 6A 15 E8 ?? ?? ?? ?? 83 C4 08 84 C0 75 ?? A1 ?? ?? ?? ?? 83 78 74 00 75 ?? 50 E8 ?? ?? ?? ?? 83 C4 04 6A 00 53 6A 2E E8 ?? ?? ?? ?? 83 C4 0C',['offset']=12,['patch']='0C 01'}}
OPGG.FREEPATCHES={'chipCost','archCost','empty','TouchEvent_Build_4','_buildArchitecture_5','archStock','cookConsume','cookSeasoningConsume','cookAvailable','cookSeasoningAvailable','cookGrayStock','cookSelectStock'}
OPGG.BUILD={ts=1793713042,size=38080512}
-- GameTemplate common framework is retained above. Game-specific overrides:
-- Property uses ordinary int/long arrays in this build, NOT XProperty.
-- No heap addresses or module RVAs are persisted. Reflection + unique AOBs.
OPGG.TAG='OPGG'; OPGG.TITLE='ONE PIECE: Grand Gourmet'; OPGG.EXE='OPGG.exe'
OPGG.MODULE='GameAssembly.dll'; OPGG.GAMEVER='1.1.1'; OPGG.CHEATVER='1.1.1-001-010'
OPGG.rows={}; OPGG.patches={}; OPGG.on={}
OPGG.cache={}; OPGG.offsets={}; OPGG.listCache={}; OPGG.session=0; OPGG.lang='en'
local function ptr(a) return a and a&gt;65536 and readInteger(a) or nil end
local function valid(a) return a and a&gt;65536 and readBytes(a,1)~=nil end
local function hex(a) return string.format('%X',a or 0) end
function OPGG.fail(en,ja) error(OPGG.T(en,ja),2) end
function OPGG.str(p)
  if not valid(p) then return '' end
  local n=readInteger(p+8); if not n or n&lt;0 or n&gt;8192 then return '' end
  return readString(p+12,n*2,true) or ''
end







function OPGG.list(field) return OPGG.listIndex(field).objects end
function OPGG.app()
  if OPGG.pid~=getOpenedProcessID() then OPGG.fail('Attach first.','先にアタッチしてください。') end
  local p=ptr(OPGG.static)
  if not p or ptr(p)~=OPGG.appClass then OPGG.fail('AppData instance unavailable.','AppDataが未検出です。') end
  return p
end
function OPGG.saveAddr(kind,index)
  if type(index)=='string' then index=OPGG.saveConstant(index) end
  local sv=OPGG.obj(OPGG.app(),'save_'); local a=OPGG.obj(sv,kind)
  local n=a and readInteger(a+12)
  if not n or index&lt;0 or index&gt;=n then OPGG.fail('Save array unavailable.','セーブ配列未検出です。') end
  return OPGG.arrayElement(a,index,kind=='lngs' and 10 or 8)
end
function OPGG.dataId(p)
  local d=OPGG.obj(p,'data_'); return d and readInteger(OPGG.field(d,'id_'))
end
function OPGG.find(field,id)
  local index=OPGG.listIndex(field)
  if index.duplicates and index.duplicates[id] then OPGG.fail('Duplicate data ID: '..tostring(id),'データIDが重複しています：'..tostring(id)) end
  local p=index.byId[id]
  if valid(p) then return p end
  OPGG.fail('ID not found: '..tostring(id),'ID未検出: '..tostring(id))
end
function OPGG.currentDeparture()
  local id=readInteger(OPGG.saveAddr('ints','SAVEI_CURRENT_DEPARTURE')); return OPGG.find('departureList_',id)
end
function OPGG.point(id) if type(id)=='string' then id=OPGG.metadataConstant('data.PointData.ID',id) end;return OPGG.field(OPGG.find('pointList_',id),'value_') end
function OPGG.nativeName(p)
  local d=OPGG.obj(p,'data_'); if not d then return '' end
  for _,f in ipairs({'&lt;name_&gt;k__BackingField','&lt;itemName_&gt;k__BackingField'}) do
    local ok,a=pcall(OPGG.field,d,f); if ok then local s=OPGG.str(ptr(a)); if s~='' then return s end end
  end
  return 'ID '..tostring(OPGG.dataId(p))
end
function OPGG.label(p)
  local en,ja=OPGG.namePair(p)
  return OPGG.T(en,ja)..' [ID '..tostring(OPGG.dataId(p))..']'
end
function OPGG.namePair(p)
  local n=OPGG.nativeName(p)
  return n,n
end
-- Same single-choice search -&gt; native CT rows interaction as the reference table.
-- Stable selection keys prevent refreshed row positions from selecting another guest.
function OPGG.pick(title,names,multiple,refresh)
  -- Snapshot once per opening. Never replace rows while the picker is open.
  local keys={};if refresh then names,keys=refresh() end
  local form=createForm(false);form.Name='OPGG_Picker';form.Caption=title;form.Position='poScreenCenter'
  form.BorderStyle='bsSizeable';form.ClientWidth=840;form.ClientHeight=620
  form.Color=0x252525;form.Font.Name='Yu Gothic UI';form.Font.Size=10;form.Font.Color=0xF0F0F0
  pcall(function()form.Constraints.MinWidth=620;form.Constraints.MinHeight=380 end)
  local hint=createLabel(form);hint.Caption=multiple and OPGG.T('Search by name / ID — Ctrl / Shift: select multiple','名前・IDで検索 — Ctrl・Shiftで複数選択') or OPGG.T('Search by name / ID','名前・IDで検索');hint.Font.Color=0xCFCFCF
  local search=createEdit(form);search.Name='OPGG_PickerSearch';search.Color=0x353535;search.Font.Color=0xFFFFFF;search.Text=''
  local clear=createButton(form);clear.Caption=OPGG.T('Clear filters','検索解除')
  local list=createListView(form);list.Name='OPGG_PickerList';list.ViewStyle='vsReport';list.ReadOnly=true;list.RowSelect=true;list.HideSelection=false
  list.MultiSelect=multiple or false;list.Color=0x252525;list.Font.Color=0xFFFFFF;list.ShowColumnHeaders=true
  local number=list.Columns.add();number.Caption='#';number.Width=70
  local nameColumn=list.Columns.add();nameColumn.Caption=OPGG.T('Name / ID','名前・ID');nameColumn.Width=720
  list.OnCustomDrawItem=function(sender,item)
    sender.Canvas.Font.Color=0xFFFFFF;sender.Canvas.Brush.Color=item.Selected and 0x805020 or 0x252525;return true
  end
  local status=createLabel(form);status.Font.Color=0xCFCFCF
  local selectAll=createButton(form);selectAll.Caption=OPGG.T('Select all shown','表示分を全選択');selectAll.Visible=multiple or false
  local clearSelection=createButton(form);clearSelection.Caption=OPGG.T('Clear selection','選択解除');clearSelection.Visible=multiple or false
  local cancel=createButton(form);cancel.Name='OPGG_PickerCancel';cancel.Caption=OPGG.T('Cancel','キャンセル');cancel.Cancel=true
  local accept=createButton(form);accept.Name='OPGG_PickerAccept';accept.Caption=OPGG.T('Select','選択');accept.Default=true
  local view,chosen={},{};local selected,selectedKey;local updating=false;local sortColumn=0;local ascending=true
  local function updateStatus()
    local n=0;for _ in pairs(chosen) do n=n+1 end
    status.Caption=OPGG.T('Shown: ','表示：')..#view..' / '..#names..(multiple and (OPGG.T('   Selected: ','   選択：')..n) or '')
  end
  local function capture()
    if multiple then for row,index in ipairs(view) do chosen[index]=list.Items[row-1].Selected or nil end end
  end
  local function fill()
    capture();local old=view[(list.ItemIndex or -1)+1];local query=search.Text:lower();local nextView={}
    for i,name in ipairs(names) do if query=='' or name:lower():find(query,1,true) then nextView[#nextView+1]=i end end
    if sortColumn==1 then table.sort(nextView,function(a,b)if names[a]==names[b] then return a&lt;b end;if ascending then return names[a]&lt;names[b] else return names[a]&gt;names[b] end end)
    elseif not ascending then table.sort(nextView,function(a,b)return a&gt;b end) end
    updating=true;list.Items.beginUpdate()
    local ok,e=pcall(function()
      list.Items.clear();view=nextView
      for row,index in ipairs(view) do local item=list.Items.add();item.Caption=tostring(index);item.SubItems.add(names[index]);if multiple then item.Selected=chosen[index] or false end end
      if not multiple then
        list.ItemIndex=-1;for row,index in ipairs(view) do if index==old then list.ItemIndex=row-1;break end end
        if list.ItemIndex&lt;0 and #view&gt;0 then list.ItemIndex=0 end
      end
    end)
    list.Items.endUpdate();updating=false;if not ok then error(e) end;updateStatus()
  end
  search.OnChange=function()if not updating then fill()end end
  clear.OnClick=function()search.Text=''end
  list.OnColumnClick=function(_,column)capture();if sortColumn==column.Index then ascending=not ascending else sortColumn=column.Index;ascending=true end;fill()end
  list.OnSelectItem=function()if not updating then capture();updateStatus()end end
  selectAll.OnClick=function()
    updating=true;for row,index in ipairs(view) do chosen[index]=true;list.Items[row-1].Selected=true end;updating=false;updateStatus()
  end
  clearSelection.OnClick=function()
    chosen={};updating=true;for row=0,list.Items.Count-1 do list.Items[row].Selected=false end;updating=false;updateStatus()
  end
  accept.OnClick=function()
    if multiple then
      capture();local indices={};for i=1,#names do if chosen[i] then indices[#indices+1]=i end end
      if #indices&gt;0 then selected=indices;form.ModalResult=1 end
    else
      local i=view[(list.ItemIndex or -1)+1];if i then selected=i;selectedKey=keys[i];form.ModalResult=1 end
    end
  end
  list.OnDblClick=accept.OnClick;cancel.OnClick=function()form.ModalResult=2 end
  local function layout()
    local width,height=form.ClientWidth,form.ClientHeight
    hint.Left=12;hint.Top=10;hint.Width=width-24;hint.Height=24
    search.Left=12;search.Top=38;search.Width=width-150;search.Height=28
    clear.Left=width-128;clear.Top=36;clear.Width=116;clear.Height=30
    list.Left=12;list.Top=76;list.Width=width-24;list.Height=height-168;nameColumn.Width=math.max(260,list.Width-number.Width-28)
    status.Left=12;status.Top=height-82;status.Width=width-24;status.Height=22
    selectAll.Left=12;selectAll.Top=height-48;selectAll.Width=150;selectAll.Height=32
    clearSelection.Left=170;clearSelection.Top=height-48;clearSelection.Width=130;clearSelection.Height=32
    cancel.Left=width-260;cancel.Top=height-48;cancel.Width=120;cancel.Height=32
    accept.Left=width-132;accept.Top=height-48;accept.Width=120;accept.Height=32
  end
  form.OnResize=layout
  local ok,e=pcall(function()layout();fill();form.showModal()end)
  form.destroy();if not ok then error(e)end
  return selected,selectedKey
end


function OPGG.row(parent,en,ja,fn,typ)
  local m=OPGG.addRec(parent,en,ja,'0',typ or vtDword)
  OPGG.bind(m,fn,en,ja); return m
end
function OPGG.clearChildren(mr)
  while mr.Count&gt;0 do
    local m=mr.Child[0];OPGG.clearChildren(m);OPGG.rows[m.ID]=nil;if OPGG.yagaraFeedDisplays then OPGG.yagaraFeedDisplays[m.ID]=nil end;if OPGG.detailDisplays then OPGG.detailDisplays[m.ID]=nil end;if OPGG.levelDisplays then OPGG.levelDisplays[m.ID]=nil end
    for i=#OPGG.dyn,1,-1 do if OPGG.dyn[i].mr==m then table.remove(OPGG.dyn,i) end end
    if OPGG.contextOwners then for _,token in ipairs(OPGG.contextOwners[m.ID] or {})do OPGG.editorContexts[token]=nil end;OPGG.contextOwners[m.ID]=nil end
    m.Active=false;m.destroy()
  end
end
function OPGG.require() OPGG.app(); return true end
function OPGG.attachGame()
  local pid=getProcessIDFromProcessName(OPGG.EXE)
  if not pid or pid==0 then OPGG.fail('OPGG.exe is not running.','OPGG.exeが起動していません。') end
  local changed=pid~=getOpenedProcessID(); if changed then openProcess(pid) end
  return changed
end

function OPGG.bindCore()
  for id,def in pairs(OPGG.CORE) do
    local mr=getAddressList().getMemoryRecordByID(id)
    if mr then OPGG.bind(mr,def) end
  end
end
function OPGG.restore(key)
  local states=OPGG.patches[key]; if not states then return end
  if OPGG.pid==getOpenedProcessID() then
    local ok,e=OPGG.withPaused(function()
      for i=#states,1,-1 do local st=states[i]
        local got=readBytes(st.address,#st.new,true)
        for j,v in ipairs(st.new) do if not got or got[j]~=v then OPGG.fail('Patched code changed externally: '..key,'他の変更を検出しました: '..key) end end
      end
      for i=#states,1,-1 do local st=states[i]
        if not writeBytes(st.address,st.old) then OPGG.fail('Code restoration failed.','コード復元失敗。') end
      end
    end)
    if not ok then error(e) end
  end
  OPGG.patches[key]=nil
end

function OPGG.patchFeature(key,keys)
  local states={}
  -- Resolve and validate the complete transaction before writing.
  for _,name in ipairs(keys) do
    local a=OPGG.scan(name); local bytes={}
    for v in OPGG.PATCHDEF[name].patch:gmatch('%x%x') do bytes[#bytes+1]=tonumber(v,16) end
    local current=readBytes(a,#bytes,true);local resolved=OPGG.sigCache[name]
    for i=1,#bytes do if not current or current[i]~=resolved.original[i] then OPGG.fail('Code changed: '..name,'コードの変更を検出：'..name) end end
    states[#states+1]={address=a,old=current,new=bytes}
  end
  OPGG.patches[key]={}
  local ok,err=OPGG.withPaused(function()
    for _,st in ipairs(states) do
      local current=readBytes(st.address,#st.old,true)
      for i,b in ipairs(st.old) do if not current or current[i]~=b then error('Code changed during resolution') end end
    end
    for _,st in ipairs(states) do
      if not writeBytes(st.address,st.new) then
        for _,done in ipairs(OPGG.patches[key]) do writeBytes(done.address,done.old) end
        OPGG.patches[key]={};OPGG.fail('Patch write failed.','パッチ書き込み失敗。')
      end
      OPGG.patches[key][#OPGG.patches[key]+1]=st
    end
  end)
  if not ok then pcall(OPGG.restore,key); error(err) end
end
-- Scale the engine's own form-update loop; no OS timer hooks or native calls.
function OPGG.speedAssembly(page,site)
  return string.format([[
define(opggSpeedData,%X)
define(opggSpeedCode,%X)
define(opggSpeedReturn,%X)
label(opggSpeedBucketReady)
label(opggSpeedCountReady)
opggSpeedCode:
pushfd
pushad
mov ecx,edi
shr ecx,4
and ecx,FF
lea ecx,[opggSpeedData+ecx*8+40]
cmp [ecx],edi
je opggSpeedBucketReady
mov [ecx],edi
mov dword ptr [ecx+4],0
opggSpeedBucketReady:
mov eax,[ebp-18]
add [opggSpeedData+4],eax
imul eax,[opggSpeedData]
add eax,[ecx+4]
xor edx,edx
mov ebx,#1000
div ebx
mov [ecx+4],edx
mov [ebp-18],eax
add [opggSpeedData+8],eax
test eax,eax
jne opggSpeedCountReady
mov dword ptr [edi+1C],3
mov dword ptr [ebp-2C],1
opggSpeedCountReady:
popad
popfd
lea esi,[ebp+8]
mov dword ptr [ebp-68],0
jmp opggSpeedReturn
]],page,page+4096,site+10)
end
function OPGG.enableGameSpeed()
  local factor=math.floor((OPGG.speedValue or 1)*1000+0.5)
  if OPGG.patches.speed then
    if not writeInteger(OPGG.speedPage,factor) then OPGG.fail('Speed update failed.','速度設定に失敗しました。') end
    return
  end
  local site=OPGG.scan('speedScheduler')
  if not OPGG.speedPage then
    OPGG.speedPage=allocateMemory(8192)
    if not OPGG.speedPage or OPGG.speedPage==0 then OPGG.fail('Speed memory allocation failed.','速度制御領域を確保できません。') end
  end
  if not writeInteger(OPGG.speedPage,factor) then OPGG.fail('Speed update failed.','速度設定に失敗しました。') end
  local ok,e=autoAssemble(OPGG.speedAssembly(OPGG.speedPage,site))
  if not ok then OPGG.fail('Speed code assembly failed: '..tostring(e),'速度制御コードの組み立てに失敗しました：'..tostring(e)) end
  local displacement=(OPGG.speedPage+4096-site-5)%4294967296
  local bytes={0xE9}
  for i=1,4 do bytes[#bytes+1]=displacement%256;displacement=math.floor(displacement/256) end
  while #bytes&lt;10 do bytes[#bytes+1]=0x90 end
  local encoded={};for i,v in ipairs(bytes) do encoded[i]=string.format('%02X',v) end
  OPGG.PATCHDEF.speedScheduler.patch=table.concat(encoded,' ')
  OPGG.patchFeature('speed',{'speedScheduler'})
end
-- The code page is retained until process exit so an in-flight update can return safely.

function OPGG.featureImpl(key,on)
  if key=='ship' then OPGG.setShipExpansion(on);return end
  if not on then
    local wasOn=OPGG.on[key]; OPGG.on[key]=nil
    if key=='instantBuild' and OPGG.job and OPGG.job.kind=='atelier' then OPGG.cancelAchievementJob(true) end
    OPGG.restore(key)

    return
  end
  if key~='freeBuild' and key~='instantBuild' and key~='guestPass' and key~='clock' and key~='speed' then OPGG.require() end
  if key=='freeBuild' then OPGG.patchFeature(key,OPGG.selectedKeys[key])
  elseif key=='guestPass' then OPGG.patchFeature(key,OPGG.selectedKeys[key])
  elseif key=='instantBuild' then OPGG.patchFeature(key,OPGG.selectedKeys[key])
  elseif key=='clock' then OPGG.patchFeature(key,{'clock'})
  elseif key=='speed' then OPGG.enableGameSpeed() end
  OPGG.on[key]=true
end


-- Resolve a live record by ID before touching any CE object properties.
-- Lua wrappers can outlive the native records after a table reload.
function OPGG.rowRecord(id,row)
  local mr=getAddressList().getMemoryRecordByID(id)
  if mr and row and mr==row.mr then return mr end
end
function OPGG.disarmRows()
  for id,row in pairs(OPGG.rows) do
    local mr=OPGG.rowRecord(id,row)
    if mr then mr.Active=false;mr.Address='0' else OPGG.rows[id]=nil end
  end
end
function OPGG.stop(restore)
  OPGG.shipMode=nil
  OPGG.clearShipPermit(restore and OPGG.alive())
  OPGG.dreamQueue={}
  local hadSpeed=OPGG.on.speed; OPGG.on={}
  OPGG.cancelAchievementJob(restore and OPGG.alive())
  OPGG.disarmRows()
  if restore then local keys={}; for k in pairs(OPGG.patches) do keys[#keys+1]=k end; for _,k in ipairs(keys) do OPGG.restore(k) end
  else OPGG.patches={} end

  for _,id in ipairs({108,401,402,403,501,502,602,603}) do local m=getAddressList().getMemoryRecordByID(id); if m then m.Active=false end end
end
function OPGG.alive()
  return OPGG.pid and OPGG.pid==getOpenedProcessID() and OPGG.pid==getProcessIDFromProcessName(OPGG.EXE) and getAddressSafe(OPGG.MODULE)~=nil
end

OPGG.CORE={
 [101]=function() return OPGG.saveAddr('lngs','SAVEL_MONEY') end,
 [102]=function() return OPGG.point('PIRATE') end,
 [103]=function() return OPGG.point('HEART') end,
 [104]=function() return OPGG.field(OPGG.currentDeparture(),'popular_') end,
 [105]=function() return OPGG.field(OPGG.currentDeparture(),'popularExp_') end,
 [106]=function() return OPGG.field(OPGG.currentDeparture(),'hearts_') end,
 [503]=function() return OPGG.saveAddr('ints','SAVEI_HOUR') end,
 [504]=function() return OPGG.saveAddr('ints','SAVEI_TIME') end,
 [505]=function() return OPGG.saveAddr('ints','SAVEI_YEAR') end,
 [506]=function() return OPGG.saveAddr('ints','SAVEI_MONTH') end,
}
OPGG.CHARFIELDS={
 {'exp_','Satisfaction / EXP (current LV)','満足／経験値（現在LV内）'}, {'staffExp_','staffExp_ (purpose unconfirmed)','staffExp_（用途未確認）'},
 {'visitCount_','Visits','来店回数'},{'regularVisitCount_','Regular visits','常連来店回数'},
 {'paymentAmountToday_','Spent today','本日の支払額'},{'bestPaymentAmount_','Best payment','最高支払額'},
 {'isFind_','Discovered','発見済み',vtByte},{'isRegular_','Regular','常連',vtByte},
 {'isFan_','Fan','ファン',vtByte},{'isWorkingToday_','Working today','本日勤務',vtByte},
 {'isInjured_','Injured','負傷',vtByte},{'isSick_','Sick','病気',vtByte},
 {'isFavorite_','Favorite','お気に入り',vtByte},
}
-- Character LV is a reference to shared CharacterLevelData, not an editable shared ID.
OPGG.levelDisplays={}



function OPGG.customerLevel29Plan()
  OPGG.require();local levels=OPGG.levelTable()
  if not levels[29] or not levels[30] then OPGG.fail('LV 29 / 30 data unavailable.','LV29・30のデータが見つかりません。') end
  local app=OPGG.app();local save=OPGG.obj(app,'save_');local plan={};local seen={};local stats={eligible=0,unchanged=0,found=0,hidden=0,excluded=0}
  for _,character in ipairs(OPGG.freshList('characterList_')) do
    local data=OPGG.obj(character,'data_')
    if OPGG.readFlag(data,'&lt;isCustomer_&gt;k__BackingField')~=0 and not seen[character] then
      seen[character]=true
      if OPGG.levelInfo(character)&gt;=30 then stats.excluded=stats.excluded+1 else
      stats.eligible=stats.eligible+1
      local required=OPGG.levelThreshold(character,levels[29])
      if not required or required&lt;1 or required&gt;0x7FFFFFFF then OPGG.fail('Invalid LV29 experience requirement.','LV29の必要経験値が不正です。') end
      local levelAddress=OPGG.field(character,'levelData_');local expAddress=OPGG.checkedAddress(OPGG.field(character,'exp_'),vtDword)
      local oldLevel=ptr(levelAddress);local oldExp=readInteger(expAddress)
      if not valid(oldLevel) or oldExp==nil then OPGG.fail('Customer level data unavailable.','お客様のLVデータが見つかりません。') end
      if oldLevel==levels[29] and oldExp==required-1 then stats.unchanged=stats.unchanged+1 else
      plan[#plan+1]={context=OPGG.characterContext(character),character=character,levelAddress=levelAddress,expAddress=expAddress,oldLevel=oldLevel,oldExp=oldExp,level=levels[29],exp=required-1,required=required}
        if OPGG.readFlag(character,'isFind_')~=0 then stats.found=stats.found+1 else stats.hidden=stats.hidden+1 end
      end
      end
    end
  end
  return plan,app,save,stats
end
function OPGG.allCustomersLevel29()
  local plan,app,save,stats=OPGG.customerLevel29Plan()
  if #plan==0 then print(string.format(OPGG.T('No changes needed. Already at target LV / EXP: %d; excluded LV30+: %d.','変更対象は0人です。設定済み：%d人／LV30以上で除外：%d人。'),stats.unchanged,stats.excluded));return 0 end
  local ok,e=OPGG.withPaused(function()
    if OPGG.app()~=app or OPGG.obj(app,'save_')~=save then error(OPGG.T('Save changed; retry.','セーブが変わりました。再実行してください。')) end
    for _,r in ipairs(plan) do
      OPGG.resolveCharacter(r.context)
      if ptr(r.levelAddress)~=r.oldLevel or readInteger(r.expAddress)~=r.oldExp then error(OPGG.T('Customer data changed; retry.','お客様のデータが変わりました。再実行してください。')) end
    end
    local touched={}
    local success,err=pcall(function()
      for _,r in ipairs(plan) do
        touched[#touched+1]=r
        if not writeInteger(r.expAddress,r.exp) or not writeInteger(r.levelAddress,r.level) then error('Customer LV / EXP write failed') end
        if ptr(r.levelAddress)~=r.level or readInteger(r.expAddress)~=r.exp then error('Customer LV / EXP verification failed') end
      end
    end)
    if not success then
      local failed=0
      for _,r in ipairs(touched) do
        local a=writeInteger(r.levelAddress,r.oldLevel);local b=writeInteger(r.expAddress,r.oldExp)
        if not a or not b or ptr(r.levelAddress)~=r.oldLevel or readInteger(r.expAddress)~=r.oldExp then failed=failed+1 end
      end
      if failed&gt;0 then error(tostring(err)..' / rollback failed: '..failed) end
      error(err,0)
    end
  end)
  if not ok then error(e,0) end
  pcall(OPGG.updateLevelDisplays);pcall(OPGG.updateCharacterDetails)
  print(string.format(OPGG.T('Changed %d customers to LV29 / 1 EXP remaining (discovered: %d, undiscovered: %d). Already set: %d; excluded LV30+: %d.','実際に変更：%d人（LV29・残り経験値1／発見済み：%d人・未発見：%d人）。設定済み：%d人／LV30以上で除外：%d人。'),#plan,stats.found,stats.hidden,stats.unchanged,stats.excluded))
  return #plan
end

function OPGG.customerLevel99Plan()
  OPGG.require();local levels=OPGG.levelTable()
  if not levels[99] or not levels[100] then OPGG.fail('LV 99 / 100 data unavailable.','LV99・100のデータが見つかりません。') end
  local app=OPGG.app();local save=OPGG.obj(app,'save_');local plan={};local seen={};local stats={eligible=0,unchanged=0,found=0,hidden=0,excluded=0}
  for _,character in ipairs(OPGG.freshList('characterList_')) do
    local data=OPGG.obj(character,'data_')
    if OPGG.readFlag(data,'&lt;isCustomer_&gt;k__BackingField')~=0 and not seen[character] then
      seen[character]=true
      if OPGG.levelInfo(character)&gt;=100 then stats.excluded=stats.excluded+1 else
      stats.eligible=stats.eligible+1
      local required=OPGG.levelThreshold(character,levels[99])
      if not required or required&lt;1 or required&gt;0x7FFFFFFF then OPGG.fail('Invalid LV99 experience requirement.','LV99の必要経験値が不正です。') end
      local levelAddress=OPGG.field(character,'levelData_');local expAddress=OPGG.checkedAddress(OPGG.field(character,'exp_'),vtDword)
      local oldLevel=ptr(levelAddress);local oldExp=readInteger(expAddress)
      if not valid(oldLevel) or oldExp==nil then OPGG.fail('Customer level data unavailable.','お客様のLVデータが見つかりません。') end
      if oldLevel==levels[99] and oldExp==required-1 then stats.unchanged=stats.unchanged+1 else
      plan[#plan+1]={context=OPGG.characterContext(character),character=character,levelAddress=levelAddress,expAddress=expAddress,oldLevel=oldLevel,oldExp=oldExp,level=levels[99],exp=required-1,required=required}
        if OPGG.readFlag(character,'isFind_')~=0 then stats.found=stats.found+1 else stats.hidden=stats.hidden+1 end
      end
      end
    end
  end
  return plan,app,save,stats
end
function OPGG.allCustomersLevel99()
  local plan,app,save,stats=OPGG.customerLevel99Plan()
  if #plan==0 then print(string.format(OPGG.T('No changes needed. Already at target LV / EXP: %d; excluded LV100+: %d.','変更対象は0人です。設定済み：%d人／LV100以上で除外：%d人。'),stats.unchanged,stats.excluded));return 0 end
  local ok,e=OPGG.withPaused(function()
    if OPGG.app()~=app or OPGG.obj(app,'save_')~=save then error(OPGG.T('Save changed; retry.','セーブが変わりました。再実行してください。')) end
    for _,r in ipairs(plan) do
      OPGG.resolveCharacter(r.context)
      if ptr(r.levelAddress)~=r.oldLevel or readInteger(r.expAddress)~=r.oldExp then error(OPGG.T('Customer data changed; retry.','お客様のデータが変わりました。再実行してください。')) end
    end
    local touched={}
    local success,err=pcall(function()
      for _,r in ipairs(plan) do
        touched[#touched+1]=r
        if not writeInteger(r.expAddress,r.exp) or not writeInteger(r.levelAddress,r.level) then error('Customer LV / EXP write failed') end
        if ptr(r.levelAddress)~=r.level or readInteger(r.expAddress)~=r.exp then error('Customer LV / EXP verification failed') end
      end
    end)
    if not success then
      local failed=0
      for _,r in ipairs(touched) do
        local a=writeInteger(r.levelAddress,r.oldLevel);local b=writeInteger(r.expAddress,r.oldExp)
        if not a or not b or ptr(r.levelAddress)~=r.oldLevel or readInteger(r.expAddress)~=r.oldExp then failed=failed+1 end
      end
      if failed&gt;0 then error(tostring(err)..' / rollback failed: '..failed) end
      error(err,0)
    end
  end)
  if not ok then error(e,0) end
  pcall(OPGG.updateLevelDisplays);pcall(OPGG.updateCharacterDetails)
  print(string.format(OPGG.T('Changed %d customers to LV99 / 1 EXP remaining (discovered: %d, undiscovered: %d). Already set: %d; excluded LV100+: %d.','実際に変更：%d人（LV99・残り経験値1／発見済み：%d人・未発見：%d人）。設定済み：%d人／LV100以上で除外：%d人。'),#plan,stats.found,stats.hidden,stats.unchanged,stats.excluded))
  return #plan
end

function OPGG.updateLevelDisplays()
  if OPGG.uiActionBusy then return end
  local al=getAddressList()
  for id,display in pairs(OPGG.levelDisplays) do
    local level=display.level.id and al.getMemoryRecordByID(display.level.id)
    local expRecord=display.exp.id and al.getMemoryRecordByID(display.exp.id)
    if not level or level~=display.level.mr or not expRecord or expRecord~=display.exp.mr then OPGG.levelDisplays[id]=nil else
      local ok,lv,needed,exp=pcall(function() local p=OPGG.resolveCharacter(display.context);local lv,needed=OPGG.levelInfo(p);return lv,needed,readInteger(OPGG.field(p,'exp_')) end)
      if ok then
        display.level.en='LV / Shop affinity: '..lv..' (check to change)';display.level.ja='LV／お店好き度：'..lv..'（チェックで変更）'
        display.exp.en='Satisfaction: '..exp..' / '..needed;display.exp.ja='満足：'..exp..'／'..needed
        level.Description=OPGG.T(display.level.en,display.level.ja)
        expRecord.Description=OPGG.T(display.exp.en,display.exp.ja)
      end
    end
  end
end


-- Use Customer.RealizeDream on the existing Unity Trophy.Update thread.
-- Run the normal completion, notification and reward path.
OPGG.dreamQueue={}
OPGG.dreamPages={}
function OPGG.isDreamCompleted(character,kind,index)
  for _,dream in ipairs(OPGG.items(OPGG.obj(character,'realizedDreams_'))) do
    if readInteger(OPGG.field(dream,'type_'))==kind and readInteger(OPGG.field(dream,'index_'))==index then return true end
  end
  return false
end
function OPGG.validDream(character,kind,index)
  for _,line in ipairs(OPGG.characterDetails(character)) do
    local dream=line[3]
    if dream and dream.kind==kind and dream.index==index then return true end
  end
  return false
end
function OPGG.completeDream(id,kind,index,context)
  context=context or OPGG.characterContext(OPGG.find('characterList_',id));local character=OPGG.resolveCharacter(context)
  if not OPGG.validDream(character,kind,index) then OPGG.fail('This dream does not belong to the character.','このキャラクターの願いではありません。') end
  if OPGG.isDreamCompleted(character,kind,index) then OPGG.updateCharacterDetails();return end
  if OPGG.job and OPGG.job.kind~='dream' then OPGG.fail('Another game-thread job is running; retry after it finishes.','別の処理を実行中です。完了後に再実行してください。') end
  if OPGG.job and OPGG.job.characterId==id and OPGG.job.dreamKind==kind and OPGG.job.dreamIndex==index then return end
  for _,task in ipairs(OPGG.dreamQueue) do if task.id==id and task.kind==kind and task.index==index then return end end
  OPGG.dreamQueue[#OPGG.dreamQueue+1]={id=id,kind=kind,index=index,context=context}
  local ok,e=pcall(OPGG.startNextDream)
  if not ok then OPGG.dreamQueue={};error(e,0) end
end
function OPGG.dreamAssembly(page,site,target,original)
  return string.format([[
define(opggDreamState,%X)
define(opggDreamCharacter,%X)
define(opggDreamKind,%X)
define(opggDreamIndex,%X)
define(opggDreamAppCell,%X)
define(opggDreamApp,%X)
define(opggDreamSaveCell,%X)
define(opggDreamSave,%X)
label(opggDreamExit)
label(opggDreamStale)
%X:
pushfd
pushad
mov ebp,esp
sub esp,210
and esp,FFFFFFF0
fxsave [esp]
cmp dword ptr [opggDreamState],1
jne opggDreamExit
mov dword ptr [opggDreamState],2
mov eax,[opggDreamAppCell]
mov eax,[eax]
cmp eax,[opggDreamApp]
jne opggDreamStale
mov eax,[opggDreamSaveCell]
mov eax,[eax]
cmp eax,[opggDreamSave]
jne opggDreamStale
push 0
push [opggDreamIndex]
push [opggDreamKind]
push [opggDreamCharacter]
call %X
add esp,10
mov dword ptr [opggDreamState],3
jmp opggDreamExit
opggDreamStale:
mov dword ptr [opggDreamState],4
opggDreamExit:
fxrstor [esp]
mov esp,ebp
popad
popfd
db %s
jmp %X
]],page+0x800,page+0x804,page+0x808,page+0x80C,page+0x810,page+0x814,page+0x818,page+0x81C,page,target,original,site+7)
end
function OPGG.startNextDream()
  if OPGG.job or #OPGG.dreamQueue==0 then return end
  local task=table.remove(OPGG.dreamQueue,1);local character=OPGG.resolveCharacter(task.context)
  if OPGG.isDreamCompleted(character,task.kind,task.index) then OPGG.startNextDream();return end
  if not OPGG.validDream(character,task.kind,task.index) then OPGG.fail('Dream data changed; reopen the editor.','願いのデータが変わりました。エディタを開き直してください。') end
  local site=OPGG.scan('TrophyType');local target=OPGG.nativeContract('RealizeDream',OPGG.elementClass(OPGG.obj(OPGG.app(),'customerList_'),'game','Customer'),'RealizeDream',true,{18,17,8},2);local original=readBytes(site,7,true)
  if not original or original[1]~=0x80 or original[2]~=0x3D or original[7]~=0 then OPGG.fail('Unexpected Unity update entry.','更新処理の命令が想定と異なります。') end
  -- A fresh page avoids rewriting an earlier handler before its epilogue returns.
  local page=allocateMemory(4096)
  if not page or page&lt;65536 or page&gt;0x7FFF0000 then OPGG.fail('32-bit job allocation failed.','32bit処理領域を確保できません。') end
  OPGG.dreamPages[#OPGG.dreamPages+1]=page -- Retain until the process exits.
  local bytes={};for _,v in ipairs(original) do bytes[#bytes+1]=string.format('%02X',v) end
  local code=OPGG.dreamAssembly(page,site,target,table.concat(bytes,' '))
  local marker='push 0\npush [opggDreamIndex]';local at=assert(code:find(marker,1,true));code=code:sub(1,at-1)..OPGG.characterNativeGuard(task.context)..code:sub(at)
  local ok,e=autoAssembleCheck(code,true,false)
  if not ok then OPGG.fail('Dream job syntax failed: '..tostring(e),'願い処理の構文検査失敗：'..tostring(e)) end
  if not autoAssemble(code) then OPGG.fail('Dream job assembly failed.','願い処理の組み立てに失敗しました。') end
  local app=OPGG.app();local saveAddress=OPGG.field(app,'save_');local save=ptr(saveAddress)
  local values={0,character,task.kind,task.index,OPGG.static,app,saveAddress,save}
  for i,v in ipairs(values) do if not writeInteger(page+0x800+(i-1)*4,v) then OPGG.fail('Dream job preparation failed.','願い処理の準備に失敗しました。') end end
  OPGG.job={kind='dream',page=page,site=site,old=original,start=getTickCount(),pid=OPGG.pid,context=task.context,characterId=task.id,dreamKind=task.kind,dreamIndex=task.index}
  local delta=(page-site-5)&amp;0xFFFFFFFF
  local patch={0xE9,delta&amp;255,(delta&gt;&gt;8)&amp;255,(delta&gt;&gt;16)&amp;255,(delta&gt;&gt;24)&amp;255,0x90,0x90}
  local success,err=OPGG.withPaused(function()
    local now=readBytes(site,7,true)
    for i,v in ipairs(original) do if not now or now[i]~=v then error('Unity update changed during preparation') end end
    if not writeBytes(site,patch) then writeBytes(site,original);error('Dream hook write failed') end
    OPGG.job.patched=patch
    if not writeInteger(page+0x800,1) then error('Dream activation failed') end
  end)
  if not success then OPGG.cancelAchievementJob(true);OPGG.dreamQueue={};error(err,0) end
end
function OPGG.pollDreamJob()
  local job=OPGG.job;if not job or job.kind~='dream' then return end
  local state=readInteger(job.page+0x800)
  if state==3 then
    local done=OPGG.isDreamCompleted(OPGG.resolveCharacter(job.context),job.dreamKind,job.dreamIndex)
    OPGG.cancelAchievementJob(true)
    if not done then OPGG.dreamQueue={};OPGG.fail('Dream completion was not confirmed.','願いの達成を確認できませんでした。') end
    print(OPGG.T('Normal dream completion confirmed.','願いの達成を確認しました。'));OPGG.updateCharacterDetails();OPGG.startNextDream()
  elseif state==4 or getTickCount()-job.start&gt;30000 then
    OPGG.cancelAchievementJob(true);OPGG.dreamQueue={}
    OPGG.fail('Dream job cancelled: save changed or update timed out.','願い処理を中止しました。セーブ変更または更新待ちのタイムアウトです。')
  end
end

function OPGG.itemCatalog()
  local class=OPGG.class('data','Data');local data=ptr(ptr(class+0x5C))
  local teams=OPGG.obj(data,'teamData_');local teamCount=readInteger(teams+12);local members={}
  if not teamCount or teamCount&lt;0 or teamCount&gt;10000 then OPGG.fail('Invalid gift preference data.','贈り物の好みデータが不正です。') end
  for i=0,teamCount-1 do
    local team=ptr(OPGG.arrayElement(teams,i,18));local ids=OPGG.obj(team,'&lt;charaIds_&gt;k__BackingField');local set={}
    local count=valid(ids) and readInteger(ids+12) or 0
    for j=0,count-1 do set[readInteger(OPGG.arrayElement(ids,j,8))]=true end
    members[i]=set
  end
  local catalog={}
  for _,item in ipairs(OPGG.list('treasureList_')) do
    local d=OPGG.obj(item,'data_')
    if OPGG.readFlag(d,'&lt;isPresentImpossible_&gt;k__BackingField')==0 then
      local id=OPGG.dataId(item);local en,ja=OPGG.dataNamePair(d)
      local team=readInteger(OPGG.field(d,'&lt;spTeamId_&gt;k__BackingField'))
      catalog[#catalog+1]={id=id,en=en,ja=ja,likes=members[team] or {},speed=math.max(0,readInteger(OPGG.field(d,'&lt;moveSpeedUpRate_&gt;k__BackingField'))-100),serving=readInteger(OPGG.field(d,'&lt;additionalServing_&gt;k__BackingField'))}
    end
  end
  return catalog
end
function OPGG.itemChoices(character)
  local id=OPGG.dataId(character);local owned={}
  for _,data in ipairs(OPGG.items(OPGG.obj(character,'treasureDataList_'))) do owned[readInteger(OPGG.field(data,'id_'))]=true end
  local choices={}
  for _,entry in ipairs(OPGG.itemCatalog()) do if not owned[entry.id] then choices[#choices+1]=entry end end
  table.sort(choices,function(a,b)if (a.likes[id] and true or false)~=(b.likes[id] and true or false) then return a.likes[id] and true or false end;return a.id&lt;b.id end)
  return choices
end
function OPGG.chooseCharacterItem(id,slot,context)
  context=context or OPGG.characterContext(OPGG.find('characterList_',id));OPGG.resolveCharacter(context)
  OPGG.require()
  if OPGG.job then OPGG.fail('Another game-thread job is running. Retry after completion.','別の処理を実行中です。完了後に再実行してください。') end
  local character=OPGG.find('characterList_',id);local owned=OPGG.items(OPGG.obj(character,'treasureDataList_'))
  if #owned&gt;=2 or slot~=#owned+1 then OPGG.fail('Fill the first empty slot in order; reopen the editor.','枠1から順に設定してください。エディタを開き直してください。') end
  local choices=OPGG.itemChoices(character);local names={}
  local bonusUsed=OPGG.readFlag(character,'isExecuteFavoriteGift_')~=0
  for i,entry in ipairs(choices) do
    local like=entry.likes[id]
    local badge=like and OPGG.T('[Likes] ','【好み一致】') or OPGG.T('[Normal] ','【通常】')
    if like and bonusUsed then badge=badge..OPGG.T('[First-gift bonus used] ','【初回特典済み】') end
    names[i]=badge..OPGG.T(entry.en,entry.ja)..' [ID '..entry.id..'] '..OPGG.T('Speed +','速度補正＋')..entry.speed..'%'..OPGG.T(' / Serving +','／食事量補正＋')..entry.serving
  end
  local chosen=OPGG.pick(OPGG.T('Give an item (preference first; inventory unchanged)','プレゼント（好み一致を先頭表示・アイテム消費なし）'),names)
  if not chosen then return end
  OPGG.queueCharacterItem(id,slot,choices[chosen].id,context)
end
function OPGG.itemParent()
  local game=OPGG.obj(OPGG.app(),'frmGame_');local manager=OPGG.obj(game,'formManager_')
  local stack=OPGG.obj(manager,'formStack_');local list=OPGG.obj(stack,'list_');OPGG.requireListABI(list);local forms=OPGG.items(list)
  local form=forms[#forms]
  if not valid(form) then OPGG.fail('No active game screen.','ゲーム画面を取得できません。') end
  local c=ptr(form);local compatible=false
  for i=1,32 do
    if not valid(c) then break end
    if readString(ptr(c+8),128)=='MyFormBase' and readString(ptr(c+12),128)=='form' then compatible=true;break end
    c=ptr(c+0x2C)
  end
  if not compatible or readInteger(OPGG.field(form,'formProcMode_'))==4 then OPGG.fail('Game screen is changing; retry.','ゲーム画面の切替中です。再実行してください。') end
  local name=readString(ptr(ptr(form)+8),128)
  if name:find('Present') then OPGG.fail('Finish the current gift result first.','現在のプレゼント結果を閉じてください。') end
  return form,stack,list
end
function OPGG.itemAssembly(page,site,target,original,restoreTarget,stockOffset)
  local code=OPGG.dreamAssembly(page,site,target,original)
  local marker='push 0\npush [opggDreamIndex]'
  local guards=string.format([=[mov eax,[%X]
mov eax,[eax]
test eax,eax
jz opggDreamStale
mov eax,[eax+C]
cmp eax,[%X]
jne opggDreamStale
mov eax,[%X]
mov eax,[eax]
cmp eax,[%X]
jne opggDreamStale
mov eax,[%X]
mov eax,[eax]
cmp eax,[%X]
jne opggDreamStale
mov eax,[%X]
cmp dword ptr [eax],4
je opggDreamStale
mov eax,[opggDreamKind]
mov eax,[eax+%X]
mov [%X],eax
]=],page+0x820,page+0x824,page+0x828,page+0x82C,page+0x830,page+0x834,page+0x838,stockOffset,page+0x840)
  local at=assert(code:find(marker,1,true));code=code:sub(1,at-1)..guards..code:sub(at)
  local after=string.format([=[add esp,10
mov eax,[opggDreamKind]
mov ecx,[%X]
sub ecx,[eax+%X]
test ecx,ecx
jz opggItemRestored
sub esp,4
push 0
push ecx
push eax
call %X
add esp,10
opggItemRestored:
mov dword ptr [opggDreamState],3]=],page+0x840,stockOffset,restoreTarget)
  local needle='add esp,10\nmov dword ptr [opggDreamState],3';local at2=assert(code:find(needle,1,true))
  code=code:sub(1,at2-1)..after..code:sub(at2+#needle)
  return 'label(opggItemRestored)\n'..code
end
function OPGG.queueCharacterItem(id,slot,itemId,context)
  context=context or OPGG.characterContext(OPGG.find('characterList_',id));OPGG.resolveCharacter(context)
  if OPGG.job then OPGG.fail('Another game-thread job is running.','別の処理を実行中です。') end
  local character=OPGG.find('characterList_',id);local owned=OPGG.items(OPGG.obj(character,'treasureDataList_'))
  if #owned&gt;=2 or slot~=#owned+1 then OPGG.fail('Owned item slots changed. Reopen the editor.','所有枠が変わりました。エディタを開き直してください。') end
  local permitted=false;for _,entry in ipairs(OPGG.itemChoices(character)) do if entry.id==itemId then permitted=true;break end end
  if not permitted then OPGG.fail('This item is already owned or cannot be presented.','所持済み、またはプレゼント不可のアイテムです。') end
  local item=OPGG.find('treasureList_',itemId);local form,stack,formList=OPGG.itemParent()
  local site=OPGG.scan('TrophyType');local target=OPGG.nativeContract('CharacterSetItem',ptr(character),'SetItem',false,{18,18},1);local restoreTarget=OPGG.nativeContract('TreasureAddHaveNum',ptr(item),'AddHaveNum',false,{8},1);local original=readBytes(site,7,true)
  if not original or original[1]~=0x80 or original[2]~=0x3D or original[7]~=0 then OPGG.fail('Unexpected update entry.','更新処理の命令が想定と異なります。') end
  local page=allocateMemory(4096)
  if not page or page&lt;65536 or page&gt;0x7FFF0000 then OPGG.fail('Item job allocation failed.','アイテム処理領域を確保できません。') end
  OPGG.dreamPages[#OPGG.dreamPages+1]=page
  local bytes={};for _,v in ipairs(original) do bytes[#bytes+1]=string.format('%02X',v) end
  OPGG.requireListABI(OPGG.obj(character,'treasureDataList_'));OPGG.requireListABI(formList)
  local stockOffset=OPGG.checkedAddress(OPGG.field(item,'haveNum_'),vtDword)-item
  local code=OPGG.itemAssembly(page,site,target,table.concat(bytes,' '),restoreTarget,stockOffset)
  local marker='mov eax,['..string.format('%X',page+0x820)..']';local at=assert(code:find(marker,1,true));code=code:sub(1,at-1)..OPGG.characterNativeGuard(context)..code:sub(at)
  local ok,e=autoAssembleCheck(code,true,false)
  if not ok then OPGG.fail('Item code check failed: '..tostring(e),'アイテム処理の構文検査失敗：'..tostring(e)) end
  if not autoAssemble(code) then OPGG.fail('Item job assembly failed.','アイテム処理の組み立てに失敗しました。') end
  local app=OPGG.app();local saveAddress=OPGG.field(app,'save_')
  local values={0,character,item,form,OPGG.static,app,saveAddress,ptr(saveAddress),OPGG.field(character,'treasureDataList_'),#owned,OPGG.field(stack,'list_'),formList,formList+16,readInteger(formList+16),OPGG.field(form,'formProcMode_')}
  for i,v in ipairs(values) do if not writeInteger(page+0x800+(i-1)*4,v) then OPGG.fail('Item preparation failed.','アイテム処理の準備失敗。') end end
  OPGG.job={kind='item',page=page,site=site,old=original,start=getTickCount(),pid=OPGG.pid,context=context,characterId=id,itemId=itemId,slot=slot,treasure=item}
  local delta=(page-site-5)&amp;0xFFFFFFFF;local patch={0xE9,delta&amp;255,(delta&gt;&gt;8)&amp;255,(delta&gt;&gt;16)&amp;255,(delta&gt;&gt;24)&amp;255,0x90,0x90}
  local success,err=OPGG.withPaused(function()
    local now=readBytes(site,7,true);for i,v in ipairs(original) do if not now or now[i]~=v then error('Update code changed') end end
    if not writeBytes(site,patch) then writeBytes(site,original);error('Item hook write failed') end
    OPGG.job.patched=patch;if not writeInteger(page+0x800,1) then error('Item activation failed') end
  end)
  if not success then OPGG.cancelAchievementJob(true);error(err,0) end
end
function OPGG.pollItemJob()
  local job=OPGG.job;if not job or job.kind~='item' then return end
  local state=readInteger(job.page+0x800)
  if state==3 then
    local character=OPGG.resolveCharacter(job.context);local owned=OPGG.items(OPGG.obj(character,'treasureDataList_'))
    local item=owned[job.slot];local done=item and readInteger(OPGG.field(item,'id_'))==job.itemId
    local stockOK=readInteger(OPGG.field(job.treasure,'haveNum_'))==readInteger(job.page+0x840)
    OPGG.cancelAchievementJob(true)
    if not stockOK then OPGG.fail('Inventory preservation was not confirmed.','アイテム数の維持を確認できませんでした。') end
    if not done then OPGG.fail('Item ownership was not confirmed.','アイテムの保有を確認できませんでした。') end
    OPGG.updateCharacterDetails();print(OPGG.T('Item ownership confirmed.','アイテムの保有を確認しました。'))
  elseif state==4 or getTickCount()-job.start&gt;30000 then
    OPGG.cancelAchievementJob(true);OPGG.fail('Item job cancelled: save or item slots changed, or timed out.','セーブ・所有枠の変更またはタイムアウトによりアイテム処理を中止しました。')
  end
end

OPGG.detailDisplays={}
function OPGG.dataNamePair(data)
  for _,field in ipairs({'&lt;name_&gt;k__BackingField','&lt;itemName_&gt;k__BackingField'}) do
    local ok,a=pcall(OPGG.field,data,field)
    if ok then
      local name=OPGG.str(ptr(a))
      if name~='' then return name,name end
    end
  end
  local name='ID '..tostring(readInteger(OPGG.field(data,'id_')));return name,name
end
function OPGG.characterDetails(character)
  local data=OPGG.obj(character,'data_');local lines={}
  local function add(en,ja,action) lines[#lines+1]={en,ja,action} end
  local function value(field)
    local n=readInteger(OPGG.field(data,field));if n and n&gt;2147483647 then n=n-4294967296 end;return n
  end
  local origin=value('&lt;departureId_&gt;k__BackingField')
  if origin&gt;=0 then
    local en,ja=OPGG.namePair(OPGG.find('departureList_',origin));add('Home sea: '..en,'出身の海：'..ja)
  else add('Home sea: no data (ID '..origin..')','出身の海：データなし（ID '..origin..'）') end
  if OPGG.readFlag(character,'isFan_')~=0 then add('Status: shop fan','登録状態：お店のファン')
  elseif OPGG.readFlag(character,'isRegular_')~=0 then add('Status: regular customer','登録状態：常連') end
  add('Dreams (check incomplete rows to complete)','お店でかなえたいこと（未達成はチェックで達成）')
  local realized={}
  for _,dream in ipairs(OPGG.items(OPGG.obj(character,'realizedDreams_'))) do
    realized[readInteger(OPGG.field(dream,'type_'))..':'..readInteger(OPGG.field(dream,'index_'))]=true
  end
  local dreams={};local list=OPGG.obj(data,'dreamDefinitionList_')
  if valid(list) then
    for _,dream in ipairs(OPGG.items(list)) do dreams[#dreams+1]={readInteger(OPGG.field(dream,'type_')),readInteger(OPGG.field(dream,'index_'))} end
  else
    if value('&lt;dreamRecipeId_&gt;k__BackingField')&gt;=0 then dreams[#dreams+1]={0,0} end
    local chips=OPGG.obj(data,'&lt;dreamChipIdList_&gt;k__BackingField');local count=valid(chips) and readInteger(chips+12) or 0
    for index=0,count-1 do dreams[#dreams+1]={1,index} end
    if value('&lt;dreamArchitectureId_&gt;k__BackingField')&gt;=0 then dreams[#dreams+1]={2,0} end
  end
  for _,dream in ipairs(dreams) do
    local kind,index=dream[1],dream[2];local nameEn,nameJa
    if kind==0 then
      nameEn,nameJa=OPGG.namePair(OPGG.find('recipeList_',value('&lt;dreamRecipeId_&gt;k__BackingField')))
      nameEn='Try dish: '..nameEn;nameJa='料理を味わう：'..nameJa
    elseif kind==1 then
      local chips=OPGG.obj(data,'&lt;dreamChipIdList_&gt;k__BackingField');local count=readInteger(chips+12)
      if index&lt;0 or index&gt;=count then OPGG.fail('Invalid dream index.','願いの番号が不正です。') end
      nameEn,nameJa=OPGG.namePair(OPGG.find('chipModelList_',readInteger(OPGG.arrayElement(chips,index,8))))
      nameEn='Visit: '..nameEn;nameJa='利用する：'..nameJa
    elseif kind==2 then
      nameEn,nameJa=OPGG.namePair(OPGG.find('architectureList_',value('&lt;dreamArchitectureId_&gt;k__BackingField')))
      local item=value('&lt;dreamArchitectureItemId_&gt;k__BackingField')
      if item&gt;=0 then local ie,ij=OPGG.namePair(OPGG.find('treasureList_',item));nameEn=nameEn..' / '..ie;nameJa=nameJa..'／'..ij end
      nameEn='Visit facility: '..nameEn;nameJa='施設を利用する：'..nameJa
    else nameEn='Unknown dream type '..kind;nameJa='未確認の願い種別 '..kind end
    local done=realized[kind..':'..index]
    add((done and '[Completed] ' or '[Incomplete] ')..nameEn,(done and '【達成】' or '【未達成】')..nameJa,{kind=kind,index=index,done=done and true or false})
  end
  if #dreams==0 then add('No dreams','願いなし') end
  add('Owned items (check an empty slot)','所有アイテム（空き枠をチェックして設定）')
  local items=OPGG.items(OPGG.obj(character,'treasureDataList_'))
  -- The game detail screen renders two slots (InitCharacterCustomerInfo).
  for i=1,math.max(2,#items) do
    if items[i] then
      local ie,ij=OPGG.dataNamePair(items[i]);add('Slot '..i..': '..ie,'枠'..i..'：'..ij)
    else
      if i==#items+1 then add('Slot '..i..': Empty (select item)','枠'..i..'：空き（アイテム選択）',{itemSlot=i})
      else add('Slot '..i..': Empty (fill previous slot first)','枠'..i..'：空き（前の枠から設定）') end
    end
  end
  return lines
end
function OPGG.updateCharacterDetails()
  for _,display in pairs(OPGG.detailDisplays) do
    local ok,lines=pcall(function() return OPGG.characterDetails(OPGG.resolveCharacter(display.context)) end)
    if not ok then lines={{'Details unavailable: '..tostring(lines),'詳細を取得できません：'..tostring(lines)}} end
    local parts={}
    for _,line in ipairs(lines) do parts[#parts+1]=line[1]..'\t'..line[2] end
    local signature=table.concat(parts,'\n')
    if display.signature~=signature then
      OPGG.clearChildren(display.parent)
      for _,line in ipairs(lines) do
        local action=line[3]
        local capable=not action or OPGG.allCodes(action.itemSlot and {'TrophyType','CharacterSetItem','TreasureAddHaveNum','DataType'} or {'TrophyType','RealizeDream'})
        if action and not action.done and capable then
          local m=OPGG.addRec(display.parent,line[1],line[2],'0',vtAutoAssembler);m.Color=OPGG.C_SCRIPT
          local call=action.itemSlot and ('OPGG.chooseCharacterItem('..display.id..','..action.itemSlot..',OPGG.editorContext('..display.contextId..'))') or ('OPGG.completeDream('..display.id..','..action.kind..','..action.index..',OPGG.editorContext('..display.contextId..'))')
          m.Script='[ENABLE]\n{$lua}\nif syntaxcheck then return end\nOPGG.oneShot(memrec,function() '..call..' end)\n{$asm}\n[DISABLE]\n'
        else OPGG.addHdr(display.parent,line[1]..(not capable and ' [Unavailable]' or ''),line[2]..(not capable and '【使用不可】' or '')) end
      end
      display.signature=signature
    end
  end
end
function OPGG.addCharacterDetails(parent,id,context)
  local group=OPGG.addHdr(parent,'Customer details','お客様詳細')
  OPGG.detailDisplays[group.ID]={parent=group,id=id,context=context,contextId=OPGG.keepEditorContext(context,group.ID)}
  OPGG.updateCharacterDetails()
end


function OPGG.yagaraburuState()
  OPGG.require();local app=OPGG.app();local animal=OPGG.obj(app,'myYagaraburu_')
  if not OPGG.isA(animal,'game','Yagaraburu') then
    OPGG.fail('Yagara Bull unavailable; load a save where it is unlocked.','ヤガラブルが見つかりません。解放済みのセーブをロードしてください。')
  end
  local data=OPGG.obj(animal,'data_');local ok,parameters=pcall(OPGG.obj,animal,'paramList_');if not ok or not valid(parameters) then parameters=nil end
  if not valid(data) then
    OPGG.fail('Yagara Bull data is not initialized.','ヤガラブルのデータが初期化されていません。')
  end
  return {app=app,save=OPGG.obj(app,'save_'),animal=animal,data=data,parameters=parameters,session=OPGG.session}
end
function OPGG.yagaraburuAddress(state,field,index)
  if OPGG.session~=state.session or OPGG.app()~=state.app or OPGG.obj(state.app,'save_')~=state.save then return nil end
  local current=OPGG.yagaraburuState()
  if current.animal~=state.animal or current.data~=state.data or current.parameters~=state.parameters then return nil end
  if index~=nil then
    if not valid(current.parameters) or index&lt;0 or index&gt;=(readInteger(current.parameters+12) or 0) or index%1~=0 then return nil end
    return OPGG.arrayElement(current.parameters,index,8)
  end
  return OPGG.field(current.animal,field)
end
OPGG.yagaraFeedDisplays={}
function OPGG.yagaraFeedSnapshot(state)
  if not OPGG.yagaraburuAddress(state,'stomach_') then OPGG.fail('Reopen the Yagara Bull editor.','ヤガラブルエディタを開き直してください。') end
  local list=OPGG.obj(state.animal,'feedsList_');local items=OPGG.items(list);local counts={0,0,0}
  for _,feed in ipairs(items) do
    local quality=readInteger(OPGG.field(feed,'result_'))
    if quality==nil or quality&lt;0 or quality&gt;2 then OPGG.fail('Invalid feed quality.','餌の品質データが不正です。') end
    counts[quality+1]=counts[quality+1]+1
  end
  return list,items,counts
end
function OPGG.yagaraAction(parent,en,ja,call)
  local mr=OPGG.addRec(parent,en,ja,'0',vtAutoAssembler);mr.Color=OPGG.C_SCRIPT
  mr.Script='[ENABLE]\n{$lua}\nif syntaxcheck then return end\nOPGG.oneShot(memrec,function() '..call..' end)\n{$asm}\n[DISABLE]\n'
  return mr
end
function OPGG.updateYagaraFeedDisplays()
  if not next(OPGG.yagaraFeedDisplays) then return end
  for _,d in pairs(OPGG.yagaraFeedDisplays) do
    local ok,_,items,counts=pcall(OPGG.yagaraFeedSnapshot,d.state)
    if ok then
      d.display.en=string.format('Feed quality %d: %d',d.quality,counts[d.quality+1]);d.display.ja=string.format('餌・品質%d：%d個',d.quality,counts[d.quality+1])
      local name=OPGG.T(d.display.en,d.display.ja)
      if d.display.mr.Description~=name then d.display.mr.Description=name end
    end
  end
end
function OPGG.nativeGameJob(action,targetKey,object,arg,before,callCode,after,context,labels)
  OPGG.require();if OPGG.job then OPGG.fail('Another game-thread job is running.','別のゲーム内処理を実行中です。') end
  local site=OPGG.scan('TrophyType');local target
  if targetKey=='YagaraFeed' then target=OPGG.nativeContract(targetKey,ptr(object),'GiveFeeds',false,{18},1)
  elseif targetKey=='AtelierFrame' then target=OPGG.nativeContract(targetKey,OPGG.elementClass(OPGG.obj(OPGG.app(),'atelierList_'),'game','Atelier'),'ExecuteFrameEvent',true,{},1)
  else OPGG.fail('Unsupported native job.','未対応のゲーム内呼び出しです。') end
  local original=readBytes(site,7,true)
  if not original or original[1]~=0x80 or original[2]~=0x3D or original[7]~=0 then OPGG.fail('Unexpected Unity update entry.','更新処理の命令が想定と異なります。') end
  local page=allocateMemory(4096)
  if not page or page&lt;65536 or page&gt;0x7FFF0000 then OPGG.fail('32-bit job allocation failed.','32bit処理領域を確保できません。') end
  OPGG.dreamPages[#OPGG.dreamPages+1]=page
  local bytes={};for _,v in ipairs(original) do bytes[#bytes+1]=string.format('%02X',v) end
  local code=OPGG.dreamAssembly(page,site,target,table.concat(bytes,' '))
  local needle=string.format('push 0\npush [opggDreamIndex]\npush [opggDreamKind]\npush [opggDreamCharacter]\ncall %X\nadd esp,10',target)
  local a,b=code:find(needle,1,true);if not a then error('Yagara job template mismatch') end
  local body=(before or '')..(callCode or needle)..'\n'..(after or '')
  body=body:gsub('YAGARA_TARGET',string.format('%X',target)):gsub('YAGARA_COUNTER',string.format('%X',page+0x820))
  code=(labels or '')..code:sub(1,a-1)..body..code:sub(b+1)
  local ok,e=autoAssembleCheck(code,true,false);if not ok then error(e,0) end
  if not autoAssemble(code) then error('Yagara job assembly failed') end
  local app=OPGG.app();local saveAddress=OPGG.field(app,'save_');local values={0,object,arg,0,OPGG.static,app,saveAddress,ptr(saveAddress),0}
  for i,v in ipairs(values) do if not writeInteger(page+0x800+(i-1)*4,v) then error('Yagara job preparation failed') end end
  OPGG.job={kind=action=='atelier' and 'atelier' or 'yagara',action=action,page=page,site=site,old=original,start=getTickCount(),pid=OPGG.pid,context=context}
  local delta=(page-site-5)&amp;0xFFFFFFFF;local patch={0xE9,delta&amp;255,(delta&gt;&gt;8)&amp;255,(delta&gt;&gt;16)&amp;255,(delta&gt;&gt;24)&amp;255,0x90,0x90}
  local success,err=OPGG.withPaused(function()
    local now=readBytes(site,7,true);for i,v in ipairs(original) do if not now or now[i]~=v then error('Unity update changed during preparation') end end
    if not writeBytes(site,patch) then writeBytes(site,original);error('Yagara hook write failed') end
    OPGG.job.patched=patch
    if not writeInteger(page+0x800,1) then error('Yagara job activation failed') end
  end)
  if not success then OPGG.cancelAchievementJob(true);error(err,0) end
end
function OPGG.pollYagaraJob()
  local job=OPGG.job;if not job or job.kind~='yagara' then return end
  local state=readInteger(job.page+0x800)
  if state==3 then
    local done=readInteger(job.page+0x820);OPGG.cancelAchievementJob(true)
    print(string.format(OPGG.T('Feed added through game processing: %d','ゲーム内処理で餌を%d個追加しました。'),done));OPGG.updateYagaraFeedDisplays()
  elseif state==4 or getTickCount()-job.start&gt;30000 then
    OPGG.cancelAchievementJob(true)
    print(OPGG.T('Feed addition canceled: game state changed.','ゲーム状態が変わったため餌の追加を中止しました。'))
  end
end
function OPGG.updateInstantAtelier()
  if not OPGG.on.instantBuild or OPGG.job then return end
  for _,atelier in ipairs(OPGG.freshList('atelierList_')) do
    if OPGG.readFlag(atelier,'isRunning_')==1 and OPGG.readFlag(atelier,'isComplete_')==0 and readInteger(OPGG.field(atelier,'remainingHours_'))&gt;0 then
      OPGG.nativeGameJob('atelier','AtelierFrame',0,0,nil,'sub esp,C\npush 0\ncall YAGARA_TARGET\nadd esp,10',nil,nil,nil)
      return
    end
  end
end
function OPGG.pollAtelierJob()
  local job=OPGG.job;if not job or job.kind~='atelier' then return end
  local state=readInteger(job.page+0x800)
  if state==3 then
    OPGG.cancelAchievementJob(true)
  elseif state==4 or getTickCount()-job.start&gt;30000 then
    OPGG.cancelAchievementJob(true);OPGG.on.instantBuild=nil;OPGG.restore('instantBuild')
    print(OPGG.T('[OPGG] Instant build stopped: game state changed or update timed out.','[OPGG] ゲーム状態変更または更新待ちのタイムアウトで即ビルドを停止しました。'))
  end
end
function OPGG.addYagaraFeed()
  local state=OPGG.yagaraburuState();local list,items=OPGG.yagaraFeedSnapshot(state)
  local space=readInteger(OPGG.field(state.animal,'feedsMax_'))-#items
  if space&lt;1 then OPGG.fail('No free feed slots. Increase feed capacity first.','餌の空き枠がありません。先に餌枠上限を増やしてください。') end
  local choice=OPGG.pick(OPGG.T('Feed quality','餌の品質'),{OPGG.T('Quality 0: training +10','品質0：訓練上昇+10'),OPGG.T('Quality 1: training +5','品質1：訓練上昇+5'),OPGG.T('Quality 2: training +2','品質2：訓練上昇+2')})
  if not choice then return end
  local count=OPGG.askInt(OPGG.T('Add feed','餌を追加'),OPGG.T('Quantity (free slots: ','個数（空き枠：')..space..')',1,1,math.min(999,space));if not count then return end
  if not OPGG.yagaraburuAddress(state,'stomach_') then OPGG.fail('Reopen the editor.','エディタを開き直してください。') end
  local character=OPGG.newcomer()
  local guard=string.format([[
cmp dword ptr [%X],%X
jne opggDreamStale
cmp dword ptr [%X],%X
jne opggDreamStale
]],OPGG.field(state.app,'myYagaraburu_'),state.animal,OPGG.field(state.animal,'feedsList_'),list)
  local feedLayout=OPGG.listLayout(list);local feedClass=ptr(ptr(feedLayout.array)+0x20)
  local info=OPGG.fieldInfo(feedClass,'result_');if info.type~=17 or OPGG.enumFieldWidth(info)~=4 then OPGG.fail('Feed enum unsupported.','餌の品質定義が未対応です。') end
  local qualityOffset=info.offset
  local body=string.format([[
mov ebx,[opggDreamCharacter]
mov esi,%X
opggYagaraFeedLoop:
mov edi,[esi+0C]
cmp edi,[ebx+%X]
jge opggYagaraFeedEnd
cmp dword ptr [YAGARA_COUNTER],%X
jge opggYagaraFeedEnd
push 0
push 0
push [opggDreamKind]
push ebx
call YAGARA_TARGET
add esp,10
mov eax,[esi+0C]
sub eax,edi
cmp eax,1
jne opggDreamStale
mov eax,[esi+08]
cmp edi,[eax+0C]
jae opggDreamStale
mov eax,[eax+edi*4+10]
test eax,eax
jz opggDreamStale
mov dword ptr [eax+%X],%X
inc dword ptr [YAGARA_COUNTER]
jmp opggYagaraFeedLoop
opggYagaraFeedEnd:
]],list,OPGG.off(state.animal,'feedsMax_'),count,qualityOffset,choice-1)
  OPGG.nativeGameJob('feed','YagaraFeed',state.animal,character,guard,body,nil,state,'label(opggYagaraFeedLoop)\nlabel(opggYagaraFeedEnd)\n')
end

function OPGG.yagaraburuEditor(parent)
  local state=OPGG.yagaraburuState();OPGG.clearChildren(parent)
  local maxOK,maximum=pcall(OPGG.metadataConstant,'game.Yagaraburu','PARAM_MAX')
  local params={{'SMART','Intelligence','知性'},{'SPEED','Speed','速度'},{'STAMINA','Stamina','体力'}}
  for _,names in ipairs(params) do
    local ok,index=pcall(OPGG.metadataConstant,'game.Yagaraburu.PARAM_ID',names[1])
    local en=names[2]..(maxOK and ' (0-'..maximum..')' or '');local ja=names[3]..(maxOK and '（0～'..maximum..'）' or '')
    if ok then OPGG.row(parent,en,ja,function()return OPGG.yagaraburuAddress(state,nil,index)end)
    else OPGG.addHdr(parent,en..' [Unavailable]',ja..'【使用不可】') end
  end
  for _,f in ipairs({
    {'stomach_','Fullness (internal value)','満腹度（内部値）',vtDword},
    {'hasAura_','Aura display flag (raising screen)','オーラ表示フラグ（育成画面）',vtByte},
    {'raceCount_','Races today (0: can enter)','本日の出走回数（0：出走可能）',vtDword},
    {'totalPrize_','Total prize money','累計獲得賞金',vtDword}
  }) do
    local field=f[1]
    OPGG.row(parent,f[2],f[3],function() return OPGG.yagaraburuAddress(state,field) end,f[4])
  end
  OPGG.addHdr(parent,'Feed inventory / quality 0: +10, 1: +5, 2: +2','餌／品質0：+10、品質1：+5、品質2：+2')
  OPGG.row(parent,'Feed capacity','餌枠上限',function() return OPGG.yagaraburuAddress(state,'feedsMax_') end)
  local ok,list,items,counts=pcall(OPGG.yagaraFeedSnapshot,state)
  if not ok then OPGG.addHdr(parent,'Feed section unavailable','餌の項目：未対応');OPGG.noteOnce('feed-section',list);return end
  for quality=0,2 do
    local mr=OPGG.addHdr(parent,'Feed quality '..quality..': '..counts[quality+1],'餌・品質'..quality..'：'..counts[quality+1]..'個')
    OPGG.yagaraFeedDisplays[mr.ID]={state=state,quality=quality,display=OPGG.dyn[#OPGG.dyn]}
  end
  OPGG.yagaraAction(parent,'Add feed (quality / quantity)','餌を追加（品質・個数）','OPGG.addYagaraFeed()')
  for i,feed in ipairs(items) do
    local index=i-1;local object=feed
    local mr=OPGG.row(parent,'Feed #'..i..' quality (0 / 1 / 2)','餌 #'..i..' 品質（0／1／2）',function()
      if not OPGG.yagaraburuAddress(state,'stomach_') or OPGG.obj(state.animal,'feedsList_')~=list then return nil end
      local array=ptr(list+8);local n=readInteger(list+12)
      if not valid(array) or not n or index&gt;=n or readInteger(array+12)&lt;=index or ptr(array+16+index*4)~=object then return nil end
      return OPGG.field(object,'result_')
    end)
    mr.DropDownList.Text='0:+10\n1:+5\n2:+2';mr.DropDownReadOnly=true;mr.DropDownDescriptionOnly=false;mr.DisplayAsDropDownListItem=true
  end
end

function OPGG.player(parent) OPGG.require(); OPGG.editCharacter(parent,OPGG.newcomer()) end
function OPGG.characters(parent)
  OPGG.require(); local ps=OPGG.list('characterList_'); local names={};local ids={};local contexts={}
  for i,p in ipairs(ps) do names[i]=OPGG.label(p);ids[i]=OPGG.dataId(p);contexts[i]=OPGG.characterContext(p) end
  local i=OPGG.pick(OPGG.T('Character editor (search)','キャラクターエディタ（検索）'),names)
  if i then OPGG.editCharacter(parent,OPGG.resolveCharacter(contexts[i])) end
end
-- Customer membership must be read fresh, even if list headers were reused.

function OPGG.customerSnapshot()
  local game=OPGG.obj(OPGG.app(),'frmGame_');local map=OPGG.obj(game,'map_');local result={}
  for _,p in ipairs(OPGG.freshList('customerList_')) do
    local ok,entry=pcall(function()
      local class=ptr(p)
      if not OPGG.isA(p,'game','Customer') then return end
      if OPGG.readFlag(p,'delete_')~=0 or OPGG.obj(p,'map_')~=map then return end
      local character=OPGG.obj(p,'character_')
      if not valid(character) then return end
      local key=table.concat({hex(p),hex(class),hex(character),hex(map),tostring(readInteger(OPGG.field(p,'id_'))),hex(ptr(OPGG.field(p,'code_')))},':')
      return {object=p,character=character,key=key}
    end)
    if ok and entry then result[#result+1]=entry end
  end
  return result
end
function OPGG.currentCustomer(key)
  for _,entry in ipairs(OPGG.customerSnapshot()) do if entry.key==key then return entry end end
end
-- The game's customer register contains Characters, not the live Customer actors.
OPGG.customerOrder={}
function OPGG.gameCustomerList()
  local game=OPGG.obj(OPGG.app(),'frmGame_');local manager=OPGG.obj(game,'formManager_')
  local stack=OPGG.obj(manager,'formStack_');local forms=OPGG.items(OPGG.obj(stack,'list_'))
  for i=#forms,1,-1 do
    local form=forms[i]
    if readString(ptr(ptr(form)+8),128)=='SubFormCharacterCustomerListSub' and readInteger(OPGG.field(form,'formProcMode_'))~=4 then
      return OPGG.items(OPGG.obj(form,'characterList_'))
    end
  end
end
function OPGG.registeredCustomerSnapshot()
  local characters=OPGG.gameCustomerList();local result={}
  if characters then
    OPGG.customerOrder={}
    for i,p in ipairs(characters) do OPGG.customerOrder[OPGG.dataId(p)]=i end
  else
    characters={}
    for _,p in ipairs(OPGG.freshList('characterList_')) do
      local data=OPGG.obj(p,'data_')
      if OPGG.readFlag(p,'isFind_')~=0 and OPGG.readFlag(data,'&lt;isCustomer_&gt;k__BackingField')~=0 then characters[#characters+1]=p end
    end
    table.sort(characters,function(a,b)
      local aid,bid=OPGG.dataId(a),OPGG.dataId(b);local ar,br=OPGG.customerOrder[aid],OPGG.customerOrder[bid]
      if ar or br then return (ar or math.huge)&lt;(br or math.huge) end
      local function rank(p)
        if OPGG.readFlag(p,'isFan_')~=0 then return 0 end
        if readInteger(OPGG.field(p,'regularVisitCount_'))&gt;0 then return 1 end
        if OPGG.readFlag(p,'isRegular_')~=0 then return 2 end
        return 3
      end
      local ra,rb=rank(a),rank(b);if ra~=rb then return ra&lt;rb end;return aid&lt;bid
    end)
  end
  for _,p in ipairs(characters) do result[#result+1]={character=p,key='character:'..hex(p)..':'..OPGG.dataId(p)} end
  return result
end
function OPGG.customers(parent)
  local boundary=OPGG.captureBoundary();OPGG.clearChildren(parent)
  local function refresh()
    local entries=OPGG.registeredCustomerSnapshot();local names,keys={},{}
    for i,entry in ipairs(entries) do names[i]=OPGG.label(entry.character);keys[i]=entry.key end
    return names,keys
  end
  local names,keys=refresh()
  local i=OPGG.pick(OPGG.T('Customers (game list)','お客様一覧（ゲーム内一覧）')..' ('..#names..')',names,false)
  if not i then return end
  OPGG.assertBoundary(boundary)
  local key=keys[i]
  local selected
  for _,entry in ipairs(OPGG.registeredCustomerSnapshot()) do if entry.key==key then selected=entry;break end end
  if not selected then OPGG.fail('Customer registration changed. Reopen the editor.','お客様の登録状態が変わりました。開き直してください。') end
  OPGG.editCharacter(parent,selected.character)
  local active
  for _,entry in ipairs(OPGG.customerSnapshot()) do if entry.character==selected.character then active=entry;break end end
  if not active then OPGG.addHdr(parent,'Not currently visiting','現在は来店していません');return end
  OPGG.addHdr(parent,'Live customer state','来店中のお客様の状態')
  local session=OPGG.session;local actorKey=active.key
  local function address(field)
    return function()
      if session~=OPGG.session then return nil end
      local entry=OPGG.currentCustomer(actorKey)
      if entry then return OPGG.field(entry.object,field) end
    end
  end
  for _,f in ipairs({{'stamina_','Stamina','体力'},{'staminaMax_','Max stamina','最大体力'},{'lobbyCount_','Lobby wait count','待機カウント'},{'satTableCount_','Tables used','利用テーブル数'}}) do OPGG.row(parent,f[2],f[3],address(f[1])) end
end

OPGG.CATEGORIES={
 {'ingredientList_','Ingredients','食材','Ingredient',99},
 {'chipModelList_','Furniture / decorations','家具・装飾','ChipModel',99},
 {'architectureList_','Architecture','建築物','Architecture',99},
 {'toppingList_','Toppings','トッピング','Topping',99},
 {'treasureList_','Items / gifts / treasure','アイテム・贈り物・宝物','Treasure',99},
}
function OPGG.category() local n={};for i,c in ipairs(OPGG.CATEGORIES) do n[i]=OPGG.T(c[2],c[3]) end; local i=OPGG.pick(OPGG.T('Category','カテゴリ'),n);return i and OPGG.CATEGORIES[i] end
function OPGG.inventory(parent)
  local boundary=OPGG.captureBoundary();local cat=OPGG.category();if not cat then return end;OPGG.assertBoundary(boundary)
  OPGG.clearChildren(parent)
  for _,p in ipairs(OPGG.list(cat[1])) do
    local id=OPGG.dataId(p); local field=cat[1];local context=OPGG.dataContext(field,p)
    local en,ja=OPGG.namePair(p);en=en..' [ID '..id..']';ja=ja..' [ID '..id..']'
    OPGG.row(parent,en,ja,function() return OPGG.field(OPGG.resolveData(context),'haveNum_') end)
  end
end

function OPGG.changeSpeed(mr)
  OPGG.ensureProcess();local pid=OPGG.pid;local session=OPGG.session
  local s=inputQuery(OPGG.T('Game speed','ゲーム速度'),OPGG.T('Multiplier: 0.1 - 10 (1 = normal)','倍率：0.1～10（1＝通常速度）'),tostring(OPGG.speedValue or 1))
  if not s then error(OPGG.T('Cancelled.','キャンセルしました。'),0) end
  local n=tonumber(s)
  if not n or n~=n or n&lt;0.1 or n&gt;10 then OPGG.fail('Range: 0.1-10','範囲: 0.1～10') end
  if OPGG.pid~=pid or OPGG.session~=session then OPGG.fail('Game connection changed; retry.','ゲームの接続が変わりました。再実行してください。')end
  local previous=OPGG.speedValue;OPGG.speedValue=n
  local ok,result=pcall(OPGG.feature,'speed',true,mr)
  if not ok or result==false then OPGG.speedValue=previous;if not ok then error(result,0) end end
end
-- Execute Trophy.Unlock on the game's own Trophy.Update thread.
-- No executeCodeEx, native API calls from remote threads, or nearby allocation.
function OPGG.nextShipExpansion(allowMax)
  local choices={}
  for _,a in ipairs(OPGG.list('architectureList_')) do
    local d=OPGG.obj(a,'data_')
    if readInteger(OPGG.field(d,'&lt;category_&gt;k__BackingField'))==OPGG.metadataConstant('data.ArchitectureData.CATEGORY','BARATIE_1F') and OPGG.readFlag(d,'&lt;isDummy_&gt;k__BackingField')==0 then
      choices[#choices+1]={object=a,id=OPGG.dataId(a)}
    end
  end
  table.sort(choices,function(a,b)return a.id&lt;b.id end)
  if #choices==0 then OPGG.fail('Ship expansion data is unavailable.','船の拡張データを取得できません。') end
  for _,entry in ipairs(choices) do if OPGG.readFlag(entry.object,'isDestroy_')==0 then return entry.object end end
  if allowMax then return end
  OPGG.fail('The ship is already fully expanded.','船はすでに最大まで拡張されています。')
end
function OPGG.shipAssembly(page,site,target,original,requestFind)
  local code=OPGG.dreamAssembly(page,site,target,original)
  local from='push 0\npush [opggDreamIndex]\npush [opggDreamKind]\npush [opggDreamCharacter]\ncall '..string.format('%X',target)..'\nadd esp,10'
  local replacement=string.format([=[mov eax,[%X]
mov eax,[eax]
cmp eax,[%X]
jne opggDreamStale
mov eax,[%X]
cmp byte ptr [eax],0
jne opggDreamStale
sub esp,8
push 0
push [opggDreamCharacter]
call %X
add esp,10
sub esp,4
push 0
push 0
push [opggDreamKind]
call %X
add esp,10]=],page+0x820,page+0x824,page+0x828,target,requestFind)
  local at=assert(code:find(from,1,true));return code:sub(1,at-1)..replacement..code:sub(at+#from)
end
function OPGG.shipExpansion()
  OPGG.require()
  if OPGG.job then OPGG.fail('Another game-thread operation is running.','別の処理を実行中です。完了後に再実行してください。') end
  local app=OPGG.app();local game=OPGG.obj(app,'frmGame_');local mapField=OPGG.field(game,'map_');local map=ptr(mapField)
  local category=readInteger(OPGG.field(OPGG.obj(map,'mapData_'),'&lt;category_&gt;k__BackingField'))
  if category~=0 then OPGG.fail('Return to the ship restaurant first.','船のレストランに戻ってから実行してください。') end
  local architecture=OPGG.nextShipExpansion();local id=OPGG.dataId(architecture)
  local request=OPGG.find('requestList_',0)
  local rd=OPGG.obj(request,'data_');if readInteger(OPGG.field(rd,'&lt;type_&gt;k__BackingField'))~=1 then OPGG.fail('Unexpected expansion request.','拡張の要望データが想定と異なります。') end
  local site=OPGG.scan('TrophyType');local target=OPGG.nativeContract('ShipExpansionFind',OPGG.elementClass(OPGG.obj(OPGG.app(),'architectureList_'),'game','Architecture'),'Find',false,{},1);local requestFind=OPGG.nativeContract('ShipRequestFind',OPGG.elementClass(OPGG.obj(OPGG.app(),'requestList_'),'game','Request'),'Find',false,{2},1);local original=readBytes(site,7,true)
  if not original or original[1]~=0x80 or original[2]~=0x3D or original[7]~=0 then OPGG.fail('Unexpected update entry.','更新処理の命令が想定と異なります。') end
  local page=allocateMemory(4096)
  if not page or page&lt;65536 or page&gt;0x7FFF0000 then OPGG.fail('Ship job allocation failed.','船の拡張処理領域を確保できません。') end
  OPGG.dreamPages[#OPGG.dreamPages+1]=page
  local bytes={};for _,v in ipairs(original) do bytes[#bytes+1]=string.format('%02X',v) end
  local code=OPGG.shipAssembly(page,site,target,table.concat(bytes,' '),requestFind);local ok,e=autoAssembleCheck(code,true,false)
  if not ok then error(e,0) end
  if not autoAssemble(code) then OPGG.fail('Ship job assembly failed.','船の拡張処理を組み立てられません。') end
  local saveAddress=OPGG.field(app,'save_');local values={0,architecture,request,0,OPGG.static,app,saveAddress,ptr(saveAddress),mapField,map,OPGG.field(architecture,'isDestroy_')}
  for i,v in ipairs(values) do if not writeInteger(page+0x800+(i-1)*4,v) then OPGG.fail('Ship job preparation failed.','船の拡張処理の準備に失敗しました。') end end
  OPGG.job={kind='ship',page=page,site=site,old=original,start=getTickCount(),pid=OPGG.pid,architecture=architecture,architectureId=id,map=map,request=request,save=ptr(saveAddress)}
  local delta=(page-site-5)&amp;0xFFFFFFFF;local patch={0xE9,delta&amp;255,(delta&gt;&gt;8)&amp;255,(delta&gt;&gt;16)&amp;255,(delta&gt;&gt;24)&amp;255,0x90,0x90}
  local success,err=OPGG.withPaused(function()
    local now=readBytes(site,7,true);for i,v in ipairs(original) do if not now or now[i]~=v then error('Update code changed') end end
    if not writeBytes(site,patch) then writeBytes(site,original);error('Ship hook write failed') end
    OPGG.job.patched=patch;if not writeInteger(page+0x800,1) then error('Ship job activation failed') end
  end)
  if not success then OPGG.cancelAchievementJob(true);error(err,0) end
end
function OPGG.shipPanel(permit)
  local game=OPGG.obj(OPGG.app(),'frmGame_');if OPGG.obj(game,'map_')~=permit.map then return end
  local manager=OPGG.obj(game,'formManager_');local stack=OPGG.obj(manager,'formStack_');local forms=OPGG.items(OPGG.obj(stack,'list_'));local form=forms[#forms]
  if not valid(form) or readString(ptr(ptr(form)+8),128)~='SubFormChallengeBreakSub' or readInteger(OPGG.field(form,'formProcMode_'))==4 then return end
  local callback=OPGG.obj(form,'callback_');local receiver=OPGG.obj(callback,'m_target')
  if OPGG.obj(receiver,'&lt;&gt;4__this')==permit.architecture and OPGG.obj(receiver,'map')==permit.map then return form,stack end
end
function OPGG.clearShipPermit(restore)
  local permit=OPGG.shipPermit;OPGG.shipPermit=nil
  if not restore or not permit or permit.pid~=getOpenedProcessID() or not valid(permit.save) or OPGG.obj(OPGG.app(),'save_')~=permit.save then return end
  local form,stack=OPGG.shipPanel(permit)
  if form and permit.form==form and permit.original then
    local ok,e=OPGG.withPaused(function()
      if OPGG.shipPanel(permit)~=form then return end
      for _,f in ipairs(permit.original) do
        local write=f.float and writeFloat or (f.byte and writeBytes or writeInteger)
        if not write(f.float and OPGG.fieldStorage(form,f.name,(f.offset or 0)+4)+(f.offset or 0) or OPGG.checkedAddress(OPGG.field(form,f.name),f.byte and vtByte or vtDword),f.value) then error('Ship requirement restoration failed') end
      end
    end)
    if not ok then error(e,0) end
  end
end
function OPGG.updateShipPermit()
  local permit=OPGG.shipPermit;if not permit then return end
  if permit.pid~=getOpenedProcessID() or OPGG.obj(OPGG.app(),'save_')~=permit.save then OPGG.shipPermit=nil;return end
  if OPGG.readFlag(permit.architecture,'isDestroy_')~=0 then OPGG.shipPermit=nil;return end
  local form,stack=OPGG.shipPanel(permit);if not form or permit.form==form then return end
  local fields={{'memberLimit_',0,false},{'cost_',0,false},{'isNotEnoughCost_',0,true},{'isPossibleDestroy_',1,true}};local originals={}
  for _,f in ipairs(fields) do local address=OPGG.field(form,f[1]);originals[#originals+1]={name=f[1],value=f[3] and readBytes(address,1) or readInteger(address),byte=f[3]} end
  local colorOK,color=pcall(OPGG.fieldStorage,form,'memberNumColor_',16)
  if colorOK then for i=0,3 do originals[#originals+1]={name='memberNumColor_',offset=i*4,value=readFloat(color+i*4),float=true} end end
  local ok,e=OPGG.withPaused(function()
    if OPGG.shipPanel(permit)~=form then error('Expansion screen changed') end
    for _,f in ipairs(fields) do local write=f[3] and writeBytes or writeInteger;if not write(OPGG.checkedAddress(OPGG.field(form,f[1]),f[3] and vtByte or vtDword),f[2]) then error('Expansion field write failed') end end
    if colorOK then for i=0,3 do if not writeFloat(color+i*4,i==3 and 1 or 0) then error('Expansion color write failed') end end end
  end)
  if not ok then error(e,0) end
  permit.form=form;permit.original=originals
end
function OPGG.pollShipJob()
  local job=OPGG.job;if not job or job.kind~='ship' then return end
  local state=readInteger(job.page+0x800)
  if state==3 then
    local confirmed=OPGG.readFlag(job.architecture,'isFind_')==1 and OPGG.readFlag(job.architecture,'isDestroy_')==0
    OPGG.cancelAchievementJob(true)
    if not confirmed then OPGG.fail('Expansion request registration was not confirmed.','拡張の要望登録を確認できませんでした。') end
    OPGG.clearShipPermit(true)
    OPGG.shipPermit={pid=job.pid,save=job.save,architecture=job.architecture,map=job.map}
    print(OPGG.T('Ship expansion request registered. Reopen the Requests list and select Franky.','船の拡張の要望を登録しました。要望一覧を開き直し、フランキーの要望を選んでください。'));return
  end
  if state==4 or getTickCount()-job.start&gt;30000 then OPGG.cancelAchievementJob(true);OPGG.fail('Ship request cancelled: state changed or timed out.','状態変更またはタイムアウトにより拡張の要望登録を中止しました。') end
end
function OPGG.setShipExpansion(on)
  if not on then
    OPGG.shipMode=nil
    if OPGG.job and OPGG.job.kind=='ship' then OPGG.cancelAchievementJob(OPGG.alive()) end
    OPGG.clearShipPermit(OPGG.alive());return
  end
  OPGG.require()
  OPGG.nextShipExpansion()
  OPGG.shipMode={pid=OPGG.pid,save=OPGG.obj(OPGG.app(),'save_')}
  OPGG.updateShipExpansion()
  OPGG.updateShipPermit()
end
function OPGG.updateShipExpansion()
  local mode=OPGG.shipMode;if not mode then return end
  if mode.pid~=getOpenedProcessID() or OPGG.obj(OPGG.app(),'save_')~=mode.save then OPGG.setShipExpansion(false);return end
  if OPGG.job then return end
  local architecture=OPGG.nextShipExpansion(true)
  if not architecture then
    OPGG.setShipExpansion(false)
    local row=getAddressList().getMemoryRecordByID(403);if row then row.Active=false end
    print(OPGG.T('Ship is fully expanded; unconditional expansion disabled.','船は最大拡張済みです。無条件拡張を解除しました。'));return
  end
  local permit=OPGG.shipPermit
  if permit and permit.architecture==architecture then return end
  OPGG.clearShipPermit(true)
  local game=OPGG.obj(OPGG.app(),'frmGame_');local map=OPGG.obj(game,'map_')
  if readInteger(OPGG.field(OPGG.obj(map,'mapData_'),'&lt;category_&gt;k__BackingField'))~=0 then return end
  local request=OPGG.find('requestList_',0)
  if OPGG.readFlag(architecture,'isFind_')==1 then
    OPGG.shipPermit={pid=mode.pid,save=mode.save,architecture=architecture,map=map};return
  end
  if readInteger(OPGG.field(game,'state_'))~=0 then return end
  local manager=OPGG.obj(game,'formManager_');local stack=OPGG.obj(manager,'formStack_');local forms=OPGG.items(OPGG.obj(stack,'list_'));local top=forms[#forms]
  if not valid(top) then return end
  local name=readString(ptr(ptr(top)+8),128)
  if name~='GameForm' and name~='MenuSub' and name~='SubFormRequestListSub' then return end
  OPGG.shipExpansion()
end

function OPGG.forceBanquet()
  OPGG.require()
  if OPGG.job then OPGG.fail('Another game-thread job is running.','別のゲーム内処理を実行中です。') end
  local app=OPGG.app();local game=OPGG.obj(app,'frmGame_')
  local manager=OPGG.obj(game,'formManager_');local stack=OPGG.obj(manager,'formStack_');local list=OPGG.obj(stack,'list_');OPGG.requireListABI(list);local forms=OPGG.items(list)
  local top=forms[#forms]
  if top~=game or readInteger(OPGG.field(game,'state_'))~=0 or readInteger(OPGG.field(game,'formProcMode_'))==4 then
    OPGG.fail('Close menus and result screens; run during normal play.','メニュー・結果画面を閉じ、通常プレイ中に実行してください。')
  end
  if readInteger(OPGG.saveAddr('ints','SAVEI_FEVER_TIME'))&gt;0 then OPGG.fail('A banquet is already active.','すでに宴の開催中です。') end
  local block=OPGG.scan('FeverStart')
  local function callTarget(offset)
    if readBytes(block+offset,1)~=0xE8 then OPGG.fail('Banquet call signature mismatch.','宴の呼び出し命令が一致しません。') end
    local d=readInteger(block+offset+1);if d&gt;=0x80000000 then d=d-0x100000000 end
    return block+offset+5+d
  end
  local cell=ptr(block+0xC2);local cls=ptr(cell)
  if not valid(cls) or readString(ptr(cls+8),128)~='SubFormUtageStartSub' or readString(ptr(cls+12),128)~='form' then
    OPGG.fail('Banquet resources are not initialized yet; allow normal play to advance first.','宴のデータが未初期化です。通常プレイを少し進めてから実行してください。')
  end
  local nativeNew=callTarget(0xC6);local ctor=callTarget(0xD0);local push=callTarget(0xD9)
  local timeIndex=OPGG.saveConstant('SAVEI_FEVER_TIME');local valueIndex=OPGG.saveConstant('SAVEI_FEVER_VALUE');local countIndex=OPGG.saveConstant('SAVEI_FEVER_EXECUTE_COUNT')
  local saveArray=OPGG.obj(OPGG.obj(app,'save_'),'ints')
  OPGG.arrayElement(saveArray,timeIndex,8);OPGG.arrayElement(saveArray,valueIndex,8);OPGG.arrayElement(saveArray,countIndex,8)
  local timeOffset=16+timeIndex*4;local valueOffset=16+valueIndex*4;local countOffset=16+countIndex*4
  if readInteger(block+11)~=timeOffset then OPGG.fail('Banquet save definition mismatch.','宴のセーブ定義が一致しません。')end
  local duration=readInteger(block+15);local cap=readInteger(block+0x9E)
  if not duration or duration&lt;1 or duration&gt;10000 or not cap or cap&lt;1 or cap&gt;1000000 or readBytes(block+0x9D,1)~=0x68 then OPGG.fail('Banquet constants unsupported.','宴の定義値を検証できません。')end

  local site=OPGG.scan('TrophyType');local original=readBytes(site,7,true)
  if not original or original[1]~=0x80 or original[2]~=0x3D or original[7]~=0 then OPGG.fail('Unexpected Unity update entry.','更新処理の命令が想定と異なります。') end
  local page=allocateMemory(4096)
  if not page or page&lt;65536 or page&gt;0x7FFF0000 then OPGG.fail('32-bit job allocation failed.','32bit処理領域を確保できません。') end
  OPGG.dreamPages[#OPGG.dreamPages+1]=page
  local bytes={};for _,v in ipairs(original) do bytes[#bytes+1]=string.format('%02X',v) end
  local body=string.format([[
mov eax,[%X]
cmp eax,%X
jne opggDreamStale
cmp dword ptr [%X],0
jne opggDreamStale
cmp dword ptr [%X],4
je opggDreamStale
cmp dword ptr [%X],%X
jne opggDreamStale
cmp dword ptr [%X],%X
jne opggDreamStale
cmp dword ptr [%X],%X
jne opggDreamStale
mov ebx,[%X]
cmp ebx,%X
jne opggDreamStale
cmp dword ptr [ebx+0C],2E
jbe opggDreamStale
cmp dword ptr [ebx+C0],0
jg opggDreamStale
cmp dword ptr [%X],%X
jne opggDreamStale
sub esp,0C
push %X
call %X
add esp,10
 test eax,eax
jz opggDreamStale
mov esi,eax
sub esp,08
push 0
push esi
call %X
add esp,10
mov dword ptr [ebx+C0],9
mov dword ptr [ebx+C4],0
mov eax,[ebx+C8]
cmp eax,3E7
jge opggFeverCountDone
inc eax
mov [ebx+C8],eax
opggFeverCountDone:
sub esp,04
push 0
push esi
push %X
call %X
add esp,10
]],OPGG.field(app,'frmGame_'),game,OPGG.field(game,'state_'),OPGG.field(game,'formProcMode_'),list+8,ptr(list+8),list+12,readInteger(list+12),list+16,readInteger(list+16),OPGG.field(OPGG.obj(app,'save_'),'ints'),OPGG.obj(OPGG.obj(app,'save_'),'ints'),cell,cls,cls,nativeNew,ctor,game,push)
  body=body:gsub('%[ebx%+C0%]','[ebx+'..hex(timeOffset)..']'):gsub('%[ebx%+C4%]','[ebx+'..hex(valueOffset)..']'):gsub('%[ebx%+C8%]','[ebx+'..hex(countOffset)..']')
  body=body:gsub('cmp dword ptr %[ebx%+0C%],2E','cmp dword ptr [ebx+0C],'..hex(math.max(timeIndex,valueIndex,countIndex))):gsub('mov dword ptr (%[ebx%+%x+%]),9','mov dword ptr %1,'..hex(duration)):gsub('cmp eax,3E7','cmp eax,'..hex(cap))
  local code=OPGG.dreamAssembly(page,site,0,table.concat(bytes,' '))
  local needle='push 0\npush [opggDreamIndex]\npush [opggDreamKind]\npush [opggDreamCharacter]\ncall 0\nadd esp,10'
  local start,finish=code:find(needle,1,true)
  if not start then error('Banquet worker template mismatch') end
  code=code:sub(1,start-1)..body..code:sub(finish+1)
  code='label(opggFeverCountDone)\n'..code
  local ok,e=autoAssembleCheck(code,true,false);if not ok then error(e,0) end
  if not autoAssemble(code) then OPGG.fail('Banquet job assembly failed.','宴の処理を組み立てられません。') end
  local saveAddress=OPGG.field(app,'save_');local values={0,0,0,0,OPGG.static,app,saveAddress,ptr(saveAddress)}
  for i,v in ipairs(values) do if not writeInteger(page+0x800+(i-1)*4,v) then error('Banquet job preparation failed') end end
  OPGG.job={kind='banquet',page=page,site=site,old=original,start=getTickCount(),pid=OPGG.pid}
  local delta=(page-site-5)&amp;0xFFFFFFFF;local patch={0xE9,delta&amp;255,(delta&gt;&gt;8)&amp;255,(delta&gt;&gt;16)&amp;255,(delta&gt;&gt;24)&amp;255,0x90,0x90}
  local success,err=OPGG.withPaused(function()
    local now=readBytes(site,7,true);for i,v in ipairs(original) do if not now or now[i]~=v then error('Unity update changed during preparation') end end
    if not writeBytes(site,patch) then writeBytes(site,original);error('Banquet hook write failed') end
    OPGG.job.patched=patch
    if not writeInteger(page+0x800,1) then error('Banquet activation failed') end
  end)
  if not success then OPGG.cancelAchievementJob(true);error(err,0) end
end
function OPGG.pollBanquetJob()
  local job=OPGG.job;if not job or job.kind~='banquet' then return end
  local state=readInteger(job.page+0x800)
  if state==3 then
    OPGG.cancelAchievementJob(true)
    print(OPGG.T('Banquet start requested through the normal game presentation.','ゲーム内の開始演出を通して宴を開始しました。'))
  elseif state==4 or getTickCount()-job.start&gt;30000 then
    OPGG.cancelAchievementJob(true)
    OPGG.fail('Banquet was canceled because the game state changed. Retry during normal play.','ゲーム状態が変わったため宴の開始を中止しました。通常プレイ中に再実行してください。')
  end
end

function OPGG.achievementInfo()
  OPGG.require();local c=OPGG.class('kairo.unity.util','Trophy');local st=ptr(c+0x5C)
  if not valid(st) then OPGG.fail('Trophy static data unavailable.','実績管理データ未検出。') end
  local ids=ptr(st+OPGG.offClass(c,'STEAM_ACHIEVEMENT_IDS'))
  local count=ids and readInteger(ids+12)
  if not count or count&lt;1 or count&gt;500 then OPGG.fail('Invalid achievement ID array.','実績ID配列が不正です。') end
  local names={};for i=0,count-1 do local name=OPGG.str(ptr(OPGG.arrayElement(ids,i,18)));if name~='' then names[#names+1]={index=i,name=name} end end
  return {class=c,static=st,ids=ids,count=count,names=names,ready=readBytes(st+OPGG.offClass(c,'m_bStatsValid'),1)==1}
end
function OPGG.achievements(unlock)
  if unlock~=true then OPGG.fail('Explicit unlock request required.','実績解除の明示指定が必要です。') end
  local info=OPGG.achievementInfo()
  if not info.ready then OPGG.fail('Steam statistics are not ready.','Steamの実績情報がまだ準備できていません。') end
  if OPGG.job then OPGG.fail('An achievement job is already pending.','実績処理が実行待ちです。') end
  local site=OPGG.scan('TrophyType');local target=OPGG.nativeContract('TrophyUnlock',OPGG.class('kairo.unity.util','Trophy'),'Unlock',true,{8,2},1)
  local orig=readBytes(site,7,true)
  if not orig or orig[1]~=0x80 or orig[2]~=0x3D or orig[7]~=0 then OPGG.fail('Unexpected Trophy.Update entry.','Trophy.Updateの命令が想定と異なります。') end
  local page=OPGG.jobPage
  if not page then
    page=allocateMemory(4096)
    if not page or page&lt;65536 or page&gt;0x7FFF0000 then OPGG.fail('32-bit job page allocation failed.','32bit処理領域の確保失敗。') end
    OPGG.jobPage=page -- Keep until process exits; never free while code can be in flight.
  end
  local db={};for _,b in ipairs(orig) do db[#db+1]=string.format('%02X',b) end
  local code=OPGG.achievementAssembly(page,site,target,table.concat(db,' '))
  local ok,err=autoAssembleCheck(code,true,false)
  if not ok then OPGG.fail('Job syntax check failed: '..tostring(err),'実績処理の構文検査失敗: '..tostring(err)) end
  if not autoAssemble(code) then OPGG.fail('Job assembly failed.','実績処理の組み立て失敗。') end
  writeInteger(page+0x800,0);writeInteger(page+0x804,info.count);writeInteger(page+0x808,info.ids);writeInteger(page+0x80C,0)
  OPGG.job={page=page,site=site,old=orig,total=#info.names,start=getTickCount(),pid=OPGG.pid}
  local delta=(page-site-5)&amp;0xFFFFFFFF
  local patch={0xE9,delta&amp;255,(delta&gt;&gt;8)&amp;255,(delta&gt;&gt;16)&amp;255,(delta&gt;&gt;24)&amp;255,0x90,0x90}
  local success,msg=OPGG.withPaused(function()
    local now=readBytes(site,7,true)
    for i,b in ipairs(orig) do if not now or now[i]~=b then error('Trophy.Update changed during preparation') end end
    if not writeBytes(site,patch) then writeBytes(site,orig);error('hook write failed') end
    OPGG.job.patched=patch
    if not writeInteger(page+0x800,1) then error('job activation write failed') end
  end)
  if not success then OPGG.cancelAchievementJob(true);error(msg) end
  print(OPGG.T('Achievement requests queued on the game thread.','ゲームスレッドで実績解除を実行待ちです。'))
end
function OPGG.achievementAssembly(page,site,target,original)
  return string.format([[
label(ggJobExit)
label(ggJobLoop)
label(ggJobNext)
label(ggJobDone)
%X:
pushfd
pushad
mov ebp,esp
sub esp,210
and esp,FFFFFFF0
fxsave [esp]
cmp dword ptr [%X],1
jne ggJobExit
mov dword ptr [%X],2
xor esi,esi
ggJobLoop:
cmp dword ptr [%X],2
jne ggJobExit
cmp esi,[%X]
jae ggJobDone
mov eax,[%X]
mov eax,[eax+esi*4+10]
test eax,eax
je ggJobNext
cmp dword ptr [eax+8],0
jle ggJobNext
push 0
push 0
push esi
call %X
add esp,0C
inc dword ptr [%X]
ggJobNext:
inc esi
jmp ggJobLoop
ggJobDone:
mov dword ptr [%X],3
ggJobExit:
fxrstor [esp]
mov esp,ebp
popad
popfd
db %s
jmp %X
]],page,page+0x800,page+0x800,page+0x800,page+0x804,page+0x808,target,page+0x80C,page+0x800,original,site+7)
end
function OPGG.withPaused(fn)
  pause();local ok,e=pcall(fn);unpause();return ok,e
end
function OPGG.cancelAchievementJob(restore)
  local job=OPGG.job;if not job then return end
  if restore and job.pid==getOpenedProcessID() then
    local ok,e=OPGG.withPaused(function()
      writeInteger(job.page+0x800,0)
      if job.patched then
        local bytes=readBytes(job.site,7,true)
        for i,b in ipairs(job.patched) do if not bytes or bytes[i]~=b then error('Trophy.Update changed externally') end end
        if not writeBytes(job.site,job.old) then error('Trophy.Update restore failed') end
      end
    end)
    if not ok then OPGG.fail('Achievement hook restore failed: '..tostring(e),'実績フック復元失敗: '..tostring(e)) end
  end
  OPGG.job=nil
end
function OPGG.pollAchievementJob()
  if OPGG.job and OPGG.job.kind=='atelier' then OPGG.pollAtelierJob();return end
  if OPGG.job and OPGG.job.kind=='yagara' then OPGG.pollYagaraJob();return end
  if OPGG.job and OPGG.job.kind=='banquet' then OPGG.pollBanquetJob();return end
  if OPGG.job and OPGG.job.kind=='ship' then OPGG.pollShipJob();return end
  if OPGG.job and OPGG.job.kind=='item' then OPGG.pollItemJob();return end
  if OPGG.job and OPGG.job.kind=='dream' then OPGG.pollDreamJob();return end
  local job=OPGG.job;if not job then return end
  local state=readInteger(job.page+0x800)
  if state==3 then
    local done=readInteger(job.page+0x80C);OPGG.cancelAchievementJob(true)
    print(OPGG.T('Achievement requests completed: ','実績解除要求完了: ')..done..'/'..job.total..OPGG.T(' (server sync is asynchronous).','（サーバー同期は非同期）。'))
  elseif getTickCount()-job.start&gt;30000 then
    OPGG.cancelAchievementJob(true);print(OPGG.T('Achievement job timed out; hook restored.','実績処理がタイムアウトしたためフックを復元しました。'))
  end
end

function OPGG.statusReport()
  OPGG.require(); print('[OPGG] '..OPGG.CHEATVER..' PID='..OPGG.pid..' AppData='..hex(OPGG.app()))
  print('Berry='..tostring(readQword(OPGG.saveAddr('lngs','SAVEL_MONEY')))..' Coin='..readInteger(OPGG.point('PIRATE'))..' Heart='..readInteger(OPGG.point('HEART')))
  for _,c in ipairs(OPGG.CATEGORIES) do print(c[2]..': '..#OPGG.list(c[1])) end
  print('Characters: '..#OPGG.list('characterList_')..' Customers: '..#OPGG.list('customerList_'))
end
OPGG.FIELD_TYPES={
 ['.Yagaraburu.Feeds.delete_']=2,
 ['.Yagaraburu.Feeds.result_']=17,
 ['data.CharacterData.dreamDefinitionList_']=21,
 ['data.Data.characterLevelData_']=29,
 ['data.Data.mapData_']=29,
 ['data.Data.teamData_']=29,
 ['form.GameForm.callback_']=18,
 ['form.GameForm.map_']=18,
 ['form.GameForm.requestList_']=21,
 ['form.GameForm.state_']=8,
 ['form.MyFormBase.result_']=8,
 ['form.SubFormChallengeBreakSub.callback_']=18,
 ['form.SubFormChallengeBreakSub.isPossibleDestroy_']=2,
 ['form.SubFormCharacterCustomerListSub.callback_']=18,
 ['form.SubFormCharacterCustomerListSub.characterList_']=21,
 ['form.SubFormCharacterCustomerListSub.type_']=17,
 ['game.Architecture.data_']=18,
 ['game.Architecture.haveNum_']=8,
 ['game.Architecture.isDestroy_']=2,
 ['game.Architecture.isFind_']=2,
 ['game.Atelier.data_']=18,
 ['game.Atelier.isComplete_']=2,
 ['game.Atelier.isRunning_']=2,
 ['game.Atelier.remainingHours_']=8,
 ['game.Character.bestPaymentAmount_']=8,
 ['game.Character.data_']=18,
 ['game.Character.exp_']=8,
 ['game.Character.index_']=8,
 ['game.Character.isExecuteFavoriteGift_']=2,
 ['game.Character.isFan_']=2,
 ['game.Character.isFavorite_']=2,
 ['game.Character.isFind_']=2,
 ['game.Character.isInjured_']=2,
 ['game.Character.isRegular_']=2,
 ['game.Character.isSick_']=2,
 ['game.Character.isWorkingToday_']=2,
 ['game.Character.levelData_']=18,
 ['game.Character.paymentAmountToday_']=8,
 ['game.Character.realizedDreams_']=21,
 ['game.Character.regularVisitCount_']=8,
 ['game.Character.staffExp_']=8,
 ['game.Character.treasureDataList_']=21,
 ['game.Character.visitCount_']=8,
 ['game.ChipModel.data_']=18,
 ['game.ChipModel.exp_']=8,
 ['game.ChipModel.haveNum_']=8,
 ['game.ChipModel.isFind_']=2,
 ['game.Customer.character_']=18,
 ['game.Customer.code_']=14,
 ['game.Customer.lobbyCount_']=8,
 ['game.Customer.satTableCount_']=8,
 ['game.Customer.staminaMax_']=8,
 ['game.Customer.stamina_']=8,
 ['game.Departure.data_']=18,
 ['game.Departure.hearts_']=8,
 ['game.Departure.isFind_']=2,
 ['game.Departure.popularExp_']=8,
 ['game.Departure.popular_']=8,
 ['game.Ingredient.data_']=18,
 ['game.Ingredient.haveNum_']=8,
 ['game.Ingredient.isFind_']=2,
 ['game.Point.data_']=18,
 ['game.Point.value_']=8,
 ['game.Request.data_']=18,
 ['game.Request.isComplete_']=2,
 ['game.Request.isFind_']=2,
 ['game.Request.isRunning_']=2,
 ['game.Topping.data_']=18,
 ['game.Topping.haveNum_']=8,
 ['game.Topping.isFind_']=2,
 ['game.Treasure.data_']=18,
 ['game.Treasure.haveNum_']=8,
 ['game.Treasure.isFind_']=2,
 ['game.Yagaraburu.data_']=18,
 ['game.Yagaraburu.feedsList_']=21,
 ['game.Yagaraburu.feedsMax_']=8,
 ['game.Yagaraburu.hasAura_']=2,
 ['game.Yagaraburu.paramList_']=29,
 ['game.Yagaraburu.raceCount_']=8,
 ['game.Yagaraburu.stomach_']=8,
 ['game.Yagaraburu.totalPrize_']=8,
 ['kairo.unity.form.FormBase.formManager_']=18,
 ['kairo.unity.form.FormBase.formProcMode_']=8,
 ['kairo.unity.form.FormBase.id_']=8,
 ['kairo.unity.form.FormManagerBase.formStack_']=18,
 ['main.AppData.architectureList_']=21,
 ['main.AppData.atelierList_']=21,
 ['main.AppData.characterList_']=21,
 ['main.AppData.chipModelList_']=21,
 ['main.AppData.customerList_']=21,
 ['main.AppData.departureList_']=21,
 ['main.AppData.frmGame_']=18,
 ['main.AppData.ingredientList_']=21,
 ['main.AppData.myYagaraburu_']=18,
 ['main.AppData.pointList_']=21,
 ['main.AppData.recipeList_']=21,
 ['main.AppData.requestList_']=21,
 ['main.AppData.save_']=18,
 ['main.AppData.toppingList_']=21,
 ['main.AppData.treasureList_']=21,
}
-- Checked IL2CPP x86 metadata, shared by every editor and data feature.
OPGG.metaCache={};OPGG.addressMeta={}

-- Derive the runtime header layout from its metadata token and declared counts.
-- The previous implementation confused method_count with field_count and read stack-slot size as array stride.
function OPGG.metadataLayout(fallback)
  if OPGG.runtimeLayout then return OPGG.runtimeLayout end
  local c=valid(OPGG.appClass) and OPGG.appClass or fallback
  local handle=valid(c) and ptr(c+0x34)
  local token=handle and readInteger(handle+0x54);local methods=handle and readSmallInteger(handle+0x40);local fields=handle and readSmallInteger(handle+0x44)
  if not token or (token&amp;0xFF000000)~=0x02000000 or not methods or methods&lt;0 or methods&gt;4096 or not fields or fields&lt;0 or fields&gt;2048 then OPGG.fail('Runtime metadata header cannot be validated.','実行時メタデータのヘッダーを検証できません。')end
  local candidates={}
  for offset=0x90,0xB0,4 do
    if readInteger(c+offset)==token and readSmallInteger(c+offset+4)==methods and readSmallInteger(c+offset+8)==fields then candidates[#candidates+1]=offset end
  end
  if #candidates~=1 then OPGG.fail('Runtime metadata layout absent or ambiguous.','実行時メタデータの配置が未検出または複数一致です。')end
  local offset=candidates[1];OPGG.runtimeLayout={fieldCount=offset+8,methodCount=offset+4,elementSize=offset-0x18,token=offset}
  return OPGG.runtimeLayout
end
function OPGG.fieldInfo(c,name)
  local key=tostring(OPGG.pid)..':'..tostring(OPGG.session)..':'..hex(c)..':'..name
  local cached=OPGG.metaCache[key];if cached then return cached end
  local seen={};local current=c
  for depth=1,32 do
    if not valid(current) or seen[current] then break end;seen[current]=true
    local fields=ptr(current+0x40);local count=readSmallInteger(current+OPGG.metadataLayout(current).fieldCount)
    if not count or count&lt;0 or count&gt;2048 then OPGG.fail('Invalid field metadata.','フィールド定義を検証できません。') end
    for i=0,count-1 do
      local f=fields and fields+i*20
      if not f or ptr(f+8)~=current then OPGG.fail('Invalid field owner.','フィールドの所属が一致しません。') end
      if readString(ptr(f),256)==name then
        local typePointer=ptr(f+4);local bits=typePointer and readInteger(typePointer+4);local offset=readInteger(f+12)
        if not bits or not offset then OPGG.fail('Unreadable field metadata.','フィールド定義を読み取れません。') end
        local info={offset=offset,type=(bits&gt;&gt;16)&amp;255,static=(bits&amp;0x10)~=0,owner=current,name=name}
        local owner=readString(ptr(current+8),128);local ns=readString(ptr(current+12),128)
        local expected=OPGG.FIELD_TYPES[ns..'.'..owner..'.'..name]
        if expected and expected~=info.type then OPGG.fail('Field type changed: '..name,'フィールドの型が変わっています：'..name) end
        OPGG.metaCache[key]=info;return info
      end
    end
    current=ptr(current+0x2C)
  end
  OPGG.fail('Field unavailable: '..name,'フィールド未検出：'..name)
end
function OPGG.offClass(c,name) return OPGG.fieldInfo(c,name).offset end
function OPGG.off(obj,name) return OPGG.offClass(ptr(obj),name) end
function OPGG.field(obj,name)
  if not valid(obj) then OPGG.fail('Object unavailable.','対象データを取得できません。') end
  local cls=ptr(obj);local m=OPGG.fieldInfo(cls,name);local size=readInteger(cls+0x80)
  local widths={[2]=1,[4]=1,[5]=1,[6]=2,[7]=2,[8]=4,[9]=4,[10]=8,[11]=8,[12]=4,[13]=8}
  local width=widths[m.type] or 4
  if m.type==17 then width=1 end -- Struct members are handled by their owning operation, never by a guessed scalar width.
  if m.static or not size or size&lt;8 or size&gt;0x100000 or m.offset&lt;8 or m.offset+width&gt;size then OPGG.fail('Field layout unsupported: '..name,'フィールド構造が未対応です：'..name) end
  local address=obj+m.offset;OPGG.addressMeta[address]={type=m.type,object=obj,class=cls,field=name};return address
end
function OPGG.obj(obj,name)
  local a=OPGG.field(obj,name);local t=OPGG.addressMeta[a].type
  if t~=14 and t~=18 and t~=20 and t~=21 and t~=28 and t~=29 then OPGG.fail('Expected a reference field: '..name,'参照型ではありません：'..name) end
  return ptr(a)
end
function OPGG.readFlag(obj,name)
  local a=OPGG.field(obj,name);local t=OPGG.addressMeta[a].type
  if t~=2 and t~=4 and t~=5 then OPGG.fail('Flag type unsupported: '..name,'フラグの型が未対応です：'..name) end
  local n=readBytes(a,1);if n~=0 and n~=1 then OPGG.fail('Flag value unreadable: '..name,'フラグを正しく読み取れません：'..name) end
  return n
end
function OPGG.arrayElement(array,index,typeCode)
  if not valid(array) or index&lt;0 or index%1~=0 then OPGG.fail('Invalid array.','配列を検証できません。') end
  local cls=ptr(array);local n=readInteger(array+12);local size=readInteger(cls+OPGG.metadataLayout(cls).elementSize)
  local widths={[8]=4,[9]=4,[10]=8,[11]=8,[18]=4};local width=widths[typeCode]
  if not width or size~=width or not n or n&lt;0 or n&gt;1000000 or index&gt;=n or (typeCode~=18 and readString(ptr(cls+8),128)~=(typeCode==10 and 'Int64[]' or 'Int32[]')) then OPGG.fail('Array element layout unsupported.','配列要素の構造が未対応です。') end
  local address=array+16+index*width;OPGG.addressMeta[address]={type=typeCode,object=array,class=cls};return address
end
function OPGG.listLayout(list)
  local items=OPGG.field(list,'_items');local size=OPGG.field(list,'_size');local version=OPGG.field(list,'_version')
  if OPGG.addressMeta[size].type~=8 or OPGG.addressMeta[version].type~=8 then OPGG.fail('List counters are not integers.','一覧の件数・更新番号が整数型ではありません。') end
  local array=ptr(items);local n=readInteger(size);local v=readInteger(version)
  if not valid(array) or not n or n&lt;0 or n&gt;10000 or not v or (readInteger(array+12) or -1)&lt;n then OPGG.fail('Invalid list snapshot.','一覧の構造を検証できません。') end
  return {list=list,array=array,count=n,version=v,itemsAddress=items,countAddress=size,versionAddress=version}
end
function OPGG.requireListABI(list)
  local l=OPGG.listLayout(list)
  if l.itemsAddress-list~=8 or l.countAddress-list~=12 or l.versionAddress-list~=16 then OPGG.fail('Native-job List layout unsupported.','ゲーム内呼び出し用の一覧構造が未対応です。') end
  return l
end
function OPGG.items(list)
  if not valid(list) then return {} end
  local l=OPGG.listLayout(list);local result={}
  for i=0,l.count-1 do local p=ptr(OPGG.arrayElement(l.array,i,18));if p~=0 then if not valid(p) then OPGG.fail('List contains an invalid object.','一覧に無効な対象が含まれています。') end;result[#result+1]=p end end
  if ptr(l.itemsAddress)~=l.array or readInteger(l.countAddress)~=l.count or readInteger(l.versionAddress)~=l.version then OPGG.fail('List changed; retry.','一覧が変化しました。再実行してください。') end
  return result
end
function OPGG.freshList(field)
  for attempt=1,3 do
    local app=OPGG.app();local list=OPGG.obj(app,field)
    if not valid(list) then return {} end
    local ok,result=pcall(OPGG.items,list)
    if ok and OPGG.app()==app and OPGG.obj(app,field)==list then return result end
  end
  OPGG.fail('List changed or is unsupported: '..field,'一覧が変化したか、構造が未対応です：'..field)
end
function OPGG.listIndex(field)
  local objects=OPGG.freshList(field);local byId={};local duplicates={}
  if field~='customerList_' then
    for _,o in ipairs(objects) do local ok,id=pcall(OPGG.dataId,o);if ok and id~=nil then if byId[id] then duplicates[id]=true;byId[id]=nil elseif not duplicates[id] then byId[id]=o end end end
  end
  return {objects=objects,byId=byId,duplicates=duplicates}
end
function OPGG.checkedAddress(address,vt)
  if not valid(address) then return nil end
  local m=OPGG.addressMeta[address];if not m then OPGG.fail('Value type could not be verified.','編集値の型を検証できません。') end
  local allowed=(vt==vtByte and (m.type==2 or m.type==4 or m.type==5)) or (vt==vtDword and (m.type==8 or m.type==9 or (m.type==17 and OPGG.enumFieldWidth(m)==4))) or (vt==vtQword and (m.type==10 or m.type==11)) or (vt==vtSingle and m.type==12)
  if not allowed then OPGG.fail('Editor value type mismatch.','エディタとゲームの値の型が一致しません。') end
  if m.object and ptr(m.object)~=m.class then return nil end
  return address
end
function OPGG.bind(mr,fn,en,ja)
  mr.Active=false;mr.Address='0';mr.IsGroupHeader=false
  local session,pid=OPGG.session,OPGG.pid;local app=OPGG.app();local save=OPGG.obj(app,'save_');local initial
  local dynamic=mr.DontSave;local valueType=mr.Type
  local function resolve()
    if session~=OPGG.session or pid~=OPGG.pid or app~=OPGG.app() or save~=OPGG.obj(app,'save_') then return nil end
    local address=OPGG.checkedAddress(fn(),valueType)
    if dynamic and initial and address~=initial then return nil end
    if address then initial=initial or address end
    return address
  end
  OPGG.rows[mr.ID]={mr=mr,fn=resolve,en=en,ja=ja,session=session}
  local ok,a=pcall(resolve);if ok and a then mr.Address=hex(a) else mr.IsGroupHeader=true;OPGG.rows[mr.ID].disabled=true;mr.Description=OPGG.T(en or mr.Description,ja or mr.Description)..OPGG.T(' [Unavailable]','【使用不可】') end
end
function OPGG.characterContext(character)
  OPGG.require();local cls=ptr(character)
  if not OPGG.isA(character,'game','Character') then OPGG.fail('Character identity mismatch.','キャラクターの識別が一致しません。') end
  return {app=OPGG.app(),save=OPGG.obj(OPGG.app(),'save_'),pid=OPGG.pid,session=OPGG.session,character=character,class=cls,data=OPGG.obj(character,'data_'),id=OPGG.dataId(character)}
end
function OPGG.resolveCharacter(context)
  if not context or context.pid~=OPGG.pid or context.session~=OPGG.session or context.app~=OPGG.app() or context.save~=OPGG.obj(context.app,'save_') then OPGG.fail('Reopen the character editor after a save / process change.','セーブ・プロセス変更後はエディタを開き直してください。') end
  local p=OPGG.find('characterList_',context.id)
  if p~=context.character or ptr(p)~=context.class or OPGG.obj(p,'data_')~=context.data then OPGG.fail('Character instance changed; reopen the editor.','キャラクターの実体が変わりました。エディタを開き直してください。') end
  return p
end
function OPGG.characterRules(character)
  local a=OPGG.scan('CharacterExpRule');local data=OPGG.obj(character,'data_');local level=OPGG.obj(character,'levelData_')
  local offsets={{character,'data_',8},{data,'&lt;groupId_&gt;k__BackingField',15},{data,'id_',21},{character,'levelData_',27},{level,'&lt;expMax_&gt;k__BackingField',34},{character,'levelData_',46},{level,'&lt;expMaxMugiwara_&gt;k__BackingField',53}}
  for _,v in ipairs(offsets) do if OPGG.off(v[1],v[2])~=readBytes(a+v[3],1) then OPGG.fail('Character EXP layout changed.','キャラクターの経験値構造が変わっています。') end end
  local id=readBytes(a+22,1);local required=readInteger(a+38)
  if not id or not required or required&lt;1 or required&gt;2147483647 then OPGG.fail('Character EXP rule unsupported.','キャラクターの経験値定義が未対応です。') end
  return {newcomer=id,newcomerExp=required}
end
function OPGG.newcomer()
  local a=OPGG.scan('CharacterExpRule');local id=readBytes(a+22,1)
  if not id then OPGG.fail('Newcomer definition unavailable.','新人の定義を取得できません。') end
  local character=OPGG.find('characterList_',id);OPGG.characterRules(character);return character
end
function OPGG.levelThreshold(character,level)
  local rules=OPGG.characterRules(character);local data=OPGG.obj(character,'data_');local group=readInteger(OPGG.field(data,'&lt;groupId_&gt;k__BackingField'))
  if group==nil then OPGG.fail('Character group unavailable.','キャラクターの所属を取得できません。') end
  local required
  if group~=0 and OPGG.dataId(character)==rules.newcomer then required=rules.newcomerExp else required=readInteger(OPGG.field(level,group==0 and '&lt;expMaxMugiwara_&gt;k__BackingField' or '&lt;expMax_&gt;k__BackingField')) end
  if not required or required&lt;1 or required&gt;2147483647 then OPGG.fail('Invalid EXP threshold.','必要経験値を検証できません。') end
  return required
end
function OPGG.levelInfo(character)
  local level=OPGG.obj(character,'levelData_');local id=readInteger(OPGG.field(level,'id_'))
  if not id or id&lt;0 or id&gt;999 then OPGG.fail('Invalid level ID.','LVのIDが不正です。') end
  return id+1,OPGG.levelThreshold(character,level)
end
function OPGG.levelTable()
  local c=OPGG.class('data','Data');local data=ptr(ptr(c+0x5C));local array=OPGG.obj(data,'characterLevelData_');local n=readInteger(array+12)
  if not n or n&lt;1 or n&gt;1000 then OPGG.fail('Level table unavailable.','LVテーブルを取得できません。') end
  local levels={max=0}
  for i=0,n-1 do
    local level=ptr(OPGG.arrayElement(array,i,18));local cls=ptr(level);local id=readInteger(OPGG.field(level,'id_'))
    if not cls or readString(ptr(cls+8),128)~='CharacterLevelData' or not id or id&lt;0 or id&gt;=1000 or levels[id+1] then OPGG.fail('Level definitions are invalid or duplicate.','LVの定義が不正または重複しています。') end
    levels[id+1]=level;levels.max=math.max(levels.max,id+1)
  end
  return levels
end
function OPGG.setCharacterLevelImpl(id,context)
  context=context or OPGG.characterContext(OPGG.find('characterList_',id));local character=OPGG.resolveCharacter(context);local levels=OPGG.levelTable();local old=OPGG.levelInfo(character)
  local wanted=OPGG.askInt(OPGG.T('Character LV','キャラクターLV'),OPGG.T('LV 1-','LV 1～')..levels.max,old,1,levels.max)
  if not wanted then return 'cancelled' end
  if wanted==old then return 'unchanged' end
  if not levels[wanted] then OPGG.fail('This LV is not defined.','このLVは定義されていません。') end
  local ok,e=OPGG.withPaused(function()
    local p=OPGG.resolveCharacter(context);local current=OPGG.levelTable();if current[wanted]~=levels[wanted] then error('Level definitions changed') end
    local la=OPGG.field(p,'levelData_');local ea=OPGG.checkedAddress(OPGG.field(p,'exp_'),vtDword);local oldLevel=ptr(la);local oldExp=readInteger(ea)
    if not oldLevel or oldExp==nil then error('Level values unavailable') end
    local success,err=pcall(function()
      if not writeInteger(ea,0) then OPGG.fail('EXP write failed.','経験値の書き込みに失敗しました。')end
      if not writeInteger(la,levels[wanted]) then OPGG.fail('LV write failed.','LVの書き込みに失敗しました。')end
      if readInteger(ea)~=0 or ptr(la)~=levels[wanted] then OPGG.fail('LV / EXP readback mismatch.','書き込み後のLV・経験値が指定値と一致しません。')end
    end)
    if not success then
      local a=writeInteger(la,oldLevel);local b=writeInteger(ea,oldExp)
      if not a or not b or ptr(la)~=oldLevel or readInteger(ea)~=oldExp then error('LV rollback failed: '..tostring(err),0)end
      error(err,0)
    end
  end)
  if not ok then error(e,0)end
  OPGG.msg('LV write verified: '..old..' -&gt; '..wanted..' (EXP 0).','LV書き込み確認：'..old..' → '..wanted..'（経験値0）。')
  OPGG.updateLevelDisplays()
  return 'success'
end
function OPGG.setCharacterLevel(id,context)
  OPGG.lastLevelResult={status='not-completed'}
  local ok,result=pcall(OPGG.setCharacterLevelImpl,id,context)
  if not ok then OPGG.lastLevelResult={status='failed',error=tostring(result)};error(result,0)end
  OPGG.lastLevelResult={status=result}
end
function OPGG.addLevelEditor(parent,id)
  local context=OPGG.characterContext(OPGG.find('characterList_',id));local ok,e=pcall(OPGG.levelInfo,context.character)
  if not ok then OPGG.addHdr(parent,'LV editing unavailable','LV編集：未対応');OPGG.noteOnce('level-fields',e);return end
  local m=OPGG.addRec(parent,'LV (check to change)','LV（チェックで変更）','0',vtAutoAssembler);m.Color=OPGG.C_SCRIPT;m.Async=false
  local contextId=OPGG.keepEditorContext(context,m.ID)
  m.Script='[ENABLE]\n{$lua}\nif syntaxcheck then return end\nOPGG.deferEditorAction(memrec,function() OPGG.setCharacterLevel('..id..',OPGG.editorContext('..contextId..')) end)\n{$asm}\n[DISABLE]\n'
  local display=OPGG.dyn[#OPGG.dyn];OPGG.addHdr(parent,'EXP threshold for current LV','現在LVの必要経験値');OPGG.levelDisplays[m.ID]={id=id,context=context,level=display,exp=OPGG.dyn[#OPGG.dyn]};OPGG.updateLevelDisplays()
end
OPGG.editorContexts={};OPGG.contextOwners={};OPGG.nextEditorContext=0
function OPGG.keepEditorContext(context,owner)
  OPGG.nextEditorContext=OPGG.nextEditorContext+1;local token=OPGG.nextEditorContext;OPGG.editorContexts[token]=context
  if owner then OPGG.contextOwners[owner]=OPGG.contextOwners[owner] or {};table.insert(OPGG.contextOwners[owner],token)end
  return token
end
function OPGG.editCharacter(parent,p)
  OPGG.clearChildren(parent);local context=OPGG.characterContext(p);local id=context.id;local en,ja=OPGG.namePair(p);OPGG.addHdr(parent,en..' [ID '..id..']',ja..' [ID '..id..']')
  OPGG.addLevelEditor(parent,id)
  for _,f in ipairs(OPGG.CHARFIELDS) do
    local field,typ=f[1],f[4] or vtDword
    local function address()return OPGG.field(OPGG.resolveCharacter(context),field)end
    local ok=pcall(function()OPGG.checkedAddress(address(),typ)end)
    if ok then OPGG.row(parent,f[2],f[3],address,typ) else OPGG.addHdr(parent,f[2]..' [Unavailable]',f[3]..'【使用不可】') end
  end
  local ok,e=pcall(OPGG.addCharacterDetails,parent,id,context)
  if not ok then OPGG.addHdr(parent,'Customer details unavailable','お客様詳細：未対応');OPGG.noteOnce('character-details',e) end
end

function OPGG.editorContext(id)
  local c=OPGG.editorContexts[id];if not c then OPGG.fail('Reopen this editor.','エディタを開き直してください。') end
  OPGG.resolveCharacter(c);return c
end
function OPGG.elementClass(list,ns,name)
  local l=OPGG.listLayout(list);local cls=ptr(ptr(l.array)+0x20)
  if not valid(cls) or readString(ptr(cls+8),128)~=name or readString(ptr(cls+12),128)~=ns then OPGG.fail('List element class changed.','一覧の要素クラスが変わっています。') end
  return cls
end
function OPGG.nativeContract(key,cls,name,isStatic,parameters,returns)
  local target=OPGG.scan(key);local matches=0;local seen={};local current=cls
  for depth=1,32 do
    if not valid(current) or seen[current]then break end;seen[current]=true
    local methods=ptr(current+0x4C);local count=readSmallInteger(current+OPGG.metadataLayout(current).methodCount)
    if not count or count&lt;0 or count&gt;4096 or (count&gt;0 and not methods)then OPGG.fail('Native method metadata unavailable: '..name,'呼び出し定義を取得できません：'..name)end
    for i=0,count-1 do
      local m=ptr(methods+i*4)
      if m and ptr(m)==target and readString(ptr(m+12),128)==name then
        local flags=readSmallInteger(m+0x28);local n=readBytes(m+0x2E,1);local result=ptr(m+0x14);local bits=result and readInteger(result+4)
        if ptr(m+0x10)~=current or not flags or ((flags&amp;0x10)~=0)~=isStatic or n~=#parameters or not bits or ((bits&gt;&gt;16)&amp;255)~=returns then OPGG.fail('Native signature changed: '..name,'呼び出し形式が変わっています：'..name)end
        local args=ptr(m+0x18)
        for j,expected in ipairs(parameters)do
          local t=args and ptr(args+(j-1)*4);local b=t and readInteger(t+4)
          if not b or ((b&gt;&gt;16)&amp;255)~=expected or (b&amp;0x40000000)~=0 then OPGG.fail('Native parameter changed: '..name,'引数の定義が変わっています：'..name)end
        end
        matches=matches+1
      end
    end
    current=ptr(current+0x2C)
  end
  if matches~=1 then OPGG.fail('Native method not uniquely identified: '..name,'呼び出し先を一意に識別できません：'..name)end
  return target
end
function OPGG.characterNativeGuard(context)
  local p=OPGG.resolveCharacter(context);local list=OPGG.obj(context.app,'characterList_');local l=OPGG.listLayout(list);local cell
  for i=0,l.count-1 do local a=OPGG.arrayElement(l.array,i,18);if ptr(a)==p then if cell then OPGG.fail('Duplicate character instance.','キャラクターの実体が重複しています。') end;cell=a end end
  if not cell then OPGG.fail('Character membership changed.','キャラクターの所属一覧が変わりました。') end
  return string.format('cmp dword ptr [%X],%X\njne opggDreamStale\ncmp dword ptr [%X],%X\njne opggDreamStale\ncmp dword ptr [%X],%X\njne opggDreamStale\ncmp dword ptr [%X],%X\njne opggDreamStale\n',OPGG.field(context.app,'characterList_'),list,l.itemsAddress,l.array,cell,p,OPGG.field(p,'data_'),context.data)
end
-- Read only the requested integer definitions from the installed metadata; no game text is retained.
OPGG.constantCache={}
function OPGG.metadataBytes()
  if OPGG.metadataReader then return OPGG.metadataReader() end
  local candidates={}
  if type(enumModules)=='function' then
    for _,m in ipairs(enumModules()) do
      if m.Name==OPGG.MODULE or m.Name==OPGG.EXE then
        local path=m.PathToFile or m.Path or m.FileName
        if path and path:find('[\\/]') then candidates[#candidates+1]=path end
      end
    end
  end
  for _,path in ipairs(candidates) do
    local dir=path:match('^(.*)[\\/]');local filename=dir and dir..'\\'..OPGG.EXE:gsub('%.exe$','')..'_Data\\il2cpp_data\\Metadata\\global-metadata.dat'
    local f=filename and io.open(filename,'rb')
    if f then local blob=f:read('*a');f:close();return blob end
  end
  OPGG.fail('Installed metadata file was not found.','インストール済みのメタデータファイルを取得できません。')
end
function OPGG.metadataInt(blob,offset)
  if not offset or offset&lt;0 or offset+4&gt;#blob then OPGG.fail('Metadata bounds mismatch.','メタデータの範囲が不正です。') end
  return string.unpack('&lt;I4',blob,offset+1)
end
function OPGG.compressedInt(blob,offset)
  local function byte(p)local b=blob:byte(p+1);if not b then OPGG.fail('Truncated metadata integer.','メタデータの整数が途中で切れています。')end;return b end
  local first=byte(offset);local value
  if first&lt;0x80 then value=first
  elseif first&lt;0xC0 then value=((first&amp;0x3F)&lt;&lt;8)|byte(offset+1)
  elseif first&lt;0xE0 then value=((first&amp;0x1F)&lt;&lt;24)|(byte(offset+1)&lt;&lt;16)|(byte(offset+2)&lt;&lt;8)|byte(offset+3)
  elseif first==0xF0 then value=OPGG.metadataInt(blob,offset+1)
  elseif first==0xFE then value=0xFFFFFFFE elseif first==0xFF then value=0xFFFFFFFF
  else OPGG.fail('Unsupported metadata integer encoding.','メタデータの整数形式が未対応です。') end
  if value==0xFFFFFFFF then return -2147483648 end
  return (value&amp;1)==0 and (value&gt;&gt;1) or -((value&gt;&gt;1)+1)
end
function OPGG.metadataConstant(owner,name)
  local key=owner..'.'..name;local cached=OPGG.constantCache[key];if cached~=nil then return cached end
  local blob=OPGG.metadataBytes();local u=OPGG.metadataInt
  if u(blob,0)~=0xFAB11BAF or (u(blob,4)~=29 and u(blob,4)~=31) then OPGG.fail('Unsupported metadata format.','メタデータの形式が未対応です。') end
  local so,ss=u(blob,0x18),u(blob,0x1C);local fo,fs=u(blob,0x60),u(blob,0x64);local dfo,dfs=u(blob,0x40),u(blob,0x44);local data,ds=u(blob,0x48),u(blob,0x4C);local to,ts=u(blob,0xA0),u(blob,0xA4)
  if so+ss&gt;#blob or fo+fs&gt;#blob or dfo+dfs&gt;#blob or data+ds&gt;#blob or to+ts&gt;#blob or fs%12~=0 or dfs%12~=0 or ts%88~=0 then OPGG.fail('Metadata tables are invalid.','メタデータの表構造が不正です。') end
  local function text(index)
    if index&gt;=ss then OPGG.fail('Invalid metadata name.','メタデータの名前が不正です。')end
    local first=so+index+1;local last=blob:find('\0',first,true)
    if not last or last&gt;so+ss then OPGG.fail('Invalid metadata string.','メタデータの文字列が不正です。')end
    return blob:sub(first,last-1)
  end
  local byType={};for i=0,ts//88-1 do byType[u(blob,to+i*88+8)]=i end
  local function qualified(i,seen)
    if not i or i&lt;0 or i&gt;=ts//88 or seen[i] then OPGG.fail('Invalid declaring type.','型の所属が不正です。')end
    seen[i]=true;local row=to+i*88;local decl=u(blob,row+12);local leaf=text(u(blob,row))
    if decl~=0xFFFFFFFF then return qualified(byType[decl],seen)..'.'..leaf end
    local ns=text(u(blob,row+4));return ns~='' and ns..'.'..leaf or leaf
  end
  local found,count=nil,0;local leaf=owner:match('([^.]+)$')
  for i=0,ts//88-1 do local row=to+i*88;if text(u(blob,row))==leaf and qualified(i,{})==owner then found=row;count=count+1 end end
  if count~=1 then OPGG.fail('Definition owner absent or ambiguous: '..owner,'定義の所属が未検出または重複しています：'..owner) end
  local first=u(blob,found+32);local n=string.unpack('&lt;I2',blob,found+69);local field,matches=nil,0
  if first+n&gt;fs//12 then OPGG.fail('Invalid field definition range.','フィールド定義の範囲が不正です。')end
  for i=first,first+n-1 do if text(u(blob,fo+i*12))==name then field=i;matches=matches+1 end end
  if matches~=1 then OPGG.fail('Definition unavailable: '..key,'定義を一意に取得できません：'..key)end
  local value;matches=0
  for i=0,dfs//12-1 do local row=dfo+i*12;if u(blob,row)==field then local index=u(blob,row+8);if index&gt;=ds then OPGG.fail('Invalid constant data.','定義値の範囲が不正です。')end;value=OPGG.compressedInt(blob,data+index);matches=matches+1 end end
  if matches~=1 or not value or value&lt;0 or value&gt;100000 then OPGG.fail('Integer definition unsupported: '..key,'整数定義が未対応です：'..key)end
  OPGG.constantCache[key]=value;return value
end
function OPGG.saveConstant(name)
  local info=OPGG.fieldInfo(OPGG.appClass,name)
  if info.type~=8 or not info.static then OPGG.fail('Save definition is not an integer constant.','セーブ定義が整数定数ではありません。')end
  return OPGG.metadataConstant('main.AppData',name)
end
function OPGG.enumFieldWidth(info)
  -- Prove a 32-bit enum store from the owning type's simple Init method.
  local cls=info.owner;local methods=ptr(cls+0x4C);local n=readSmallInteger(cls+OPGG.metadataLayout(cls).methodCount)
  if not methods or not n or n&gt;4096 then OPGG.fail('Enum storage could not be verified.','列挙値の格納形式を検証できません。') end
  for i=0,n-1 do
    local m=ptr(methods+i*4)
    if m and readString(ptr(m+12),128)=='Init' and readBytes(m+0x2E,1)==1 then
      local a=ptr(m);local b=getAddressSafe(OPGG.MODULE)
      if a and b and a&gt;=b and a+14&lt;b+getModuleSize(OPGG.MODULE) then
        local bytes=readBytes(a,14,true)
        if bytes and bytes[1]==0x55 and bytes[2]==0x8B and bytes[3]==0xEC and bytes[4]==0x8B and bytes[6]==8 and bytes[7]==0x8B and bytes[9]==12 and bytes[10]==0x89 and bytes[12]==info.offset and bytes[13]==0x5D and bytes[14]==0xC3 and ((bytes[5]==0x45 and bytes[8]==0x4D and bytes[11]==0x48) or (bytes[5]==0x4D and bytes[8]==0x45 and bytes[11]==0x41)) then return 4 end
      end
    end
  end
  OPGG.fail('Enum storage could not be verified.','列挙値の格納形式を検証できません。')
end
function OPGG.captureBoundary()
  OPGG.require();local app=OPGG.app();return {pid=OPGG.pid,session=OPGG.session,app=app,save=OPGG.obj(app,'save_')}
end
function OPGG.assertBoundary(c)
  if not c or c.pid~=OPGG.pid or c.session~=OPGG.session or c.app~=OPGG.app() or c.save~=OPGG.obj(c.app,'save_') then OPGG.fail('Game / save changed; reopen the dialog.','ゲーム・セーブが変わりました。画面を開き直してください。')end
end
function OPGG.dataContext(field,p)
  local c=OPGG.captureBoundary();c.field=field;c.object=p;c.class=ptr(p);c.id=OPGG.dataId(p);c.data=OPGG.obj(p,'data_');return c
end
function OPGG.resolveData(c)
  OPGG.assertBoundary(c);local p=OPGG.find(c.field,c.id)
  if p~=c.object or ptr(p)~=c.class or OPGG.obj(p,'data_')~=c.data then OPGG.fail('Data instance changed; reopen the editor.','データの実体が変わりました。エディタを開き直してください。')end
  return p
end
function OPGG.addItem()
  local boundary=OPGG.captureBoundary();local cat=OPGG.category();if not cat then return end;OPGG.assertBoundary(boundary)
  local names,contexts={},{}
  for i,p in ipairs(OPGG.list(cat[1]))do names[i]=OPGG.label(p);contexts[i]=OPGG.dataContext(cat[1],p)end
  local chosen=OPGG.pick(OPGG.T('Add items (multiple selection)','アイテム追加（複数選択）'),names,true);if not chosen then return end
  local amount=OPGG.askInt(OPGG.T('Add quantity','追加個数'),OPGG.T('Quantity to add (1-99; total capped at 99)','追加個数（1～99、合計99まで）'),1,1,99);if not amount then return end
  local ok,e=OPGG.withPaused(function()
    OPGG.assertBoundary(boundary);local plan={};local seen={}
    for _,index in ipairs(chosen)do
      local c=contexts[index];if not c then error('Selection changed')end
      if not seen[c.id] then
        seen[c.id]=true;local p=OPGG.resolveData(c);local address=OPGG.checkedAddress(OPGG.field(p,'haveNum_'),vtDword);local old=readInteger(address)
        if not old or old&lt;0 then error('Quantity unreadable')end
        local flag,oldFlag;local flagOK,a=pcall(OPGG.field,p,'isFind_')
        if flagOK then OPGG.checkedAddress(a,vtByte);flag=a;oldFlag=OPGG.readFlag(p,'isFind_')end
        plan[#plan+1]={address=address,old=old,new=math.min(cat[5],old+amount),flag=flag,oldFlag=oldFlag}
      end
    end
    local touched={};local success,err=pcall(function()
      for _,r in ipairs(plan)do
        touched[#touched+1]=r
        if not writeInteger(r.address,r.new) or readInteger(r.address)~=r.new then error('Quantity verification failed')end
        if r.flag and (not writeBytes(r.flag,1) or readBytes(r.flag,1)~=1)then error('Discovery flag verification failed')end
      end
    end)
    if not success then
      local rollback=true
      for _,r in ipairs(touched)do
        if not writeInteger(r.address,r.old) or readInteger(r.address)~=r.old then rollback=false end
        if r.flag and (not writeBytes(r.flag,r.oldFlag) or readBytes(r.flag,1)~=r.oldFlag)then rollback=false end
      end
      if not rollback then error('Inventory rollback failed')end;error(err,0)
    end
  end)
  if not ok then error(e,0)end
end
function OPGG.fieldStorage(obj,name,width)
  local address=OPGG.field(obj,name);local offset=address-obj;local cls=ptr(obj);local room=readInteger(cls+0x80)-offset;local seen={}
  for depth=1,32 do
    if not valid(cls) or seen[cls] then break end;seen[cls]=true
    local fields=ptr(cls+0x40);local n=readSmallInteger(cls+OPGG.metadataLayout(cls).fieldCount)
    if not n or n&gt;2048 then OPGG.fail('Field storage cannot be verified.','フィールドの格納範囲を検証できません。')end
    for i=0,n-1 do
      local f=fields+i*20;local t=ptr(f+4);local bits=t and readInteger(t+4);local nextOffset=readInteger(f+12)
      if not bits or not nextOffset then OPGG.fail('Field storage cannot be read.','フィールドの格納範囲を読み取れません。')end
      if (bits&amp;0x10)==0 and nextOffset&gt;offset then room=math.min(room,nextOffset-offset)end
    end
    cls=ptr(cls+0x2C)
  end
  if room&lt;width then OPGG.fail('Field is smaller than the operation requires: '..name,'処理に必要な格納範囲がありません：'..name)end
  return address
end

function OPGG.isA(obj,ns,name)
  local c=valid(obj) and ptr(obj);local seen={}
  for depth=1,32 do
    if not valid(c) or seen[c]then return false end;seen[c]=true
    if readString(ptr(c+8),128)==name and readString(ptr(c+12),128)==ns then return true end
    c=ptr(c+0x2C)
  end
  return false
end

-- Resolve each capability independently; a missing anchor is not a table-wide failure.
OPGG.sigCache={};OPGG.notices={};OPGG.failedTasks={};OPGG.selectedKeys={};OPGG.recordStatus={};OPGG.coreReady=false
OPGG.FEATURE_IDS={freeBuild=401,instantBuild=402,ship=403,clock=501,speed=502,guestPass=108,customerStamina=602,health=603}
function OPGG.noteOnce(key,message)
  if OPGG.notices[key] then return end
  OPGG.notices[key]=true
  local text=tostring(message):gsub('^%[string .-%]:%d+: ',''):gsub('^.-%.lua:%d+: ','')
  print('[OPGG] '..text)
end
function OPGG.deferOff(mr)
  if not mr then return end
  local t=createTimer(nil,false);t.Interval=150
  t.OnTimer=function(tt) tt.destroy();pcall(function() mr.Active=false end) end;t.Enabled=true
end
function OPGG.userRun(fn,mr)
  if mr and OPGG.recordStatus[mr.ID]==false then
    OPGG.noteOnce('record:'..mr.ID,OPGG.T('Unavailable in this session: ','この接続では使用不可：')..mr.Description);OPGG.deferOff(mr);return false
  end
  local ok,e=pcall(fn)
  if not ok then OPGG.noteOnce('action:'..tostring(e):gsub('^%[string .-%]:%d+: ',''),e);OPGG.deferOff(mr) end
  return ok
end
function OPGG.ensureProcess()
  if not OPGG.alive() then OPGG.fail('Attach to OPGG.exe first.','先にOPGG.exeへ接続してください。') end
end
function OPGG.scanCandidates(key)
  local sg=OPGG.PATCHDEF[key];if not sg then return {} end
  local b=getAddressSafe(OPGG.MODULE);if not b then return {} end
  local limit=b+getModuleSize(OPGG.MODULE);local result=AOBScan(sg.pattern,'+X');local hits={}
  if result then
    for i=0,result.Count-1 do local a=tonumber(result[i],16);if a and a&gt;=b and a&lt;limit then hits[#hits+1]=a+(sg.offset or 0) end end
    result.destroy()
  end
  return hits
end
function OPGG.scan(key)
  local cached=OPGG.sigCache[key]
  if not cached then
    local hits=OPGG.scanCandidates(key);cached={count=#hits};OPGG.sigCache[key]=cached
    if #hits==1 then cached.address=hits[1];cached.original=readBytes(hits[1],64,true) end
  end
  if not cached.address then OPGG.fail('Code unavailable: '..key..' ('..cached.count..' matches).','コード未対応：'..key..'（'..cached.count..'件一致）。') end
  return cached.address
end
function OPGG.hasCode(key) local ok,a=pcall(OPGG.scan,key);return ok and a~=nil end
function OPGG.class(ns,name)
  local key=ns..'.'..name;if OPGG.cache[key] then return OPGG.cache[key] end
  local anchors=(ns=='main' and name=='AppData') and {'AppType','AppTypeGet'} or (ns=='data' and name=='Data') and {'DataType'} or name=='Trophy' and {'TrophyType'} or {}
  local candidates={}
  for _,anchor in ipairs(anchors) do
    local sg=OPGG.PATCHDEF[anchor]
    if sg and sg.cellOffset then
      for _,site in ipairs(OPGG.scanCandidates(anchor)) do
        local ok,c=pcall(function()
          local cell=ptr(site+sg.cellOffset);local cls=ptr(cell)
          if valid(cls) and readString(ptr(cls+8),128)==name and readString(ptr(cls+12),128)==ns then return cls end
        end)
        if ok and c then candidates[c]=true end
      end
    end
  end
  local found,count=nil,0;for c in pairs(candidates) do found=c;count=count+1 end
  if count~=1 then OPGG.fail('Class unavailable: '..key,'クラス未対応：'..key) end
  OPGG.cache[key]=found;return found
end
function OPGG.allCodes(keys)
  for _,key in ipairs(keys) do if not OPGG.hasCode(key) then return false end end;return true
end
function OPGG.featureKeys(key)
  local selected={};local partial=false
  if key=='freeBuild' then
    for _,name in ipairs(OPGG.FREEPATCHES) do if OPGG.hasCode(name) then selected[#selected+1]=name else partial=true end end
    return #selected&gt;0,selected,partial
  elseif key=='instantBuild' then
    if OPGG.hasCode('construct') then selected[#selected+1]='construct' else partial=true end
    local nativeOK=false
    if OPGG.coreReady and OPGG.allCodes({'atelierInstant','atelierGate','AtelierFrame','TrophyType'}) then
      nativeOK=pcall(function()OPGG.nativeContract('AtelierFrame',OPGG.elementClass(OPGG.obj(OPGG.app(),'atelierList_'),'game','Atelier'),'ExecuteFrameEvent',true,{},1)end)
    end
    if nativeOK then
      for _,name in ipairs({'atelierInstant','atelierGate'}) do selected[#selected+1]=name end
    else partial=true end
    return #selected&gt;0,selected,partial
  elseif key=='guestPass' then
    -- Hospitality and request-dish results are independent capabilities.
    if OPGG.allCodes({'inviteJudge','invitePass'}) then selected={'inviteJudge','invitePass'} else partial=true end
    local delivery={'deliveryPass','deliveryFilter','deliveryLevel','deliveryUIRecipe','deliveryUICount','deliveryExecCount','deliveryExecMenu'}
    if OPGG.allCodes(delivery) then for _,name in ipairs(delivery) do selected[#selected+1]=name end else partial=true end
    return #selected&gt;0,selected,partial
  elseif key=='clock' then return OPGG.hasCode('clock'),{'clock'},false
  elseif key=='speed' then return OPGG.hasCode('speedScheduler'),{'speedScheduler'},false
  elseif key=='ship' then return OPGG.coreReady and OPGG.allCodes({'ShipExpansionFind','ShipRequestFind','TrophyType'}),{},false
  end
  return OPGG.coreReady,{},false
end
function OPGG.refreshAvailability()
  local al=getAddressList()
  for key,id in pairs(OPGG.FEATURE_IDS) do
    local available,keys,partial=OPGG.featureKeys(key);OPGG.recordStatus[id]=available;OPGG.selectedKeys[key]=keys
    OPGG.suffix[id]=not available and OPGG.T('Unavailable','使用不可') or partial and OPGG.T('Partial','一部対応') or nil
  end
  local deps={[204]={'DataType','CharacterExpRule'},[205]={'DataType','CharacterExpRule'},[107]={'FeverStart','TrophyType'},[601]={'TrophyType','TrophyUnlock'}}
  for _,id in ipairs({101,102,103,104,105,106,201,202,203,204,205,206,301,503,504,505,506,107,302,601}) do
    local available=OPGG.coreReady and (not deps[id] or OPGG.allCodes(deps[id]));
    if available and OPGG.CORE[id] then local ok,address=pcall(OPGG.CORE[id]);local mr=al.getMemoryRecordByID(id);available=ok and address~=nil;if available and mr then local verified,checked=pcall(OPGG.checkedAddress,address,mr.Type);available=verified and checked~=nil end end
    OPGG.recordStatus[id]=available
    if available then OPGG.suffix[id]=nil else OPGG.suffix[id]=OPGG.T('Unavailable','使用不可') end
    local mr=al.getMemoryRecordByID(id)
    if mr and not available and mr.Type~=vtAutoAssembler then mr.Active=false;mr.Address='0' end
  end
  OPGG.applyLang()
end
-- A save can be absent during startup / loading. Never dereference it until verified.
function OPGG.currentSave()
  local app=OPGG.app();local save=OPGG.obj(app,'save_');local cls=valid(save) and ptr(save)
  if not valid(cls) then OPGG.fail('Save is not ready; waiting for game data.','セーブの準備待ちです。ゲームデータを待っています。') end
  local name=ptr(cls+8)
  if not valid(name) or readString(name,128)~='Property' then OPGG.fail('Save layout unsupported.','セーブ構造が未対応です。') end
  return app,save
end
function OPGG.connectData()
  local ok,e=pcall(function()
    local c=OPGG.class('main','AppData');local found={}
    for o=0x40,0xC0,4 do local st=ptr(c+o);local p=ptr(st);if valid(p) and ptr(p)==c then found[#found+1]=st end end
    if #found~=1 then OPGG.fail('AppData singleton unavailable or ambiguous.','AppDataの接続先が未検出または複数一致です。') end
    OPGG.appClass=c;OPGG.static=found[1]
    local app,save=OPGG.currentSave();OPGG.lastSave=save
  end)
  OPGG.coreReady=ok;OPGG.dataRetryTicks=0
  if not ok then OPGG.static=nil;OPGG.noteOnce('core:'..tostring(e):gsub('^%[string .-%]:%d+: ',''),OPGG.T('Data features are waiting: ','データ機能は接続待ち：')..tostring(e)) end
  return ok
end
function OPGG.init()
  OPGG.ensureProcess()
  OPGG.jobPage=nil;OPGG.job=nil;OPGG.lastSave=nil;OPGG.speedPage=nil;OPGG.dreamQueue={};OPGG.dreamPages={}
  OPGG.runtimeLayout=nil;OPGG.constantCache={};OPGG.metaCache={};OPGG.addressMeta={};OPGG.editorContexts={};OPGG.contextOwners={};OPGG.cache={};OPGG.offsets={};OPGG.listCache={};OPGG.customerOrder={};OPGG.sigCache={};OPGG.notices={};OPGG.failedTasks={};OPGG.static=nil;OPGG.coreReady=false
  OPGG.session=OPGG.session+1
  if targetIs64Bit() then OPGG.fail('This table targets OPGG x86.','このCTはOPGG x86向けです。') end
  OPGG.connectData()
  OPGG.checkBuild();OPGG.refreshAvailability();OPGG.startTimer()
  if OPGG.coreReady then OPGG.bindCore() end
end
function OPGG.feature(key,on,mr)
  if on then
    local ready,why=pcall(OPGG.ensureProcess);if not ready then OPGG.noteOnce('not-attached',why);OPGG.deferOff(mr);return false end
    local ok,keys,partial=OPGG.featureKeys(key)
    if not ok then OPGG.noteOnce('feature:'..key,OPGG.T('Unavailable feature: ','未対応のため無効：')..key);OPGG.deferOff(mr);return false end
    OPGG.selectedKeys[key]=keys;OPGG.failedTasks[key]=nil
    if key=='instantBuild' then OPGG.failedTasks.atelier=nil end
    if partial then OPGG.noteOnce('partial:'..key,OPGG.T('Only supported parts enabled: ','対応している部分のみ有効：')..key) end
  end
  local ok,e=pcall(OPGG.featureImpl,key,on)
  if not ok then
    OPGG.on[key]=nil;pcall(OPGG.restore,key);OPGG.deferOff(mr)
    OPGG.noteOnce('feature-error:'..key,e);return false
  end
  return true
end
function OPGG.disableAll(self)
  OPGG.stop(OPGG.alive());OPGG.attachGame();OPGG.pid=getOpenedProcessID();OPGG.init()
  local al=getAddressList();for i=al.Count-1,0,-1 do local m=al[i];if m.Active and m~=self then m.Active=false end end
  if OPGG.coreReady then
    OPGG.noteOnce('attached',OPGG.T('Attached; game data verified. All features OFF.','接続完了。ゲームデータの取得を確認しました。全機能解除。'))
  else
    OPGG.noteOnce('attached-waiting',OPGG.T('Process attached; waiting for game data. Code features remain independently available.','プロセスへ接続。ゲームデータの取得待ちです。コード機能は個別に利用可否を判定します。'))
  end
end
function OPGG.isolate(key,fn,off)
  if OPGG.failedTasks[key] then return end
  local ok,e=pcall(fn)
  if not ok then
    OPGG.failedTasks[key]=true;if off then pcall(off) end
    OPGG.noteOnce('task:'..key,OPGG.T('Stopped this task only: ','この処理のみ停止：')..key..' / '..tostring(e))
  end
end
function OPGG.tick()
  if not OPGG.alive() then OPGG.stop(false);if OPGG.timer then OPGG.timer.Enabled=false end;return end
  if OPGG.uiActionBusy then return end
  if not OPGG.coreReady then
    OPGG.dataRetryTicks=(OPGG.dataRetryTicks or 0)+1
    if OPGG.dataRetryTicks&gt;=5 and OPGG.connectData() then
      OPGG.failedTasks={};OPGG.refreshAvailability();OPGG.bindCore()
      OPGG.noteOnce('core-ready:'..OPGG.session,OPGG.T('Game data is ready; data features are now available.','ゲームデータの取得を確認しました。データ機能を利用できます。'))
    end
    return
  end
  local ok,app,save=pcall(OPGG.currentSave)
  if not ok then
    OPGG.coreReady=false;OPGG.dataRetryTicks=0;OPGG.session=OPGG.session+1;pcall(OPGG.cancelAchievementJob,true)
    OPGG.on.customerStamina=nil;OPGG.on.health=nil;OPGG.shipMode=nil;OPGG.shipPermit=nil
    OPGG.disarmRows()
    OPGG.refreshAvailability();OPGG.noteOnce('core-lost',OPGG.T('Data connection lost; dependent features stopped. Reconnecting automatically.','データ接続を失ったため依存機能を停止しました。自動で再接続します。'));return
  end
  if OPGG.lastSave and save~=OPGG.lastSave then OPGG.stop(true);OPGG.customerOrder={};OPGG.session=OPGG.session+1;OPGG.metaCache={};OPGG.addressMeta={};OPGG.editorContexts={};OPGG.contextOwners={};OPGG.lastSave=save;OPGG.bindCore();return end
  OPGG.lastSave=save
  if not OPGG.job then OPGG.failedTasks.jobs=nil end
  OPGG.isolate('jobs',OPGG.pollAchievementJob,function()OPGG.cancelAchievementJob(true)end)
  OPGG.isolate('atelier',function()if OPGG.on.instantBuild and OPGG.selectedKeys.instantBuild and #OPGG.selectedKeys.instantBuild&gt;1 then OPGG.updateInstantAtelier()end end,function()OPGG.feature('instantBuild',false);OPGG.deferOff(getAddressList().getMemoryRecordByID(402))end)
  OPGG.isolate('ship',function()OPGG.updateShipExpansion();OPGG.updateShipPermit()end,function()OPGG.feature('ship',false);OPGG.deferOff(getAddressList().getMemoryRecordByID(403))end)
  OPGG.isolate('levels',OPGG.updateLevelDisplays);OPGG.isolate('details',OPGG.updateCharacterDetails);OPGG.isolate('feeds',OPGG.updateYagaraFeedDisplays)
  for id,r in pairs(OPGG.rows) do
    local mr=OPGG.rowRecord(id,r)
    if not mr then OPGG.rows[id]=nil else
      local rowOK=pcall(function()
        local success,address=false,nil;if not r.disabled then success,address=pcall(r.fn)end
        address=success and valid(address) and hex(address) or '0'
        if mr.Address~=address then mr.Active=false;mr.Address=address end
      end)
      if not rowOK then mr.Active=false;OPGG.rows[id]=nil end
    end
  end
  if OPGG.on.customerStamina then OPGG.isolate('customerStamina',function()
    for _,p in ipairs(OPGG.list('customerList_')) do writeInteger(OPGG.checkedAddress(OPGG.field(p,'stamina_'),vtDword),readInteger(OPGG.checkedAddress(OPGG.field(p,'staminaMax_'),vtDword))) end
  end,function()OPGG.feature('customerStamina',false);OPGG.deferOff(getAddressList().getMemoryRecordByID(602))end) end
  if OPGG.on.health then OPGG.isolate('health',function()
    for _,p in ipairs(OPGG.list('characterList_')) do writeBytes(OPGG.checkedAddress(OPGG.field(p,'isInjured_'),vtByte),0);writeBytes(OPGG.checkedAddress(OPGG.field(p,'isSick_'),vtByte),0) end
  end,function()OPGG.feature('health',false);OPGG.deferOff(getAddressList().getMemoryRecordByID(603))end) end
end
function OPGG.startTimer()
  if OPGG.timer then OPGG.timer.destroy() end
  OPGG.timer=createTimer(nil,false);OPGG.timer.Interval=200
  OPGG.timer.OnTimer=function(t)
    local ok,e=pcall(OPGG.tick)
    if not ok then
      t.Enabled=false;OPGG.coreReady=false;OPGG.dataRetryTicks=0;OPGG.session=OPGG.session+1;pcall(OPGG.cancelAchievementJob,true);OPGG.on.customerStamina=nil;OPGG.on.health=nil;OPGG.shipMode=nil;OPGG.shipPermit=nil
      OPGG.disarmRows()
      pcall(OPGG.refreshAvailability)
      OPGG.noteOnce('timer',OPGG.T('Background updates stopped; independent code features remain active. ','背景更新を停止しました。独立したコード機能は継続します。')..tostring(e)) end
  end
  OPGG.timer.Enabled=true
end

function OPGG.scanSelfTest()
  OPGG.ensureProcess();local good,total=0,0
  for key in pairs(OPGG.PATCHDEF) do
    local ok,a
    if key=='AppTypeGet' or key=='AppType' then ok,a=pcall(OPGG.class,'main','AppData') else ok,a=pcall(OPGG.scan,key) end
    total=total+1;if ok then good=good+1 end
    print('[OPGG] '..key..': '..(ok and hex(a) or OPGG.T('unavailable','使用不可')))
  end
  print(string.format('[OPGG] %d / %d',good,total))
end

function OPGG.setLang(language)
  OPGG.lang=language
  if OPGG.pid and OPGG.alive() then OPGG.refreshAvailability() else OPGG.applyLang() end
end

-- Short version and same-value write check. No tracing or file export.
OPGG.COMPAT_REFERENCE={game='3de17fd093fcee9d060328a7d900489e',data='d283a598e4d09018a02930ca27ed28d1',build='26406937'}
function OPGG.shortDiagnosticError(err)
  return tostring(err):gsub('^%[string .-%]:%d+: ',''):gsub('^.-%.lua:%d+: ',''):gsub('[\r\n].*',''):sub(1,140)
end
function OPGG.checkLevelWrite()
  if not OPGG.coreReady or not OPGG.alive() then return 'not-ready' end
  local ok,result=pcall(function()
    local character=OPGG.freshList('characterList_')[1]
    if not character then return 'not-ready' end
    local context=OPGG.characterContext(character)
    local success,why=OPGG.withPaused(function()
      local p=OPGG.resolveCharacter(context)
      local la=OPGG.field(p,'levelData_');local ea=OPGG.checkedAddress(OPGG.field(p,'exp_'),vtDword)
      local level=readInteger(la);local exp=ea and readInteger(ea)
      if not valid(level) or exp==nil then error('LV / EXP unreadable',0)end
      -- Reapply the current bytes only; do not level up or reset EXP.
      if not writeInteger(ea,exp) then error('EXP write rejected',0)end
      if not writeInteger(la,level) then error('LV write rejected',0)end
      if readInteger(ea)~=exp or readInteger(la)~=level then error('readback mismatch',0)end
    end)
    if not success then return 'failed: '..OPGG.shortDiagnosticError(why)end
    return 'ok'
  end)
  return ok and result or 'failed: '..OPGG.shortDiagnosticError(result)
end
function OPGG.compatibilitySummary()
  local report={ce='unknown',game='not-attached',data='not-attached',build='unknown'}
  if type(getCEVersion)=='function' then local ok,v=pcall(getCEVersion);if ok and v then report.ce=tostring(v)end end
  if type(getCheatEngineFileVersion)=='function' then
    local ok,number,v=pcall(getCheatEngineFileVersion)
    if ok and type(v)=='table' and v.major and v.minor and v.release and v.build then report.ce=string.format('%d.%d.%d.%d',v.major,v.minor,v.release,v.build)end
  end
  local processOK,pid=pcall(getOpenedProcessID);local expectedOK,expected=pcall(getProcessIDFromProcessName,OPGG.EXE)
  if processOK and expectedOK and pid and pid~=0 and pid==expected then
    local base
    if type(enumModules)=='function' then
      local ok,modules=pcall(enumModules)
      if ok and type(modules)=='table' then
        for _,m in ipairs(modules)do
          if m.Name==OPGG.MODULE or m.Name==OPGG.EXE then
            local file=m.PathToFile or m.Path or m.FileName
            if type(file)=='string' and file:find('[\\/]')then base=file:match('^(.*)[\\/]');break end
          end
        end
      end
    end
    report.game='unknown';report.data='unknown'
    if base then
      local function matchFile(file,reference)
        if type(md5file)~='function' then return 'hash-unavailable' end
        local ok,digest=pcall(md5file,file)
        if not ok or type(digest)~='string' or digest=='' then return 'unreadable' end
        return digest:lower()==reference and 'same' or 'different'
      end
      report.game=matchFile(base..'\\'..OPGG.MODULE,OPGG.COMPAT_REFERENCE.game)
      report.data=matchFile(base..'\\'..OPGG.EXE:gsub('%.exe$','')..'_Data\\il2cpp_data\\Metadata\\global-metadata.dat',OPGG.COMPAT_REFERENCE.data)
      local steamapps=base:match('^(.*)[\\/]common[\\/]')
      local f=steamapps and io.open(steamapps..'\\appmanifest_3905010.acf','rb')
      if f then local text=f:read('*a');f:close();report.build=text:match('"buildid"%s+"(%d+)"')or 'unknown' end
    end
  end
  return report
end
function OPGG.checkCompatibility()
  local r=OPGG.compatibilitySummary();local write=OPGG.checkLevelWrite()
  local text='OPGG '..OPGG.CHEATVER..' | CE='..r.ce..' | Build='..r.build..' | Game='..r.game..' | Data='..r.data..' | Write='..write
  if OPGG.lastLevelResult and OPGG.lastLevelResult.status=='failed' then text=text..' | EditError='..OPGG.shortDiagnosticError(OPGG.lastLevelResult.error)end
  local copied=false
  if type(writeToClipboard)=='function' then copied=pcall(writeToClipboard,text)end
  print('[OPGG] '..text)
  OPGG.msg(copied and 'Result copied. Paste it into your reply.'or 'Copy the result from Lua Engine.',copied and '結果をコピーしました。そのまま返信へ貼り付けてください。'or 'Lua Engineから結果をコピーしてください。')
  return text
end

OPGG.applyLang(); OPGG.initCollapse()
_G.OPGG=OPGG
</LuaScript>
</CheatTable>