convert_obj_threejs_slim.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. """Convert Wavefront OBJ / MTL files into Three.js (slim models version, to be used with web worker based ascii / binary loader)
  2. -------------------------
  3. How to use this converter
  4. -------------------------
  5. python convert_obj_threejs_slim.py -i infile.obj -o outfile.js [-m morphfiles*.obj] [-a center|top|bottom] [-s smooth|flat] [-t ascii|binary] [-d invert|normal]
  6. Notes:
  7. - by default:
  8. converted model will be centered (middle of bounding box goes to 0,0,0)
  9. use smooth shading (if there were vertex normals in the original model)
  10. will be in ASCII format
  11. original model is assumed to use non-inverted transparency / dissolve (0.0 fully transparent, 1.0 fully opaque)
  12. - binary conversion will create two files:
  13. outfile.js (materials)
  14. outfile.bin (binary buffers)
  15. --------------------------------------------------
  16. How to use generated JS file in your HTML document
  17. --------------------------------------------------
  18. <script type="text/javascript" src="Three.js"></script>
  19. ...
  20. <script type="text/javascript">
  21. ...
  22. var loader = new THREE.Loader();
  23. // load ascii model
  24. loader.loadAscii( "Model_slim.js", function( geometry ) { createScene( geometry) }, path_to_textures );
  25. // load binary model
  26. loader.loadBinary( "Model_bin.js", function( geometry ) { createScene( geometry) }, path_to_textures );
  27. function createScene( geometry ) {
  28. var normalizeUVsFlag = 1; // set to 1 if canvas render has missing materials
  29. var mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial(), normalizeUVsFlag );
  30. }
  31. ...
  32. </script>
  33. -------------------------------------
  34. Parsers based on formats descriptions
  35. -------------------------------------
  36. http://en.wikipedia.org/wiki/Obj
  37. http://en.wikipedia.org/wiki/Material_Template_Library
  38. -------------------
  39. Current limitations
  40. -------------------
  41. - for the moment, only diffuse color and texture are used
  42. (will need to extend shaders / renderers / materials in Three)
  43. - models can have more than 65,536 vertices,
  44. but in most cases it will not work well with browsers,
  45. which currently seem to have troubles with handling
  46. large JS files
  47. - texture coordinates can be wrong in canvas renderer
  48. (there is crude normalization, but it doesn't
  49. work for all cases)
  50. - smoothing can be turned on/off only for the whole mesh
  51. ----------------------------------------------
  52. How to get proper OBJ + MTL files with Blender
  53. ----------------------------------------------
  54. 0. Remove default cube (press DEL and ENTER)
  55. 1. Import / create model
  56. 2. Select all meshes (Select -> Select All by Type -> Mesh)
  57. 3. Export to OBJ (File -> Export -> Wavefront .obj) [*]
  58. - enable following options in exporter
  59. Material Groups
  60. Rotate X90
  61. Apply Modifiers
  62. High Quality Normals
  63. Copy Images
  64. Selection Only
  65. Objects as OBJ Objects
  66. UVs
  67. Normals
  68. Materials
  69. Edges
  70. - select empty folder
  71. - give your exported file name with "obj" extension
  72. - click on "Export OBJ" button
  73. 4. Your model is now all files in this folder (OBJ, MTL, number of images)
  74. - this converter assumes all files staying in the same folder,
  75. (OBJ / MTL files use relative paths)
  76. - for WebGL, textures must be power of 2 sized
  77. [*] If OBJ export fails (Blender 2.54 beta), patch your Blender installation
  78. following instructions here:
  79. http://www.blendernation.com/2010/09/12/blender-2-54-beta-released/
  80. ------
  81. Author
  82. ------
  83. AlteredQualia http://alteredqualia.com
  84. """
  85. import fileinput
  86. import operator
  87. import random
  88. import os.path
  89. import getopt
  90. import sys
  91. import struct
  92. import math
  93. import glob
  94. # #####################################################
  95. # Configuration
  96. # #####################################################
  97. ALIGN = "center" # center bottom top none
  98. SHADING = "smooth" # smooth flat
  99. TYPE = "ascii" # ascii binary
  100. TRANSPARENCY = "normal" # normal invert
  101. # default colors for debugging (each material gets one distinct color):
  102. # white, red, green, blue, yellow, cyan, magenta
  103. COLORS = [0xeeeeee, 0xee0000, 0x00ee00, 0x0000ee, 0xeeee00, 0x00eeee, 0xee00ee]
  104. # #####################################################
  105. # Templates
  106. # #####################################################
  107. TEMPLATE_FILE_ASCII = u"""\
  108. // Converted from: %(fname)s
  109. // vertices: %(nvertex)d
  110. // faces: %(nface)d
  111. // materials: %(nmaterial)d
  112. //
  113. // Generated with OBJ -> Three.js converter
  114. // http://github.com/alteredq/three.js/blob/master/utils/exporters/convert_obj_threejs_slim.py
  115. var model = {
  116. 'materials': [%(materials)s],
  117. 'normals': [%(normals)s],
  118. 'vertices': [%(vertices)s],
  119. 'morphTargets': [%(morphTargets)s],
  120. 'uvs': [%(uvs)s],
  121. 'triangles': [%(triangles)s],
  122. 'trianglesUvs': [%(trianglesUvs)s],
  123. 'trianglesNormals': [%(trianglesNormals)s],
  124. 'trianglesNormalsUvs': [%(trianglesNormalsUvs)s],
  125. 'quads': [%(quads)s],
  126. 'quadsUvs': [%(quadsUvs)s],
  127. 'quadsNormals': [%(quadsNormals)s],
  128. 'quadsNormalsUvs': [%(quadsNormalsUvs)s],
  129. 'end': (new Date).getTime()
  130. }
  131. postMessage( model );
  132. """
  133. TEMPLATE_FILE_BIN = u"""\
  134. // Converted from: %(fname)s
  135. // vertices: %(nvertex)d
  136. // faces: %(nface)d
  137. // materials: %(nmaterial)d
  138. //
  139. // Generated with OBJ -> Three.js converter
  140. // http://github.com/alteredq/three.js/blob/master/utils/exporters/convert_obj_threejs_slim.py
  141. var model = {
  142. 'materials': [%(materials)s],
  143. 'buffers': '%(buffers)s',
  144. 'end': (new Date).getTime()
  145. }
  146. postMessage( model );
  147. """
  148. TEMPLATE_VERTEX = "%f,%f,%f"
  149. TEMPLATE_UV_TRI = "%f,%f,%f,%f,%f,%f"
  150. TEMPLATE_UV_QUAD = "%f,%f,%f,%f,%f,%f,%f,%f"
  151. TEMPLATE_TRI = "%d,%d,%d,%d"
  152. TEMPLATE_QUAD = "%d,%d,%d,%d,%d"
  153. TEMPLATE_TRI_UV = "%d,%d,%d,%d,%d,%d,%d"
  154. TEMPLATE_QUAD_UV = "%d,%d,%d,%d,%d,%d,%d,%d,%d"
  155. TEMPLATE_TRI_N = "%d,%d,%d,%d,%d,%d,%d"
  156. TEMPLATE_QUAD_N = "%d,%d,%d,%d,%d,%d,%d,%d,%d"
  157. TEMPLATE_TRI_N_UV = "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d"
  158. TEMPLATE_QUAD_N_UV = "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d"
  159. TEMPLATE_N = "%f,%f,%f"
  160. TEMPLATE_UV = "%f,%f"
  161. TEMPLATE_MORPH = "\t{ 'name': '%s', 'vertices': [%s] }"
  162. # #####################################################
  163. # Utils
  164. # #####################################################
  165. def file_exists(filename):
  166. """Return true if file exists and is accessible for reading.
  167. Should be safer than just testing for existence due to links and
  168. permissions magic on Unix filesystems.
  169. @rtype: boolean
  170. """
  171. try:
  172. f = open(filename, 'r')
  173. f.close()
  174. return True
  175. except IOError:
  176. return False
  177. def get_name(fname):
  178. """Create model name based of filename ("path/fname.js" -> "fname").
  179. """
  180. return os.path.splitext(os.path.basename(fname))[0]
  181. def bbox(vertices):
  182. """Compute bounding box of vertex array.
  183. """
  184. if len(vertices)>0:
  185. minx = maxx = vertices[0][0]
  186. miny = maxy = vertices[0][1]
  187. minz = maxz = vertices[0][2]
  188. for v in vertices[1:]:
  189. if v[0]<minx:
  190. minx = v[0]
  191. elif v[0]>maxx:
  192. maxx = v[0]
  193. if v[1]<miny:
  194. miny = v[1]
  195. elif v[1]>maxy:
  196. maxy = v[1]
  197. if v[2]<minz:
  198. minz = v[2]
  199. elif v[2]>maxz:
  200. maxz = v[2]
  201. return { 'x':[minx,maxx], 'y':[miny,maxy], 'z':[minz,maxz] }
  202. else:
  203. return { 'x':[0,0], 'y':[0,0], 'z':[0,0] }
  204. def translate(vertices, t):
  205. """Translate array of vertices by vector t.
  206. """
  207. for i in xrange(len(vertices)):
  208. vertices[i][0] += t[0]
  209. vertices[i][1] += t[1]
  210. vertices[i][2] += t[2]
  211. def center(vertices):
  212. """Center model (middle of bounding box).
  213. """
  214. bb = bbox(vertices)
  215. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  216. cy = bb['y'][0] + (bb['y'][1] - bb['y'][0])/2.0
  217. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  218. translate(vertices, [-cx,-cy,-cz])
  219. def top(vertices):
  220. """Align top of the model with the floor (Y-axis) and center it around X and Z.
  221. """
  222. bb = bbox(vertices)
  223. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  224. cy = bb['y'][1]
  225. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  226. translate(vertices, [-cx,-cy,-cz])
  227. def bottom(vertices):
  228. """Align bottom of the model with the floor (Y-axis) and center it around X and Z.
  229. """
  230. bb = bbox(vertices)
  231. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  232. cy = bb['y'][0]
  233. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  234. translate(vertices, [-cx,-cy,-cz])
  235. def normalize(v):
  236. """Normalize 3d vector"""
  237. l = math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
  238. if l:
  239. v[0] /= l
  240. v[1] /= l
  241. v[2] /= l
  242. # #####################################################
  243. # MTL parser
  244. # #####################################################
  245. def texture_relative_path(fullpath):
  246. texture_file = os.path.basename(fullpath)
  247. return texture_file
  248. def parse_mtl(fname):
  249. """Parse MTL file.
  250. """
  251. materials = {}
  252. for line in fileinput.input(fname):
  253. chunks = line.split()
  254. if len(chunks) > 0:
  255. # Material start
  256. # newmtl identifier
  257. if chunks[0] == "newmtl" and len(chunks) == 2:
  258. identifier = chunks[1]
  259. if not identifier in materials:
  260. materials[identifier] = {}
  261. # Diffuse color
  262. # Kd 1.000 1.000 1.000
  263. if chunks[0] == "Kd" and len(chunks) == 4:
  264. materials[identifier]["colorDiffuse"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  265. # Ambient color
  266. # Ka 1.000 1.000 1.000
  267. if chunks[0] == "Ka" and len(chunks) == 4:
  268. materials[identifier]["colorAmbient"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  269. # Specular color
  270. # Ks 1.000 1.000 1.000
  271. if chunks[0] == "Ks" and len(chunks) == 4:
  272. materials[identifier]["colorSpecular"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  273. # Specular coefficient
  274. # Ns 154.000
  275. if chunks[0] == "Ns" and len(chunks) == 2:
  276. materials[identifier]["specularCoef"] = float(chunks[1])
  277. # Transparency
  278. # Tr 0.9 or d 0.9
  279. if (chunks[0] == "Tr" or chunks[0] == "d") and len(chunks) == 2:
  280. if TRANSPARENCY == "invert":
  281. materials[identifier]["transparency"] = 1.0 - float(chunks[1])
  282. else:
  283. materials[identifier]["transparency"] = float(chunks[1])
  284. # Optical density
  285. # Ni 1.0
  286. if chunks[0] == "Ni" and len(chunks) == 2:
  287. materials[identifier]["opticalDensity"] = float(chunks[1])
  288. # Diffuse texture
  289. # map_Kd texture_diffuse.jpg
  290. if chunks[0] == "map_Kd" and len(chunks) == 2:
  291. materials[identifier]["mapDiffuse"] = texture_relative_path(chunks[1])
  292. # Ambient texture
  293. # map_Ka texture_ambient.jpg
  294. if chunks[0] == "map_Ka" and len(chunks) == 2:
  295. materials[identifier]["mapAmbient"] = texture_relative_path(chunks[1])
  296. # Specular texture
  297. # map_Ks texture_specular.jpg
  298. if chunks[0] == "map_Ks" and len(chunks) == 2:
  299. materials[identifier]["mapSpecular"] = texture_relative_path(chunks[1])
  300. # Alpha texture
  301. # map_d texture_alpha.png
  302. if chunks[0] == "map_d" and len(chunks) == 2:
  303. materials[identifier]["mapAlpha"] = texture_relative_path(chunks[1])
  304. # Bump texture
  305. # map_bump texture_bump.jpg or bump texture_bump.jpg
  306. if (chunks[0] == "map_bump" or chunks[0] == "bump") and len(chunks) == 2:
  307. materials[identifier]["mapBump"] = texture_relative_path(chunks[1])
  308. # Illumination
  309. # illum 2
  310. #
  311. # 0. Color on and Ambient off
  312. # 1. Color on and Ambient on
  313. # 2. Highlight on
  314. # 3. Reflection on and Ray trace on
  315. # 4. Transparency: Glass on, Reflection: Ray trace on
  316. # 5. Reflection: Fresnel on and Ray trace on
  317. # 6. Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  318. # 7. Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  319. # 8. Reflection on and Ray trace off
  320. # 9. Transparency: Glass on, Reflection: Ray trace off
  321. # 10. Casts shadows onto invisible surfaces
  322. if chunks[0] == "illum" and len(chunks) == 2:
  323. materials[identifier]["illumination"] = int(chunks[1])
  324. return materials
  325. # #####################################################
  326. # OBJ parser
  327. # #####################################################
  328. def parse_vertex(text):
  329. """Parse text chunk specifying single vertex.
  330. Possible formats:
  331. vertex index
  332. vertex index / texture index
  333. vertex index / texture index / normal index
  334. vertex index / / normal index
  335. """
  336. v = 0
  337. t = 0
  338. n = 0
  339. chunks = text.split("/")
  340. v = int(chunks[0])
  341. if len(chunks) > 1:
  342. if chunks[1]:
  343. t = int(chunks[1])
  344. if len(chunks) > 2:
  345. if chunks[2]:
  346. n = int(chunks[2])
  347. return { 'v':v, 't':t, 'n':n }
  348. def parse_obj(fname):
  349. """Parse OBJ file.
  350. """
  351. vertices = []
  352. normals = []
  353. uvs = []
  354. faces = []
  355. materials = {}
  356. mcounter = 0
  357. mcurrent = 0
  358. mtllib = ""
  359. # current face state
  360. group = 0
  361. object = 0
  362. smooth = 0
  363. for line in fileinput.input(fname):
  364. chunks = line.split()
  365. if len(chunks) > 0:
  366. # Vertices as (x,y,z) coordinates
  367. # v 0.123 0.234 0.345
  368. if chunks[0] == "v" and len(chunks) == 4:
  369. x = float(chunks[1])
  370. y = float(chunks[2])
  371. z = float(chunks[3])
  372. vertices.append([x,y,z])
  373. # Normals in (x,y,z) form; normals might not be unit
  374. # vn 0.707 0.000 0.707
  375. if chunks[0] == "vn" and len(chunks) == 4:
  376. x = float(chunks[1])
  377. y = float(chunks[2])
  378. z = float(chunks[3])
  379. normals.append([x,y,z])
  380. # Texture coordinates in (u,v[,w]) coordinates, w is optional
  381. # vt 0.500 -1.352 [0.234]
  382. if chunks[0] == "vt" and len(chunks) >= 3:
  383. u = float(chunks[1])
  384. v = float(chunks[2])
  385. w = 0
  386. if len(chunks)>3:
  387. w = float(chunks[3])
  388. uvs.append([u,v,w])
  389. # Face
  390. if chunks[0] == "f" and len(chunks) >= 4:
  391. vertex_index = []
  392. uv_index = []
  393. normal_index = []
  394. for v in chunks[1:]:
  395. vertex = parse_vertex(v)
  396. if vertex['v']:
  397. vertex_index.append(vertex['v'])
  398. if vertex['t']:
  399. uv_index.append(vertex['t'])
  400. if vertex['n']:
  401. normal_index.append(vertex['n'])
  402. faces.append({
  403. 'vertex':vertex_index,
  404. 'uv':uv_index,
  405. 'normal':normal_index,
  406. 'material':mcurrent,
  407. 'group':group,
  408. 'object':object,
  409. 'smooth':smooth,
  410. })
  411. # Group
  412. if chunks[0] == "g" and len(chunks) == 2:
  413. group = chunks[1]
  414. # Object
  415. if chunks[0] == "o" and len(chunks) == 2:
  416. object = chunks[1]
  417. # Materials definition
  418. if chunks[0] == "mtllib" and len(chunks) == 2:
  419. mtllib = chunks[1]
  420. # Material
  421. if chunks[0] == "usemtl" and len(chunks) == 2:
  422. material = chunks[1]
  423. if not material in materials:
  424. mcurrent = mcounter
  425. materials[material] = mcounter
  426. mcounter += 1
  427. else:
  428. mcurrent = materials[material]
  429. # Smooth shading
  430. if chunks[0] == "s" and len(chunks) == 2:
  431. smooth = chunks[1]
  432. return faces, vertices, uvs, normals, materials, mtllib
  433. # #####################################################
  434. # Generator
  435. # #####################################################
  436. def generate_vertex(v):
  437. return TEMPLATE_VERTEX % (v[0], v[1], v[2])
  438. def generate_triangle(f):
  439. v = f['vertex']
  440. return TEMPLATE_TRI % (v[0]-1, v[1]-1, v[2]-1,
  441. f['material'])
  442. def generate_triangle_uv(f):
  443. v = f['vertex']
  444. uv = f['uv']
  445. return TEMPLATE_TRI_UV % (v[0]-1, v[1]-1, v[2]-1,
  446. f['material'],
  447. uv[0]-1, uv[1]-1, uv[2]-1)
  448. def generate_triangle_n(f):
  449. v = f['vertex']
  450. n = f['normal']
  451. return TEMPLATE_TRI_N % (v[0]-1, v[1]-1, v[2]-1,
  452. f['material'],
  453. n[0]-1, n[1]-1, n[2]-1)
  454. def generate_triangle_n_uv(f):
  455. v = f['vertex']
  456. n = f['normal']
  457. uv = f['uv']
  458. return TEMPLATE_TRI_N_UV % (v[0]-1, v[1]-1, v[2]-1,
  459. f['material'],
  460. n[0]-1, n[1]-1, n[2]-1,
  461. uv[0]-1, uv[1]-1, uv[2]-1)
  462. def generate_quad(f):
  463. vi = f['vertex']
  464. return TEMPLATE_QUAD % (vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  465. f['material'])
  466. def generate_quad_uv(f):
  467. v = f['vertex']
  468. uv = f['uv']
  469. return TEMPLATE_QUAD_UV % (v[0]-1, v[1]-1, v[2]-1, v[3]-1,
  470. f['material'],
  471. uv[0]-1, uv[1]-1, uv[2]-1, uv[3]-1)
  472. def generate_quad_n(f):
  473. v = f['vertex']
  474. n = f['normal']
  475. return TEMPLATE_QUAD_N % (v[0]-1, v[1]-1, v[2]-1, v[3]-1,
  476. f['material'],
  477. n[0]-1, n[1]-1, n[2]-1, n[3]-1)
  478. def generate_quad_n_uv(f):
  479. v = f['vertex']
  480. n = f['normal']
  481. uv = f['uv']
  482. return TEMPLATE_QUAD_N_UV % (v[0]-1, v[1]-1, v[2]-1, v[3]-1,
  483. f['material'],
  484. n[0]-1, n[1]-1, n[2]-1, n[3]-1,
  485. uv[0]-1, uv[1]-1, uv[2]-1, uv[3]-1)
  486. def generate_normal(n):
  487. return TEMPLATE_N % (n[0], n[1], n[2])
  488. def generate_uv(uv):
  489. return TEMPLATE_UV % (uv[0], 1.0 - uv[1])
  490. # #####################################################
  491. # Morphs
  492. # #####################################################
  493. def generate_morph(name, vertices):
  494. vertex_string = ",".join(generate_vertex(v) for v in vertices)
  495. return TEMPLATE_MORPH % (name, vertex_string)
  496. # #####################################################
  497. # Materials
  498. # #####################################################
  499. def generate_color(i):
  500. """Generate hex color corresponding to integer.
  501. Colors should have well defined ordering.
  502. First N colors are hardcoded, then colors are random
  503. (must seed random number generator with deterministic value
  504. before getting colors).
  505. """
  506. if i < len(COLORS):
  507. return "0x%06x" % COLORS[i]
  508. else:
  509. return "0x%06x" % int(0xffffff * random.random())
  510. def value2string(v):
  511. if type(v)==str and v[0:2] != "0x":
  512. return '"%s"' % v
  513. return str(v)
  514. def generate_materials(mtl, materials):
  515. """Generate JS array of materials objects
  516. JS material objects are basically prettified one-to-one
  517. mappings of MTL properties in JSON format.
  518. """
  519. mtl_array = []
  520. for m in mtl:
  521. if m in materials:
  522. index = materials[m]
  523. # add debug information
  524. # materials should be sorted according to how
  525. # they appeared in OBJ file (for the first time)
  526. # this index is identifier used in face definitions
  527. mtl[m]['DbgName'] = m
  528. mtl[m]['DbgIndex'] = index
  529. mtl[m]['DbgColor'] = generate_color(index)
  530. mtl_raw = ",\n".join(['\t"%s" : %s' % (n, value2string(v)) for n,v in sorted(mtl[m].items())])
  531. mtl_string = "\t{\n%s\n\t}" % mtl_raw
  532. mtl_array.append([index, mtl_string])
  533. return ",\n\n".join([m for i,m in sorted(mtl_array)])
  534. def generate_mtl(materials):
  535. """Generate dummy materials (if there is no MTL file).
  536. """
  537. mtl = {}
  538. for m in materials:
  539. index = materials[m]
  540. mtl[m] = {
  541. 'DbgName': m,
  542. 'DbgIndex': index,
  543. 'DbgColor': generate_color(index)
  544. }
  545. return mtl
  546. def generate_materials_string(materials, mtllib):
  547. """Generate final materials string.
  548. """
  549. random.seed(42) # to get well defined color order for materials
  550. # default materials with debug colors for when
  551. # there is no specified MTL / MTL loading failed,
  552. # or if there were no materials / null materials
  553. if not materials:
  554. materials = { 'default':0 }
  555. mtl = generate_mtl(materials)
  556. if mtllib:
  557. # create full pathname for MTL (included from OBJ)
  558. path = os.path.dirname(infile)
  559. fname = os.path.join(path, mtllib)
  560. if file_exists(fname):
  561. # override default materials with real ones from MTL
  562. # (where they exist, otherwise keep defaults)
  563. mtl.update(parse_mtl(fname))
  564. else:
  565. print "Couldn't find [%s]" % fname
  566. return generate_materials(mtl, materials)
  567. # #####################################################
  568. # Faces
  569. # #####################################################
  570. def is_triangle_flat(f):
  571. return len(f['vertex'])==3 and not (f["normal"] and SHADING == "smooth") and not f['uv']
  572. def is_triangle_flat_uv(f):
  573. return len(f['vertex'])==3 and not (f["normal"] and SHADING == "smooth") and len(f['uv'])==3
  574. def is_triangle_smooth(f):
  575. return len(f['vertex'])==3 and f["normal"] and SHADING == "smooth" and not f['uv']
  576. def is_triangle_smooth_uv(f):
  577. return len(f['vertex'])==3 and f["normal"] and SHADING == "smooth" and len(f['uv'])==3
  578. def is_quad_flat(f):
  579. return len(f['vertex'])==4 and not (f["normal"] and SHADING == "smooth") and not f['uv']
  580. def is_quad_flat_uv(f):
  581. return len(f['vertex'])==4 and not (f["normal"] and SHADING == "smooth") and len(f['uv'])==4
  582. def is_quad_smooth(f):
  583. return len(f['vertex'])==4 and f["normal"] and SHADING == "smooth" and not f['uv']
  584. def is_quad_smooth_uv(f):
  585. return len(f['vertex'])==4 and f["normal"] and SHADING == "smooth" and len(f['uv'])==4
  586. def sort_faces(faces):
  587. data = {
  588. 'triangles_flat': [],
  589. 'triangles_flat_uv': [],
  590. 'triangles_smooth': [],
  591. 'triangles_smooth_uv': [],
  592. 'quads_flat': [],
  593. 'quads_flat_uv': [],
  594. 'quads_smooth': [],
  595. 'quads_smooth_uv': []
  596. }
  597. for f in faces:
  598. if is_triangle_flat(f):
  599. data['triangles_flat'].append(f)
  600. elif is_triangle_flat_uv(f):
  601. data['triangles_flat_uv'].append(f)
  602. elif is_triangle_smooth(f):
  603. data['triangles_smooth'].append(f)
  604. elif is_triangle_smooth_uv(f):
  605. data['triangles_smooth_uv'].append(f)
  606. elif is_quad_flat(f):
  607. data['quads_flat'].append(f)
  608. elif is_quad_flat_uv(f):
  609. data['quads_flat_uv'].append(f)
  610. elif is_quad_smooth(f):
  611. data['quads_smooth'].append(f)
  612. elif is_quad_smooth_uv(f):
  613. data['quads_smooth_uv'].append(f)
  614. return data
  615. # #####################################################
  616. # API - ASCII converter
  617. # #####################################################
  618. def convert_ascii(infile, morphfiles, outfile):
  619. """Convert infile.obj to outfile.js
  620. Here is where everything happens. If you need to automate conversions,
  621. just import this file as Python module and call this method.
  622. """
  623. if not file_exists(infile):
  624. print "Couldn't find [%s]" % infile
  625. return
  626. faces, vertices, uvs, normals, materials, mtllib = parse_obj(infile)
  627. if ALIGN == "center":
  628. center(vertices)
  629. elif ALIGN == "bottom":
  630. bottom(vertices)
  631. elif ALIGN == "top":
  632. top(vertices)
  633. normals_string = ""
  634. if SHADING == "smooth":
  635. normals_string = ",".join(generate_normal(n) for n in normals)
  636. sfaces = sort_faces(faces)
  637. skipOriginalMorph = False
  638. norminfile = os.path.normpath(infile)
  639. morphData = []
  640. for mfilepattern in morphfiles.split():
  641. for path in glob.glob(mfilepattern):
  642. normpath = os.path.normpath(path)
  643. if normpath != norminfile or not skipOriginalMorph:
  644. name = os.path.basename(normpath)
  645. morphFaces, morphVertices, morphUvs, morphNormals, morphMaterials, morphMtllib = parse_obj(normpath)
  646. if ALIGN == "center":
  647. center(morphVertices)
  648. elif ALIGN == "bottom":
  649. bottom(morphVertices)
  650. elif ALIGN == "top":
  651. top(morphVertices)
  652. morphData.append((get_name(name), morphVertices ))
  653. print name, len(morphVertices)
  654. morphTargets = ""
  655. if len(morphData):
  656. morphTargets = "\n%s\n\t" % ",\n".join(generate_morph(name, vertices) for name, vertices in morphData)
  657. text = TEMPLATE_FILE_ASCII % {
  658. "name" : get_name(outfile),
  659. "fname" : infile,
  660. "nvertex" : len(vertices),
  661. "nface" : len(faces),
  662. "nmaterial" : len(materials),
  663. "materials" : generate_materials_string(materials, mtllib),
  664. "normals" : normals_string,
  665. "uvs" : ",".join(generate_uv(uv) for uv in uvs),
  666. "vertices" : ",".join(generate_vertex(v) for v in vertices),
  667. "morphTargets" : morphTargets,
  668. "triangles" : ",".join(generate_triangle(f) for f in sfaces['triangles_flat']),
  669. "trianglesUvs" : ",".join(generate_triangle_uv(f) for f in sfaces['triangles_flat_uv']),
  670. "trianglesNormals" : ",".join(generate_triangle_n(f) for f in sfaces['triangles_smooth']),
  671. "trianglesNormalsUvs": ",".join(generate_triangle_n_uv(f) for f in sfaces['triangles_smooth_uv']),
  672. "quads" : ",".join(generate_quad(f) for f in sfaces['quads_flat']),
  673. "quadsUvs" : ",".join(generate_quad_uv(f) for f in sfaces['quads_flat_uv']),
  674. "quadsNormals" : ",".join(generate_quad_n(f) for f in sfaces['quads_smooth']),
  675. "quadsNormalsUvs" : ",".join(generate_quad_n_uv(f) for f in sfaces['quads_smooth_uv'])
  676. }
  677. out = open(outfile, "w")
  678. out.write(text)
  679. out.close()
  680. print "%d vertices, %d faces, %d materials" % (len(vertices), len(faces), len(materials))
  681. # #############################################################################
  682. # API - Binary converter
  683. # #############################################################################
  684. def convert_binary(infile, outfile):
  685. """Convert infile.obj to outfile.js + outfile.bin
  686. """
  687. if not file_exists(infile):
  688. print "Couldn't find [%s]" % infile
  689. return
  690. binfile = get_name(outfile) + ".bin"
  691. faces, vertices, uvs, normals, materials, mtllib = parse_obj(infile)
  692. if ALIGN == "center":
  693. center(vertices)
  694. elif ALIGN == "bottom":
  695. bottom(vertices)
  696. elif ALIGN == "top":
  697. top(vertices)
  698. sfaces = sort_faces(faces)
  699. # ###################
  700. # generate JS file
  701. # ###################
  702. text = TEMPLATE_FILE_BIN % {
  703. "name" : get_name(outfile),
  704. "materials" : generate_materials_string(materials, mtllib),
  705. "buffers" : binfile,
  706. "fname" : infile,
  707. "nvertex" : len(vertices),
  708. "nface" : len(faces),
  709. "nmaterial" : len(materials)
  710. }
  711. out = open(outfile, "w")
  712. out.write(text)
  713. out.close()
  714. # ###################
  715. # generate BIN file
  716. # ###################
  717. if SHADING == "smooth":
  718. nnormals = len(normals)
  719. else:
  720. nnormals = 0
  721. buffer = []
  722. # header
  723. # ------
  724. header_bytes = struct.calcsize('<8s')
  725. header_bytes += struct.calcsize('<BBBBBBBB')
  726. header_bytes += struct.calcsize('<IIIIIIIIIII')
  727. # signature
  728. signature = struct.pack('<8s', 'Three.js')
  729. # metadata (all data is little-endian)
  730. vertex_coordinate_bytes = 4
  731. normal_coordinate_bytes = 1
  732. uv_coordinate_bytes = 4
  733. vertex_index_bytes = 4
  734. normal_index_bytes = 4
  735. uv_index_bytes = 4
  736. material_index_bytes = 2
  737. # header_bytes unsigned char 1
  738. # vertex_coordinate_bytes unsigned char 1
  739. # normal_coordinate_bytes unsigned char 1
  740. # uv_coordinate_bytes unsigned char 1
  741. # vertex_index_bytes unsigned char 1
  742. # normal_index_bytes unsigned char 1
  743. # uv_index_bytes unsigned char 1
  744. # material_index_bytes unsigned char 1
  745. bdata = struct.pack('<BBBBBBBB', header_bytes,
  746. vertex_coordinate_bytes,
  747. normal_coordinate_bytes,
  748. uv_coordinate_bytes,
  749. vertex_index_bytes,
  750. normal_index_bytes,
  751. uv_index_bytes,
  752. material_index_bytes)
  753. # nvertices unsigned int 4
  754. # nnormals unsigned int 4
  755. # nuvs unsigned int 4
  756. # ntri_flat unsigned int 4
  757. # ntri_smooth unsigned int 4
  758. # ntri_flat_uv unsigned int 4
  759. # ntri_smooth_uv unsigned int 4
  760. # nquad_flat unsigned int 4
  761. # nquad_smooth unsigned int 4
  762. # nquad_flat_uv unsigned int 4
  763. # nquad_smooth_uv unsigned int 4
  764. ndata = struct.pack('<IIIIIIIIIII', len(vertices),
  765. nnormals,
  766. len(uvs),
  767. len(sfaces['triangles_flat']),
  768. len(sfaces['triangles_smooth']),
  769. len(sfaces['triangles_flat_uv']),
  770. len(sfaces['triangles_smooth_uv']),
  771. len(sfaces['quads_flat']),
  772. len(sfaces['quads_smooth']),
  773. len(sfaces['quads_flat_uv']),
  774. len(sfaces['quads_smooth_uv']))
  775. buffer.append(signature)
  776. buffer.append(bdata)
  777. buffer.append(ndata)
  778. # 1. vertices
  779. # ------------
  780. # x float 4
  781. # y float 4
  782. # z float 4
  783. for v in vertices:
  784. data = struct.pack('<fff', v[0], v[1], v[2])
  785. buffer.append(data)
  786. # 2. normals
  787. # ---------------
  788. # x signed char 1
  789. # y signed char 1
  790. # z signed char 1
  791. if SHADING == "smooth":
  792. for n in normals:
  793. normalize(n)
  794. data = struct.pack('<bbb', math.floor(n[0]*127+0.5),
  795. math.floor(n[1]*127+0.5),
  796. math.floor(n[2]*127+0.5))
  797. buffer.append(data)
  798. # 3. uvs
  799. # -----------
  800. # u float 4
  801. # v float 4
  802. for uv in uvs:
  803. data = struct.pack('<ff', uv[0], 1.0-uv[1])
  804. buffer.append(data)
  805. # 4. flat triangles
  806. # ------------------
  807. # a unsigned int 4
  808. # b unsigned int 4
  809. # c unsigned int 4
  810. # m unsigned short 2
  811. for f in sfaces['triangles_flat']:
  812. vi = f['vertex']
  813. data = struct.pack('<IIIH',
  814. vi[0]-1, vi[1]-1, vi[2]-1,
  815. f['material'])
  816. buffer.append(data)
  817. # 5. smooth triangles
  818. # -------------------
  819. # a unsigned int 4
  820. # b unsigned int 4
  821. # c unsigned int 4
  822. # m unsigned short 2
  823. # na unsigned int 4
  824. # nb unsigned int 4
  825. # nc unsigned int 4
  826. for f in sfaces['triangles_smooth']:
  827. vi = f['vertex']
  828. ni = f['normal']
  829. data = struct.pack('<IIIHIII',
  830. vi[0]-1, vi[1]-1, vi[2]-1,
  831. f['material'],
  832. ni[0]-1, ni[1]-1, ni[2]-1)
  833. buffer.append(data)
  834. # 6. flat triangles uv
  835. # --------------------
  836. # a unsigned int 4
  837. # b unsigned int 4
  838. # c unsigned int 4
  839. # m unsigned short 2
  840. # ua unsigned int 4
  841. # ub unsigned int 4
  842. # uc unsigned int 4
  843. for f in sfaces['triangles_flat_uv']:
  844. vi = f['vertex']
  845. ui = f['uv']
  846. data = struct.pack('<IIIHIII',
  847. vi[0]-1, vi[1]-1, vi[2]-1,
  848. f['material'],
  849. ui[0]-1, ui[1]-1, ui[2]-1)
  850. buffer.append(data)
  851. # 7. smooth triangles uv
  852. # ----------------------
  853. # a unsigned int 4
  854. # b unsigned int 4
  855. # c unsigned int 4
  856. # m unsigned short 2
  857. # na unsigned int 4
  858. # nb unsigned int 4
  859. # nc unsigned int 4
  860. # ua unsigned int 4
  861. # ub unsigned int 4
  862. # uc unsigned int 4
  863. for f in sfaces['triangles_smooth_uv']:
  864. vi = f['vertex']
  865. ni = f['normal']
  866. ui = f['uv']
  867. data = struct.pack('<IIIHIIIIII',
  868. vi[0]-1, vi[1]-1, vi[2]-1,
  869. f['material'],
  870. ni[0]-1, ni[1]-1, ni[2]-1,
  871. ui[0]-1, ui[1]-1, ui[2]-1)
  872. buffer.append(data)
  873. # 8. flat quads
  874. # ------------------
  875. # a unsigned int 4
  876. # b unsigned int 4
  877. # c unsigned int 4
  878. # d unsigned int 4
  879. # m unsigned short 2
  880. for f in sfaces['quads_flat']:
  881. vi = f['vertex']
  882. data = struct.pack('<IIIIH',
  883. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  884. f['material'])
  885. buffer.append(data)
  886. # 9. smooth quads
  887. # -------------------
  888. # a unsigned int 4
  889. # b unsigned int 4
  890. # c unsigned int 4
  891. # d unsigned int 4
  892. # m unsigned short 2
  893. # na unsigned int 4
  894. # nb unsigned int 4
  895. # nc unsigned int 4
  896. # nd unsigned int 4
  897. for f in sfaces['quads_smooth']:
  898. vi = f['vertex']
  899. ni = f['normal']
  900. data = struct.pack('<IIIIHIIII',
  901. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  902. f['material'],
  903. ni[0]-1, ni[1]-1, ni[2]-1, ni[3]-1)
  904. buffer.append(data)
  905. # 10. flat quads uv
  906. # ------------------
  907. # a unsigned int 4
  908. # b unsigned int 4
  909. # c unsigned int 4
  910. # d unsigned int 4
  911. # m unsigned short 2
  912. # ua unsigned int 4
  913. # ub unsigned int 4
  914. # uc unsigned int 4
  915. # ud unsigned int 4
  916. for f in sfaces['quads_flat_uv']:
  917. vi = f['vertex']
  918. ui = f['uv']
  919. data = struct.pack('<IIIIHIIII',
  920. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  921. f['material'],
  922. ui[0]-1, ui[1]-1, ui[2]-1, ui[3]-1)
  923. buffer.append(data)
  924. # 11. smooth quads uv
  925. # -------------------
  926. # a unsigned int 4
  927. # b unsigned int 4
  928. # c unsigned int 4
  929. # d unsigned int 4
  930. # m unsigned short 2
  931. # na unsigned int 4
  932. # nb unsigned int 4
  933. # nc unsigned int 4
  934. # nd unsigned int 4
  935. # ua unsigned int 4
  936. # ub unsigned int 4
  937. # uc unsigned int 4
  938. # ud unsigned int 4
  939. for f in sfaces['quads_smooth_uv']:
  940. vi = f['vertex']
  941. ni = f['normal']
  942. ui = f['uv']
  943. data = struct.pack('<IIIIHIIIIIIII',
  944. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  945. f['material'],
  946. ni[0]-1, ni[1]-1, ni[2]-1, ni[3]-1,
  947. ui[0]-1, ui[1]-1, ui[2]-1, ui[3]-1)
  948. buffer.append(data)
  949. path = os.path.dirname(outfile)
  950. fname = os.path.join(path, binfile)
  951. out = open(fname, "wb")
  952. out.write("".join(buffer))
  953. out.close()
  954. # #############################################################################
  955. # Helpers
  956. # #############################################################################
  957. def usage():
  958. print "Usage: %s -i filename.obj -o filename.js [-m morphfiles*.obj] [-a center|top|bottom] [-s flat|smooth] [-t binary|ascii] [-d invert|normal]" % os.path.basename(sys.argv[0])
  959. # #####################################################
  960. # Main
  961. # #####################################################
  962. if __name__ == "__main__":
  963. # get parameters from the command line
  964. try:
  965. opts, args = getopt.getopt(sys.argv[1:], "hi:m:o:a:s:t:d:", ["help", "input=", "morphs=", "output=", "align=", "shading=", "type=", "dissolve="])
  966. except getopt.GetoptError:
  967. usage()
  968. sys.exit(2)
  969. infile = outfile = ""
  970. morphfiles = ""
  971. for o, a in opts:
  972. if o in ("-h", "--help"):
  973. usage()
  974. sys.exit()
  975. elif o in ("-i", "--input"):
  976. infile = a
  977. elif o in ("-m", "--morphs"):
  978. morphfiles = a
  979. elif o in ("-o", "--output"):
  980. outfile = a
  981. elif o in ("-a", "--align"):
  982. if a in ("top", "bottom", "center"):
  983. ALIGN = a
  984. elif o in ("-s", "--shading"):
  985. if a in ("flat", "smooth"):
  986. SHADING = a
  987. elif o in ("-t", "--type"):
  988. if a in ("binary", "ascii"):
  989. TYPE = a
  990. elif o in ("-d", "--dissolve"):
  991. if a in ("normal", "invert"):
  992. TRANSPARENCY = a
  993. if infile == "" or outfile == "":
  994. usage()
  995. sys.exit(2)
  996. print "Converting [%s] into [%s] ..." % (infile, outfile)
  997. if morphfiles:
  998. print "Morphs [%s]" % morphfiles
  999. if TYPE == "ascii":
  1000. convert_ascii(infile, morphfiles, outfile)
  1001. elif TYPE == "binary":
  1002. convert_binary(infile, outfile)