Skip to content
Verified contractPartialApache-2.0

KVMStepCore4

Address0xef51b2e3ff4a00efb244493c652689dd13c93be0
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
Apache-2.0
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,267,259
Creation transaction
0x028fae602e…0112a32aeb
Libraries
src/KVMStep4.sol:Trig2560x9905…5124d8src/KVMStep4.sol:PencilVM0x9078…f1a617src/KVMStep4.sol:PencilStep0xca98…df54e5

src/KVMStep4.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

pragma solidity ^0.8.13;

import "../lib/kohi/Trig256.sol";
import "./SinLutSingleton.sol";
import "./GradNoiseSingleton.sol";
import "./PencilVM.sol";
import "./PencilStep.sol";

/* =============================================================================
 *  KVMS4 · the resumable KVM interpreter, pencil-family build
 * =============================================================================
 *
 * A KVM program can take billions of steps. One eth_call cannot run that
 * many. This library is the KVM interpreter built so that a render can stop
 * and resume. executeChunk() runs a bounded number of steps and packs the
 * complete VM state into a flat image. A later call resumes from that image.
 * A render costs O(total work) over free view calls, not
 * O(chunks x total work).
 *
 * THE CORE FLEET. The full instruction set does not fit one contract under
 * the EIP-170 size limit, so the stepped interpreter ships as several
 * cores, split by NOISE kind and by family:
 *
 *     KVMStepCore    kind 0 (NoiseV1)     byte-frozen; serves the minted
 *                                         kind-0 catalog
 *     KVMStepCore2   kind 1 (GradNoise)   the full 2D surface
 *     KVMStepCore3   kind 1, mesh subset  adds MESHC (0xaf)
 *     KVMStepCore4   kinds 0 and 1,       this file: it adds PENCIL (0xb0,
 *                    pencil subset        render family 6) and removes the
 *                                         2D drawing surface and the Mesh3D
 *                                         records. A removed instruction
 *                                         reverts KVMError(8). A PENCIL
 *                                         program traps on the other cores.
 *
 * The other cores sit behind KVMStepRunner. This core sits behind its own
 * codec surface, KVMPencilStepRunner, because the pencil family adds state
 * to the snapshot and a deployed KVMStepRunner cannot change. The removed
 * set is the 2D surface (fill/stroke/blend/brush state, BG/BGPAL,
 * SAVE/RESTORE and the 2D transform, clips, YFLIP, the path family, the
 * shape emitters, GRADIENT, the glyph walkers, STAMP/FIELD/ALIASED,
 * GFILL/FFILL) and the Mesh3D records (CAM/LIGHT/MESH/MESHC).
 *
 * NOISE. This core serves both kinds, like KVMPencilRunner, because p5's
 * noise() compiles to kind 0. Kind 1 has no table: NOISEINIT stores
 * {octaves, gain} packed in one scalar word (State @704, inside the flat
 * copy range) and sets the armed marker 2 at @736. NOISE staticcalls the
 * first-party GradNoise singleton at the CREATE2 constant GRADNOISE. Kind 0
 * builds no table in the op: the client supplies the assembled NoiseV1Ext
 * call blob (blobs[1], a pure function of the run seed), and NOISEINIT
 * kind 0 charges +4096 steps, stages the blob, and sets marker 1. NOISE then
 * staticcalls NoiseV1Ext at the address given to the constructor. A core
 * built with address(0) traps at NOISEINIT kind 0.
 *
 * THE PENCIL STATE. Unlike the mesh records, PENCIL keeps VM state across
 * ops: the paper, the pen, the pending points, polygons and terms, and 16
 * installed region slots. That state crosses the chunk boundary as a pencil
 * section of the flat image (see the pencil resume seam below), and as the
 * KSN7/KSN8 wire variants that KVMPencilStepRunner specifies. The pure glue
 * of the arm is in the linked library PencilStep, and its exact Fix64 value
 * math is in the linked library PencilVM. Both are DELEGATECALL targets, so
 * this core fits EIP-170.
 *
 * THE INVARIANT. A resume from a snapshot produces a stream byte-identical
 * to one uninterrupted run of KVMPencilRunner, for ANY chunk boundaries. The
 * yield check sits at the head of the hot loop, next to the STEP_LIMIT
 * check, so a boundary never falls inside an op. An op executes if and only
 * if steps < startSteps + budget. Interior surcharges (the PENCIL charges,
 * NOISEINIT kind 0, BEZSET +200) can overshoot the budget by at most one op.
 * s.gCursor (offset 2656) keeps the shared KFI1 layout. This build has no
 * GRADIENT, so it never parks a cursor. A nonzero value from a resumed
 * image faults in _run.
 *
 * TWO deployables split the lane, because the interpreter and the wire
 * codec do not fit one EIP-170 address together:
 *   - KVMStepCore4 (end of this file): the interpreter plus the KFI1
 *     flat-image codec. KFI1 is an INTERNAL, word-aligned serialization of
 *     the interpreter State. It is not the wire format, has no
 *     compatibility promise, and never leaves the Runner-to-Core call.
 *   - KVMPencilStepRunner: the public executeChunk surface: header
 *     validation, the KSN wire codec, and the linear-memory write-delta
 *     diff.
 *
 * THE SPARSE-STATE SNAPSHOT. State that is large, growing, or
 * client-reconstructible does not round-trip through the snapshot, so the
 * cost of a chunk scales with its own work:
 *
 *     state                arrives as                returns as
 *     -----                ----------                ----------
 *     scalars + the four   flatIn (the KFI1 image)   flatOut (KFI1 image)
 *     interpreter arrays
 *     pencil state         the flatIn pencil         the flatOut pencil
 *                          section                   section
 *     noise, kind 1        nothing: {octaves,        nothing (the same
 *                          gain} ride the scalar     scalar copy)
 *                          copy (@704)
 *     noise, kind 0        the noiseTable blob       nothing: the client
 *                          (blobs[1]), read when     holds the blob
 *                          marker 1 resumes or at
 *                          NOISEINIT kind 0
 *     linear memory        the memImage blob,        the chunk's write set
 *     (up to 40,960 x      read in place (mem_rd);   (bitmap + packed
 *     8 B, memBound)       writes land in a sparse   shadow) at the flatOut
 *                          per-chunk overlay         tail, the memDelta the
 *                          (mem_wr)                  client folds in
 *     accumulated open     the pathBlob, read in     this chunk's appended
 *     path                 place (flush_path         tail, as the flat's
 *                          prepends it to the        path section (the
 *                          paint record)             pathDelta)
 *
 * THE RESUME CONTRACT. This Core only resumes. For a fresh run, flatIn is
 * the genesis image that KVMPencilStepRunner builds (style defaults, the
 * seed-0 xorshift guard, memBound, an empty pencil section). The Runner
 * prepends the begin record (b0) to the first chunk's stream. The chunk
 * that completes execution emits the end record (b1) here, exactly once.
 * executeChunk returns reason 0 (done, flatOut empty) or 1 (budget
 * exhausted at a yield point, flatOut holds the snapshot).
 *
 * THE FORK. Every op below is a byte-for-byte copy of the canonical KVM
 * library, and a conformance corpus replays the same programs through both.
 * The fork differs from the canonical interpreter only here:
 *   1. State gains halted/traitCount/ceil at the struct END (offsets 2560,
 *      2592, 2624). Every pinned offset above them is unchanged.
 *   2. execute() becomes executeChunk() (flat-image resume).
 *   3. _hotLoop: the budget-yield check at the loop head (exitOp 0x101).
 *      HALT records s.halted.
 *   4. _run: returns a reason (0 done / 1 budget). It admits NOISEINIT
 *      kind 0 at the cold layer (_noise0).
 *   5. TRAIT increments s.traitCount (the KSN1 counter).
 *   6. _pack (the KFI1 serializer) and the KVMStepCore4 wrapper.
 *   7. The PENCIL arm and its resume seam (_pLoad, _pImage).
 *
 * THE CONTAINER (KVM1). All multi-byte fields, container and stream, are
 * big-endian; stack slots are int64, Fix64 signed Q31.32 fixed point.
 *
 *     offset   size  field
 *     ------   ----  ------------------------------------------------------
 *          0      4  magic "KVM1" (0x4b564d31)
 *          4      1  version, always 1
 *          5      1  flags: bit0 DEVICE_STROKE, bit1 STROKE_HARD;
 *                    bits 2..7 reserved, must be 0
 *          6      2  width  (u16, pixels)
 *          8      2  height (u16, pixels)
 *         10      1  palette count N
 *         11    4*N  palette, u32 ARGB entries
 *      11+4N      4  data-segment length D (u32)
 *      15+4N      D  data segment: read-only bytes for DR8/DR16/DR32,
 *                    GLYPH/GLYPH64/GLYPHC records, GFILL stop tables
 *    15+4N+D    ...  code, to the end of the container
 *
 * THE DRAW STREAM. One `begin` record, then drawing records in program
 * order, then one `end`. A field list like `i64 ax ay bx by` is that many
 * consecutive fields of that width. This build emits only begin, trait,
 * paper, region, stroke and end. The other records belong to the canonical
 * format and to the mesh family.
 *
 *   begin       b0 | u16 width | u16 height
 *   background  00 | u32 argb
 *   paint       01 | u8 hasFill | u32 fill | u8 hasStroke | u32 stroke
 *                  | i64 strokeWidth | u8 flags | [u8 cap | u8 join]
 *                  | [u8 blend] | [gradient | field] | u8 hasClip
 *                  | [i64 clip quad, 4 points] | u16 segCount | segs
 *     flags       bit0 evenOdd · bit1 cap/join follow · bit2 blend follows
 *                 bit3 gradient follows · bit4 field follows (never both)
 *     hasClip     0 none · 1 rect test · 2 truncating rect test
 *                 (the quad, 8 x i64, follows when nonzero)
 *     gradient    u8 kind | i64 ax ay bx by | u8 n | n x (u16 off | u32 argb)
 *     field       u8 kind | i64 scale | i64 warp | u32 colorA | u32 colorB
 *                 | i32 seed
 *     seg M       01 | i64 x y
 *     seg L       02 | i64 x y
 *     seg C       03 | i64 c1x c1y c2x c2y x y
 *     seg Z       04
 *   trait       02 | u8 id | i64 value
 *   stamp       04 | u32 color | u8 tip | u8 blend
 *                  | i64 cx cy size dirx diry pressure
 *   field       06 | u8 kind | u32 colorA | u32 colorB
 *                  | kind 1 only: i64 scale | i64 warp | i32 seed
 *   aliased     07 | u8 threshold
 *   cam         08 | i64 camZ halfW halfH
 *   light       09 | u8 kind | i64 r g b dx dy dz
 *   mesh        0a | i64 verts+normals x18 | u32 albedo | u32 specColor
 *                  | i64 shininess
 *   meshc       0b | i64 verts+normals x18 | u32 albedo0 albedo1 albedo2
 *                  | u32 specColor | i64 shininess
 *   paper       0c | u8 r | u8 g | u8 b | u32 seed | i32 sheetMm
 *   region      0d | u8 slot | i32 kv wobAmp wobBias tolL
 *                  | u16 npoly | npoly x (u8 n | n x (i32 x | i32 y))
 *                  | u16 nterm | nterm x (u8 kind | i32 ax ay bx by a b)
 *   stroke      0e | u8 flags | u8 slot | i32 abR abG abB reach strength wax
 *                  | i32 r | i32 off | u16 n | n x (i32 x | i32 y | i32 p)
 *   end         b1
 *
 * Every number in a pencil record is a Q16 i32 (device px or a unit
 * quantity), except the u8/u16 counts, slots, flags, kinds and the paper's
 * color bytes and seed. This build has no transform: a pencil coordinate is
 * device px exactly as the program gives it. The stream is byte-identical
 * to the one KVMPencilRunner returns; its header draws the record layouts.
 *
 * EXECUTION. A stack machine: 256 int64 stack slots, 256 locals, a 64-frame
 * call stack, up to 40960 words of linear memory, and a hard budget of 2^32
 * steps across all chunks of a run. The 64 SAVE/RESTORE slots stay in the
 * KFI1 layout, but SAVE and RESTORE trap in this build. A fault is
 * total: an out-of-range access or an exhausted limit reverts the whole
 * call and leaves no partial output.
 *
 * TRUST BOUNDARY. KVMStepCore4 has no storage, no owner, and no upgrade
 * path. It is a trusted-input execution kernel behind KVMPencilStepRunner.
 * The Runner validates the header, the wire snapshot (the pencil section
 * included), and the blob geometry before it calls in. An image with the
 * wrong geometry faults here (the exact-consumption check in _init). The
 * Runner owns content validation. The interpreter calls these deployed
 * contracts: Trig256 (MIT), linked by address, for
 * atan2/pow/exp/log/asin/acos; PencilVM and PencilStep (first-party,
 * linked) for the pencil arm; the first-party GradNoise singleton at the
 * CREATE2 constant GRADNOISE for NOISE kind 1; and, when the deployment
 * supplies one, NoiseV1Ext (LGPL-2.1-only) at the constructor address for
 * NOISE kind 0. This file holds no noise math.
 */
library KVMS4 {
    // ---- container ----------------------------------------------------------
    uint32 internal constant MAGIC = 0x4b564d31; // "KVM1"
    uint8 internal constant VERSION = 1;

    // ---- execution limits (part of the spec) --------------------------------
    // The enforced ceiling is 2^32, hardcoded as 0x100000000 at every check
    // site. No site reads this constant.
    uint256 internal constant STEP_LIMIT = 1 << 32; // ~4.3B steps; full Kintsugi is 1.48B
    uint256 internal constant MAX_STACK = 256;
    uint256 internal constant MAX_LOCALS = 256;
    uint256 internal constant MAX_SAVE_DEPTH = 64;
    uint256 internal constant MAX_PATH_VERTICES = 65535; // the stream's u16 segCount limit
    uint256 internal constant MAX_CALL_DEPTH = 64;
    uint256 internal constant MEMORY_SLOTS = 40960;
    uint256 internal constant MAX_BEZIERS = 64;

    // Words per SAVE slot: 15 raw-copied words (the contiguous ma..mf,
    // strokeW, c0x..c3y State block at _STATE_SAVE_OFF = &s.ma) plus one
    // word that packs fill(0..31) hasFill(32) stroke(40..71) hasStroke(72)
    // evenOdd(73) clipSet(74..75, a 0/1/2 mode) brush(76..83) blend(84..91)
    // cap(92..99) join(100..107).
    uint256 internal constant SAVE_WORDS = 16;
    uint256 internal constant _STATE_SAVE_OFF = 1024; // &s.ma
    uint256 internal constant _STATE_STYLE_OFF = 832; // &s.fill (6 words)

    int64 internal constant ONE = 4294967296; // Fix64.ONE
    int64 internal constant QUARTER = 1073741824; // 0.25 in Q31.32
    /// Cubic-arc circle constant: round(0.552284749830793398 * 2^32).
    /// The specification pins it.
    int64 internal constant KAPPA = 2372049776;

    // ---- errors -------------------------------------------------------------
    // One error covers every fault: `KVMError(code)`, selector 0x4c49dedb.
    // The payload has two tiers. Neither changes the draw stream of a valid
    // program.
    //   * Solidity-side header, opcode, and save reverts carry a `code`.
    //   * The 108 hot-path Yul interpreter faults revert the bare selector
    //     through the arg-less `fail()` helper. This saves EIP-170 bytes.
    //     Callers do not decode them.
    // Solidity-side code map (stable):
    //   1 TruncatedHeader   2 BadMagic   3 BadVersion   4 TruncatedPalette
    //   5 TruncatedData     6 BadFlags   8 InvalidOpcode
    //   12 SaveDepthExceeded   13 RestoreWithoutSave
    error KVMError(uint256 code);

    // ---- interpreter state --------------------------------------------------

    struct State {
        bytes program; // full container bytes
        uint256 dataStart; // offset of data segment within program
        uint256 dataLen;
        uint256 codeStart; // offset of code within program
        uint256 codeLen;
        uint32[] palette;
        uint256 pc; // relative to codeStart
        uint256 steps;
        int64[] stack;
        uint256 sp;
        int64[] locals;
        int64[] params;
        int32 initialSeed; // run seed (for RandomV1 lazy build)
        int32 seed; // mutable XorShift state
        // call stack
        uint256[] callStack;
        uint256 callDepth;
        // mem is a dead slot (see pathBase below); a store sets memInit
        int64[] mem;
        bool memInit;
        // RandomV1 state (built on the first RV1 op): raw pointer to 58
        // words: 56 seed slots (index 0 unused), inext, inextp
        uint256 rv1;
        bool rv1Built;
        // Bezier bank (built on the first BEZSET): raw pointer to 64 record
        // pointers (0 = unset). A record is 8 coeff words + 101 arc words
        uint256 beziers;
        bool bezInit;
        // Noise state (set by NOISEINIT). noiseInit is a marker: 0 none,
        // 1 kind 0 (NoiseV1; table from the client blob), 2 kind 1
        // (GradNoise). For kind 1, @704 packs octaves<<64|gain inside the
        // flat scalar range. Only assembly reads either slot.
        int64[] noiseTable;
        uint256 noiseInit;
        // SinLut256 blob data contract and its memory copy, which the first
        // trig-dependent op stages. This keeps the ~2.6 KB LUT selection
        // tree out of the runtime code (EIP-170).
        address lutAddr;
        uint256 lutPtr;
        // style flags (packed into one word of a SAVE slot by _save/_restore)
        uint32 fill;
        bool hasFill;
        uint32 stroke;
        bool hasStroke;
        bool evenOdd; // fill winding rule (false = non-zero, default)
        // clip MODE, not a bool: 0 none | 1 CLIPRECT | 2 CLIPRECTT's
        // truncating test (the quad is in the save block). It is the
        // stream's hasClip byte and takes two bits (74..75) in the save word.
        uint256 clipSet;
        // The contiguous SAVE block (_STATE_SAVE_OFF, 15 raw-copied words):
        // transform matrix [a b c d e f]
        //   X = a*x + c*y + e, Y = b*x + d*y + f
        // stroke width, clip quad (device space)
        int64 ma;
        int64 mb;
        int64 mc;
        int64 md;
        int64 me;
        int64 mf;
        int64 strokeW;
        int64 c0x;
        int64 c0y;
        int64 c1x;
        int64 c1y;
        int64 c2x;
        int64 c2y;
        int64 c3x;
        int64 c3y;
        // save stack: SAVE_WORDS words per slot
        uint256[] saves;
        uint256 saveDepth;
        // path buffer (canonical seg encoding, device space)
        bytes path;
        uint256 pathLen;
        uint256 segCount;
        bool hasCurrent;
        int64 curX; // device-space current point (last emitted M/L/C endpoint)
        int64 curY;
        int64 twoThirds; // Fix64.div(TWO, THREE), pinned by spec
        // one-shot two-stage glyph transform (GLYPHXF; GLYPH/GLYPHC use it)
        bool glyphXfActive;
        int64 glyphEm;
        int64 glyphOx;
        int64 glyphOy;
        // GRADIENT scratch (kept off the stack to avoid stack-too-deep)
        int64 gX;
        int64 gY;
        int64 gW;
        int64 gH;
        uint32 gC1;
        uint32 gC2;
        int64 gLineWidth;
        // output buffer
        bytes out;
        uint256 outLen;
        // painterly style state (u8 each; SAVE/RESTORE-scoped, packed into
        // the style word of a SAVE slot): active SDF brush tip (BRUSH) and
        // blend mode (BLEND). Appended after outLen.
        uint256 brush;
        uint256 blend;
        // Stroke cap and join (STROKECAP/STROKEJOIN; u8 each; SAVE/RESTORE-
        // scoped, packed into the style word). Default 0 (Butt/Miter): the
        // paint record then omits the cap and join bytes.
        uint256 cap; // offset 2272
        uint256 join; // offset 2304
        // Exact device y-flip height (YFLIP 0x58; 0 = off). When set, every
        // device y becomes (flipH - y) AFTER the matrix, at ALL transform
        // sites (the fy() Yul helper: path staging, CLIPRECT/STAMP xf_pt,
        // GRADIENT endpoints, QUADTO's control point). SAVE/RESTORE does
        // not save it, the same as in the reference implementation.
        int64 flipH; // offset 2336
        // Container flags bit0 (FLAG_DEVICE_STROKE): stroke widths, STAMP
        // sizes, and the GRADIENT line width stay literal. det_scale skips
        // sqrt(|det|), which is not 1 for a LUT-trig rotation CTM.
        bool deviceStroke; // offset 2368
        // Declared linear-memory bound (MEMCAP 0xa4). The genesis image sets
        // memBound = MEMORY_SLOTS. The four memory-op bounds checks and the
        // two first-store allocation sites read it. memcapSet enforces
        // once-per-run inside the MEMCAP handler, off the hot path.
        // Appended at the END (memBound @2400, memcapSet @2432).
        uint256 memBound;
        uint256 memcapSet;
        // GFILL gradient-fill style state (0xa7), appended at the END.
        //   gradMeta @2464: bit0 active | bit1 kind | bits 8..15 n |
        //     bits 16..47 stop-table byte offset (data-segment-relative,
        //     validated at GFILL time). 0 means no gradient. FILL, FILLPAL,
        //     and NOFILL clear it. POINT masks it around its stroke-colored
        //     dot.
        //   gradGeom @2496: the four USER-space i64 anchors packed
        //     x0|y0|x1|y1 high-to-low. The device transform waits until
        //     PAINT time (fill_ext), like path coordinates.
        //   gradSaves @2528: raw pointer to the 64-slot x 2-word gradient
        //     save bank. _init always lands it from the image, because this
        //     core only resumes. This build does not dispatch SAVE or
        //     RESTORE, so _save and _restore are unreachable.
        uint256 gradMeta;
        uint256 gradGeom;
        uint256 gradSaves;
        // stepKVM fork fields, appended at the struct END (the canonical KVM
        // library has none). halted and traitCount are STATE inside the flat
        // scalar copy range [192, 2624). ceil is per-call and sits past it.
        // HALT executed (the KSN1 `halted` bit). End of code is derivable
        // from pc. An executed HALT is not.
        uint256 halted; // offset 2560
        // Plain per-TRAIT counter (the KSN1 `traitCount`). The canonical
        // interpreter keeps none, because trait values are stream output.
        uint256 traitCount; // offset 2592
        // Budget-yield ceiling for THIS chunk: startSteps + stepBudget.
        uint256 ceil; // offset 2624
        // The sparse-state fields below are per-call or derived. They sit
        // outside the flat scalar copy range [192, 2624).
        //
        // pathBase has no field. The resumed base path
        // ((baseSegCount << 32) | baseByteLen; 0 = no live base) lives in
        // the dead s.mem slot @512, which is inside the flat scalar range:
        // it reaches the Runner by the scalar copy at flat offset 352. _init
        // derives it from the resumed segCount (the tail buffer is empty at
        // a boundary). Every path reset (path_reset) clears it. flush_path
        // and the Runner's pathDelta consume it.
        //
        // s.gCursor (offset 2656) keeps the shared KFI1 layout: in the other
        // cores it is the GRADIENT op checkpoint, 0 or (1 << 64) | line-i.
        // It crosses the KFI1 boundary in the dead out-pointer flat word
        // (flat offset 1984 = State 2144), and in the KSN3 wire as the bit5
        // trailing section. _init hoists it before the allocator overwrites
        // s.out. This build has no GRADIENT, so it never parks a cursor. A
        // nonzero value from a resumed image faults in _run.
        uint256 gCursor; // offset 2656
        // Calldata offset of the base-path blob payload (blobs[2]). Set and
        // read only when a live base exists.
        uint256 pathBaseOff; // offset 2688
        // The per-chunk sparse linear-memory WRITE overlay: a pointer to a
        // [5,120 B bitmap | memBound x 8 B packed shadow] block that the
        // first store of THIS chunk allocates (0 until then). The bitmap
        // marks the slots this chunk wrote (mem_rd checks it). Every other
        // read uses the client memImage calldata blob in place (memBase).
        uint256 memShadow; // offset 2720
        // Calldata offset of the memImage blob payload (head slot 4 = 0x84),
        // or calldatasize() when memory is absent or unallocated (a calldata
        // read past the end returns 0, the fresh-memory value).
        uint256 memBase; // offset 2752
        // Calldata offset of flatIn's pencil section (its byteLen word). The
        // section landing in _init sets it. _pLoad reads it.
        uint256 pencilOff; // offset 2784
        // The NoiseV1Ext address (the constructor immutable of the core: a
        // runtime address, never a baked link). The NOISE arm stages it for
        // the kind-0 sample.
        address noiseLib; // offset 2816
    }
    // FFILL field-as-fill state (0xad) reuses the GFILL words. The two fill
    // modes are mutually exclusive. gradMeta @2464 bit2 = "this is a FIELD,
    // not a gradient" (a gradient never sets it). When bit2 is set: bit0
    // clear | bit1 kind | bits 8..39 colorA | bits 40..71 colorB, and
    // gradGeom @2496 = i64 scale (bits 192..255) | i64 warp (bits
    // 128..191). The seed is not held here: it is the RUN seed
    // (initialSeed @384), captured at PAINT time (the field arm of
    // fill_ext). The field uses absolute device-pixel space, so rasterizers
    // stay seed-blind. Because the field reuses the GFILL words, it saves,
    // restores, clears (FILL, FILLPAL, NOFILL, and POINT zero gradMeta),
    // and packs with no extra Core code. The KSN5/KSN6 wire still carries a
    // distinct field sub-record (the Runner splits gradient from field by
    // bit2).

    // ---- the KFI1 flat image ------------------------------------------------
    // KFI1 is the INTERNAL Runner-to-Core serialization, not the KSN wire
    // format. It has no compatibility promise. All sections are
    // word-aligned:
    //   word 0            bezier slot mask (bit i = slot i set)
    //   32   .. 2464      raw State words [192, 2624): pc, steps, sp, seed,
    //                     callDepth, the init flags, style/matrix/clip,
    //                     saveDepth, path scalars, glyph xform, gradient
    //                     scratch, brush..gradGeom, halted, traitCount.
    //                     The dead s.mem slot (flat offset 352) carries the
    //                     pathBase ((segs<<32|byteLen) of the live resumed
    //                     base path). On flatIn the Core derives it again
    //                     from segCount and the blob. The other
    //                     pointer-valued words are garbage: _init copies the
    //                     scalars into a VIRGIN struct before the allocator
    //                     overwrites every pointer.
    //   2464 .. 53792     the four eager interpreter arrays AS ALLOCATED
    //                     (stack | locals | saves | callStack, LENGTH WORDS
    //                     INCLUDED), moved in ONE copy. The length words are
    //                     the constants 256/256/1024/64.
    //   53792 .. 57888    the 64x2-word gradient save bank (zeros when never
    //                     allocated)
    //   then, in order:   [rv1 58 words if rv1Built]
    //                     [109-word bezier records per mask bit, ascending]
    //                     [pathLen bytes of open-path segs. In flatOut this
    //                     is THIS CHUNK's appended tail (the pathDelta
    //                     payload). In flatIn it MUST be empty (pathLen 0).]
    //   flatOut ONLY:     [the raw sparse write overlay if memInit: the
    //                     5,120 B bitmap, then the memBound x 8 B packed
    //                     shadow. The shadow is omitted when no store ran
    //                     this chunk, so presence = flat length past the
    //                     bitmap. The Runner walks the bitmap into the wire
    //                     memDelta.]
    //
    // The linear-memory image and the accumulated open path are
    // CLIENT-SUPPLIED calldata blobs (memImage/pathBlob on runChunk). Kind 1
    // has no noise table, so blobs[1] is unused. They are never sections of
    // flatIn, so the cost per chunk
    // does not grow with the total state. flatOut returns only the per-chunk
    // deltas.
    uint256 internal constant _FLAT_SCALARS_OFF = 192;
    uint256 internal constant _FLAT_SCALARS_LEN = 2432;
    uint256 internal constant _FLAT_ARRAYS_LEN = 0xC880; // 0x2020+0x2020+0x8020+0x820

    // ---- entry points -------------------------------------------------------

    /// @notice Validate a KVM1 container header without executing it.
    /// @dev The in-memory twin of the check that KVMPencilStepRunner applies
    ///      before it calls this Core. Checks run in this order: length,
    ///      magic, version, flags, palette bounds, data bounds. Reverts
    ///      KVMError(1..6) as mapped above. Nothing in this file calls it.
    /// @param program A KVM1 container.
    function validateHeader(bytes memory program) internal pure {
        if (program.length < 15) revert KVMError(1); // TruncatedHeader
        uint256 w0 = _word(program, 0);
        if (uint32(w0 >> 224) != MAGIC) revert KVMError(2); // BadMagic
        if (uint8(w0 >> 216) != VERSION) revert KVMError(3); // BadVersion
        // flags byte 5: bits 0..1 are assigned (DEVICE_STROKE, STROKE_HARD).
        // Bits 2..7 are reserved and rejected, so new flags fail loudly.
        if (uint8(w0 >> 208) > 3) revert KVMError(6); // BadFlags
        uint256 n = uint8(w0 >> 168);
        uint256 headerLen = 11 + n * 4;
        if (program.length < headerLen + 4) revert KVMError(4); // TruncatedPalette
        uint256 dataLen = uint32(_word(program, headerLen) >> 224);
        if (program.length < headerLen + 4 + dataLen) revert KVMError(5); // TruncatedData
    }

    /// @notice Execute one bounded chunk of a KVM1 container run.
    /// @dev Always resumes from flatIn (the Runner's genesis image on a fresh
    ///      run). An image with the wrong geometry faults at the
    ///      exact-consumption check in _init. The finishing chunk appends the
    ///      0xB1 end record. The Runner owns the 0xB0 begin record. Every
    ///      interpreter fault reverts the whole call with KVMError (mostly
    ///      the bare selector; see the errors note).
    ///
    ///      THE HEAD SEAM. The blobs array ([memImage, noiseTable, pathBlob])
    ///      is read straight from the ABI head of the wrapper's runChunk
    ///      (head slot 4 = 0x84, elements walked in place). The wrapper
    ///      calls this internal function in the same frame, so the head slots
    ///      are fixed. This keeps the legacy pipeline under its 16-slot
    ///      stack. A caller with a different ABI shape reads garbage cursors.
    ///      The Core consumes a cursor only when the resumed state needs the
    ///      blob, and the Runner validates the blob geometry first.
    ///      memImage (blobs[0]): the client-held linear-memory image
    ///      (memBound x 8 B big-endian i64). REQUIRED, with exact length,
    ///      when the resumed image has memInit set. The Core reads it in
    ///      place.
    ///      noiseTable (blobs[1]): the assembled NoiseV1Ext call blob for
    ///      kind 0 (133,316 B, which KVMPencilStepRunner builds from the
    ///      client's raw table). REQUIRED when the resumed image has marker
    ///      1 and at NOISEINIT kind 0. Kind 1 has no table.
    ///      pathBlob (blobs[2]): the client-held accumulated open path
    ///      (canonical seg bytes). REQUIRED when the resumed segCount is not
    ///      zero. The Core reads it in place at PAINT.
    /// @param program    A KVM1 container: header, palette, data segment,
    ///                   code. The Runner validates it before this call.
    /// @param seed       The int32 run seed. Every random source in the ISA
    ///                   derives from it.
    /// @param params     Values for the PARAM ops. A missing index reads 0.
    /// @param flatIn     The KFI1 flat image to resume from (the Runner's
    ///                   genesis image on a fresh run).
    /// @param stepBudget The yield ceiling for this chunk. It MUST be at
    ///                   least 1, which the Runner enforces: budget 0 would
    ///                   yield forever without progress.
    /// @param sinLut     SSTORE2 data contract that holds the SinLut256
    ///                   blob. The first trig-dependent op stages it.
    /// @param noiseLib   The NoiseV1Ext address for NOISE kind 0, or
    ///                   address(0) for a core where kind 0 traps.
    /// @return reason  0 = done (out ends with 0xB1), 1 = step budget
    ///                 exhausted at a yield point.
    /// @return out     This chunk's draw-stream fragment.
    /// @return flatOut The KFI1 image to resume from (empty when reason is
    ///                 0). Its tail holds the per-chunk memory write set. Its
    ///                 path section holds the appended path tail.
    function executeChunk(
        bytes memory program,
        int32 seed,
        int64[] memory params,
        bytes calldata flatIn,
        uint256 stepBudget,
        address sinLut,
        address noiseLib
    ) internal view returns (uint256 reason, bytes memory out, bytes memory flatOut) {
        State memory s;
        // The pencil family's VM state, landed from the flat's pencil
        // section after _init parks its calldata offset.
        PState memory ps;
        _init(s, program, flatIn, sinLut);
        _pLoad(s, ps);
        // Kind-0 resume: an armed NoiseV1 (marker 1, the KSN bit3 state)
        // stages the client's assembled table blob (blobs[1]) again. Kind 1
        // needs nothing: its packed params ride the flat copy at @704.
        uint256 nz;
        assembly {
            mstore(add(s, 2816), noiseLib)
            nz := mload(add(s, 736))
        }
        if (nz == 1) _noiseBlob(s);
        // Raw stores save EIP-170 bytes. Every value is already canonical
        // (the ABI decoder sign-extends seed, and params is a memory
        // pointer).
        assembly {
            mstore(add(s, 352), params)
            mstore(add(s, 384), seed) // initialSeed (the run input)
            // The genesis flat from the Runner carries the fresh-run style
            // defaults and the seed-0 xorshift guard. The scalar copy in
            // _init lands ma/md/fill/hasFill/strokeW, the live xorshift seed,
            // and memBound. This Core never initializes a fresh run.
            // ceil = steps + stepBudget (the budget-yield ceiling, unchecked)
            mstore(add(s, 2624), add(mload(add(s, 224)), stepBudget))
        }

        reason = _run(s, ps);

        assembly {
            out := mload(add(s, 2144))
            let outLen := mload(add(s, 2176))
            if iszero(reason) {
                // end record: append 0xB1 raw. Only the chunk that completes
                // execution emits it, exactly once. The ensure_out slack
                // keeps the single trailing byte in bounds.
                mstore8(add(add(out, 0x20), outLen), 0xb1)
                outLen := add(outLen, 1)
            }
            mstore(out, outLen)
        }
        if (reason != 0) flatOut = _pack(s, _pImage(ps));
    }

    /// Read the header, allocate the arrays, and land the KFI1 image. Split
    /// out of executeChunk for the 16-slot stack of the legacy pipeline.
    function _init(State memory s, bytes memory program, bytes calldata flatIn, address sinLut) private view {
        unchecked {
        s.program = program;
        uint256 w0 = _word(program, 0);
        uint256 paletteN = uint8(w0 >> 168);
        uint256 headerLen = 11 + paletteN * 4;
        // HEADER VALIDATION LIVES IN KVMPencilStepRunner, not here. This
        // Core is a trusted-input kernel. KVMPencilStepRunner.executeChunk
        // carries the magic, version, flags, and bounds checks and reverts with
        // the canonical KVMError(code) values. A malformed program that
        // reaches the Core directly still faults through the bare-KVMError
        // paths, with no distinct code. Only the dataLen parse that the
        // allocator needs stays here (the Runner guarantees
        // program.length >= headerLen + 4).
        s.dataLen = uint32(_word(program, headerLen) >> 224);

        // Interpreter arrays are bump-allocated into their pinned struct
        // slots. Only `locals` is zero-filled, because LOAD before STORE must
        // read 0. The program writes every other array before it reads it
        // (stack below sp, saves and callStack below their depth counters,
        // out and path below outLen and pathLen). All sit at low addresses.
        assembly {
            // Resume: land the raw KFI1 State scalar words FIRST, into the
            // still-virgin struct (program and dataLen sit at offsets 0 and
            // 64, below the copy range). The allocator below then overwrites
            // every pointer field. A malformed image ends in invalid() at the
            // exact-consumption check after the section landing
            // (calldatacopy zero-pads past calldata, so a short image never
            // smashes memory). The Runner owns KSN wire validation.
            {
                calldatacopy(add(s, _FLAT_SCALARS_OFF), add(flatIn.offset, 32), _FLAT_SCALARS_LEN)
                // The parked GRADIENT cursor ((1<<64)|line-i, 0 = none) rides
                // the dead out-pointer flat word (flat offset 1984 = State
                // 2144). Hoist it to gCursor now: the allocator below
                // overwrites s.out.
                mstore(add(s, 2656), mload(add(s, 2144)))
            }
            let fp := mload(0x40)
            // palette: pal_color reads it in place from the program header.
            // No array is built (EIP-170 headroom).
            mstore(add(s, 256), fp) // stack: 256 slots, unzeroed
            mstore(fp, 256)
            fp := add(fp, 0x2020)
            mstore(add(s, 320), fp) // locals: 256 slots, ZEROED
            mstore(fp, 256)
            calldatacopy(add(fp, 0x20), calldatasize(), 0x2000)
            fp := add(fp, 0x2020)
            mstore(add(s, 1504), fp) // saves: 64 * SAVE_WORDS(16), unzeroed
            mstore(fp, 1024)
            fp := add(fp, 0x8020)
            mstore(add(s, 448), fp) // callStack: 64 slots, unzeroed
            mstore(fp, 64)
            fp := add(fp, 0x820)
            mstore(add(s, 2144), fp) // out: 131072 B, unzeroed
            mstore(fp, 131072)
            // s.outLen = 0 for every chunk: the Core never emits the 0xB0
            // begin record, and each out buffer holds only THIS chunk's
            // fragment. The default linear-memory bound (40960) rides the
            // genesis flat's memBound word. A resume carries it at 2400.
            mstore(add(s, 2176), 0)
            fp := add(fp, 0x20020)
            // path buffer: 16384 B, grown by the doubling rule of
            // ensure_path. A resume lands NO path bytes: the base rides the
            // client path blob and the buffer holds only THIS chunk's tail.
            // flatIn pathLen must be 0.
            mstore(add(s, 1568), fp) // path: unzeroed
            mstore(fp, 16384)
            fp := add(fp, add(0x20, 16384))
            // FLAG_DEVICE_STROKE: header flags byte 5, bit0 (see det_scale)
            mstore(add(s, 2368), and(shr(208, w0), 1))
            // The scalar image copy left FOREIGN pointer words (from the
            // frame that packed the image) in the lazy-table slots and the
            // staged-LUT pointer. Restore the fresh values: int64[] members
            // point at the reserved-zero slot 0x60, and raw pointers are 0.
            // The s.mem slot @512 is the pathBase scalar. Zero it here: a
            // fresh run carries the 0x60 array-init, and a resume carries the
            // stale value of the previous chunk. The sections landing below
            // recomputes it from the resumed segCount and the blob length.
            mstore(add(s, 512), 0) // pathBase (the dead mem slot)
            mstore(add(s, 576), 0) // rv1 (raw ptr)
            mstore(add(s, 640), 0) // beziers (raw ptr)
            // No @704 reset: that slot holds the packed kind-1
            // {octaves, gain} across chunks, and the flat landing above is
            // its restore. Only marker 2 reads it.
            mstore(add(s, 800), 0) // lutPtr (staged lazily per-call)
            // Set lutAddr after the scalar copy, which left a stale word in
            // that slot. lut_ptr reads it on the first trig-dependent op.
            mstore(add(s, 768), sinLut)
            // resume: land the KFI1 array sections
            {
                let bezMask := calldataload(flatIn.offset)
                let src := add(flatIn.offset, 2464)
                // the four eager arrays as ONE block (stack | locals | saves
                // | callStack, the allocator order above), LENGTH WORDS
                // INCLUDED. They equal the constants the allocator wrote.
                calldatacopy(mload(add(s, 256)), src, _FLAT_ARRAYS_LEN)
                src := add(src, _FLAT_ARRAYS_LEN)
                // gradient save bank: always materialized on resume. If the
                // bank never existed, gradMeta is 0 and every slot is 0, so a
                // restore writes 0 over 0.
                mstore(add(s, 2528), fp)
                calldatacopy(fp, src, 0x1000)
                fp := add(fp, 0x1000)
                src := add(src, 0x1000)
                // RandomV1 58-word block (56 seed words + inext + inextp)
                if mload(add(s, 608)) {
                    mstore(add(s, 576), fp)
                    calldatacopy(fp, src, 0x740)
                    fp := add(fp, 0x740)
                    src := add(src, 0x740)
                }
                // (no noise section: kind 1 has no table)
                // (no linear-memory section: the memory ops read the client
                // memImage blob in place and write the sparse overlay)
                // bezier bank: 64 pointer slots, then one 109-word record per
                // mask bit (ascending slot order, mirrored by _pack)
                if bezMask {
                    let bank := fp
                    fp := add(fp, 0x800)
                    calldatacopy(bank, calldatasize(), 0x800) // 64 null ptrs
                    mstore(add(s, 640), bank)
                    for { let i := 0 } lt(i, 64) { i := add(i, 1) } {
                        if and(shr(i, bezMask), 1) {
                            mstore(add(bank, shl(5, i)), fp)
                            calldatacopy(fp, src, 0xda0)
                            fp := add(fp, 0xda0)
                            src := add(src, 0xda0)
                        }
                    }
                }
                // open path: flatIn carries NO seg bytes (the base rides the
                // client path blob). A nonzero incoming pathLen is a malformed
                // image and fails the exact-consumption check below.
                // The pencil section: u256 byteLen, then the word image that
                // _pLoad reads (byteLen 0 = no pencil state). Its calldata
                // offset parks in s.pencilOff for the landing after _init.
                mstore(add(s, 2784), src)
                src := add(src, add(32, calldataload(src)))
                // the image must be consumed exactly
                if iszero(eq(sub(src, flatIn.offset), flatIn.length)) { invalid() }
                // the resumed base path. At an inter-op boundary the tail
                // buffer is empty, so base segs = the resumed segCount and
                // byteLen = the length of the blobs[2] blob. pathBaseOff stays
                // 0 when there is no base. flush_path checks pathBase.
                let sc := mload(add(s, 1632))
                if sc {
                    let eo := add(4, calldataload(0x84))
                    eo := add(add(eo, 0x20), calldataload(add(eo, 0x60)))
                    mstore(add(s, 2688), add(eo, 0x20))
                    mstore(add(s, 512), or(shl(32, sc), calldataload(eo)))
                }
            }
            // memBase cursor (head seam: blobs sits at runChunk head slot 4
            // = 0x84): the memImage (blobs[0]) payload, or calldatasize()
            // when memory is unallocated.
            {
                let bo := add(4, calldataload(0x84))
                bo := add(add(add(bo, 0x20), calldataload(add(bo, 0x20))), 0x20)
                if iszero(mload(add(s, 544))) { bo := calldatasize() }
                mstore(add(s, 2752), bo)
            }
            // dataStart, codeStart, codeLen, twoThirds: dataStart @32,
            // dataLen @64 (set above), codeStart @96, codeLen @128,
            // twoThirds @1760.
            let dstart := add(headerLen, 4)
            mstore(add(s, 32), dstart)
            let cstart := add(dstart, mload(add(s, 64)))
            mstore(add(s, 96), cstart)
            mstore(add(s, 128), sub(mload(program), cstart))
            // (twoThirds @1760 = Fix64.div(TWO, THREE) rides the flat: the
            // Runner seeds it into every genesis and decoded image, and _pack
            // round-trips it. The value is bit-exact.)
            mstore(0x40, fp)
        }
        } // unchecked: the Runner's header validation bounds every
        // quantity here (EIP-170: checked-math guards are dead weight)
    }


    /// Serialize the complete VM state into a KFI1 flat image: the inverse
    /// of the landing code in _init, with the same section order and sizes.
    /// One pass: sections append at a cursor. pim is the pencil section that
    /// _pImage builds.
    function _pack(State memory s, bytes memory pim) private pure returns (bytes memory f) {
        assembly {
            f := mload(0x40)
            let d := add(f, 0x20)
            // word 0 (bezMask) is reserved here. The bezier-bank walk below
            // backfills it, so one scan replaces two.
            mcopy(add(d, 32), add(s, _FLAT_SCALARS_OFF), _FLAT_SCALARS_LEN)
            d := add(d, 2464)
            // the four eager arrays as ONE block (see _init)
            mcopy(d, mload(add(s, 256)), _FLAT_ARRAYS_LEN)
            d := add(d, _FLAT_ARRAYS_LEN)
            // gradient bank (zeros when never allocated; see _init)
            switch mload(add(s, 2528))
            case 0 { calldatacopy(d, calldatasize(), 0x1000) }
            default { mcopy(d, mload(add(s, 2528)), 0x1000) }
            d := add(d, 0x1000)
            if mload(add(s, 608)) {
                mcopy(d, mload(add(s, 576)), 0x740)
                d := add(d, 0x740)
            }
            // (no noise section: kind 1 has no table. Linear memory returns
            // as the write overlay at the flat TAIL below, for the Runner's
            // write-delta diff)
            // beziers: the ascending records. The same pass computes bezMask
            // and backfills word 0 (bezInit at 672 gates the bank)
            let bezMask := 0
            if mload(add(s, 672)) {
                let bank := mload(add(s, 640))
                for { let i := 0 } lt(i, 64) { i := add(i, 1) } {
                    let rec := mload(add(bank, shl(5, i)))
                    if rec {
                        bezMask := or(bezMask, shl(i, 1))
                        mcopy(d, rec, 0xda0)
                        d := add(d, 0xda0)
                    }
                }
            }
            // (pathBase reaches the Runner inside the scalar copy, in the
            // dead s.mem slot @512 = flat offset 352. Word 0 stays the pure
            // bezier mask. The parked GRADIENT cursor (the op checkpoint, 0
            // when none) overwrites the dead out-pointer word at flat offset
            // 1984. The scalar mcopy above filled that word with the live
            // buffer pointer, which the Runner must never read as a cursor.)
            mstore(add(f, 0x20), bezMask)
            mstore(add(add(f, 0x20), 1984), mload(add(s, 2656)))
            // the pencil section (u256 byteLen + the word image), between
            // the bezier records and the path tail
            mcopy(d, add(pim, 0x20), mload(pim))
            d := add(d, mload(pim))
            {
                let pl := mload(add(s, 1600))
                mcopy(d, add(mload(add(s, 1568)), 0x20), pl)
                d := add(d, pl)
            }
            // sparse-memory tail (flatOut only, when memInit): THIS chunk's
            // write overlay RAW. First the 5,120 B bitmap, then the memBound
            // x 8 B packed shadow (omitted when no store ran this chunk).
            // The RUNNER walks the bitmap and emits the wire memDelta,
            // because it has the EIP-170 headroom and this fork does not.
            if mload(add(s, 544)) {
                let sh := mload(add(s, 2720))
                switch sh
                case 0 { calldatacopy(d, calldatasize(), 0x1400) }
                default {
                    let n := add(0x1400, shl(3, mload(add(s, 2400))))
                    mcopy(d, sh, n)
                    d := add(d, sub(n, 0x1400))
                }
                d := add(d, 0x1400)
            }
            mstore(f, sub(d, add(f, 0x20)))
            mstore(0x40, and(add(add(d, 24), 31), not(31)))
        }
    }

    // ---- the interpreter core -----------------------------------------------

    /*
     * The interpreter core: one inline-assembly block with the dispatch
     * loop and every hot opcode as Yul. ip, sp, and steps live in EVM stack
     * slots, and the arrays are addressed raw off the State struct. A cold
     * op syncs ip/sp/steps into the State, goes through the router in _run,
     * and re-enters the block. Every interpreter fault reverts the bare
     * KVMError selector (the fail() helper). The saturating Fix64 add, sub,
     * and div and the Q31.32 mul and floor are 1:1 transcriptions of the
     * Fix64 library.
     */
    function _run(State memory s, PState memory ps) private view returns (uint256 reason) {
        // This build has no GRADIENT (0x76) case. Only a snapshot this core
        // did not make (KSN flags bit5) can set s.gCursor. _warmOps then
        // reaches invalid() and the call reverts with no data. A run of this
        // core never parks a cursor.
        if (s.gCursor != 0) _warmOps(s, 0x76);
        while (true) {
            uint256 exitOp = _hotLoop(s);
            if (exitOp == 0x101) return 1; // budget yield (between ops or mid-op:
                // a parked GRADIENT cursor makes the hot loop exit with it)
            if (exitOp >= 0x100) return 0; // HALT (s.halted set) or end of code
            // cold op: _hotLoop synced ip/sp/steps into the State
            uint256 op = exitOp;
            // Cold routing: each arm stages its op family and faults in
            // place, then falls to the ONE shared _warmOps call below.
            if (op < 0x38) {
                // NOP/DUP2/SWAP, DR8, math, RV1RESET/RV1RAW: warm Yul. The
                // only unassigned value in the range is 0x07. The _warmOps
                // switch defaults are an invalid() backstop.
                if (op == 0x07) revert KVMError(8); // InvalidOpcode
            } else if (op < 0x40) {
                // RAND/RANDR are hot-inlined and never arrive here. RV1GAUSS
                // needs the Trig256 address staged for its ln staticcall.
                if (op == 0x3b) _stageTrig(s);
            } else if (op < 0x50) {
                // The KVMPencilRunner subset, stepped: only the color VALUE
                // ops (SETALPHA, TINT, HSB2RGB) survive. Fill, stroke, blend,
                // and brush state and BG/BGPAL trap. A program that uses them
                // needs the 2D cores.
                if (!(op == 0x49 || op == 0x4a || op == 0x4d)) {
                    revert KVMError(8); // InvalidOpcode (not in the pencil subset)
                }
            } else if (op < 0x70) {
                // SAVE/RESTORE, the 2D CTM, clips, YFLIP, stroke style, the
                // path family, STAMP/FIELD/ALIASED, and the input family do
                // not exist in a pencil stream. The whole block traps.
                revert KVMError(8); // InvalidOpcode (not in the pencil subset)
            } else if (op < 0x80) {
                // Of 0x70..0x7f only the VALUE ops survive: the bezier bank
                // (BEZSET/BEZMX/BEZMY) and the noise family, kinds 0 and 1.
                // The 2D shape emitters, GRADIENT, and glyph walkers trap.
                if (!(op >= 0x79 && op <= 0x7d)) revert KVMError(8); // InvalidOpcode
                // The range is warm Yul, except NOISEINIT kind 0, which this
                // layer admits (_noise0: the table is the client's blobs[1],
                // with no build in the op). Kind 1 and every NOISEINIT fault
                // go to the warm case. NOISE stages the NoiseV1Ext address
                // for its kind-0 staticcall. Kind 1 staticcalls the CREATE2
                // constant GRADNOISE.
                if (op == 0x7c) {
                    if (_noise0(s)) continue;
                } else if (op == 0x7d) {
                    assembly {
                        mstore(add(s, 2112), mload(add(s, 2816)))
                    }
                }
            } else if (op <= 0x8c) {
                // TAN/ATAN2/POW/EXP/LOG/ROUND/CEIL/FRACT/SIGN/DIST/ASIN/ACOS/
                // SEED: warm Yul. Stage the Trig256 address for the ext calls.
                _stageTrig(s);
            } else if (op == 0xb0) {
                // PENCIL: the arm this stepped core exists to carry. It is
                // atomic like every op. Its surcharge lands in s.steps, so the
                // budget check at the next loop head can overshoot by this
                // one op, as the reference stepper does.
                _pencil(s, ps);
                continue;
            } else if (
                !((op <= 0x96 && op != 0x8e && op != 0x8f) || op == 0xa4 || (op >= 0xaa && op <= 0xac) || op == 0xae)
            ) {
                // RGBPACK 0x8d, bitwise 0x90..0x96, MEMCAP 0xa4, FL32 0xaa,
                // HASH 0xab, PSCATTER 0xac, UNPACK 0xae: warm Yul. 0x97..0x9f
                // and 0xa1/0xa2 are hot-inlined superinstructions and never
                // exit cold. The Mesh3D records (CAM/LIGHT 0x8e/0x8f, MESH
                // 0xa3, MESHC 0xaf), GLYPHC 0xa0, the 2D CTM pair 0xa5/0xa6,
                // GFILL/GLYPH64XF/CLIPRECTT 0xa7..0xa9, and FFILL 0xad are not
                // in the pencil subset. Every other value is invalid
                // everywhere.
                revert KVMError(8); // InvalidOpcode
            }
            _warmOps(s, op);
        }
    }

    /// The hot interpreter core: one Yul block that runs ops until HALT or
    /// end of code (returns 0x100) or an op it does not implement (returns
    /// that op for the cold dispatch). ip, sp, and steps live in EVM stack
    /// slots and sync through s.pc, s.sp, and s.steps at the boundary. The
    /// Fix64 helpers are 1:1 transcriptions of the Fix64 library. Every
    /// fault goes through the shared fail() helper.
    function _hotLoop(State memory s) private pure returns (uint256 exitOp) {
        assembly {
                function fail() {
                    // KVMError() with the bare selector 0x4c49dedb (no code
                    // word). The 108 interpreter-fault sites push no code,
                    // which saves ~2 B each. The code map covers only the
                    // Solidity-side reverts.
                    mstore(0x00, shl(224, 0x4c49dedb))
                    revert(0x00, 0x04)
                }
                function fx_add(x, y) -> r {
                    r := signextend(7, add(x, y))
                    if and(and(not(xor(x, y)), xor(x, r)), 0x8000000000000000) {
                        switch sgt(x, 0)
                        case 1 { r := 0x7fffffffffffffff }
                        default { r := signextend(7, 0x8000000000000000) }
                    }
                }
                function fx_sub(x, y) -> r {
                    r := signextend(7, sub(x, y))
                    if and(and(xor(x, y), xor(x, r)), 0x8000000000000000) {
                        switch slt(x, 0)
                        case 1 { r := signextend(7, 0x8000000000000000) }
                        default { r := 0x7fffffffffffffff }
                    }
                }
                function fx_mul(x, y) -> r {
                    r := signextend(7, sar(32, mul(x, y)))
                }
                function fx_div(x, y) -> r {
                    if iszero(y) { fail() } // AttemptedToDivideByZero()
                    let ax := x
                    if slt(ax, 0) { ax := sub(0, ax) }
                    r := y
                    if slt(r, 0) { r := sub(0, r) }
                    ax := div(shl(33, ax), r) // ax = q
                    switch gt(ax, 0xffffffffffffffff)
                    case 1 {
                        switch and(xor(x, y), 0x8000000000000000)
                        case 0 { r := 0x7fffffffffffffff }
                        default { r := signextend(7, 0x8000000000000000) }
                    }
                    default {
                        r := signextend(7, shr(1, add(ax, 1)))
                        if and(xor(x, y), 0x8000000000000000) { r := signextend(7, sub(0, r)) }
                    }
                }
                function mem_rd(s_, addr) -> mv {
                    // sparse linear memory: a slot THIS chunk wrote reads the
                    // overlay shadow (gated by the bitmap). Every other slot
                    // reads the client memImage calldata blob in place
                    // (memBase @2752; calldatasize() when absent, so a fresh
                    // slot reads 0). This helper owns the bounds check.
                    if or(slt(addr, 0), iszero(slt(addr, mload(add(s_, 2400))))) { fail() } // MemoryOutOfRange()
                    mv := calldataload(add(mload(add(s_, 2752)), shl(3, addr)))
                    let sh := mload(add(s_, 2720))
                    if sh {
                        if and(mload(add(sh, shl(5, shr(8, addr)))), shl(and(addr, 0xff), 1)) {
                            mv := mload(add(add(sh, 0x1400), shl(3, addr)))
                        }
                    }
                    mv := signextend(7, shr(192, mv))
                }
                function mem_wr(s_, addr, v) {
                    // sparse write: mark the bitmap and store the packed 8 B
                    // value in the shadow (read-modify-write keeps the three
                    // neighbor slots). The first store of the chunk allocates
                    // the [5,120 B zeroed bitmap | memBound x 8 B unzeroed
                    // shadow] block and sets memInit. This helper owns the
                    // bounds check, AFTER both pops, in the operand order of
                    // the reference (every fault is the same bare selector).
                    if or(slt(addr, 0), iszero(slt(addr, mload(add(s_, 2400))))) { fail() } // MemoryOutOfRange()
                    let sh := mload(add(s_, 2720))
                    if iszero(sh) {
                        sh := mload(0x40)
                        mstore(0x40, add(sh, add(0x1420, shl(3, mload(add(s_, 2400))))))
                        calldatacopy(sh, calldatasize(), 0x1400)
                        mstore(add(s_, 2720), sh)
                        mstore(add(s_, 544), 1) // s.memInit
                    }
                    {
                        let bw := add(sh, shl(5, shr(8, addr)))
                        mstore(bw, or(mload(bw), shl(and(addr, 0xff), 1)))
                    }
                    let p := add(add(sh, 0x1400), shl(3, addr))
                    mstore(p, or(shl(192, v), shr(64, shl(64, mload(p)))))
                }

                let ip_ := mload(add(s, 192))
                let sp_ := mload(add(s, 288))
                let steps_ := mload(add(s, 224))
                exitOp := 0x100

                let codeBase := add(add(mload(s), 0x20), mload(add(s, 96)))
                let cl := mload(add(s, 128))
                // stack and locals base pointers sit in scratch (stack-depth
                // relief for the legacy Yul->EVM transform)
                mstore(0x00, add(mload(add(s, 256)), 0x20))
                mstore(0x20, add(mload(add(s, 320)), 0x20))

                for {} lt(ip_, cl) {} {
                    // stepKVM budget-yield seam: yield BEFORE the dispatch of
                    // the next op, at the boundary that the STEP_LIMIT trap
                    // uses. An op executes if and only if steps < ceil
                    // (pre-increment), as in the TS interpreter. ceil rides
                    // the State (2624), not a Yul local, because the loop is
                    // already at the stack ceiling of the legacy transform.
                    if iszero(lt(steps_, mload(add(s, 2624)))) {
                        exitOp := 0x101
                        break
                    }
                    steps_ := add(steps_, 1)
                    if gt(steps_, 0x100000000) { fail() } // StepLimitExceeded()
                    let op := byte(0, mload(add(codeBase, ip_)))
                    ip_ := add(ip_, 1)
                    switch op
                    case 0x14 {
                        // LOAD u8
                        if iszero(lt(ip_, cl)) { fail() } // TruncatedImmediate()
                        let k := byte(0, mload(add(codeBase, ip_)))
                        if iszero(lt(sp_, 256)) { fail() } // StackOverflow()
                        mstore(add(mload(0x00), shl(5, sp_)), mload(add(mload(0x20), shl(5, k))))
                        ip_ := add(ip_, 1)
                        sp_ := add(sp_, 1)
                    }
                    default {
                    // Two-level dispatch (LOAD keeps a flat fast lane). The
                    // group order 1, 2, 0xa, 0, 9, 3 follows the measured
                    // dynamic frequency. A cold op exits after ~7 compares,
                    // not ~44.
                    switch shr(4, op)
                    case 1 {
                    switch op
                    case 0x15 {
                        // STORE u8
                        if iszero(lt(ip_, cl)) { fail() }
                        let k := byte(0, mload(add(codeBase, ip_)))
                        if iszero(sp_) { fail() } // StackUnderflow()
                        ip_ := add(ip_, 1)
                        sp_ := sub(sp_, 1)
                        mstore(add(mload(0x20), shl(5, k)), mload(add(mload(0x00), shl(5, sp_))))
                    }
                    case 0x12 {
                        // MLOAD (mem_rd checks the bound s.memBound;
                        // sparse read)
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                        let addr := sar(32, mload(add(mload(0x00), shl(5, sp_))))
                        mstore(add(mload(0x00), shl(5, sp_)), mem_rd(s, addr))
                        sp_ := add(sp_, 1)
                    }
                    case 0x13 {
                        // MSTORE (mem_wr checks the bound and owns the
                        // first-store alloc; sparse write overlay)
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                        let addr := sar(32, mload(add(mload(0x00), shl(5, sp_))))
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                        mem_wr(s, addr, mload(add(mload(0x00), shl(5, sp_))))
                    }
                    case 0x1f {
                        // DR16: pop byte offset -> u16 BE * ONE
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                        let off := sar(32, mload(add(mload(0x00), shl(5, sp_))))
                        if or(slt(off, 0), sgt(add(off, 2), mload(add(s, 64)))) { fail() } // DataReadOutOfBounds()
                        let v := shr(240, mload(add(add(add(mload(s), 0x20), mload(add(s, 32))), off)))
                        mstore(add(mload(0x00), shl(5, sp_)), shl(32, v))
                        sp_ := add(sp_, 1)
                    }
                    case 0x11 {
                        // DROP
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                    }
                    case 0x16 {
                        // LOAD0
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(add(mload(0x00), shl(5, sp_)), mload(mload(0x20)))
                        sp_ := add(sp_, 1)
                    }
                    case 0x17 {
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(add(mload(0x00), shl(5, sp_)), mload(add(mload(0x20), 0x20)))
                        sp_ := add(sp_, 1)
                    }
                    case 0x18 {
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(add(mload(0x00), shl(5, sp_)), mload(add(mload(0x20), 0x40)))
                        sp_ := add(sp_, 1)
                    }
                    case 0x19 {
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(add(mload(0x00), shl(5, sp_)), mload(add(mload(0x20), 0x60)))
                        sp_ := add(sp_, 1)
                    }
                    case 0x1a {
                        // STORE0
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                        mstore(mload(0x20), mload(add(mload(0x00), shl(5, sp_))))
                    }
                    case 0x1b {
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                        mstore(add(mload(0x20), 0x20), mload(add(mload(0x00), shl(5, sp_))))
                    }
                    case 0x1c {
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                        mstore(add(mload(0x20), 0x40), mload(add(mload(0x00), shl(5, sp_))))
                    }
                    case 0x1d {
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                        mstore(add(mload(0x20), 0x60), mload(add(mload(0x00), shl(5, sp_))))
                    }
                    default {
                        exitOp := op
                        break
                    }
                    }
                    case 2 {
                    switch op
                    case 0x20 {
                        // ADD
                        if lt(sp_, 2) { fail() }
                        sp_ := sub(sp_, 1)
                        let aslot := add(mload(0x00), shl(5, sub(sp_, 1)))
                        mstore(aslot, fx_add(mload(aslot), mload(add(aslot, 0x20))))
                    }
                    case 0x22 {
                        // MUL
                        if lt(sp_, 2) { fail() }
                        sp_ := sub(sp_, 1)
                        let aslot := add(mload(0x00), shl(5, sub(sp_, 1)))
                        mstore(aslot, fx_mul(mload(aslot), mload(add(aslot, 0x20))))
                    }
                    case 0x23 {
                        // DIV: y == 0 -> 0
                        if lt(sp_, 2) { fail() }
                        sp_ := sub(sp_, 1)
                        let aslot := add(mload(0x00), shl(5, sub(sp_, 1)))
                        let b := mload(add(aslot, 0x20))
                        switch b
                        case 0 { mstore(aslot, 0) }
                        default { mstore(aslot, fx_div(mload(aslot), b)) }
                    }
                    case 0x21 {
                        // SUB
                        if lt(sp_, 2) { fail() }
                        sp_ := sub(sp_, 1)
                        let aslot := add(mload(0x00), shl(5, sub(sp_, 1)))
                        mstore(aslot, fx_sub(mload(aslot), mload(add(aslot, 0x20))))
                    }
                    case 0x29 {
                        // FLOOR
                        if iszero(sp_) { fail() }
                        let tslot := add(mload(0x00), shl(5, sub(sp_, 1)))
                        mstore(tslot, signextend(7, and(mload(tslot), 0xFFFFFFFF00000000)))
                    }
                    default {
                        exitOp := op
                        break
                    }
                    }
                    case 0xa {
                    switch op
                    case 0xa2 {
                        // LADD8 u8 k, i8 c == LOAD k; PUSH8 c; ADD
                        if gt(add(ip_, 2), cl) { fail() }
                        let w := mload(add(codeBase, ip_))
                        ip_ := add(ip_, 2)
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(
                            add(mload(0x00), shl(5, sp_)),
                            fx_add(mload(add(mload(0x20), shl(5, byte(0, w)))), shl(32, signextend(0, byte(1, w))))
                        )
                        sp_ := add(sp_, 1)
                    }
                    case 0xa1 {
                        // LLOAD u8 k, u8 j == LOAD k; LOAD j
                        if gt(add(ip_, 2), cl) { fail() }
                        let w := mload(add(codeBase, ip_))
                        ip_ := add(ip_, 2)
                        if gt(add(sp_, 2), 256) { fail() }
                        let sb := add(mload(0x00), shl(5, sp_))
                        mstore(sb, mload(add(mload(0x20), shl(5, byte(0, w)))))
                        mstore(add(sb, 0x20), mload(add(mload(0x20), shl(5, byte(1, w)))))
                        sp_ := add(sp_, 2)
                    }
                    default {
                        exitOp := op
                        break
                    }
                    }
                    case 0 {
                    switch op
                    case 0x08 {
                        // PUSH8: i8 * ONE
                        if iszero(lt(ip_, cl)) { fail() }
                        let v := shl(32, signextend(0, byte(0, mload(add(codeBase, ip_)))))
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(add(mload(0x00), shl(5, sp_)), v)
                        ip_ := add(ip_, 1)
                        sp_ := add(sp_, 1)
                    }
                    case 0x09 {
                        // PUSH16: i16 * ONE
                        if gt(add(ip_, 2), cl) { fail() }
                        let v := shl(32, signextend(1, shr(240, mload(add(codeBase, ip_)))))
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(add(mload(0x00), shl(5, sp_)), v)
                        ip_ := add(ip_, 2)
                        sp_ := add(sp_, 1)
                    }
                    case 0x0a {
                        // PUSHQ16: q16 << 24
                        if gt(add(ip_, 2), cl) { fail() }
                        let v := shl(24, signextend(1, shr(240, mload(add(codeBase, ip_)))))
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(add(mload(0x00), shl(5, sp_)), v)
                        ip_ := add(ip_, 2)
                        sp_ := add(sp_, 1)
                    }
                    case 0x02 {
                        // JMP rel16 (one live local under the discriminants
                        // of the nested dispatch)
                        if gt(add(ip_, 2), cl) { fail() }
                        let np := add(add(ip_, 2), signextend(1, shr(240, mload(add(codeBase, ip_)))))
                        if or(slt(np, 0), sgt(np, cl)) { fail() } // JumpOutOfBounds()
                        ip_ := np
                    }
                    case 0x04 {
                        // JNZ rel16 (the taken branch re-reads the immediate:
                        // pure, and keeps one live local)
                        if gt(add(ip_, 2), cl) { fail() }
                        ip_ := add(ip_, 2)
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                        if iszero(iszero(mload(add(mload(0x00), shl(5, sp_))))) {
                            let np := add(ip_, signextend(1, shr(240, mload(add(codeBase, sub(ip_, 2))))))
                            if or(slt(np, 0), sgt(np, cl)) { fail() }
                            ip_ := np
                        }
                    }
                    case 0x05 {
                        // CALL u16 absolute (the target is parked in the gX
                        // scratch, so `depth` is the only local; check order
                        // matches the reference)
                        if gt(add(ip_, 2), cl) { fail() }
                        mstore(add(s, 1920), shr(240, mload(add(codeBase, ip_))))
                        ip_ := add(ip_, 2)
                        if gt(mload(add(s, 1920)), cl) { fail() }
                        let depth := mload(add(s, 480))
                        if iszero(lt(depth, 64)) { fail() } // CallDepthExceeded()
                        mstore(add(add(mload(add(s, 448)), 0x20), shl(5, depth)), ip_)
                        mstore(add(s, 480), add(depth, 1))
                        ip_ := mload(add(s, 1920))
                    }
                    case 0x06 {
                        // RET
                        let depth := mload(add(s, 480))
                        if iszero(depth) { fail() } // RetWithoutCall()
                        depth := sub(depth, 1)
                        ip_ := mload(add(add(mload(add(s, 448)), 0x20), shl(5, depth)))
                        mstore(add(s, 480), depth)
                    }
                    case 0x0d {
                        // PUSHC: u32 raw (zero-extended)
                        if gt(add(ip_, 4), cl) { fail() }
                        let v := shr(224, mload(add(codeBase, ip_)))
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(add(mload(0x00), shl(5, sp_)), v)
                        ip_ := add(ip_, 4)
                        sp_ := add(sp_, 1)
                    }
                    case 0x0b {
                        // PUSHQ32: i32 << 16
                        if gt(add(ip_, 4), cl) { fail() }
                        let v := shl(16, signextend(3, shr(224, mload(add(codeBase, ip_)))))
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(add(mload(0x00), shl(5, sp_)), v)
                        ip_ := add(ip_, 4)
                        sp_ := add(sp_, 1)
                    }
                    case 0x0c {
                        // PUSH64: raw i64
                        if gt(add(ip_, 8), cl) { fail() }
                        let v := signextend(7, shr(192, mload(add(codeBase, ip_))))
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(add(mload(0x00), shl(5, sp_)), v)
                        ip_ := add(ip_, 8)
                        sp_ := add(sp_, 1)
                    }
                    case 0x0e {
                        // DUP
                        if iszero(sp_) { fail() }
                        if iszero(lt(sp_, 256)) { fail() }
                        let sb := add(mload(0x00), shl(5, sp_))
                        mstore(sb, mload(sub(sb, 0x20)))
                        sp_ := add(sp_, 1)
                    }
                    case 0x03 {
                        // JZ rel16 (immediate re-read on the taken branch)
                        if gt(add(ip_, 2), cl) { fail() }
                        ip_ := add(ip_, 2)
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                        if iszero(mload(add(mload(0x00), shl(5, sp_)))) {
                            let np := add(ip_, signextend(1, shr(240, mload(add(codeBase, sub(ip_, 2))))))
                            if or(slt(np, 0), sgt(np, cl)) { fail() }
                            ip_ := np
                        }
                    }
                    case 0x00 {
                        // HALT: record it (the KSN1 `halted` bit). End of
                        // code is derivable on resume. An executed HALT is not.
                        mstore(add(s, 2560), 1)
                        break
                    }
                    default {
                        exitOp := op
                        break
                    }
                    }
                    case 9 {
                    switch op
                    case 0x97 {
                        // PUSH48: raw i48
                        if gt(add(ip_, 6), cl) { fail() }
                        let v := signextend(5, shr(208, mload(add(codeBase, ip_))))
                        if iszero(lt(sp_, 256)) { fail() }
                        mstore(add(mload(0x00), shl(5, sp_)), v)
                        ip_ := add(ip_, 6)
                        sp_ := add(sp_, 1)
                    }
                    case 0x9b {
                        // LINC u8 k, i8 c: locals[k] = add(locals[k], c*ONE)
                        if gt(add(ip_, 2), cl) { fail() }
                        let w := mload(add(codeBase, ip_))
                        ip_ := add(ip_, 2)
                        let lslot := add(mload(0x20), shl(5, byte(0, w)))
                        mstore(lslot, fx_add(mload(lslot), shl(32, signextend(0, byte(1, w)))))
                    }
                    case 0x98 {
                        // TEE u8: locals[k] = top (no pop)
                        if iszero(lt(ip_, cl)) { fail() }
                        let k := byte(0, mload(add(codeBase, ip_)))
                        ip_ := add(ip_, 1)
                        if iszero(sp_) { fail() }
                        mstore(add(mload(0x20), shl(5, k)), mload(add(mload(0x00), shl(5, sub(sp_, 1)))))
                    }
                    case 0x9e {
                        // JGEI u8 k, i16 n, rel16 == LOAD k; PUSH16 n; LT; JZ
                        if gt(add(ip_, 5), cl) { fail() }
                        let w := mload(add(codeBase, ip_))
                        ip_ := add(ip_, 5)
                        if iszero(slt(mload(add(mload(0x20), shl(5, byte(0, w)))), shl(32, signextend(1, shr(232, w))))) {
                            let np := add(ip_, signextend(1, shr(216, w)))
                            if or(slt(np, 0), sgt(np, cl)) { fail() }
                            ip_ := np
                        }
                    }
                    case 0x99 {
                        // LTJZ: LT; JZ, jump when !(a < b)
                        if gt(add(ip_, 2), cl) { fail() }
                        let rel := signextend(1, shr(240, mload(add(codeBase, ip_))))
                        ip_ := add(ip_, 2)
                        if lt(sp_, 2) { fail() }
                        sp_ := sub(sp_, 2)
                        let sb := add(mload(0x00), shl(5, sp_))
                        if iszero(slt(mload(sb), mload(add(sb, 0x20)))) {
                            let np := add(ip_, rel)
                            if or(slt(np, 0), sgt(np, cl)) { fail() }
                            ip_ := np
                        }
                    }
                    case 0x9a {
                        // LEJNZ: LE; JNZ, jump when a <= b
                        if gt(add(ip_, 2), cl) { fail() }
                        let rel := signextend(1, shr(240, mload(add(codeBase, ip_))))
                        ip_ := add(ip_, 2)
                        if lt(sp_, 2) { fail() }
                        sp_ := sub(sp_, 2)
                        let sb := add(mload(0x00), shl(5, sp_))
                        if iszero(sgt(mload(sb), mload(add(sb, 0x20)))) {
                            let np := add(ip_, rel)
                            if or(slt(np, 0), sgt(np, cl)) { fail() }
                            ip_ := np
                        }
                    }
                    case 0x9c {
                        // MLOADX: addr = add(a, b) >> 32 (mem_rd checks the
                        // bound; sparse read)
                        if lt(sp_, 2) { fail() }
                        sp_ := sub(sp_, 2)
                        let sb := add(mload(0x00), shl(5, sp_))
                        mstore(sb, mem_rd(s, sar(32, fx_add(mload(sb), mload(add(sb, 0x20))))))
                        sp_ := add(sp_, 1)
                    }
                    case 0x9d {
                        // MSTOREX: addr = add(a, b) >> 32 (mem_wr checks the
                        // bound and owns the first-store alloc)
                        if lt(sp_, 2) { fail() }
                        sp_ := sub(sp_, 2)
                        let sb := add(mload(0x00), shl(5, sp_))
                        let addr := sar(32, fx_add(mload(sb), mload(add(sb, 0x20))))
                        if iszero(sp_) { fail() }
                        sp_ := sub(sp_, 1)
                        mem_wr(s, addr, mload(add(mload(0x00), shl(5, sp_))))
                    }
                    case 0x9f {
                        // JLEZ u8 k, rel16 == LOAD k; PUSH8 0; LE; JNZ
                        if gt(add(ip_, 3), cl) { fail() }
                        let w := mload(add(codeBase, ip_))
                        ip_ := add(ip_, 3)
                        if iszero(sgt(mload(add(mload(0x20), shl(5, byte(0, w)))), 0)) {
                            let np := add(ip_, signextend(1, shr(232, w)))
                            if or(slt(np, 0), sgt(np, cl)) { fail() }
                            ip_ := np
                        }
                    }
                    default {
                        exitOp := op
                        break
                    }
                    }
                    case 3 {
                    switch op
                    case 0x31 {
                        // LT
                        if lt(sp_, 2) { fail() }
                        sp_ := sub(sp_, 1)
                        let aslot := add(mload(0x00), shl(5, sub(sp_, 1)))
                        mstore(aslot, shl(32, slt(mload(aslot), mload(add(aslot, 0x20)))))
                    }
                    case 0x38 {
                        // RAND: xorshift32 (13/17/5, int32 wrap) then
                        // (u32 >> 8) << 8. Hot-inlined: the body is small,
                        // and staying in the loop skips the cold-exit sync
                        let ns := mload(add(s, 416))
                        ns := signextend(3, xor(ns, shl(13, ns)))
                        ns := signextend(3, xor(ns, sar(17, ns)))
                        ns := signextend(3, xor(ns, shl(5, ns)))
                        mstore(add(s, 416), ns)
                        if iszero(lt(sp_, 256)) { fail() } // StackOverflow()
                        mstore(add(mload(0x00), shl(5, sp_)), shl(8, shr(8, and(ns, 0xffffffff))))
                        sp_ := add(sp_, 1)
                    }
                    case 0x39 {
                        // RANDR: lo hi -> lo + (hi-lo)*rand (hot-inlined)
                        if lt(sp_, 2) { fail() } // StackUnderflow()
                        sp_ := sub(sp_, 2)
                        let ns := mload(add(s, 416))
                        ns := signextend(3, xor(ns, shl(13, ns)))
                        ns := signextend(3, xor(ns, sar(17, ns)))
                        ns := signextend(3, xor(ns, shl(5, ns)))
                        mstore(add(s, 416), ns)
                        let base := add(mload(0x00), shl(5, sp_))
                        mstore(
                            base,
                            fx_add(
                                mload(base),
                                fx_mul(
                                    fx_sub(mload(add(base, 0x20)), mload(base)),
                                    shl(8, shr(8, and(ns, 0xffffffff)))
                                )
                            )
                        )
                        sp_ := add(sp_, 1)
                    }
                    case 0x32 {
                        // LE
                        if lt(sp_, 2) { fail() }
                        sp_ := sub(sp_, 1)
                        let aslot := add(mload(0x00), shl(5, sub(sp_, 1)))
                        mstore(aslot, shl(32, iszero(sgt(mload(aslot), mload(add(aslot, 0x20))))))
                    }
                    case 0x30 {
                        // EQ
                        if lt(sp_, 2) { fail() }
                        sp_ := sub(sp_, 1)
                        let aslot := add(mload(0x00), shl(5, sub(sp_, 1)))
                        mstore(aslot, shl(32, eq(mload(aslot), mload(add(aslot, 0x20)))))
                    }
                    default {
                        exitOp := op
                        break
                    }
                    }
                    default {
                        exitOp := op
                        break
                    }
                    }
                }

                mstore(add(s, 192), ip_)
                mstore(add(s, 288), sp_)
                mstore(add(s, 224), steps_)
                // A parked mid-op GRADIENT cursor (the op checkpoint) is a
                // budget yield even when ip == cl reads as end of code above
                // (a GRADIENT as the last op of the program still drains)
                if mload(add(s, 2656)) { exitOp := 0x101 }
        }
    }


    /*
     * Warm ops: heavyweight opcodes that run as Yul in their own frame,
     * because the hot block's stack is crowded. A warm op does the work of
     * hundreds of ops, so the extra block exit and entry cost little. The
     * block also holds the shared path-emit Yul library (the p-side path
     * buffer, the w-side output buffer, paint, sqrt). Loop and parked state
     * live in the GRADIENT scratch State slots (never live during a warm
     * op), because the legacy Yul->EVM transform cannot spill. The dispatch
     * switch at the end of the block covers only the pencil subset of
     * this build (PENCIL itself runs in Solidity, in _pencil). The path,
     * glyph, gradient, and fill emitters are not dispatched, and any op
     * without a case reaches invalid().
     */
    function _warmOps(State memory s, uint256 op) private view {
        assembly {
            function fail() {
                // KVMError() with the bare selector 0x4c49dedb (no code
                // word); see the fail() note in _hotLoop.
                mstore(0x00, shl(224, 0x4c49dedb))
                revert(0x00, 0x04)
            }
            function fx_add(x, y) -> r {
                r := signextend(7, add(x, y))
                if and(and(not(xor(x, y)), xor(x, r)), 0x8000000000000000) {
                    switch sgt(x, 0)
                    case 1 { r := 0x7fffffffffffffff }
                    default { r := signextend(7, 0x8000000000000000) }
                }
            }
            function fx_sub(x, y) -> r {
                r := signextend(7, sub(x, y))
                if and(and(xor(x, y), xor(x, r)), 0x8000000000000000) {
                    switch slt(x, 0)
                    case 1 { r := signextend(7, 0x8000000000000000) }
                    default { r := 0x7fffffffffffffff }
                }
            }
            function fx_mul(x, y) -> r {
                r := signextend(7, sar(32, mul(x, y)))
            }
            function fx_abs(x) -> r {
                // Fix64.abs transcribed 1:1 (branchless; MIN stays MIN)
                let m := sar(63, x)
                r := signextend(7, xor(add(x, m), m))
            }
            function fx_clamp(v, lo, hi) -> r {
                // Fix64.constrain: shared by the clamp-heavy ops (HSB2RGB,
                // ASIN, ACOS, RGBPACK): one body, not inline pairs
                r := v
                if sgt(r, hi) { r := hi }
                if slt(r, lo) { r := lo }
            }
            function fx_div(x, y) -> r {
                if iszero(y) { fail() } // AttemptedToDivideByZero()
                let ax := x
                if slt(ax, 0) { ax := sub(0, ax) }
                r := y
                if slt(r, 0) { r := sub(0, r) }
                ax := div(shl(33, ax), r) // ax = q
                switch gt(ax, 0xffffffffffffffff)
                case 1 {
                    switch and(xor(x, y), 0x8000000000000000)
                    case 0 { r := 0x7fffffffffffffff }
                    default { r := signextend(7, 0x8000000000000000) }
                }
                default {
                    r := signextend(7, shr(1, add(ax, 1)))
                    if and(xor(x, y), 0x8000000000000000) { r := signextend(7, sub(0, r)) }
                }
            }
            function fx_sqrt(x) -> r {
                // Trig256.sqrt transcribed 1:1 (restoring, two passes). The
                // uint64 wrap at the pass boundary is masked explicitly.
                if slt(x, 0) { fail() } // NegativeValuePassed()
                let num := x
                let bit := shl(62, 1)
                for {} gt(bit, num) {} { bit := shr(2, bit) }
                for {} bit {} {
                    switch lt(num, add(r, bit))
                    case 0 {
                        num := sub(num, add(r, bit))
                        r := add(shr(1, r), bit)
                    }
                    default { r := shr(1, r) }
                    bit := shr(2, bit)
                }
                switch gt(num, 0xffffffff)
                case 1 {
                    num := and(sub(shl(32, sub(num, r)), 0x80000000), 0xffffffffffffffff)
                    r := add(shl(32, r), 0x80000000)
                }
                default {
                    num := shl(32, num)
                    r := shl(32, r)
                }
                for { bit := shl(30, 1) } bit {} {
                    switch lt(num, add(r, bit))
                    case 0 {
                        num := sub(num, add(r, bit))
                        r := add(shr(1, r), bit)
                    }
                    default { r := shr(1, r) }
                    bit := shr(2, bit)
                }
                if gt(num, r) { r := add(r, 1) }
            }
            function fx_sign(x) -> r {
                // Fix64.sign: -1 / 0 / 1
                r := sub(sgt(x, 0), slt(x, 0))
            }
            function fx_round(x) -> r {
                // Fix64.round (round-half-to-even on the Q31.32 fraction)
                // with the reference's int64 truncation of integral + ONE
                let fr := and(x, 0xffffffff)
                r := signextend(7, and(x, 0xffffffff00000000))
                if iszero(lt(fr, 0x80000000)) {
                    switch gt(fr, 0x80000000)
                    case 1 { r := signextend(7, add(r, 0x100000000)) }
                    default { if and(r, 0x100000000) { r := signextend(7, add(r, 0x100000000)) } }
                }
            }
            function lut_ptr(s_) -> ptr {
                // _lut: stage the SinLut256 blob from the SSTORE2 data
                // contract on first use (skip the STOP prefix)
                ptr := mload(add(s_, 800))
                if iszero(ptr) {
                    ptr := mload(0x40)
                    mstore(0x40, add(ptr, 0x820))
                    extcodecopy(mload(add(s_, 768)), ptr, 1, 0x800)
                    mstore(add(s_, 800), ptr)
                }
            }
            function lut_at(lp, i) -> v {
                // SinLut256.sinlut(lutPtr, i), with the fallthrough clamps of
                // the original selection tree for indices out of range
                if slt(i, 0) { i := 1 }
                if sgt(i, 255) { i := 255 }
                v := shr(192, mload(add(lp, shl(3, i))))
            }
            function trig_clamp(x) -> c, flipH, flipV {
                // Trig256.clamp: fold x into [0, PI/2) with flip flags
                c := x
                for { let i := 0 } lt(i, 29) { i := add(i, 1) } {
                    c := smod(c, shr(i, 7244019458077122842)) // LARGE_PI >> i
                }
                if slt(x, 0) { c := add(c, 0x6487ED511) } // TWO_PI
                flipV := iszero(slt(c, 0x3243F6A88)) // >= PI
                for {} iszero(slt(c, 0x3243F6A88)) {} { c := sub(c, 0x3243F6A88) }
                flipH := iszero(slt(c, 0x1921FB544)) // >= PI_OVER_2
                if flipH { c := sub(c, 0x1921FB544) }
            }
            function fx_sin(s_, x) -> v {
                // Trig256.sin(x, lutPtr) transcribed 1:1: LUT lookup with a
                // round-half-to-even index and linear interpolation on the
                // index error (mul_256 == sar(32, mul) exactly for int64)
                let c, flipH, flipV
                c, flipH, flipV := trig_clamp(x)
                let raw := sar(32, mul(c, 697236581115)) // LUT_INTERVAL
                let ri := fx_round(raw)
                let ie := fx_sub(raw, ri)
                ri := shr(32, ri)
                let lp := lut_ptr(s_)
                let n1
                let n2
                switch flipH
                case 0 {
                    n1 := lut_at(lp, ri)
                    n2 := lut_at(lp, add(ri, fx_sign(ie)))
                }
                default {
                    n1 := lut_at(lp, sub(255, ri))
                    n2 := lut_at(lp, sub(sub(255, ri), fx_sign(ie)))
                }
                let delta := fx_mul(ie, fx_abs(fx_sub(n1, n2)))
                switch flipH
                case 0 { v := signextend(7, add(n1, delta)) }
                default { v := signextend(7, sub(n1, delta)) }
                if flipV { v := signextend(7, sub(0, v)) }
            }
            function fx_cos(s_, x) -> v {
                // Trig256.cos: sin(x + (x > 0 ? -(PI + PI/2) : PI/2))
                switch sgt(x, 0)
                case 1 { v := fx_sin(s_, fx_add(x, sub(0, 0x4B65F1FCC))) }
                default { v := fx_sin(s_, fx_add(x, 0x1921FB544)) }
            }
            function ext_1(a, sel, x) -> r {
                // Trig256._ext1: one-word staticcall to the linked Trig256
                // (sel is pre-shifted to the bytes4 position). Reverts bubble
                // up unchanged.
                let p := mload(0x40)
                mstore(p, sel)
                mstore(add(p, 4), x)
                if iszero(staticcall(gas(), a, p, 36, p, 32)) {
                    returndatacopy(0, 0, returndatasize())
                    revert(0, returndatasize())
                }
                // callers sign-extend the int64 library word; fold it here
                r := signextend(7, mload(p))
            }
            function pal_color(s_, idxFx) -> c {
                // _palColor: floor(idx) wrapped into [0, n); empty -> opaque
                // black. Read in place from the program header (count @ byte
                // 10, then n u32 BE ARGB entries @ 11 + 4i): no palette array.
                let prog := add(mload(s_), 0x20)
                let n := byte(0, mload(add(prog, 10)))
                switch n
                case 0 { c := 0xff000000 }
                default {
                    let i := smod(sar(32, idxFx), n)
                    if slt(i, 0) { i := add(i, n) }
                    c := shr(224, mload(add(add(prog, 11), shl(2, i))))
                }
            }
            function color_tint(target, tc) -> c {
                // ColorMath.tint: keep the target alpha, take the tint RGB.
                // A pure-black target (with alpha) passes through.
                c := or(and(target, 0xff000000), and(tc, 0xffffff))
                if and(iszero(and(target, 0xffffff)), iszero(iszero(and(target, 0xff000000)))) { c := target }
            }
            function hsb_byte(v, mAdd) -> b {
                // _hsbByte: floor(constrain(v + mAdd, 0, 1) * 255)
                b := fx_add(v, mAdd)
                if sgt(b, 0x100000000) { b := 0x100000000 }
                if slt(b, 0) { b := 0 }
                b := shr(32, mul(b, 255))
            }
            function hsb2rgb(s_) {
                // _hsb2rgb: p5 colorMode(HSB) default ranges: h wraps mod
                // 360, s and b clamp to [0,100]. Pinned Fix64 sextant walk;
                // alpha 255.
                let sIn, bIn := pop2(s_)
                bIn := fx_clamp(bIn, 0, 0x6400000000) // 100*ONE
                sIn := fx_clamp(sIn, 0, 0x6400000000)
                let h := smod(pop_fx(s_), 0x16800000000) // % 360*ONE (unchecked)
                if slt(h, 0) { h := add(h, 0x16800000000) }
                bIn := fx_div(bIn, 0x6400000000) // vN
                let c := fx_mul(bIn, fx_div(sIn, 0x6400000000)) // chroma
                let m := fx_sub(bIn, c) // mAdd
                h := fx_div(h, 0x3C00000000) // hp in [0, 6)
                let x := fx_mul(c, fx_sub(0x100000000, fx_abs(fx_sub(smod(h, 0x200000000), 0x100000000))))
                let r5 := 0
                let g6 := 0
                let b7 := 0
                switch shr(32, and(h, 0xffffffff00000000)) // sextant
                case 0 {
                    r5 := c
                    g6 := x
                }
                case 1 {
                    r5 := x
                    g6 := c
                }
                case 2 {
                    g6 := c
                    b7 := x
                }
                case 3 {
                    g6 := x
                    b7 := c
                }
                case 4 {
                    r5 := x
                    b7 := c
                }
                default {
                    r5 := c
                    b7 := x
                }
                push_fx(
                    s_,
                    or(or(0xff000000, shl(16, hsb_byte(r5, m))), or(shl(8, hsb_byte(g6, m)), hsb_byte(b7, m)))
                )
            }
            function fy(s_, v) -> r {
                // YFLIP post-transform: device y -> (flipH - y) when armed
                // (State.flipH at 2336; 0 = off)
                r := v
                let h := mload(add(s_, 2336))
                if h { r := fx_sub(h, v) }
            }
            function xf_pt(s_, x, y, dst) {
                // _apply into a contiguous (x, y) slot pair
                mstore(
                    dst,
                    fx_add(fx_add(fx_mul(mload(add(s_, 1024)), x), fx_mul(mload(add(s_, 1088)), y)), mload(add(s_, 1152)))
                )
                let dy :=
                    fx_add(fx_add(fx_mul(mload(add(s_, 1056)), x), fx_mul(mload(add(s_, 1120)), y)), mload(add(s_, 1184)))
                mstore(add(dst, 0x20), fy(s_, dy))
            }
            function clip_rect(s_, m) {
                // CLIPRECT/CLIPRECTT body: the rect corners (x gX, y gY,
                // w gW, h gH) go through the matrix into the c0..c3 clip
                // quad. clipSet := m, the inclusion-test mode (1 = CLIPRECT,
                // 2 = CLIPRECTT's truncating test). It is the stream's hasClip
                // byte.
                xf_pt(s_, mload(add(s_, 1920)), mload(add(s_, 1952)), add(s_, 1248))
                xf_pt(s_, fx_add(mload(add(s_, 1920)), mload(add(s_, 1984))), mload(add(s_, 1952)), add(s_, 1312))
                xf_pt(
                    s_,
                    fx_add(mload(add(s_, 1920)), mload(add(s_, 1984))),
                    fx_add(mload(add(s_, 1952)), mload(add(s_, 2016))),
                    add(s_, 1376)
                )
                xf_pt(s_, mload(add(s_, 1920)), fx_add(mload(add(s_, 1952)), mload(add(s_, 2016))), add(s_, 1440))
                mstore(add(s_, 992), m)
            }
            function fl32v(x) -> r {
                // FL32 (0xaa): the IEEE binary32 value NEAREST x, ties to
                // EVEN. x is exact in Q31.32, so there is exactly ONE
                // rounding. That makes this float32 rounding, not a
                // double-rounded approximation. Faults on 0 < |x| < 2^-9: the
                // ulp of the result (2^(e-23)) is finer than the 2^-32 of
                // Q31.32, so the answer is not representable. The fault is
                // loud and never rounds twice.
                r := 0
                if iszero(x) { leave }
                let neg := slt(x, 0)
                let a := x
                if neg { a := sub(0, x) }
                // bit length: 2^(bl-1) <= a < 2^bl (a < 2^63; no clz on EVM)
                let bl := 1
                let v := a
                if gt(v, 0xffffffff) { v := shr(32, v) bl := add(bl, 32) }
                if gt(v, 0xffff) { v := shr(16, v) bl := add(bl, 16) }
                if gt(v, 0xff) { v := shr(8, v) bl := add(bl, 8) }
                if gt(v, 0xf) { v := shr(4, v) bl := add(bl, 4) }
                if gt(v, 0x3) { v := shr(2, v) bl := add(bl, 2) }
                if gt(v, 0x1) { bl := add(bl, 1) }
                // value = a / 2^32, so the binade is e = bl - 33 and the ulp
                // in RAW units is 2^(bl-24). e >= -9 <=> bl >= 24.
                if lt(bl, 24) { fail() } // FL32 out of range
                let sh := sub(bl, 24)
                r := a
                if sh {
                    let q := shr(sh, a)
                    let rem := sub(a, shl(sh, q))
                    let half := shl(sub(sh, 1), 1)
                    r := shl(sh, q)
                    // round half to EVEN (a carry to 2^24 is the next binade)
                    if or(gt(rem, half), and(eq(rem, half), and(q, 1))) { r := shl(sh, add(q, 1)) }
                }
                if neg { r := sub(0, r) }
            }
            function xs_step(x) -> r {
                // XorShiftV3.step: xorshift32 (13/17/5), int32 wrap per op
                r := signextend(3, xor(x, shl(13, x)))
                r := signextend(3, xor(r, sar(17, r)))
                r := signextend(3, xor(r, shl(5, r)))
            }
            function h_mix(a, b) -> h {
                // hash(a, b) = fmix32(a ^ imul(b+1, 0x9e3779b1)); a, b as u32.
                // MurmurHash3 finalizer, byte-exact with the reference
                // implementation.
                let m := and(xor(and(a, 0xffffffff), and(mul(and(add(and(b, 0xffffffff), 1), 0xffffffff), 0x9e3779b1), 0xffffffff)), 0xffffffff)
                m := and(mul(xor(m, shr(16, m)), 0x85ebca6b), 0xffffffff)
                m := and(mul(xor(m, shr(13, m)), 0xc2b2ae35), 0xffffffff)
                h := and(xor(m, shr(16, m)), 0xffffffff)
            }
            function rv1_ensure(s_) -> p {
                // _ensureRv1 + RandomV1.buildSeedTable (the .NET-compatible
                // subtractive generator). Flat layout: 56 seed words (index 0
                // never touched), then inext, inextp.
                p := mload(add(s_, 576))
                if iszero(mload(add(s_, 608))) {
                    p := mload(0x40)
                    mstore(0x40, add(p, 0x740)) // 58 words, unzeroed
                    {
                        let subv := mload(add(s_, 384)) // initialSeed
                        if slt(subv, 0) { subv := sub(0, subv) }
                        if gt(subv, 0x7fffffff) { subv := 0x7fffffff } // |MIN| -> MAX
                        let mj := sub(161803398, subv) // MSEED - subtraction
                        mstore(add(p, 0x6e0), mj) // seedArray[55]
                        let mk := 1
                        let ii := 0
                        for { let i := 1 } lt(i, 55) { i := add(i, 1) } {
                            ii := add(ii, 21)
                            if iszero(lt(ii, 55)) { ii := sub(ii, 55) }
                            mstore(add(p, shl(5, ii)), mk)
                            mk := signextend(3, sub(mj, mk))
                            if slt(mk, 0) { mk := add(mk, 0x7fffffff) }
                            mj := mload(add(p, shl(5, ii)))
                        }
                    }
                    for { let k := 1 } lt(k, 5) { k := add(k, 1) } {
                        for { let i := 1 } lt(i, 56) { i := add(i, 1) } {
                            let n := add(i, 30)
                            if iszero(lt(n, 55)) { n := sub(n, 55) }
                            let v :=
                                signextend(3, sub(mload(add(p, shl(5, i))), mload(add(p, shl(5, add(1, n))))))
                            if slt(v, 0) { v := add(v, 0x7fffffff) }
                            mstore(add(p, shl(5, i)), v)
                        }
                    }
                    mstore(add(p, 0x700), 0) // inext
                    mstore(add(p, 0x720), 21) // inextp
                    mstore(add(s_, 576), p)
                    mstore(add(s_, 608), 1)
                }
            }
            function rv1_next(p) -> r {
                // RandomV1.next(): one subtractive draw
                let ni := add(mload(add(p, 0x700)), 1)
                if iszero(lt(ni, 56)) { ni := 1 }
                let np := add(mload(add(p, 0x720)), 1)
                if iszero(lt(np, 56)) { np := 1 }
                r := sub(mload(add(p, shl(5, ni))), mload(add(p, shl(5, np))))
                if eq(r, 0x7fffffff) { r := sub(r, 1) }
                if slt(r, 0) { r := add(r, 0x7fffffff) }
                mstore(add(p, shl(5, ni)), r)
                mstore(add(p, 0x700), ni)
                mstore(add(p, 0x720), np)
            }
            function rv1_sample(s_, range32) -> r {
                // shared next(prng, ..) tail: int32(mul(mul(raw*ONE,
                // INV_MBIG), range*ONE) >> 32). INV_MBIG = pinned raw 2.
                r :=
                    signextend(
                        3,
                        sar(
                            32,
                            fx_mul(
                                fx_mul(shl(32, rv1_next(rv1_ensure(s_))), 2),
                                signextend(7, shl(32, range32))
                            )
                        )
                    )
            }
            function imm8(s_) -> v {
                // _imm8: one code byte at pc (TruncatedImmediate past end)
                let pc_ := mload(add(s_, 192))
                if iszero(lt(pc_, mload(add(s_, 128)))) { fail() } // TruncatedImmediate()
                v := byte(0, mload(add(add(add(mload(s_), 0x20), mload(add(s_, 96))), pc_)))
                mstore(add(s_, 192), add(pc_, 1))
            }
            function imm8v(s_, mask) -> v {
                // u8 selector immediate checked against a vocabulary BITMASK
                // (bit v set = value v valid). An unknown value traps like an
                // unknown opcode. shl saturates past 255, so any v > 7 fails
                // masks under 0x100.
                v := imm8(s_)
                if iszero(and(shl(v, 1), mask)) { fail() } // invalid selector
            }
            function popn(s_, n) -> sc {
                // Pop n operands into transient scratch above the free
                // pointer, parked by DESCENDING index so scratch reads back
                // in push order. No allocating helper may run between the
                // park and the use (grow the out buffer BEFORE this call).
                sc := mload(0x40)
                for { let i := n } i { i := sub(i, 1) } {
                    mstore(add(sc, shl(5, sub(i, 1))), pop_fx(s_))
                }
            }
            function ext_2(a, sel, x, y) -> r {
                // two-arg variant (atan2), mirroring the extAtan2 stub
                let p := mload(0x40)
                mstore(p, sel)
                mstore(add(p, 4), x)
                mstore(add(p, 36), y)
                if iszero(staticcall(gas(), a, p, 68, p, 32)) {
                    returndatacopy(0, 0, returndatasize())
                    revert(0, returndatasize())
                }
                r := signextend(7, mload(p)) // caller sign-extends the int64 word, so fold it here
            }
            function bz_x(rec, t) -> v {
                // Bezier.xFunc: literal port. The mul nesting of the t2 term
                // DIFFERS from bz_y (a quirk of the reference; Fix64.mul
                // truncates). rec: 8 coeff words ax ay bx by cx cy dx dy, then
                // 101 arc words.
                let t0 := fx_sub(0x100000000, t)
                v :=
                    fx_add(
                        fx_add(
                            fx_mul(t0, fx_mul(t0, fx_mul(t0, mload(rec)))),
                            fx_mul(fx_mul(fx_mul(fx_mul(t0, t0), 0x300000000), t), mload(add(rec, 0x40)))
                        ),
                        fx_add(
                            fx_mul(0x300000000, fx_mul(t0, fx_mul(fx_mul(t, t), mload(add(rec, 0x80))))),
                            fx_mul(t, fx_mul(t, fx_mul(t, mload(add(rec, 0xc0)))))
                        )
                    )
            }
            function bz_y(rec, t) -> v {
                // Bezier.yFunc: literal port (t2 nesting differs from bz_x)
                let t0 := fx_sub(0x100000000, t)
                v :=
                    fx_add(
                        fx_add(
                            fx_mul(t0, fx_mul(t0, fx_mul(t0, mload(add(rec, 0x20))))),
                            fx_mul(t0, fx_mul(t0, fx_mul(0x300000000, fx_mul(t, mload(add(rec, 0x60))))))
                        ),
                        fx_add(
                            fx_mul(0x300000000, fx_mul(t0, fx_mul(fx_mul(t, t), mload(add(rec, 0xa0))))),
                            fx_mul(t, fx_mul(t, fx_mul(t, mload(add(rec, 0xe0)))))
                        )
                    )
            }
            function bz_rec(s_) -> rec, t {
                // shared BEZMX/BEZMY prologue: pop slot, then t, and fetch
                // the bank record (same slot-range and unset faults)
                let slot := pop_int(s_)
                t := pop_fx(s_)
                if or(slt(slot, 0), sgt(slot, 63)) { fail() } // BezierSlotOutOfRange()
                if mload(add(s_, 672)) { rec := mload(add(mload(add(s_, 640)), shl(5, slot))) }
                if iszero(rec) { fail() } // BezierSlotNotSet()
            }
            function bz_build(rec) {
                // the 100-step arc-length integration. Segment length:
                // sqrt(dx^2 + dy^2) (Fix64 route; the sqrt keeps the
                // negative-input revert of the reference).
                let n := bz_x(rec, 0)
                let r := bz_y(rec, 0)
                let e := 0
                for { let a := 1 } iszero(gt(a, 100)) { a := add(a, 1) } {
                    let z := fx_mul(42949672, shl(32, a)) // STEP * a*ONE
                    let c := bz_x(rec, z)
                    let u := bz_y(rec, z)
                    e := fx_add(e, fx_sqrt(fx_add(fx_mul(fx_sub(n, c), fx_sub(n, c)), fx_mul(fx_sub(r, u), fx_sub(r, u)))))
                    mstore(add(add(rec, 0x100), shl(5, a)), e)
                    n := c
                    r := u
                }
            }
            function bz_map(rec, t) -> v {
                // Bezier.map: arc length -> curve parameter (binary search
                // over the 101 cumulative entries + linear interpolation)
                let arcp := add(rec, 0x100)
                let h := fx_mul(t, mload(add(arcp, 0xc80))) // arc[100]
                let n := 0
                let lo := 0
                let hi := 100
                for {} lt(lo, hi) {} {
                    n := add(lo, shr(1, sub(hi, lo)))
                    switch slt(mload(add(arcp, shl(5, n))), h)
                    case 1 { lo := add(n, 1) }
                    default { hi := n }
                }
                if and(sgt(mload(add(arcp, shl(5, n))), h), gt(n, 0)) { n := sub(n, 1) }
                let rr := mload(add(arcp, shl(5, n)))
                switch eq(rr, h)
                case 1 { v := fx_div(shl(32, n), 0x6400000000) } // /(100*ONE)
                default {
                    v :=
                        fx_div(
                            fx_add(
                                shl(32, n),
                                fx_div(fx_sub(h, rr), fx_sub(mload(add(add(arcp, 0x20), shl(5, n))), rr))
                            ),
                            0x6400000000
                        )
                }
            }
            function ensure_path(s_, need) {
                // grow s.path so pathLen + need + 32 fits (unzeroed; only
                // bytes below pathLen are ever read)
                let buf := mload(add(s_, 1568))
                let want := add(add(mload(add(s_, 1600)), need), 32)
                if gt(want, mload(buf)) {
                    let cap := shl(1, mload(buf))
                    for {} gt(want, cap) {} { cap := shl(1, cap) }
                    let nb := mload(0x40)
                    mstore(0x40, add(nb, add(0x20, cap)))
                    mstore(nb, cap)
                    let len := mload(add(s_, 1600))
                    for { let i := 0 } lt(i, len) { i := add(i, 0x20) } {
                        mstore(add(add(nb, 0x20), i), mload(add(add(buf, 0x20), i)))
                    }
                    mstore(add(s_, 1568), nb)
                }
            }
            function p8(s_, v) {
                ensure_path(s_, 1)
                let len := mload(add(s_, 1600))
                mstore8(add(add(mload(add(s_, 1568)), 0x20), len), v)
                mstore(add(s_, 1600), add(len, 1))
            }
            function p64(s_, v) {
                ensure_path(s_, 8)
                let len := mload(add(s_, 1600))
                mstore(
                    add(add(mload(add(s_, 1568)), 0x20), len),
                    shl(192, and(v, 0xffffffffffffffff))
                )
                mstore(add(s_, 1600), add(len, 8))
            }
            function vert_check(s_) {
                let n := mload(add(s_, 1632))
                if iszero(lt(n, 65535)) { fail() } // PathVertexLimitExceeded()
                mstore(add(s_, 1632), add(n, 1))
            }
            function xf_cur(s_, x, y) {
                // apply the current matrix; stage device coords in curX/curY
                // (same transform as xf_pt; curX/curY are a contiguous pair)
                xf_pt(s_, x, y, add(s_, 1696))
            }
            function cur64(s_) {
                // append the staged device point (curX, curY @1696/1728) to
                // the path: the shared p64 pair of every vertex emitter
                p64(s_, mload(add(s_, 1696)))
                p64(s_, mload(add(s_, 1728)))
            }
            function xfp64(s_, x, y) {
                // transform (x, y) through the CTM into curX/curY, then
                // append the pair: the cubic/arc control-point emit step
                xf_cur(s_, x, y)
                cur64(s_)
            }
            function emit_cur(s_, cmd8) {
                // append (cmd8, curX, curY) to the path
                vert_check(s_)
                p8(s_, cmd8)
                cur64(s_)
            }
            function seg_move(s_, x, y) {
                xf_cur(s_, x, y)
                emit_cur(s_, 0x01)
                mstore(add(s_, 1664), 1)
            }
            function seg_line(s_, x, y) {
                xf_cur(s_, x, y)
                switch mload(add(s_, 1664))
                case 0 {
                    emit_cur(s_, 0x01)
                    mstore(add(s_, 1664), 1)
                }
                default { emit_cur(s_, 0x02) }
            }
            function close_vert(s_) {
                vert_check(s_)
                p8(s_, 0x04)
            }
            function seg_cubic(s_, c1x, c1y, c2x, c2y, x, y) {
                // _segCubic: fall back to a move when there is no current
                // point. Otherwise emit (0x03, c1, c2, end), each pair staged
                // through curX/curY so the endpoint becomes the current point.
                switch mload(add(s_, 1664))
                case 0 { seg_move(s_, x, y) }
                default {
                    vert_check(s_)
                    p8(s_, 0x03)
                    xfp64(s_, c1x, c1y)
                    xfp64(s_, c2x, c2y)
                    xfp64(s_, x, y)
                }
            }
            function ellipse_path_g(s_) {
                // _ellipsePath: an axis-aligned (user space) ellipse as four
                // KAPPA cubic arcs. Center in gX/gY, radii in gW/gH. gC1 and
                // gC2 become kx and ky (KAPPA = 2372049776, pinned by spec).
                mstore(add(s_, 2048), fx_mul(2372049776, mload(add(s_, 1984))))
                mstore(add(s_, 2080), fx_mul(2372049776, mload(add(s_, 2016))))
                seg_move(s_, fx_add(mload(add(s_, 1920)), mload(add(s_, 1984))), mload(add(s_, 1952)))
                seg_cubic(
                    s_,
                    fx_add(mload(add(s_, 1920)), mload(add(s_, 1984))),
                    fx_add(mload(add(s_, 1952)), mload(add(s_, 2080))),
                    fx_add(mload(add(s_, 1920)), mload(add(s_, 2048))),
                    fx_add(mload(add(s_, 1952)), mload(add(s_, 2016))),
                    mload(add(s_, 1920)),
                    fx_add(mload(add(s_, 1952)), mload(add(s_, 2016)))
                )
                seg_cubic(
                    s_,
                    fx_sub(mload(add(s_, 1920)), mload(add(s_, 2048))),
                    fx_add(mload(add(s_, 1952)), mload(add(s_, 2016))),
                    fx_sub(mload(add(s_, 1920)), mload(add(s_, 1984))),
                    fx_add(mload(add(s_, 1952)), mload(add(s_, 2080))),
                    fx_sub(mload(add(s_, 1920)), mload(add(s_, 1984))),
                    mload(add(s_, 1952))
                )
                seg_cubic(
                    s_,
                    fx_sub(mload(add(s_, 1920)), mload(add(s_, 1984))),
                    fx_sub(mload(add(s_, 1952)), mload(add(s_, 2080))),
                    fx_sub(mload(add(s_, 1920)), mload(add(s_, 2048))),
                    fx_sub(mload(add(s_, 1952)), mload(add(s_, 2016))),
                    mload(add(s_, 1920)),
                    fx_sub(mload(add(s_, 1952)), mload(add(s_, 2016)))
                )
                seg_cubic(
                    s_,
                    fx_add(mload(add(s_, 1920)), mload(add(s_, 2048))),
                    fx_sub(mload(add(s_, 1952)), mload(add(s_, 2016))),
                    fx_add(mload(add(s_, 1920)), mload(add(s_, 1984))),
                    fx_sub(mload(add(s_, 1952)), mload(add(s_, 2080))),
                    fx_add(mload(add(s_, 1920)), mload(add(s_, 1984))),
                    mload(add(s_, 1952))
                )
                close_vert(s_)
            }
            function glyph_seg(s_, cmd, gx, gy) {
                // shared per-record tail: optional GLYPHXF then dispatch
                if mload(add(s_, 1792)) {
                    let em := mload(add(s_, 1824))
                    let gxt := fx_add(fx_mul(gx, em), mload(add(s_, 1856)))
                    gy := fx_add(fx_sub(0, fx_mul(gy, em)), mload(add(s_, 1888)))
                    gx := gxt
                }
                switch cmd
                case 1 { seg_move(s_, gx, gy) }
                default { seg_line(s_, gx, gy) }
            }
            function pop_fx(s_) -> v {
                // _pop: raw Fix64 value (StackUnderflow on empty)
                let sp := mload(add(s_, 288))
                if iszero(sp) { fail() }
                sp := sub(sp, 1)
                mstore(add(s_, 288), sp)
                v := mload(add(add(mload(add(s_, 256)), 0x20), shl(5, sp)))
            }
            function pop_int(s_) -> v {
                // _popInt: pop then >> 32
                v := sar(32, pop_fx(s_))
            }
            function pop2(s_) -> a, b {
                // two pops in one body: b is the top of the stack, a the
                // value beneath it. `let a, b := pop2()` replaces
                // `let b := pop_fx(); let a := pop_fx()`. Underflow faults the
                // same way (same bare selector).
                let sp := mload(add(s_, 288))
                if lt(sp, 2) { fail() }
                sp := sub(sp, 2)
                mstore(add(s_, 288), sp)
                let base := add(add(mload(add(s_, 256)), 0x20), shl(5, sp))
                a := mload(base)
                b := mload(add(base, 0x20))
            }
            function pop4g(s_) {
                // pop 4 into the gX..gH scratch quad, top of stack first
                // (gH @2016 down to gX @1920): the shared park sequence of
                // ELLIPSE/RECT/ARC/GRADIENT/CLIPRECT
                for { let o := 2016 } iszero(lt(o, 1920)) { o := sub(o, 0x20) } {
                    mstore(add(s_, o), pop_fx(s_))
                }
            }
            function push_fx(s_, v) {
                // _push (StackOverflow at 256 slots)
                let sp := mload(add(s_, 288))
                if iszero(lt(sp, 256)) { fail() } // StackOverflow()
                mstore(add(add(mload(add(s_, 256)), 0x20), shl(5, sp)), v)
                mstore(add(s_, 288), add(sp, 1))
            }
            function ensure_out(s_, need) {
                // grow s.out so outLen + need + 32 fits (unzeroed; only
                // bytes below outLen are ever read)
                let buf := mload(add(s_, 2144))
                let want := add(add(mload(add(s_, 2176)), need), 32)
                if gt(want, mload(buf)) {
                    let cap := shl(1, mload(buf))
                    for {} gt(want, cap) {} { cap := shl(1, cap) }
                    let nb := mload(0x40)
                    mstore(0x40, add(nb, add(0x20, cap)))
                    mstore(nb, cap)
                    let len := mload(add(s_, 2176))
                    for { let i := 0 } lt(i, len) { i := add(i, 0x20) } {
                        mstore(add(add(nb, 0x20), i), mload(add(add(buf, 0x20), i)))
                    }
                    mstore(add(s_, 2144), nb)
                }
            }
            function w8(s_, v) {
                ensure_out(s_, 1)
                let len := mload(add(s_, 2176))
                mstore8(add(add(mload(add(s_, 2144)), 0x20), len), v)
                mstore(add(s_, 2176), add(len, 1))
            }
            function w16(s_, v) {
                ensure_out(s_, 2)
                let len := mload(add(s_, 2176))
                mstore(add(add(mload(add(s_, 2144)), 0x20), len), shl(240, and(v, 0xffff)))
                mstore(add(s_, 2176), add(len, 2))
            }
            function w32(s_, v) {
                ensure_out(s_, 4)
                let len := mload(add(s_, 2176))
                mstore(add(add(mload(add(s_, 2144)), 0x20), len), shl(224, and(v, 0xffffffff)))
                mstore(add(s_, 2176), add(len, 4))
            }
            function w64(s_, v) {
                ensure_out(s_, 8)
                let len := mload(add(s_, 2176))
                mstore(
                    add(add(mload(add(s_, 2144)), 0x20), len),
                    shl(192, and(v, 0xffffffffffffffff))
                )
                mstore(add(s_, 2176), add(len, 8))
            }
            function flush_path(s_) {
                // _flushPath: append the path bytes to the output. The path
                // is base ++ tail. The base is the resumed client blob,
                // copied in place from pathBaseOff. The tail is the buffer of
                // this chunk.
                let plen := mload(add(s_, 1600))
                let blen := and(mload(add(s_, 512)), 0xffffffff)
                ensure_out(s_, add(plen, blen))
                let off := mload(add(s_, 2176))
                let dp := add(add(mload(add(s_, 2144)), 0x20), off)
                calldatacopy(dp, mload(add(s_, 2688)), blen) // blen 0 = no-op
                dp := add(dp, blen)
                off := add(off, blen)
                let srcp := add(mload(add(s_, 1568)), 0x20)
                for { let i := 0 } lt(i, plen) { i := add(i, 0x20) } {
                    mstore(add(dp, i), mload(add(srcp, i)))
                }
                mstore(add(s_, 2176), add(off, plen))
            }
            function path_reset(s_) {
                // _beginPath: zero pathLen, segCount, and hasCurrent (three
                // contiguous State words, one calldatacopy zero-fill) AND
                // discard the resumed base path (the Runner's pathDelta
                // reports it)
                calldatacopy(add(s_, 1600), calldatasize(), 96)
                mstore(add(s_, 512), 0)
            }
            function det_scale(s_, v) -> r {
                // v * sqrt(|ma*md - mb*mc|): the user-to-device scale shared
                // by stroke widths, STAMP sizes, and the GRADIENT line width
                // (v = ONE). DEVICE_STROKE pieces (State.deviceStroke, 2368)
                // keep v literal, as the deviceStrokeWidth rule of the
                // reference does.
                r := v
                if mload(add(s_, 2368)) { leave }
                r := fx_mul(
                    v,
                    fx_sqrt(
                        fx_abs(
                            fx_sub(
                                fx_mul(mload(add(s_, 1024)), mload(add(s_, 1120))),
                                fx_mul(mload(add(s_, 1056)), mload(add(s_, 1088)))
                            )
                        )
                    )
                )
            }
            function stamp_emit(s_) {
                // STAMP tail (own frame; runs only when a fill is set):
                // 0x04 | u32 fill | u8 tip | u8 blend | i64 dcx | i64 dcy
                // | i64 dsize | i64 dirx | i64 diry | i64 pressure.
                // The 0x67 case parks the operands: cx gX, cy gY, angle gC1,
                // size gC2, pressure gLineWidth. The center goes through the
                // CTM (curX/curY stay untouched). dsize = size * sqrt(|det|).
                // The orientation resolves to (cos, sin) HERE with the LUT
                // trig of SIN and COS, so the rasterizer needs no trig.
                w8(s_, 0x04)
                w32(s_, mload(add(s_, 832)))
                w16(s_, or(shl(8, mload(add(s_, 2208))), mload(add(s_, 2240)))) // tip | blend
                xf_pt(s_, mload(add(s_, 1920)), mload(add(s_, 1952)), add(s_, 1920))
                w64(s_, mload(add(s_, 1920)))
                w64(s_, mload(add(s_, 1952)))
                w64(s_, det_scale(s_, mload(add(s_, 2080))))
                w64(s_, fx_cos(s_, mload(add(s_, 2048))))
                w64(s_, fx_sin(s_, mload(add(s_, 2048))))
                w64(s_, mload(add(s_, 2112)))
            }
            function paint_flags(s_, segs, hasFill) {
                // shared paint-record tail of do_paint and gradient_line:
                // the flags byte (bit0 evenOdd, bit1 cap/join follow, bit2
                // blend follows, bit3 GFILL gradient follows, bit4 FFILL
                // field follows), the optional cap, join, and blend bytes,
                // the gradient OR field extension, the clip marker (+ quad),
                // and u16 segCount.
                // hasFill 1 = this paint fills with the STYLE fill (the
                // gradOk rule of the reference): a gradient (gradMeta bit0)
                // OR a field (bit2) rides it. The stroke-only scanlines of
                // gradient_line and the stroke-colored dot of POINT pass 0.
                let meta := mload(add(s_, 2464))
                let hasG := and(hasFill, and(meta, 1))
                let hasF_ := and(hasFill, and(shr(2, meta), 1))
                let cj := iszero(iszero(or(mload(add(s_, 2272)), mload(add(s_, 2304)))))
                let bl := iszero(iszero(mload(add(s_, 2240))))
                w8(s_, or(or(or(or(mload(add(s_, 960)), shl(1, cj)), shl(2, bl)), shl(3, hasG)), shl(4, hasF_)))
                if cj {
                    w8(s_, mload(add(s_, 2272))) // cap
                    w8(s_, mload(add(s_, 2304))) // join
                }
                if bl {
                    w8(s_, mload(add(s_, 2240))) // blend mode
                }
                // gradient (bit0) and field (bit2) are mutually exclusive, so
                // at most one fires: one emit path (fill_ext)
                if or(hasG, hasF_) { fill_ext(s_, hasF_) }
                let clip := mload(add(s_, 992))
                w8(s_, clip)
                if clip {
                    // clip quad c0x..c3y (8 words at 1248..1472)
                    for { let o := 1248 } lt(o, 1504) { o := add(o, 0x20) } {
                        w64(s_, mload(add(s_, o)))
                    }
                }
                w16(s_, segs)
            }
            function fill_ext(s_, isField) {
                // the paint-record fill extension: the GFILL gradient (flags
                // bit3) OR the FFILL field (bit4), in one frame. Both share
                // the meta/geom load and the u8 kind byte.
                //  GRADIENT: u8 kind | i64 ax ay bx by | u8 n |
                //   n x (u16 off | u32 argb). Anchors resolve HERE, at paint
                //   time, through the CTM (+ YFLIP via pt64). The radial
                //   radius takes det_scale (literal under DEVICE_STROKE,
                //   by = 0). The stops copy RAW from the data segment (GFILL
                //   validated them).
                //  FIELD (meta bit2): u8 kind | i64 scale | i64 warp |
                //   u32 colorA | u32 colorB | i32 run seed (29 B). NOTHING
                //   is transformed (absolute device-pixel space). The seed is
                //   the RUN seed (initialSeed @384), captured HERE at paint
                //   time, so rasterizers stay seed-blind.
                let meta := mload(add(s_, 2464))
                let geom := mload(add(s_, 2496))
                w8(s_, and(shr(1, meta), 1)) // kind (shared)
                if isField {
                    // w64/w32 mask internally; no signextend/and guards needed
                    w64(s_, shr(192, geom)) // scale
                    w64(s_, shr(128, geom)) // warp
                    w32(s_, shr(8, meta)) // colorA
                    w32(s_, shr(40, meta)) // colorB
                    w32(s_, mload(add(s_, 384))) // i32 run seed
                    leave
                }
                pt64(s_, signextend(7, shr(192, geom)), signextend(7, shr(128, geom))) // ax ay
                switch and(shr(1, meta), 1)
                case 1 {
                    w64(s_, det_scale(s_, signextend(7, shr(64, geom)))) // bx = device radius
                    w64(s_, 0) // by = 0 (reserved)
                }
                default { pt64(s_, signextend(7, shr(64, geom)), signextend(7, geom)) } // bx by
                let n := and(shr(8, meta), 0xff)
                w8(s_, n)
                let len := mul(n, 6)
                ensure_out(s_, len)
                let o := mload(add(s_, 2176))
                let dp := add(add(mload(add(s_, 2144)), 0x20), o)
                let srcp := add(add(add(mload(s_), 0x20), mload(add(s_, 32))), shr(16, meta))
                // word-wise copy. The overhang of up to 31 bytes stays inside
                // the ensure_out slack and the next write overwrites it
                for { let i := 0 } lt(i, len) { i := add(i, 0x20) } {
                    mstore(add(dp, i), mload(add(srcp, i)))
                }
                mstore(add(s_, 2176), add(o, len))
            }
            function gfill_run(s_, kind) {
                // GFILL 0xa7 body (kind already checked against the
                // vocabulary). TRAP ORDER: (1) kind at dispatch, (2) the six
                // pops, (3) n outside [2,16], (4) radial y1 != 0, (5) data
                // bounds (the DR* rule), (6) decreasing offsets during the
                // stop scan. On success: fill = the color of the FIRST stop
                // (hasFill stays 1), and gradMeta and gradGeom are set.
                let dOff
                let n
                {
                    let a, b := pop2(s_) // b = n (top of stack), a = dataOff
                    dOff := sar(32, a)
                    n := sar(32, b)
                }
                let x1, y1 := pop2(s_)
                let x0, y0 := pop2(s_)
                if or(slt(n, 2), sgt(n, 16)) { fail() } // GfillInvalidStopCount()
                if and(eq(kind, 1), iszero(iszero(y1))) { fail() } // GfillRadialY1()
                if or(slt(dOff, 0), sgt(add(dOff, mul(n, 6)), mload(add(s_, 64)))) { fail() } // DataReadOutOfBounds()
                let tbl := add(add(add(mload(s_), 0x20), mload(add(s_, 32))), dOff)
                {
                    // non-decreasing u16 offsets (equal adjacent offsets make
                    // a hard step: legal, and it resolves to the LATER stop)
                    let prev := 0
                    for { let i := 0 } lt(i, n) { i := add(i, 1) } {
                        let so := shr(240, mload(add(tbl, mul(i, 6))))
                        if lt(so, prev) { fail() } // GfillDecreasingOffsets()
                        prev := so
                    }
                }
                mstore(add(s_, 832), shr(224, mload(add(tbl, 2)))) // fill = first stop's argb
                mstore(add(s_, 864), 1)
                mstore(add(s_, 2464), or(or(1, shl(1, kind)), or(shl(8, n), shl(16, dOff))))
                mstore(
                    add(s_, 2496),
                    or(
                        or(shl(192, and(x0, 0xffffffffffffffff)), shl(128, and(y0, 0xffffffffffffffff))),
                        or(shl(64, and(x1, 0xffffffffffffffff)), and(y1, 0xffffffffffffffff))
                    )
                )
                // (the first _save allocates the shared save bank, for EIP-170)
            }
            function ffill_run(s_, kind) {
                // FFILL 0xad body (kind already checked against the
                // vocabulary). The kind selects the NOISE FAMILY (0 =
                // NoiseV1, 1 = GradNoise). BOTH are domain-warped noise
                // grounds, so both pop colorB, colorA, warp, scale. fill =
                // colorA. The field state layout is in the State comment.
                let cA, cB
                {
                    let a, b := pop2(s_) // b = colorB (top), a = colorA
                    cA := and(a, 0xffffffff)
                    cB := and(b, 0xffffffff)
                }
                let scale, warp := pop2(s_) // warp = top, scale = deeper
                mstore(add(s_, 832), cA) // fill = colorA
                mstore(add(s_, 864), 1)
                // gradMeta: bit1 kind | bit2 FIELD-active | colorA<<8 |
                // colorB<<40. A FIELD deliberately leaves bit0 CLEAR. Bit0
                // stays "gradient armed", so a field-free build and this one
                // emit the same gradient records.
                mstore(add(s_, 2464), or(or(shl(1, kind), 4), or(shl(8, cA), shl(40, cB))))
                // gradGeom: i64 scale (bits 192..255) | i64 warp (bits
                // 128..191). shl(192, scale) discards bits >= 64, so scale
                // needs no mask. Warp needs its mask: without it, warp bits
                // 64..127 would collide with bits 192..255 of scale.
                mstore(
                    add(s_, 2496),
                    or(shl(192, scale), shl(128, and(warp, 0xffffffffffffffff)))
                )
                // (the first _save allocates the shared save bank, for EIP-170)
            }
            function do_paint(s_, hasF, fillC, hasS, strokeC) {
                // _doPaint: write the paint head and flush the path if the
                // path is non-empty and either style is set. Always clear it.
                let segs := mload(add(s_, 1632))
                // every reset goes through path_reset (the zero-fill of the
                // path words plus the base-path discard)
                if and(iszero(iszero(segs)), or(hasF, hasS)) {
                    w8(s_, 0x01)
                    w8(s_, hasF)
                    w32(s_, mul(hasF, fillC))
                    w8(s_, hasS)
                    w32(s_, mul(hasS, strokeC))
                    // _deviceStrokeWidth: strokeW through the shared scale
                    w64(s_, det_scale(s_, mload(add(s_, 1216))))
                    // flags, optional cap/join/blend, gradient, clip, and
                    // segCount. The defaults (Butt/Miter, source-over, solid
                    // fill) omit the optional bytes. hasF = this paint fills
                    // with the style fill. POINT masks gradMeta around its
                    // stroke-colored dot.
                    paint_flags(s_, segs, hasF)
                    flush_path(s_)
                }
                path_reset(s_)
            }
            function lerp_ch(cs, ct, k, bk, bidx) -> ch {
                ch :=
                    sdiv(
                        fx_add(fx_mul(shl(32, byte(bidx, cs)), bk), fx_mul(shl(32, byte(bidx, ct)), k)),
                        0x100000000
                    )
            }
            function color_lerp(cs, ct, k) -> c {
                // ColorMath.lerp for any k (CLERP is unconstrained):
                // per-channel Fix64 lerp with truncating div, then the
                // int32-wrap channel pack of the reference. Each term keeps
                // its low 32 bits before the or.
                let bk := fx_sub(0x100000000, k)
                c :=
                    or(
                        or(
                            and(shl(24, lerp_ch(cs, ct, k, bk, 28)), 0xffffffff),
                            and(shl(16, lerp_ch(cs, ct, k, bk, 29)), 0xffffffff)
                        ),
                        or(
                            and(shl(8, lerp_ch(cs, ct, k, bk, 30)), 0xffffffff),
                            and(lerp_ch(cs, ct, k, bk, 31), 0xffffffff)
                        )
                    )
            }
            function lerp23(s_, q, cur) -> v {
                // cur + (q - cur) * TWO_THIRDS (s.twoThirds @1760, pinned):
                // the control-point lerp of QUADTO from quadratic to cubic
                v := fx_add(cur, fx_mul(fx_sub(q, cur), mload(add(s_, 1760))))
            }
            function pt64(s_, x, i) {
                // one (x, i) user-space point through the CTM (+ YFLIP), the
                // same math as xf_pt, written straight to out. The GRADIENT
                // scanline endpoints and the GFILL anchors share it.
                w64(
                    s_,
                    fx_add(fx_add(fx_mul(mload(add(s_, 1024)), x), fx_mul(mload(add(s_, 1088)), i)), mload(add(s_, 1152)))
                )
                let dy :=
                    fx_add(fx_add(fx_mul(mload(add(s_, 1056)), x), fx_mul(mload(add(s_, 1120)), i)), mload(add(s_, 1184)))
                w64(s_, fy(s_, dy))
            }
            function grad_pt(s_, cmd8, x, i) {
                // one gradient seg record: cmd byte + the transformed point
                w8(s_, cmd8)
                pt64(s_, x, i)
            }
            function gradient_line(s_, i) {
                // _gradientLine: one scan line: a stroke-only paint head and
                // an M/L seg pair written straight to out (path untouched)
                let t := 0
                {
                    let gh := mload(add(s_, 2016))
                    if gh {
                        t := fx_div(fx_sub(i, mload(add(s_, 1952))), gh)
                        if sgt(t, 0x100000000) { t := 0x100000000 }
                        if slt(t, 0) { t := 0 }
                    }
                }
                w8(s_, 0x01)
                w8(s_, 0)
                w32(s_, 0)
                w8(s_, 1)
                w32(s_, color_lerp(mload(add(s_, 2048)), mload(add(s_, 2080)), t))
                w64(s_, mload(add(s_, 2112)))
                // flags, optional cap/join, blend, clip, and segCount(2),
                // exactly as in do_paint: the shared paint_flags tail. The
                // scanlines are STROKE-only paints, so a GFILL or FFILL never
                // rides them (hasFill = 0).
                paint_flags(s_, 2, 0)
                grad_pt(s_, 0x01, mload(add(s_, 1920)), i)
                grad_pt(s_, 0x02, fx_add(mload(add(s_, 1920)), mload(add(s_, 1984))), i)
            }
            function glyphc_run(s_) {
                // GLYPHC record loop (ptr gX, remaining gY, data-end gW, cw
                // gH, shift gC1, parked by the 0xa0 case), own frame
                for {} mload(add(s_, 1952)) {} {
                    mstore(add(s_, 1952), sub(mload(add(s_, 1952)), 1))
                    pop(glyph_steps(s_))
                    if iszero(lt(mload(add(s_, 1920)), mload(add(s_, 1984)))) { fail() }
                    let w := mload(mload(add(s_, 1920)))
                    switch byte(0, w)
                    case 4 {
                        mstore(add(s_, 1920), add(mload(add(s_, 1920)), 1))
                        if mload(add(s_, 1632)) { close_vert(s_) }
                    }
                    default {
                        let cw := mload(add(s_, 2016))
                        if gt(add(mload(add(s_, 1920)), add(1, shl(1, cw))), mload(add(s_, 1984))) {
                            fail()
                        }
                        if iszero(or(eq(byte(0, w), 1), eq(byte(0, w), 2))) { fail() }
                        mstore(add(s_, 1920), add(mload(add(s_, 1920)), add(1, shl(1, cw))))
                        let shift := mload(add(s_, 2048))
                        glyph_seg(
                            s_,
                            byte(0, w),
                            signextend(7, shl(shift, signextend(sub(cw, 1), shr(sub(248, shl(3, cw)), w)))),
                            signextend(7, shl(shift, signextend(sub(cw, 1), shr(sub(248, shl(4, cw)), w))))
                        )
                    }
                }
                mstore(add(s_, 1792), 0)
            }
            function poly_build(s_) {
                // POLYGON vertex loop (cx gX, cy gY, r gW, rot gH,
                // stepA gC1, n gC2), in its own frame
                for { let i := 0 } lt(i, mload(add(s_, 2080))) { i := add(i, 1) } {
                    let t := fx_add(mload(add(s_, 2016)), fx_mul(shl(32, i), mload(add(s_, 2048))))
                    let px := fx_add(fx_mul(fx_cos(s_, t), mload(add(s_, 1984))), mload(add(s_, 1920)))
                    let py := fx_add(fx_mul(fx_sin(s_, t), mload(add(s_, 1984))), mload(add(s_, 1952)))
                    switch i
                    case 0 { seg_move(s_, px, py) }
                    default { seg_line(s_, px, py) }
                }
            }
            function arc_build(s_, sweep) {
                // the non-degenerate ARC body (sweep != 0). The parked mode is
                // popped off the VM operand stack here.
                for {} iszero(sgt(sweep, 0)) {} { sweep := fx_add(sweep, 0x6487ED511) }
                if sgt(sweep, 0x6487ED511) { sweep := 0x6487ED511 }
                let nsegs := add(shr(32, and(fx_div(sweep, 0x1921FB544), 0xffffffff00000000)), 1)
                if gt(nsegs, 5) { nsegs := 5 }
                mstore(add(s_, 2080), fx_div(sweep, shl(32, nsegs))) // seg
                {
                    let seg4 := fx_div(mload(add(s_, 2080)), 0x400000000)
                    let segCos := fx_cos(s_, seg4)
                    switch segCos
                    case 0 { mstore(add(s_, 2048), 0) }
                    default {
                        mstore(
                            add(s_, 2048),
                            fx_mul(fx_div(0x400000000, 0x300000000), fx_div(fx_sin(s_, seg4), segCos))
                        )
                    }
                }
                path_reset(s_)
                let c0 := fx_cos(s_, mload(add(s_, 2112)))
                let s0 := fx_sin(s_, mload(add(s_, 2112)))
                seg_move(
                    s_,
                    fx_add(mload(add(s_, 1920)), fx_mul(mload(add(s_, 1984)), c0)),
                    fx_add(mload(add(s_, 1952)), fx_mul(mload(add(s_, 2016)), s0))
                )
                for {} nsegs { nsegs := sub(nsegs, 1) } {
                    mstore(add(s_, 2112), fx_add(mload(add(s_, 2112)), mload(add(s_, 2080))))
                    vert_check(s_)
                    p8(s_, 0x03)
                    // the c1 pair uses c0/s0, which then die. c1/s1 reuse their
                    // registers (cos/sin are pure; stream order is unchanged)
                    xfp64(
                        s_,
                        fx_add(mload(add(s_, 1920)), fx_mul(mload(add(s_, 1984)), fx_sub(c0, fx_mul(mload(add(s_, 2048)), s0)))),
                        fx_add(mload(add(s_, 1952)), fx_mul(mload(add(s_, 2016)), fx_add(s0, fx_mul(mload(add(s_, 2048)), c0))))
                    )
                    c0 := fx_cos(s_, mload(add(s_, 2112)))
                    s0 := fx_sin(s_, mload(add(s_, 2112)))
                    xfp64(
                        s_,
                        fx_add(mload(add(s_, 1920)), fx_mul(mload(add(s_, 1984)), fx_add(c0, fx_mul(mload(add(s_, 2048)), s0)))),
                        fx_add(mload(add(s_, 1952)), fx_mul(mload(add(s_, 2016)), fx_sub(s0, fx_mul(mload(add(s_, 2048)), c0))))
                    )
                    xfp64(
                        s_,
                        fx_add(mload(add(s_, 1920)), fx_mul(mload(add(s_, 1984)), c0)),
                        fx_add(mload(add(s_, 1952)), fx_mul(mload(add(s_, 2016)), s0))
                    )
                }
                {
                    let m := pop_fx(s_) // the parked mode
                    if eq(m, 2) { seg_line(s_, mload(add(s_, 1920)), mload(add(s_, 1952))) }
                    if m { close_vert(s_) }
                }
                do_paint(s_, mload(add(s_, 864)), mload(add(s_, 832)), mload(add(s_, 928)), mload(add(s_, 896)))
            }
            // NoiseV1 (LGPL-2.1-only, p5.js-derived) is not transcribed into
            // this file. Its expression is in the separately deployed
            // NoiseV1Ext contract, which the 0x7d case reaches only by
            // STATICCALL to the noiseLib address. Kind 1 (first-party
            // GradNoise) is reached by STATICCALL at the CREATE2 constant
            // GRADNOISE.
            function glyph_run(s_, recLen, wide, xf) {
                // the WHOLE GLYPH/GLYPH64/GLYPH64XF body as one shared loop
                // with TWO independent knobs. `wide` selects the coord decode
                // (0 = i32 Q15.16 widened <<16 / recLen 9; 1 = raw i64 /
                // recLen 17). `xf` selects the armed-transform contract:
                //   xf 1 (GLYPH, GLYPH64XF): APPLY + CONSUME. glyph_seg
                //     applies the armed one-shot per record and the flag is
                //     CLEARED below.
                //   xf 0 (GLYPH64): IGNORE + PRESERVE. The flag is zeroed
                //     across the loop so glyph_seg skips the transform, then
                //     RESTORED below (raw coords; the one-shot stays armed
                //     for the next GLYPH/GLYPHC).
                // Callers: GLYPH (9,0,1), GLYPH64 (17,1,0), GLYPH64XF (17,1,1).
                let off := pop_int(s_)
                let dl := mload(add(s_, 64))
                if or(slt(off, 0), sgt(add(off, 2), dl)) { fail() }
                let dbase := add(add(mload(s_), 0x20), mload(add(s_, 32)))
                let cnt := shr(240, mload(add(dbase, off)))
                if sgt(add(add(off, 2), mul(cnt, recLen)), dl) { fail() }
                mstore(add(s_, 1920), add(dbase, add(off, 2))) // ptr
                mstore(add(s_, 1952), cnt) // remaining records
                let savedXf := mload(add(s_, 1792))
                if iszero(xf) { mstore(add(s_, 1792), 0) }
                for {} mload(add(s_, 1952)) {} {
                    mstore(add(s_, 1952), sub(mload(add(s_, 1952)), 1))
                    pop(glyph_steps(s_))
                    let w := mload(mload(add(s_, 1920)))
                    mstore(add(s_, 1920), add(mload(add(s_, 1920)), recLen))
                    switch byte(0, w)
                    case 4 {
                        if mload(add(s_, 1632)) { close_vert(s_) }
                    }
                    default {
                        if iszero(or(eq(byte(0, w), 1), eq(byte(0, w), 2))) { fail() } // GlyphBadCommand()
                        let gx
                        let gy
                        switch wide
                        case 0 {
                            gx := shl(16, signextend(3, shr(216, w)))
                            gy := shl(16, signextend(3, shr(184, w)))
                        }
                        default {
                            gx := signextend(7, shr(184, w))
                            gy := signextend(7, shr(120, w))
                        }
                        glyph_seg(s_, byte(0, w), gx, gy)
                    }
                }
                // xf 1: clear the one-shot. xf 0: restore the stashed flag
                // (mul(1, saved)), so it stays armed.
                mstore(add(s_, 1792), mul(iszero(xf), savedXf))
            }
            function glyph_steps(s_) -> st {
                st := add(mload(add(s_, 224)), 1)
                if gt(st, 0x100000000) { fail() } // StepLimitExceeded()
                mstore(add(s_, 224), st)
            }

            switch op
            default {
            // Two-level dispatch: each op selects its high-nibble group
            // first, then the op within it (worst case ~8 compares, not
            // ~50). Group order follows the dynamic frequency.
            switch shr(4, op)
            case 6 {
            switch op
            default { invalid() }
            }
            case 7 {
            switch op
            case 0x7c {
                // NOISEINIT, vocabulary {1} here (imm8v mask 0x02). The router
                // admits kind 0 first (_noise0), so this case sees kind 1 or a
                // fault. Kinds >= 2 are reserved and trap like unknown
                // opcodes. Kind 1 = GradNoise: pop octaves (top), then gain.
                // Check octaves in [1,8] and gain in (0, ONE). Record the
                // packed word and marker 2. No table, no +4096 steps,
                // nothing to checkpoint.
                pop(imm8v(s, 0x02))
                let gain, octfx := pop2(s)
                let oct := sar(32, octfx)
                if or(or(slt(oct, 1), sgt(oct, 8)), or(slt(gain, 1), sgt(gain, 0xffffffff))) { fail() }
                mstore(add(s, 704), or(shl(64, oct), gain)) // packed {octaves, gain}
                mstore(add(s, 736), 2) // kind-1 armed
            }
            case 0x7d {
                // NOISE: pop y, x -> one sample of the armed kind. Marker 1
                // calls NoiseV1Ext. Marker 2 calls the CREATE2 constant
                // GRADNOISE with seed, octaves, gain, x, and y. Any other
                // marker traps.
                let x, y := pop2(s)
                let p := mload(0x40)
                switch mload(add(s, 736))
                case 1 {
                    // kind 0 (NoiseV1): the staged blob IS the call. Write x
                    // and y into its head and send all 133,316 B to
                    // NoiseV1Ext.
                    let ar := mload(add(s, 704))
                    mstore(add(ar, 4), x)
                    mstore(add(ar, 36), y)
                    if iszero(staticcall(gas(), mload(add(s, 2112)), ar, 133316, p, 32)) {
                        returndatacopy(0, 0, returndatasize())
                        revert(0, returndatasize())
                    }
                    push_fx(s, signextend(7, mload(p)))
                }
                case 2 {
                    let w := mload(add(s, 704))
                    mstore(p, shl(224, 0x1349e518)) // grad(int32,uint256,int64,int64,int64)
                    mstore(add(p, 4), mload(add(s, 384))) // initialSeed (sign-extended int32)
                    mstore(add(p, 36), shr(64, w)) // octaves
                    mstore(add(p, 68), and(w, 0xffffffffffffffff)) // gain (positive < ONE)
                    mstore(add(p, 100), x)
                    mstore(add(p, 132), y)
                    if iszero(staticcall(gas(), GRADNOISE, p, 164, p, 32)) {
                        returndatacopy(0, 0, returndatasize())
                        revert(0, returndatasize())
                    }
                    push_fx(s, mload(p)) // grad returns a canonical ABI-encoded int64
                }
                default { fail() } // NoiseNotInitialized()
            }
            case 0x79 {
                // BEZSET: pop slot, then D.y D.x C.y C.x B.y B.x A.y A.x.
                // Build the cubic and a 101-entry cumulative arc-length
                // table. The bank has 64 lazily allocated pointer slots
                // (zeroed; null = unset, and a read of an unset slot
                // faults). Each record (8 coeff + 101 arc words) is
                // bump-allocated unzeroed.
                let rec
                {
                    let slot := pop_int(s)
                    if or(slt(slot, 0), sgt(slot, 63)) { fail() } // BezierSlotOutOfRange()
                    let bank := mload(add(s, 640))
                    if iszero(mload(add(s, 672))) {
                        bank := mload(0x40)
                        mstore(0x40, add(bank, 0x800))
                        calldatacopy(bank, calldatasize(), 0x800) // 64 null ptrs
                        mstore(add(s, 640), bank)
                        mstore(add(s, 672), 1)
                    }
                    rec := mload(0x40)
                    mstore(0x40, add(rec, 0xda0)) // 109 words
                    mstore(add(bank, shl(5, slot)), rec)
                }
                for { let o := 0xe0 } iszero(slt(o, 0)) { o := sub(o, 0x20) } {
                    mstore(add(rec, o), pop_fx(s))
                }
                mstore(add(rec, 0x100), 0) // arc[0]
                bz_build(rec)
                mstore(add(s, 224), add(mload(add(s, 224)), 200)) // steps += 200 (arc-length build budget)
            }
            case 0x7a {
                // BEZMX: pop slot, pop t -> XFunc(Map(t))
                let rec, t := bz_rec(s)
                push_fx(s, bz_x(rec, bz_map(rec, t)))
            }
            case 0x7b {
                // BEZMY: pop slot, pop t -> YFunc(Map(t))
                let rec, t := bz_rec(s)
                push_fx(s, bz_y(rec, bz_map(rec, t)))
            }
            default { invalid() }
            }
            case 2 {
            switch op
            case 0x24 {
                // MOD: truncated remainder; y == 0 -> 0
                let a, b := pop2(s)
                switch b
                case 0 { push_fx(s, 0) }
                default { push_fx(s, smod(a, b)) }
            }
            case 0x2b {
                // SIN
                push_fx(s, fx_sin(s, pop_fx(s)))
            }
            case 0x2c {
                // COS
                push_fx(s, fx_cos(s, pop_fx(s)))
            }
            case 0x2a {
                // SQRT: x < 0 -> 0
                let a := pop_fx(s)
                switch slt(a, 0)
                case 1 { a := 0 }
                default { a := fx_sqrt(a) }
                push_fx(s, a)
            }
            case 0x2d {
                // LERP: a b t -> a + (b-a)*t
                let t := pop_fx(s)
                let a, b := pop2(s)
                push_fx(s, fx_add(a, fx_mul(fx_sub(b, a), t)))
            }
            case 0x2e {
                // MAP: n a b c d -> c + (d-c)*((n-a)/(b-a)); b == a -> c
                mstore(add(s, 1920), pop_fx(s)) // d
                mstore(add(s, 1952), pop_fx(s)) // c
                let a, b := pop2(s)
                let n := pop_fx(s)
                let t := 0
                if iszero(eq(b, a)) { t := fx_div(fx_sub(n, a), fx_sub(b, a)) }
                push_fx(
                    s,
                    fx_add(mload(add(s, 1952)), fx_mul(fx_sub(mload(add(s, 1920)), mload(add(s, 1952))), t))
                )
            }
            case 0x2f {
                // CONSTRAIN: v lo hi -> max(min(v, hi), lo)
                let lo, hi := pop2(s)
                let v := pop_fx(s)
                if sgt(v, hi) { v := hi }
                if slt(v, lo) { v := lo }
                push_fx(s, v)
            }
            case 0x25 {
                // NEG (saturating: -MIN -> MAX)
                push_fx(s, fx_sub(0, pop_fx(s)))
            }
            case 0x26 {
                // ABS
                push_fx(s, fx_abs(pop_fx(s)))
            }
            case 0x27 {
                // MIN: a < b ? a : b
                let a, b := pop2(s)
                switch slt(a, b)
                case 1 { push_fx(s, a) }
                default { push_fx(s, b) }
            }
            case 0x28 {
                // MAX: a >= b ? a : b
                let a, b := pop2(s)
                switch slt(a, b)
                case 1 { push_fx(s, b) }
                default { push_fx(s, a) }
            }
            default { invalid() }
            }
            case 0xa {
            switch op
            case 0xa4 {
                // MEMCAP u16 BE: declare the linear-memory bound (s.memBound
                // := n). Faults when n == 0, n > 40960, memory is already
                // allocated (s.memInit: a store has executed), or MEMCAP ran
                // before (s.memcapSet). Both once-checks live HERE, never on
                // the memory-op hot path. Emits nothing. One step.
                let pc_ := mload(add(s, 192))
                if gt(add(pc_, 2), mload(add(s, 128))) { fail() } // TruncatedImmediate()
                let n := shr(240, mload(add(add(add(mload(s), 0x20), mload(add(s, 96))), pc_)))
                mstore(add(s, 192), add(pc_, 2))
                if or(iszero(n), gt(n, 40960)) { fail() } // MemcapBoundOutOfRange()
                if mload(add(s, 544)) { fail() } // MemcapAfterStore()
                if mload(add(s, 2432)) { fail() } // MemcapDuplicate()
                mstore(add(s, 2432), 1) // s.memcapSet = true
                mstore(add(s, 2400), n) // s.memBound = n
            }
            case 0xaa {
                // FL32: pop v; push the nearest IEEE binary32 value (ties to
                // even)
                push_fx(s, fl32v(pop_fx(s)))
            }
            case 0xab {
                // HASH: pop b, pop a -> hash(intpart a, intpart b) as Fix64
                // [0,1)
                let b := pop_fx(s)
                let a := pop_fx(s)
                push_fx(s, h_mix(sar(32, a), sar(32, b)))
            }
            case 0xac {
                // PSCATTER u8 k: reseed the xorshift to hash(initialSeed,
                // intpart(locals[k])), using the run seed (@384), not @416.
                let k := imm8(s)
                let iv := sar(32, mload(add(add(mload(add(s, 320)), 0x20), shl(5, k))))
                mstore(add(s, 416), signextend(3, h_mix(mload(add(s, 384)), iv)))
            }
            case 0xae {
                // UNPACK: color -> r g b as Fix64 [0,255] (push r, g, b; b on
                // top), the exact inverse of RGBPACK (0x8d); alpha dropped.
                // Byte-for-byte the case 0xae of the canonical KVM library.
                let c := pop_fx(s)
                push_fx(s, shl(32, and(shr(16, c), 0xff)))
                push_fx(s, shl(32, and(shr(8, c), 0xff)))
                push_fx(s, shl(32, and(c, 0xff)))
            }
            default { invalid() }
            }
            case 3 {
            switch op
            case 0x3a {
                // RANDL: legacy 1/1000-quantized nextFloat
                let ns := xs_step(mload(add(s, 416)))
                mstore(add(s, 416), ns)
                let t := ns
                if slt(t, 0) { t := sub(0, t) }
                push_fx(s, fx_div(shl(32, mod(t, 1000)), 0x3E800000000))
            }
            case 0x3c {
                // PARAM u8 (missing -> 0)
                let i := imm8(s)
                let v := 0
                if lt(i, mload(mload(add(s, 352)))) { v := mload(add(add(mload(add(s, 352)), 0x20), shl(5, i))) }
                push_fx(s, v)
            }
            case 0x3d {
                // TRAIT u8: 0x02 | u8 id | i64 value
                let id := imm8(s)
                let v := pop_fx(s)
                w8(s, 0x02)
                w8(s, id)
                w64(s, v)
                // stepKVM seam: the plain per-TRAIT counter (KSN1 traitCount)
                mstore(add(s, 2592), add(mload(add(s, 2592)), 1))
            }
            case 0x35 {
                // DR32: pop byte offset -> u32 BE raw (zero-extended)
                let off := pop_int(s)
                if or(slt(off, 0), sgt(add(off, 4), mload(add(s, 64)))) { fail() } // DataReadOutOfBounds()
                push_fx(s, shr(224, mload(add(add(add(mload(s), 0x20), mload(add(s, 32))), off))))
            }
            case 0x37 {
                // RV1RAW: RandomV1.next() raw sample -> int64(sample) * ONE
                push_fx(s, shl(32, rv1_next(rv1_ensure(s))))
            }
            case 0x3e {
                // RV1N: max -> RandomV1 integer in [0, max) as Fix64 int.
                // The reference truncates the popped max to int32 AFTER the
                // negativity check. Both fault CONDITIONS are preserved. The
                // payloads are the bare selector like every other
                // interpreter fault.
                let m := pop_int(s)
                if slt(m, 0) { fail() } // Rv1NegativeMax()
                m := signextend(3, m)
                if slt(m, 0) { fail() } // truncated-negative max
                push_fx(s, signextend(7, shl(32, rv1_sample(s, m))))
            }
            case 0x3f {
                // RV1R: min max -> RandomV1 integer in [min, max) as Fix64
                // int. No max > min guard (C#-compatible: equal bounds
                // return min and still consume a draw). Fault CONDITIONS are
                // preserved (range > int32.max; the CHECKED final int32 add
                // of the reference). The payloads are the bare selector.
                let mx := signextend(3, pop_int(s))
                let mn := signextend(3, pop_int(s))
                mx := sub(mx, mn) // range (int64-wide, exact)
                if sgt(mx, 0x7fffffff) { fail() } // large range
                mx := add(rv1_sample(s, mx), mn)
                if iszero(eq(mx, signextend(3, mx))) { fail() } // checked-add overflow
                push_fx(s, signextend(7, shl(32, mx)))
            }
            case 0x3b {
                // RV1GAUSS: Box-Muller, two raw draws; ln via the ext
                // staticcall (the router stages the Trig256 address). The
                // final add(0, mul(ONE, x)) of the reference is an identity.
                let p := rv1_ensure(s)
                let u1 := fx_sub(0x100000000, fx_mul(shl(32, rv1_next(p)), 2))
                let u2 := fx_sub(0x100000000, fx_mul(shl(32, rv1_next(p)), 2))
                push_fx(
                    s,
                    fx_mul(
                        fx_sqrt(
                            fx_mul(
                                sub(0, 0x200000000),
                                ext_1(mload(add(s, 2112)), shl(224, 0x403bc281), u1)
                            )
                        ),
                        fx_sin(s, fx_mul(0x200000000, fx_mul(0x3243F6A88, u2)))
                    )
                )
            }
            case 0x36 {
                // RV1RESET: rebuild the RandomV1 state from the immutable run
                // seed (fresh table; allows multi-pass derivation)
                mstore(add(s, 608), 0)
                pop(rv1_ensure(s))
            }
            case 0x33 {
                // NOT: x == 0 -> ONE else 0
                push_fx(s, mul(iszero(pop_fx(s)), 0x100000000))
            }
            case 0x34 {
                // CLERP: c1 c2 k -> ColorMath.lerp (k unconstrained)
                let k := pop_fx(s)
                let c1, c2 := pop2(s)
                push_fx(s, color_lerp(and(c1, 0xffffffff), and(c2, 0xffffffff), k))
            }
            default { invalid() }
            }
            case 4 {
            switch op
            case 0x49 {
                // SETALPHA: color a -> alpha = floor(constrain(a,0,1)*255);
                // the clamp+scale is exactly hsb_byte with mAdd 0
                let c, av := pop2(s)
                push_fx(s, or(and(c, 0xffffff), shl(24, hsb_byte(av, 0))))
            }
            case 0x4a {
                // TINT: target tint
                let tgt, tc := pop2(s)
                push_fx(s, color_tint(and(tgt, 0xffffffff), and(tc, 0xffffffff)))
            }
            case 0x4d {
                // HSB2RGB: h s b -> packed ARGB (alpha 255)
                hsb2rgb(s)
            }
            default { invalid() }
            }
            case 5 {
            switch op
            default { invalid() }
            }
            case 8 {
            switch op
            case 0x80 {
                // TAN: cos == 0 -> 0
                let a := pop_fx(s)
                let c := fx_cos(s, a)
                switch c
                case 0 { push_fx(s, 0) }
                default { push_fx(s, fx_div(fx_sin(s, a), c)) }
            }
            case 0x89 {
                // DIST: x1 y1 x2 y2 -> sqrt(dx^2+dy^2); overflow-negative -> 0
                let x2, y2 := pop2(s)
                let x1, y1 := pop2(s)
                x1 := fx_sub(x2, x1)
                y1 := fx_sub(y2, y1)
                x1 := fx_add(fx_mul(x1, x1), fx_mul(y1, y1))
                switch slt(x1, 0)
                case 1 { x1 := 0 }
                default { x1 := fx_sqrt(x1) }
                push_fx(s, x1)
            }
            case 0x81 {
                // ATAN2: y x -> theta (external Trig256.atan2)
                let y, x := pop2(s)
                push_fx(s, ext_2(mload(add(s, 2112)), shl(224, 0xbe5c8cf1), y, x))
            }
            case 0x82 {
                // POW: b e -> exp(e*ln b); b <= 0 -> 0
                let b, e := pop2(s)
                switch sgt(b, 0)
                case 0 { push_fx(s, 0) }
                default {
                    push_fx(
                        s,
                        ext_1(
                            mload(add(s, 2112)),
                            shl(224, 0x2c8d875d),
                            fx_mul(e, ext_1(mload(add(s, 2112)), shl(224, 0x403bc281), b))
                        )
                    )
                }
            }
            case 0x83 {
                // EXP
                push_fx(s, ext_1(mload(add(s, 2112)), shl(224, 0x2c8d875d), pop_fx(s)))
            }
            case 0x84 {
                // LOG: x <= 0 -> 0
                let x := pop_fx(s)
                switch sgt(x, 0)
                case 0 { push_fx(s, 0) }
                default { push_fx(s, ext_1(mload(add(s, 2112)), shl(224, 0x403bc281), x)) }
            }
            case 0x85 {
                // ROUND (round-half-to-even)
                push_fx(s, fx_round(pop_fx(s)))
            }
            case 0x86 {
                // CEIL: -floor(-x)
                push_fx(s, fx_sub(0, signextend(7, and(fx_sub(0, pop_fx(s)), 0xffffffff00000000))))
            }
            case 0x87 {
                // FRACT: x - floor(x)
                let x := pop_fx(s)
                push_fx(s, fx_sub(x, signextend(7, and(x, 0xffffffff00000000))))
            }
            case 0x88 {
                // SIGN
                push_fx(s, mul(fx_sign(pop_fx(s)), 0x100000000))
            }
            case 0x8a {
                // ASIN: pi/2 - acos(x); |x| > 1 clamps
                let x := fx_clamp(pop_fx(s), sub(0, 0x100000000), 0x100000000)
                push_fx(
                    s,
                    fx_sub(0x1921FB544, ext_1(mload(add(s, 2112)), shl(224, 0x3a87d0f9), x))
                )
            }
            case 0x8b {
                // ACOS: |x| > 1 clamps
                let x := fx_clamp(pop_fx(s), sub(0, 0x100000000), 0x100000000)
                push_fx(s, ext_1(mload(add(s, 2112)), shl(224, 0x3a87d0f9), x))
            }
            case 0x8c {
                // SEED: the run's int32 seed as a Fix64 integer
                push_fx(s, signextend(7, shl(32, mload(add(s, 384)))))
            }
            case 0x8d {
                // RGBPACK: r g b -> packed ARGB (alpha 255). Per channel:
                // constrain(0,255) + floor, the p5c literal-fold pin (b, g, r
                // pop at shifts 0, 8, 16; branchless clamps)
                let acc := 0xff000000
                for { let sh := 0 } lt(sh, 24) { sh := add(sh, 8) } {
                    acc := or(acc, shl(sh, shr(32, fx_clamp(pop_fx(s), 0, 0xff00000000))))
                }
                push_fx(s, acc)
            }
            default { invalid() }
            }
            case 9 {
            switch op
            case 0x90 {
                // BAND (int32 domain, results * ONE)
                let b := signextend(3, pop_int(s))
                push_fx(s, signextend(7, shl(32, and(signextend(3, pop_int(s)), b))))
            }
            case 0x91 {
                // BOR
                let b := signextend(3, pop_int(s))
                push_fx(s, signextend(7, shl(32, or(signextend(3, pop_int(s)), b))))
            }
            case 0x92 {
                // BXOR
                let b := signextend(3, pop_int(s))
                push_fx(s, signextend(7, shl(32, signextend(3, xor(signextend(3, pop_int(s)), b)))))
            }
            case 0x93 {
                // BNOT
                push_fx(s, signextend(7, shl(32, signextend(3, not(signextend(3, pop_int(s)))))))
            }
            case 0x94 {
                // SHL (int32 wrap; shift masked to 31)
                let b := signextend(3, pop_int(s))
                push_fx(
                    s,
                    signextend(7, shl(32, signextend(3, shl(and(b, 31), and(signextend(3, pop_int(s)), 0xffffffff)))))
                )
            }
            case 0x95 {
                // SHR (sign-propagating; shift masked to 31)
                let b := signextend(3, pop_int(s))
                push_fx(s, signextend(7, shl(32, sar(and(b, 31), signextend(3, pop_int(s))))))
            }
            case 0x96 {
                // USHR (zero-fill; result wraps into int64 two's complement)
                let b := signextend(3, pop_int(s))
                push_fx(s, signextend(7, shl(32, shr(and(b, 31), and(signextend(3, pop_int(s)), 0xffffffff)))))
            }
            default { invalid() }
            }
            case 0 {
            switch op
            case 0x0f {
                // DUP2: a b -> a b a b
                let a, b := pop2(s)
                push_fx(s, a)
                push_fx(s, b)
                push_fx(s, a)
                push_fx(s, b)
            }
            case 0x01 {
                // NOP
            }
            default { invalid() }
            }
            case 1 {
            switch op
            case 0x10 {
                // SWAP
                let a, b := pop2(s)
                push_fx(s, b)
                push_fx(s, a)
            }
            case 0x1e {
                // DR8: pop byte offset -> data[off] * ONE
                let off := pop_int(s)
                if or(slt(off, 0), sgt(add(off, 1), mload(add(s, 64)))) { fail() } // DataReadOutOfBounds()
                push_fx(s, shl(32, byte(0, mload(add(add(add(mload(s), 0x20), mload(add(s, 32))), off)))))
            }
            default { invalid() }
            }
            default { invalid() } // unreachable: routed explicitly
            }
        }
    }

    // ---- shared handler bodies ----------------------------------------------
    //
    // Every opcode family except PENCIL executes in the Yul blocks above. The
    // Solidity bodies are the pencil family below (_pencil, its helpers and
    // the resume seam), the kind-0 noise admit (_noise0, _noiseBlob),
    // _stageTrig, and _save and _restore (never called: SAVE/RESTORE trap).
    // _stageTrig stays a function because address(Trig256) is a 20-byte link
    // placeholder, and each of its two call sites would carry a copy if it
    // were inlined.

    // ---- the pencil family (PENCIL 0xb0) ------------------------------------
    //
    // The arm this fork carries: the arm of KVMPencilRunner, sub-op for
    // sub-op (the sub-op table is in the KVMPencil header). Its pure glue
    // (the PAPER and RTERM checks, the region install, the paper and region
    // records) is in the linked library PencilStep, and the exact Fix64 value
    // math is in PencilVM, so the core fits EIP-170. Values cross into the
    // family as Q16: floor(v / 2^16), which must fit an int32. The records
    // carry Q16. VARY and SAMPLE are exact Fix64. Every fault reverts the
    // bare KVMError selector, like the other interpreter faults.

    /// A growable word vector in memory.
    struct PVec {
        uint256 ptr;
        uint256 len;
        uint256 cap;
    }

    /// The family's VM state. Pending values stay as the program's own Fix64
    /// values. A record carries their Q16, range-checked when the value
    /// entered. The Yul of the resume seam reads the fields at fixed offsets
    /// (reference-typed members are pointers):
    ///
    ///     offset  field     contents
    ///     ------  --------  ---------------------------------------------
    ///          0  hasPaper
    ///         32  hasPen
    ///         64  paper     PencilVM's paper words
    ///         96  pen       Q16 abR abG abB reach strength wax
    ///        128  pts       x, y, p per pending point
    ///        160  polys     n, n x (x, y) per pending polygon
    ///        192  np        the pending polygon count
    ///        224  terms     kind, ax, ay, bx, by, a, b per pending term
    ///        256  slots     per slot, PencilVM's region words (0 = empty)
    ///        288  counts    per slot, vertex count << 128 | term count
    ///                       (SAMPLE's charge)
    ///        320  sheet     the paper's sheetMm (Q16)
    ///        352  seed      the paper's seed
    ///        384  srcs      per slot, the SOURCE words of the region
    ///                       (PencilStep's source layout)
    ///
    /// The vary lattices of the paper are a pure function of sheet, seed and
    /// the canvas.
    struct PState {
        bool hasPaper;
        bool hasPen;
        int256[11] paper;
        int256[6] pen;
        PVec pts;
        PVec polys;
        uint256 np;
        PVec terms;
        uint256[16] slots;
        uint256[16] counts;
        int256 sheet;
        uint256 seed;
        uint256[16] srcs;
    }

    int256 private constant PQ = 65536;

    function _pfail() private pure {
        assembly {
            mstore(0x00, shl(224, 0x4c49dedb))
            revert(0x00, 0x04)
        }
    }

    // Pop and push the operand stack raw, like the hot loop (s.stack at
    // offset 256, s.sp at 288). Underflow and overflow revert the bare
    // KVMError.
    function _ppop(State memory s) private pure returns (int64 v) {
        assembly {
            let sp := mload(add(s, 288))
            if iszero(sp) {
                mstore(0x00, shl(224, 0x4c49dedb))
                revert(0x00, 0x04)
            }
            sp := sub(sp, 1)
            mstore(add(s, 288), sp)
            v := signextend(7, mload(add(add(mload(add(s, 256)), 0x20), shl(5, sp))))
        }
    }

    function _ppush(State memory s, int64 v) private pure {
        assembly {
            let sp := mload(add(s, 288))
            if iszero(lt(sp, 256)) {
                mstore(0x00, shl(224, 0x4c49dedb))
                revert(0x00, 0x04)
            }
            mstore(add(add(mload(add(s, 256)), 0x20), shl(5, sp)), v)
            mstore(add(s, 288), add(sp, 1))
        }
    }

    /// A Fix64 value as Q16 (floor); outside int32 traps.
    function _q(int256 v) private pure returns (int256 r) {
        r = v >> 16;
        if (r < -2147483648 || r > 2147483647) _pfail();
    }

    /// Pop a value that must fit int32 Q16; returns it as Fix64.
    function _pf(State memory s) private pure returns (int256 v) {
        v = _ppop(s);
        _q(v);
    }

    /// A small whole-number operand (its integer part) in [0, hi].
    function _pint(State memory s, int256 hi) private pure returns (uint256) {
        int256 k = int256(_ppop(s)) >> 32;
        if (k < 0 || k > hi) _pfail();
        return uint256(k);
    }

    function _inBox(int256 v) private pure returns (bool) {
        v >>= 16;
        return v >= -2048 * PQ && v < 6144 * PQ;
    }

    /// Make room for n more stream bytes and return the write address. Grows
    /// s.out like ensure_out, with 32 B of slack.
    function _pgrow(State memory s, uint256 n) private pure returns (uint256 at) {
        assembly {
            let buf := mload(add(s, 2144))
            let len := mload(add(s, 2176))
            let want := add(add(len, n), 32)
            if gt(want, mload(buf)) {
                let cap := shl(1, mload(buf))
                for {} gt(want, cap) {} { cap := shl(1, cap) }
                let nb := mload(0x40)
                mstore(0x40, add(nb, add(0x20, cap)))
                mstore(nb, cap)
                mcopy(add(nb, 0x20), add(buf, 0x20), len)
                mstore(add(s, 2144), nb)
                buf := nb
            }
            at := add(add(buf, 0x20), len)
            mstore(add(s, 2176), add(len, n))
        }
    }

    /// Append n big-endian bytes of v to the stream.
    function _pw(State memory s, uint256 v, uint256 n) private pure {
        uint256 at = _pgrow(s, n);
        assembly {
            let bits := shl(3, n)
            mstore(at, shl(sub(256, bits), and(v, sub(shl(bits, 1), 1))))
        }
    }

    /// Append a record the library built.
    function _pwb(State memory s, bytes memory r) private pure {
        uint256 at = _pgrow(s, r.length);
        assembly {
            mcopy(at, add(r, 0x20), mload(r))
        }
    }

    function _vpush(PVec memory v, uint256 w) private pure {
        uint256 l = v.len;
        if (l == v.cap) {
            uint256 cap = l == 0 ? 60 : 2 * l;
            uint256 np;
            uint256 op = v.ptr;
            assembly {
                np := mload(0x40)
                mstore(0x40, add(np, shl(5, cap)))
                mcopy(np, op, shl(5, l))
            }
            v.ptr = np;
            v.cap = cap;
        }
        uint256 p = v.ptr;
        assembly {
            mstore(add(p, shl(5, l)), w)
        }
        v.len = l + 1;
    }

    function _vget(PVec memory v, uint256 i) private pure returns (uint256 w) {
        uint256 p = v.ptr;
        assembly {
            w := mload(add(p, shl(5, i)))
        }
    }

    function _pencil(State memory s, PState memory ps) private view {
        unchecked {
            uint256 so;
            assembly {
                // the u8 sub-op immediate (pc @192, codeStart @96,
                // codeLen @128)
                let ip := mload(add(s, 192))
                if iszero(lt(ip, mload(add(s, 128)))) {
                    mstore(0x00, shl(224, 0x4c49dedb))
                    revert(0x00, 0x04) // TruncatedImmediate
                }
                so := byte(0, mload(add(add(mload(s), 0x20), add(mload(add(s, 96)), ip))))
                mstore(add(s, 192), add(ip, 1))
            }
            uint256 extra;
            if (so == 0) {
                // PAPER: pop sheetMm, seed, b, g, r; record 0x0c
                int256 sheet = _q(_ppop(s));
                uint256 sd = uint256(int256(_ppop(s)) >> 32) & 0xffffffff;
                int256 b = int256(_ppop(s)) >> 32;
                int256 g = int256(_ppop(s)) >> 32;
                int256 r = int256(_ppop(s)) >> 32;
                if (ps.hasPaper) _pfail(); // paper already declared
                bytes memory rec;
                (rec, extra) = _pPaper(s, ps, r, g, b, sd, sheet, true);
                _pwb(s, rec);
            } else if (so == 1) {
                // VARY: pop y, x -> vary32(floor x, floor y)
                int64 y = _ppop(s);
                int64 x = _ppop(s);
                if (!ps.hasPaper) _pfail(); // no paper
                _ppush(s, PencilVM.vary32(ps.paper, x >> 32, y >> 32));
            } else if (so == 2) {
                // PEN: pop wax, strength, reach, abB, abG, abR. Each
                // absorbance is in [0, 64], the rest are in [0, 4].
                for (uint256 i = 6; i > 0; --i) {
                    int256 v = _q(_ppop(s));
                    ps.pen[i - 1] = v;
                }
                for (uint256 i; i < 6; ++i) {
                    int256 v = ps.pen[i];
                    if (v < 0 || v > (i < 3 ? 64 * PQ : 4 * PQ)) _pfail(); // invalid pen
                }
                ps.hasPen = true;
            } else if (so == 3) {
                // PT: pop p, y, x. The pressure is in [0, 4]. At most
                // 65,535 points are pending.
                int256 p = _ppop(s);
                int256 y = _ppop(s);
                int256 x = _ppop(s);
                int256 pq = _q(p);
                _q(y);
                _q(x);
                if (pq < 0 || pq > 4 * PQ) _pfail(); // invalid pressure
                if (ps.pts.len >= 65535 * 3) _pfail(); // too many points
                _vpush(ps.pts, uint256(x));
                _vpush(ps.pts, uint256(y));
                _vpush(ps.pts, uint256(p));
            } else if (so == 4) {
                extra = _pStroke(s, ps);
            } else if (so == 5) {
                // RPOLY: the pending points (3..255, in the box) become one
                // polygon
                uint256 n = ps.pts.len / 3;
                if (n < 3 || n > 255) _pfail(); // a polygon takes 3 to 255 points
                if (ps.np >= 65535) _pfail(); // too many polygons
                _vpush(ps.polys, n);
                for (uint256 i; i < n; ++i) {
                    uint256 x = _vget(ps.pts, 3 * i);
                    uint256 y = _vget(ps.pts, 3 * i + 1);
                    if (!_inBox(int256(x)) || !_inBox(int256(y))) _pfail(); // outside the coordinate box
                    _vpush(ps.polys, x);
                    _vpush(ps.polys, y);
                }
                ps.np += 1;
                ps.pts.len = 0;
                extra = n;
            } else if (so == 6) {
                // RTERM: pop b, a, by, bx, ay, ax (Fix64), then kind. One
                // shade term.
                int256[7] memory f; // kind, ax, ay, bx, by, a, b
                for (uint256 i = 7; i > 1; --i) f[i - 1] = _ppop(s);
                f[0] = int256(_pint(s, 1));
                PencilStep.term(f);
                if (ps.terms.len >= 65535 * 7) _pfail(); // too many terms
                for (uint256 i; i < 7; ++i) _vpush(ps.terms, uint256(f[i]));
            } else if (so == 7) {
                extra = _pRend(s, ps);
            } else if (so == 8) {
                extra = _pSample(s, ps);
            } else {
                _pfail(); // invalid sub-op
            }
            s.steps += extra;
        }
    }

    /// Install the paper for (r, g, b, sd, sheet) on this program's canvas in
    /// ps. With `check`, also apply the PAPER traps and return its record and
    /// its step surcharge (the resume seam rebuilds without them).
    function _pPaper(State memory s, PState memory ps, int256 r, int256 g, int256 b, uint256 sd, int256 sheet, bool check)
        private
        pure
        returns (bytes memory rec, uint256 extra)
    {
        uint256 w0 = _word(s.program, 0);
        (ps.paper, extra, rec) = PencilStep.paper(
            int256(uint256(uint16(w0 >> 192))), int256(uint256(uint16(w0 >> 176))), r, g, b, sd, sheet, check
        );
        ps.hasPaper = true;
        ps.sheet = sheet;
        ps.seed = sd;
    }

    /// STROKE: pop flags, slot, off, r; record 0x0e through the pending points.
    function _pStroke(State memory s, PState memory ps) private pure returns (uint256 n) {
        unchecked {
            uint256 flags = _pint(s, 7);
            uint256 slot = _pint(s, 15);
            int256 off = _q(_ppop(s));
            int256 r = _q(_ppop(s));
            if (!ps.hasPaper || !ps.hasPen) _pfail(); // no paper / no pen
            if (r < 4096 || r > 256 * PQ || off < 0) _pfail(); // invalid stroke
            if ((flags & 5) != 0 && _pw32(ps, 256, slot) == 0) _pfail(); // empty slot
            n = ps.pts.len / 3;
            // the record in one pass: tag | flags | slot | pen x i32 | r |
            // off | u16 n | n x (i32 x | i32 y | i32 p), each value as Q16
            uint256 at = _pgrow(s, 37 + 12 * n);
            int256[6] memory pen = ps.pen;
            uint256 pp = ps.pts.ptr;
            assembly {
                mstore(at, shl(232, or(0x0e0000, or(shl(8, flags), slot))))
                let w := add(at, 3)
                for { let i := 0 } lt(i, 6) { i := add(i, 1) } {
                    mstore(w, shl(224, mload(add(pen, shl(5, i)))))
                    w := add(w, 4)
                }
                mstore(w, shl(224, r))
                mstore(add(w, 4), shl(224, off))
                mstore(add(w, 8), shl(240, n))
                w := add(w, 10)
                for { let i := 0 } lt(i, mul(3, n)) { i := add(i, 1) } {
                    mstore(w, shl(224, sar(16, mload(add(pp, shl(5, i))))))
                    w := add(w, 4)
                }
            }
            ps.pts.len = 0;
        }
    }

    /// REND: pop tolL, wobBias, wobAmp, kv (Fix64), then slot; record 0x0d.
    function _pRend(State memory s, PState memory ps) private pure returns (uint256) {
        unchecked {
            int256[] memory src;
            uint256 slot;
            {
                uint256 nl = ps.polys.len;
                uint256 nw = ps.terms.len;
                src = new int256[](6 + nl + nw);
                for (uint256 i = 4; i > 0; --i) src[i - 1] = _pf(s); // kv, wobAmp, wobBias, tolL
                slot = _pint(s, 15);
                src[4] = int256(ps.np);
                uint256 sp;
                assembly {
                    sp := add(src, 0xc0)
                }
                uint256 pp = ps.polys.ptr;
                uint256 tp = ps.terms.ptr;
                assembly {
                    mcopy(sp, pp, shl(5, nl))
                    mstore(add(sp, shl(5, nl)), div(nw, 7))
                    mcopy(add(add(sp, shl(5, nl)), 0x20), tp, shl(5, nw))
                }
            }
            _pwb(s, _pInstall(ps, slot, src, true));
            ps.polys.len = 0;
            ps.np = 0;
            ps.terms.len = 0;
            uint256 c = _pw32(ps, 288, slot);
            return (c >> 128) + (c & type(uint128).max);
        }
    }

    /// Install a region in a slot from its source words, and keep the source
    /// for the snapshot. PencilStep.region builds the exact Fix64 region and
    /// SAMPLE's charge. With `check`, it also applies the kv trap of REND and
    /// returns the record.
    function _pInstall(PState memory ps, uint256 slot, int256[] memory src, bool check)
        private
        pure
        returns (bytes memory rec)
    {
        int256[] memory R;
        uint256 c;
        (R, rec, c) = PencilStep.region(src, slot, check);
        uint256 rp;
        uint256 sp;
        assembly {
            rp := R
            sp := src
        }
        assembly {
            let o := shl(5, slot)
            mstore(add(mload(add(ps, 256)), o), rp) // slots
            mstore(add(mload(add(ps, 288)), o), c) // counts
            mstore(add(mload(add(ps, 384)), o), sp) // srcs
        }
    }

    /// SAMPLE: pop which, slot, y, x -> the region at the point (Fix64).
    function _pSample(State memory s, PState memory ps) private view returns (uint256) {
        unchecked {
            uint256 which = _pint(s, 2);
            uint256 slot = _pint(s, 15);
            int64 y = _ppop(s);
            int64 x = _ppop(s);
            if (!ps.hasPaper) _pfail(); // no paper
            uint256 rp = _pw32(ps, 256, slot);
            if (rp == 0) _pfail(); // empty slot
            int256[] memory R;
            assembly {
                R := rp
            }
            _ppush(s, PencilVM.sample(R, ps.paper, x, y, which));
            uint256 c = _pw32(ps, 288, slot);
            return which == 2 ? c & type(uint128).max : c >> 128;
        }
    }

    /// Word `slot` of the PState array member at struct offset `field`
    /// (slots 256, counts 288, srcs 384; slot already range-checked).
    function _pw32(PState memory ps, uint256 field, uint256 slot) private pure returns (uint256 w) {
        assembly {
            w := mload(add(mload(add(ps, field)), shl(5, slot)))
        }
    }

    // ---- the pencil resume seam ---------------------------------------------
    //
    // The flat image carries the family's state as one section between the
    // bezier records and the path. Every entry is one 32-byte word:
    //
    //     u256 byteLen               0 = nothing armed (the fresh state)
    //     hasPaper | hasPen | sheet | seed
    //     pen x 6                    Q16, as the VM holds it
    //     nPts3, then nPts3 words    x, y, p per pending point
    //     np                         the pending polygon count
    //     nPolyW, then nPolyW words  n, n x (x, y) per pending polygon
    //     nTerm7, then nTerm7 words  kind, ax, ay, bx, by, a, b per term
    //     slotMask                   bit i = slot i installed
    //     per set slot, ascending    its source as an int256[] image (length
    //                                word, then PencilStep's source words)
    //
    // Every other value is the program's own Fix64. KVMPencilStepRunner owns
    // the wire codec and its validation. This is the trusted internal form,
    // so the landing is one copy and a pointer walk. The vectors point INTO
    // the landed image with cap = len, so a push reallocates. Each installed
    // slot is built again from its source, and the paper from sheet and
    // seed.

    /// Land flatIn's pencil section (its offset parked by _init) into ps.
    function _pLoad(State memory s, PState memory ps) private view {
        uint256 p;
        uint256 mask;
        assembly {
            let off := mload(add(s, 2784))
            let len := calldataload(off)
            if len {
                p := mload(0x40)
                calldatacopy(p, add(off, 32), len)
                mstore(0x40, add(p, len))
                // a (count, words) run as a vector, cap = len
                function vec(v, q) -> nq {
                    let n := mload(q)
                    mstore(v, add(q, 32))
                    mstore(add(v, 32), n)
                    mstore(add(v, 64), n)
                    nq := add(add(q, 32), shl(5, n))
                }
                mstore(ps, mload(p)) // hasPaper
                mstore(add(ps, 32), mload(add(p, 32))) // hasPen
                mstore(add(ps, 320), mload(add(p, 64))) // sheet
                mstore(add(ps, 352), mload(add(p, 96))) // seed
                mcopy(mload(add(ps, 96)), add(p, 128), 192) // pen
                let q := vec(mload(add(ps, 128)), add(p, 320)) // pts
                mstore(add(ps, 192), mload(q)) // np
                q := vec(mload(add(ps, 160)), add(q, 32)) // polys
                q := vec(mload(add(ps, 224)), q) // terms
                mask := mload(q)
                p := add(q, 32)
            }
        }
        if (ps.hasPaper) _pPaper(s, ps, 0, 0, 0, ps.seed, ps.sheet, false);
        for (uint256 i; i < 16; ++i) {
            if ((mask >> i) & 1 == 0) continue;
            int256[] memory src;
            assembly {
                src := p
                p := add(p, add(32, shl(5, mload(p))))
            }
            _pInstall(ps, i, src, false);
        }
    }

    /// The flat pencil section for ps (u256 byteLen + the words, as above),
    /// as a bytes value for _pack to copy.
    function _pImage(PState memory ps) private pure returns (bytes memory b) {
        assembly {
            // a vector as (count, words) at q_
            function vout(q_, v) -> nq {
                let n := mload(add(v, 32))
                mstore(q_, n)
                mcopy(add(q_, 32), mload(v), shl(5, n))
                nq := add(add(q_, 32), shl(5, n))
            }
            b := mload(0x40)
            let q := add(b, 0x40)
            mstore(q, mload(ps)) // hasPaper
            mstore(add(q, 32), mload(add(ps, 32))) // hasPen
            mstore(add(q, 64), mload(add(ps, 320))) // sheet
            mstore(add(q, 96), mload(add(ps, 352))) // seed
            mcopy(add(q, 128), mload(add(ps, 96)), 192) // pen
            q := vout(add(q, 320), mload(add(ps, 128))) // pts
            mstore(q, mload(add(ps, 192))) // np
            q := vout(add(q, 32), mload(add(ps, 160))) // polys
            q := vout(q, mload(add(ps, 224))) // terms
            let mq := q
            q := add(q, 32)
            let mask := 0
            let srcs := mload(add(ps, 384))
            for { let i := 0 } lt(i, 16) { i := add(i, 1) } {
                let sp := mload(add(srcs, shl(5, i)))
                if sp {
                    mask := or(mask, shl(i, 1))
                    let w := add(32, shl(5, mload(sp)))
                    mcopy(q, sp, w)
                    q := add(q, w)
                }
            }
            mstore(mq, mask)
            mstore(add(b, 0x20), sub(q, add(b, 0x40))) // byteLen
            mstore(b, sub(q, add(b, 0x20)))
            mstore(0x40, q)
        }
    }

    // ---- NOISEINIT kind 0 ---------------------------------------------------

    /// NOISEINIT kind 0 at the cold layer. When the u8 kind immediate exists
    /// and is 0: consume it, charge the +4096 table build, stage the client's
    /// assembled blob, and arm marker 1. A core built without a noiseLib
    /// traps here, like the one-shot. Otherwise leave the op to the warm case
    /// (kind 1, and every other fault).
    function _noise0(State memory s) private pure returns (bool k0) {
        assembly {
            let ip := mload(add(s, 192))
            if lt(ip, mload(add(s, 128))) {
                k0 := iszero(byte(0, mload(add(add(add(mload(s), 0x20), mload(add(s, 96))), ip))))
            }
            if k0 {
                if iszero(mload(add(s, 2816))) {
                    mstore(0x00, shl(224, 0x4c49dedb))
                    revert(0x00, 0x04)
                }
                mstore(add(s, 192), add(ip, 1))
                mstore(add(s, 224), add(mload(add(s, 224)), 4096)) // steps += 4096 (unchecked)
            }
        }
        if (k0) _noiseBlob(s);
    }

    /// Stage the assembled NoiseV1Ext blob in memory as the kind-0 table
    /// (State word 704) and arm marker 1 (word 736). The blob is blobs[1],
    /// which the Runner builds from the client's raw table (a pure function
    /// of the run seed).
    function _noiseBlob(State memory s) private pure {
        assembly {
            let src
            {
                let bo := add(4, calldataload(0x84))
                src := add(add(add(bo, 0x20), calldataload(add(bo, 0x40))), 0x20)
            }
            let ar := mload(0x40)
            mstore(0x40, add(ar, 133344)) // 32-aligned bump over the 133,316 B blob
            calldatacopy(ar, src, 133316)
            mstore(add(s, 704), ar)
            mstore(add(s, 736), 1)
        }
    }

    /// Stage the linked Trig256 library address in the gLineWidth scratch
    /// for the ext staticcalls of the warm ops (`linkersymbol` is not
    /// available in inline assembly).
    function _stageTrig(State memory s) private pure {
        address trig = address(Trig256);
        assembly {
            mstore(add(s, 2112), trig)
        }
    }

    // ---- SAVE/RESTORE (0x50/0x51) -------------------------------------------

    /// SAVE: raw copy of the contiguous ma..c3y State block into the save
    /// stack (bump-allocated unzeroed in _init; see the allocation site).
    function _save(State memory s) private pure {
        uint256 depth = s.saveDepth;
        if (depth >= MAX_SAVE_DEPTH) revert KVMError(12); // SaveDepthExceeded
        uint256[] memory sv = s.saves;
        assembly {
            let src := add(s, _STATE_SAVE_OFF)
            let dst := add(add(sv, 0x20), mul(depth, mul(SAVE_WORDS, 0x20)))
            for { let i := 0 } lt(i, 0x1e0) { i := add(i, 0x20) } {
                mstore(add(dst, i), mload(add(src, i)))
            }
            let sty := add(s, _STATE_STYLE_OFF)
            mstore(
                add(dst, 0x1e0),
                or(
                    or(
                        or(mload(sty), shl(32, mload(add(sty, 0x20)))),
                        or(shl(40, mload(add(sty, 0x40))), shl(72, mload(add(sty, 0x60))))
                    ),
                    or(
                        // clipSet is a 0/1/2 MODE (2 = CLIPRECTT), so it takes
                        // TWO bits (74..75). brush/blend/cap/join follow at
                        // 76/84/92/100.
                        or(shl(73, mload(add(sty, 0x80))), shl(74, mload(add(sty, 0xa0)))),
                        or(
                            or(shl(76, mload(add(s, 2208))), shl(84, mload(add(s, 2240)))),
                            or(shl(92, mload(add(s, 2272))), shl(100, mload(add(s, 2304))))
                        )
                    )
                )
            )
            // GFILL/FFILL fill-mode state (SAVE/RESTORE-scoped like every
            // style): 2 words per depth in the shared bank. The FIRST SAVE
            // allocates the bank HERE (the single allocation site, for
            // EIP-170). A save without a gradient or field writes 0/0, so
            // flatOut is byte-identical whether or not a fill mode was ever
            // armed.
            let gb := mload(add(s, 2528))
            if iszero(gb) {
                gb := mload(0x40)
                mstore(0x40, add(gb, 0x1000))
                calldatacopy(gb, calldatasize(), 0x1000)
                mstore(add(s, 2528), gb)
            }
            let gslot := add(gb, shl(6, depth))
            mstore(gslot, mload(add(s, 2464)))
            mstore(add(gslot, 0x20), mload(add(s, 2496)))
        }
        unchecked {
            s.saveDepth = depth + 1;
        }
    }

    function _restore(State memory s) private pure {
        uint256 depth = s.saveDepth;
        if (depth == 0) revert KVMError(13); // RestoreWithoutSave
        unchecked {
            depth -= 1;
        }
        uint256[] memory sv = s.saves;
        assembly {
            let src := add(add(sv, 0x20), mul(depth, mul(SAVE_WORDS, 0x20)))
            let dst := add(s, _STATE_SAVE_OFF)
            for { let i := 0 } lt(i, 0x1e0) { i := add(i, 0x20) } {
                mstore(add(dst, i), mload(add(src, i)))
            }
            let w := mload(add(src, 0x1e0))
            let sty := add(s, _STATE_STYLE_OFF)
            mstore(sty, and(w, 0xffffffff))
            mstore(add(sty, 0x20), and(shr(32, w), 1))
            mstore(add(sty, 0x40), and(shr(40, w), 0xffffffff))
            mstore(add(sty, 0x60), and(shr(72, w), 1))
            mstore(add(sty, 0x80), and(shr(73, w), 1))
            // clipSet: a 2-bit 0/1/2 mode. A 1-bit mask could not tell mode
            // 2 (CLIPRECTT) from mode 1, so it takes the full 2 bits.
            mstore(add(sty, 0xa0), and(shr(74, w), 3))
            mstore(add(s, 2208), and(shr(76, w), 0xff))
            mstore(add(s, 2240), and(shr(84, w), 0xff))
            mstore(add(s, 2272), and(shr(92, w), 0xff))
            mstore(add(s, 2304), and(shr(100, w), 0xff))
            // GFILL gradient state: restore from the bank when it exists
            // (slots of saves taken before a GFILL restore "no gradient")
            let gb := mload(add(s, 2528))
            if gb {
                let gslot := add(gb, shl(6, depth))
                mstore(add(s, 2464), mload(gslot))
                mstore(add(s, 2496), mload(add(gslot, 0x20)))
            }
        }
        s.saveDepth = depth;
    }

    function _word(bytes memory data, uint256 off) private pure returns (uint256 w) {
        assembly {
            w := mload(add(add(data, 0x20), off))
        }
    }

    // The output buffer grows by doubling, with a 32-byte slack for word
    // writes (see ensure_out and w8/w16/w32/w64 in _warmOps).
}

/// @notice The stepped interpreter core for pencil-family programs (NOISE
///         kinds 0 and 1): the forked interpreter plus the KFI1 flat-image
///         codec. It is NOT the public protocol surface. Callers use
///         KVMPencilStepRunner.executeChunk, which holds the KSN wire codec
///         (KSN7/KSN8 included) and the linear-memory write-delta diff. The
///         flat image is an internal format with no compatibility promise.
/// @dev    Stateless and ownerless: no storage, no admin, no upgrade path.
///         The SinLut256 blob is the ONE shared SSTORE2 data contract at
///         SINLUT (see SinLutSingleton), deployed once per network at a
///         deterministic CREATE2 address.
contract KVMStepCore4 {
    address private immutable sinLut;
    // NoiseV1Ext (kind 0) is a RUNTIME address, never a baked link: a
    // deployment can point the core at a substitute noise without
    // recompiling, and address(0) makes kind 0 trap at NOISEINIT. Kind 1
    // staticcalls the CREATE2 constant GRADNOISE.
    address private immutable noiseLib;

    /// @param noiseLib_ The NoiseV1Ext address, or address(0) for a core
    ///                  where NOISE kind 0 traps.
    constructor(address noiseLib_) {
        sinLut = SINLUT;
        noiseLib = noiseLib_;
    }

    /// @notice Run one bounded chunk of a KVM1 program on this core,
    ///         resuming from a flat image.
    /// @dev The trusted-input kernel entry point. KVMPencilStepRunner
    ///      validates the program header, the wire snapshot, and the blob
    ///      geometry before it calls in. An interpreter fault here reverts
    ///      the whole call with KVMError (mostly the bare selector). The
    ///      unnamed bytes[] parameter is the blobs array [memImage,
    ///      noiseTable, pathBlob], read in place from calldata inside
    ///      KVMS4.executeChunk (the head seam described there). noiseTable
    ///      is read only for NOISE kind 0. The parameter is unnamed so the
    ///      ABI decoder emits no pointer-validation code (EIP-170).
    /// @param program    A KVM1 container: header, palette, data segment,
    ///                   code.
    /// @param seed       The int32 run seed.
    /// @param params     Values for the PARAM ops. A missing index reads 0.
    /// @param flatIn     The KFI1 flat image to resume from (the Runner's
    ///                   genesis image on a fresh run).
    /// @param stepBudget The yield ceiling for this chunk. The Runner
    ///                   enforces at least 1.
    /// @return reason      0 = done, 1 = step budget exhausted (call again
    ///                     with flatOut to continue).
    /// @return chunkStream This chunk's draw-stream fragment (the finishing
    ///                     chunk's fragment ends with the 0xB1 end record).
    /// @return flatOut     The KFI1 image to resume from (empty when reason
    ///                     is 0). Its tail holds the sparse memory write set
    ///                     and its path section holds the appended path tail,
    ///                     for the memDelta and pathDelta of the Runner.
    function runChunk(
        bytes calldata program,
        int32 seed,
        int64[] calldata params,
        bytes calldata flatIn,
        bytes[] calldata, /* blobs = [memImage, noiseTable, pathBlob] */
        uint256 stepBudget
    ) external view returns (uint256 reason, bytes memory chunkStream, bytes memory flatOut) {
        // The unnamed bytes[] (blobs) is consumed INSIDE KVMS4.executeChunk,
        // read off the fixed ABI head slot 4 (0x84) of this function; see
        // the @dev note above. One array, not three bytes parameters, keeps
        // this wrapper under the 16-slot stack of the legacy pipeline.
        return KVMS4.executeChunk(program, seed, params, flatIn, stepBudget, sinLut, noiseLib);
    }
}

lib/kohi-fixmath/src/Errors.sol

// SPDX-License-Identifier: MIT
/* Copyright (c) Kohi Art Community, Inc. All rights reserved. */

/*
/*
///////////////////////////////////////////////////////////////////////////////////
//                                                                               //
//     @@@@@@@@@@@@@@                        @@@@                                // 
//               @@@@                        @@@@ @@@@@@@@                       // 
//               @@@@    @@@@@@@@@@@@@@@@    @@@@@@@          @@@@@@@@@@@@@@@@   // 
//               @@@@                        @@@@                                // 
//     @@@@@@@@@@@@@@                        @@@@@@@@@@@@@                       // 
//               @@@@                          @@@@@@@@@@@                       // 
//                                                                               //
///////////////////////////////////////////////////////////////////////////////////
*/

pragma solidity ^0.8.13;

/// @notice Custom errors shared by the Fix64 / Trig256 fixed-point library.

/// @notice An index or argument fell outside the range a function accepts.
error ArgumentOutOfRange();

/// @notice A division was attempted with a zero divisor.
error AttemptedToDivideByZero();

/// @notice A function that requires a non-negative input received a negative one.
error NegativeValuePassed();

lib/kohi-fixmath/src/Fix64.sol

// SPDX-License-Identifier: MIT
/* Copyright (c) Kohi Art Community, Inc. All rights reserved. */

/*
/*
///////////////////////////////////////////////////////////////////////////////////
//                                                                               //
//     @@@@@@@@@@@@@@                        @@@@                                //
//               @@@@                        @@@@ @@@@@@@@                       //
//               @@@@    @@@@@@@@@@@@@@@@    @@@@@@@          @@@@@@@@@@@@@@@@   //
//               @@@@                        @@@@                                //
//     @@@@@@@@@@@@@@                        @@@@@@@@@@@@@                       //
//               @@@@                          @@@@@@@@@@@                       //
//                                                                               //
///////////////////////////////////////////////////////////////////////////////////
*/

pragma solidity ^0.8.13;

/*
    Fix64: signed fixed-point arithmetic in Q31.32 format (a 64-bit two's
    complement integer with 32 fractional bits, so 1.0 is represented as
    1 << 32). This library provides the core operators, add/sub/mul/div,
    floor/round, sign/abs, min/max, and clamping/mapping helpers, that the
    rest of this codebase's trigonometric and logarithmic functions build on.

    exp: Adapted from Petteri Aimonen's libfixmath

    See: https://github.com/PetteriAimonen/libfixmath
         https://github.com/PetteriAimonen/libfixmath/blob/master/LICENSE

    other functions: Adapted from Andre Slupik's FixedMath.NET
                     https://github.com/asik/FixedMath.Net/blob/master/LICENSE.txt

    THIRD PARTY NOTICES:
    ====================

    libfixmath is Copyright (c) 2011-2021 Flatmush <[email protected]>,
    Petteri Aimonen <[email protected]>, & libfixmath AUTHORS

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.

    Copyright 2012 André Slupik

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    This project uses code from the log2fix library, which is under the following license:
    The MIT License (MIT)

    Copyright (c) 2015 Dan Moulding

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    IN THE SOFTWARE.
*/

/*
    The arithmetic below runs inside `unchecked` blocks so that int64/uint64
    operations wrap on overflow (two's complement), matching the original
    FixedMath.NET reference behavior. Solidity's default checked arithmetic
    would revert on exactly the wraps and saturations this format relies on.
*/

import "./Errors.sol";

/// @notice Signed fixed-point arithmetic in Q31.32 format (32 fractional bits).
library Fix64 {
    /// @notice Number of fractional bits in the Q31.32 representation.
    int64 public constant FRACTIONAL_PLACES = 32;
    /// @notice The fixed-point representation of 1.0 (1 << FRACTIONAL_PLACES).
    int64 public constant ONE = 4294967296; // 1 << FRACTIONAL_PLACES
    int64 public constant TWO = ONE * 2;
    int64 public constant THREE = ONE * 3;
    /// @notice Pi, in Q31.32.
    int64 public constant PI = 0x3243F6A88;
    /// @notice 2*Pi, in Q31.32.
    int64 public constant TWO_PI = 0x6487ED511;
    /// @notice The largest representable Fix64 value.
    int64 public constant MAX_VALUE = type(int64).max;
    /// @notice The smallest representable Fix64 value.
    int64 public constant MIN_VALUE = type(int64).min;
    /// @notice Pi / 2, in Q31.32.
    int64 public constant PI_OVER_2 = 0x1921FB544;

    /// @dev Counts leading zero bits in a 64-bit word, for bit-scan style
    /// routines. Does not handle x == 0 (the scan never terminates).
    function countLeadingZeros(uint64 x) internal pure returns (int64) {
        unchecked {
            int64 result = 0;
            while ((x & 0xF000000000000000) == 0) {
                result += 4;
                x <<= 4;
            }
            while ((x & 0x8000000000000000) == 0) {
                result += 1;
                x <<= 1;
            }
            return result;
        }
    }

    /*
     * div() and mul() are closed forms of the original FixedMath.NET
     * loop/decomposition implementations, bit-identical for every input:
     * the long division computes exactly floor(|x|*2^33/|y|) with
     * saturation and half-up rounding of the extra bit, and mul_256's
     * four-part decomposition absorbs its intermediate wraps mod 2^64.
     */

    /// @notice Divides x by y in Q31.32, rounding the result half up.
    /// @dev Saturates to MAX_VALUE/MIN_VALUE on overflow.
    /// @return The fixed-point quotient x / y.
    /// @custom:reverts AttemptedToDivideByZero if y == 0.
    function div(int64 x, int64 y) internal pure returns (int64) {
        unchecked {
            if (y == 0) {
                revert AttemptedToDivideByZero();
            }

            uint256 ax = uint64(x >= 0 ? x : -x);
            uint256 ay = uint64(y >= 0 ? y : -y);
            uint256 q = (ax << 33) / ay;
            if (q > type(uint64).max) {
                return ((x ^ y) & MIN_VALUE) == 0 ? MAX_VALUE : MIN_VALUE;
            }
            int64 result = int64(uint64((q + 1) >> 1));
            if (((x ^ y) & MIN_VALUE) != 0) {
                result = -result;
            }

            return result;
        }
    }

    /// @notice Multiplies x by y in Q31.32.
    /// @dev Widens to int256 for the multiply, then rescales; wraps on
    /// overflow rather than saturating (matches the original reference).
    /// @return The fixed-point product x * y.
    function mul(int64 x, int64 y) internal pure returns (int64) {
        unchecked {
            return int64(int256((int256(x) * int256(y)) >> 32));
        }
    }

    /// @notice Multiplies two Q31.32 values without truncating to int64.
    /// @dev Splits each operand into high/low 32-bit halves and sums the
    /// four partial products, so the result stays exact in int256 instead
    /// of wrapping the way mul() does. Used where intermediate precision
    /// matters, e.g. squaring a value repeatedly in log2().
    /// @return The fixed-point product x * y as an int256.
    function mul_256(int256 x, int256 y) internal pure returns (int256) {
        unchecked {
            int256 xl = x;
            int256 yl = y;

            uint256 xlo = uint256((xl & int256(0x00000000FFFFFFFF)));
            int256 xhi = xl >> 32; // FRACTIONAL_PLACES
            uint256 ylo = uint256(yl & int256(0x00000000FFFFFFFF));
            int256 yhi = yl >> 32; // FRACTIONAL_PLACES

            uint256 lolo = xlo * ylo;
            int256 lohi = int256(xlo) * yhi;
            int256 hilo = xhi * int256(ylo);
            int256 hihi = xhi * yhi;

            uint256 loResult = lolo >> 32; // FRACTIONAL_PLACES
            int256 midResult1 = lohi;
            int256 midResult2 = hilo;
            int256 hiResult = hihi << 32; // FRACTIONAL_PLACES

            int256 sum = int256(loResult) + midResult1 + midResult2 + hiResult;

            return sum;
        }
    }

    /// @notice Truncates a Q31.32 value down to the nearest whole number.
    /// @dev Zeroes the fractional bits; rounds toward negative infinity.
    function floor(int256 x) internal pure returns (int64) {
        unchecked {
            return int64(x & 0xFFFFFFFF00000000);
        }
    }

    /// @notice Rounds a Q31.32 value to the nearest whole number.
    /// @dev Ties (fractional part exactly 0.5) round to even, matching
    /// IEEE-754 banker's rounding.
    function round(int256 x) internal pure returns (int256) {
        unchecked {
            int256 fractionalPart = x & 0x00000000FFFFFFFF;
            int256 integralPart = floor(x);
            if (fractionalPart < 0x80000000) return integralPart;
            if (fractionalPart > 0x80000000) return integralPart + ONE;
            if ((integralPart & ONE) == 0) return integralPart;
            return integralPart + ONE;
        }
    }

    /// @notice Subtracts y from x, saturating instead of wrapping on overflow.
    /// @return x - y, clamped to [MIN_VALUE, MAX_VALUE].
    function sub(int64 x, int64 y) internal pure returns (int64) {
        unchecked {
            int64 xl = x;
            int64 yl = y;
            int64 diff = xl - yl;
            if (((xl ^ yl) & (xl ^ diff) & MIN_VALUE) != 0)
                diff = xl < 0 ? MIN_VALUE : MAX_VALUE;
            return diff;
        }
    }

    /// @notice Adds x and y, saturating instead of wrapping on overflow.
    /// @return x + y, clamped to [MIN_VALUE, MAX_VALUE].
    function add(int64 x, int64 y) internal pure returns (int64) {
        unchecked {
            int64 xl = x;
            int64 yl = y;
            int64 sum = xl + yl;
            if ((~(xl ^ yl) & (xl ^ sum) & MIN_VALUE) != 0)
                sum = xl > 0 ? MAX_VALUE : MIN_VALUE;
            return sum;
        }
    }

    /// @notice The sign of x.
    /// @return -1, 0, or 1.
    function sign(int64 x) internal pure returns (int8) {
        return x == int8(0) ? int8(0) : x > int8(0) ? int8(1) : int8(-1);
    }

    /// @notice The absolute value of x.
    /// @dev Branchless via the sign-mask trick; MIN_VALUE has no positive
    /// counterpart and wraps back to itself under the unchecked negation.
    function abs(int64 x) internal pure returns (int64) {
        unchecked {
            int64 mask = x >> 63;
            return (x + mask) ^ mask;
        }
    }

    /// @notice The larger of a and b.
    function max(int64 a, int64 b) internal pure returns (int64) {
        return a >= b ? a : b;
    }

    /// @notice The smaller of a and b.
    function min(int64 a, int64 b) internal pure returns (int64) {
        return a < b ? a : b;
    }

    /// @notice Linearly maps n from the range [start1, stop1] to [start2, stop2],
    /// then clamps the result to that output range.
    /// @return The mapped and clamped value.
    /// @custom:reverts AttemptedToDivideByZero if start1 == stop1.
    function map(
        int64 n,
        int64 start1,
        int64 stop1,
        int64 start2,
        int64 stop2
    ) internal pure returns (int64) {
        int64 value = mul(
            div(sub(n, start1), sub(stop1, start1)),
            add(sub(stop2, start2), start2)
        );

        return
            start2 < stop2
                ? constrain(value, start2, stop2)
                : constrain(value, stop2, start2);
    }

    /// @notice Clamps n to the inclusive range [low, high].
    function constrain(
        int64 n,
        int64 low,
        int64 high
    ) internal pure returns (int64) {
        return max(min(n, high), low);
    }
}

lib/kohi-fixmath/src/SinLut256.sol

// SPDX-License-Identifier: MIT
/* Copyright (c) wattsy. Portions Copyright (c) Kohi Art Community, Inc. (MIT). */

/*
 * This is a generated Solidity artifact of Kohi's MIT SinLut256: a 256-entry
 * Q31.32 sine table over [0, PI/2]. The table values are Kohi's MIT-licensed
 * work; this generated file is released under MIT, retaining the original Kohi
 * MIT notice as MIT requires.
 */

/*
/*
///////////////////////////////////////////////////////////////////////////////////
//                                                                               //
//     @@@@@@@@@@@@@@                        @@@@                                //
//               @@@@                        @@@@ @@@@@@@@                       //
//               @@@@    @@@@@@@@@@@@@@@@    @@@@@@@          @@@@@@@@@@@@@@@@   //
//               @@@@                        @@@@                                //
//     @@@@@@@@@@@@@@                        @@@@@@@@@@@@@                       //
//               @@@@                          @@@@@@@@@@@                       //
//                                                                               //
///////////////////////////////////////////////////////////////////////////////////
*/

pragma solidity ^0.8.13;

/*
 * Generated: do not hand-edit. Value-identical to the original Kohi
 * SinLut256 table (256-entry Q31.32 sine LUT over [0, PI/2]), repacked
 * 4 entries per uint256 word so it inlines compactly. Boundary behavior
 * matches the original table's fallthrough: a negative index reads entry 1,
 * an index above 255 reads entry 255.
 */
library SinLut256 {
    /**
     * @notice Lookup table for computing the sine value for a given angle.
     * @param i The clamped and rounded angle integral to index into the table.
     * @return The sine value in fixed-point (Q31.32) space.
     */
    function sinlut(int256 i) internal pure returns (int64) {
        unchecked {
            if (i < 0) i = 1; // original tree fallthrough for negatives
            if (i > 255) i = 255; // and for overflow
            uint256 w = uint256(i) >> 2;
            uint256 lane = uint256(i) & 3;
            return int64(uint64(_word(w) >> ((3 - lane) << 6)));
        }
    }

    function _word(uint256 w) private pure returns (uint256) {
        if (w <= 31) {
            if (w <= 15) {
                if (w <= 7) {
                    if (w <= 3) {
                        if (w <= 1) {
                            if (w <= 0) {
                                return 0x0000000000000000000000000193b2c100000000032761960000000004bb0894;
                            } else {
                                return 0x00000000064ea3ce0000000007e22f59000000000975a749000000000b0907b3;
                            }
                        } else {
                            if (w <= 2) {
                                return 0x000000000c9c4cab000000000e2f7248000000000fc2749e0000000011554fc3;
                            } else {
                                return 0x0000000012e7ffce00000000147a80d400000000160cceee00000000179ee632;
                            }
                        }
                    } else {
                        if (w <= 5) {
                            if (w <= 4) {
                                return 0x000000001930c2b9000000001ac2609b000000001c53bbf1000000001de4d0d7;
                            } else {
                                return 0x000000001f759b6500000000210617b800000000229641eb000000002426161c;
                            }
                        } else {
                            if (w <= 6) {
                                return 0x0000000025b59067000000002744aced0000000028d367cb000000002a61bd23;
                            } else {
                                return 0x000000002befa917000000002d7d27c7000000002f0a3559000000003096cdf1;
                            }
                        }
                    }
                } else {
                    if (w <= 11) {
                        if (w <= 9) {
                            if (w <= 8) {
                                return 0x000000003222edb30000000033ae90c8000000003539b3580000000036c4518b;
                            } else {
                                return 0x00000000384e678d0000000039d7f18a000000003b60ebae000000003ce95229;
                            }
                        } else {
                            if (w <= 10) {
                                return 0x000000003e71212a000000003ff854e400000000417ee98a000000004304db50;
                            } else {
                                return 0x00000000448a266d00000000460ec718000000004792b98b000000004915fa02;
                            }
                        }
                    } else {
                        if (w <= 13) {
                            if (w <= 12) {
                                return 0x000000004a9884b9000000004c1a55ef000000004d9b69e5000000004f1bbcdc;
                            } else {
                                return 0x00000000509b4b1a00000000521a10e50000000053980a840000000055153442;
                            }
                        } else {
                            if (w <= 14) {
                                return 0x0000000056918a6b00000000580d094d000000005987ad38000000005b01727f;
                            } else {
                                return 0x000000005c7a5576000000005df25274000000005f6965d20000000060df8bec;
                            }
                        }
                    }
                }
            } else {
                if (w <= 23) {
                    if (w <= 19) {
                        if (w <= 17) {
                            if (w <= 16) {
                                return 0x000000006254c11e0000000063c901ca00000000653c4a500000000066ae9716;
                            } else {
                                return 0x00000000681fe4840000000069902f01000000006aff72fc000000006c6dace2;
                            }
                        } else {
                            if (w <= 18) {
                                return 0x000000006ddad924000000006f46f4370000000070b1fa9200000000721be8ac;
                            } else {
                                return 0x000000007384bb030000000074ec6e15000000007652fe630000000077b86873;
                            }
                        }
                    } else {
                        if (w <= 21) {
                            if (w <= 20) {
                                return 0x00000000791ca8ca000000007a7fbbf4000000007be19e7c000000007d424cf4;
                            } else {
                                return 0x000000007ea1c3ee000000007fffffff00000000815cfdc20000000082b8b9d3;
                            }
                        } else {
                            if (w <= 22) {
                                return 0x00000000841330cf00000000856c5f5b0000000086c4421b00000000881ad5b8;
                            } else {
                                return 0x00000000897016df000000008ac4023e000000008c169489000000008d67ca76;
                            }
                        }
                    }
                } else {
                    if (w <= 27) {
                        if (w <= 25) {
                            if (w <= 24) {
                                return 0x000000008eb7a0bd000000009006141d000000009153215400000000929ec527;
                            } else {
                                return 0x0000000093e8fc5e000000009531c3c200000000967918230000000097bef652;
                            }
                        } else {
                            if (w <= 26) {
                                return 0x0000000099035b26000000009a464376000000009b87ac21000000009cc79207;
                            } else {
                                return 0x000000009e05f20c000000009f42c91a00000000a07e141b00000000a1b7d000;
                            }
                        }
                    } else {
                        if (w <= 29) {
                            if (w <= 28) {
                                return 0x00000000a2eff9bc00000000a4268e4800000000a55b8a9f00000000a68eebc1;
                            } else {
                                return 0x00000000a7c0aeb100000000a8f0d07700000000aa1f4e1e00000000ab4c24b7;
                            }
                        } else {
                            if (w <= 30) {
                                return 0x00000000ac77515400000000ada0d11000000000aec8a10400000000afeebe52;
                            } else {
                                return 0x00000000b113261f00000000b235d59300000000b356c9db00000000b476002a;
                            }
                        }
                    }
                }
            }
        } else {
            if (w <= 47) {
                if (w <= 39) {
                    if (w <= 35) {
                        if (w <= 33) {
                            if (w <= 32) {
                                return 0x00000000b59375b300000000b6af27b300000000b7c9136600000000b8e13611;
                            } else {
                                return 0x00000000b9f78cfb00000000bb0c156e00000000bc1eccbd00000000bd2fb03a;
                            }
                        } else {
                            if (w <= 34) {
                                return 0x00000000be3ebd4100000000bf4bf12f00000000c057496600000000c160c34d;
                            } else {
                                return 0x00000000c2685c5100000000c36e11e200000000c471e17400000000c573c883;
                            }
                        }
                    } else {
                        if (w <= 37) {
                            if (w <= 36) {
                                return 0x00000000c673c48d00000000c771d31400000000c86df1a200000000c9681dc3;
                            } else {
                                return 0x00000000ca60550900000000cb56950b00000000cc4adb6400000000cd3d25b6;
                            }
                        } else {
                            if (w <= 38) {
                                return 0x00000000ce2d71a500000000cf1bbcdc00000000d008050b00000000d0f247e5;
                            } else {
                                return 0x00000000d1da832500000000d2c0b48800000000d3a4d9d300000000d486f0ce;
                            }
                        }
                    }
                } else {
                    if (w <= 43) {
                        if (w <= 41) {
                            if (w <= 40) {
                                return 0x00000000d566f74600000000d644eb0f00000000d720ca0100000000d7fa91f8;
                            } else {
                                return 0x00000000d8d240d800000000d9a7d48800000000da7b4af500000000db4ca210;
                            }
                        } else {
                            if (w <= 42) {
                                return 0x00000000dc1bd7d300000000dce8ea3800000000ddb3d74200000000de7c9cf9;
                            } else {
                                return 0x00000000df43396900000000e007aaa500000000e0c9eec300000000e18a03e1;
                            }
                        }
                    } else {
                        if (w <= 45) {
                            if (w <= 44) {
                                return 0x00000000e247e82100000000e30399ab00000000e3bd16ad00000000e4745d57;
                            } else {
                                return 0x00000000e5296be400000000e5dc409100000000e68cd9a100000000e73b355d;
                            }
                        } else {
                            if (w <= 46) {
                                return 0x00000000e7e7521300000000e8912e1800000000e938c7c400000000e9de1d77;
                            } else {
                                return 0x00000000ea812d9700000000eb21f68d00000000ebc076ca00000000ec5cacc3;
                            }
                        }
                    }
                }
            } else {
                if (w <= 55) {
                    if (w <= 51) {
                        if (w <= 49) {
                            if (w <= 48) {
                                return 0x00000000ecf696f400000000ed8e33df00000000ee23820900000000eeb68001;
                            } else {
                                return 0x00000000ef472c5800000000efd585a700000000f0618a8c00000000f0eb39aa;
                            }
                        } else {
                            if (w <= 50) {
                                return 0x00000000f17291ab00000000f1f7913e00000000f27a371900000000f2fa81f8;
                            } else {
                                return 0x00000000f378709a00000000f3f401c600000000f46d344a00000000f4e406f8;
                            }
                        }
                    } else {
                        if (w <= 53) {
                            if (w <= 52) {
                                return 0x00000000f55878a900000000f5ca883b00000000f63a349100000000f6a77c98;
                            } else {
                                return 0x00000000f7125f3e00000000f77adb7a00000000f7e0f04900000000f8449cac;
                            }
                        } else {
                            if (w <= 54) {
                                return 0x00000000f8a5dfab00000000f904b85500000000f96125bd00000000f9bb26ff;
                            } else {
                                return 0x00000000fa12bb3900000000fa67e19300000000faba993900000000fb0ae15c;
                            }
                        }
                    }
                } else {
                    if (w <= 59) {
                        if (w <= 57) {
                            if (w <= 56) {
                                return 0x00000000fb58b93500000000fba4200300000000fbed150b00000000fc339795;
                            } else {
                                return 0x00000000fc77a6f500000000fcb9427f00000000fcf8699100000000fd351b8e;
                            }
                        } else {
                            if (w <= 58) {
                                return 0x00000000fd6f57df00000000fda71df300000000fddc6d4000000000fe0f4540;
                            } else {
                                return 0x00000000fe3fa57600000000fe6d8d6900000000fe98fca700000000fec1f2c4;
                            }
                        }
                    } else {
                        if (w <= 61) {
                            if (w <= 60) {
                                return 0x00000000fee86f5a00000000ff0c720a00000000ff2dfa7900000000ff4d0855;
                            } else {
                                return 0x00000000ff699b4f00000000ff83b32200000000ff9b4f8d00000000ffb07054;
                            }
                        } else {
                            if (w <= 62) {
                                return 0x00000000ffc3154300000000ffd33e2b00000000ffe0eae500000000ffec1b4f;
                            } else {
                                return 0x00000000fff4cf4c00000000fffb06c700000000fffec1b10000000100000000;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @notice sinlut() against a memory-resident copy of the table (entry i
     *         at lutPtr + i*8, big-endian: the table() blob staged verbatim,
     *         with >= 24 bytes of readable slack after it for the tail mload).
     *         Value- and boundary-identical to sinlut(i); costs one mload
     *         instead of the ~2.6 KB selection tree, for callers that need
     *         to stay under a contract size limit such as EIP-170.
     */
    function sinlut(uint256 lutPtr, int256 i) internal pure returns (int64 v) {
        unchecked {
            if (i < 0) i = 1; // original tree fallthrough for negatives
            if (i > 255) i = 255; // and for overflow
            assembly {
                v := shr(192, mload(add(lutPtr, shl(3, i))))
            }
        }
    }

    /// @notice The full table as one blob (entry i at byte i*8, big-endian),
    ///         for staging into an SSTORE2 data contract at deploy time.
    ///         Reference it from constructors only, so the 2 KB rides in
    ///         initcode and never counts against the runtime size limit.
    function table() internal pure returns (bytes memory) {
        return
            hex"0000000000000000000000000193b2c100000000032761960000000004bb089400000000064ea3ce0000000007e22f59000000000975a749000000000b0907b3000000000c9c4cab000000000e2f7248000000000fc2749e0000000011554fc30000000012e7ffce00000000147a80d400000000160cceee00000000179ee632000000001930c2b9000000001ac2609b000000001c53bbf1000000001de4d0d7000000001f759b6500000000210617b800000000229641eb000000002426161c0000000025b59067000000002744aced0000000028d367cb000000002a61bd23000000002befa917000000002d7d27c7000000002f0a3559000000003096cdf1000000003222edb30000000033ae90c8000000003539b3580000000036c4518b00000000384e678d0000000039d7f18a000000003b60ebae000000003ce95229000000003e71212a000000003ff854e400000000417ee98a000000004304db5000000000448a266d00000000460ec718000000004792b98b000000004915fa02000000004a9884b9000000004c1a55ef000000004d9b69e5000000004f1bbcdc00000000509b4b1a00000000521a10e50000000053980a8400000000551534420000000056918a6b00000000580d094d000000005987ad38000000005b01727f000000005c7a5576000000005df25274000000005f6965d20000000060df8bec000000006254c11e0000000063c901ca00000000653c4a500000000066ae971600000000681fe4840000000069902f01000000006aff72fc000000006c6dace2000000006ddad924000000006f46f4370000000070b1fa9200000000721be8ac000000007384bb030000000074ec6e15000000007652fe630000000077b8687300000000791ca8ca000000007a7fbbf4000000007be19e7c000000007d424cf4000000007ea1c3ee000000007fffffff00000000815cfdc20000000082b8b9d300000000841330cf00000000856c5f5b0000000086c4421b00000000881ad5b800000000897016df000000008ac4023e000000008c169489000000008d67ca76000000008eb7a0bd000000009006141d000000009153215400000000929ec5270000000093e8fc5e000000009531c3c200000000967918230000000097bef6520000000099035b26000000009a464376000000009b87ac21000000009cc79207000000009e05f20c000000009f42c91a00000000a07e141b00000000a1b7d00000000000a2eff9bc00000000a4268e4800000000a55b8a9f00000000a68eebc100000000a7c0aeb100000000a8f0d07700000000aa1f4e1e00000000ab4c24b700000000ac77515400000000ada0d11000000000aec8a10400000000afeebe5200000000b113261f00000000b235d59300000000b356c9db00000000b476002a00000000b59375b300000000b6af27b300000000b7c9136600000000b8e1361100000000b9f78cfb00000000bb0c156e00000000bc1eccbd00000000bd2fb03a00000000be3ebd4100000000bf4bf12f00000000c057496600000000c160c34d00000000c2685c5100000000c36e11e200000000c471e17400000000c573c88300000000c673c48d00000000c771d31400000000c86df1a200000000c9681dc300000000ca60550900000000cb56950b00000000cc4adb6400000000cd3d25b600000000ce2d71a500000000cf1bbcdc00000000d008050b00000000d0f247e500000000d1da832500000000d2c0b48800000000d3a4d9d300000000d486f0ce00000000d566f74600000000d644eb0f00000000d720ca0100000000d7fa91f800000000d8d240d800000000d9a7d48800000000da7b4af500000000db4ca21000000000dc1bd7d300000000dce8ea3800000000ddb3d74200000000de7c9cf900000000df43396900000000e007aaa500000000e0c9eec300000000e18a03e100000000e247e82100000000e30399ab00000000e3bd16ad00000000e4745d5700000000e5296be400000000e5dc409100000000e68cd9a100000000e73b355d00000000e7e7521300000000e8912e1800000000e938c7c400000000e9de1d7700000000ea812d9700000000eb21f68d00000000ebc076ca00000000ec5cacc300000000ecf696f400000000ed8e33df00000000ee23820900000000eeb6800100000000ef472c5800000000efd585a700000000f0618a8c00000000f0eb39aa00000000f17291ab00000000f1f7913e00000000f27a371900000000f2fa81f800000000f378709a00000000f3f401c600000000f46d344a00000000f4e406f800000000f55878a900000000f5ca883b00000000f63a349100000000f6a77c9800000000f7125f3e00000000f77adb7a00000000f7e0f04900000000f8449cac00000000f8a5dfab00000000f904b85500000000f96125bd00000000f9bb26ff00000000fa12bb3900000000fa67e19300000000faba993900000000fb0ae15c00000000fb58b93500000000fba4200300000000fbed150b00000000fc33979500000000fc77a6f500000000fcb9427f00000000fcf8699100000000fd351b8e00000000fd6f57df00000000fda71df300000000fddc6d4000000000fe0f454000000000fe3fa57600000000fe6d8d6900000000fe98fca700000000fec1f2c400000000fee86f5a00000000ff0c720a00000000ff2dfa7900000000ff4d085500000000ff699b4f00000000ff83b32200000000ff9b4f8d00000000ffb0705400000000ffc3154300000000ffd33e2b00000000ffe0eae500000000ffec1b4f00000000fff4cf4c00000000fffb06c700000000fffec1b10000000100000000";
    }
}

lib/kohi-fixmath/src/Trig256.sol

// SPDX-License-Identifier: MIT
/* Copyright (c) Kohi Art Community, Inc. All rights reserved. */

/*
/*
///////////////////////////////////////////////////////////////////////////////////
//                                                                               //
//     @@@@@@@@@@@@@@                        @@@@                                //
//               @@@@                        @@@@ @@@@@@@@                       //
//               @@@@    @@@@@@@@@@@@@@@@    @@@@@@@          @@@@@@@@@@@@@@@@   //
//               @@@@                        @@@@                                //
//     @@@@@@@@@@@@@@                        @@@@@@@@@@@@@                       //
//               @@@@                          @@@@@@@@@@@                       //
//                                                                               //
///////////////////////////////////////////////////////////////////////////////////
*/
pragma solidity ^0.8.13;

import "./Fix64.sol";
import "./SinLut256.sol";

/*
    Trig256: trigonometric, logarithmic, and exponential functions over the
    Fix64 Q31.32 fixed-point format. sin/cos are computed via range reduction
    plus a 256-entry lookup table with linear interpolation (see SinLut256.sol);
    log2/log/exp use the power-series and binary-logarithm algorithms below;
    acos/atan/atan2 are series approximations adapted from FixedMath.NET.

    exp: Adapted from Petteri Aimonen's libfixmath

    See: https://github.com/PetteriAimonen/libfixmath
         https://github.com/PetteriAimonen/libfixmath/blob/master/LICENSE

    other functions: Adapted from Andre Slupik's FixedMath.NET
                     https://github.com/asik/FixedMath.Net/blob/master/LICENSE.txt

    THIRD PARTY NOTICES:
    ====================

    libfixmath is Copyright (c) 2011-2021 Flatmush <[email protected]>,
    Petteri Aimonen <[email protected]>, & libfixmath AUTHORS

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.

    Copyright 2012 André Slupik

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    This project uses code from the log2fix library, which is under the following license:
    The MIT License (MIT)

    Copyright (c) 2015 Dan Moulding

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    IN THE SOFTWARE.
*/

/*
    sin/cos/sqrt/clamp bodies below run inside `unchecked` blocks so
    int64/uint64 arithmetic wraps on overflow, matching the original
    reference implementation. See Fix64.sol for the same convention.
*/

/// @notice Trigonometric, logarithmic, and exponential functions over Fix64.
library Trig256 {
    int64 private constant LARGE_PI = 7244019458077122842;
    /// @dev ln(2) in Q31.32, used to convert log2() results to natural log.
    int64 private constant LN2 = 0xB17217F7;
    /// @dev Largest input to exp() that does not saturate the Q31.32 range.
    int64 private constant LN_MAX = 0x157CD0E702;
    /// @dev Smallest input to exp() before the result underflows to zero.
    int64 private constant LN_MIN = -0x162E42FEFA;
    /// @dev The value exp() returns as a fast-path shortcut for x == ONE,
    /// preserved bit-for-bit from the reference implementation.
    int64 private constant E = -0x2B7E15162;

    // Fix64.div((256 - 1) * Fix64.ONE, Fix64.PI_OVER_2), precomputed: the
    // long-division routine is far too expensive to rerun per sin() call.
    int64 private constant LUT_INTERVAL = 697236581115;

    /// @notice Sine of x, computed via range reduction into [0, PI/2] and a
    /// 256-entry lookup table with linear interpolation between entries.
    /// @param x Angle in radians, Q31.32.
    /// @return Sine of x, Q31.32, in [-ONE, ONE].
    function sin(int64 x) internal pure returns (int64) {
        unchecked {
            (int64 clamped, bool flipHorizontal, bool flipVertical) = clamp(x);

            int64 lutInterval = LUT_INTERVAL;
            int256 rawIndex = Fix64.mul_256(clamped, lutInterval);
            int64 roundedIndex = int64(Fix64.round(rawIndex));
            int64 indexError = Fix64.sub(int64(rawIndex), roundedIndex);

            roundedIndex = roundedIndex >> 32; /* FRACTIONAL_PLACES */

            int64 nearestValueIndex = flipHorizontal
                ? (256 - 1) - roundedIndex
                : roundedIndex;

            int64 nearestValue = SinLut256.sinlut(nearestValueIndex);

            int64 secondNearestValue = SinLut256.sinlut(
                flipHorizontal
                    ? (256 - 1) - roundedIndex - Fix64.sign(indexError)
                    : roundedIndex + Fix64.sign(indexError)
            );

            int64 delta = Fix64.mul(
                indexError,
                Fix64.abs(Fix64.sub(nearestValue, secondNearestValue))
            );
            int64 interpolatedValue = nearestValue +
                (flipHorizontal ? -delta : delta);
            int64 finalValue = flipVertical
                ? -interpolatedValue
                : interpolatedValue;

            return finalValue;
        }
    }

    /// @notice Cosine of x, via a phase shift into sin().
    /// @param x Angle in radians, Q31.32.
    /// @return Cosine of x, Q31.32, in [-ONE, ONE].
    function cos(int64 x) internal pure returns (int64) {
        unchecked {
            int64 xl = x;
            int64 angle;
            if (xl > 0) {
                angle = Fix64.add(xl, Fix64.sub(0 - Fix64.PI, Fix64.PI_OVER_2));
            } else {
                angle = Fix64.add(xl, Fix64.PI_OVER_2);
            }
            return sin(angle);
        }
    }

    /*
     * sin/cos against a memory-resident copy of the SinLut256 table (see
     * SinLut256.table()), for callers that cannot afford the ~2.6 KB inlined
     * selection tree that sinlut(int256) compiles to, e.g. contracts close to
     * the EIP-170 runtime size limit. Statement-for-statement identical to
     * sin(x)/cos(x) above; only the LUT access differs, and results are
     * bit-identical. If you change one variant, mirror the other.
     */
    /// @notice Sine of x, reading the sine table from memory at lutPtr instead
    /// of the inlined selection tree (see SinLut256.table()).
    /// @param x Angle in radians, Q31.32.
    /// @param lutPtr Pointer to a 256*8-byte, big-endian copy of the sine table.
    /// @return Sine of x, Q31.32, bit-identical to sin(x).
    function sin(int64 x, uint256 lutPtr) internal pure returns (int64) {
        unchecked {
            (int64 clamped, bool flipHorizontal, bool flipVertical) = clamp(x);

            int64 lutInterval = LUT_INTERVAL;
            int256 rawIndex = Fix64.mul_256(clamped, lutInterval);
            int64 roundedIndex = int64(Fix64.round(rawIndex));
            int64 indexError = Fix64.sub(int64(rawIndex), roundedIndex);

            roundedIndex = roundedIndex >> 32; /* FRACTIONAL_PLACES */

            int64 nearestValueIndex = flipHorizontal
                ? (256 - 1) - roundedIndex
                : roundedIndex;

            int64 nearestValue = SinLut256.sinlut(lutPtr, nearestValueIndex);

            int64 secondNearestValue = SinLut256.sinlut(
                lutPtr,
                flipHorizontal
                    ? (256 - 1) - roundedIndex - Fix64.sign(indexError)
                    : roundedIndex + Fix64.sign(indexError)
            );

            int64 delta = Fix64.mul(
                indexError,
                Fix64.abs(Fix64.sub(nearestValue, secondNearestValue))
            );
            int64 interpolatedValue = nearestValue +
                (flipHorizontal ? -delta : delta);
            int64 finalValue = flipVertical
                ? -interpolatedValue
                : interpolatedValue;

            return finalValue;
        }
    }

    /// @notice Cosine of x, reading the sine table from memory at lutPtr.
    /// @param x Angle in radians, Q31.32.
    /// @param lutPtr Pointer to a 256*8-byte, big-endian copy of the sine table.
    /// @return Cosine of x, Q31.32, bit-identical to cos(x).
    function cos(int64 x, uint256 lutPtr) internal pure returns (int64) {
        unchecked {
            int64 xl = x;
            int64 angle;
            if (xl > 0) {
                angle = Fix64.add(xl, Fix64.sub(0 - Fix64.PI, Fix64.PI_OVER_2));
            } else {
                angle = Fix64.add(xl, Fix64.PI_OVER_2);
            }
            return sin(angle, lutPtr);
        }
    }

    /// @notice Square root of a Q31.32 value.
    /// @dev Digit-by-digit binary square root, run twice over the 64-bit
    /// word (once per 32-bit half) so the result comes out correctly
    /// scaled in Q31.32 rather than needing a separate rescale step.
    /// @custom:reverts NegativeValuePassed if x < 0.
    function sqrt(int64 x) internal pure returns (int64) {
        unchecked {
            int64 xl = x;
            if (xl < 0) revert NegativeValuePassed();

            uint64 num = uint64(xl);
            uint64 result = uint64(0);
            uint64 bit = uint64(1) << (64 - 2);

            while (bit > num) bit >>= 2;
            for (uint8 i = 0; i < 2; ++i) {
                while (bit != 0) {
                    if (num >= result + bit) {
                        num -= result + bit;
                        result = (result >> 1) + bit;
                    } else {
                        result = result >> 1;
                    }

                    bit >>= 2;
                }

                if (i == 0) {
                    if (num > (uint64(1) << (64 / 2)) - 1) {
                        num -= result;
                        num = (num << (64 / 2)) - uint64(0x80000000);
                        result = (result << (64 / 2)) + uint64(0x80000000);
                    } else {
                        num <<= 64 / 2;
                        result <<= 64 / 2;
                    }

                    bit = uint64(1) << (64 / 2 - 2);
                }
            }

            if (num > result) ++result;
            return int64(result);
        }
    }

    /// @notice Base-2 logarithm of x, computed at int256 precision.
    /// @param x A positive Q31.32 value.
    /// @return log2(x) in Q31.32.
    /// @custom:reverts NegativeValuePassed if x <= 0.
    function log2_256(int256 x) public pure returns (int256) {
        if (x <= 0) {
            revert NegativeValuePassed();
        }

        // This implementation is based on Clay. S. Turner's fast binary logarithm
        // algorithm (C. S. Turner,  "A Fast Binary Logarithm Algorithm", IEEE Signal
        //     Processing Mag., pp. 124,140, Sep. 2010.)

        int256 b = 1 << 31; // FRACTIONAL_PLACES - 1
        int256 y = 0;

        int256 rawX = x;
        while (rawX < Fix64.ONE) {
            rawX <<= 1;
            y -= Fix64.ONE;
        }

        while (rawX >= Fix64.ONE << 1) {
            rawX >>= 1;
            y += Fix64.ONE;
        }

        int256 z = rawX;

        for (uint8 i = 0; i < 32 /* FRACTIONAL_PLACES */; i++) {
            z = Fix64.mul_256(z, z);
            if (z >= Fix64.ONE << 1) {
                z = z >> 1;
                y += b;
            }
            b >>= 1;
        }

        return y;
    }

    /// @notice Natural logarithm of x, computed at int256 precision.
    /// @param x A positive Q31.32 value.
    /// @return ln(x) in Q31.32.
    /// @custom:reverts NegativeValuePassed if x <= 0.
    function log_256(int256 x) public pure returns (int256) {
        return Fix64.mul_256(log2_256(x), LN2);
    }

    /// @notice Base-2 logarithm of x.
    /// @param x A positive Q31.32 value.
    /// @return log2(x) in Q31.32.
    /// @custom:reverts NegativeValuePassed if x <= 0.
    function log2(int64 x) public pure returns (int64) {
        if (x <= 0) revert NegativeValuePassed();

        // This implementation is based on Clay. S. Turner's fast binary logarithm
        // algorithm (C. S. Turner,  "A Fast Binary Logarithm Algorithm", IEEE Signal
        //     Processing Mag., pp. 124,140, Sep. 2010.)

        int64 b = 1 << 31; // FRACTIONAL_PLACES - 1
        int64 y = 0;

        int64 rawX = x;
        while (rawX < Fix64.ONE) {
            rawX <<= 1;
            y -= Fix64.ONE;
        }

        while (rawX >= Fix64.ONE << 1) {
            rawX >>= 1;
            y += Fix64.ONE;
        }

        int64 z = rawX;

        for (int32 i = 0; i < Fix64.FRACTIONAL_PLACES; i++) {
            z = Fix64.mul(z, z);
            if (z >= Fix64.ONE << 1) {
                z = z >> 1;
                y += b;
            }

            b >>= 1;
        }

        return y;
    }

    /// @notice Natural logarithm of x.
    /// @param x A positive Q31.32 value.
    /// @return ln(x) in Q31.32.
    /// @custom:reverts NegativeValuePassed if x <= 0.
    function log(int64 x) public pure returns (int64) {
        return Fix64.mul(log2(x), LN2);
    }

    /// @notice e raised to the power of x.
    /// @param x Exponent, Q31.32.
    /// @return exp(x) in Q31.32; MAX_VALUE if x is large enough to overflow,
    /// 0 if x is small enough to underflow.
    function exp(int64 x) public pure returns (int64) {
        if (x == 0) return Fix64.ONE;
        if (x == Fix64.ONE) return E;
        if (x >= LN_MAX) return Fix64.MAX_VALUE;
        if (x <= LN_MIN) return 0;

        /* The algorithm is based on the power series for exp(x):
         * http://en.wikipedia.org/wiki/Exponential_function#Formal_definition
         *
         * From term n, we get term n+1 by multiplying with x/n.
         * When the sum term drops to zero, we can stop summing.
         */

        // The power-series converges much faster on positive values
        // and exp(-x) = 1/exp(x).

        bool neg = (x < 0);
        if (neg) x = -x;

        int64 result = Fix64.add(int64(x), Fix64.ONE);
        int64 term = x;

        for (uint32 i = 2; i < 40; i++) {
            term = Fix64.mul(x, Fix64.div(term, int32(i) * Fix64.ONE));
            result = Fix64.add(result, int64(term));
            if (term == 0) break;
        }

        if (neg) {
            result = Fix64.div(Fix64.ONE, result);
        }

        return result;
    }

    /*
     * Compact cross-contract stubs for this library's cold `public` fns.
     * The functions stay public (deployed once in the linked Trig256
     * library); these wrappers replace solc's per-site delegatecall stubs
     * with one shared staticcall sequence: the callees are pure, so a
     * direct staticcall against the library address returns identical
     * bytes with none of the generated ABI ceremony. The fixed callees
     * always return exactly 32 bytes on success, so returndata length
     * needs no validation; failures bubble verbatim.
     */
    /// @dev Calls a single-int-argument public function on this library's own
    /// deployed code via staticcall, bypassing the ABI-encoded delegatecall
    /// stub solc would otherwise generate at each call site.
    function _ext1(bytes4 sel, int256 x) private view returns (int256 r) {
        address a = address(Trig256);
        assembly {
            let p := mload(0x40)
            mstore(p, sel)
            mstore(add(p, 4), x)
            if iszero(staticcall(gas(), a, p, 36, p, 32)) {
                returndatacopy(0, 0, returndatasize())
                revert(0, returndatasize())
            }
            r := mload(p)
        }
    }

    /// @dev Cross-contract call to log(), see _ext1.
    function extLog(int64 x) internal view returns (int64) {
        return int64(_ext1(Trig256.log.selector, x));
    }

    /// @dev Cross-contract call to exp(), see _ext1.
    function extExp(int64 x) internal view returns (int64) {
        return int64(_ext1(Trig256.exp.selector, x));
    }

    /// @dev Cross-contract call to acos(), see _ext1.
    function extAcos(int64 x) internal view returns (int64) {
        return int64(_ext1(Trig256.acos.selector, x));
    }

    /// @dev Cross-contract call to log_256(), see _ext1.
    function extLog256(int256 x) internal view returns (int256) {
        return _ext1(Trig256.log_256.selector, x);
    }

    /// @dev Cross-contract call to atan2(), same staticcall approach as
    /// _ext1 but inlined for the two-argument signature.
    function extAtan2(int64 y, int64 x) internal view returns (int64 r) {
        address a = address(Trig256);
        bytes4 sel = Trig256.atan2.selector;
        assembly {
            let p := mload(0x40)
            mstore(p, sel)
            mstore(add(p, 4), y)
            mstore(add(p, 36), x)
            if iszero(staticcall(gas(), a, p, 68, p, 32)) {
                returndatacopy(0, 0, returndatasize())
                revert(0, returndatasize())
            }
            r := mload(p)
        }
    }

    /// @dev Range-reduces x into [0, PI/2], the domain the sine lookup table
    /// covers, and records which reflections are needed to reconstruct the
    /// value in the original quadrant.
    /// @return clamped x reduced into [0, PI/2].
    /// @return flipHorizontal True if x fell in the second half of [0, PI].
    /// @return flipVertical True if x fell in [PI, 2*PI).
    function clamp(int64 x) internal pure returns (int64, bool, bool) {
        unchecked {
            int64 clamped2Pi = x;
            for (uint8 i = 0; i < 29; ++i) {
                clamped2Pi %= LARGE_PI >> i;
            }
            if (x < 0) {
                clamped2Pi += Fix64.TWO_PI;
            }

            bool flipVertical = clamped2Pi >= Fix64.PI;
            int64 clampedPi = clamped2Pi;
            while (clampedPi >= Fix64.PI) {
                clampedPi -= Fix64.PI;
            }

            bool flipHorizontal = clampedPi >= Fix64.PI_OVER_2;

            int64 clampedPiOver2 = clampedPi;
            if (clampedPiOver2 >= Fix64.PI_OVER_2)
                clampedPiOver2 -= Fix64.PI_OVER_2;

            return (clampedPiOver2, flipHorizontal, flipVertical);
        }
    }

    /// @notice Arc cosine of x, via atan(sqrt(1 - x^2) / x).
    /// @param x A Q31.32 value in [-ONE, ONE].
    /// @return result Angle in radians, Q31.32, in [0, PI].
    /// @custom:reverts "invalid range for x" if x is outside [-ONE, ONE].
    function acos(int64 x) public pure returns (int64 result) {
        if (x < -Fix64.ONE || x > Fix64.ONE) revert("invalid range for x");
        if (x == 0) return Fix64.PI_OVER_2;

        int64 t1 = Fix64.ONE - Fix64.mul(x, x);
        int64 t2 = Fix64.div(sqrt(t1), x);

        result = atan(t2);
        return x < 0 ? result + Fix64.PI : result;
    }

    /// @notice Arc tangent of z, via a continued-fraction series. Values
    /// with |z| > 1 are computed as PI/2 - atan(1/z) for faster convergence.
    /// @param z Q31.32.
    /// @return result Angle in radians, Q31.32, in (-PI/2, PI/2).
    function atan(int64 z) public pure returns (int64 result) {
        if (z == 0) return 0;

        bool neg = z < 0;
        if (neg) z = -z;

        int64 two = Fix64.TWO;
        int64 three = Fix64.THREE;

        bool invert = z > Fix64.ONE;
        if (invert) z = Fix64.div(Fix64.ONE, z);

        result = Fix64.ONE;
        int64 term = Fix64.ONE;

        int64 zSq = Fix64.mul(z, z);
        int64 zSq2 = Fix64.mul(zSq, two);
        int64 zSqPlusOne = Fix64.add(zSq, Fix64.ONE);
        int64 zSq12 = Fix64.mul(zSqPlusOne, two);
        int64 dividend = zSq2;
        int64 divisor = Fix64.mul(zSqPlusOne, three);

        for (uint8 i = 2; i < 30; ++i) {
            term = Fix64.mul(term, Fix64.div(dividend, divisor));
            result = Fix64.add(result, term);

            dividend = Fix64.add(dividend, zSq2);
            divisor = Fix64.add(divisor, zSq12);

            if (term == 0) break;
        }

        result = Fix64.mul(result, Fix64.div(z, zSqPlusOne));

        if (invert) {
            result = Fix64.sub(Fix64.PI_OVER_2, result);
        }

        if (neg) {
            result = -result;
        }

        return result;
    }

    /// @notice Angle of the point (x, y) from the positive x-axis, via a
    /// rational polynomial approximation (a separate algorithm from atan()).
    /// @param y Q31.32.
    /// @param x Q31.32.
    /// @return result Angle in radians, Q31.32, in (-PI, PI].
    function atan2(int64 y, int64 x) public pure returns (int64 result) {
        int64 e = 1202590848; /* 0.28 */
        int64 yl = y;
        int64 xl = x;

        if (xl == 0) {
            if (yl > 0) {
                return Fix64.PI_OVER_2;
            }
            if (yl == 0) {
                return 0;
            }
            return -Fix64.PI_OVER_2;
        }

        int64 z = Fix64.div(y, x);

        if (
            Fix64.add(Fix64.ONE, Fix64.mul(e, Fix64.mul(z, z))) ==
            type(int64).max
        ) {
            return y < 0 ? -Fix64.PI_OVER_2 : Fix64.PI_OVER_2;
        }

        if (Fix64.abs(z) < Fix64.ONE) {
            result = Fix64.div(
                z,
                Fix64.add(Fix64.ONE, Fix64.mul(e, Fix64.mul(z, z)))
            );
            if (xl < 0) {
                if (yl < 0) {
                    return Fix64.sub(result, Fix64.PI);
                }

                return Fix64.add(result, Fix64.PI);
            }
        } else {
            result = Fix64.sub(
                Fix64.PI_OVER_2,
                Fix64.div(z, Fix64.add(Fix64.mul(z, z), e))
            );

            if (yl < 0) {
                return Fix64.sub(result, Fix64.PI);
            }
        }
    }
}

lib/kohi/Fix64.sol

// SPDX-License-Identifier: MIT
// Re-export shim. The Fix64 fixed-point math is the kohi-fixmath library (MIT).
// This file gives its consumers (AggRaster, KohiStroke, KVMRender, KVMRenderV1,
// KVMVerts, Mesh3D, StampRaster) one stable import path for it.
//
// It exports Fix64 and the three custom errors of kohi-fixmath. Other code
// refers to AttemptedToDivideByZero by its selector. Each symbol is named
// explicitly.
pragma solidity ^0.8.13;

import {Fix64} from "kohi-fixmath/src/Fix64.sol";
import {ArgumentOutOfRange, AttemptedToDivideByZero, NegativeValuePassed} from "kohi-fixmath/src/Errors.sol";

lib/kohi/Trig256.sol

// SPDX-License-Identifier: MIT
// Re-export shim. The Trig256 trig, log and exp math is the kohi-fixmath library
// (MIT). This file gives its consumers (KVM, KVMInteractive, KVMStep, KVMTraits,
// KohiStroke, Mesh3D, StampRaster) one stable import path for it.
//
// It exports Trig256, Fix64, SinLut256 and the three custom errors. Some
// consumers (KVM, KVMInteractive, KVMStep, KVMTraits) use `Fix64.*` through this
// path only, so Fix64 is re-exported here. Every path resolves to the same
// kohi-fixmath declarations, so a symbol that also arrives through another shim
// does not collide.
pragma solidity ^0.8.13;

import {Trig256} from "kohi-fixmath/src/Trig256.sol";
import {Fix64} from "kohi-fixmath/src/Fix64.sol";
import {SinLut256} from "kohi-fixmath/src/SinLut256.sol";
import {ArgumentOutOfRange, AttemptedToDivideByZero, NegativeValuePassed} from "kohi-fixmath/src/Errors.sol";

src/GradNoiseSingleton.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */
pragma solidity ^0.8.13;

/* =============================================================================
 *  GRADNOISE · one gradient-noise library, one address, every network
 * =============================================================================
 *
 * NOISEINIT kind 1 is GradNoise: first-party gradient noise that every KVM
 * backend computes bit for bit. On chain, it is one shared library, deployed
 * once per network, as pure code with no state, at an address that any chain
 * can reproduce. This file holds that address and its derivation.
 *
 * Every unit that serves kind 1 (KVMRunner, KVMTraitsRunner,
 * KVMInteractiveRunner, KVMStepCore2, and StampRaster for field fills)
 * reaches GradNoise through this compile-time constant. It makes one STATICCALL
 * of grad(int32,uint256,int64,int64,int64), selector 0x1349e518, for each
 * noise sample. The address is NOT a constructor immutable. The two noise
 * kinds use different linkage:
 *
 *   - Kind 0 (NoiseV1Ext, LGPL-2.1-only) uses the `noiseLib` CONSTRUCTOR
 *     ARG. The runner reaches it by STATICCALL to a separate contract at an
 *     address given at construction. A deployment can use its own
 *     implementation without recompilation. The argument is also the
 *     deploy-time switch. With noiseLib = address(0), kind 0 traps. With the
 *     real library, one runner bytecode serves kinds {0,1}.
 *   - Kind 1 is first-party and its implementation is frozen. Its output is
 *     checked bit for bit against a cross-backend reference. Its address is
 *     pinned like the SinLut256 table (SinLutSingleton). A different
 *     implementation is a new kind, never a relink.
 *
 * DERIVATION, reproducible on any chain:
 *
 *   proxy     = 0x4e59b44847b379578588920cA78FbF26c0B4956C
 *               the canonical deterministic-deployment proxy: it executes
 *               CREATE2(0, initcode, salt) with the first 32 calldata bytes
 *               as the salt, and is already present on mainnet, sepolia,
 *               anvil, and the forge test/script EVM
 *
 *   salt      = keccak256("kohi.gradnoise.v1")
 *             = 0xaf234e95d20abe73c80a24b97db3b469bb49da89e4c4df28a13d56d54526ad59
 *
 *   initcode  = the GradNoise library's compiled creation code, 1,467 bytes
 *               under the pinned toolchain (solc 0.8.24, cancun, optimizer
 *               200, via_ir off, cbor_metadata false, bytecode_hash none);
 *               keccak256(initcode)
 *             = 0x1d8994a50a055a57839834aa137b525f705f74198abed1763782704ba08a5752
 *
 *   GRADNOISE = keccak256(0xff ++ proxy ++ salt ++ keccak256(initcode))[12:]
 *             = 0x3A0af0fbf84C4B36706569c687b864010242bf4e
 *
 * The deployed runtime at GRADNOISE is 1,414 bytes, in the standard solc
 * library deploy pattern:
 *
 *       0    1                      21                                  1414
 *       +----+----------------------+-----------------------------------+
 *       |0x73| GRADNOISE (20 bytes) | the library runtime: grad(), the  |
 *       |PUSH|  call-protection slot| only entry point                  |
 *       +----+----------------------+-----------------------------------+
 *
 * Bytes [1..21) are the call-protection slot (the PUSH20 after the leading
 * 0x73). The slot holds GRADNOISE itself. `grad` is pure, so the protection
 * never blocks a STATICCALL.
 *
 * SINLUT is a raw data blob, independent of the compiler. This initcode is
 * compiled output. The address pins the exact frozen GradNoise source AND the
 * toolchain above. The kind-1 algorithm is frozen, so this is intended. A
 * check guards it: compile the source and replay the CREATE2. The result must
 * equal this address. Any source or compiler change shows up as a mismatch.
 *
 * GRADNOISE_CREATE2_PROXY, GRADNOISE_SALT and GRADNOISE_INITCODE_HASH are the
 * derivation inputs, shared by the deploy tooling and the test fixture. All
 * four constants are file-level with no getter. They add no bytecode to a
 * contract that does not reference them.
 */
address constant GRADNOISE = 0x3A0af0fbf84C4B36706569c687b864010242bf4e;

// Canonical deterministic-deployment proxy. Present on mainnet, sepolia,
// anvil, and the forge test/script EVM. SINLUT derives through the same proxy.
address constant GRADNOISE_CREATE2_PROXY = 0x4e59b44847b379578588920cA78FbF26c0B4956C;

// keccak256("kohi.gradnoise.v1"), as a literal. No hash runs at compile time.
bytes32 constant GRADNOISE_SALT = 0xaf234e95d20abe73c80a24b97db3b469bb49da89e4c4df28a13d56d54526ad59;

// keccak256 of the GradNoise creation code under the pinned toolchain. The
// deploy tooling checks that a fresh compile hashes to this value first.
bytes32 constant GRADNOISE_INITCODE_HASH = 0x1d8994a50a055a57839834aa137b525f705f74198abed1763782704ba08a5752;

src/PencilStep.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

pragma solidity ^0.8.13;

import "./PencilVM.sol";

/* =============================================================================
 *  PencilStep · the pure glue of the stepped pencil arm
 * =============================================================================
 *
 * The stepped core of the pencil family (KVMStepCore4) does not fit EIP-170
 * with the whole PENCIL (0xb0) arm inside it. This separately deployed
 * library holds the pure part of the arm. The core keeps the family's VM
 * state in its own memory and does the pops. These functions take the
 * popped operands (or the source words of a region) and return what the arm
 * needs: the checks, the paper, the installed region, and the stream
 * records. The semantics are exactly those of the one-shot arm
 * (KVMPencilRunner), sub-op for sub-op. Every fault reverts the bare
 * KVMError selector (0x4c49dedb), like every other interpreter fault, so the
 * order of the checks is not observable.
 *
 * A value "as Q16" is floor(v / 2^16). The records carry Q16, big-endian:
 *
 *   paper   0c | u8 r | u8 g | u8 b | u32 seed | i32 sheetMm
 *   region  0d | u8 slot | i32 kv wobAmp wobBias tolL
 *              | u16 npoly | npoly x (u8 n | n x (i32 x | i32 y))
 *              | u16 nterm | nterm x (u8 kind | i32 ax ay bx by a b)
 *
 * The SOURCE words of a region (int256[]) are the program's own values, in
 * the source layout of PencilVM:
 *
 *   kv | wobAmp | wobBias | tolL (Fix64)
 *   | np | np x (n | n x (x | y))
 *   | nt | nt x (kind | ax | ay | bx | by | a | b)
 *
 * The library holds no state and links PencilVM.
 */
library PencilStep {
    int256 internal constant PQ = 65536;

    function _fail() private pure {
        assembly {
            mstore(0x00, shl(224, 0x4c49dedb))
            revert(0x00, 0x04)
        }
    }

    /// @notice PAPER after its pops: the paper words and the step surcharge,
    ///         and with `check` also the traps and the record.
    /// @dev With `check`, reverts the bare KVMError on a canvas side over
    ///      4096, a channel outside 0..255, or a sheet outside [W/256, 16W]
    ///      mm or over 420 mm. Without `check` (a resume), the paper is only
    ///      built again and rec is empty.
    /// @param W     Canvas width in px.
    /// @param H     Canvas height in px.
    /// @param r     Red, the integer part of the popped value.
    /// @param g     Green, the integer part of the popped value.
    /// @param b     Blue, the integer part of the popped value.
    /// @param sd    The seed: the low 32 bits of the popped integer part.
    /// @param sheet The sheet width in mm, Q16.
    /// @param check True for the PAPER sub-op, false for a resume.
    /// @return P     The paper words (PencilVM.makePaper).
    /// @return extra The step surcharge of PAPER.
    /// @return rec   The 12-byte paper record (0x0c), or empty.
    function paper(int256 W, int256 H, int256 r, int256 g, int256 b, uint256 sd, int256 sheet, bool check)
        public
        pure
        returns (int256[11] memory P, uint256 extra, bytes memory rec)
    {
        if (check) {
            if (W > 4096 || H > 4096) _fail(); // canvas too large
            if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) _fail(); // invalid paper color
            if (!(sheet * 256 >= W * PQ && sheet <= 16 * W * PQ && sheet <= 420 * PQ)) _fail(); // invalid sheet width
            rec = abi.encodePacked(uint8(0x0c), uint8(uint256(r)), uint8(uint256(g)), uint8(uint256(b)), uint32(sd), uint32(uint256(sheet)));
        }
        (P, extra) = PencilVM.makePaper(W, H, sheet, sd);
    }

    function _inBox(int256 v) private pure returns (bool) {
        v >>= 16;
        return v >= -2048 * PQ && v < 6144 * PQ;
    }

    function _q(int256 v) private pure returns (int256 r) {
        r = v >> 16;
        if (r < -2147483648 || r > 2147483647) _fail();
    }

    /// @notice The checks of RTERM on one shade term.
    /// @dev Reverts the bare KVMError unless each value fits int32 Q16, each
    ///      end is inside the box [-2048, 6144) px, the span is at most 4096
    ///      px on each axis, an occlusion (kind 0) has a in [0, 16] and
    ///      b > 0, and a sliver (kind 1) has a < b. The caller checks the
    ///      kind (0..1) first.
    /// @param f The term: kind, ax, ay, bx, by, a, b (Fix64 after the kind).
    function term(int256[7] memory f) public pure {
        int256[7] memory q;
        for (uint256 i = 1; i < 7; ++i) q[i] = _q(f[i]);
        if (!_inBox(f[1]) || !_inBox(f[2]) || !_inBox(f[3]) || !_inBox(f[4])) _fail(); // outside the box
        int256 sx = q[3] - q[1];
        int256 sy = q[4] - q[2];
        if (sx > 4096 * PQ || -sx > 4096 * PQ || sy > 4096 * PQ || -sy > 4096 * PQ) _fail(); // too long
        if (f[0] == 0 ? (q[5] < 0 || q[5] > 16 * PQ || q[6] <= 0) : q[5] >= q[6]) _fail(); // invalid term
    }

    /// @notice Install a region from its source words: the exact Fix64
    ///         region, the charge of SAMPLE, and with `check` the record.
    /// @dev With `check`, reverts the bare KVMError on kv outside
    ///      [-16, 16] (the trap of REND). Without `check` (a resume), the
    ///      region is only built again and rec is empty.
    /// @param src   The source words (see the header).
    /// @param slot  The slot (0..15), written into the record.
    /// @param check True for the REND sub-op, false for a resume.
    /// @return R      The region words (PencilVM.region).
    /// @return rec    The region record (0x0d), or empty.
    /// @return counts vertex count << 128 | term count (the charge of
    ///                SAMPLE).
    function region(int256[] memory src, uint256 slot, bool check)
        public
        pure
        returns (int256[] memory R, bytes memory rec, uint256 counts)
    {
        if (check && ((src[0] >> 16) < -16 * PQ || (src[0] >> 16) > 16 * PQ)) _fail(); // invalid kv
        R = PencilVM.region(src);
        uint256 np = uint256(src[4]);
        uint256 o = 5;
        uint256 verts;
        uint256 size = 22;
        for (uint256 p; p < np; ++p) {
            uint256 n = uint256(src[o]);
            verts += n;
            size += 1 + 8 * n;
            o += 1 + 2 * n;
        }
        uint256 nt = uint256(src[o]);
        counts = (verts << 128) | nt;
        if (check) rec = _record(src, slot, size + 25 * nt);
    }

    /// The region record for src in `slot`, `size` bytes.
    function _record(int256[] memory src, uint256 slot, uint256 size) private pure returns (bytes memory rec) {
        rec = new bytes(size);
        uint256 w;
        assembly {
            w := add(rec, 0x20)
        }
        w = _put(w, (0x0d << 8) | slot, 2);
        for (uint256 i; i < 4; ++i) w = _put(w, uint256(src[i] >> 16), 4);
        uint256 np = uint256(src[4]);
        w = _put(w, np, 2);
        uint256 o = 5;
        for (uint256 p; p < np; ++p) {
            uint256 n = uint256(src[o]);
            w = _put(w, n, 1);
            for (uint256 i = 1; i <= 2 * n; ++i) w = _put(w, uint256(src[o + i] >> 16), 4);
            o += 1 + 2 * n;
        }
        uint256 nt = uint256(src[o]);
        w = _put(w, nt, 2);
        for (uint256 k; k < nt; ++k) {
            uint256 t = o + 1 + 7 * k;
            w = _put(w, uint256(src[t]), 1);
            for (uint256 j = 1; j < 7; ++j) w = _put(w, uint256(src[t + j] >> 16), 4);
        }
    }

    /// Write the low n bytes of v big-endian at w. The word write zeroes the
    /// bytes after them, and the next write overwrites those. Past the end of
    /// the record it touches only zero padding and unallocated memory.
    function _put(uint256 w, uint256 v, uint256 n) private pure returns (uint256) {
        assembly {
            let bits := shl(3, n)
            mstore(w, shl(sub(256, bits), and(v, sub(shl(bits, 1), 1))))
        }
        return w + n;
    }
}

src/PencilVM.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

pragma solidity ^0.8.13;

import "../lib/kohi/Fix64.sol";
import "../lib/kohi/Trig256.sol";
import "./raster/PencilCore.sol";

/* =============================================================================
 *  PencilVM · the value half of the pencil family, in exact Fix64
 * =============================================================================
 *
 * The PENCIL instruction (0xb0) pushes values back to the program: VARY
 * reads the paper, and SAMPLE reads a region. This library computes those
 * values as the interpreter holds them, bit-exact with the reference
 * interpreter. The paper's vary field is held in Fix64 as the float32 array
 * of the reference pencil engine holds it. The regions are exact Fix64 on
 * the program's own vertices. The per-pixel math of the rasterizer is the
 * Q16 integer half (PencilCore, PencilRaster). The two halves never mix.
 *
 *   vary32(x, y)  1/2, plus vary layer 0 in Fix64, rounded to float32 (the
 *                 FL32 rounding: nearest binary32, ties to even; where
 *                 binary32 has no Q31.32 image the value stays unrounded),
 *                 plus layer 1, rounded again. Exactly 1/2 off the canvas.
 *                 One layer: the lattice value 2U - 2^32 per cell, the axis
 *                 fraction (p * num << 16) / den in Q32, the smoothstep
 *                 t*t*(3 - 2t), bilinear in Fix64 add/sub/mul, times the
 *                 amplitude of the layer (raw 944892805 and 1116691497).
 *   inside        some polygon has no edge where the point lies further
 *                 out than tol + (vary - 1/2) * wobAmp + wobBias. The edges
 *                 are Fix64 inward unit edges (Trig256.sqrt and Fix64.div of
 *                 the program's vertices).
 *   shade         (1 + kv (vary - 1/2)) times each term: an occlusion term
 *                 is 1 + a e^(-d/b), a sliver term is
 *                 smooth((d - a) / (b - a)). d is the distance to the
 *                 segment of the term, with the projection clamped to it.
 *
 * Fix64 add/sub saturate and mul wraps, exactly as the Fix64 library does.
 *
 * DEPLOYMENT. A separately deployed library. The interpreter reaches it by
 * DELEGATECALL, so its code sits outside the EIP-170 budget of the runner.
 * It holds no state. Its data crosses as flat int256 words:
 *
 *   paper   int256[11]
 *           +---+---+------+----------------------+----------------------+
 *           | W | H | seed | layer 0: num den gw  | layer 1: num den gw  |
 *           |   |   |      |          off         |          off         |
 *           +---+---+------+----------------------+----------------------+
 *           0   1   2      3                      7                      11
 *
 *   source  int256[]: the program's own values
 *           kv | wobAmp | wobBias | tolL           (Fix64)
 *           | np | np x (n | n x (x | y))
 *           | nt | nt x (kind | ax | ay | bx | by | a | b)
 *
 *   region  int256[]: the installed form, built from a source
 *           kv | wobAmp | wobBias | tolL | np | toff
 *           | np x (n | n x (px | py | ex | ey))   (point + inward unit edge)
 *           then at word toff:
 *           nt | nt x (kind | ax | ay | bx | by | a | b)
 */
library PencilVM {
    int64 internal constant ONE = 4294967296;
    int64 internal constant HALF = 2147483648;
    int64 internal constant AMP0 = 944892805; // 0.22
    int64 internal constant AMP1 = 1116691497; // 0.26
    int64 internal constant BOX_LO = -2048 * 4294967296;
    int64 internal constant BOX_HI = 6144 * 4294967296 - 1;

    // ---- paper --------------------------------------------------------------

    /// @notice The paper words for a canvas, and the step surcharge of PAPER.
    /// @dev The surcharge is the fibre walk (PencilCore.FIBRES) plus the
    ///      cells of the two vary lattices. Does not revert for the inputs
    ///      the interpreter passes (it checks them first).
    /// @param W       Canvas width in px.
    /// @param H       Canvas height in px.
    /// @param sheet16 The sheet width in mm, Q16. The canvas width spans it.
    /// @param seed    The paper seed (u32).
    /// @return P         The paper words (see the header).
    /// @return surcharge The extra steps PAPER charges.
    function makePaper(int256 W, int256 H, int256 sheet16, uint256 seed)
        public
        pure
        returns (int256[11] memory P, uint256 surcharge)
    {
        PencilLayout memory L = PencilCore.paperLayout(W, H, sheet16, seed, false);
        PencilLat memory a = L.lat[6];
        PencilLat memory b = L.lat[7];
        P[0] = W;
        P[1] = H;
        P[2] = int256(L.seed);
        (P[3], P[4], P[5], P[6]) = (a.num, a.den, a.gw, a.off);
        (P[7], P[8], P[9], P[10]) = (b.num, b.den, b.gw, b.off);
        surcharge = PencilCore.FIBRES + uint256(a.gw * a.gh + b.gw * b.gh);
    }

    /// float32 rounding (FL32), or the value itself where binary32 has no
    /// Q31.32 image.
    function f32(int64 v) internal pure returns (int64) {
        if (v == 0) return 0;
        int256 x = v;
        bool neg = x < 0;
        uint256 a = uint256(neg ? -x : x);
        uint256 bits;
        for (uint256 t = a; t != 0; t >>= 1) ++bits;
        if (bits < 24) return v;
        uint256 shift = bits - 24;
        uint256 r = a;
        if (shift > 0) {
            uint256 q = a >> shift;
            uint256 rem = a - (q << shift);
            uint256 half = uint256(1) << (shift - 1);
            r = (rem > half || (rem == half && (q & 1) == 1)) ? (q + 1) << shift : q << shift;
        }
        return int64(neg ? -int256(r) : int256(r));
    }

    /// The axis parameter of layer l (0 or 1) at pixel p: the cell and the
    /// smoothstep (Fix64).
    function _axis(int256[11] memory P, uint256 l, int256 p) private pure returns (int256 i, int64 s) {
        uint256 o = 3 + 4 * l;
        uint256 f = ((uint256(p) * uint256(P[o])) << 16) / uint256(P[o + 1]);
        int64 t = int64(uint64(f & 0xffffffff));
        i = int256(f >> 32);
        s = Fix64.mul(Fix64.mul(t, t), 3 * ONE - 2 * t);
    }

    /// The lattice value 2U - 2^32 of cell idx of layer l.
    function _lat(int256[11] memory P, uint256 l, int256 idx) private pure returns (int64) {
        return int64(int256(2 * PencilCore.mb32(uint256(P[2]), uint256(P[6 + 4 * l] + idx))) - int256(ONE));
    }

    /// a + (b - a) * s along a lattice row, a and b the cells at i and i + 1.
    function _row(int256[11] memory P, uint256 l, int256 i, int64 s) private pure returns (int64) {
        int64 a = _lat(P, l, i);
        return Fix64.add(a, Fix64.mul(Fix64.sub(_lat(P, l, i + 1), a), s));
    }

    /// One vary layer at integer pixel (x, y), Fix64, in the order of the
    /// reference engine.
    function _layer(int256[11] memory P, uint256 l, int256 x, int256 y) private pure returns (int64) {
        (int256 ix, int64 sx) = _axis(P, l, x);
        (int256 iy, int64 sy) = _axis(P, l, y);
        int256 gw = P[5 + 4 * l];
        int64 top = _row(P, l, iy * gw + ix, sx);
        int64 bot = _row(P, l, iy * gw + gw + ix, sx);
        return Fix64.mul(l == 0 ? AMP0 : AMP1, Fix64.add(top, Fix64.mul(Fix64.sub(bot, top), sy)));
    }

    /// @notice The paper's vary at an integer pixel, as the float32 array of
    ///         the reference engine holds it (the value VARY pushes).
    /// @dev Exactly 1/2 off the canvas. Does not revert.
    /// @param P The paper words (makePaper).
    /// @param x Pixel x (the floor of the program's Fix64 x).
    /// @param y Pixel y (the floor of the program's Fix64 y).
    /// @return The vary value, Fix64.
    function vary32(int256[11] memory P, int256 x, int256 y) public pure returns (int64) {
        return _vary32(P, x, y);
    }

    function _vary32(int256[11] memory P, int256 x, int256 y) private pure returns (int64) {
        if (x < 0 || y < 0 || x >= P[0] || y >= P[1]) return HALF;
        int64 v0 = f32(Fix64.add(HALF, _layer(P, 0, x, y)));
        return f32(Fix64.add(v0, _layer(P, 1, x, y)));
    }

    // ---- regions ------------------------------------------------------------

    /// @notice Build the installed region words from source words (see the
    ///         header).
    /// @dev The interpreter checks the source first. A degenerate edge
    ///      (length 0) keeps a zero unit vector.
    /// @param src The source words: the program's own values.
    /// @return R The region words, with the inward unit edges.
    function region(int256[] memory src) public pure returns (int256[] memory R) {
        uint256 np = uint256(src[4]);
        uint256 o = 5;
        uint256 size = 6;
        for (uint256 p; p < np; ++p) {
            uint256 n = uint256(src[o]);
            size += 1 + 4 * n;
            o += 1 + 2 * n;
        }
        uint256 nt = uint256(src[o]);
        R = new int256[](size + 1 + 7 * nt);
        for (uint256 i; i < 5; ++i) R[i] = src[i];
        R[5] = int256(size);
        o = 5;
        uint256 w = 6;
        for (uint256 p; p < np; ++p) {
            uint256 n = uint256(src[o]);
            R[w] = int256(n);
            _edges(src, o + 1, n, R, w + 1);
            o += 1 + 2 * n;
            w += 1 + 4 * n;
        }
        for (uint256 i; i <= 7 * nt; ++i) R[w + i] = src[o + i];
    }

    /// The inward Fix64 unit edges of the polygon of n vertices at src[o..]:
    /// (px, py, ex, ey) per edge into R[w..]. The winding is the sign of
    /// twice the area on the raw values.
    function _edges(int256[] memory src, uint256 o, uint256 n, int256[] memory R, uint256 w) private pure {
        int256 a2;
        for (uint256 i; i < n; ++i) {
            uint256 j = (i + 1) % n;
            a2 += src[o + 2 * i] * src[o + 2 * j + 1] - src[o + 2 * j] * src[o + 2 * i + 1];
        }
        int256 sgn = a2 > 0 ? int256(1) : int256(-1);
        for (uint256 i; i < n; ++i) {
            uint256 j = (i + 1) % n;
            int256 px = src[o + 2 * i];
            int256 py = src[o + 2 * i + 1];
            int64 dx = int64((src[o + 2 * j] - px) * sgn);
            int64 dy = int64((src[o + 2 * j + 1] - py) * sgn);
            int64 len = Trig256.sqrt(Fix64.add(Fix64.mul(dx, dx), Fix64.mul(dy, dy)));
            uint256 e = w + 4 * i;
            R[e] = px;
            R[e + 1] = py;
            if (len != 0) {
                R[e + 2] = Fix64.div(dx, len);
                R[e + 3] = Fix64.div(dy, len);
            }
        }
    }

    /// The inside test of SAMPLE at Fix64 point (x, y).
    function _inside(int256[] memory R, int64 x, int64 y, int64 tol, int64 vary) private pure returns (bool) {
        int64 lim = Fix64.add(tol, Fix64.add(Fix64.mul(Fix64.sub(vary, HALF), int64(R[1])), int64(R[2])));
        uint256 np = uint256(R[4]);
        uint256 o = 6;
        for (uint256 p; p < np; ++p) {
            uint256 n = uint256(R[o]);
            bool ok = true;
            for (uint256 i; i < n; ++i) {
                if (_out(R, o + 1 + 4 * i, x, y) > lim) {
                    ok = false;
                    break;
                }
            }
            if (ok) return true;
            o += 1 + 4 * n;
        }
        return false;
    }

    /// How far (x, y) lies outside the edge at R[e..] (px, py, ex, ey),
    /// Fix64.
    function _out(int256[] memory R, uint256 e, int64 x, int64 y) private pure returns (int64) {
        return Fix64.sub(
            Fix64.mul(Fix64.sub(x, int64(R[e])), int64(R[e + 3])),
            Fix64.mul(Fix64.sub(y, int64(R[e + 1])), int64(R[e + 2]))
        );
    }

    /// The distance (Fix64) from (x, y) to the term at R[k..], with the
    /// projection clamped to the segment.
    function _dist(int256[] memory R, uint256 k, int64 x, int64 y) private pure returns (int64) {
        int64 ax = int64(R[k + 1]);
        int64 ay = int64(R[k + 2]);
        int64 ex = Fix64.sub(int64(R[k + 3]), ax);
        int64 ey = Fix64.sub(int64(R[k + 4]), ay);
        int64 ee = Fix64.add(Fix64.mul(ex, ex), Fix64.mul(ey, ey));
        int64 dx = Fix64.sub(x, ax);
        int64 dy = Fix64.sub(y, ay);
        int64 t = ee == 0 ? int64(0) : Fix64.div(Fix64.add(Fix64.mul(dx, ex), Fix64.mul(dy, ey)), ee);
        if (t < 0) t = 0;
        else if (t > ONE) t = ONE;
        dx = Fix64.sub(dx, Fix64.mul(ex, t));
        dy = Fix64.sub(dy, Fix64.mul(ey, t));
        return Trig256.sqrt(Fix64.add(Fix64.mul(dx, dx), Fix64.mul(dy, dy)));
    }

    /// The shade of SAMPLE at Fix64 point (x, y).
    function _shade(int256[] memory R, int64 x, int64 y, int64 vary) private view returns (int64 s) {
        s = Fix64.add(ONE, Fix64.mul(int64(R[0]), Fix64.sub(vary, HALF)));
        uint256 t0 = uint256(R[5]);
        uint256 end = t0 + 1 + 7 * uint256(R[t0]);
        for (uint256 k = t0 + 1; k < end; k += 7) {
            int64 d = _dist(R, k, x, y);
            int64 a = int64(R[k + 5]);
            int64 b = int64(R[k + 6]);
            if (R[k] == 0) {
                int64 e = Trig256.extExp(Fix64.sub(0, Fix64.div(d, b)));
                s = Fix64.mul(s, Fix64.add(ONE, Fix64.mul(a, e)));
            } else {
                int64 v = Fix64.div(Fix64.sub(d, a), Fix64.sub(b, a));
                if (v < 0) v = 0;
                else if (v > ONE) v = ONE;
                s = Fix64.mul(s, Fix64.mul(Fix64.mul(v, v), 3 * ONE - 2 * v));
            }
        }
    }

    /// @notice The value SAMPLE pushes for a region at a Fix64 point.
    /// @dev The point is clamped into the coordinate box [-2048, 6144) px
    ///      first. The shade calls Trig256 (exp) for occlusion terms.
    /// @param R     The region words (region).
    /// @param P     The paper words (makePaper).
    /// @param x     Point x, Fix64.
    /// @param y     Point y, Fix64.
    /// @param which 0 = inside (0/1) · 1 = inside with tolL (0/1) · 2 = shade.
    /// @return The value, Fix64 (ONE or 0 for which 0 and 1).
    function sample(int256[] memory R, int256[11] memory P, int64 x, int64 y, uint256 which)
        public
        view
        returns (int64)
    {
        if (x < BOX_LO) x = BOX_LO;
        else if (x > BOX_HI) x = BOX_HI;
        if (y < BOX_LO) y = BOX_LO;
        else if (y > BOX_HI) y = BOX_HI;
        int64 v = _vary32(P, x >> 32, y >> 32);
        if (which == 2) return _shade(R, x, y, v);
        return _inside(R, x, y, which == 1 ? int64(R[3]) : int64(0), v) ? ONE : int64(0);
    }
}

src/SinLutSingleton.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */
pragma solidity ^0.8.13;

/* =============================================================================
 *  SINLUT · one sine table, one address, every network
 * =============================================================================
 *
 * The KVM uses fixed-point trigonometry. All of it reads one 2048-byte table:
 * sin(x) at 256 points across a quarter wave, in Q31.32. The interpreter folds
 * each angle into [0, pi/2). At sample time it mirrors and negates the table
 * entries to rebuild the full period. The table never changes and every
 * backend reads the same bytes. On chain, the table is deployed once, as pure
 * data, at an address that any chain can reproduce. This file holds that
 * address and its derivation. The address commits to the table bytes. The
 * constants below let a reader check the commitment.
 *
 * Every KVM runner (KVMRunner, KVMStepCore, KVMStepRunner,
 * KVMInteractiveRunner, KVMTraitsRunner) reads its sine table from the SSTORE2
 * data contract at SINLUT. The deployed code is `STOP ++ SinLut256.table()`:
 *
 *       0    1                                                     2049
 *       +----+-------------------------------------------------------+
 *       |STOP| SinLut256.table(): 256 entries x 8 bytes, entry i at  |
 *       |0x00| table byte i*8, big-endian Q31.32                     |
 *       +----+-------------------------------------------------------+
 *
 * The 0x00 prefix is STOP, so the blob never executes as code. The runtime
 * read is an EXTCODECOPY that skips the prefix.
 *
 * One blob serves every runner. Each runner constructor stores
 * `sinLut = SINLUT`. No runner holds a private copy of the table. This saves
 * four 2 KB data contracts and about 2 KB of initcode per runner (the table
 * and the SSTORE2.write helper). The runtime read is an EXTCODECOPY of
 * `sinLut`, whatever that address holds.
 *
 * DERIVATION, reproducible on any chain:
 *
 *   proxy    = 0x4e59b44847b379578588920cA78FbF26c0B4956C
 *              the canonical deterministic-deployment proxy: it executes
 *              CREATE2(0, initcode, salt) with the first 32 calldata bytes
 *              as the salt, and is already present on mainnet, sepolia,
 *              anvil, and the forge test/script EVM
 *
 *   salt     = keccak256("kohi.sinlut.v1")
 *            = 0x2f069f27506488b699fe2e6321f2e31e737bf677c92426f475d84207c4f9af96
 *
 *   initcode = 0x61 ++ uint16(2049) ++ 0x3d81600a3d39f3 ++ 0x00
 *                   ++ SinLut256.table()
 *              (2059 bytes, the exact bytes SSTORE2.write(SinLut256.table())
 *              would CREATE); keccak256(initcode)
 *            = 0xe83f3fbd7fa53d2241a16e77cd0dd0f73365b0575cbbfef9e203cabf15128308
 *
 *   SINLUT   = keccak256(0xff ++ proxy ++ salt ++ keccak256(initcode))[12:]
 *            = 0x425Ea1bE9bFd353d7539a918b913f59289b028b8
 *
 * The deployed code at SINLUT is `STOP ++ SinLut256.table()` (2049 bytes),
 * codehash
 * 0x639034a1143ed727142506b4017fafc3fa9e1f811a62c77a25bfca61870bdd2b.
 *
 * The table bytes, the proxy and the salt are fixed. SINLUT is therefore the
 * SAME address on every network. The deploy tooling rebuilds the initcode,
 * runs it through the proxy, and asserts that the result equals this
 * constant. It MUST run before any runner, so that the runtime EXTCODECOPY
 * finds the table.
 *
 * The runners reference only SINLUT. SINLUT_CREATE2_PROXY and SINLUT_SALT are
 * the derivation inputs, shared by the deploy tooling and the test fixture.
 * All three are file-level constants with no getter. They add no bytecode to a
 * contract that does not reference them.
 */
address constant SINLUT = 0x425Ea1bE9bFd353d7539a918b913f59289b028b8;

// Canonical deterministic-deployment proxy. Present on mainnet, sepolia,
// anvil, and the forge test/script EVM.
address constant SINLUT_CREATE2_PROXY = 0x4e59b44847b379578588920cA78FbF26c0B4956C;

// keccak256("kohi.sinlut.v1"), as a literal. No hash runs at compile time.
bytes32 constant SINLUT_SALT = 0x2f069f27506488b699fe2e6321f2e31e737bf677c92426f475d84207c4f9af96;

src/raster/PencilCore.sol

// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

pragma solidity ^0.8.13;

import "../../lib/kohi/Fix64.sol";

/* =============================================================================
 *  PencilCore · the shared integer half of the pencil family
 * =============================================================================
 *
 * The pencil family (PENCIL 0xb0, render family 6) draws its paper from one
 * seeded generator and clips and shades by regions. This library holds the
 * parts that the rasterizer and the interpreter share: the paper's
 * index-addressable mulberry32, its draw layout, value-noise sampling, the
 * exp table reader, and the region inside and shade math. It is internal
 * only (no deployed code of its own).
 *
 * It is bit-exact with the shared module of the reference, which states
 * every quantity as an exact integer under 2^53 with FLOOR semantics. Here
 * every intermediate is an int256, and every division or shift that can see
 * a negative operand floors explicitly (`fdiv`, and `>>` on a signed int,
 * which is arithmetic).
 *
 *     format  1.0 =    use
 *     ------  -------  ------------------------------------------------------
 *     Q16     65536    unit quantities, pressures, tooth, wax, vary,
 *                      density, and positions in the stream records
 *                      (device px)
 *     Q12     4096     positions for the shade distances (1/4096 px)
 *     Q20     1048576  the unit vectors of region edges
 *
 * MULBERRY32 BY INDEX. The paper is drawn from mulberry32(seed). Its state
 * after k steps is seed + k * 0x6D2B79F5 (mod 2^32), so draw k is a pure
 * function of (seed, k), and a tile computes only the draws it needs.
 *
 * THE LAYOUT. A W x H canvas that spans `sheet16` mm (Q16) lays out its
 * draws in the order of the reference pencil engine:
 *
 *     lat  draws                     layer
 *     ---  ------------------------  ----------------------------------
 *      0   2 per cell                Worley grain
 *      1   1 per cell                tooth, value noise (3 layers)
 *      2   1 per cell
 *      3   1 per cell
 *      -   5 + steps per fibre       2,600 laid fibres (the step count
 *                                    comes from the 4th draw of the
 *                                    fibre, through Fix64)
 *      4   1 per cell                paper brightness (2 layers)
 *      5   1 per cell
 *      6   1 per cell                vary (2 layers)
 *      7   1 per cell
 *      -   256                       striation table
 *
 * The cell of a lattice is den/num * 65536 px exactly (num = 1000 * sheet16,
 * den = milli * W), counted exactly from the sheet width.
 */

/// One value-noise (or Worley) lattice.
struct PencilLat {
    int256 num;
    int256 den;
    int256 cell; // Q16 px, floored (the Worley distance ratio only)
    int256 gw;
    int256 gh;
    int256 off; // first draw index
    int256 amp; // Q16 amplitude
}

/// The draw layout of the paper. lat: 0 Worley, 1..3 tooth, 4..5
/// brightness, 6..7 vary. fib[i] = first draw of fibre i << 32 | its step
/// count (filled on request).
struct PencilLayout {
    int256 W;
    int256 H;
    int256 sheet16;
    int64 px; // px per mm, Fix64
    uint256 seed; // u32
    PencilLat[8] lat;
    uint256[] fib;
    int256 striOff;
    int256 draws;
}

/// A region ready to sample. Per polygon, per edge: (ex, ey) the inward unit
/// vector in Q20 and (px, py) the start of the edge in Q16. Per term, 8
/// words: kind, ax, ay, ex, ey (Q12), ee, a (Q16), b (Q12 for an occlusion,
/// Q16 for a sliver).
struct PencilRegion {
    bool set;
    int256 kv;
    int256 wobAmp;
    int256 wobBias;
    int256 tolL;
    int256[][] edges;
    int256[] terms;
    uint256 nt;
    uint256 verts;
}

library PencilCore {
    int256 internal constant Q = 65536;
    int256 internal constant Q20 = 1048576;
    int256 internal constant SHADE_MAX = 256 * 65536;
    int256 internal constant DMAX = 33554432; // 2^25: an offset from a term's segment clamps here (Q12)
    uint256 internal constant FIBRES = 2600;
    int256 internal constant LOG2E16 = 94548;

    // Fix64 constants of the fibre walk (raw = floor(x * 2^32))
    int64 internal constant F_0_7 = 3006477107;
    int64 internal constant F_0_8 = 3435973836;
    int64 internal constant F_2_7 = 11596411699;

    // ---- integers -----------------------------------------------------------

    /// Floor division (Math.floor(a / b) of the reference). Reverts on
    /// b == 0.
    function fdiv(int256 a, int256 b) internal pure returns (int256 q) {
        q = a / b;
        unchecked {
            if ((a % b != 0) && ((a ^ b) < 0)) q -= 1;
        }
    }

    /// floor(sqrt(n)) for any n >= 0.
    function isqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            if (a == 0) return 0;
            uint256 r = 1;
            uint256 t = a;
            if (t >> 128 > 0) { t >>= 128; r <<= 64; }
            if (t >> 64 > 0) { t >>= 64; r <<= 32; }
            if (t >> 32 > 0) { t >>= 32; r <<= 16; }
            if (t >> 16 > 0) { t >>= 16; r <<= 8; }
            if (t >> 8 > 0) { t >>= 8; r <<= 4; }
            if (t >> 4 > 0) { t >>= 4; r <<= 2; }
            if (t >> 2 > 0) { r <<= 1; }
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            r = (r + a / r) >> 1;
            uint256 s = a / r;
            return r < s ? r : s;
        }
    }

    /// Hermite smoothstep of a Q16 t in [0, Q].
    function smooth16(int256 t) internal pure returns (int256) {
        unchecked {
            return (((t * t) >> 16) * (3 * Q - 2 * t)) >> 16;
        }
    }

    /// Draw k (0-based) of mulberry32(seed), as a u32.
    function mb32(uint256 seed, uint256 k) internal pure returns (uint256 r) {
        assembly {
            let a := and(add(seed, mul(add(k, 1), 0x6d2b79f5)), 0xffffffff)
            let t := and(mul(xor(a, shr(15, a)), or(a, 1)), 0xffffffff)
            t := xor(and(add(t, mul(xor(t, shr(7, t)), or(t, 61))), 0xffffffff), t)
            r := xor(t, shr(14, t))
        }
    }

    /// hash2(a, b) = fmix32(a ^ imul(b + 1, 0x9e3779b1)), a and b as u32.
    function hash2(uint256 a, uint256 b) internal pure returns (uint256 h) {
        assembly {
            let m := and(xor(and(a, 0xffffffff), and(mul(and(add(and(b, 0xffffffff), 1), 0xffffffff), 0x9e3779b1), 0xffffffff)), 0xffffffff)
            m := and(mul(xor(m, shr(16, m)), 0x85ebca6b), 0xffffffff)
            m := and(mul(xor(m, shr(13, m)), 0xc2b2ae35), 0xffffffff)
            h := and(xor(m, shr(16, m)), 0xffffffff)
        }
    }

    // ---- layout -------------------------------------------------------------

    function _ceil(uint256 a, uint256 b) private pure returns (int256) {
        return int256((a + b - 1) / b);
    }

    function _vn(PencilLayout memory L, uint256 i, uint256 milli, int256 amp, uint256 extra, int256 off)
        private
        pure
        returns (int256)
    {
        unchecked {
            uint256 S = uint256(L.sheet16);
            uint256 W = uint256(L.W);
            uint256 H = uint256(L.H);
            PencilLat memory t = L.lat[i];
            t.num = int256(1000 * S);
            t.den = int256(milli * W);
            t.cell = int256((milli * W * 65536 * 65536) / (1000 * S));
            t.gw = _ceil(1000 * S, milli * 65536) + int256(extra);
            t.gh = _ceil(1000 * S * H, milli * 65536 * W) + int256(extra);
            t.off = off;
            t.amp = amp;
            return off + t.gw * t.gh * (extra == 1 ? int256(2) : int256(1));
        }
    }

    /// The steps of the fibre whose first draw is `base`: the count of
    /// k >= 0 with k * 0.7 < len, where len = mm(0.8 + 2.7 g) in Fix64 px
    /// and g is the 4th draw of the fibre.
    function fibreSteps(uint256 seed, uint256 base, int64 px) internal pure returns (uint256) {
        int64 g = int64(uint64(mb32(seed, base + 3)));
        int64 len = Fix64.mul(Fix64.add(F_0_8, Fix64.mul(g, F_2_7)), px);
        if (len <= 0) return 0;
        unchecked {
            return uint256(int256((len - 1) / F_0_7)) + 1;
        }
    }

    /// The layout of the paper. With `withFibres`, also record the draw base
    /// and the step count of every fibre.
    function paperLayout(int256 W, int256 H, int256 sheet16, uint256 seed, bool withFibres)
        internal
        pure
        returns (PencilLayout memory L)
    {
        unchecked {
            L.W = W;
            L.H = H;
            L.sheet16 = sheet16;
            L.seed = seed & 0xffffffff;
            int256 off = _vn(L, 0, 220, 39322, 1, 0);
            off = _vn(L, 1, 160, 7864, 2, off);
            off = _vn(L, 2, 400, 14418, 2, off);
            off = _vn(L, 3, 1600, 3932, 2, off);
            L.px = Fix64.div(int64(W << 32), int64(sheet16 << 16));
            if (withFibres) L.fib = new uint256[](FIBRES);
            for (uint256 i; i < FIBRES; ++i) {
                uint256 n = fibreSteps(L.seed, uint256(off), L.px);
                if (withFibres) L.fib[i] = (uint256(off) << 32) | n;
                off += int256(5 + n);
            }
            off = _vn(L, 4, 5000, 655, 2, off);
            off = _vn(L, 5, 28000, 1049, 2, off);
            off = _vn(L, 6, 2200, 14418, 2, off);
            off = _vn(L, 7, 7000, 17039, 2, off);
            L.striOff = off;
            L.draws = off + 256;
        }
    }

    /// The value-noise axis parameter of pixel p: (lattice index,
    /// smoothstepped fraction Q16).
    function vnAxis(int256 p, PencilLat memory L) internal pure returns (int256 i, int256 s) {
        unchecked {
            int256 f = fdiv(p * L.num, L.den);
            i = f >> 16;
            s = smooth16(f - i * Q);
        }
    }

    /// A lattice value from its draw: g * 2 - 1 in Q16, [-Q, Q).
    function latQ16(uint256 u) internal pure returns (int256) {
        unchecked {
            return int256(u >> 15) - Q;
        }
    }

    // ---- exp ----------------------------------------------------------------

    /// e^(-x) for x >= 0, both Q16, through the EXP2 table at `t` (memory,
    /// u16 entries). A negative x keeps the int32 shift semantics of the
    /// reference (f >> (ip & 31)).
    function expNeg16(int256 x, uint256 t) internal pure returns (int256 f) {
        unchecked {
            int256 y = (x * LOG2E16) >> 16;
            int256 ip = y >> 16;
            if (ip >= 17) return 0;
            assembly {
                let fp := sub(y, mul(ip, 65536))
                let j := shr(8, fp)
                let r := and(fp, 255)
                let p := add(t, shl(1, j))
                let a := add(shr(240, mload(p)), 32768)
                let b := add(shr(240, mload(add(p, 2))), 32768)
                f := shr(and(ip, 31), shr(8, add(mul(a, sub(256, r)), mul(b, r))))
            }
        }
    }

    // ---- regions ------------------------------------------------------------

    /// Build a region from Q16 polygons (x, y interleaved) and Q16 terms (7
    /// words each).
    function buildRegion(
        int256 kv,
        int256 wobAmp,
        int256 wobBias,
        int256 tolL,
        int256[][] memory polys,
        int256[] memory terms7
    ) internal pure returns (PencilRegion memory R) {
        unchecked {
            R.set = true;
            R.kv = kv;
            R.wobAmp = wobAmp;
            R.wobBias = wobBias;
            R.tolL = tolL;
            R.edges = new int256[][](polys.length);
            uint256 verts;
            for (uint256 p; p < polys.length; ++p) {
                int256[] memory poly = polys[p];
                uint256 n = poly.length >> 1;
                verts += n;
                int256 a2;
                for (uint256 i; i < n; ++i) {
                    uint256 j = (i + 1) % n;
                    a2 += (poly[2 * i] >> 8) * (poly[2 * j + 1] >> 8) - (poly[2 * j] >> 8) * (poly[2 * i + 1] >> 8);
                }
                int256 sgn = a2 > 0 ? int256(1) : int256(-1);
                int256[] memory e = new int256[](n * 4);
                for (uint256 i; i < n; ++i) {
                    uint256 j = (i + 1) % n;
                    int256 px = poly[2 * i];
                    int256 py = poly[2 * i + 1];
                    int256 dx = (poly[2 * j] - px) * sgn;
                    int256 dy = (poly[2 * j + 1] - py) * sgn;
                    int256 len = int256(isqrt(uint256(dx * dx + dy * dy)));
                    if (len != 0) {
                        e[4 * i] = fdiv(dx * Q20, len);
                        e[4 * i + 1] = fdiv(dy * Q20, len);
                    }
                    e[4 * i + 2] = px;
                    e[4 * i + 3] = py;
                }
                R.edges[p] = e;
            }
            R.verts = verts;
            uint256 nt = terms7.length / 7;
            R.nt = nt;
            R.terms = new int256[](nt * 8);
            int256[] memory T = R.terms;
            for (uint256 k; k < nt; ++k) {
                uint256 s = 7 * k;
                uint256 o = 8 * k;
                int256 ax = terms7[s + 1] >> 4;
                int256 ay = terms7[s + 2] >> 4;
                int256 ex = (terms7[s + 3] >> 4) - ax;
                int256 ey = (terms7[s + 4] >> 4) - ay;
                T[o] = terms7[s];
                T[o + 1] = ax;
                T[o + 2] = ay;
                T[o + 3] = ex;
                T[o + 4] = ey;
                T[o + 5] = ex * ex + ey * ey;
                T[o + 6] = terms7[s + 5];
                if (terms7[s] == 0) {
                    int256 b = terms7[s + 6] >> 4;
                    T[o + 7] = b > 1 ? b : int256(1);
                } else {
                    T[o + 7] = terms7[s + 6];
                }
            }
        }
    }

    /// The inside test at Q16 point (x, y), with tolerance tol (Q16 px) and
    /// the vary of the pixel.
    function regionInside(PencilRegion memory R, int256 x, int256 y, int256 tol, int256 vary16)
        internal
        pure
        returns (bool)
    {
        unchecked {
            int256 lim = (tol + (((vary16 - Q / 2) * R.wobAmp) >> 16) + R.wobBias) * Q20;
            int256[][] memory E = R.edges;
            for (uint256 p; p < E.length; ++p) {
                int256[] memory e = E[p];
                bool ok = true;
                uint256 m = e.length;
                for (uint256 i; i < m; i += 4) {
                    if ((x - e[i + 2]) * e[i + 1] - (y - e[i + 3]) * e[i] > lim) {
                        ok = false;
                        break;
                    }
                }
                if (ok) return true;
            }
            return false;
        }
    }

    /// The distance (Q12) from Q12 point (x, y) to the term at word o. The
    /// projection is an exact long division in four 4-bit steps.
    function _termDist(int256[] memory T, uint256 o, int256 x, int256 y) private pure returns (int256) {
        unchecked {
            int256 ex = T[o + 3];
            int256 ey = T[o + 4];
            int256 ee = T[o + 5];
            int256 dx = x - T[o + 1];
            int256 dy = y - T[o + 2];
            if (dx > DMAX) dx = DMAX;
            else if (dx < -DMAX) dx = -DMAX;
            if (dy > DMAX) dy = DMAX;
            else if (dy < -DMAX) dy = -DMAX;
            int256 dot = dx * ex + dy * ey;
            int256 t = Q;
            if (ee == 0 || dot <= 0) {
                t = 0;
            } else if (dot < ee) {
                int256 r = dot;
                t = 0;
                for (uint256 k; k < 4; ++k) {
                    int256 q = (r * 16) / ee;
                    t = t * 16 + q;
                    r = r * 16 - q * ee;
                }
            }
            int256 rx = dx - ((ex * t) >> 16);
            int256 ry = dy - ((ey * t) >> 16);
            return int256(isqrt(uint256(rx * rx + ry * ry)));
        }
    }

    /// The shade at Q12 point (x, y), Q16: max(0, 1 + kv (vary - 1/2)) times
    /// each term in record order.
    function regionShade(PencilRegion memory R, int256 x12, int256 y12, int256 vary16, uint256 exp2)
        internal
        pure
        returns (int256 s)
    {
        unchecked {
            s = Q + ((R.kv * (vary16 - Q / 2)) >> 16);
            if (s < 0) s = 0;
            int256[] memory T = R.terms;
            uint256 nt = R.nt;
            for (uint256 k; k < nt; ++k) {
                uint256 o = k * 8;
                int256 d = _termDist(T, o, x12, y12);
                if (T[o] == 0) {
                    int256 v = (s * (Q + ((T[o + 6] * expNeg16(fdiv(d * Q, T[o + 7]), exp2)) >> 16))) >> 16;
                    s = v < SHADE_MAX ? v : SHADE_MAX;
                } else {
                    int256 e0 = T[o + 6];
                    int256 t = fdiv((d * 16 - e0) * Q, T[o + 7] - e0);
                    if (t < 0) t = 0;
                    if (t > Q) t = Q;
                    s = (s * smooth16(t)) >> 16;
                }
            }
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "src/KVMStep4.sol": {
      "Trig256": "0x9905c8152a46fddd62e935cf496dbff3b65124d8",
      "PencilVM": "0x90788fc9600ae61e95bd409f7456acc5cef1a617",
      "PencilStep": "0xca980a6be630cdf98f5ba463150e280ff7df54e5"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "kohi-fixmath/=lib/kohi-fixmath/",
    "lib/kohi-noise-lgpl/:kohi-fixmath/=lib/kohi-fixmath/",
    "lib/kohi-noise-lgpl/:kohi-fixmath/=lib/kohi-fixmath/",
    "kohi-noise-lgpl/=lib/kohi-noise-lgpl/",
    "kohi/=lib/kohi/",
    "test/=lib/kohi-noise-lgpl/test/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.