convert_obj_threejs_slim.py 37 KB

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