convert_obj_three.py 38 KB

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