<?xml version="1.0" encoding="utf-8"?>
<CheatTable AutoAttach="NeedForSpeedUnbound.exe" FullClientAddressList="1" CheatEngineTableVersion="52">
  <CheatEntries>
    <CheatEntry>
      <ID>27033</ID>
      <Description>"Frostbite Toolkit"</Description>
      <VariableType>Auto Assembler Script</VariableType>
      <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- ============================================================================
-- Frostbite Toolkit - Need for Speed Unbound
-- Resolves game objects at runtime. No hardcoded addresses or game offsets:
--   * globals and field offsets are read from code signatures (AOB),
--   * object links are found by the type of the pointed object,
--   * data-class fields are read from Frostbite reflection.
-- Symbols (refreshed every second):
--   fbPlayer, fbBank, fbVehicle, fbNOS, fbNOSReserve, fbNOSCapacity,
--   fbSpeed (Float32, m/s), fbCash (Int64, banked cash)
-- ============================================================================
FB = FB or {}
FB.module = "NeedForSpeedUnbound.exe"

-- Code signatures. Every match must give the same values.
--   rip : index of a rip-relative disp32 -&gt; absolute address of a global
--   i32 : index of a disp32 field offset
--   u8  : index of a disp8 field offset
FB.SIGS = {
  -- mov [ClientBankEntity global], rdi (constructor)
  { aob = "48 89 3D ?? ?? ?? ?? E8 ?? ?? ?? ?? 4C 8D 46 10 41 B1 01 48 8D 15",
    rip = { bankGlobal = 3 } },
  -- mov rcx, [ClientUnlockManager global] ; test rcx,rcx ; je ; test rdx,rdx ; je ; call
  { aob = "48 8B 0D ?? ?? ?? ?? 48 85 C9 74 ?? 48 85 D2 74 ?? E8",
    rip = { unlockGlobal = 3 } },
  -- NOS gauge update: gauge = clamp(reserve / config.Capacity, 0, 1)
  { aob = "48 8B 83 ?? ?? ?? ?? 48 8D 8B ?? ?? ?? ?? F3 0F 10 48 ?? 0F 2F 0D ?? ?? ?? ?? 77 ?? " ..
          "0F 2F 0D ?? ?? ?? ?? 72 ?? B8 01 00 00 00 EB 02 33 C0 84 C0 74 ?? F3 0F 11 75 ?? " ..
          "0F 28 C6 EB ?? F3 0F 10 83 ?? ?? ?? ?? F3 0F 5E C1",
    i32 = { nosConfig = 3, nosReserve = 64 }, site = "nosGauge" },
  -- car speed: [car+X] = vehicle-&gt;GetSpeed()
  { aob = "48 8B 87 ?? ?? ?? ?? 48 8B C8 48 8B 10 FF 92 ?? ?? ?? ?? F6 87 ?? ?? ?? ?? 04 " ..
          "4C 8B BC 24 ?? ?? ?? ?? 4C 8B B4 24 ?? ?? ?? ?? F3 0F 11 87",
    i32 = { carSpeed = 46 } },
  -- bank transaction: lea rcx,[bank+balances] ; ... ; call map lookup
  { aob = "48 8D 8F ?? ?? ?? ?? 4C 89 B4 24 ?? ?? ?? ?? 48 8B D3 E8 ?? ?? ?? ?? 48 8D 8F",
    i32 = { bankBalances = 3 } },
  -- std::map&lt;uint32, ...&gt;::lower_bound (root, key and child offsets)
  { aob = "48 8B 41 ?? 48 8B F2 48 8B F9 48 8B D9 48 85 C0 74 ?? 8B 0A 0F 1F 40 00 " ..
          "39 48 ?? 72 ?? 48 8B D8 48 8B 40 ??",
    u8 = { mapRoot = 3, mapKey = 26, mapLeft = 35 } },
}

-- ---------------------------------------------------------------- helpers ---
local function isPtr(p) return p and p &gt; 0x10000 and p &lt; 0x7FFFFFFFFFFF end

-- align: 8 for pointer values (much faster on the whole heap)
function FB.scan(aob, startAddr, stopAddr, prot, align)
  local ms = createMemScan()
  ms.firstScan(soExactValue, vtByteArray, rtRounded, aob, nil, startAddr, stopAddr, prot or "",
    align and fsmAligned or fsmNotAligned, align and tostring(align) or "1", true, false, false, false)
  ms.waitTillDone()
  local fl = createFoundList(ms); fl.initialize()
  local t = {}
  for i = 0, fl.Count - 1 do t[#t + 1] = tonumber(fl.Address[i], 16) end
  fl.destroy(); ms.destroy()
  return t
end

-- Background jobs, run one at a time so that memory scans never pile up.
--   work() runs in a background thread, done(result) back in the main thread
--   (done(nil) if work failed).
FB.jobs = FB.jobs or {}

local function nextJob()
  local job = table.remove(FB.jobs, 1)
  FB.jobRunning = job ~= nil
  if not job then return end
  createThread(function(thread)
    thread.Name = "FB job"
    local ok, result = pcall(job.work)
    synchronize(function()
      if ok then
        local okDone, err = pcall(job.done, result)
        if not okDone then print("[FB] " .. tostring(err)) end
      else
        print("[FB] " .. tostring(result))
        pcall(job.done, nil)
      end
      nextJob()
    end)
  end)
end

function FB.background(work, done)
  FB.jobs[#FB.jobs + 1] = { work = work, done = done or function() end }
  if not FB.jobRunning then nextJob() end
end

-- ------------------------------------------------------------- code caves ---
-- Every code cave of the table comes from one 64 KB block allocated in a free
-- region within reach of a 5-byte jump from anywhere in the game module.
-- Hooks are always written as "jmp rel32" + nops over exactly the bytes of
-- the replaced instructions: never a longer jump that would overwrite more.
-- The block starts with a hook registry (site, size, original bytes) kept in
-- the game process: if Cheat Engine is closed with hooks still in place, the
-- next session finds the block and puts the game code back.
local REACH = 0x7FF00000
local MAGIC = "FBTK hooks v1"
local MAX_HOOKS, ENTRY, FIRST_CAVE = 64, 0x20, 0x1000
-- header: +00 magic | +10 u32 hook count | +14 u32 next free offset

local function inReach(a, b) return math.abs(a - b) &lt; REACH end

local function moduleRange()
  local base = getAddress(FB.module)
  return base, base + getModuleSize(FB.module)
end

local function setPool(block)
  FB.pool = { pid = getOpenedProcessID(), block = block }
end

-- Finds the block of a previous session and undoes its hooks still in place.
function FB.restoreStaleHooks()
  if FB.pool and FB.pool.pid == getOpenedProcessID() then return end   -- same session
  local base, stop = moduleRange()
  local hex = {}
  for c in MAGIC:gmatch(".") do hex[#hex + 1] = string.format("%02X", c:byte()) end
  for _, block in ipairs(FB.scan(table.concat(hex, " "), math.max(stop - REACH, 0x10000), base + REACH, "+X")) do
    if block &amp; 0xFFFF == 0 then
      for i = 0, (readInteger(block + 0x10) or 0) - 1 do
        local e = block + 0x20 + i * ENTRY
        local site, size = readQword(e), readBytes(e + 8, 1)
        local b = readBytes(site, 1)
        local target = b == 0xE9 and site + 5 + readInteger(site + 1, true)
        if target and target &gt;= block and target &lt; block + 0x10000 then
          writeBytes(site, readBytes(e + 9, size, true))
        end
      end
      if not FB.pool or FB.pool.pid ~= getOpenedProcessID() then setPool(block) end
    end
  end
end

function FB.caveAlloc(size)
  if not FB.pool or FB.pool.pid ~= getOpenedProcessID() then
    local base, stop = moduleRange()
    local block
    for _, r in ipairs(enumMemoryRegions()) do
      local a = (r.BaseAddress + 0xFFFF) &amp; ~0xFFFF
      if r.State == 0x10000 and a + 0x10000 &lt;= r.BaseAddress + r.RegionSize
         and inReach(a, base) and inReach(a + 0x10000, stop) then
        local got = allocateMemory(0x10000, a)
        if got and inReach(got, base) and inReach(got + 0x10000, stop) then block = got break end
        if got then deAlloc(got) end
      end
    end
    if not block then error("No free memory within reach of the game code") end
    writeString(block, MAGIC)
    writeInteger(block + 0x10, 0)
    writeInteger(block + 0x14, FIRST_CAVE)
    setPool(block)
  end
  local block = FB.pool.block
  local a = block + readInteger(block + 0x14)
  if a + size &gt; block + 0x10000 then error("Code cave block full") end
  writeInteger(block + 0x14, ((a + size + 0xF) &amp; ~0xF) - block)
  return a
end

-- Writes "jmp target" + nops over the size bytes at site (5 to 15 bytes),
-- after recording the original bytes in the registry.
function FB.writeJump(site, target, size)
  local rel = target - (site + 5)
  if size &lt; 5 or size &gt; 15 or not inReach(target, site) then
    error(string.format("Jump from %X cannot reach %X", site, target))
  end
  local block = FB.pool.block
  local count = readInteger(block + 0x10)
  local known = false
  for i = 0, count - 1 do if readQword(block + 0x20 + i * ENTRY) == site then known = true end end
  if not known and readBytes(site, 1) ~= 0xE9 then
    if count &gt;= MAX_HOOKS then error("Hook registry full") end
    local e = block + 0x20 + count * ENTRY
    writeQword(e, site)
    writeBytes(e + 8, size)
    writeBytes(e + 9, readBytes(site, size, true))
    writeInteger(block + 0x10, count + 1)
  end
  local b = { 0xE9 }
  for i = 0, 3 do b[#b + 1] = (rel &gt;&gt; (i * 8)) &amp; 0xFF end
  for _ = 6, size do b[#b + 1] = 0x90 end
  writeBytes(site, b)   -- keeps the page protection (signature scans skip writable code)
end

-- ------------------------------------------------------------- reflection ---
-- TypeInfo     : +00 TypeInfoData*
-- TypeInfoData : +00 name | +0E u16 size | +32 u16 fieldCount | +38 super | +40 fields
-- FieldInfo    : +00 name | +0E u16 offset | +10 TypeInfo*   (stride 0x18)
-- Array field  : pointer to the elements, u32 count stored just before them
function FB.name(ti)
  local d = isPtr(ti) and readQword(ti)
  local p = isPtr(d) and readQword(d)
  local n = isPtr(p) and readString(p, 128)
  if n and n:match("^[%w_:%[%]&lt;&gt;]+$") then return n end
end

function FB.size(ti)
  local d = readQword(ti)
  return d and readSmallInteger(d + 0x0E)
end

-- Type of an object, from the first virtual function (GetType):
--   entities       : lea rax,[TypeInfo] ; ret
--   data containers: mov rax,[rcx+disp8] ; ret
function FB.typeOf(obj)
  if not isPtr(obj) then return nil end
  local vt = readQword(obj); if not isPtr(vt) then return nil end
  local fn = readQword(vt);  if not isPtr(fn) then return nil end
  local b = readBytes(fn, 8, true); if not b then return nil end
  local ti
  if b[1] == 0x48 and b[2] == 0x8D and b[3] == 0x05 and b[8] == 0xC3 then
    ti = fn + 7 + readInteger(fn + 3, true)
  elseif b[1] == 0x48 and b[2] == 0x8B and b[3] == 0x41 and b[5] == 0xC3 then
    ti = readQword(obj + b[4])
  end
  if ti then return FB.name(ti), ti end
end

function FB.fields(ti)
  local list, depth = {}, 0
  while isPtr(ti) and depth &lt; 32 do
    local d = readQword(ti)
    local count = readSmallInteger(d + 0x32) or 0
    -- classes keep their field list at +40, value types at +68
    local f = readQword(d + 0x40)
    local n = isPtr(f) and readQword(f)
    if not (isPtr(n) and (readString(n, 80) or ""):match("^[%w_]+$")) then f = readQword(d + 0x68) end
    if isPtr(f) and count &lt; 2000 then
      for k = 0, count - 1 do
        local e = f + k * 0x18
        local np = readQword(e)
        list[#list + 1] = { name = isPtr(np) and readString(np, 80) or "?",
                            offset = readSmallInteger(e + 0x0E),
                            type = FB.name(readQword(e + 0x10)) or "?" }
      end
    end
    local super = readQword(d + 0x38)
    ti = (isPtr(super) and FB.name(super)) and super or nil
    depth = depth + 1
  end
  return list
end

-- Offset of a field of a type, by name.
function FB.fieldOffset(ti, fieldName)
  for _, f in ipairs(FB.fields(ti)) do
    if f.name == fieldName then return f.offset end
  end
end

-- Address of a reflected field of a data object, by name.
function FB.field(obj, fieldName)
  local _, ti = FB.typeOf(obj)
  if not ti then return nil end
  for _, f in ipairs(FB.fields(ti)) do
    if f.name == fieldName then return obj + f.offset end
  end
end

-- Elements of a reflected array field.
function FB.array(obj, fieldName)
  local a = FB.field(obj, fieldName)
  local p = a and readQword(a)
  local list = {}
  if isPtr(p) then
    for i = 0, (readInteger(p - 4) or 0) - 1 do list[#list + 1] = readQword(p + i * 8) end
  end
  return list
end

-- First pointer inside obj whose target has the given type.
function FB.findPtr(obj, typeName, size)
  if not isPtr(obj) then return nil end
  if not size then
    local _, ti = FB.typeOf(obj)
    size = ti and FB.size(ti) or 0
  end
  for o = 0, size - 8, 8 do
    local p = readQword(obj + o)
    if isPtr(p) and FB.typeOf(p) == typeName then return p end
  end
end

-- Slow helpers (memory scans): call them from a background thread only.
local function qwordAob(v)
  local t = {}
  for i = 0, 7 do t[#t + 1] = string.format("%02X", (v &gt;&gt; (i * 8)) &amp; 0xFF) end
  return table.concat(t, " ")
end

-- TypeInfo by name: name string -&gt; TypeInfoData -&gt; TypeInfo (cached). Several
-- types can share a name: give a field name to pick the right one.
FB.typeCache = FB.typeCache or {}

function FB.typeByName(name, fieldName)
  local key = name .. "." .. (fieldName or "")
  local c = FB.typeCache[key]
  if c and c.pid == getOpenedProcessID() then return c.ti end
  local ti = FB.findType(name, fieldName)
  if ti then FB.typeCache[key] = { pid = getOpenedProcessID(), ti = ti } end
  return ti
end

function FB.findType(name, fieldName)
  local base = getAddress(FB.module)
  local stop = base + getModuleSize(FB.module)
  local hex = {}
  for c in name:gmatch(".") do hex[#hex + 1] = string.format("%02X", c:byte()) end
  hex[#hex + 1] = "00"
  for _, s in ipairs(FB.scan(table.concat(hex, " "), base, stop, "")) do
    if readBytes(s - 1, 1) == 0 then
      for _, d in ipairs(FB.scan(qwordAob(s), base, stop, "", 8)) do
        for _, ti in ipairs(FB.scan(qwordAob(d), base, stop, "", 8)) do
          if FB.name(ti) == name and (not fieldName or FB.fieldOffset(ti, fieldName)) then return ti end
        end
      end
    end
  end
end

-- Live entities of a type: entity -&gt; vtable -&gt; "lea rax,[TypeInfo] ; ret".
function FB.entities(name)
  if not getAddressSafe(FB.module) then return {} end       -- game not running
  local base = getAddress(FB.module)
  local stop = base + getModuleSize(FB.module)
  local ti = FB.typeByName(name)
  local list = {}
  if not ti then return list end
  for _, fn in ipairs(FB.scan("48 8D 05 ?? ?? ?? ?? C3", base, stop, "+X-W")) do
    if fn + 7 + readInteger(fn + 3, true) == ti then
      for _, vt in ipairs(FB.scan(qwordAob(fn), base, stop, "-X", 8)) do
        for _, obj in ipairs(FB.scan(qwordAob(vt), 0x10000, 0x7FFFFFFFFFFF, "+W-C", 8)) do
          if FB.typeOf(obj) == name then list[#list + 1] = obj end
        end
      end
    end
  end
  return list
end

-- Values of an enum, from one of its members: { [member name] = value }.
-- Enum members are consecutive FieldInfos { name, hash, value }.
function FB.enumValues(member)
  local base = getAddress(FB.module)
  local stop = base + getModuleSize(FB.module)
  local prefix = member:match("^(.*_)")
  local hex = {}
  for c in member:gmatch(".") do hex[#hex + 1] = string.format("%02X", c:byte()) end
  hex[#hex + 1] = "00"
  for _, s in ipairs(FB.scan(table.concat(hex, " "), base, stop, "")) do
    if readBytes(s - 1, 1) == 0 then
      for _, e in ipairs(FB.scan(qwordAob(s), base, stop, "", 8)) do
        local function name(at) return readString(readQword(at) or 0, 96) or "" end
        while name(e - 0x18):sub(1, #prefix) == prefix do e = e - 0x18 end
        local values = {}
        while name(e):sub(1, #prefix) == prefix do
          values[name(e)] = readInteger(e + 0x10)
          e = e + 0x18
        end
        return values
      end
    end
  end
  return {}
end

-- Offset of the TypeInfo in a data container ("mov rax,[rcx+disp8] ; ret"),
-- read from a data container that always exists: the bank's data.
local function dataTypeSlot()
  local data = FB.findPtr(FB.bank(), "BankEntityData")
  local fn = data and readQword(readQword(data))
  local b = fn and readBytes(fn, 5, true)
  if b and b[1] == 0x48 and b[2] == 0x8B and b[3] == 0x41 and b[5] == 0xC3 then return b[4] end
end

-- Loaded data objects of a type. Only real data containers are kept: other
-- small objects also store a TypeInfo, at another place.
function FB.instances(ti)
  local slot = dataTypeSlot()
  local list = {}
  if not slot then return list end
  for _, p in ipairs(FB.scan(qwordAob(ti), 0x10000, 0x7FFFFFFFFFFF, "+W-C", 8)) do
    local obj = p - slot
    local fn = isPtr(readQword(obj)) and readQword(readQword(obj))
    local _, t = FB.typeOf(obj)
    if t == ti and readBytes(fn + 3, 1) == slot then list[#list + 1] = obj end
  end
  return list
end

-- -------------------------------------------------------------- signatures ---
-- Runs once; fills FB.off. Returns nil and an error message on failure.
-- "+X-W" = executable, non-writable memory (skips the large packed RWX section).
function FB.resolve()
  local base = getAddress(FB.module)
  local stop = base + getModuleSize(FB.module)
  local off = {}
  for i, sig in ipairs(FB.SIGS) do
    local hits = FB.scan(sig.aob, base, stop, "+X-W")
    if #hits == 0 then return nil, "signature #" .. i .. " not found" end
    for _, a in ipairs(hits) do
      local values = {}
      for name, idx in pairs(sig.rip or {}) do values[name] = a + idx + 4 + readInteger(a + idx, true) end
      for name, idx in pairs(sig.i32 or {}) do values[name] = readInteger(a + idx, true) end
      for name, idx in pairs(sig.u8 or {}) do values[name] = readBytes(a + idx, 1) end
      if sig.site then values[sig.site] = a end
      for name, v in pairs(values) do
        if off[name] and off[name] ~= v then
          return nil, "signature #" .. i .. ": ambiguous value for " .. name
        end
        off[name] = v
      end
    end
  end
  FB.off = off
  return off
end

-- ----------------------------------------------------------------- objects ---
function FB.player()
  local mgr = readQword(FB.off.unlockGlobal)
  if FB.typeOf(mgr) ~= "ClientUnlockManager" then return nil end
  return FB.findPtr(mgr, "ClientPlayer")
end

function FB.bank()
  local b = readQword(FB.off.bankGlobal)
  if FB.typeOf(b) == "ClientBankEntity" then return b end
end

function FB.vehicle(player)
  return FB.findPtr(player or FB.player(), "ClientRaceVehicleEntity")
end

-- NOS components seen by the game's NOS gauge update, which runs for every
-- car with nitro. A small hook stores each component it processes in a ring
-- of 16 slots; the player's one is the component that points to the
-- physics component of the player's vehicle. No memory scan needed.
local RING = 16   -- slots of the ring written by the NOS hook (see FB.nosHook)

function FB.nosHook(on)
  local h = FB.nosRing
  if not h or h.pid ~= getOpenedProcessID() then
    local site = FB.off.nosGauge
    local size = getInstructionSize(site)   -- "mov rax,[rbx+config]", moved into the cave
    if size &lt; 5 then error("NOS hook: instruction too short") end
    -- ring: 16 qwords | +80 write index | +88 player's NOS | +90 infinite on | +94 capacity offset
    local cave = FB.caveAlloc(0x180)
    local ok = autoAssemble(string.format([[
label(fbNosRing)
registersymbol(fbNosRing)
label(done)
%X:
  pushfq
  push rax
  push rcx
  mov ecx,[fbNosRing+80]          // write index
  and ecx,F
  lea rax,[fbNosRing]             // rip-relative: the ring is next to the cave
  mov [rax+rcx*8],rbx             // rbx = NOS component being updated
  inc dword ptr [fbNosRing+80]
  cmp dword ptr [fbNosRing+90],0  // infinite nitro off
  je done
  cmp rbx,[fbNosRing+88]          // only the player's NOS component
  jne done
  mov rax,[rbx+%X]                // NOS config
  test rax,rax
  je done
  mov ecx,[fbNosRing+94]
  test ecx,ecx
  je done
  mov ecx,[rax+rcx]               // capacity
  mov [rbx+%X],ecx                // reserve = capacity (rbx is live: the game is updating it)
done:
  pop rcx
  pop rax
  popfq
  readmem(%X,%d)
  jmp %X
fbNosRing:
  dq 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  dd 0 0
  dq 0
  dd 0 0
]], cave, FB.off.nosConfig, FB.off.nosReserve, site, size, site + size))
    if not ok then error("NOS hook: cave assembly failed") end
    h = { pid = getOpenedProcessID(), site = site, size = size, cave = cave,
          original = readBytes(site, size, true), ring = getAddress("fbNosRing") }
    FB.nosRing = h
  end
  if on then
    FB.writeJump(h.site, h.cave, h.size)
  else
    writeBytes(h.site, h.original)
  end
end

-- Infinite nitro on/off (applied by the NOS hook, see FB.refresh).
function FB.nitroSet(on)
  FB.nitro = on or nil
  if FB.running then FB.refresh() end
end

-- Per-vehicle addresses (NOS and speed) from its NOS component.
function FB.nosInfo(nos)
  local cfg = readQword(nos + FB.off.nosConfig)
  local car = FB.findPtr(nos, "ClientCarComponent")
  return { nos = nos,
           reserve = nos + FB.off.nosReserve,
           capacity = FB.field(cfg, "Capacity"),
           capOffset = FB.field(cfg, "Capacity") and FB.field(cfg, "Capacity") - cfg,
           speed = car and car + FB.off.carSpeed }
end

-- The player's NOS component among the ones recorded by the hook.
function FB.findNOS(vehicle)
  local phys = FB.findPtr(vehicle, "ClientRaceVehiclePhysicsComponent")
  if not phys or not FB.nosRing then return nil end
  local seen = {}
  for i = 0, RING - 1 do
    local nos = readQword(FB.nosRing.ring + i * 8)
    if isPtr(nos) and not seen[nos] then
      seen[nos] = true
      local name, ti = FB.typeOf(nos)
      if name == "ClientNOSComponent" then
        local size = FB.size(ti)
        local block = readBytes(nos, size, true)
        if block then
          for o = 1, size - 7, 8 do
            local q = 0
            for k = 7, 0, -1 do q = (q &lt;&lt; 8) | block[o + k] end
            if q == phys then
              local info = FB.nosInfo(nos)
              info.vehicle = vehicle
              return info
            end
          end
        end
      end
    end
  end
end

-- Balance address of a currency, by alias (e.g. "BANK", "GAINS").
-- Balances are a std::map&lt;currency id, int64&gt; inside the bank entity.
function FB.balance(bank, alias)
  local data = FB.findPtr(bank, "BankEntityData")
  local id
  for _, c in ipairs(FB.array(data, "Currencies")) do
    local a = FB.field(c, "Alias")
    if a and readString(readQword(a), 32) == alias then
      id = readInteger(FB.field(c, "Id")) &amp; 0xFFFFFFFF
    end
  end
  if not id then return nil end
  local o = FB.off
  local map = bank + o.bankBalances
  local node, best = readQword(map + o.mapRoot), nil
  while isPtr(node) do
    if (readInteger(node + o.mapKey) &amp; 0xFFFFFFFF) &lt; id then
      node = readQword(node)
    else
      best, node = node, readQword(node + o.mapLeft)
    end
  end
  if best and best ~= map and (readInteger(best + o.mapKey) &amp; 0xFFFFFFFF) == id then
    return best + o.mapKey + 8 -- value follows the 4-byte key, 8-byte aligned
  end
end

-- ------------------------------------------------------------ server side ---
-- The game runs its own server in-process: ServerChaseManager keeps one chase
-- target per player, which points to the ServerPlayer. Searched once per game
-- session in the background; FB.serverPlayer() returns nil until then.
function FB.chaseManager()
  local c = FB.chase
  if not c or c.pid ~= getOpenedProcessID() then
    c = { pid = getOpenedProcessID() }
    FB.chase = c
  end
  if not c.manager and not c.searching then
    c.searching = true
    FB.background(function() return FB.entities("ServerChaseManager")[1] end,
      function(m) c.searching = false c.manager = m end)
  end
  return c.manager
end

-- The player's chase target: element of a manager vector pointing to a ServerPlayer.
function FB.chaseTarget()
  local m = FB.chaseManager()
  if not m then return nil end
  local _, ti = FB.typeOf(m)
  for o = 0, FB.size(ti) - 8, 8 do
    local p = readQword(m + o)
    local t = isPtr(p) and readQword(p)
    local sp = isPtr(t) and FB.findPtr(t, "ServerPlayer", 0x800)
    if sp then return t, sp end
  end
end

-- ------------------------------------------------------------------ health ---
-- Shared hook on the game's health setters, used by the "God mode",
-- "Wreck opponents on damage" and "Freeze opponents and police" scripts.
-- Every setter "movss [rcx+health],xmmN" jumps to a small cave:
--   rcx = player's health part         -&gt; new health = max      (god)
--   rcx = other race vehicle's health  -&gt; new health = 0        (freeze)
--                                         or 0 if it goes down  (wreck)
-- Hooks are installed while at least one feature is on.
FB.health = FB.health or { features = {} }
local H = FB.health

-- aob + index of "movss [rcx+health],xmmN" in the match
H.SETTERS = {
  -- generic: movss [rcx+h],xmm6 ; mov ecx,1 ; ucomiss ; cmove ; test ; jne ; mov edx,[rbx+disp32]
  { aob = "F3 0F 11 71 ?? B9 01 00 00 00 0F 2E B3 ?? ?? ?? ?? 0F 44 C1 84 C0 75 ?? 8B 93", at = 0 },
  -- race vehicle: sub rsp,28 ; cmp byte [rcx+disp32],0 ; mov r10,rcx ; movss [rcx+h],xmm1 ; je
  { aob = "48 83 EC 28 80 B9 ?? ?? ?? ?? 00 4C 8B D1 F3 0F 11 49 ?? 0F 84", at = 14 },
}

-- "movss xmm0,[rcx+disp8] ; ret" -&gt; disp8
local function getterDisp(fn)
  local b = fn and readBytes(fn, 6, true)
  if b and b[1] == 0xF3 and b[2] == 0x0F and b[3] == 0x10 and b[4] == 0x41 and b[6] == 0xC3 then
    return b[5]
  end
end

-- Health part of a vehicle: the sub-object of its health component whose
-- vtable holds the getter of the current health followed by the getter of
-- the max. Returns part, max offset, health component.
local function vehicleHealth(vehicle)
  local hc = FB.findPtr(vehicle, "ClientRaceVehicleHealthComponent")
  if not hc then return nil end
  local _, ti = FB.typeOf(hc)
  local base = getAddress(FB.module)
  local stop = base + getModuleSize(FB.module)
  for o = 8, FB.size(ti) - 8, 8 do
    local vt = readQword(hc + o)
    if vt and vt &gt;= base and vt &lt; stop then
      for slot = 0, 63 do
        local fn = readQword(vt + slot * 8)
        if not fn or fn &lt; base or fn &gt;= stop then break end
        if getterDisp(fn) == H.current then
          local maxDisp = getterDisp(readQword(vt + (slot + 1) * 8))
          if maxDisp then return hc + o, maxDisp, hc end
        end
      end
    end
  end
end

-- Data block read by the caves:
--   +00 player's health part   +08 max offset   +20 god (0 off, 1 on)
--   +28 player's server-side health part (0 = not found yet)
--   +0C mode for others (0 off, 1 on damage, 2 always)
--   +10 offset of the health part in its component   +18 component vtable
local function createCaves(sites)
  H.data = FB.caveAlloc(0x30)          -- next to the caves: rip-relative access
  unregisterSymbol("fbHealthData")
  registerSymbol("fbHealthData", H.data, true)
  H.hooks = {}
  H.current = readBytes(sites[1] + 4, 1)
  for i, site in ipairs(sites) do
    local xmm = (readBytes(site + 3, 1) &gt;&gt; 3) &amp; 7         -- register of the original store
    local CAVE_SIZE = 0x100
    local cave = FB.caveAlloc(CAVE_SIZE)
    local ok = autoAssemble(string.format([[
label(player)
label(others)
label(wreck)
label(apply)
%X:
  pushfq                  // the next game instruction may use the flags
  push rax
  cmp rcx,[fbHealthData]
  je player
  cmp rcx,[fbHealthData+28] // server-side copy of the player's health
  jne others
player:
  cmp dword ptr [fbHealthData+20],0 // the player is never wrecked or frozen
  je apply
  mov eax,[fbHealthData+8]
  movss xmm%d,[rcx+rax]   // player: new health = max
  jmp apply
others:
  cmp dword ptr [fbHealthData+C],0
  je apply
  mov rax,rcx
  sub rax,[fbHealthData+10]
  mov rax,[rax]
  cmp rax,[fbHealthData+18] // part of another race vehicle health component?
  jne apply
  cmp dword ptr [fbHealthData+C],2
  je wreck
  comiss xmm%d,[rcx+%X]   // health going down?
  jae apply
wreck:
  xorps xmm%d,xmm%d
apply:
  pop rax
  popfq
  readmem(%X,5)
  jmp %X
]], cave, xmm, xmm, H.current, xmm, xmm, site, site + 5))
    if not ok then error("Health: cave assembly failed") end
    -- the cave must end ("jmp site+5") inside its reserved space
    local a, last = cave, nil
    while a &lt; cave + CAVE_SIZE do
      if disassemble(a):find(string.format("jmp %X", site + 5), 1, true) then last = a break end
      a = a + getInstructionSize(a)
    end
    if not last or last + 5 &gt; cave + CAVE_SIZE then error("Health: cave larger than its reserved space") end
    H.hooks[i] = { site = site, original = readBytes(site, 5, true), cave = cave }
  end
end

-- Writes the data block from the enabled features and the player's vehicle.
local function update()
  if H.pid ~= getOpenedProcessID() then return end       -- game restarted
  local f = H.features
  local vehicle = FB.sym.fbVehicle
  if vehicle ~= H.vehicle then
    H.vehicle = vehicle
    H.target, H.maxDisp, H.hc = nil, nil, nil
    if vehicle then H.target, H.maxDisp, H.hc = vehicleHealth(vehicle) end
    unregisterSymbol("fbHealth")
    if H.target then registerSymbol("fbHealth", H.target + H.current, true) end
    H.server = nil
  end
  -- same part in the server-side health component of the player's vehicle
  if H.target and not (H.server and readQword(H.server) == H.serverVt) then
    local _, sp = FB.chaseTarget()
    local sv = sp and FB.findPtr(sp, "ServerRaceVehicleEntity")
    local shc = sv and FB.findPtr(sv, "ServerRaceVehicleHealthComponent")
    H.server = shc and shc + (H.target - H.hc)
    H.serverVt = H.server and readQword(H.server)
  end
  local mode = (f.freeze and 2) or (f.wreck and 1) or 0
  writeInteger(H.data + 8, H.maxDisp or 0)
  writeQword(H.data + 0x10, H.target and (H.target - H.hc) or 0)
  writeQword(H.data + 0x18, H.hc and readQword(H.hc) or 0)
  writeInteger(H.data + 0x0C, H.target and mode or 0)  -- needs the player's type as reference
  writeInteger(H.data + 0x20, f.god and 1 or 0)
  writeQword(H.data + 0x28, H.server or 0)
  writeQword(H.data, H.target or 0)
end

local function hook(on)
  for _, h in ipairs(H.hooks) do
    if on then
      FB.writeJump(h.site, h.cave, 5)
    else
      writeBytes(h.site, h.original)
    end
  end
  if H.timer then H.timer.destroy() H.timer = nil end
  if on then
    H.vehicle = false
    H.timer = createTimer(nil, false)
    H.timer.Interval = 1000
    H.timer.OnTimer = update
    H.timer.Enabled = true
    update()
  else
    unregisterSymbol("fbHealth")
  end
end

-- Turns a feature ("god", "wreck", "freeze") on or off.
function FB.healthSet(feature, on)
  if H.pid ~= getOpenedProcessID() then -- new game process: start from scratch
    if H.timer then H.timer.destroy() end
    H.pid, H.features, H.hooks, H.searching, H.timer = getOpenedProcessID(), {}, nil, false, nil
  end
  local wasActive = next(H.features) ~= nil
  H.features[feature] = on or nil
  local active = next(H.features) ~= nil
  if not H.hooks then
    if not active or H.searching then return end
    H.searching = true
    FB.background(function()
      local base = getAddress(FB.module)
      local stop = base + getModuleSize(FB.module)
      local sites = {}
      for i, s in ipairs(H.SETTERS) do
        local hits = FB.scan(s.aob, base, stop, "+X")
        if #hits ~= 1 then return string.format("setter #%d: %d matches (expected 1)", i, #hits) end
        sites[i] = hits[1] + s.at
      end
      return sites
    end, function(sites)
      H.searching = false
      if type(sites) ~= "table" then print("[Health] " .. tostring(sites)) return end
      createCaves(sites)
      if next(H.features) then hook(true) end
      print("[Health] ready")
    end)
  elseif active ~= wasActive then
    hook(active)
  elseif active then
    update()
  end
end

-- ------------------------------------------------------------ data tweaks ---
-- Changes fields of the game's loaded data objects (tuning tables).
--   spec.name   : unique key
--   spec.type   : reflected type name, spec.field: a field that type must have
--   spec.slots  : function(obj, ti) -&gt; addresses of the floats to change
--                 (runs in the background thread: may call the slow helpers)
--   spec.value  : function(original) -&gt; new value (nil = leave it)
--   spec.kind   : "float" (default) or "u8"
-- Applied every second. Objects are only written while they still have the
-- expected type, and are searched again (at most once a minute) once unloaded.
FB.tweaks = FB.tweaks or {}

local KINDS = {
  float = { read = readFloat, write = writeFloat },
  u8 = { read = function(a) return readBytes(a, 1) end, write = function(a, v) writeBytes(a, v) end },
}

function FB.tweakSet(spec, on)
  local t = FB.tweaks[spec.name]
  if not t or t.pid ~= getOpenedProcessID() then
    t = { pid = getOpenedProcessID(), tables = {} }
    FB.tweaks[spec.name] = t
  end
  t.spec = spec

  local function search()
    if t.searching then return end
    t.searching, t.lastSearch = true, getTickCount()
    FB.background(function()
      t.ti = t.ti or FB.typeByName(spec.type, spec.field)
      local tables = {}
      for _, obj in ipairs(t.ti and FB.instances(t.ti) or {}) do
        local slots = {}
        local ok, addrs = pcall(t.spec.slots, obj, t.ti)
        for _, a in ipairs(ok and addrs or {}) do
          slots[#slots + 1] = { addr = a, original = KINDS[t.spec.kind or "float"].read(a) }
        end
        tables[#tables + 1] = { obj = obj, slots = slots }
      end
      return tables
    end, function(tables)
      t.searching = false
      t.tables = tables or {}
      print(string.format("[%s] %d object(s) found", spec.name, #t.tables))
      if t.timer then t.apply() end
    end)
  end

  function t.apply(restore)
    if t.pid ~= getOpenedProcessID() then return end      -- game restarted
    local valid = 0
    for _, o in ipairs(t.tables) do
      local _, ti = FB.typeOf(o.obj)
      if ti and ti == t.ti then
        valid = valid + 1
        for _, s in ipairs(o.slots) do
          local v = s.original
          if not restore then v = t.spec.value(s.original) end
          if v then KINDS[t.spec.kind or "float"].write(s.addr, v) end
        end
      end
    end
    if not restore and valid == 0 and getTickCount() - (t.lastSearch or 0) &gt; 60000 then search() end
  end

  if t.timer then t.timer.destroy() t.timer = nil end
  if on then
    t.timer = createTimer(nil, false)
    t.timer.Interval = 1000
    t.timer.OnTimer = function() t.apply() end
    t.timer.Enabled = true
    if #t.tables &gt; 0 then t.apply() else search() end
  else
    t.apply(true)
  end
end

-- ------------------------------------------------------------------- heat ---
-- The player's heat (the 🔥 value, 0 to 5: its whole part is the pursuit
-- level) lives in the player's chase target, kept by the ServerChaseManager.
-- Its offset and maximum are read from the game's "add heat" function.
-- The target is never cached: every tick reads it again from the manager
-- (a session-long object), then writes at once. "watch" keeps fbHeat only.
FB.heat = FB.heat or { features = {} }
local HEAT = FB.heat

-- mov rbx,rcx ; movss xmm7,[rcx+heat] ; mov ecx,1 ; movaps xmm6,xmm7 ;
-- addss xmm6,xmm1 ; minss xmm6,[max]
HEAT.SIG = "48 8B D9 F3 0F 10 B9 ?? ?? ?? ?? B9 01 00 00 00 0F 28 F7 F3 0F 58 F1 F3 0F 5D 35"

-- Current chase target of the player, read from the manager right now.
-- The layout (which manager field, where the ServerPlayer pointer is) is
-- found once; addresses are never kept.
local function heatTarget()
  local h = HEAT
  local m = FB.chaseManager()
  if not m or FB.typeOf(m) ~= "ServerChaseManager" then return nil end
  if not h.vecOff then
    local _, ti = FB.typeOf(m)
    for o = 0, FB.size(ti) - 8, 8 do
      local p = readQword(m + o)
      local t = isPtr(p) and readQword(p)
      if isPtr(t) then
        for so = 0, 0x800 - 8, 8 do
          local sp = readQword(t + so)
          if isPtr(sp) and FB.typeOf(sp) == "ServerPlayer" then h.vecOff, h.spOff = o, so break end
        end
      end
      if h.vecOff then break end
    end
    if not h.vecOff then return nil end
  end
  local p = readQword(m + h.vecOff)
  local t = isPtr(p) and readQword(p)
  if isPtr(t) and FB.typeOf(readQword(t + h.spOff)) == "ServerPlayer" then return t end
end

local function heatTick()
  local h = HEAT
  if h.pid ~= getOpenedProcessID() or not h.offset then return end
  local t = heatTarget()
  local addr = t and t + h.offset
  if addr ~= h.symbol then
    unregisterSymbol("fbHeat")
    if addr then registerSymbol("fbHeat", addr, true) end
    h.symbol = addr
  end
  if not addr then return end
  local f = h.features
  if f.max then
    writeFloat(addr, h.max)
  elseif f.zero then
    writeFloat(addr, 0)
  elseif f.lock then
    local heat = readFloat(addr)
    if not h.locked or heat &lt; h.locked then h.locked = heat end   -- follows drops
    if heat &gt; h.locked then writeFloat(addr, h.locked) end
  end
  if not f.lock then h.locked = nil end
end

local function heatRun()
  if HEAT.timer then HEAT.timer.destroy() HEAT.timer = nil end
  HEAT.timer = createTimer(nil, false)
  HEAT.timer.Interval = 250
  HEAT.timer.OnTimer = heatTick
  HEAT.timer.Enabled = true
end

-- Turns a heat feature ("lock", "zero", "max", "watch") on or off.
function FB.heatSet(feature, on)
  if HEAT.pid ~= getOpenedProcessID() then                -- new game session
    if HEAT.timer then HEAT.timer.destroy() end
    HEAT.pid, HEAT.features, HEAT.offset, HEAT.timer = getOpenedProcessID(), {}, nil, nil
    HEAT.vecOff, HEAT.spOff, HEAT.symbol = nil, nil, nil
  end
  HEAT.features[feature] = on or nil
  if not next(HEAT.features) then
    if HEAT.timer then HEAT.timer.destroy() HEAT.timer = nil end
    unregisterSymbol("fbHeat") HEAT.symbol = nil
    return
  end
  FB.chaseManager()                                       -- starts its search if needed
  if HEAT.offset then heatRun() return end
  if HEAT.searching then return end
  HEAT.searching = true
  FB.background(function()
    local base = getAddress(FB.module)
    local hits = FB.scan(HEAT.SIG, base, base + getModuleSize(FB.module), "+X-W")
    if #hits ~= 1 then return "signature matches: " .. #hits .. " (expected 1)" end
    local a = hits[1]
    return { offset = readInteger(a + 7), max = readFloat(a + 31 + readInteger(a + 27, true)) }
  end, function(r)
    HEAT.searching = false
    if type(r) ~= "table" then print("[Heat] " .. tostring(r)) return end
    HEAT.offset, HEAT.max = r.offset, r.max
    print(string.format("[Heat] ready (max %.1f)", HEAT.max))
    if next(HEAT.features) then heatRun() end
  end)
end

-- ------------------------------------------------------------------ tires ---
-- The game's "set tire burst" function (rcx = wheel, dl = 1 burst / 0 fixed)
-- is intercepted at its start:
--   "mine"   : the player's wheels are never burst (dl forced to 0)
--   "others" : every other wheel is always burst (dl forced to 1)
-- A wheel belongs to the player when it points to the FBPhysicsComponent of
-- the player's vehicle; that field's offset is found once per session from
-- the live wheels.
FB.tires = FB.tires or { features = {} }
local TIRE = FB.tires

-- push rbx ; push rsi ; push rdi ; sub rsp,20 ; mov r8,[rcx+..] ;
-- movzx eax,dl ; movzx edi,dl ; mov rsi,rcx ; xor al,[r8+..]
TIRE.SIG = "40 53 56 57 48 83 EC 20 4C 8B 81 ?? ?? ?? ?? 0F B6 C2 0F B6 FA 48 8B F1 41 32 80"
TIRE.HOOK = 8      -- push rbx, push rsi, push rdi, sub rsp,20: moved into the cave
TIRE.CAVE = 0x100

-- Cave block: +00 player's FBPhysicsComponent | +08 its offset in a wheel |
-- +0C flags (1 mine, 2 others) | code at +10.
local function tireCave(site)
  local block = FB.caveAlloc(TIRE.CAVE)
  local data, code = block, block + 0x10
  local ok = autoAssemble(string.format([[
label(other)
label(done)
%X:
  dq 0
  dd 0 0
%X:
  pushfq
  push rax
  cmp qword ptr [%X],0          // player's vehicle not known yet
  je done
  mov eax,[%X]                  // offset of the physics component in a wheel
  test eax,eax
  je done
  mov rax,[rcx+rax]
  cmp rax,[%X]
  jne other
  test dword ptr [%X],1         // player's wheel: never burst
  je done
  xor edx,edx
  jmp done
other:
  test dword ptr [%X],2         // other wheels: always burst
  je done
  mov dl,1
done:
  pop rax
  popfq
  readmem(%X,%d)
  jmp %X
]], data, code, data, data + 8, data, data + 0xC, data + 0xC, site, TIRE.HOOK, site + TIRE.HOOK))
  if not ok then error("Tires: cave assembly failed") end
  local a, last = code, nil
  while a &lt; block + TIRE.CAVE do
    if disassemble(a):find(string.format("jmp %X", site + TIRE.HOOK), 1, true) then last = a break end
    a = a + getInstructionSize(a)
  end
  if not last or last + 5 &gt; block + TIRE.CAVE then error("Tires: cave larger than its reserved space") end
  return code, data
end

local function tireTick()
  local t = TIRE
  if t.pid ~= getOpenedProcessID() or not t.data then return end
  local f = t.features
  local phys = FB.sym.fbVehicle and FB.findPtr(FB.sym.fbVehicle, "FBPhysicsComponent")
  writeQword(t.data, phys or 0)
  writeInteger(t.data + 0xC, (f.mine and 1 or 0) + (f.others and 2 or 0))
end

local function tireApply()
  local t = TIRE
  local on = next(t.features) ~= nil
  if on and not t.cave then
    t.cave, t.data = tireCave(t.site)
    writeInteger(t.data + 8, t.physOff)
  end
  if t.cave then
    tireTick()
    if on then FB.writeJump(t.site, t.cave, TIRE.HOOK) else writeBytes(t.site, t.original) end
  end
  if on and not t.timer then
    t.timer = createTimer(nil, false)
    t.timer.Interval = 1000
    t.timer.OnTimer = tireTick
    t.timer.Enabled = true
  elseif not on and t.timer then
    t.timer.destroy() t.timer = nil
  end
end

-- Turns a tire feature ("mine", "others") on or off.
function FB.tireSet(feature, on)
  if TIRE.pid ~= getOpenedProcessID() then                -- new game session
    if TIRE.timer then TIRE.timer.destroy() end
    TIRE.pid, TIRE.features, TIRE.timer = getOpenedProcessID(), {}, nil
    TIRE.site, TIRE.cave, TIRE.data, TIRE.original, TIRE.physOff = nil, nil, nil, nil, nil
  end
  TIRE.features[feature] = on or nil
  if TIRE.site then tireApply() return end
  if TIRE.searching or not next(TIRE.features) then return end
  TIRE.searching = true
  print("[Tires] searching (about 20 s)...")
  FB.background(function()
    local base = getAddress(FB.module)
    local hits = FB.scan(TIRE.SIG, base, base + getModuleSize(FB.module), "+X-W")
    if #hits ~= 1 then return "signature matches: " .. #hits .. " (expected 1)" end
    -- offset of the vehicle's physics component in one of the player's wheels
    local phys = FB.sym.fbVehicle and FB.findPtr(FB.sym.fbVehicle, "FBPhysicsComponent")
    if not phys then return "player's vehicle not found" end
    for _, wheel in ipairs(FB.entities("ClientRaceWheelComponent")) do
      local _, ti = FB.typeOf(wheel)
      for o = 8, FB.size(ti) - 8, 8 do
        if readQword(wheel + o) == phys then return { site = hits[1], physOff = o } end
      end
    end
    return "player's wheels not found"
  end, function(r)
    TIRE.searching = false
    if type(r) ~= "table" then print("[Tires] " .. tostring(r)) return end
    TIRE.site, TIRE.physOff = r.site, r.physOff
    TIRE.original = readBytes(r.site, TIRE.HOOK, true)
    print(string.format("[Tires] ready (physics at +%X)", r.physOff))
    tireApply()
  end)
end

-- ----------------------------------------------------------------- symbols ---
local function setSymbol(name, addr)
  if FB.sym[name] == addr then return end
  unregisterSymbol(name)
  if addr then registerSymbol(name, addr, true) end
  FB.sym[name] = addr
end

function FB.refresh()
  local player = FB.player()
  local vehicle = FB.vehicle(player)
  local bank = FB.bank()
  -- Cheap check, redone every second until the player's NOS is found.
  local info = FB.lastInfo
  if not (vehicle and info and info.vehicle == vehicle
          and FB.typeOf(info.nos) == "ClientNOSComponent") then
    info = vehicle and FB.findNOS(vehicle)
    FB.lastInfo = info
  end
  setSymbol("fbPlayer", player)
  setSymbol("fbVehicle", vehicle)
  setSymbol("fbNOS", info and info.nos)
  -- infinite nitro is applied by the NOS hook itself, on the component the
  -- game is updating: never a write through a possibly stale pointer
  local ring = FB.nosRing and FB.nosRing.pid == getOpenedProcessID() and FB.nosRing.ring
  if ring then
    writeQword(ring + 0x88, info and info.nos or 0)
    writeInteger(ring + 0x94, info and info.capOffset or 0)
    writeInteger(ring + 0x90, FB.nitro and 1 or 0)
  end
  setSymbol("fbNOSReserve", info and info.reserve)
  setSymbol("fbNOSCapacity", info and info.capacity)
  setSymbol("fbSpeed", info and info.speed)
  setSymbol("fbBank", bank)
  setSymbol("fbCash", bank and FB.balance(bank, "BANK"))
end

-- Display type: Float32 m/s shown and edited as km/h.
local function registerSpeedType()
  if FB.speedTypeRegistered then return end
  registerCustomTypeLua("Speed km/h", 4,
    function(b1, b2, b3, b4)
      return string.unpack("&lt;f", string.char(b1, b2, b3, b4)) * 3.6
    end,
    function(v)
      return string.pack("&lt;f", v / 3.6):byte(1, 4)
    end, true)
  FB.speedTypeRegistered = true
end

-- Signature scans take a few seconds: run them in a background thread so
-- Cheat Engine stays responsive, then start the refresh timer.
function FB.start()
  FB.sym = FB.sym or {}
  FB.running = true
  -- our own NOS hook would hide signature #3 from the scan
  if FB.nosRing and FB.nosRing.pid == getOpenedProcessID() then FB.nosHook(false) end
  createThread(function(thread)
    thread.Name = "FB.resolve"
    FB.restoreStaleHooks()
    local ok, err = FB.resolve()
    synchronize(function()
      if not FB.running then return end
      if not ok then print("[FB] " .. err) return end
      registerSpeedType()
      FB.nosHook(true)
      FB.lastInfo = nil
      FB.refresh()
      if FB.timer then FB.timer.destroy() end
      FB.timer = createTimer(nil, false)
      FB.timer.Interval = 1000
      FB.timer.OnTimer = function() FB.refresh() end
      FB.timer.Enabled = true
      print("[FB] ready")
    end)
  end)
end

function FB.stop()
  FB.running = false
  if FB.timer then FB.timer.destroy() FB.timer = nil end
  if FB.nosRing and FB.nosRing.pid == getOpenedProcessID() then FB.nosHook(false) end
  for name in pairs(FB.sym or {}) do unregisterSymbol(name) end
  FB.sym = {}
end

FB.start()
[DISABLE]
{$lua}
if syntaxcheck then return end
FB.stop()
</AssemblerScript>
      <CheatEntries>
        <CheatEntry>
          <ID>27034</ID>
          <Description>"Nitro"</Description>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>27035</ID>
              <Description>"Infinite nitro"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Infinite nitro: the player's NOS reserve stays at full capacity. Applied
-- inside the toolkit's NOS hook, on the component the game is updating.
if not (FB and FB.running and FB.nitroSet) then error("Enable 'Frostbite Toolkit' first") end
if NITRO_TIMER then NITRO_TIMER.destroy() NITRO_TIMER = nil end   -- previous version
FB.nitroSet(true)

[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.nitroSet then FB.nitroSet(false) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27036</ID>
              <Description>"NOS reserve (s)"</Description>
              <VariableType>Float</VariableType>
              <Address>fbNOSReserve</Address>
            </CheatEntry>
            <CheatEntry>
              <ID>27037</ID>
              <Description>"NOS capacity (s) - shared by all cars using this NOS config"</Description>
              <VariableType>Float</VariableType>
              <Address>fbNOSCapacity</Address>
            </CheatEntry>
            <CheatEntry>
              <ID>27038</ID>
              <Description>"Speed (km/h)"</Description>
              <VariableType>Custom</VariableType>
              <CustomType>Speed km/h</CustomType>
              <Address>fbSpeed</Address>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>27040</ID>
          <Description>"Money"</Description>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>27041</ID>
              <Description>"Credit multiplier"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Credit multiplier: multiplies every bank credit (rewards cashed in at the
-- garage, escape bounties...) by "Credit multiplier (x)". Debits are untouched.
-- The game's credit instruction is found by signature and its original bytes
-- are copied into the code cave, so no game offset is hardcoded here.
if not (FB and FB.running) then error("Enable 'Frostbite Toolkit' first") end

-- State survives disable/enable, but not a game restart.
if not CREDIT or CREDIT.pid ~= getOpenedProcessID() then
  CREDIT = { pid = getOpenedProcessID() }
end

-- mov rdx,[rcx+amount] ; je debit ; add [rax+balance],rdx ; jmp next ; sub [rax+balance],rdx
local AOB = "48 8B 51 20 74 06 48 01 50 38 EB 04 48 29 50 38"
local ADD = 6  -- "add [rax+balance],rdx" (4 bytes) + "jmp short next" (2 bytes)

-- The cave is created once and kept: no thread can ever jump into freed memory.
local function createCave(add)
  local next = add + 6 + readBytes(add + 5, 1)          -- target of the short jump
  local cave = FB.caveAlloc(0x40)
  local ok = autoAssemble(string.format([[
label(fbCreditFactor)
registersymbol(fbCreditFactor)

%X:
  imul rdx,[fbCreditFactor]
  readmem(%X,4)
  jmp %X

fbCreditFactor:
  dq #10
]], cave, add, next))
  if not ok then error("Credit multiplier: cave assembly failed") end
  CREDIT.site, CREDIT.original, CREDIT.cave = add, readBytes(add, 6, true), cave
end

local function hook()
  FB.writeJump(CREDIT.site, CREDIT.cave, 6)
  print(string.format("[Credit] ready at %X", CREDIT.site))
end

if CREDIT.site then
  hook()
else
  print("[Credit] searching the credit instruction...")
  createThread(function()
    local base = getAddress(FB.module)
    local hits = FB.scan(AOB, base, base + getModuleSize(FB.module), "+X")
    synchronize(function()
      if #hits ~= 1 then print("[Credit] signature matches: " .. #hits .. " (expected 1)") return end
      createCave(hits[1] + ADD)
      hook()
    end)
  end)
end

[DISABLE]
{$lua}
if syntaxcheck then return end
if CREDIT and CREDIT.site and CREDIT.pid == getOpenedProcessID() then writeBytes(CREDIT.site, CREDIT.original) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27042</ID>
              <Description>"Credit multiplier (x)"</Description>
              <ShowAsSigned>1</ShowAsSigned>
              <VariableType>8 Bytes</VariableType>
              <Address>fbCreditFactor</Address>
            </CheatEntry>
            <CheatEntry>
              <ID>27039</ID>
              <Description>"Cash (bank) - display copy"</Description>
              <ShowAsSigned>1</ShowAsSigned>
              <VariableType>8 Bytes</VariableType>
              <Address>fbCash</Address>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>27043</ID>
          <Description>"Driving"</Description>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>27044</ID>
              <Description>"God mode (player vehicle)"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
if not (FB and FB.running and FB.healthSet) then error("Enable 'Frostbite Toolkit' first") end
FB.healthSet("god", true)
[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.healthSet then FB.healthSet("god", false) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27050</ID>
              <Description>"Wreck opponents on damage"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
if not (FB and FB.running and FB.healthSet) then error("Enable 'Frostbite Toolkit' first") end
FB.healthSet("wreck", true)
[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.healthSet then FB.healthSet("wreck", false) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27051</ID>
              <Description>"Freeze opponents and police"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
if not (FB and FB.running and FB.healthSet) then error("Enable 'Frostbite Toolkit' first") end
FB.healthSet("freeze", true)
[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.healthSet then FB.healthSet("freeze", false) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27045</ID>
              <Description>"Health (player vehicle)"</Description>
              <VariableType>Float</VariableType>
              <Address>fbHealth</Address>
            </CheatEntry>
            <CheatEntry>
              <ID>27058</ID>
              <Description>"Gas Station Always Available"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Gas Station Always Available: removes the waiting time of service (gas)
-- stations between two uses, in free roam, chases and extractions. Every
-- "ServiceStation...Cooldown" setting of CollectablesSettings is set to 0.
if not (FB and FB.running and FB.tweakSet) then error("Enable 'Frostbite Toolkit' first") end

FB.tweakSet({
  name = "GasStation", type = "CollectablesSettings", field = "ServiceStationCooldown",
  slots = function(settings, ti)
    local list = {}
    for _, f in ipairs(FB.fields(ti)) do
      if f.type == "Float32" and f.name:find("^ServiceStation") and f.name:find("Cooldown") then
        list[#list + 1] = settings + f.offset
      end
    end
    return list
  end,
  value = function() return 0 end,
}, true)

[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.tweakSet and FB.tweaks["GasStation"] then FB.tweakSet(FB.tweaks["GasStation"].spec, false) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27066</ID>
              <Description>"No Tire Damage"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- No Tire Damage: the player's tires never burst (spike strips...).
if not (FB and FB.running and FB.tireSet) then error("Enable 'Frostbite Toolkit' first") end
FB.tireSet("mine", true)

[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.tireSet then FB.tireSet("mine", false) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27067</ID>
              <Description>"Instant Tire Damage"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Instant Tire Damage: the tires of every other car are always burst.
if not (FB and FB.running and FB.tireSet) then error("Enable 'Frostbite Toolkit' first") end
FB.tireSet("others", true)

[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.tireSet then FB.tireSet("others", false) end
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>27047</ID>
          <Description>"Events"</Description>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>27048</ID>
              <Description>"Takeover Score Multiplier"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Takeover Score Multiplier: multiplies the points given by every scoring
-- action of Takeover events (drift, airborne, smashables, speed traps, boost,
-- checkpoints...) in the game's scoring tables, so the real banked score is
-- multiplied. Penalties (negative points) are left untouched.
-- Factor: "Takeover Score Multiplier (x)". Enable it before the event starts.
if not (FB and FB.running and FB.tweakSet) then error("Enable 'Frostbite Toolkit' first") end
if not getAddressSafe("fbScoreFactor") then
  autoAssemble("alloc(fbScoreFactor,4)\nregistersymbol(fbScoreFactor)\nfbScoreFactor:\n  dd (float)10\n")
end

FB.tweakSet({
  name = "Score", type = "SpeedCrossScoringActionsAsset", field = "TrackedActionScoring",
  slots = function(asset, ti)
    local list = { asset + FB.fieldOffset(ti, "DefaultCheckpointScore") }
    local scorer = FB.typeByName("SpeedCrossScorer", "ScoreToAdd")      -- array element type
    local p = readQword(asset + FB.fieldOffset(ti, "TrackedActionScoring"))
    if scorer and p then
      local stride, points = FB.size(scorer), FB.fieldOffset(scorer, "ScoreToAdd")
      for i = 0, (readInteger(p - 4) or 0) - 1 do list[#list + 1] = p + i * stride + points end
    end
    return list
  end,
  value = function(points)
    if points &gt; 0 then return points * (readFloat("fbScoreFactor") or 1) end
  end,
}, true)

[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.tweakSet and FB.tweaks["Score"] then FB.tweakSet(FB.tweaks["Score"].spec, false) end

</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27049</ID>
              <Description>"Takeover Score Multiplier (x)"</Description>
              <VariableType>Float</VariableType>
              <Address>fbScoreFactor</Address>
            </CheatEntry>
            <CheatEntry>
              <ID>27068</ID>
              <Description>"Easy Win (Drift Zone)"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Easy Win (Drift Zone): whatever your drifting, a drift zone ends with at
-- least the four-star score. When the zone ends, your score becomes at least
-- the four-star score (+0.1 %) before the game computes stars and results;
-- a higher real score is kept. Only drift zone objects are changed.
-- All offsets come from the game's code (signatures).
if not (FB and FB.running and FB.caveAlloc) then error("Enable 'Frostbite Toolkit' first") end

if not EASYDZ or EASYDZ.pid ~= getOpenedProcessID() then
  EASYDZ = { pid = getOpenedProcessID() }
end

-- drift zone end (entry): computes the stars, then calls the event finish
local ENTRY_SIG = "48 89 5C 24 08 57 48 83 EC 20 48 83 B9 ?? ?? ?? ?? 00 48 8B F9 74 ?? 48 8B 81 ?? ?? ?? ?? 48 8B 50 08 48 2B 10 48 C1 FA 07"
-- event finish: cmp byte [rdi+lowerIsBetter],0 / jne / movss xmm0,[rdi+best] / comiss xmm0,[rdi+score]
local CMP_SIG = "80 BF ?? ?? ?? ?? 00 75 ?? F3 0F 10 87 ?? ?? ?? ?? 0F 2F 87 ?? ?? ?? ?? 72 ?? 80 BF"
local SCORE_DISP = 20
-- star targets set from the event data: last store = four-star target
local STAR_SIG = "F3 0F 10 48 ?? F3 0F 59 CA F3 0F 11 8B ?? ?? ?? ?? F3 0F 10 40 ?? F3 0F 59 C2 F3 0F 11 83 ?? ?? ?? ?? 48 83 C4 20 5B C3"
local STAR_DISP = 30
local SIZE = 5      -- "mov [rsp+08],rbx", moved into the cave
local CAVE = 0x80

local function createCave(r)
  local cave = FB.caveAlloc(CAVE)
  local ok = autoAssemble(string.format([[
label(vt)
label(k)
label(orig)
%X:
  push rax
  mov rax,[vt]
  cmp [rcx],rax                   // drift zone object?
  pop rax
  jne orig
  sub rsp,10
  movdqu [rsp],xmm0
  movss xmm0,[rcx+%X]             // four-star score
  mulss xmm0,[k]
  maxss xmm0,[rcx+%X]             // score = max(score, target * 1.001)
  movss [rcx+%X],xmm0
  movdqu xmm0,[rsp]
  add rsp,10
orig:
  readmem(%X,%d)
  jmp %X
vt:
  dq %X
k:
  dd (float)1.001
]], cave, r.star, r.score, r.score, r.site, SIZE, r.site + SIZE, r.vt))
  if not ok then error("Easy Win (Drift Zone): cave assembly failed") end
  local a, last = cave, nil
  while a &lt; cave + CAVE do
    if disassemble(a):find(string.format("jmp %X", r.site + SIZE), 1, true) then last = a break end
    a = a + getInstructionSize(a)
  end
  if not last or last + 5 + 12 &gt; cave + CAVE then error("Easy Win (Drift Zone): cave larger than its reserved space") end
  EASYDZ.site, EASYDZ.cave, EASYDZ.original = r.site, cave, readBytes(r.site, SIZE, true)
end

local function hook()
  FB.writeJump(EASYDZ.site, EASYDZ.cave, SIZE)
  print(string.format("[Easy Win Drift Zone] ready at %X", EASYDZ.site))
end

if EASYDZ.cave then
  hook()
else
  FB.background(function()
    local base = getAddress(FB.module)
    local stop = base + getModuleSize(FB.module)
    local a = FB.scan(ENTRY_SIG, base, stop, "+X-W")
    local b = FB.scan(CMP_SIG, base, stop, "+X-W")
    local c = FB.scan(STAR_SIG, base, stop, "+X-W")
    if #a ~= 1 or #b ~= 1 or #c ~= 1 then return string.format("signature matches: %d / %d / %d (expected 1 / 1 / 1)", #a, #b, #c) end
    local zones = FB.entities("ClientDriftZoneEntity")
    if not zones or #zones == 0 then return "no drift zone found (load the open world first)" end
    return { site = a[1], score = readInteger(b[1] + SCORE_DISP), star = readInteger(c[1] + STAR_DISP), vt = readQword(zones[1]) }
  end, function(r)
    if type(r) ~= "table" then print("[Easy Win Drift Zone] " .. tostring(r)) return end
    createCave(r)
    hook()
  end)
end

[DISABLE]
{$lua}
if syntaxcheck then return end
if EASYDZ and EASYDZ.cave and EASYDZ.pid == getOpenedProcessID() then writeBytes(EASYDZ.site, EASYDZ.original) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27069</ID>
              <Description>"Easy Win (Speed Run)"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Easy Win (Speed Run): whatever your driving, a speed run ends with at least
-- the four-star target. The game's running average speed is raised to the
-- event's four-star target (+0.1 %) each time it is stored; a faster real
-- average is kept. Both offsets come from the game's code (signatures).
if not (FB and FB.running and FB.caveAlloc) then error("Enable 'Frostbite Toolkit' first") end

if not EASYSR or EASYSR.pid ~= getOpenedProcessID() then
  EASYSR = { pid = getOpenedProcessID() }
end

-- average = (average * time + speed * dt) / total ; movss [rbx+average],xmm1
local STORE_SIG = "0F 57 C9 0F 2E 8B ?? ?? ?? ?? 74 ?? F3 0F 10 8B ?? ?? ?? ?? F3 0F 59 8B ?? ?? ?? ?? F3 0F 59 47 ?? F3 0F 58 C8 F3 0F 5E 8B ?? ?? ?? ?? F3 0F 11 8B"
local STORE_AT = 45
-- star targets set from the event data: last store = four-star target
local STAR_SIG = "F3 0F 10 48 ?? F3 0F 59 CA F3 0F 11 8B ?? ?? ?? ?? F3 0F 10 40 ?? F3 0F 59 C2 F3 0F 11 83 ?? ?? ?? ?? 48 83 C4 20 5B C3"
local STAR_DISP = 30
local SIZE = 8      -- "movss [rbx+average],xmm1", moved into the cave
local CAVE = 0x40

local function createCave(site, star)
  local cave = FB.caveAlloc(CAVE)
  local ok = autoAssemble(string.format([[
label(k)
%X:
  movss xmm0,[rbx+%X]             // four-star target (xmm0 is free here)
  mulss xmm0,[k]
  maxss xmm1,xmm0                 // average = max(average, target * 1.001)
  readmem(%X,%d)
  jmp %X
k:
  dd (float)1.001
]], cave, star, site, SIZE, site + SIZE))
  if not ok then error("Easy Win (Speed Run): cave assembly failed") end
  local a, last = cave, nil
  while a &lt; cave + CAVE do
    if disassemble(a):find(string.format("jmp %X", site + SIZE), 1, true) then last = a break end
    a = a + getInstructionSize(a)
  end
  if not last or last + 5 &gt; cave + CAVE then error("Easy Win (Speed Run): cave larger than its reserved space") end
  EASYSR.site, EASYSR.cave, EASYSR.original = site, cave, readBytes(site, SIZE, true)
end

local function hook()
  FB.writeJump(EASYSR.site, EASYSR.cave, SIZE)
  print(string.format("[Easy Win Speed Run] ready at %X", EASYSR.site))
end

if EASYSR.cave then
  hook()
else
  FB.background(function()
    local base = getAddress(FB.module)
    local stop = base + getModuleSize(FB.module)
    local a = FB.scan(STORE_SIG, base, stop, "+X-W")
    local b = FB.scan(STAR_SIG, base, stop, "+X-W")
    if #a ~= 1 or #b ~= 1 then return string.format("signature matches: %d / %d (expected 1 / 1)", #a, #b) end
    return { site = a[1] + STORE_AT, star = readInteger(b[1] + STAR_DISP) }
  end, function(r)
    if type(r) ~= "table" then print("[Easy Win Speed Run] " .. tostring(r)) return end
    createCave(r.site, r.star)
    hook()
  end)
end

[DISABLE]
{$lua}
if syntaxcheck then return end
if EASYSR and EASYSR.cave and EASYSR.pid == getOpenedProcessID() then writeBytes(EASYSR.site, EASYSR.original) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27070</ID>
              <Description>"Easy Win (Speed Trap)"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Easy Win (Speed Trap): whatever your speed, a speed trap ends with at least
-- the four-star speed. When you pass the trap, the speed the game stores (and
-- then reports) becomes at least the four-star speed (+0.1 %); a faster real
-- speed is kept. Only speed trap objects are changed.
-- All offsets come from the game's code (signatures).
if not (FB and FB.running and FB.caveAlloc) then error("Enable 'Frostbite Toolkit' first") end

if not EASYST or EASYST.pid ~= getOpenedProcessID() then
  EASYST = { pid = getOpenedProcessID() }
end

-- cmp byte [rbx+passed],0 / movss [rbx+score],xmm0 / je / ... (result is reported right after)
local STORE_SIG = "80 BB ?? ?? ?? ?? 00 F3 0F 11 83 ?? ?? ?? ?? 74 ?? 40 84 ED 75 ?? 4C 8B 43 30"
local PASSED_DISP, SCORE_DISP = 2, 11
-- star targets set from the event data: last store = four-star target
local STAR_SIG = "F3 0F 10 48 ?? F3 0F 59 CA F3 0F 11 8B ?? ?? ?? ?? F3 0F 10 40 ?? F3 0F 59 C2 F3 0F 11 83 ?? ?? ?? ?? 48 83 C4 20 5B C3"
local STAR_DISP = 30
local SIZE = 15     -- "cmp byte [rbx+passed],0 / movss [rbx+score],xmm0", moved into the cave
local CAVE = 0x80

local function createCave(r)
  local cave = FB.caveAlloc(CAVE)
  local ok = autoAssemble(string.format([[
label(vt)
label(k)
label(orig)
%X:
  cmp byte ptr [rbx+%X],0         // trap passed this frame?
  je orig
  push rax
  mov rax,[vt]
  cmp [rbx],rax                   // speed trap object?
  pop rax
  jne orig
  sub rsp,10
  movdqu [rsp],xmm1
  movss xmm1,[rbx+%X]             // four-star speed
  mulss xmm1,[k]
  maxss xmm0,xmm1                 // speed = max(speed, target * 1.001)
  movdqu xmm1,[rsp]
  add rsp,10
orig:
  readmem(%X,%d)
  jmp %X
vt:
  dq %X
k:
  dd (float)1.001
]], cave, r.passed, r.star, r.site, SIZE, r.site + SIZE, r.vt))
  if not ok then error("Easy Win (Speed Trap): cave assembly failed") end
  local a, last = cave, nil
  while a &lt; cave + CAVE do
    if disassemble(a):find(string.format("jmp %X", r.site + SIZE), 1, true) then last = a break end
    a = a + getInstructionSize(a)
  end
  if not last or last + 5 + 12 &gt; cave + CAVE then error("Easy Win (Speed Trap): cave larger than its reserved space") end
  EASYST.site, EASYST.cave, EASYST.original = r.site, cave, readBytes(r.site, SIZE, true)
end

local function hook()
  FB.writeJump(EASYST.site, EASYST.cave, SIZE)
  print(string.format("[Easy Win Speed Trap] ready at %X", EASYST.site))
end

if EASYST.cave then
  hook()
else
  FB.background(function()
    local base = getAddress(FB.module)
    local stop = base + getModuleSize(FB.module)
    local a = FB.scan(STORE_SIG, base, stop, "+X-W")
    local c = FB.scan(STAR_SIG, base, stop, "+X-W")
    if #a ~= 1 or #c ~= 1 then return string.format("signature matches: %d / %d (expected 1 / 1)", #a, #c) end
    local traps = FB.entities("ClientSpeedTrapEntity")
    if not traps or #traps == 0 then return "no speed trap found (load the open world first)" end
    return { site = a[1], passed = readInteger(a[1] + PASSED_DISP), star = readInteger(c[1] + STAR_DISP), vt = readQword(traps[1]) }
  end, function(r)
    if type(r) ~= "table" then print("[Easy Win Speed Trap] " .. tostring(r)) return end
    createCave(r)
    hook()
  end)
end

[DISABLE]
{$lua}
if syntaxcheck then return end
if EASYST and EASYST.cave and EASYST.pid == getOpenedProcessID() then writeBytes(EASYST.site, EASYST.original) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27071</ID>
              <Description>"Easy Win (Hot Lap)"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Easy Win (Hot Lap): whatever your driving, a hot lap ends with at least
-- the four-star time. When the event finishes, your lap time becomes at most
-- the four-star time (-0.1 %); a faster real lap is kept. Only events where
-- a lower score is better are changed (speed runs are left alone).
-- All offsets come from the game's code (signatures).
if not (FB and FB.running and FB.caveAlloc) then error("Enable 'Frostbite Toolkit' first") end

if not EASYHL or EASYHL.pid ~= getOpenedProcessID() then
  EASYHL = { pid = getOpenedProcessID() }
end

-- event finish function (entry)
local ENTRY_SIG = "48 8B C4 48 89 58 10 48 89 68 18 48 89 70 20 57 41 56 41 57 48 81 EC 30 01 00 00 48 8B 59 30 48 8D 50 B8 48 8B F9"
-- inside it: cmp byte [rdi+lowerIsBetter],0 / movss xmm0,[rdi+best] / comiss xmm0,[rdi+score]
local CMP_SIG = "80 BF ?? ?? ?? ?? 00 75 ?? F3 0F 10 87 ?? ?? ?? ?? 0F 2F 87 ?? ?? ?? ?? 72 ?? 80 BF"
local FLAG_DISP, SCORE_DISP = 2, 20
-- star targets set from the event data: last store = four-star target
local STAR_SIG = "F3 0F 10 48 ?? F3 0F 59 CA F3 0F 11 8B ?? ?? ?? ?? F3 0F 10 40 ?? F3 0F 59 C2 F3 0F 11 83 ?? ?? ?? ?? 48 83 C4 20 5B C3"
local STAR_DISP = 30
local SIZE = 7      -- "mov rax,rsp / mov [rax+10],rbx", moved into the cave
local CAVE = 0x80

local function createCave(r)
  local cave = FB.caveAlloc(CAVE)
  local ok = autoAssemble(string.format([[
label(k)
label(zero)
label(orig)
%X:
  cmp byte ptr [rcx+%X],0         // lower is better? (hot lap)
  je orig
  sub rsp,10
  movdqu [rsp],xmm0
  movss xmm0,[rcx+%X]             // four-star time
  ucomiss xmm0,[zero]
  jbe short @f
  mulss xmm0,[k]
  minss xmm0,[rcx+%X]             // score = min(score, target * 0.999)
  movss [rcx+%X],xmm0
@@:
  movdqu xmm0,[rsp]
  add rsp,10
orig:
  readmem(%X,%d)
  jmp %X
k:
  dd (float)0.999
zero:
  dd 0
]], cave, r.flag, r.star, r.score, r.score, r.site, SIZE, r.site + SIZE))
  if not ok then error("Easy Win (Hot Lap): cave assembly failed") end
  local a, last = cave, nil
  while a &lt; cave + CAVE do
    if disassemble(a):find(string.format("jmp %X", r.site + SIZE), 1, true) then last = a break end
    a = a + getInstructionSize(a)
  end
  if not last or last + 5 + 8 &gt; cave + CAVE then error("Easy Win (Hot Lap): cave larger than its reserved space") end
  EASYHL.site, EASYHL.cave, EASYHL.original = r.site, cave, readBytes(r.site, SIZE, true)
end

local function hook()
  FB.writeJump(EASYHL.site, EASYHL.cave, SIZE)
  print(string.format("[Easy Win Hot Lap] ready at %X", EASYHL.site))
end

if EASYHL.cave then
  hook()
else
  FB.background(function()
    local base = getAddress(FB.module)
    local stop = base + getModuleSize(FB.module)
    local a = FB.scan(ENTRY_SIG, base, stop, "+X-W")
    local b = FB.scan(CMP_SIG, base, stop, "+X-W")
    local c = FB.scan(STAR_SIG, base, stop, "+X-W")
    if #a ~= 1 or #b ~= 1 or #c ~= 1 then return string.format("signature matches: %d / %d / %d (expected 1 / 1 / 1)", #a, #b, #c) end
    return { site = a[1], flag = readInteger(b[1] + FLAG_DISP), score = readInteger(b[1] + SCORE_DISP), star = readInteger(c[1] + STAR_DISP) }
  end, function(r)
    if type(r) ~= "table" then print("[Easy Win Hot Lap] " .. tostring(r)) return end
    createCave(r)
    hook()
  end)
end

[DISABLE]
{$lua}
if syntaxcheck then return end
if EASYHL and EASYHL.cave and EASYHL.pid == getOpenedProcessID() then writeBytes(EASYHL.site, EASYHL.original) end
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>27052</ID>
          <Description>"Unlocks"</Description>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>27053</ID>
              <Description>"Vehicles / Parts Are Free"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Vehicles / Parts Are Free: every bank debit (purchases, upgrades...) is
-- turned into a debit of 0 before the game checks the balance, so the
-- purchase always goes through and the money stays. Credits are untouched.
-- Offsets come from the game's own code, nothing is hardcoded here.
if not (FB and FB.running) then error("Enable 'Frostbite Toolkit' first") end

if not FREE or FREE.pid ~= getOpenedProcessID() then
  FREE = { pid = getOpenedProcessID() }
end

-- mov rcx,[rdi] ; cmp byte [rcx+isCredit],0 ; jne credit ; mov rdx,rcx ;
-- mov rcx,[rax+balance] ; cmp [rdx+amount],rcx ; jle ...
local AOB = "48 8B 0F 80 79 ?? 00 75 ?? 48 89 CA 48 8B 48 ?? 48 39 4A ?? 7E"
local SIZE = 7   -- "mov rcx,[rdi]" + "cmp byte [rcx+isCredit],0", moved into the cave

-- The cave is created once and kept: no thread can ever jump into freed memory.
local function createCave(site)
  local amount = readBytes(site + 19, 1)
  local cave = FB.caveAlloc(0x40)
  local ok = autoAssemble(string.format([[
label(done)

%X:
  readmem(%X,%d)
  jne done                        // credit: keep it
  mov qword ptr [rcx+%X],0        // debit: amount = 0 (mov keeps the flags)
done:
  jmp %X
]], cave, site, SIZE, amount, site + SIZE))
  if not ok then error("Free purchases: cave assembly failed") end
  FREE.site, FREE.original, FREE.cave = site, readBytes(site, SIZE, true), cave
end

local function hook()
  FB.writeJump(FREE.site, FREE.cave, SIZE)
  print(string.format("[Free] ready at %X", FREE.site))
end

if FREE.site then
  hook()
else
  print("[Free] searching the debit check...")
  createThread(function()
    local base = getAddress(FB.module)
    local hits = FB.scan(AOB, base, base + getModuleSize(FB.module), "+X")
    synchronize(function()
      if #hits ~= 1 then print("[Free] signature matches: " .. #hits .. " (expected 1)") return end
      createCave(hits[1])
      hook()
    end)
  end)
end

[DISABLE]
{$lua}
if syntaxcheck then return end
if FREE and FREE.site and FREE.pid == getOpenedProcessID() then writeBytes(FREE.site, FREE.original) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27054</ID>
              <Description>"Unlock All Items"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Unlock All Items: the game's "is this item unlocked?" check always answers
-- yes. Its first instructions are replaced by "mov al,1 ; ret" while enabled.
if not (FB and FB.running) then error("Enable 'Frostbite Toolkit' first") end

if not UNLOCK or UNLOCK.pid ~= getOpenedProcessID() then
  UNLOCK = { pid = getOpenedProcessID() }
end

-- test r8,r8 ; jne lookup ; mov al,1 ; ret ; lookup: mov r10d,[r8+..] ;
-- lea r8,[rcx+..] ; mov rcx,[rcx+..]   (map lookup of the item)
local AOB = "4D 85 C0 75 ?? B0 01 C3 45 8B 50 ?? 4C 8D 41 ?? 48 8B 49"

local function patch()
  local ok = autoAssemble(string.format("%X:\n  db B0 01 C3\n", UNLOCK.site))
  if not ok then error("Unlock all items: patch failed") end
  print(string.format("[Unlock] ready at %X", UNLOCK.site))
end

if UNLOCK.site then
  patch()
else
  print("[Unlock] searching the unlock check...")
  createThread(function()
    local base = getAddress(FB.module)
    local hits = FB.scan(AOB, base, base + getModuleSize(FB.module), "+X")
    synchronize(function()
      if #hits ~= 1 then print("[Unlock] signature matches: " .. #hits .. " (expected 1)") return end
      UNLOCK.site, UNLOCK.original = hits[1], readBytes(hits[1], 3, true)
      patch()
    end)
  end)
end

[DISABLE]
{$lua}
if syntaxcheck then return end
if UNLOCK and UNLOCK.site and UNLOCK.pid == getOpenedProcessID() then writeBytes(UNLOCK.site, UNLOCK.original) end
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>27055</ID>
          <Description>"Police"</Description>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>27056</ID>
              <Description>"Fast escape"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Fast escape: shortens the "Evasion" cooldown of every heat level (the time
-- the cops must lose sight of you before the chase ends) to
-- "Fast escape (s)". Longer only if the game's own value is shorter.
if not (FB and FB.running and FB.tweakSet) then error("Enable 'Frostbite Toolkit' first") end
if not getAddressSafe("fbEscapeTime") then
  autoAssemble("alloc(fbEscapeTime,4)\nregistersymbol(fbEscapeTime)\nfbEscapeTime:\n  dd (float)1\n")
end

FB.tweakSet({
  name = "Escape", type = "HeatLevel", field = "CooldownDuration",
  slots = function(level, ti) return { level + FB.fieldOffset(ti, "CooldownDuration") } end,
  value = function(seconds) return math.min(seconds, readFloat("fbEscapeTime") or seconds) end,
}, true)

[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.tweakSet and FB.tweaks["Escape"] then FB.tweakSet(FB.tweaks["Escape"].spec, false) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27057</ID>
              <Description>"Fast escape (s)"</Description>
              <VariableType>Float</VariableType>
              <Address>fbEscapeTime</Address>
            </CheatEntry>
            <CheatEntry>
              <ID>27059</ID>
              <Description>"Heat Level"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Heat Level: keeps the fbHeat symbol up to date (child value: 0 to 5,
-- the whole part is the pursuit level). Edit the value to change the heat.
if not (FB and FB.running and FB.heatSet) then error("Enable 'Frostbite Toolkit' first") end
FB.heatSet("watch", true)
[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.heatSet then FB.heatSet("watch", false) end
</AssemblerScript>
              <CheatEntries>
                <CheatEntry>
                  <ID>27065</ID>
                  <Description>"Heat (0-5, whole part = pursuit level)"</Description>
                  <VariableType>Float</VariableType>
                  <Address>fbHeat</Address>
                </CheatEntry>
              </CheatEntries>
            </CheatEntry>
            <CheatEntry>
              <ID>27060</ID>
              <Description>"Heat never increases"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Heat never increases: the heat can drop (escape, bust) but never rises.
if not (FB and FB.running and FB.heatSet) then error("Enable 'Frostbite Toolkit' first") end
FB.heatSet("lock", true)
[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.heatSet then FB.heatSet("lock", false) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27061</ID>
              <Description>"Drop Heat To 0"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Drop Heat To 0: keeps the heat at 0 while enabled.
if not (FB and FB.running and FB.heatSet) then error("Enable 'Frostbite Toolkit' first") end
FB.heatSet("zero", true)
[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.heatSet then FB.heatSet("zero", false) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27062</ID>
              <Description>"Max Heat"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Max Heat: keeps the heat at its maximum (read from the game) while enabled.
if not (FB and FB.running and FB.heatSet) then error("Enable 'Frostbite Toolkit' first") end
FB.heatSet("max", true)
[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.heatSet then FB.heatSet("max", false) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27063</ID>
              <Description>"Cops Don't Chase You"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Cops Don't Chase You: no pursuit can start. The chase manager's
-- "start pursuit" function returns nothing (the same result as when the
-- game declines to start one), so you stay "not being chased", whether
-- the cops spot you or you hit them. The function is found by signature.
if not (FB and FB.running and FB.caveAlloc) then error("Enable 'Frostbite Toolkit' first") end

if not NOCHASE or NOCHASE.pid ~= getOpenedProcessID() then
  NOCHASE = { pid = getOpenedProcessID() }
end

-- chase manager: start pursuit (entry)
local ENTRY_SIG = "40 55 53 56 41 55 41 56 41 57 48 8D 6C 24 C8 48 81 EC 38 01 00 00 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 45 F8 4C 8B 2A 45 33 FF"
local SIZE = 6      -- "push rbp / push rbx / push rsi / push r13"
local CAVE = 0x20

local function createCave(site)
  local cave = FB.caveAlloc(CAVE)
  local ok = autoAssemble(string.format([[
%X:
  xor eax,eax                     // no pursuit object
  ret
]], cave))
  if not ok then error("Cops Don't Chase You: cave assembly failed") end
  NOCHASE.site, NOCHASE.cave, NOCHASE.original = site, cave, readBytes(site, SIZE, true)
end

local function hook()
  FB.writeJump(NOCHASE.site, NOCHASE.cave, SIZE)
  print(string.format("[Cops Don't Chase You] ready at %X", NOCHASE.site))
end

if NOCHASE.cave then
  hook()
else
  FB.background(function()
    local base = getAddress(FB.module)
    local a = FB.scan(ENTRY_SIG, base, base + getModuleSize(FB.module), "+X-W")
    if #a ~= 1 then return string.format("signature matches: %d (expected 1)", #a) end
    return a[1]
  end, function(site)
    if type(site) ~= "number" then print("[Cops Don't Chase You] " .. tostring(site)) return end
    createCave(site)
    hook()
  end)
end

[DISABLE]
{$lua}
if syntaxcheck then return end
if NOCHASE and NOCHASE.cave and NOCHASE.pid == getOpenedProcessID() then writeBytes(NOCHASE.site, NOCHASE.original) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27072</ID>
              <Description>"Cops Don't Detect You"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Cops Don't Detect You: the cops' spotting meter (time they must see you
-- before a pursuit starts) of every heat level becomes practically endless.
-- Hitting a police car still starts a pursuit.
if not (FB and FB.running and FB.tweakSet) then error("Enable 'Frostbite Toolkit' first") end

FB.tweakSet({
  name = "NoDetect", type = "HeatLevel", field = "SpottingMeterFillUpTime",
  slots = function(level, ti) return { level + FB.fieldOffset(ti, "SpottingMeterFillUpTime") } end,
  value = function() return 1000000 end,
}, true)

[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.tweakSet and FB.tweaks["NoDetect"] then FB.tweakSet(FB.tweaks["NoDetect"].spec, false) end
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>27064</ID>
              <Description>"Reinforcements Never Arrive"</Description>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
-- Reinforcements Never Arrive: no cop reinforcement waves at any heat level
-- (NumReinforcementsInWave = 0).
if not (FB and FB.running and FB.tweakSet) then error("Enable 'Frostbite Toolkit' first") end

FB.tweakSet({
  name = "NoReinforcements", type = "HeatLevel", field = "NumReinforcementsInWave", kind = "u8",
  slots = function(level, ti) return { level + FB.fieldOffset(ti, "NumReinforcementsInWave") } end,
  value = function() return 0 end,
}, true)
[DISABLE]
{$lua}
if syntaxcheck then return end
if FB and FB.tweakSet and FB.tweaks["NoReinforcements"] then FB.tweakSet(FB.tweaks["NoReinforcements"].spec, false) end
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
  </CheatEntries>
  <UserdefinedSymbols/>
  <LuaScript>-- Automatically enable Full Window Address List after table finishes loading
local t = createTimer(getMainForm())
t.Interval = 100
t.OnTimer = function(sender)
  sender.destroy()
  local mf = getMainForm()
  if mf and mf.miFullWindowAddressList and not mf.miFullWindowAddressList.Checked then
    mf.miFullWindowAddressList.Checked = true
    if mf.miFullWindowAddressList.OnClick then
      mf.miFullWindowAddressList.OnClick(mf.miFullWindowAddressList)
    end
  end
end

</LuaScript>
</CheatTable>
