convert_obj_threejs_slim.py 37 KB

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