Match Your Colors: minimal ordinary-Lua core, version 1

This contract describes the numerical core and its local calculation adapter
inside the Match colors folder mod. The full mod separately captures current
appearance data and applies guarded game changes through the panel. Statements
below about no game access or unsent output apply to the numerical core/adapter,
not to the complete connected mod.

Attribution
-----------
colour.lua, matcher.lua and transfer.lua are unchanged files from the
Vanilla Plus source-v42 MatchYourColors component, copyright (C) 2026
MatchYourColors, Zero-Clause BSD. LICENSE.upstream.txt contains its license;
UPSTREAM.json pins every file and source SHA-256. core.lua and init.lua adapt
those modules to ordinary tables. These Lua modules use no FFI or native bridge.
Their runtime requires Lua 5.1-compatible behavior with math.atan2. The panel
supplies the standalone LuaJIT EXE and its adjacent runtime DLL for this purpose.

Input
-----
The package's run_request.lua configures module lookup relative to the mod
folder. Its fixed numerical entry point is:

  local Core = require('color_match')
  local result = Core.match(request)

request = {
  direction = 'helmet_from_armor',
  samples = {
    detail = {layer1, layer2, ...},
    camo = {layer1, layer2, ...} -- empty only when no analyzed row uses camo
  },
  helmet = {luts = lut_map, rows = row_list},
  armor = {luts = lut_map, rows = row_list},
  cape = {luts = lut_map, rows = row_list} -- needed only for cape targets
}

Directions: helmet_from_armor, armor_from_helmet, cape_from_armor,
cape_from_helmet, helmet_and_cape_from_armor, armor_and_cape_from_helmet.
Only the named target(s) and source are required. Combined targets are fitted
independently against the original source and their LUT copies are merged;
target roles sharing a LUT ID are rejected to avoid conflicting ownership.

Cape support covers its 23-column base-cloth material LUT. Its row coverage
comes from the cape's scalar fields, common outline, outside/inside weights
and gradient/tint split, not an armor ID mask. The 16-column cape LUT, tint
colors, gradients and emblem/decal sheets stay unchanged. Fully tint-covered
capes are rejected by the reader because there is no exposed base cloth to fit.

Each sample layer is a dense 1-based numeric array of exactly 512 RGBA texels
(2048 values in [0,1]), in the upstream deterministic sample order. At least
one detail layer is required. Do not substitute arbitrary average texels.
The upstream shader model selects a layer using trunc(index) modulo count.

lut_map maps a lowercase hexadecimal resource ID (1..16 digits, no 0x prefix)
to {width=23, height=N, values={R,G,B,A,...}}. values is a dense 1-based numeric
array of width*height*4 finite values, row-major. These are decoded original
float32 material-LUT texels represented as ordinary Lua numbers, not raw bytes.
Input values are not modified. Extra unused LUT rows are copied unchanged.

Each row_list entry is:
  {lut='0123456789abcdef', row=0, area=0.6, under=0.1, protected=false}

row is ZERO-BASED. area is the row's actual coverage weight across the item's
pieces/materials; normalize all rows consistently. under is its undergarment
portion in [0,area], defaults to zero. Zero-coverage rows are skipped. Duplicate
LUT/row identities are rejected: aggregate contributions before calling.
protected is optional; true keeps the row intact and excludes it from matching.
The core also automatically protects mode >= 2.5 and hard-paint emissive rows
(mode < 0.5 with column 13 x > 0), matching upstream visor/light rules.
The caller can protect additional known special-purpose rows explicitly.

LUT controls and material columns must be authentic decoded data. The adapter
validates shape, finite numeric range and bounds, not the semantics of arbitrary
controls. Limits per item: 128 LUTs, 256 rows per LUT, 4096 coverage entries;
256 layers per sample family; 2,097,152 total decoded input floats.

Output
------
result.luts contains independent copies of ALL target LUTs, in the same format
as input. Only RGB channels in zero-based columns 0,2,5,6,16,17,18,19 may differ.
Every other target value is copied directly, including alpha, material mode,
metallic/specular/roughness, sheen, detail/camo controls and tiling. Visor,
emissive, explicitly protected, unplanned and unlisted rows are unchanged.

result.status is 'matched' or 'unchanged'. changed_luts is a sorted array of
IDs with differences. rows describes each fitted target row: key, source row
key, match kind, target Lab goal, model CIEDE2000 error, and changed_offsets.
changed_offsets are ZERO-BASED scalar offsets into that LUT's flat RGBA array
(the corresponding Lua values index is offset+1). Also returned:
changed_float_count, fitted_row_count, max_error, protected_rows and limitations.
Invalid input raises an ordinary Lua error before returning any result.

Scope and fidelity
------------------
This preserves the upstream unmeasured matcher and iterative color fitter.
It is not full-mod parity: no measured per-kit appearance calibration, cape
tint layers, pattern plans, hood metadata, zones or optional variety balancing.
The upstream optional dark_finish roughness adjustment is deliberately disabled
because this contract preserves ALL non-color values. A glossy light item made
dark can therefore still look glossier than the source. RGB-only copy-back is
enforced independently of the fitter. Reported errors measure the model, not
rendered screenshots. Core.match itself does not recolor the game. The full
Match colors package handles application and restoration outside this core.

Responsibilities outside the numerical core
------------------------------------------
The full package's reader and appearance service provide the live integration.
The core depends on the following data and behavior from its caller:
1. Current equipped helmet/armor -> piece unit -> mesh/material -> actual LUT
   and ID-mask ownership, including any per-piece overrides and patched assets.
   Cape: the selected cape kit has no unit; its material-LUT override is bound
   on the current armor's slot-1 cape-mount unit, not a separate cape unit.
2. Original decoded 23-column material LUTs and matching normalized row coverage
   weights/under contributions, preserving zero-based row IDs.
3. Current decoded global detail/camo tiler layers sampled at the upstream 512
   deterministic coordinates and order. Source-v42 samples cannot silently be
   assumed equivalent to build 26568081.
4. Optional current per-kit response measurements if closer rendered matching
   is required; this minimal core currently uses the unmeasured model only.
5. Guarded texture creation/update, binding, mesh update, lifetime and
   restoration. The core implements none of these operations; the package's
   appearance service and game-side Lua implementation own them.

No game APIs, target-memory access, game-process access, engine resource binding
or UI operations occur inside the numerical core or its local calculation
adapter. Numerical tests use the standalone interpreter and local synthetic or
frozen fixtures. Such tests do not establish live integration behavior.

Package-local Python adapter
----------------------------
The mod's appearance service calls the bundled adapter through a relative
import from the mod root:

  from .color_match import run_match
  result = run_match(document)

document may be the request above or color_assets.prepare_match's envelope
{payload: request, evidence: ..., provenance: ...}. Only payload is passed to
the core. The Python function invokes the panel-supplied standalone LuaJIT
as a separate local calculation process, with no game/broker connection.
The panel's standalone_lua.verified_interpreter() helper owns and verifies the
EXE and adjacent compat_luajit51.dll hashes. The package keeps no separate
binary pins or panel-resource path; missing or changed binaries remain errors.
This interpreter is supplied as Match colors' calculation dependency, separate
from the external game-side Lua loader and its configured runtime directory.
The adapter installs no runtime or native extension.
It serializes JSON data as escaped Lua literals, and run_request.lua evaluates
the data in an empty environment. Only the fixed pure core modules may load.
The connected portable panel creates temporary calculation folders beneath
data/runtime/color-match/ and removes them on completion or failure. The caller
passes the selected profile's output boundary; package code must respect it.

The adapter defaults to a 120-second timeout. A package-local caller can use
run_match(document, include_uploads=False, timeout=120) to return only numeric
LUTs, validation and diagnostics. The portable release does not expose this
adapter as a standalone Python command-line tool. Use the Match colors editor
for normal operation and the included SDK for suitable synthetic package tests.

The adapter independently validates all copied target LUTs, every changed
scalar, changed-offset reports and preservation of protected/non-color data.
The result adds validation, offline timing/provenance and, by default, uploads:

  uploads[i] = {
    lut, width, height, format='R16G16B16A16F', byte_order='little',
    encoding='base64', byte_count, row_pitch_bytes, sha256, data_base64,
    original_sha256, original_base64,
    preserves_original_non_color_exactly=true,
    fits_2048_byte_decoder, max_allowed_rgb_quantization_error
  }

These are UNSENT little-endian RGBA half-float blobs. The adapter does not open
an engine channel, create/bind a texture, mutate a resource or test a renderer.
Every protected/non-color and unchanged source scalar must be exactly representable as half
float before these blobs can be emitted; otherwise encoding raises an error
instead of silently changing the material. Use include_uploads=False for
numeric computation of a source that requires another texture format.
fit errors describe pre-quantization model colors; quantization error is
reported separately. A 23x8 LUT is 1472 bytes and fits a 2048-byte decoder; larger
dimensions are reported truthfully, with no automatic chunking/upload implied.
