"""Fit the gloved hands onto the rifle: no penetration, finger pads in contact, natural joints. Run in Blender after pose_hands_natural.py has been exec'd into the same namespace `g`: g = {'__name__': 'pose'} exec(open(r'C:\\roblox\\hunter\\blender\\pose_hands_natural.py', encoding='utf-8').read(), g) exec(open(r'C:\\roblox\\hunter\\blender\\fit_grip.py', encoding='utf-8').read(), g) print(g['FIT_RESULT']) # paste the numbers back into pose_hands_natural.py Each hand is fitted by coordinate descent over its placement (knuckle point, orientation) and joint angles. The cost punishes penetration hard, rewards finger pads resting on the surface, and keeps joints near a natural curl. Inside/outside: every rifle part is a closed mesh, so a glove vertex is inside a part when a ray from it crosses that part's surface an odd number of times (parts pre-filtered by bounding box). """ import math import time import bpy from mathutils import Vector from mathutils.bvhtree import BVHTree FINGERS = ('index', 'middle', 'ring', 'pink') DEPTH_WEIGHT = 40.0 # penetration is far worse than a small gap CONTACT_GAP = 0.01 # a phalanx counts as touching below this gap RAY_DIR = Vector((0.5774, 0.5774, 0.5774)) TRIGGER = Vector((-2.35, -0.06, -0.35)) HANDGUARD_TOP = 0.5 def build_rifle_bvh(): dg = bpy.context.evaluated_depsgraph_get() verts, polys, parts = [], [], [] for o in bpy.data.collections['Rifle V4'].objects: if o.type != 'MESH' or o.hide_render: continue oe = o.evaluated_get(dg) me = oe.to_mesh() wv = [oe.matrix_world @ v.co for v in me.vertices] wp = [list(p.vertices) for p in me.polygons] oe.to_mesh_clear() lo = Vector([min(v[i] for v in wv) for i in range(3)]) hi = Vector([max(v[i] for v in wv) for i in range(3)]) parts.append((lo, hi, BVHTree.FromPolygons(wv, wp), o.name)) base = len(verts) verts += wv polys += [[base + i for i in p] for p in wp] return BVHTree.FromPolygons(verts, polys), parts def depth_inside(p): """Penetration depth of point p into the rifle (0 when outside).""" deepest = 0.0 for lo, hi, tree, _ in PARTS: if not (lo.x <= p.x <= hi.x and lo.y <= p.y <= hi.y and lo.z <= p.z <= hi.z): continue hits, origin = 0, p.copy() while True: loc, _, _, _ = tree.ray_cast(origin, RAY_DIR) if loc is None: break hits += 1 origin = loc + RAY_DIR * 1e-4 if hits % 2: deepest = max(deepest, tree.find_nearest(p)[3]) return deepest GLOVE = bpy.data.objects['hardknuckle'] RIFLE, PARTS = build_rifle_bvh() _groups = {vg.index: vg.name for vg in GLOVE.vertex_groups} OWNER = [] for _v in GLOVE.data.vertices: _best = max(_v.groups, key=lambda gw: gw.weight, default=None) OWNER.append(_groups[_best.group] if _best else None) def chain(finger, side): if finger == 'thumb': return [f'thumb_L.{side}', f'thumb_L.002.{side}', f'thumb_L.001.{side}'] return [f'{finger}_L.{side}', f'{finger}_L.003.{side}', f'{finger}_L.002.{side}', f'{finger}_L.001.{side}'] def hand_bones(side): return [f'hand_L.{side}'] + [b for f in FINGERS + ('thumb',) for b in chain(f, side)] def measure(bones): """{bone: [penetration depth sum, closest outside gap]} for glove vertices owned by `bones`.""" bpy.context.view_layer.update() ge = GLOVE.evaluated_get(bpy.context.evaluated_depsgraph_get()) me = ge.to_mesh() mw = ge.matrix_world out = {b: [0.0, 9.0] for b in bones} for i, v in enumerate(me.vertices): b = OWNER[i] if b not in out: continue p = mw @ v.co d = depth_inside(p) if d > 0: out[b][0] += d else: loc, _, _, dist = RIFLE.find_nearest(p, 0.8) if loc is not None: out[b][1] = min(out[b][1], dist) ge.to_mesh_clear() return out def world(bone, at='head'): pb = rig.pose.bones[bone] return rig.matrix_world @ (pb.head if at == 'head' else pb.tail) # ------------------------------------------------------------------ parameterisation def set_rot(bone, x=0.0, z=0.0): pb = rig.pose.bones[bone] pb.rotation_mode = 'XYZ' pb.rotation_euler = (math.radians(x), 0.0, math.radians(z)) def aim_elbow(side, pole): s_ = world(f'upperarm_L.{side}') w_ = world(f'hand_IK_L.{side}') set_world(f'elbow_IK_L.{side}', (s_ + w_) / 2 + pole) def rotate_axes(axes, tilt): from mathutils import Euler r = Euler([math.radians(t) for t in tilt], 'XYZ').to_matrix() return [r @ a for a in axes] def apply_right(p): zr = GRIP_AXIS.normalized() xr = Vector((0, -1, 0)) axes = rotate_axes((xr, zr.cross(xr), zr), (p['tx'], p['ty'], p['tz'])) place_hand('R', RIGHT_KNUCKLE + Vector((p['kx'], p['ky'], p['kz'])), *axes) aim_elbow('R', RIGHT_ELBOW_POLE) for f in ('middle', 'ring', 'pink'): spread = {'middle': 0, 'ring': 1, 'pink': 2}[f] * p['fan'] # lower fingers curl a bit more for b, deg in zip(chain(f, 'R'), (p['b0'] + spread, p['b1'], p['b2'], p['b2'] * 0.5)): set_rot(b, z=deg) for b, deg in zip(chain('index', 'R'), (p['i0'], p['i1'], p['i2'], p['i2'] * 0.6)): set_rot(b, z=deg) rig.pose.bones['index_L.R'].rotation_euler.x = math.radians(p['ilift']) t = chain('thumb', 'R') set_rot(t[0], x=p['t0x'], z=p['t0']) set_rot(t[1], z=p['t1']) set_rot(t[2], z=p['t2']) bpy.context.view_layer.update() def apply_left(p): xl = (LEFT_PALM_NORMAL + Vector((0, p['ny'], 0))).normalized() a = math.radians(p['ang']) yl = math.cos(a) * Vector((1, 0, 0)) + math.sin(a) * Vector((0, -1, 0)) yl = (yl - xl * yl.dot(xl)).normalized() axes = rotate_axes((xl, yl, xl.cross(yl)), (p['tx'], 0.0, 0.0)) place_hand('L', LEFT_KNUCKLE + Vector((p['kx'], p['ky'], p['kz'])), *axes) aim_elbow('L', LEFT_ELBOW_POLE) for i, f in enumerate(FINGERS): for b, deg in zip(chain(f, 'L'), (p['b0'] + i * p['fan'], p['b1'], p['b2'], p['b2'] * 0.6)): set_rot(b, z=-deg) t = chain('thumb', 'L') set_rot(t[0], x=p['t0x'], z=-p['t0']) set_rot(t[1], z=-p['t1']) set_rot(t[2], z=-p['t2']) bpy.context.view_layer.update() # ------------------------------------------------------------------ costs def contact_terms(m, side, fingers): gap = 0.0 for f in fingers: for b in chain(f, side)[-2:]: # the two outer phalanges carry the pads if m[b][0] == 0: gap += max(0.0, m[b][1] - CONTACT_GAP) hb = f'hand_L.{side}' if m[hb][0] == 0: gap += 2 * max(0.0, m[hb][1] - CONTACT_GAP) # palm must rest on the rifle return gap def right_cost(p): apply_right(p) m = measure(hand_bones('R')) depth = sum(v[0] for v in m.values()) c = DEPTH_WEIGHT * depth + contact_terms(m, 'R', ('middle', 'ring', 'pink', 'thumb')) pad = (world('index_L.001.R') + world('index_L.001.R', 'tail')) / 2 c += 1.5 * (pad - TRIGGER).length # index pad on the trigger c += 0.002 * (abs(p['tx']) + abs(p['ty']) + abs(p['tz'])) return c, depth def left_cost(p): apply_left(p) m = measure(hand_bones('L')) depth = sum(v[0] for v in m.values()) c = DEPTH_WEIGHT * depth + contact_terms(m, 'L', FINGERS + ('thumb',)) for f in FINGERS: # fingertips stay on the side, below the top edge tip = world(chain(f, 'L')[-1], 'tail') c += 3.0 * max(0.0, tip.z - (HANDGUARD_TOP - 0.15)) c += 0.002 * abs(p['tx']) return c, depth def descend(cost_fn, p, steps, limits, rounds=4, budget=60.0): """Coordinate descent: try +-step on each parameter, halve the steps each round.""" t0 = time.time() best, depth = cost_fn(p) evals = 1 for _ in range(rounds): improved = True while improved and time.time() - t0 < budget: improved = False for k in p: for sgn in (1, -1): q = dict(p) lo, hi = limits.get(k, (-1e9, 1e9)) q[k] = min(hi, max(lo, p[k] + sgn * steps[k])) if q[k] == p[k]: continue c, d = cost_fn(q) evals += 1 if c < best - 1e-5: best, depth, p, improved = c, d, q, True break steps = {k: v / 2 for k, v in steps.items()} cost_fn(p) return p, round(best, 4), round(depth, 4), evals RIGHT_START = dict(kx=0.0, ky=0.0, kz=0.0, tx=0.0, ty=0.0, tz=0.0, fan=3.0, b0=80.0, b1=60.0, b2=40.0, i0=35.0, i1=45.0, i2=25.0, ilift=10.0, t0x=0.0, t0=60.0, t1=-20.0, t2=-10.0) RIGHT_STEPS = dict(kx=0.04, ky=0.04, kz=0.04, tx=6, ty=6, tz=6, fan=3, b0=8, b1=8, b2=8, i0=8, i1=8, i2=8, ilift=5, t0x=8, t0=8, t1=8, t2=8) LEFT_START = dict(kx=0.0, ky=-0.05, kz=-0.03, ny=0.0, ang=65.0, tx=0.0, fan=3.0, b0=55.0, b1=40.0, b2=20.0, t0x=0.0, t0=20.0, t1=10.0, t2=5.0) LEFT_STEPS = dict(kx=0.04, ky=0.04, kz=0.04, ny=0.1, ang=8, tx=6, fan=3, b0=8, b1=8, b2=8, t0x=8, t0=8, t1=8, t2=8) JOINT_LIMITS = {k: (0, 100) for k in ('b0', 'b1', 'b2', 'i0', 'i1', 'i2')} JOINT_LIMITS.update(fan=(0, 10), ilift=(-10, 30), t0x=(-40, 40), t0=(-30, 90), t1=(-60, 60), t2=(-60, 60), ang=(20, 90), ny=(-0.6, 0.6), tx=(-30, 30), ty=(-30, 30), tz=(-30, 30)) RIGHT_FIT = descend(right_cost, dict(RIGHT_START), RIGHT_STEPS, JOINT_LIMITS) LEFT_FIT = descend(left_cost, dict(LEFT_START), LEFT_STEPS, JOINT_LIMITS) final = measure(hand_bones('R') + hand_bones('L')) FIT_RESULT = { 'RIGHT': {k: round(v, 2) for k, v in RIGHT_FIT[0].items()}, 'LEFT': {k: round(v, 2) for k, v in LEFT_FIT[0].items()}, 'right_cost_depth_evals': RIGHT_FIT[1:], 'left_cost_depth_evals': LEFT_FIT[1:], 'bones_penetrating': sorted(b for b, v in final.items() if v[0] > 0), 'bones_touching': sorted(b for b, v in final.items() if v[0] == 0 and v[1] <= CONTACT_GAP), } print(FIT_RESULT)