File size: 12,656 Bytes
a84fca7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Keep one colourway of a mesh that ships several stacked on top of each other.

    fbx_strip_variant.py --list <fbx>...              what variants a file carries
    fbx_strip_variant.py --keep A01 <fbx>...          drop every other one, in place

`KingCobra` is the one model in this library whose mesh is two co-located copies of
the same surface, one per material — the game asset shipped two colourways of the
same mob, and the export merged both variant meshes into a single object instead of
keeping them separable. Every vertex of one copy sits within 0.0002 of a vertex of
the other, their normals agree to 1.0000, and they share a UV layout, so the two
surfaces coincide exactly: a renderer has to pick one, and which one it picks is
draw order. That is z-fighting, and it is why the same species renders brown from
one batch of clips and dark red from the other.

Keeping one variant removes the coincident surfaces and halves the mesh. The
material to keep is named, not indexed, because the two export batches connect the
same two materials to the mesh in opposite orders — `A01` is material 1 in the
`Cobra-*` files and material 0 in `run`/`walk fast`.

Polygons of the other material are dropped, the surviving vertices are renumbered,
and every array that indexes them follows: normals and vertex colours (per vertex),
UV indices (per polygon vertex), the material array (per polygon) and each skin
cluster's indices and weights. The materials, textures and embedded images that
nothing references any more are removed with them. Nothing touches the skeleton,
the curves or the bind matrices.

Correctness gate: with no edits the serializer must reproduce its input byte for
byte, and the kept vertices must still carry weights summing to 1. Writes through a
temporary file and renames it into place, so a hardlinked source keeps its bytes.
"""
import collections, os, struct, sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from fbx_graft_mesh import (parse, serialize, Node, objects, connections, clean,
                            sval, top, rd_array, wr_array, uid_prop)


def geometry_of(tree):
    for u, (c, n, s, node) in objects(tree).items():
        if c == b"Geometry": return node
    return None


def material_order(tree):
    """Material names in the order they connect to the mesh — the index the
    per-polygon material array refers to."""
    o = objects(tree)
    mesh = {u for u, (c, n, s, _) in o.items() if c == b"Model" and s == b"Mesh"}
    out = []
    for con in connections(tree):
        if con[0] == b"OO" and con[2] in mesh and con[1] in o and o[con[1]][0] == b"Material":
            out.append((clean(o[con[1]][1]), con[1]))
    return out


def layer_field(node, name):
    return next((ch for ch in node.children if ch.name == name), None)


def variants(path):
    t = parse(path)
    geo = geometry_of(t)
    if geo is None: return None
    order = material_order(t)
    V = rd_array(layer_field(geo, b"Vertices").props[0])[0]
    pvi = rd_array(layer_field(geo, b"PolygonVertexIndex").props[0])[0]
    lem = layer_field(geo, b"LayerElementMaterial")
    mats = rd_array(layer_field(lem, b"Materials").props[0])[0] if lem else [0]
    polys, cur = [], []
    for i in pvi:
        cur.append(-i - 1 if i < 0 else i)
        if i < 0: polys.append(cur); cur = []
    grp = collections.defaultdict(set)
    for p, m in zip(polys, mats if len(mats) == len(polys) else [0] * len(polys)):
        grp[m].update(p)
    return {"verts": len(V) // 3, "polys": len(polys), "materials": order,
            "groups": {m: len(v) for m, v in grp.items()}}


def strip(path, keep_sub, dry=False):
    t = parse(path)
    geo = geometry_of(t)
    if geo is None: raise ValueError("no geometry")
    order = material_order(t)
    hit = [i for i, (nm, _) in enumerate(order) if keep_sub in nm]
    if len(hit) != 1:
        raise ValueError("%r matches %d materials: %s" %
                         (keep_sub, len(hit), [n for n, _ in order]))
    keep_i = hit[0]
    keep_uid = order[keep_i][1]
    log = ["保留材质 %s(索引 %d)" % (order[keep_i][0], keep_i)]

    V, venc = rd_array(layer_field(geo, b"Vertices").props[0])
    pvi_node = layer_field(geo, b"PolygonVertexIndex")
    pvi, pienc = rd_array(pvi_node.props[0])
    lem = layer_field(geo, b"LayerElementMaterial")
    mats, menc = rd_array(layer_field(lem, b"Materials").props[0])

    polys, pvpos, cur, cpos = [], [], [], []
    for k, i in enumerate(pvi):
        cur.append(-i - 1 if i < 0 else i); cpos.append(k)
        if i < 0: polys.append(cur); pvpos.append(cpos); cur, cpos = [], []
    if len(mats) != len(polys): raise ValueError("material array is not per polygon")

    keep_poly = [k for k, m in enumerate(mats) if m == keep_i]
    if not keep_poly: raise ValueError("that material covers no polygon")
    kv = sorted({v for k in keep_poly for v in polys[k]})
    vmap = {v: i for i, v in enumerate(kv)}
    keep_pv = [p for k in keep_poly for p in pvpos[k]]
    log.append("多边形 %d → %d,顶点 %d → %d" % (len(polys), len(keep_poly), len(V) // 3, len(kv)))

    new_pvi = []
    for k in keep_poly:
        idx = [vmap[v] for v in polys[k]]
        new_pvi += idx[:-1] + [-idx[-1] - 1]
    layer_field(geo, b"Vertices").props[0] = wr_array(
        "d", [V[3 * v + j] for v in kv for j in range(3)], venc)
    pvi_node.props[0] = wr_array("i", new_pvi, pienc)
    layer_field(lem, b"Materials").props[0] = wr_array("i", [0] * len(keep_poly), menc)

    # every other layer element, by how it is mapped
    for ch in geo.children:
        if not ch.name.startswith(b"LayerElement") or ch.name == b"LayerElementMaterial":
            continue
        mapping = next((clean(cc.props[0][1]) for cc in ch.children
                        if cc.name == b"MappingInformationType"), "")
        for cc in ch.children:
            if not (cc.props and cc.props[0][0] in "dfil"): continue
            if cc.name.endswith(b"Index"):
                if mapping == "ByPolygonVertex":
                    a, e = rd_array(cc.props[0])
                    cc.props[0] = wr_array("i", [a[p] for p in keep_pv], e)
                continue
            a, e = rd_array(cc.props[0])
            if mapping == "ByVertice":
                w = len(a) // (len(V) // 3)
                cc.props[0] = wr_array(cc.props[0][0],
                                       [a[w * v + j] for v in kv for j in range(w)], e)
            elif mapping == "ByPolygonVertex" and len(a) == len(pvi):
                cc.props[0] = wr_array(cc.props[0][0], [a[p] for p in keep_pv], e)

    # skin clusters follow the surviving vertices
    o = objects(t)
    dropped = 0
    for u, (c, n, s, node) in o.items():
        if c != b"Deformer" or s != b"Cluster": continue
        gi = layer_field(node, b"Indexes"); gw = layer_field(node, b"Weights")
        if not gi: continue
        idx, ie = rd_array(gi.props[0]); wt, we = rd_array(gw.props[0])
        pair = [(vmap[i], w) for i, w in zip(idx, wt) if i in vmap]
        dropped += len(idx) - len(pair)
        gi.props[0] = wr_array("i", [p[0] for p in pair], ie)
        gw.props[0] = wr_array("d", [p[1] for p in pair], we)
    log.append("蒙皮索引丢弃 %d 条(属于被剥离的那套)" % dropped)

    # drop the materials nothing uses now, then the textures and images they held
    tobj, tcon = top(t, b"Objects"), top(t, b"Connections")
    before_n = len(objects(t))
    dead = {uid for nm, uid in order if uid != keep_uid}
    tcon.children = [ch for ch in tcon.children
                     if not ({sval(ch.props[1]), sval(ch.props[2])} & dead)]
    tobj.children = [ch for ch in tobj.children
                     if not (len(ch.props) >= 3 and sval(ch.props[0]) in dead)]

    # A texture is alive only if a surviving material still reaches it. These files
    # also connect every texture straight to the mesh node, a legacy edge that says
    # nothing about which material uses it, so reachability is walked from the
    # materials rather than taken from "appears in some connection".
    o = objects(t)
    feeds = collections.defaultdict(list)
    for con in connections(t):
        feeds[con[2]].append(con[1])
    alive, stack = set(), [u for u, (c, n, s, _) in o.items() if c == b"Material"]
    while stack:
        u = stack.pop()
        for src in feeds.get(u, []):
            if src in alive or src not in o: continue
            if o[src][0] in (b"Texture", b"LayeredTexture", b"Video"):
                alive.add(src); stack.append(src)
    dead = {u for u, (c, n, s, _) in o.items()
            if c in (b"Texture", b"LayeredTexture", b"Video") and u not in alive}

    # One image can appear as two `Video` objects with the same filename, only one
    # of which carries pixels — here the shared normal map, whose bytes hang off the
    # slot of the variant being removed while the surviving slot points at an empty
    # shell. Move the pixels across before the shell's twin is deleted, or the kept
    # colourway loses a map it had.
    def content_of(node):
        return next((ch for ch in node.children if ch.name == b"Content"), None)
    def filename_of(node):
        for key in (b"RelativeFilename", b"Filename"):
            ch = next((c for c in node.children if c.name == key), None)
            if ch and ch.props:
                return clean(ch.props[0][1]).replace("\\", "/").rsplit("/", 1)[-1]
        return None
    pixels = {}
    for u, (c, n, sub, node) in o.items():
        if c != b"Video": continue
        ct = content_of(node)
        if ct and ct.props and len(ct.props[0][1]) > 64:
            pixels.setdefault(filename_of(node), ct)
    rescued = 0
    for u, (c, n, sub, node) in o.items():
        if c != b"Video" or u in dead: continue
        ct = content_of(node)
        if ct and ct.props and len(ct.props[0][1]) > 64: continue
        donor = pixels.get(filename_of(node))
        if donor is None: continue
        if ct is not None:
            ct.props = list(donor.props)
        else:
            cp = Node(b"Content"); cp.props = list(donor.props)
            node.children.insert(len(node.children) - 1, cp)
        rescued += 1
    if rescued:
        log.append("补回 %d 张贴图的像素(像素挂在被剥离那套的槽位上)" % rescued)

    if dead:
        tcon.children = [ch for ch in tcon.children
                         if not ({sval(ch.props[1]), sval(ch.props[2])} & dead)]
        tobj.children = [ch for ch in tobj.children
                         if not (len(ch.props) >= 3 and sval(ch.props[0]) in dead)]
    log.append("移除 %d 个对象(材质、及只有它用的贴图与内嵌图像)" %
               (before_n - len(objects(t))))

    defs = top(t, b"Definitions")
    if defs:
        want = collections.Counter(c for c, _, _, _ in objects(t).values())
        for ch in defs.children:
            if ch.name == b"ObjectType" and sval(ch.props[0]) in want:
                for cc in ch.children:
                    if cc.name == b"Count":
                        cc.props[0] = ("I", struct.pack("<i", want[sval(ch.props[0])]))
            elif ch.name == b"Count":
                ch.props[0] = ("I", struct.pack("<i", sum(want.values())))

    if dry: return log, None
    data = serialize(t)
    tmp = path + ".tmp"
    with open(tmp, "wb") as fh: fh.write(data)
    os.replace(tmp, path)
    return log, len(data)


def main(argv):
    if not argv or argv[0] not in ("--list", "--keep", "--selftest"):
        print(__doc__); return 2
    mode = argv[0]
    if mode == "--selftest":
        bad = 0
        for p in argv[1:]:
            same = serialize(parse(p)) == open(p, "rb").read()
            print("%-6s %s" % ("ok" if same else "DIFF", p)); bad += not same
        return 1 if bad else 0
    if mode == "--list":
        for p in argv[1:]:
            v = variants(p)
            print("%-30s 顶点 %-6d 多边形 %-6d" % (os.path.basename(p), v["verts"], v["polys"]))
            for i, (nm, _) in enumerate(v["materials"]):
                print("      索引 %d  %-42s %d 顶点" % (i, nm, v["groups"].get(i, 0)))
        return 0
    keep, targets = argv[1], argv[2:]
    for p in targets:
        if serialize(parse(p)) != open(p, "rb").read():
            print("拒绝执行:%s 无法字节级往返" % p); return 1
        before = os.path.getsize(p)
        log, size = strip(p, keep)
        print(os.path.basename(p))
        for line in log: print("    " + line)
        print("    %d → %d 字节" % (before, size))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))