File size: 13,603 Bytes
ccf0740
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# blender/autorig_pipeline.py
# ํ—ค๋“œ๋ฆฌ์Šค(๋ฐฐ์น˜) ์‚ฌ์šฉ ์˜ˆ:
# blender -b --python blender/autorig_pipeline.py -- \
#   --in model.glb --out rigged_toon.fbx --export fbx \
#   --outline --toon --surface_deform --limit_cloth_bones --try_faceit
#
# ๊ธฐ๋Šฅ ์š”์•ฝ:
# 1) GLB/GLTF/FBX/OBJ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ
# 2) Body/์˜๋ณต/ํ—ค์–ด/์†Œํ’ˆ ๋Œ€๋žต ๋ถ„๋ฅ˜
# 3) ํœด๋จธ๋…ธ์ด๋“œ Armature(T-ํฌ์ฆˆ) ์ž๋™ ์ƒ์„ฑ + Body ์ž๋™ ๊ฐ€์ค‘์น˜
# 4) ์˜๋ณต: Surface Deform ๋˜๋Š” ๋ณธ ์˜ํ–ฅ ์ถ•์†Œ
# 5) Toon ๋จธํ‹ฐ๋ฆฌ์–ผ + ์ธ๋ฒ„ํ‹ฐ๋“œ ํ—(Outline) ์ ์šฉ
# 6) ํ‘œ์ •: Faceit ๊ฐ์ง€ ์‹œ ์•ˆ๋‚ด, ์—†์œผ๋ฉด ๊ธฐ๋ณธ Shape Key ํ”Œ๋ ˆ์ด์Šคํ™€๋” ์ƒ์„ฑ
# 7) FBX ๋˜๋Š” GLB ๋‚ด๋ณด๋‚ด๊ธฐ

import bpy, sys, os, math, argparse
from mathutils import Vector, Matrix

# -----------------------
# CLI args
# -----------------------
def parse_args():
    argv = sys.argv
    if "--" in argv:
        argv = argv[argv.index("--") + 1:]
    else:
        argv = []
    p = argparse.ArgumentParser()
    p.add_argument("--in",  dest="inp", required=True,  help="์ž…๋ ฅ ๊ฒฝ๋กœ (GLB/GLTF/FBX/OBJ)")
    p.add_argument("--out", dest="out", required=True,  help="์ถœ๋ ฅ ํŒŒ์ผ ๊ฒฝ๋กœ")
    p.add_argument("--export", choices=["fbx", "glb"], default="fbx", help="๋‚ด๋ณด๋‚ด๊ธฐ ํฌ๋งท")
    p.add_argument("--outline", action="store_true", help="์ธ๋ฒ„ํ‹ฐ๋“œ ํ— ์™ธ๊ณฝ์„  ์ƒ์„ฑ")
    p.add_argument("--toon", action="store_true", help="Toon ์…ฐ์ด๋”ฉ ์ ์šฉ")
    p.add_argument("--surface_deform", action="store_true", help="์˜๋ณต Surface Deform ๋ฐ”์ธ๋”ฉ")
    p.add_argument("--limit_cloth_bones", action="store_true", help="์˜๋ณต Armature ๋ณธ ์˜ํ–ฅ ์ถ•์†Œ(๊ฐ„์ด)")
    p.add_argument("--try_faceit", action="store_true", help="์„ค์น˜ ์‹œ Faceit ํ™œ์šฉ ์•ˆ๋‚ด")
    p.add_argument("--scale", type=float, default=1.0, help="์ „์ฒด ์Šค์ผ€์ผ")
    return p.parse_args()

args = parse_args()
inp_path  = bpy.path.abspath(args.inp)
out_path  = bpy.path.abspath(args.out)
export_fmt = args.export

# -----------------------
# ์ดˆ๊ธฐํ™”
# -----------------------
for obj in list(bpy.data.objects):
    obj.select_set(False)

# -----------------------
# Import model
# -----------------------
ext = os.path.splitext(inp_path)[1].lower()
if ext in [".glb", ".gltf"]:
    bpy.ops.import_scene.gltf(filepath=inp_path)
elif ext in [".fbx"]:
    bpy.ops.import_scene.fbx(filepath=inp_path)
elif ext in [".obj"]:
    bpy.ops.import_scene.obj(filepath=inp_path)
else:
    raise RuntimeError("์ง€์›ํ•˜์ง€ ์•Š๋Š” ํฌ๋งท: " + ext)

# ๋ชจ๋“  Mesh ์ˆ˜์ง‘
meshes = [o for o in bpy.context.scene.objects if o.type == "MESH"]
if not meshes:
    raise RuntimeError("MESH ์˜ค๋ธŒ์ ํŠธ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")

# ์ปฌ๋ ‰์…˜ ์ •๋ฆฌ
coll = bpy.data.collections.new("CHARACTER")
bpy.context.scene.collection.children.link(coll)
for o in meshes:
    # ๊ธฐ์กด ์ปฌ๋ ‰์…˜์—์„œ ์ œ๊ฑฐ ํ›„ ์ƒˆ ์ปฌ๋ ‰์…˜์œผ๋กœ ์ด๋™
    if o.users_collection:
        for c in o.users_collection:
            try:
                c.objects.unlink(o)
            except Exception:
                pass
    coll.objects.link(o)

# ์Šค์ผ€์ผ ์ •๋ฆฌ
for o in meshes:
    o.select_set(True)
bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
for o in meshes:
    o.select_set(False)

# -----------------------
# Body ์ถ”์ •: ๋ฐ”์šด๋”ฉ๋ฐ•์Šค ๋ณผ๋ฅจ ๊ธฐ์ค€
# -----------------------
def mesh_bbox_volume(obj):
    m = obj.matrix_world
    bb = [m @ Vector(corner) for corner in obj.bound_box]
    minv = Vector((min(v.x for v in bb), min(v.y for v in bb), min(v.z for v in bb)))
    maxv = Vector((max(v.x for v in bb), max(v.y for v in bb), max(v.z for v in bb)))
    sz = maxv - minv
    return abs(sz.x * sz.y * sz.z)

volumes = sorted([(mesh_bbox_volume(o), o) for o in meshes], key=lambda x: x[0], reverse=True)
body   = volumes[0][1]
others = [o for _, o in volumes[1:]]

body.name = "Body"

# ์˜๋ณต/ํ—ค์–ด/์†Œํ’ˆ ํ‚ค์›Œ๋“œ ๋ถ„๋ฅ˜(๊ฐ„์ด)
CLOTH_KEYS = ["cloth","skirt","dress","coat","cape","jacket","shirt","pants","sleeve","kimono","robe"]
HAIR_KEYS  = ["hair","bang","ponytail","fringe","bun","pigtail"]

def classify(o):
    name = (o.name + " " + " ".join([m.name for m in o.data.materials if m])).lower()
    if any(k in name for k in CLOTH_KEYS): return "Cloth"
    if any(k in name for k in HAIR_KEYS):  return "Hair"
    return "Prop"

for o in others:
    try:
        o["part_type"] = classify(o)
    except Exception:
        pass

# -----------------------
# Armature ์ƒ์„ฑ (๊ฐ„์ด ํœด๋จธ๋…ธ์ด๋“œ T-ํฌ์ฆˆ)
# -----------------------
bpy.ops.object.armature_add(enter_editmode=True)
arm = bpy.context.object
arm.name = "Armature"
eb = arm.data.edit_bones

# Body AABB ๊ธฐ๋ฐ˜ ์ค‘์‹ฌ/ํฌ๊ธฐ
bb = [body.matrix_world @ Vector(c) for c in body.bound_box]
minv = Vector((min(v.x for v in bb), min(v.y for v in bb), min(v.z for v in bb)))
maxv = Vector((max(v.x for v in bb), max(v.y for v in bb), max(v.z for v in bb)))
cent = (minv + maxv) / 2
height = (maxv.z - minv.z)
width  = (maxv.x - minv.x)

def add_bone(name, head, tail, parent=None, roll=0.0):
    b = eb.new(name)
    b.head = head; b.tail = tail; b.roll = roll
    if parent: b.parent = parent
    return b

# ์ฝ”์–ด ์ŠคํŒŒ์ธ
hips  = add_bone("Hips",  Vector((cent.x, cent.y, minv.z + height*0.20)), Vector((cent.x, cent.y, minv.z + height*0.30)))
spine = add_bone("Spine", hips.tail, Vector((cent.x, cent.y, minv.z + height*0.45)), parent=hips)
chest = add_bone("Chest", spine.tail, Vector((cent.x, cent.y, minv.z + height*0.60)), parent=spine)
neck  = add_bone("Neck",  Vector((cent.x, cent.y, minv.z + height*0.68)), Vector((cent.x, cent.y, minv.z + height*0.74)), parent=chest)
headb = add_bone("Head",  neck.tail, Vector((cent.x, cent.y, minv.z + height*0.86)), parent=neck)

# ํŒ”(T-ํฌ์ฆˆ)
arm_len = max(width*0.35, 0.05)
ua_L = add_bone("UpperArm.L", Vector((cent.x+0.05*width, cent.y, chest.tail.z-0.02*height)),
                Vector((cent.x+0.05*width+arm_len*0.5, cent.y, chest.tail.z-0.02*height)), parent=chest)
fa_L = add_bone("LowerArm.L", ua_L.tail, ua_L.tail + Vector((arm_len*0.5, 0, 0)), parent=ua_L)
handL= add_bone("Hand.L",     fa_L.tail, fa_L.tail + Vector((arm_len*0.2, 0, 0)), parent=fa_L)
ua_R = add_bone("UpperArm.R", Vector((cent.x-0.05*width, cent.y, chest.tail.z-0.02*height)),
                Vector((cent.x-0.05*width-arm_len*0.5, cent.y, chest.tail.z-0.02*height)), parent=chest)
fa_R = add_bone("LowerArm.R", ua_R.tail, ua_R.tail - Vector((arm_len*0.5, 0, 0)), parent=ua_R)
handR= add_bone("Hand.R",     fa_R.tail, fa_R.tail - Vector((arm_len*0.2, 0, 0)), parent=fa_R)

# ๋‹ค๋ฆฌ
leg_off = max(width*0.12, 0.02)
thighL = add_bone("Thigh.L", Vector((cent.x+leg_off, cent.y, hips.head.z)), Vector((cent.x+leg_off, cent.y, minv.z + height*0.05)), parent=hips)
shinL  = add_bone("Shin.L",  thighL.tail, Vector((cent.x+leg_off, cent.y, minv.z + 0.01*height)), parent=thighL)
footL  = add_bone("Foot.L",  shinL.tail, shinL.tail + Vector((0.0, 0.05*height, -0.02*height)), parent=shinL)
thighR = add_bone("Thigh.R", Vector((cent.x-leg_off, cent.y, hips.head.z)), Vector((cent.x-leg_off, cent.y, minv.z + height*0.05)), parent=hips)
shinR  = add_bone("Shin.R",  thighR.tail, Vector((cent.x-leg_off, cent.y, minv.z + 0.01*height)), parent=thighR)
footR  = add_bone("Foot.R",  shinR.tail, shinR.tail + Vector((0.0, 0.05*height, -0.02*height)), parent=shinR)

bpy.ops.object.mode_set(mode='OBJECT')

# -----------------------
# Body โ†’ Armature ์ž๋™ ๋ฐ”์ธ๋”ฉ
# -----------------------
for o in meshes:
    o.select_set(False)
body.select_set(True)
arm.select_set(True)
bpy.context.view_layer.objects.active = arm
bpy.ops.object.parent_set(type='ARMATURE_AUTO')

# -----------------------
# ์˜๋ณต ์ฒ˜๋ฆฌ
# -----------------------
if args.surface_deform:
    # Body ๊ธฐ์ค€ Surface Deform (๋ณธ๊ฐ€์ค‘์น˜ ์ตœ์†Œํ™”)
    bpy.context.view_layer.objects.active = body
    for o in others:
        if o.type != "MESH":
            continue
        # ๊ธฐ์กด Armature modifier ์ œ๊ฑฐ
        for m in list(o.modifiers):
            if m.type == "ARMATURE":
                try:
                    o.modifiers.remove(m)
                except Exception:
                    pass
        sdef = o.modifiers.new("SurfaceDeform", "SURFACE_DEFORM")
        sdef.target = body
        try:
            bpy.ops.object.surfacedeform_bind(modifier=sdef.name)
        except Exception as e:
            print("[WARN] SurfaceDeform bind ์‹คํŒจ:", e)

elif args.limit_cloth_bones:
    # Armature ์œ ์ง€ํ•˜๋˜ ๋ณธ ์˜ํ–ฅ ์ถ•์†Œ(๊ฐ„์ด ํ›…)
    for o in others:
        if o.type != "MESH":
            continue
        has_arm = any(m.type == "ARMATURE" for m in o.modifiers)
        if not has_arm:
            m = o.modifiers.new("Armature", "ARMATURE")
            m.object = arm
    # ์„ธ๋ถ€ ๊ฐ€์ค‘์น˜ ์กฐ์ •์€ ๋ชจ๋ธ๋งˆ๋‹ค ๋‹ฌ๋ผ ์™„์ „ ์ž๋™ํ™” ๋‚œ์ด๋„ ๋†’์Œ โ†’ ํ›„ํŽธ์ง‘ ์ „์ œ

# -----------------------
# Toon Shader & Outline
# -----------------------
def make_toon_material(name="ToonMat", base_color=(0.8, 0.8, 0.8, 1.0)):
    mat = bpy.data.materials.new(name)
    mat.use_nodes = True
    nt = mat.node_tree
    nodes = nt.nodes; links = nt.links
    # ์ดˆ๊ธฐํ™”
    for n in list(nodes):
        nodes.remove(n)
    out  = nodes.new("ShaderNodeOutputMaterial"); out.location = (400, 0)
    toon = nodes.new("ShaderNodeBsdfToon");       toon.location = (0, 0)
    toon.inputs["Color"].default_value  = base_color
    toon.inputs["Size"].default_value   = 0.5
    toon.inputs["Smooth"].default_value = 0.0
    links.new(toon.outputs["BSDF"], out.inputs["Surface"])
    return mat

def apply_toon(obj):
    if obj.type != "MESH":
        return
    if not obj.data.materials:
        obj.data.materials.append(make_toon_material())
    else:
        for i, _ in enumerate(obj.data.materials):
            obj.data.materials[i] = make_toon_material(f"Toon_{obj.name}_{i}")

def add_outline(obj, thickness=0.003):
    if obj.type != "MESH":
        return
    outline = obj.copy()
    outline.data = obj.data.copy()
    outline.name = obj.name + "_Outline"
    # ์ปฌ๋ ‰์…˜ ๋งํฌ
    for c in outline.users_collection:
        try:
            c.objects.unlink(outline)
        except Exception:
            pass
    bpy.context.scene.collection.objects.link(outline)

    # ๊ฒ€์ • Emission ๋จธํ‹ฐ๋ฆฌ์–ผ
    mat = bpy.data.materials.new("OutlineBlack")
    mat.use_nodes = True
    nodes = mat.node_tree.nodes; links = mat.node_tree.links
    for n in list(nodes): nodes.remove(n)
    out = nodes.new("ShaderNodeOutputMaterial"); out.location = (200, 0)
    em  = nodes.new("ShaderNodeEmission");       em.location = (0, 0)
    em.inputs["Color"].default_value = (0, 0, 0, 1)
    em.inputs["Strength"].default_value = 1.0
    links.new(em.outputs["Emission"], out.inputs["Surface"])

    outline.data.materials.clear()
    outline.data.materials.append(mat)

    # Solidify๋กœ ์™ธ๊ณฝ์„ (๋…ธ๋ฉ€ ๋ฐ˜์ „)
    bpy.context.view_layer.objects.active = outline
    solid = outline.modifiers.new("OutlineSolidify", "SOLIDIFY")
    solid.thickness = -abs(thickness)
    solid.offset = 1.0
    solid.use_flip_normals = True
    solid.material_offset = 0
    outline.show_in_front = True

if args.toon:
    apply_toon(body)
    for o in others:
        apply_toon(o)

if args.outline:
    add_outline(body)
    for o in others:
        add_outline(o, thickness=0.003)

# -----------------------
# ํ‘œ์ •(Shape Keys)
# -----------------------
def ensure_basis_key(obj):
    if obj.data.shape_keys is None:
        obj.shape_key_add(name="Basis")
    return obj.data.shape_keys.key_blocks["Basis"]

def add_placeholder_face_keys(obj):
    ensure_basis_key(obj)
    keys = [
        "EyeBlink_L","EyeBlink_R","BrowDown_L","BrowDown_R",
        "BrowUp","JawOpen","MouthSmile_L","MouthSmile_R",
        "MouthFrown","MouthPucker","MouthLeft","MouthRight"
    ]
    for k in keys:
        try:
            obj.shape_key_add(name=k)
        except Exception:
            pass

def try_faceit_generate():
    # ์• ๋“œ์˜จ ์„ค์น˜ ๊ฐ์ง€(์ž๋™ ์‹คํ–‰์€ ๋ฒ„์ „ ์˜์กด์œผ๋กœ ์ƒ๋žต)
    if "faceit" in bpy.context.preferences.addons:
        print("[INFO] Faceit addon detected. Use GUI to auto-generate blendshapes if needed.")
        return True
    for k in bpy.context.preferences.addons.keys():
        if "face" in k and "it" in k:
            print(f"[INFO] Possibly Faceit-like addon detected: {k}")
            return True
    return False

if args.try_faceit and try_faceit_generate():
    # ์‚ฌ์šฉ์ž GUI์—์„œ Faceit ์›Œํฌํ”Œ๋กœ ์ง„ํ–‰ ๊ถŒ์žฅ
    pass
else:
    add_placeholder_face_keys(body)

# -----------------------
# Export
# -----------------------
# ์„ ํƒ ์ •๋ฆฌ
for o in bpy.context.scene.objects:
    o.select_set(False)
arm.select_set(True)
body.select_set(True)
for o in others:
    if o.type == "MESH":
        o.select_set(True)
bpy.context.view_layer.objects.active = arm

if export_fmt == "fbx":
    bpy.ops.export_scene.fbx(
        filepath=out_path,
        use_selection=True,
        apply_unit_scale=True,
        bake_space_transform=True,
        add_leaf_bones=False,
        mesh_smooth_type='FACE'
    )
else:
    bpy.ops.export_scene.gltf(
        filepath=out_path,
        export_format='GLB',
        use_selection=True,
        export_apply=True
    )

print("[DONE] Exported:", out_path)