extends RefCounted
## HY3D chest armour worn on a rigged hero (view only, Boss 2026-10-21 build 46; hy3d_gear.gd decides who wears what).
## The fit = the QA'd pilot (tools/hy3d/armor_wear.gd, game_qa shots aw13-aw28, sheet art/hy3d_pilot/
## armor_wear_sheet_v2.png) with its default options, split so it never stalls the game:
##  1. a BAKE shipped with the game (res://assets/hy3d/bake/<armour>__<model>.res: skinned mesh + Skin + which body
##     vertices are hidden / moved), made by `selftest --only=hy3dgear --hy3dbake` from the same code; applied in a few
##     ms whenever its signature (fit version, armour file md5, the rig's body meshes + bone count, options) matches;
##  2. else a per-user cache (user://hy3d_armor_cache/<sig>.res) from an earlier fit;
##  3. else the fit runs on a WorkerThreadPool thread (the ~6 s of vertex work; the scene is only read on the main
##     thread, into plain arrays first) and the armour appears when it is done (callbacks), then it is cached.
## Fit (wrapper space = feet y 0, facing +Z, idle frame 0): a torso segment + one sleeve chain per side mapped onto the
## hero's bones, shrink-wrapped out of the body, skinned from the nearest body vertices (region-limited), the body
## under the plate hidden (incl. the old outfit's blue tabard by texel colour), material toon_metal (hero_dc_knight
## "shine" + the armour tuning MAT_KEYS, two-sided copy of the shader).
## Body-build looks (look_apply.gd shaped meshes) keep the same vertex order: the bake applies to every build.

const TOON_METAL = preload("res://shaders/toon_metal.gdshader")
const ML = preload("res://scripts/model_loader.gd")

const FIT_VER := 1
const BAKE_DIR := "res://assets/hy3d/bake"
const CACHE_DIR := "user://hy3d_armor_cache"

const G_TORSO := ["Spine01", "Spine02", "Waist", "NeckTwist01", "NeckTwist02", "Neck", "L_Clavicle", "R_Clavicle"]
const G_HIPS := ["Pelvis", "Hip"]

## fit / material option overrides (tests only; empty = the QA'd defaults)
static var opt := {}
## where the last wear() got its armour: "bake" / "user" / "mem" / "fit" (sync bake tool) / "pending" / ""
static var last_source := ""
static var last_ms := 0
## fits started on worker threads (tests read it)
static var fits_started := 0

static var _mem := {}
static var _jobs := {}
static var _md5 := {}
static var _tex := {}


static func _o(k: String, d: float) -> float:
	return float(opt.get(k, d))


static func _side_group(bn: String) -> String:
	for s in ["L", "R"]:
		if bn.begins_with(s + "_"):
			var r := bn.substr(2)
			if r.begins_with("Upperarm") or r.begins_with("Forearm") or r.begins_with("Hand") or r.begins_with("Finger") \
					or r.begins_with("Thumb") or r.begins_with("Index") or r.begins_with("Middle") or r.begins_with("Ring") or r.begins_with("Pinky"):
				return "arm_" + s
			if r.begins_with("Clavicle"):
				return "torso"
			if r.begins_with("Thigh"):
				return "thigh"
			return "leg"
	if bn in G_TORSO or bn.begins_with("Spine") or bn.begins_with("Neck"):
		return "torso"
	if bn in G_HIPS:
		return "hips"
	if bn.begins_with("Head") or bn.contains("Eye") or bn.contains("Jaw") or bn.contains("Hair"):
		return "head"
	return "other"


static func skeleton(model: Node3D) -> Skeleton3D:
	var l := model.find_children("*", "Skeleton3D", true, false)
	return l[0] as Skeleton3D if not l.is_empty() else null


static func _rel(model: Node, node: Node) -> Transform3D:
	var t := Transform3D()
	var n := node
	while n != null and n != model:
		if n is Node3D:
			t = (n as Node3D).transform * t
		n = n.get_parent()
	return t


## Visible inside the model (its own flag and every parent up to the model; the hero being hidden does not count).
static func _vis_in(model: Node, n: Node) -> bool:
	var p := n
	while p != null and p != model:
		if p is Node3D and not (p as Node3D).visible:
			return false
		p = p.get_parent()
	return true


## The body meshes the fit reads / hides, in a fixed order: [MeshInstance3D, surface, offset, vertex count].
static func _body_src(model: Node3D) -> Array:
	var SRC: Array = []
	var total := 0
	for mi in model.find_children("*", "MeshInstance3D", true, false):
		var m3 := mi as MeshInstance3D
		if m3.skin == null or not (m3.mesh is ArrayMesh) or m3.get_parent() is BoneAttachment3D or m3.name.begins_with("Costume") \
				or m3.name.begins_with("HY3D") or not _vis_in(model, m3):
			continue
		var mesh0: ArrayMesh = m3.get_meta("aw_mesh0") if m3.has_meta("aw_mesh0") else m3.mesh
		for s in mesh0.get_surface_count():
			var nv := mesh0.surface_get_array_len(s)
			var fm := mesh0.surface_get_format(s)
			if nv <= 0 or (fm & Mesh.ARRAY_FORMAT_BONES) == 0 or (fm & Mesh.ARRAY_FORMAT_WEIGHTS) == 0:
				continue
			SRC.append([m3, s, total, nv])
			total += nv
	return SRC


static func _file_md5(path: String) -> String:
	if not _md5.has(path):
		_md5[path] = FileAccess.get_md5(path)
	return str(_md5[path])


## Signature of (armour file, rig + body meshes, fit version, options): a bake / cache entry is used only when equal.
static func signature(model: Node3D, path: String) -> String:
	var sig := ""
	for e in _body_src(model):
		sig += str((e[0] as Node).name) + ":" + str(e[3]) + ";"
	var sk := skeleton(model)
	var keys := opt.keys()
	keys.sort()
	var o := ""
	for k in keys:
		o += "%s=%s;" % [str(k), str(opt[k])]
	return "%d|%s|%s|%d|%s" % [FIT_VER, _file_md5(path), sig, sk.get_bone_count() if sk else 0, o]


static func bake_path(armor_id: String, model_id: String) -> String:
	return BAKE_DIR.path_join("%s__%s.res" % [armor_id, model_id])


# ---------------------------------------------------------------- wear / unwear

## Puts the armour on `model` (rigged hero wrapper). Returns the worn MeshInstance3D, or null while a fit is running
## on a thread (`done` is called with no argument when it is ready: wear again) or on failure.
static func wear(model: Node3D, path: String, armor_id: String, model_id: String, done: Callable = Callable()) -> MeshInstance3D:
	var t0 := Time.get_ticks_msec()
	last_source = ""
	if skeleton(model) == null:
		return null
	var sig := signature(model, path)
	var rec = _mem.get(sig)
	var src := "mem"
	if rec == null:
		var bp := bake_path(armor_id, model_id)
		if ResourceLoader.exists(bp):
			var r = ResourceLoader.load(bp)
			if r is ArrayMesh and str((r as ArrayMesh).get_meta("aw_sig", "")) == sig:
				rec = r
				src = "bake"
	if rec == null:
		var cp := CACHE_DIR.path_join(sig.md5_text() + ".res")
		if FileAccess.file_exists(cp):
			var r2 = ResourceLoader.load(cp, "", ResourceLoader.CACHE_MODE_IGNORE)
			if r2 is ArrayMesh and str((r2 as ArrayMesh).get_meta("aw_sig", "")) == sig:
				rec = r2
				src = "user"
	if rec == null:
		_start_fit(model, path, sig, done)
		last_source = "pending"
		return null
	_mem[sig] = rec
	var mi := _apply(model, rec, path)
	last_source = src
	last_ms = Time.get_ticks_msec() - t0
	return mi


## Takes the armour off and gives the body its own meshes back (a mesh some look code replaced meanwhile stays).
static func unwear(model: Node3D) -> void:
	if model == null:
		return
	for mi in model.find_children("*", "MeshInstance3D", true, false):
		var m3 := mi as MeshInstance3D
		if str(m3.name).begins_with("HY3DArmorWorn"):
			# out of the tree now (look code walking the model right after must not see it)
			if m3.get_parent():
				m3.get_parent().remove_child(m3)
			m3.queue_free()
			continue
		if m3.has_meta("aw_mesh0"):
			if m3.mesh == m3.get_meta("aw_mesh_hid", null):
				m3.mesh = m3.get_meta("aw_mesh0")
			m3.remove_meta("aw_mesh0")
			if m3.has_meta("aw_mesh_hid"):
				m3.remove_meta("aw_mesh_hid")


static func worn(model: Node3D) -> MeshInstance3D:
	if model == null:
		return null
	for mi in model.find_children("HY3DArmorWorn*", "MeshInstance3D", true, false):
		return mi as MeshInstance3D
	return null


## The body under the armour is hidden by swapping its meshes; look code (look_apply.gd body build) may swap them back
## later: true when every hidden body mesh is still ours.
static func body_intact(model: Node3D) -> bool:
	for mi in model.find_children("*", "MeshInstance3D", true, false):
		var m3 := mi as MeshInstance3D
		if m3.has_meta("aw_mesh_hid") and m3.mesh != m3.get_meta("aw_mesh_hid"):
			return false
	return true


static func _apply(model: Node3D, rec: ArrayMesh, path: String) -> MeshInstance3D:
	var sk := skeleton(model)
	var mi := MeshInstance3D.new()
	mi.name = "HY3DArmorWorn"
	mi.mesh = rec
	mi.skin = rec.get_meta("aw_skin")
	sk.add_child(mi)
	mi.skeleton = NodePath("..")
	mi.custom_aabb = rec.get_meta("aw_aabb")
	_dress(mi, path)
	_hide_body(model, _body_src(model), rec.get_meta("aw_hid"), rec.get_meta("aw_mv"))
	return mi


## Body meshes without the triangles that have 2+ hidden vertices (+ the moved arm-tube vertices); the original
## mesh is kept in meta "aw_mesh0", ours in "aw_mesh_hid". One hidden copy per source mesh (shared by heroes).
static var _hid_meshes := {}


static func _hide_body(model: Node3D, src: Array, hid: PackedByteArray, mv: PackedVector3Array) -> void:
	var per_mi := {}
	for e in src:
		var m3: MeshInstance3D = e[0]
		if not per_mi.has(m3):
			per_mi[m3] = []
		(per_mi[m3] as Array).append(e)
	var total := 0
	for e in src:
		total = maxi(total, int(e[2]) + int(e[3]))
	if hid.size() < total:
		push_warning("hy3d_armor: hidden-vertex list shorter than the body (%d < %d), body left as is" % [hid.size(), total])
		return
	for m3 in per_mi:
		var mesh0: ArrayMesh = m3.get_meta("aw_mesh0") if m3.has_meta("aw_mesh0") else m3.mesh
		var hk := "%d|%d|%d" % [mesh0.get_instance_id(), hid.size(), hash(hid)]
		var nm: ArrayMesh = _hid_meshes.get(hk)
		if nm == null:
			nm = ArrayMesh.new()
			for s in mesh0.get_surface_count():
				var arr := mesh0.surface_get_arrays(s)
				var off := -1
				for e in per_mi[m3]:
					if int(e[1]) == s:
						off = int(e[2])
				if off >= 0:
					var idx: PackedInt32Array = arr[Mesh.ARRAY_INDEX]
					var keep := PackedInt32Array()
					for f in range(0, idx.size(), 3):
						var h := int(hid[off + idx[f]]) + int(hid[off + idx[f + 1]]) + int(hid[off + idx[f + 2]])
						if h >= int(_o("hidek", 2.0)):
							continue
						keep.append(idx[f])
						keep.append(idx[f + 1])
						keep.append(idx[f + 2])
					arr[Mesh.ARRAY_INDEX] = keep
					if not mv.is_empty():
						var vv: PackedVector3Array = arr[Mesh.ARRAY_VERTEX]
						for j in vv.size():
							vv[j] += mv[off + j]
						arr[Mesh.ARRAY_VERTEX] = vv
				nm.add_surface_from_arrays(mesh0.surface_get_primitive_type(s), arr, [], {}, mesh0.surface_get_format(s) & Mesh.ARRAY_FLAG_USE_8_BONE_WEIGHTS)
				nm.surface_set_material(s, mesh0.surface_get_material(s))
			# the cache holds the source mesh alive with its copy: bounded (one entry per hero model / build)
			if _hid_meshes.size() > 24:
				_hid_meshes.clear()
			_hid_meshes[hk] = nm
		m3.set_meta("aw_mesh0", mesh0)
		m3.set_meta("aw_mesh_hid", nm)
		m3.mesh = nm


# ---------------------------------------------------------------- material

static var _as := {}


## Armour copy of toon_metal (two-sided) with tuning uniforms for the HY3D paint (see armor_wear.gd: steel mask
## window aw_s0/aw_s1, bright cut aw_v0/aw_v1, light floor, warm-hue exclusion, despeckle).
static func _armor_shader(cull_off: bool) -> Shader:
	if _as.has(cull_off):
		return _as[cull_off]
	var code := TOON_METAL.code
	if cull_off:
		var a := code.find("render_mode")
		var e := code.find(";", a)
		code = code.substr(0, e) + ", cull_disabled" + code.substr(e)
	var pats := [
		["varying float v_metal;", "varying float v_metal;\nuniform float aw_s0 = 0.1;\nuniform float aw_s1 = 0.18;\nuniform float aw_v0 = 0.86;\nuniform float aw_v1 = 0.93;\nuniform float aw_nogold = 0.0;\nuniform float aw_floor = 0.0;\nuniform float aw_dbg = 0.0;\nuniform float aw_warm = 0.0;\nuniform float aw_w0 = 0.03;\nuniform float aw_w1 = 0.08;\nuniform float aw_rlock = 0.0;\nuniform float aw_rup = 0.62;\nuniform float aw_desp = 0.0;\nuniform float aw_dk = 0.0;"],
		["vec3 tc = texture(tex, UV * uv_scale).rgb;", "vec3 tc = texture(tex, UV * uv_scale).rgb;\n	if (aw_desp > 0.0) {\n		vec2 px = aw_desp / vec2(textureSize(tex, 0));\n		vec3 lw = vec3(0.299, 0.587, 0.114);\n		vec3 n1 = texture(tex, UV * uv_scale + vec2(px.x, 0.0)).rgb;\n		vec3 n2 = texture(tex, UV * uv_scale - vec2(px.x, 0.0)).rgb;\n		vec3 n3 = texture(tex, UV * uv_scale + vec2(0.0, px.y)).rgb;\n		vec3 n4 = texture(tex, UV * uv_scale - vec2(0.0, px.y)).rgb;\n		float mn = min(min(dot(n1, lw), dot(n2, lw)), min(dot(n3, lw), dot(n4, lw)));\n		float dk = smoothstep(0.04, 0.12, mn - dot(tc, lw)) * smoothstep(0.08, 0.2, mn);\n		tc = mix(tc, (n1 + n2 + n3 + n4) * 0.25, dk);\n	}"],
		["float up = NORMAL.y * 0.5 + 0.5;", "float up = mix(NORMAL.y * 0.5 + 0.5, aw_rup, aw_rlock);"],
		["float silver_m = (1.0 - smoothstep(0.1, 0.18, tsat)) * smoothstep(0.3, 0.45, mxc) * (1.0 - smoothstep(0.86, 0.93, mxc));",
			"float silver_m = (1.0 - smoothstep(aw_s0, aw_s1, tsat)) * mix(smoothstep(0.3, 0.45, mxc), 1.0, aw_dk) * (1.0 - smoothstep(aw_v0, aw_v1, mxc)) * (1.0 - gold_m * aw_nogold) * (1.0 - aw_warm * smoothstep(aw_w0, aw_w1, sc.r - sc.b));"],
		["	ALBEDO = base;\n", "	ALBEDO = base;\n	if (aw_dbg > 0.5) { ALBEDO = vec3(0.0); EMISSION = vec3(m, 0.0, gold_m); }\n"],
		["		DIFFUSE_LIGHT += band * LIGHT_COLOR / PI;", "		band = max(band, vec3(aw_floor * v_metal));\n		DIFFUSE_LIGHT += band * LIGHT_COLOR / PI;"],
	]
	for p in pats:
		if code.find(p[0]) < 0:
			push_warning("hy3d_armor: shader patch missing: " + str(p[0]).substr(0, 60))
		code = code.replace(p[0], p[1])
	var n := Shader.new()
	n.code = code
	_as[cull_off] = n
	return n


## the QA'd values (armor_wear.gd MAT_KEYS, shots aw13-aw18)
const MAT_KEYS := {"aw_s0": 0.28, "aw_s1": 0.42, "aw_v0": 0.97, "aw_v1": 1.01, "aw_nogold": 0.0, "aw_floor": 0.55, "aw_dbg": 0.0,
	"aw_warm": 1.0, "aw_w0": 0.03, "aw_w1": 0.08, "aw_rlock": 0.0, "aw_rup": 0.62, "aw_desp": 6.0, "aw_dk": 1.0,
	"baked": 0.0, "spec_amount": 0.5, "shade_amount": 0.55}


## The armour's albedo texture (read once per file from its GLB).
static func _albedo(path: String) -> Texture2D:
	if not _tex.has(path):
		var t: Texture2D = null
		var A := load_armor(path)
		if not A.is_empty() and A["mat"] is BaseMaterial3D:
			t = (A["mat"] as BaseMaterial3D).albedo_texture
		_tex[path] = t
	return _tex[path]


static var _mats := {}


## One shared material per armour file: toon_metal (two-sided copy) with hero_dc_knight's steel shine + MAT_KEYS,
## the ink outline as next pass.
static func _dress(mi: MeshInstance3D, path: String) -> void:
	var m: ShaderMaterial = _mats.get(path)
	if m == null:
		var tx := _albedo(path)
		var o := ShaderMaterial.new()
		o.shader = ML.Chibi.OUTLINE
		o.set_shader_parameter("thickness", _o("outline", 0.012))
		o.set_shader_parameter("outline_color", Color(0.227, 0.165, 0.2))
		m = ShaderMaterial.new()
		m.shader = _armor_shader(_o("twosided", 1.0) > 0.5)
		m.set_shader_parameter("albedo", Color.WHITE)
		if tx:
			m.set_shader_parameter("tex", tx)
			o.set_shader_parameter("tex", tx)
			o.set_shader_parameter("tex_mix", 1.0)
		m.set_shader_parameter("baked", 0.0)
		var sh: Dictionary = ML.HERO_LOOK.get("hero_dc_knight", {}).get("shine", {})
		for k in sh:
			m.set_shader_parameter(k, sh[k])
		for k in MAT_KEYS:
			m.set_shader_parameter(k, _o(k, float(MAT_KEYS[k])))
		m.set_shader_parameter("metal_lo", Color(0.5, 0.53, 0.6))
		m.next_pass = o
		_mats[path] = m
	mi.set_surface_override_material(0, m)


# ---------------------------------------------------------------- fit (snapshot on the main thread, maths anywhere)

## Armour mesh (armour space: Y up, feet 0) + its source material.
static func load_armor(path: String) -> Dictionary:
	var doc := GLTFDocument.new()
	var st := GLTFState.new()
	if doc.append_from_file(path, st) != OK:
		return {}
	var root: Node = doc.generate_scene(st)
	var l := root.find_children("*", "MeshInstance3D", true, false)
	if l.is_empty():
		root.free()
		return {}
	var mi := l[0] as MeshInstance3D
	var xf := _rel(root, mi)
	var arr := mi.mesh.surface_get_arrays(0)
	var mat = mi.mesh.surface_get_material(0)
	var vv: PackedVector3Array = arr[Mesh.ARRAY_VERTEX]
	var nn: PackedVector3Array = arr[Mesh.ARRAY_NORMAL]
	for i in vv.size():
		vv[i] = xf * vv[i]
		nn[i] = (xf.basis * nn[i]).normalized()
	arr[Mesh.ARRAY_VERTEX] = vv
	arr[Mesh.ARRAY_NORMAL] = nn
	root.free()
	return {"arr": arr, "mat": mat}


static var _imgs := {}


static func _surface_image(m3: MeshInstance3D, s: int) -> Image:
	var mat = m3.get_surface_override_material(s)
	if mat == null:
		mat = m3.mesh.surface_get_material(s)
	var tx: Texture2D = null
	if mat is ShaderMaterial:
		var t = (mat as ShaderMaterial).get_shader_parameter("tex")
		if t is Texture2D:
			tx = t
	elif mat is BaseMaterial3D:
		tx = (mat as BaseMaterial3D).albedo_texture
	if tx == null:
		return null
	if _imgs.has(tx):
		return _imgs[tx]
	var im := tx.get_image()
	if im == null:
		return null
	if im.is_compressed():
		im.decompress()
	if im.get_width() > 512:
		im.resize(512, 512 * im.get_height() / im.get_width(), Image.INTERPOLATE_NEAREST)
	_imgs[tx] = im
	return im


## Read-only copy of the skeleton's current pose (find_bone / get_bone_name / get_bone_global_pose / count).
class SkelSnap:
	var names: PackedStringArray
	var poses: Array = []
	var idx := {}

	func _init(sk: Skeleton3D) -> void:
		for b in sk.get_bone_count():
			names.append(sk.get_bone_name(b))
			poses.append(sk.get_bone_global_pose(b))
			idx[sk.get_bone_name(b)] = b

	func find_bone(n: String) -> int:
		return int(idx.get(n, -1))

	func get_bone_name(b: int) -> String:
		return names[b] if b >= 0 and b < names.size() else ""

	func get_bone_global_pose(b: int) -> Transform3D:
		return poses[b] if b >= 0 and b < poses.size() else Transform3D()

	func get_bone_count() -> int:
		return names.size()


## Everything the fit reads from the scene, as plain data (main thread; the hero posed in idle frame 0).
static func snapshot(model: Node3D, path: String) -> Dictionary:
	var A := load_armor(path)
	if A.is_empty():
		return {}
	var sk := skeleton(model)
	var snap := SkelSnap.new(sk)
	var surfs: Array = []
	for e in _body_src(model):
		var m3: MeshInstance3D = e[0]
		var s: int = e[1]
		var mesh0: ArrayMesh = m3.get_meta("aw_mesh0") if m3.has_meta("aw_mesh0") else m3.mesh
		var skin := m3.skin
		var bb: Array = []
		var bm: Array = []
		for bi in skin.get_bind_count():
			var bidx := skin.get_bind_bone(bi)
			if bidx < 0:
				bidx = sk.find_bone(skin.get_bind_name(bi))
			bb.append(bidx)
			bm.append(sk.get_bone_global_pose(maxi(bidx, 0)) * skin.get_bind_pose(bi))
		surfs.append({"arr": mesh0.surface_get_arrays(s), "bb": bb, "bm": bm, "img": _surface_image(m3, s)})
	return {"A": A, "sk": snap, "r0": _rel(model, sk), "surfs": surfs, "opt": opt.duplicate()}


## Posed body vertices in wrapper space from a snapshot (armor_wear.gd body()).
static func _body(S: Dictionary) -> Dictionary:
	var sk: SkelSnap = S["sk"]
	var r0: Transform3D = S["r0"]
	var P := PackedVector3Array()
	var N := PackedVector3Array()
	var G: Array = []
	var BW: Array = []
	var NM: Array = []
	var COL: Array = []
	var SB: Array = []
	for sf in S["surfs"]:
		var arr: Array = sf["arr"]
		var bb: Array = sf["bb"]
		var bm: Array = sf["bm"]
		var img: Image = sf["img"]
		var vv: PackedVector3Array = arr[Mesh.ARRAY_VERTEX]
		var nn: PackedVector3Array = arr[Mesh.ARRAY_NORMAL]
		var bones = arr[Mesh.ARRAY_BONES]
		var wts = arr[Mesh.ARRAY_WEIGHTS]
		var n := vv.size()
		var per: int = int(bones.size()) / n
		var uvs = arr[Mesh.ARRAY_TEX_UV]
		for i in n:
			if img != null and uvs != null and i < uvs.size():
				var uv: Vector2 = uvs[i]
				var px := Vector2i(clampi(int(fposmod(uv.x, 1.0) * img.get_width()), 0, img.get_width() - 1),
					clampi(int(fposmod(uv.y, 1.0) * img.get_height()), 0, img.get_height() - 1))
				COL.append(img.get_pixelv(px))
			else:
				COL.append(Color.WHITE)
		for i in n:
			var p := Vector3.ZERO
			var q := Vector3.ZERO
			var sbv := Basis(Vector3.ZERO, Vector3.ZERO, Vector3.ZERO)
			var lst: Array = []
			var best := -1
			var bwt := 0.0
			for j in per:
				var w := float(wts[i * per + j])
				if w <= 0.0:
					continue
				var bi2 := int(bones[i * per + j])
				if bi2 < 0 or bi2 >= bb.size() or int(bb[bi2]) < 0:
					continue
				var mx: Transform3D = bm[bi2]
				p += (mx * vv[i]) * w
				q += (mx.basis * (nn[i] if i < nn.size() else Vector3.UP)) * w
				sbv = Basis(sbv.x + mx.basis.x * w, sbv.y + mx.basis.y * w, sbv.z + mx.basis.z * w)
				lst.append([int(bb[bi2]), w])
				if w > bwt:
					bwt = w
					best = int(bb[bi2])
			if best < 0:
				P.append(r0 * vv[i])
				N.append(Vector3.UP)
				G.append("other")
				NM.append("")
				BW.append([])
				SB.append(Basis())
				continue
			P.append(r0 * p)
			N.append((r0.basis * q).normalized())
			G.append(_side_group(sk.get_bone_name(best)))
			NM.append(sk.get_bone_name(best))
			BW.append(lst)
			SB.append(sbv)
	return {"p": P, "n": N, "g": G, "bw": BW, "sk": sk, "r0": r0, "nm": NM, "col": COL, "sb": SB}


## Spatial hash of point indices.
class Grid:
	var cell := 0.05
	var map := {}
	var pts: PackedVector3Array

	func _init(p: PackedVector3Array, c: float, keep: Callable = Callable()) -> void:
		pts = p
		cell = c
		for i in p.size():
			if keep.is_valid() and not keep.call(i):
				continue
			var k := Vector3i((p[i] / cell).floor())
			if not map.has(k):
				map[k] = []
			(map[k] as Array).append(i)

	func near(q: Vector3, k: int, rings: int = 3) -> Array:
		var c := Vector3i((q / cell).floor())
		var got: Array = []
		for r in rings + 1:
			for dx in range(-r, r + 1):
				for dy in range(-r, r + 1):
					for dz in range(-r, r + 1):
						if maxi(absi(dx), maxi(absi(dy), absi(dz))) != r:
							continue
						var key := c + Vector3i(dx, dy, dz)
						if map.has(key):
							for i in (map[key] as Array):
								got.append([q.distance_to(pts[i]), i])
			if got.size() >= k and r >= 1:
				break
		got.sort_custom(func(a, b): return a[0] < b[0])
		return got.slice(0, k)


static func _pct(a: PackedFloat32Array, q: float) -> float:
	if a.is_empty():
		return 0.0
	var s := a.duplicate()
	s.sort()
	return s[clampi(int(q * (s.size() - 1)), 0, s.size() - 1)]


static func _smooth(e0: float, e1: float, x: float) -> float:
	var t := clampf((x - e0) / maxf(1e-6, e1 - e0), 0.0, 1.0)
	return t * t * (3.0 - 2.0 * t)


static func _pw(keys: Array, x: float) -> float:
	var n := keys.size()
	var i := 0
	while i < n - 2 and x > float(keys[i + 1][0]):
		i += 1
	var a0 := float(keys[i][0])
	var a1 := float(keys[i + 1][0])
	var t := (x - a0) / maxf(1e-6, a1 - a0)
	return lerpf(float(keys[i][1]), float(keys[i + 1][1]), t)


static func _rot(a: Vector3, b: Vector3) -> Basis:
	var c := a.cross(b)
	if c.length() < 1e-6:
		return Basis()
	return Basis(c.normalized(), a.angle_to(b))


static func _bp(sk: SkelSnap, r0: Transform3D, names: Array) -> Vector3:
	for nm in names:
		var b := sk.find_bone(str(nm))
		if b >= 0:
			return r0 * sk.get_bone_global_pose(b).origin
	return Vector3.INF


## The fit itself (pure: only the snapshot). Returns {arr (mesh arrays), binds [[bone name, bind]], hid, mv, aabb} or {}.
static func compute(S: Dictionary) -> Dictionary:
	if S.is_empty():
		return {}
	var A: Dictionary = S["A"]
	var B := _body(S)
	var sk: SkelSnap = B["sk"]
	var r0: Transform3D = B["r0"]
	var bp: PackedVector3Array = B["p"]
	var bn: PackedVector3Array = B["n"]
	var bg: Array = B["g"]
	if bp.is_empty():
		return {}
	# ---- hero measures (wrapper space)
	var pel := _bp(sk, r0, ["Pelvis", "Hip"])
	var sp1 := _bp(sk, r0, ["Spine01", "Waist"])
	var cal := _bp(sk, r0, ["L_Calf"])
	var arm := {}
	for s in ["L", "R"]:
		arm[s] = [_bp(sk, r0, [s + "_Upperarm"]), _bp(sk, r0, [s + "_Forearm"]), _bp(sk, r0, [s + "_Hand"]), _bp(sk, r0, [s + "_Clavicle"])]
	var ua_y := (float(arm["L"][0].y) + float(arm["R"][0].y)) * 0.5
	var tx := PackedFloat32Array()
	var tz := PackedFloat32Array()
	var cxs := PackedFloat32Array()
	var arm_r := {"L": [], "R": []}
	for i in bp.size():
		var p := bp[i]
		var g: String = bg[i]
		if g == "torso" and p.y > lerpf(sp1.y, ua_y, 0.3) and p.y < ua_y:
			tx.append(p.x)
			tz.append(p.z)
		if g == "torso":
			cxs.append(p.x)
		for s in ["L", "R"]:
			if g == "arm_" + s:
				var a: Vector3 = arm[s][0]
				var e: Vector3 = arm[s][1]
				var t := clampf((p - a).dot(e - a) / maxf(1e-6, (e - a).length_squared()), 0.0, 1.0)
				if t > 0.3 and t < 0.95:
					(arm_r[s] as Array).append(p.distance_to(a.lerp(e, t)))
	var cx := _pct(cxs, 0.5)
	var hw_c := maxf(absf(_pct(tx, 0.97) - cx), absf(_pct(tx, 0.03) - cx))
	var zf_c := _pct(tz, 0.97)
	var zb_c := _pct(tz, 0.03)
	var ar_c := (_pct(PackedFloat32Array(arm_r["L"]), _o("arq", 0.5)) + _pct(PackedFloat32Array(arm_r["R"]), _o("arq", 0.5))) * 0.5
	# ---- armour measures (armour space)
	var arr: Array = A["arr"]
	var av: PackedVector3Array = arr[Mesh.ARRAY_VERTEX]
	var H := 0.0
	for v in av:
		H = maxf(H, v.y)
	var ax := PackedFloat32Array()
	var az := PackedFloat32Array()
	var ysh := PackedFloat32Array()
	for v in av:
		if v.y > 0.6 * H and v.y < 0.8 * H and absf(v.x) < 0.3 * H:
			ax.append(absf(v.x))
			az.append(v.z)
		if absf(v.x) > 0.2 * H and absf(v.x) < 0.38 * H:
			ysh.append(v.y)
	var aw := _pct(ax, 0.97)
	var azf := _pct(az, 0.97)
	var azb := _pct(az, 0.03)
	var y_sh := _pct(ysh, 0.97)
	var y_belt := _o("belt", 0.45) * H
	var sl := {}
	for s in ["L", "R"]:
		var sg := 1.0 if s == "L" else -1.0
		var pts := PackedVector3Array()
		for v in av:
			if v.x * sg > _o("slx", 0.37) * H and v.y < y_sh - 0.04 * H:
				pts.append(v)
		var c := Vector3.ZERO
		for v in pts:
			c += v
		c /= maxf(1.0, pts.size())
		var dirv := Vector3(0.3 * sg, -1, 0).normalized()
		for it in 30:
			var acc := Vector3.ZERO
			for v in pts:
				var d := v - c
				acc += d * d.dot(dirv)
			dirv = acc.normalized()
		if dirv.y > 0.0:
			dirv = -dirv
		var hi := -INF
		var rr := PackedFloat32Array()
		for v in pts:
			var t := (v - c).dot(dirv)
			hi = maxf(hi, t)
			rr.append(((v - c) - dirv * t).length())
		var top := c + dirv * ((y_sh - 0.13 * H - c.y) / minf(-0.2, dirv.y))
		var wrist := c + dirv * hi
		sl[s] = {"S": top, "W": wrist, "d": dirv, "r": _pct(rr, 0.8), "n": pts.size()}
	var lsign := signf(float(arm["L"][0].x) - cx)
	# ---- fit maps
	var marg := _o("margin", -1.0)
	var sx := hw_c * _o("wpad", 1.15) / maxf(0.01, aw)
	var sz := (zf_c - zb_c) * _o("dpad", 1.2) / maxf(0.01, azf - azb)
	var azc := (azf + azb) * 0.5
	var zc_c := (zf_c + zb_c) * 0.5
	var y_sh_c := ua_y + ar_c * _o("shup", 0.8)
	var y_waist_c := lerpf(pel.y, sp1.y, _o("waist", 0.6))
	var y_hem_c := pel.y - (pel.y - cal.y) * _o("hem", 0.7)
	var ky := [[0.0, y_hem_c], [y_belt, y_waist_c], [y_sh, y_sh_c], [H, y_sh_c + (H - y_sh) * (y_sh_c - y_waist_c) / maxf(0.01, y_sh - y_belt) * _o("collar", 0.7)]]
	var out := PackedVector3Array()
	out.resize(av.size())
	var armw := PackedFloat32Array()
	armw.resize(av.size())
	var sidev := PackedInt32Array()
	sidev.resize(av.size())
	var arm_p := PackedVector3Array()
	for i in av.size():
		var v := av[i]
		var pt := Vector3(cx + v.x * sx, _pw(ky, v.y), zc_c + (v.z - azc) * sz)
		var best_a := 0.0
		var best_p := pt
		var best_s := 0
		for s in ["L", "R"]:
			var sg := 1.0 if s == "L" else -1.0
			if v.x * sg <= 0.0:
				continue
			var S0: Vector3 = sl[s]["S"]
			var W: Vector3 = sl[s]["W"]
			var d: Vector3 = sl[s]["d"]
			var La := S0.distance_to(W)
			var t := (v - S0).dot(d) / maxf(0.01, La)
			var radial := (v - S0) - d * (t * La)
			var dist := radial.length()
			var a := _smooth(_o("t0", 0.0), _o("t1", 0.25), t) * (1.0 - _smooth(float(sl[s]["r"]) * _o("r0", 1.25), float(sl[s]["r"]) * _o("r1", 1.7), dist))
			var hs := "L" if sg == lsign else "R"
			var U: Vector3 = arm[hs][0]
			var E: Vector3 = arm[hs][1]
			var Hn: Vector3 = arm[hs][2]
			var l1 := U.distance_to(E)
			var l2 := E.distance_to(Hn)
			var u := t * (l1 + l2)
			var pc: Vector3
			var dc: Vector3
			var d1 := (E - U).normalized()
			var d2 := (Hn - E).normalized()
			if u < l1:
				pc = U + d1 * u
			else:
				pc = E + d2 * (u - l1)
			var bl := _smooth(l1 - 0.25 * l1, l1 + 0.25 * l1, u)
			dc = d1.slerp(d2, bl).normalized()
			var kr := ar_c * _o("rpad", 1.3) / maxf(0.005, float(sl[s]["r"]))
			var s_t := Vector3(cx + S0.x * sx, _pw(ky, S0.y), zc_c + (S0.z - azc) * sz)
			var fade := 1.0 - _smooth(0.0, _o("fade", 0.6), t)
			var kr2 := lerpf(sx, kr, _smooth(0.0, _o("fade", 0.6), t))
			var pa := pc + (s_t - U) * fade + _rot(d, dc) * (radial * kr2)
			if a > best_a:
				best_a = a
				best_p = pa
				best_s = 1 if hs == "L" else 2
		out[i] = pt
		arm_p.append(best_p)
		armw[i] = best_a
		sidev[i] = best_s
	var ag0 := Grid.new(av, 0.03)
	for _ps in int(_o("smooth", 2.0)):
		var sm := PackedFloat32Array()
		sm.resize(av.size())
		for i in av.size():
			var s := 0.0
			var c := 0.0
			for nb in ag0.near(av[i], 16, 1):
				if float(nb[0]) > _o("srad", 0.045):
					break
				s += armw[int(nb[1])]
				c += 1.0
			sm[i] = s / maxf(1.0, c) if c > 0.0 else armw[i]
		armw = sm
	for i in av.size():
		out[i] = out[i].lerp(arm_p[i], armw[i])
	# ---- the body under the armour plate is hidden
	var y_hide_top := y_sh_c - _o("hidetop", 0.03)
	var y_hide_top_f := y_sh_c - _o("hidetopf", 0.055)
	var y_hide_bot := y_hem_c + _o("hidebot", 0.04)
	var hid := PackedByteArray()
	hid.resize(bp.size())
	var legs := {}
	for s in ["L", "R"]:
		legs[s] = [_bp(sk, r0, [s + "_Thigh"]), _bp(sk, r0, [s + "_Calf"])]
	var thr: Array = []
	var thd := PackedFloat32Array()
	thd.resize(bp.size())
	for i in bp.size():
		if bg[i] != "thigh":
			continue
		var best := INF
		for s in legs:
			var a0: Vector3 = legs[s][0]
			var a1: Vector3 = legs[s][1]
			var tt := clampf((bp[i] - a0).dot(a1 - a0) / maxf(1e-6, (a1 - a0).length_squared()), 0.0, 1.0)
			best = minf(best, bp[i].distance_to(a0.lerp(a1, tt)))
		thd[i] = best
		thr.append(best)
	var thigh_r := _pct(PackedFloat32Array(thr), 0.5)
	var shr := PackedVector3Array()
	shr.resize(bp.size())
	var nshr := 0
	var nhid := 0
	var bcol: Array = B["col"]
	for i in bp.size():
		if _o("hideblue", 1.0) > 0.5 and i < bcol.size() and bg[i] in ["torso", "hips", "thigh", "other"] \
				and bp[i].y > y_hem_c - _o("bluelow", 0.3) and bp[i].y < y_sh_c + 0.05:
			var c: Color = bcol[i]
			if c.b > c.r + _o("bluer", 0.12) and c.b > c.g + _o("blueg", 0.04) and c.b > 0.2:
				hid[i] = 1
				nhid += 1
				continue
		var low := y_hide_bot - (_o("hidecloth", 0.15) if bg[i] == "hips" or bg[i] == "other" or bg[i] == "thigh" else 0.0)
		var top := (y_hide_top_f if bp[i].z > zc_c and absf(bp[i].x - cx) < hw_c * 0.7 else y_hide_top) + (0.05 if bg[i].begins_with("arm") else 0.0)
		if _o("hide", 1.0) < 0.5 or bp[i].y >= top or bp[i].y <= low:
			continue
		var bnm: String = B["nm"][i]
		var arm_hide := _o("hidearm", 1.0) > 0.5 and (bnm.contains("Upperarm") or bnm.contains("Forearm"))
		if arm_hide and _o("hidearmr", 0.0) > 0.0:
			var sd := "L" if bnm.begins_with("L_") else "R"
			var U: Vector3 = arm[sd][0]
			var Hn: Vector3 = arm[sd][2]
			var tt := clampf((bp[i] - U).dot(Hn - U) / maxf(1e-6, (Hn - U).length_squared()), 0.0, 1.0)
			var axp := U.lerp(Hn, tt)
			arm_hide = bp[i].distance_to(axp) > ar_c * _o("hidearmr", 0.0) or tt < _o("hidearmt", 0.3)
			if not arm_hide and _o("armshrink", 0.7) < 0.999:
				shr[i] = (axp - bp[i]) * (1.0 - _o("armshrink", 0.7))
				nshr += 1
		var cloth: bool = bg[i] == "thigh" and thd[i] > thigh_r * _o("clothr", 1.15) and bp[i].y > low - 0.1
		if cloth:
			hid[i] = 1
			nhid += 1
			continue
		if bg[i] == "torso" or bg[i] == "hips" or bg[i] == "other" or arm_hide or (bg[i] == "thigh" and bp[i].y > y_hem_c + _o("hidethigh", 0.08)):
			hid[i] = 1
			nhid += 1
	# ---- shrink-wrap out of the (visible) body (spread over neighbours)
	var bgrid := Grid.new(bp, 0.04, func(i): return bg[i] != "head" and bg[i] != "leg" and hid[i] == 0)
	var push := PackedVector3Array()
	push.resize(out.size())
	for i in out.size():
		var nb := bgrid.near(out[i], 1, 2)
		if nb.is_empty():
			continue
		var j: int = nb[0][1]
		var depth := (out[i] - bp[j]).dot(bn[j])
		if depth < marg:
			push[i] = bn[j] * minf(marg - depth, _o("maxpush", 0.08))
	var agrid := Grid.new(out, 0.03)
	var spread := _o("spread", 0.03)
	var moved := PackedVector3Array()
	moved.resize(out.size())
	for i in out.size():
		var best := push[i]
		for nb in agrid.near(out[i], 24, 1):
			if float(nb[0]) > spread:
				break
			var pv := push[int(nb[1])]
			if pv.length() > best.length():
				best = pv
		moved[i] = out[i] + best
	out = moved
	# ---- weights from the nearest body vertices (region-limited)
	var bw: Array = B["bw"]
	var grids := {
		"torso": Grid.new(bp, 0.04, func(i): return bg[i] in ["torso", "hips"]),
		"skirt": Grid.new(bp, 0.04, func(i): return bg[i] in ["hips", "thigh", "torso"]),
		"L": Grid.new(bp, 0.04, func(i): return bg[i] == "arm_L"),
		"R": Grid.new(bp, 0.04, func(i): return bg[i] == "arm_R"),
	}
	var used := {}
	var vb: Array = []
	var thigh_k := _o("thigh", 0.35)
	var pelvis_b := sk.find_bone("Pelvis")
	var knn := func(reg: String, p: Vector3) -> Dictionary:
		var nbs: Array = (grids[reg] as Grid).near(p, 6, 4)
		if nbs.is_empty():
			nbs = (grids[reg] as Grid).near(p, 6, 12)
		var acc := {}
		var tot := 0.0
		for nb in nbs:
			var k := 1.0 / pow(float(nb[0]) + 0.01, 2.0)
			for e in bw[int(nb[1])]:
				var bo: int = e[0]
				var w: float = float(e[1]) * k
				if reg == "skirt" and _side_group(sk.get_bone_name(bo)) == "thigh":
					acc[pelvis_b] = float(acc.get(pelvis_b, 0.0)) + w * (1.0 - thigh_k)
					w *= thigh_k
				acc[bo] = float(acc.get(bo, 0.0)) + w
				tot += float(e[1]) * k
		for bo in acc:
			acc[bo] = float(acc[bo]) / maxf(1e-9, tot)
		return acc
	var paul := _o("paul", 0.95)
	var pu := _o("pu", 0.7)
	var rigid := {}
	for s in ["L", "R"]:
		var ub := sk.find_bone(s + "_Upperarm")
		var cb := sk.find_bone(s + "_Clavicle")
		var dct := {}
		if ub >= 0:
			dct[ub] = pu
		if cb >= 0:
			dct[cb] = float(dct.get(cb, 0.0)) + (1.0 - pu)
		rigid[s] = dct
	var rig_mode := _o("rigid", 1.0) > 0.5
	var wd: Array = []
	for i in out.size():
		var v := av[i]
		var pw := paul * _smooth(_o("px0", 0.26) * H, _o("px1", 0.42) * H, absf(v.x)) * _smooth(y_sh - 0.4 * H, y_sh - 0.15 * H, v.y)
		var side := "L" if signf(out[i].x - cx) == lsign else "R"
		var acc := {}
		if rig_mode:
			var sw := _smooth(_o("sh0", 0.0), _o("sh1", 1.0), armw[i])
			var pr := pw * (1.0 - sw)
			var base: Dictionary = knn.call("skirt" if v.y < y_belt and sw < 0.5 and pw < 0.5 else "torso", out[i])
			var tb := 1.0 - maxf(sw, pw)
			for bo in base:
				acc[bo] = float(base[bo]) * tb
			if pr > 0.001:
				for bo in rigid[side]:
					acc[bo] = float(acc.get(bo, 0.0)) + float(rigid[side][bo]) * pr
			if sw > 0.001:
				var aw2: Dictionary = knn.call(side, out[i])
				var sa := 1.0 - tb - pr
				for bo in aw2:
					acc[bo] = float(acc.get(bo, 0.0)) + float(aw2[bo]) * sa
		else:
			var share := maxf(armw[i], pw)
			var base: Dictionary = knn.call("skirt" if v.y < y_belt and share < 0.5 else "torso", out[i])
			for bo in base:
				acc[bo] = float(base[bo]) * (1.0 - share)
			if share > 0.001:
				var aw2: Dictionary = knn.call(side, out[i])
				for bo in aw2:
					acc[bo] = float(acc.get(bo, 0.0)) + float(aw2[bo]) * share
		wd.append(acc)
	# smooth the weights over the welded mesh graph
	var idx0: PackedInt32Array = arr[Mesh.ARRAY_INDEX]
	var keyv: Array = []
	var weld := PackedInt32Array()
	weld.resize(av.size())
	var wid := {}
	for i in av.size():
		var kk := Vector3i((av[i] * 5000.0).round())
		keyv.append(kk)
		if not wid.has(kk):
			wid[kk] = wid.size()
		weld[i] = int(wid[kk])
	var nw := wid.size()
	var nbr: Array = []
	nbr.resize(nw)
	for k in nw:
		nbr[k] = {}
	for f in range(0, idx0.size(), 3):
		for e in 3:
			var a0 := weld[idx0[f + e]]
			var a1 := weld[idx0[f + (e + 1) % 3]]
			if a0 != a1:
				(nbr[a0] as Dictionary)[a1] = true
				(nbr[a1] as Dictionary)[a0] = true
	var ww: Array = []
	ww.resize(nw)
	for i in av.size():
		ww[weld[i]] = wd[i]
	var lam := _o("wlam", 0.5)
	for _it in int(_o("wsmooth", 6.0)):
		var nx: Array = []
		nx.resize(nw)
		for k in nw:
			var nb: Dictionary = nbr[k]
			if nb.is_empty():
				nx[k] = ww[k]
				continue
			var avg := {}
			for q in nb:
				for bo in ww[q]:
					avg[bo] = float(avg.get(bo, 0.0)) + float(ww[q][bo])
			var inv := 1.0 / float(nb.size())
			var d := {}
			for bo in ww[k]:
				d[bo] = float(ww[k][bo]) * (1.0 - lam)
			for bo in avg:
				d[bo] = float(d.get(bo, 0.0)) + float(avg[bo]) * inv * lam
			nx[k] = d
		ww = nx
	for i in out.size():
		var acc: Dictionary = ww[weld[i]]
		var l: Array = []
		for bo in acc:
			l.append([bo, float(acc[bo])])
		l.sort_custom(func(x, c): return x[1] > c[1])
		l = l.slice(0, 4)
		var s4 := 0.0
		for e in l:
			s4 += float(e[1])
		for e in l:
			e[1] = float(e[1]) / maxf(1e-9, s4)
			used[int(e[0])] = true
		vb.append(l)
	# skin: bind = inverse(current pose in wrapper space) per used bone
	var binds: Array = []
	var bind_of := {}
	var ub_list := used.keys()
	ub_list.sort()
	for b in ub_list:
		bind_of[b] = binds.size()
		binds.append([sk.get_bone_name(b), (r0 * sk.get_bone_global_pose(b)).affine_inverse()])
	var bones := PackedInt32Array()
	var wts := PackedFloat32Array()
	for l in vb:
		for k in 4:
			if k < (l as Array).size():
				bones.append(int(bind_of[int(l[k][0])]))
				wts.append(float(l[k][1]))
			else:
				bones.append(0)
				wts.append(0.0)
	# normals recomputed from the fitted shape (welded by the source position: no seams)
	var idx: PackedInt32Array = idx0
	var acc_n := {}
	for f in range(0, idx.size(), 3):
		var a0 := idx[f]
		var a1 := idx[f + 1]
		var a2i := idx[f + 2]
		var fn := (out[a1] - out[a0]).cross(out[a2i] - out[a0])
		for q in [a0, a1, a2i]:
			acc_n[keyv[q]] = (acc_n.get(keyv[q], Vector3.ZERO) as Vector3) + fn
	var nn := PackedVector3Array()
	nn.resize(out.size())
	var src_n: PackedVector3Array = arr[Mesh.ARRAY_NORMAL]
	for i in out.size():
		var nv: Vector3 = (acc_n.get(keyv[i], Vector3.ZERO) as Vector3).normalized()
		nn[i] = (nv if nv.dot(src_n[i]) >= 0.0 else -nv) if nv.length() > 0.5 else src_n[i]
	# the shell's inner wall: dropped where it faces the arm / torso axis (the two-sided outer wall is seen instead)
	if _o("noinner", 1.0) > 0.5:
		var ithr := _o("innerdot", -0.3)
		var inner := PackedByteArray()
		inner.resize(out.size())
		for i in out.size():
			var p := out[i]
			var rad: Vector3
			if armw[i] > _o("innerarm", 0.5) and sidev[i] > 0:
				var hs := "L" if sidev[i] == 1 else "R"
				var U: Vector3 = arm[hs][0]
				var Hn: Vector3 = arm[hs][2]
				var tt := clampf((p - U).dot(Hn - U) / maxf(1e-6, (Hn - U).length_squared()), 0.0, 1.0)
				rad = p - U.lerp(Hn, tt)
			else:
				rad = Vector3(p.x - cx, 0.0, p.z - zc_c)
			if rad.length() > 1e-4 and nn[i].dot(rad.normalized()) < ithr:
				inner[i] = 1
		var keep := PackedInt32Array()
		for f in range(0, idx.size(), 3):
			if inner[idx[f]] + inner[idx[f + 1]] + inner[idx[f + 2]] >= int(_o("innerk", 3.0)):
				continue
			keep.append(idx[f])
			keep.append(idx[f + 1])
			keep.append(idx[f + 2])
		idx = keep
	var a2 := []
	a2.resize(Mesh.ARRAY_MAX)
	a2[Mesh.ARRAY_VERTEX] = out
	a2[Mesh.ARRAY_NORMAL] = nn
	a2[Mesh.ARRAY_TEX_UV] = arr[Mesh.ARRAY_TEX_UV]
	a2[Mesh.ARRAY_BONES] = bones
	a2[Mesh.ARRAY_WEIGHTS] = wts
	a2[Mesh.ARRAY_INDEX] = idx
	# wrapper-space arm-tube offsets -> each body vertex's mesh space (inverse of its blended skin basis)
	var mv := PackedVector3Array()
	if nhid > 0 or nshr > 0:
		var sbs: Array = B["sb"]
		mv.resize(bp.size())
		for i in bp.size():
			if shr[i] != Vector3.ZERO:
				var bs: Basis = sbs[i]
				if absf(bs.determinant()) > 1e-6:
					mv[i] = bs.inverse() * (r0.basis.inverse() * shr[i])
	return {"arr": a2, "binds": binds, "hid": hid, "mv": mv, "nhid": nhid,
		"aabb": r0.affine_inverse() * AABB(Vector3(-1.4, -0.4, -1.4), Vector3(2.8, 3.6, 2.8))}


## Fit result -> the record kept in memory / baked / cached: the skinned ArrayMesh (no material) with metas.
static func make_record(res: Dictionary, sig: String) -> ArrayMesh:
	if res.is_empty():
		return null
	var am := ArrayMesh.new()
	am.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, res["arr"])
	var skin := Skin.new()
	for b in res["binds"]:
		skin.add_named_bind(str(b[0]), b[1])
	am.set_meta("aw_skin", skin)
	am.set_meta("aw_hid", res["hid"])
	am.set_meta("aw_mv", res["mv"])
	am.set_meta("aw_aabb", res["aabb"])
	am.set_meta("aw_sig", sig)
	am.set_meta("aw_ver", FIT_VER)
	return am


## Synchronous fit + record (bake tool; the hero posed in idle frame 0).
static func fit_now(model: Node3D, path: String) -> ArrayMesh:
	var sig := signature(model, path)
	var rec := make_record(compute(snapshot(model, path)), sig)
	if rec:
		_mem[sig] = rec
	return rec


static func save(rec: ArrayMesh, file: String) -> int:
	DirAccess.make_dir_recursive_absolute(file.get_base_dir())
	return ResourceSaver.save(rec, file, ResourceSaver.FLAG_COMPRESS)


## Background fit: the snapshot now (the hero's idle frame 0 posed for it), the maths on a worker thread, the record
## made + cached on the main thread when it is done, then every waiting `done` callback runs.
static func _start_fit(model: Node3D, path: String, sig: String, done: Callable) -> void:
	if _jobs.has(sig):
		if done.is_valid():
			(_jobs[sig]["cbs"] as Array).append(done)
		return
	var ap: AnimationPlayer = model.get_meta("anim") as AnimationPlayer if model.has_meta("anim") else null
	var keep_clip := ""
	var keep_pos := 0.0
	if ap and ap.has_animation("idle"):
		keep_clip = ap.current_animation
		keep_pos = ap.current_animation_position if keep_clip != "" else 0.0
		ap.play("idle")
		ap.seek(0.0, true)
	var S := snapshot(model, path)
	if ap and keep_clip != "" and keep_clip != "idle" and ap.has_animation(keep_clip):
		ap.play(keep_clip)
		ap.seek(keep_pos, true)
	var job := {"cbs": [done] if done.is_valid() else [], "res": {}}
	job["task"] = WorkerThreadPool.add_task(func(): job["res"] = compute(S), false, "hy3d armour fit")
	_jobs[sig] = job
	fits_started += 1
	_poll(sig)


static func _poll(sig: String) -> void:
	var job: Dictionary = _jobs.get(sig, {})
	if job.is_empty():
		return
	var ml = Engine.get_main_loop()
	if not WorkerThreadPool.is_task_completed(int(job["task"])):
		if ml is SceneTree:
			(ml as SceneTree).create_timer(0.1).timeout.connect(func(): _poll(sig))
		return
	WorkerThreadPool.wait_for_task_completion(int(job["task"]))
	_jobs.erase(sig)
	var rec := make_record(job["res"], sig)
	if rec == null:
		push_warning("hy3d_armor: background fit failed")
		return
	_mem[sig] = rec
	var e := save(rec, CACHE_DIR.path_join(sig.md5_text() + ".res"))
	if e != OK:
		push_warning("hy3d_armor: cache not saved (%s)" % error_string(e))
	for cb in job["cbs"]:
		if (cb as Callable).is_valid():
			(cb as Callable).call()


static func pending() -> int:
	return _jobs.size()


## Tests: forget the in-memory records (the bake / user cache stay).
static func clear_mem() -> void:
	_mem.clear()
	_hid_meshes.clear()
