convert_obj_three.py 38 KB

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