Skip to content

Instantly share code, notes, and snippets.

@fxthomas
Created May 15, 2011 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fxthomas/973287 to your computer and use it in GitHub Desktop.
Save fxthomas/973287 to your computer and use it in GitHub Desktop.
OBJ to JSON conversion
#!/usr/bin/python
# coding=utf-8
# Base Python File (obj2py.py)
# Created: Sun 15 May 2011 05:21:50 PM CEST
# Version: 1.0
#
# This Python script was developped by François-Xavier Thomas.
# You are free to copy, adapt or modify it.
# If you do so, however, leave my name somewhere in the credits, I'd appreciate it ;)
#
# (ɔ) François-Xavier Thomas <fx.thomas@gmail.com>
import re
import sys
import json
vertices = []
normals = []
triangles = []
with open (sys.argv[1]) as f:
for line in f:
m_vertex = re.match (r"^v (?P<x>[\d.e\-]+) (?P<y>[\d.e\-]+) (?P<z>[\d.e\-]+).*$", line, re.M)
if m_vertex:
vertices.append (float(m_vertex.group ('x')));
vertices.append (float(m_vertex.group ('y')));
vertices.append (float(m_vertex.group ('z')));
continue
m_normal = re.match (r"^vn (?P<x>[\d.e\-]+) (?P<y>[\d.e\-]+) (?P<z>[\d.e\-]+).*$", line, re.M)
if m_normal:
normals.append (float(m_normal.group ('x')));
normals.append (float(m_normal.group ('y')));
normals.append (float(m_normal.group ('z')));
continue
m_face = re.match (r"^f (?P<idv1>\d+)//(?P<idn1>\d+) (?P<idv2>\d+)//(?P<idn2>\d+) (?P<idv3>\d+)//(?P<idn3>\d+).*$", line, re.M)
if m_face:
triangles.append (int (m_face.group('idv1'))-1);
triangles.append (int (m_face.group('idv2'))-1);
triangles.append (int (m_face.group('idv3'))-1);
continue
m_face = re.match (r"^f (?P<idv1>\d+)/(?P<idn1>\d+) (?P<idv2>\d+)/(?P<idn2>\d+) (?P<idv3>\d+)/(?P<idn3>\d+).*$", line, re.M)
if m_face:
triangles.append (int (m_face.group('idv1'))-1);
triangles.append (int (m_face.group('idv2'))-1);
triangles.append (int (m_face.group('idv3'))-1);
continue
m_face = re.match (r"^f (?P<idv1>\d+) (?P<idv2>\d+) (?P<idv3>\d+).*$", line, re.M)
if m_face:
triangles.append (int (m_face.group('idv1'))-1);
triangles.append (int (m_face.group('idv2'))-1);
triangles.append (int (m_face.group('idv3'))-1);
continue
output = { 'vertices' : vertices, 'indexes': triangles, 'normals': normals }
print (json.dumps (output, indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment