convert_obj_three.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  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. '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 centerxz(vertices):
  223. """Center model around X and Z.
  224. """
  225. bb = bbox(vertices)
  226. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  227. cy = 0
  228. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  229. translate(vertices, [-cx,-cy,-cz])
  230. def normalize(v):
  231. """Normalize 3d vector"""
  232. l = math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
  233. if l:
  234. v[0] /= l
  235. v[1] /= l
  236. v[2] /= l
  237. # #####################################################
  238. # MTL parser
  239. # #####################################################
  240. def texture_relative_path(fullpath):
  241. texture_file = os.path.basename(fullpath)
  242. return texture_file
  243. def parse_mtl(fname):
  244. """Parse MTL file.
  245. """
  246. materials = {}
  247. for line in fileinput.input(fname):
  248. chunks = line.split()
  249. if len(chunks) > 0:
  250. # Material start
  251. # newmtl identifier
  252. if chunks[0] == "newmtl" and len(chunks) == 2:
  253. identifier = chunks[1]
  254. if not identifier in materials:
  255. materials[identifier] = {}
  256. # Diffuse color
  257. # Kd 1.000 1.000 1.000
  258. if chunks[0] == "Kd" and len(chunks) == 4:
  259. materials[identifier]["colorDiffuse"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  260. # Ambient color
  261. # Ka 1.000 1.000 1.000
  262. if chunks[0] == "Ka" and len(chunks) == 4:
  263. materials[identifier]["colorAmbient"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  264. # Specular color
  265. # Ks 1.000 1.000 1.000
  266. if chunks[0] == "Ks" and len(chunks) == 4:
  267. materials[identifier]["colorSpecular"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  268. # Specular coefficient
  269. # Ns 154.000
  270. if chunks[0] == "Ns" and len(chunks) == 2:
  271. materials[identifier]["specularCoef"] = float(chunks[1])
  272. # Transparency
  273. # Tr 0.9 or d 0.9
  274. if (chunks[0] == "Tr" or chunks[0] == "d") and len(chunks) == 2:
  275. if TRANSPARENCY == "invert":
  276. materials[identifier]["transparency"] = 1.0 - float(chunks[1])
  277. else:
  278. materials[identifier]["transparency"] = float(chunks[1])
  279. # Optical density
  280. # Ni 1.0
  281. if chunks[0] == "Ni" and len(chunks) == 2:
  282. materials[identifier]["opticalDensity"] = float(chunks[1])
  283. # Diffuse texture
  284. # map_Kd texture_diffuse.jpg
  285. if chunks[0] == "map_Kd" and len(chunks) == 2:
  286. materials[identifier]["mapDiffuse"] = texture_relative_path(chunks[1])
  287. # Ambient texture
  288. # map_Ka texture_ambient.jpg
  289. if chunks[0] == "map_Ka" and len(chunks) == 2:
  290. materials[identifier]["mapAmbient"] = texture_relative_path(chunks[1])
  291. # Specular texture
  292. # map_Ks texture_specular.jpg
  293. if chunks[0] == "map_Ks" and len(chunks) == 2:
  294. materials[identifier]["mapSpecular"] = texture_relative_path(chunks[1])
  295. # Alpha texture
  296. # map_d texture_alpha.png
  297. if chunks[0] == "map_d" and len(chunks) == 2:
  298. materials[identifier]["mapAlpha"] = texture_relative_path(chunks[1])
  299. # Bump texture
  300. # map_bump texture_bump.jpg or bump texture_bump.jpg
  301. if (chunks[0] == "map_bump" or chunks[0] == "bump") and len(chunks) == 2:
  302. materials[identifier]["mapBump"] = texture_relative_path(chunks[1])
  303. # Illumination
  304. # illum 2
  305. #
  306. # 0. Color on and Ambient off
  307. # 1. Color on and Ambient on
  308. # 2. Highlight on
  309. # 3. Reflection on and Ray trace on
  310. # 4. Transparency: Glass on, Reflection: Ray trace on
  311. # 5. Reflection: Fresnel on and Ray trace on
  312. # 6. Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  313. # 7. Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  314. # 8. Reflection on and Ray trace off
  315. # 9. Transparency: Glass on, Reflection: Ray trace off
  316. # 10. Casts shadows onto invisible surfaces
  317. if chunks[0] == "illum" and len(chunks) == 2:
  318. materials[identifier]["illumination"] = int(chunks[1])
  319. return materials
  320. # #####################################################
  321. # OBJ parser
  322. # #####################################################
  323. def parse_vertex(text):
  324. """Parse text chunk specifying single vertex.
  325. Possible formats:
  326. vertex index
  327. vertex index / texture index
  328. vertex index / texture index / normal index
  329. vertex index / / normal index
  330. """
  331. v = 0
  332. t = 0
  333. n = 0
  334. chunks = text.split("/")
  335. v = int(chunks[0])
  336. if len(chunks) > 1:
  337. if chunks[1]:
  338. t = int(chunks[1])
  339. if len(chunks) > 2:
  340. if chunks[2]:
  341. n = int(chunks[2])
  342. return { 'v':v, 't':t, 'n':n }
  343. def parse_obj(fname):
  344. """Parse OBJ file.
  345. """
  346. vertices = []
  347. normals = []
  348. uvs = []
  349. faces = []
  350. materials = {}
  351. mcounter = 0
  352. mcurrent = 0
  353. mtllib = ""
  354. # current face state
  355. group = 0
  356. object = 0
  357. smooth = 0
  358. for line in fileinput.input(fname):
  359. chunks = line.split()
  360. if len(chunks) > 0:
  361. # Vertices as (x,y,z) coordinates
  362. # v 0.123 0.234 0.345
  363. if chunks[0] == "v" and len(chunks) == 4:
  364. x = float(chunks[1])
  365. y = float(chunks[2])
  366. z = float(chunks[3])
  367. vertices.append([x,y,z])
  368. # Normals in (x,y,z) form; normals might not be unit
  369. # vn 0.707 0.000 0.707
  370. if chunks[0] == "vn" and len(chunks) == 4:
  371. x = float(chunks[1])
  372. y = float(chunks[2])
  373. z = float(chunks[3])
  374. normals.append([x,y,z])
  375. # Texture coordinates in (u,v[,w]) coordinates, w is optional
  376. # vt 0.500 -1.352 [0.234]
  377. if chunks[0] == "vt" and len(chunks) >= 3:
  378. u = float(chunks[1])
  379. v = float(chunks[2])
  380. w = 0
  381. if len(chunks)>3:
  382. w = float(chunks[3])
  383. uvs.append([u,v,w])
  384. # Face
  385. if chunks[0] == "f" and len(chunks) >= 4:
  386. vertex_index = []
  387. uv_index = []
  388. normal_index = []
  389. for v in chunks[1:]:
  390. vertex = parse_vertex(v)
  391. if vertex['v']:
  392. vertex_index.append(vertex['v'])
  393. if vertex['t']:
  394. uv_index.append(vertex['t'])
  395. if vertex['n']:
  396. normal_index.append(vertex['n'])
  397. faces.append({
  398. 'vertex':vertex_index,
  399. 'uv':uv_index,
  400. 'normal':normal_index,
  401. 'material':mcurrent,
  402. 'group':group,
  403. 'object':object,
  404. 'smooth':smooth,
  405. })
  406. # Group
  407. if chunks[0] == "g" and len(chunks) == 2:
  408. group = chunks[1]
  409. # Object
  410. if chunks[0] == "o" and len(chunks) == 2:
  411. object = chunks[1]
  412. # Materials definition
  413. if chunks[0] == "mtllib" and len(chunks) == 2:
  414. mtllib = chunks[1]
  415. # Material
  416. if chunks[0] == "usemtl" and len(chunks) == 2:
  417. material = chunks[1]
  418. if not material in materials:
  419. mcurrent = mcounter
  420. materials[material] = mcounter
  421. mcounter += 1
  422. else:
  423. mcurrent = materials[material]
  424. # Smooth shading
  425. if chunks[0] == "s" and len(chunks) == 2:
  426. smooth = chunks[1]
  427. return faces, vertices, uvs, normals, materials, mtllib
  428. # #####################################################
  429. # Generator
  430. # #####################################################
  431. def setBit(value, position, on):
  432. if on:
  433. mask = 1 << position
  434. return (value | mask)
  435. else:
  436. mask = ~(1 << position)
  437. return (value & mask)
  438. def generate_vertex(v):
  439. return TEMPLATE_VERTEX % (v[0], v[1], v[2])
  440. def generate_face(f):
  441. isTriangle = ( len(f['vertex']) == 3 )
  442. if isTriangle:
  443. nVertices = 3
  444. else:
  445. nVertices = 4
  446. hasMaterial = True # for the moment OBJs without materials get default material
  447. hasFaceUvs = False # not supported in OBJ
  448. hasFaceVertexUvs = ( len(f['uv']) >= nVertices )
  449. hasFaceNormals = False # don't export any face normals (as they are computed in engine)
  450. hasFaceVertexNormals = ( len(f["normal"]) >= nVertices and SHADING == "smooth" )
  451. hasFaceColors = False # not supported in OBJ
  452. hasFaceVertexColors = False # not supported in OBJ
  453. faceType = 0
  454. faceType = setBit(faceType, 0, not isTriangle)
  455. faceType = setBit(faceType, 1, hasMaterial)
  456. faceType = setBit(faceType, 2, hasFaceUvs)
  457. faceType = setBit(faceType, 3, hasFaceVertexUvs)
  458. faceType = setBit(faceType, 4, hasFaceNormals)
  459. faceType = setBit(faceType, 5, hasFaceVertexNormals)
  460. faceType = setBit(faceType, 6, hasFaceColors)
  461. faceType = setBit(faceType, 7, hasFaceVertexColors)
  462. faceData = []
  463. # order is important, must match order in JSONLoader
  464. # face type
  465. # vertex indices
  466. # material index
  467. # face uvs index
  468. # face vertex uvs indices
  469. # face color index
  470. # face vertex colors indices
  471. faceData.append(faceType)
  472. # must clamp in case on polygons bigger than quads
  473. for i in xrange(nVertices):
  474. index = f['vertex'][i] - 1
  475. faceData.append(index)
  476. faceData.append( f['material'] )
  477. if hasFaceVertexUvs:
  478. for i in xrange(nVertices):
  479. index = f['uv'][i] - 1
  480. faceData.append(index)
  481. if hasFaceVertexNormals:
  482. for i in xrange(nVertices):
  483. index = f['normal'][i] - 1
  484. faceData.append(index)
  485. return ",".join( map(str, faceData) )
  486. def generate_normal(n):
  487. return TEMPLATE_N % (n[0], n[1], n[2])
  488. def generate_uv(uv):
  489. return TEMPLATE_UV % (uv[0], 1.0 - uv[1])
  490. # #####################################################
  491. # Morphs
  492. # #####################################################
  493. def generate_morph(name, vertices):
  494. vertex_string = ",".join(generate_vertex(v) for v in vertices)
  495. return TEMPLATE_MORPH % (name, vertex_string)
  496. # #####################################################
  497. # Materials
  498. # #####################################################
  499. def generate_color(i):
  500. """Generate hex color corresponding to integer.
  501. Colors should have well defined ordering.
  502. First N colors are hardcoded, then colors are random
  503. (must seed random number generator with deterministic value
  504. before getting colors).
  505. """
  506. if i < len(COLORS):
  507. return "0x%06x" % COLORS[i]
  508. else:
  509. return "0x%06x" % int(0xffffff * random.random())
  510. def value2string(v):
  511. if type(v)==str and v[0:2] != "0x":
  512. return '"%s"' % v
  513. return str(v)
  514. def generate_materials(mtl, materials):
  515. """Generate JS array of materials objects
  516. JS material objects are basically prettified one-to-one
  517. mappings of MTL properties in JSON format.
  518. """
  519. mtl_array = []
  520. for m in mtl:
  521. if m in materials:
  522. index = materials[m]
  523. # add debug information
  524. # materials should be sorted according to how
  525. # they appeared in OBJ file (for the first time)
  526. # this index is identifier used in face definitions
  527. mtl[m]['DbgName'] = m
  528. mtl[m]['DbgIndex'] = index
  529. mtl[m]['DbgColor'] = generate_color(index)
  530. mtl_raw = ",\n".join(['\t"%s" : %s' % (n, value2string(v)) for n,v in sorted(mtl[m].items())])
  531. mtl_string = "\t{\n%s\n\t}" % mtl_raw
  532. mtl_array.append([index, mtl_string])
  533. return ",\n\n".join([m for i,m in sorted(mtl_array)])
  534. def generate_mtl(materials):
  535. """Generate dummy materials (if there is no MTL file).
  536. """
  537. mtl = {}
  538. for m in materials:
  539. index = materials[m]
  540. mtl[m] = {
  541. 'DbgName': m,
  542. 'DbgIndex': index,
  543. 'DbgColor': generate_color(index)
  544. }
  545. return mtl
  546. def generate_materials_string(materials, mtllib):
  547. """Generate final materials string.
  548. """
  549. random.seed(42) # to get well defined color order for materials
  550. # default materials with debug colors for when
  551. # there is no specified MTL / MTL loading failed,
  552. # or if there were no materials / null materials
  553. if not materials:
  554. materials = { 'default':0 }
  555. mtl = generate_mtl(materials)
  556. if mtllib:
  557. # create full pathname for MTL (included from OBJ)
  558. path = os.path.dirname(infile)
  559. fname = os.path.join(path, mtllib)
  560. if file_exists(fname):
  561. # override default materials with real ones from MTL
  562. # (where they exist, otherwise keep defaults)
  563. mtl.update(parse_mtl(fname))
  564. else:
  565. print "Couldn't find [%s]" % fname
  566. return generate_materials(mtl, materials)
  567. # #####################################################
  568. # Faces
  569. # #####################################################
  570. def is_triangle_flat(f):
  571. return len(f['vertex'])==3 and not (f["normal"] and SHADING == "smooth") and not f['uv']
  572. def is_triangle_flat_uv(f):
  573. return len(f['vertex'])==3 and not (f["normal"] and SHADING == "smooth") and len(f['uv'])==3
  574. def is_triangle_smooth(f):
  575. return len(f['vertex'])==3 and f["normal"] and SHADING == "smooth" and not f['uv']
  576. def is_triangle_smooth_uv(f):
  577. return len(f['vertex'])==3 and f["normal"] and SHADING == "smooth" and len(f['uv'])==3
  578. def is_quad_flat(f):
  579. return len(f['vertex'])==4 and not (f["normal"] and SHADING == "smooth") and not f['uv']
  580. def is_quad_flat_uv(f):
  581. return len(f['vertex'])==4 and not (f["normal"] and SHADING == "smooth") and len(f['uv'])==4
  582. def is_quad_smooth(f):
  583. return len(f['vertex'])==4 and f["normal"] and SHADING == "smooth" and not f['uv']
  584. def is_quad_smooth_uv(f):
  585. return len(f['vertex'])==4 and f["normal"] and SHADING == "smooth" and len(f['uv'])==4
  586. def sort_faces(faces):
  587. data = {
  588. 'triangles_flat': [],
  589. 'triangles_flat_uv': [],
  590. 'triangles_smooth': [],
  591. 'triangles_smooth_uv': [],
  592. 'quads_flat': [],
  593. 'quads_flat_uv': [],
  594. 'quads_smooth': [],
  595. 'quads_smooth_uv': []
  596. }
  597. for f in faces:
  598. if is_triangle_flat(f):
  599. data['triangles_flat'].append(f)
  600. elif is_triangle_flat_uv(f):
  601. data['triangles_flat_uv'].append(f)
  602. elif is_triangle_smooth(f):
  603. data['triangles_smooth'].append(f)
  604. elif is_triangle_smooth_uv(f):
  605. data['triangles_smooth_uv'].append(f)
  606. elif is_quad_flat(f):
  607. data['quads_flat'].append(f)
  608. elif is_quad_flat_uv(f):
  609. data['quads_flat_uv'].append(f)
  610. elif is_quad_smooth(f):
  611. data['quads_smooth'].append(f)
  612. elif is_quad_smooth_uv(f):
  613. data['quads_smooth_uv'].append(f)
  614. return data
  615. # #####################################################
  616. # API - ASCII converter
  617. # #####################################################
  618. def convert_ascii(infile, morphfiles, outfile):
  619. """Convert infile.obj to outfile.js
  620. Here is where everything happens. If you need to automate conversions,
  621. just import this file as Python module and call this method.
  622. """
  623. if not file_exists(infile):
  624. print "Couldn't find [%s]" % infile
  625. return
  626. faces, vertices, uvs, normals, materials, mtllib = parse_obj(infile)
  627. if ALIGN == "center":
  628. center(vertices)
  629. elif ALIGN == "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)