Skip to content

Instantly share code, notes, and snippets.

@EricCousineau-TRI
Created May 15, 2019 03:32
Show Gist options
  • Save EricCousineau-TRI/f0e491f0a57dbdf0765cf3848bf004ac to your computer and use it in GitHub Desktop.
Save EricCousineau-TRI/f0e491f0a57dbdf0765cf3848bf004ac to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
With an exiting OBJ and GLTF file, re-generate mesh from OBJ and overwrite
GLTF's, but preserve (some) GLTF properties.
"""
import argparse
from collections import OrderedDict
from os.path import splitext, isfile, dirname, basename
from subprocess import run
import json
GLTF_KEYS_PRESERVE = [
"materials",
"images",
"textures",
"scenes",
]
def convert(obj, gltf):
run(
["obj2gltf", "-s", "-i", basename(obj), "-o", basename(gltf)],
check=True, cwd=dirname(obj))
# # Assimp corrupts the GLTF? :(
# import pyassimp
# scene = pyassimp.load(obj)
# pyassimp.export(scene, gltf, file_type="gltf2")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("obj", type=str)
args = parser.parse_args()
obj = args.obj
assert isfile(obj), obj
gltf = splitext(obj)[0] + ".gltf"
assert isfile(gltf), glf
# First, load original data.
with open(gltf) as f:
old = json.load(f, object_pairs_hook=OrderedDict)
# Next, run conversion.
convert(obj, gltf)
# Now, update perserved keys.
with open(gltf) as f:
new = json.load(f, object_pairs_hook=OrderedDict)
for key in GLTF_KEYS_PRESERVE:
assert key in new, key
new[key] = old[key]
# Write changes.
with open(gltf, "w") as f:
json.dump(new, f, indent=2)
print("Updated: {}".format(gltf))
assert __name__ == "__main__"
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment