File size: 8,595 Bytes
fbaaedb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4e19f9
fbaaedb
 
a4e19f9
 
 
 
 
 
 
fbaaedb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# Runs inside headless Blender: blender -b --python process.py -- in.glb out.glb report.json '{}'
import bpy, sys, json, re, traceback
from mathutils import Vector

argv = sys.argv[sys.argv.index("--") + 1:]
SRC, DST, REP = argv[0], argv[1], argv[2]
OPTS = json.loads(argv[3] or "{}")
report = {"blender": bpy.app.version_string, "warnings": []}


def norm(n):
    n = n.lower().split(":")[-1]
    return re.sub(r"[^a-z0-9]", "", n)


def side_names(base, side):
    s, l = ("left", "l") if side == "L" else ("right", "r")
    return [s + b for b in base] + [b + l for b in base] + [l + b for b in base]


CORE = {
    "hips": ["hips", "pelvis"], "spine": ["spine", "spine01", "spine1"], "neck": ["neck", "neck01"], "head": ["head"],
}
for sd in ("L", "R"):
    CORE[f"arm_{sd}"] = side_names(["arm", "upperarm", "shoulder"], sd)
    CORE[f"forearm_{sd}"] = side_names(["forearm", "lowerarm"], sd)
    CORE[f"hand_{sd}"] = side_names(["hand"], sd)
    CORE[f"upleg_{sd}"] = side_names(["upleg", "thigh", "upperleg"], sd)
    CORE[f"leg_{sd}"] = side_names(["leg", "calf", "shin", "lowerleg", "knee"], sd)


def reset():
    bpy.ops.wm.read_factory_settings(use_empty=True)


def mesh_objs():
    return [o for o in bpy.context.scene.objects if o.type == "MESH"]


def shape_names():
    out = []
    for o in mesh_objs():
        if o.data.shape_keys:
            out += [k.name for k in o.data.shape_keys.key_blocks if k.name != "Basis"]
    return out


def main():
    reset()
    bpy.ops.import_scene.gltf(filepath=SRC)
    arms = [o for o in bpy.context.scene.objects if o.type == "ARMATURE"]
    meshes = mesh_objs()
    report["mesh"] = {"objects": len(meshes), "vertices": sum(len(o.data.vertices) for o in meshes)}
    if not arms:
        report["error"] = "No skeleton found. Rig the character first."
        return
    arm = max(arms, key=lambda a: len(a.data.bones))
    bones = {norm(b.name): b.name for b in arm.data.bones}
    found, missing = {}, []
    for key, cands in CORE.items():
        hit = next((bones[c] for c in cands if c in bones), None)
        if hit:
            found[key] = hit
        else:
            missing.append(key)
    report["skeleton"] = {"compatible": not missing, "missing_bones": missing, "bone_count": len(arm.data.bones), "armature": arm.name}

    existing = shape_names()
    report["face"] = add_face(arm, found.get("head"), existing) if OPTS.get("face", True) else {"status": "skipped", "reason": "disabled"}
    report["hair"] = add_hair(arm, found.get("head"), bones) if OPTS.get("hair", True) else {"status": "skipped", "reason": "disabled"}

    bpy.ops.object.mode_set(mode="OBJECT") if bpy.context.object and bpy.context.object.mode != "OBJECT" else None
    bpy.ops.export_scene.gltf(filepath=DST, export_format="GLB", export_skins=True, export_morph=True, export_animations=True, export_apply=False)

    # Validate by re-importing the exported file into a clean scene.
    reset()
    bpy.ops.import_scene.gltf(filepath=DST)
    names = shape_names()
    a2 = [o for o in bpy.context.scene.objects if o.type == "ARMATURE"]
    report["validation"] = {
        "reimported": True,
        "bone_count": max((len(a.data.bones) for a in a2), default=0),
        "shape_keys": names[:40],
        "visemes": len([n for n in names if n.lower().startswith("viseme_")]),
        "arkit": len([n for n in names if n in ("jawOpen", "mouthClose", "mouthSmile", "eyeBlinkLeft", "eyeBlinkRight")]),
        "hair_bones": max((len([b for b in a.data.bones if "hair" in b.name.lower()]) for a in a2), default=0),
    }


def head_verts(arm, head):
    """(object, [vertex indices], [world coords]) weighted mostly to the head bone."""
    out = []
    for o in mesh_objs():
        if o.find_armature() != arm or head not in o.vertex_groups:
            continue
        gi = o.vertex_groups[head].index
        idx, co = [], []
        for v in o.data.vertices:
            for g in v.groups:
                if g.group == gi and g.weight > 0.5:
                    idx.append(v.index); co.append(o.matrix_world @ v.co)
        if idx:
            out.append((o, idx, co))
    return out


def add_face(arm, head, existing):
    if any(n in existing for n in ("jawOpen", "viseme_aa")):
        return {"status": "existing", "shape_keys": existing[:20]}
    if not head:
        return {"status": "skipped", "reason": "no head bone"}
    hv = head_verts(arm, head)
    allc = [c for _, _, cs in hv for c in cs]
    if len(allc) < 200:
        return {"status": "skipped", "reason": "head region could not be isolated from skin weights"}
    zs = [c.z for c in allc]; ys = [c.y for c in allc]; xs = [c.x for c in allc]
    zmin, zmax, ymin, ymax = min(zs), max(zs), min(ys), max(ys)
    xmid = (min(xs) + max(xs)) / 2
    h, depth, width = zmax - zmin, ymax - ymin, max(xs) - min(xs)
    # Front faces -Y after glTF import. Mouth: lower 15-40% of head, front 30%, middle 45% of width.
    z0, z1, yf = zmin + 0.15 * h, zmin + 0.40 * h, ymin + 0.30 * depth
    picks = []
    for o, idx, co in hv:
        sel = [(i, c) for i, c in zip(idx, co) if z0 <= c.z <= z1 and c.y <= yf and abs(c.x - xmid) <= 0.225 * width]
        if sel:
            picks.append((o, sel))
    total = sum(len(s) for _, s in picks)
    if total < 20 or total > 8000:
        return {"status": "skipped", "reason": f"mouth region looked unreliable ({total} vertices)"}
    added = []
    for o, sel in picks:
        if not o.data.shape_keys:
            o.shape_key_add(name="Basis", from_mix=False)
        inv = o.matrix_world.inverted().to_3x3()
        for name, amt in (("jawOpen", 0.06), ("viseme_aa", 0.05)):
            k = o.shape_key_add(name=name, from_mix=False)
            for i, c in sel:
                fall = 1.0 - (c.z - z0) / max(z1 - z0, 1e-6)  # lower lip moves most
                k.data[i].co = o.data.vertices[i].co + inv @ Vector((0, 0, -amt * h * fall))
        added.append(o.name)
    return {"status": "added", "confidence": "experimental", "shape_keys": ["jawOpen", "viseme_aa"], "vertices": total, "meshes": added}


def add_hair(arm, head, bones):
    if any("hair" in k for k in bones):
        return {"status": "existing", "bone_total": len([k for k in bones if "hair" in k])}
    if not head:
        return {"status": "skipped", "reason": "no head bone"}
    targets = []
    for o in mesh_objs():
        if o.find_armature() != arm:
            continue
        if "hair" in o.name.lower():
            targets.append((o, [v.index for v in o.data.vertices]))
            continue
        mats = [i for i, m in enumerate(o.data.materials) if m and "hair" in m.name.lower()]
        if mats:
            vs = {vi for p in o.data.polygons if p.material_index in mats for vi in p.vertices}
            targets.append((o, sorted(vs)))
    if not targets:
        return {"status": "skipped", "reason": "hair is not a separate mesh or material, so it can't be told apart from the head"}
    co = [o.matrix_world @ o.data.vertices[i].co for o, ids in targets for i in ids]
    top, bot = max(c.z for c in co), min(c.z for c in co)
    ymax = max(c.y for c in co)
    xmid = sum(c.x for c in co) / len(co)
    if top - bot < 1e-4:
        return {"status": "skipped", "reason": "hair region is flat"}
    names = ["hair_01", "hair_02", "hair_03"]
    inv = arm.matrix_world.inverted()
    bpy.context.view_layer.objects.active = arm
    bpy.ops.object.mode_set(mode="EDIT")
    eb = arm.data.edit_bones
    parent = eb[head]
    seg = (top - bot) / 3
    for i, n in enumerate(names):
        b = eb.new(n)
        b.head = inv @ Vector((xmid, ymax * 0.9, top - seg * i))
        b.tail = inv @ Vector((xmid, ymax * 0.9, top - seg * (i + 1)))
        b.parent = parent
        b.use_connect = i > 0
        parent = b
    bpy.ops.object.mode_set(mode="OBJECT")
    for o, ids in targets:
        hg = o.vertex_groups.get(head) or o.vertex_groups.new(name=head)
        groups = [o.vertex_groups.get(n) or o.vertex_groups.new(name=n) for n in names]
        for i in ids:
            t = (top - (o.matrix_world @ o.data.vertices[i].co).z) / (top - bot)
            seg_i = min(2, int(t * 3))
            w = min(0.85, 0.25 + t * 0.6)
            groups[seg_i].add([i], w, "REPLACE")
            hg.add([i], 1 - w, "REPLACE")
    return {"status": "added", "confidence": "experimental", "bones": names, "bone_total": 3, "vertices": sum(len(i) for _, i in targets)}


try:
    main()
except Exception as e:
    report["error"] = f"{e}"
    report["trace"] = traceback.format_exc()[-800:]
with open(REP, "w") as f:
    json.dump(report, f)