master
Drew Owens Current base scaffold model (Base Scaffold Assembly v7: 7 mm sheet, 5-hole panels, gold contacts), alignment features,… 598955f
#!/usr/bin/env python3
"""Give a step2glb GLB of the base scaffold (or one panel) the finishes of its Fusion appearances.

STEP carries only a color per body, so step2glb leaves metallic/roughness unset and glTF then
renders every part as rough metal. This pass finds each material by the parts (node names) that
use it and sets the finish of their Fusion appearance. Parts whose STEP color is wrong get their
own material: 'ABS (White)' parts arrive black unless the export overrode them.
Run it BEFORE any instancing/flattening pass: those drop the node names it keys on.

Usage: glb_finish.py in.glb out.glb
"""
import json, struct, sys

# part-name prefix -> (appearance label, metallic, roughness, sRGB color override or None)
PARTS = [
    ('MpinContact_Large', 'Gold - Polished (contacts)', 1.0, 0.25, None),
    ('1-copper', 'Copper (pads and plating)', 1.0, 0.35, None),
    ('64-copper', 'Copper (pads and plating)', 1.0, 0.35, None),
    ('1-soldermask', 'Soldermask (black)', 0.0, 0.6, None),
    ('64-soldermask', 'Soldermask (black)', 0.0, 0.6, None),
    ('Board', 'FR4', 0.0, 0.7, None),
    ('WB00_BaseScaffoldAlignmentSheet', 'Aluminum - Satin', 1.0, 0.45, None),
    ('BHCS', 'Aluminum - Satin', 1.0, 0.45, None),
    ('hex_socket_button_head', 'Steel (screws)', 1.0, 0.4, None),
    ('FHCS', 'Steel (screws)', 1.0, 0.4, None),
    ('M3 Square Nut', 'Steel - Satin', 1.0, 0.4, None),
    ('Slider_Back', 'Plastic - Matte (Black)', 0.0, 0.7, None),
    ('Slider_Front', 'Plastic - Matte (Black)', 0.0, 0.7, None),
    ('UHMW Tape', 'Plastic - Translucent Matte (White)', 0.0, 0.6, None),
    ('BaseScaffold_Handle', 'Plastic', 0.0, 0.5, None),
    ('ControlPanel_ScaffoldConnectorPinCover', 'ABS (White)', 0.0, 0.5, (235, 235, 230)),
    ('ControlPannelMount_Scaffold', 'ABS (White)', 0.0, 0.5, (235, 235, 230)),
    ('Middle slide support', 'ABS (White)', 0.0, 0.5, (235, 235, 230)),
]


def lin(c):
    c = c / 255.0
    return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4


def rule(name):
    for p, label, metal, rough, col in PARTS:
        if name.startswith(p):
            return label, metal, rough, col
    return None


def main(src, dst):
    b = open(src, 'rb').read()
    jlen = struct.unpack('<I', b[12:16])[0]
    g = json.loads(b[20:20 + jlen])
    rest = b[20 + jlen:]
    mats = g['materials']
    made = {}       # (old material index, label) -> new material index, for recolored parts
    votes = {}      # material index -> {rule: uses}; a shared material takes its majority part's finish
    unmatched = set()
    for n in g['nodes']:
        if 'mesh' not in n:
            continue
        r = rule(n.get('name', ''))
        if not r:
            unmatched.add(n.get('name', '').split(':')[0])
            continue
        label, metal, rough, col = r
        for p in g['meshes'][n['mesh']]['primitives']:
            mi = p.get('material')
            if mi is None:
                continue
            if col is not None:
                key = (mi, label)
                if key not in made:
                    m = json.loads(json.dumps(mats[mi]))
                    m['name'] = label
                    m['pbrMetallicRoughness']['baseColorFactor'] = [lin(c) for c in col] + [1.0]
                    m['pbrMetallicRoughness']['metallicFactor'] = metal
                    m['pbrMetallicRoughness']['roughnessFactor'] = rough
                    mats.append(m)
                    made[key] = len(mats) - 1
                p['material'] = made[key]
            else:
                v = votes.setdefault(mi, {})
                v[r] = v.get(r, 0) + 1
    for mi, v in votes.items():
        label, metal, rough, _ = max(v, key=v.get)
        pbr = mats[mi].setdefault('pbrMetallicRoughness', {})
        pbr['metallicFactor'] = metal
        pbr['roughnessFactor'] = rough
        mats[mi]['name'] = label
    j = json.dumps(g, separators=(',', ':')).encode()
    j += b' ' * ((4 - len(j) % 4) % 4)
    out = struct.pack('<III', 0x46546C67, 2, 12 + 8 + len(j) + len(rest)) + struct.pack('<II', len(j), 0x4E4F534A) + j + rest
    open(dst, 'wb').write(out)
    for i, m in enumerate(mats):
        pbr = m.get('pbrMetallicRoughness', {})
        print(i, m.get('name'), [round(x, 3) for x in pbr.get('baseColorFactor', [])[:3]], pbr.get('metallicFactor'), pbr.get('roughnessFactor'))
    if unmatched:
        print('parts with no rule (finish left unset):', sorted(unmatched))


if __name__ == '__main__':
    main(*sys.argv[1:3])