"""One authored skin field shared across touching garment/arm surfaces."""
import numpy as np
from livideo2d.deform import brush_weights

def smoothstep(t):
    t=np.clip(t,0,1);return t*t*(3-2*t)

def capsule(points,a,b,inner,outer):
    a,b=np.array(a,float),np.array(b,float);direction=b-a
    t=np.clip((points-a)@direction/(direction@direction),0,1)
    d=np.linalg.norm(points-(a+t[:,None]*direction),axis=1)
    return 1-smoothstep((d-inner)/(outer-inner))

def body_weights(points):
    points=np.asarray(points,float)
    # The hidden far wrist is an uncertain V5 observation. Its near-straight IK
    # chain must not drag visible lapels through a large inferred elbow rotation.
    bones=['torso','pelvis','upper_left','fore_left','hand_left']
    weights=np.zeros((len(points),len(bones)))
    weights[:,1]=smoothstep((points[:,1]-515)/95);weights[:,0]=1-weights[:,1]
    fields=[capsule(points,[382,325],[392,423],18,42),
            capsule(points,[429,470],[467,370],15,38),
            brush_weights(points,[478,345],[38,44],.5)]
    for i,field in enumerate(fields,2):
        weights*=1-field[:,None];weights[:,i]+=field
    return {'bones':bones,'weights':weights.tolist()}
