convert_obj_three.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  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"] [-c "morphcolors*.obj"] [-a center|centerxz|top|bottom|none] [-s smooth|flat] [-t ascii|binary] [-d invert|normal] [-b] [-e]
  6. Notes:
  7. - flags
  8. -i infile.obj input OBJ file
  9. -o outfile.js output JS file
  10. -m "morphfiles*.obj" morph OBJ files (can use wildcards, enclosed in quotes multiple patterns separate by space)
  11. -c "morphcolors*.obj" morph colors OBJ files (can use wildcards, enclosed in quotes multiple patterns separate by space)
  12. -a center|centerxz|top|bottom|none model alignment
  13. -s smooth|flat smooth = export vertex normals, flat = no normals (face normals computed in loader)
  14. -t ascii|binary export ascii or binary format (ascii has more features, binary just supports vertices, faces, normals, uvs and materials)
  15. -d invert|normal invert transparency
  16. -b bake material colors into face colors
  17. -e export edges
  18. -x 10.0 scale and truncate
  19. - by default:
  20. use smooth shading (if there were vertex normals in the original model)
  21. will be in ASCII format
  22. original model is assumed to use non-inverted transparency / dissolve (0.0 fully transparent, 1.0 fully opaque)
  23. no face colors baking
  24. no edges export
  25. - binary conversion will create two files:
  26. outfile.js (materials)
  27. outfile.bin (binary buffers)
  28. --------------------------------------------------
  29. How to use generated JS file in your HTML document
  30. --------------------------------------------------
  31. <script type="text/javascript" src="Three.js"></script>
  32. ...
  33. <script type="text/javascript">
  34. ...
  35. // load ascii model
  36. var jsonLoader = new THREE.JSONLoader();
  37. jsonLoader.load( { model: "Model_ascii.js", callback: function( geometry ) { createScene( geometry) } } );
  38. // load binary model
  39. var binLoader = new THREE.BinaryLoader();
  40. binLoader.load( { model: "Model_bin.js", callback: function( geometry ) { createScene( geometry) } } );
  41. function createScene( geometry ) {
  42. var mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );
  43. }
  44. ...
  45. </script>
  46. -------------------------------------
  47. Parsers based on formats descriptions
  48. -------------------------------------
  49. http://en.wikipedia.org/wiki/Obj
  50. http://en.wikipedia.org/wiki/Material_Template_Library
  51. -------------------
  52. Current limitations
  53. -------------------
  54. - for the moment, only diffuse color and texture are used
  55. (will need to extend shaders / renderers / materials in Three)
  56. - models can have more than 65,536 vertices
  57. - texture coordinates can be wrong in canvas renderer
  58. (there is crude normalization, but it doesn't
  59. work for all cases)
  60. - smoothing can be turned on/off only for the whole mesh
  61. ----------------------------------------------
  62. How to get proper OBJ + MTL files with Blender
  63. ----------------------------------------------
  64. 0. Remove default cube (press DEL and ENTER)
  65. 1. Import / create model
  66. 2. Select all meshes (Select -> Select All by Type -> Mesh)
  67. 3. Export to OBJ (File -> Export -> Wavefront .obj) [*]
  68. - enable following options in exporter
  69. Material Groups
  70. Rotate X90
  71. Apply Modifiers
  72. High Quality Normals
  73. Copy Images
  74. Selection Only
  75. Objects as OBJ Objects
  76. UVs
  77. Normals
  78. Materials
  79. Edges
  80. - select empty folder
  81. - give your exported file name with "obj" extension
  82. - click on "Export OBJ" button
  83. 4. Your model is now all files in this folder (OBJ, MTL, number of images)
  84. - this converter assumes all files staying in the same folder,
  85. (OBJ / MTL files use relative paths)
  86. - for WebGL, textures must be power of 2 sized
  87. [*] If OBJ export fails (Blender 2.54 beta), patch your Blender installation
  88. following instructions here:
  89. http://www.blendernation.com/2010/09/12/blender-2-54-beta-released/
  90. ------
  91. Author
  92. ------
  93. AlteredQualia http://alteredqualia.com
  94. """
  95. import fileinput
  96. import operator
  97. import random
  98. import os.path
  99. import getopt
  100. import sys
  101. import struct
  102. import math
  103. import glob
  104. # #####################################################
  105. # Configuration
  106. # #####################################################
  107. ALIGN = "none" # center centerxz bottom top none
  108. SHADING = "smooth" # smooth flat
  109. TYPE = "ascii" # ascii binary
  110. TRANSPARENCY = "normal" # normal invert
  111. TRUNCATE = False
  112. SCALE = 1.0
  113. BAKE_COLORS = False
  114. EXPORT_EDGES = False
  115. # default colors for debugging (each material gets one distinct color):
  116. # white, red, green, blue, yellow, cyan, magenta
  117. COLORS = [0xeeeeee, 0xee0000, 0x00ee00, 0x0000ee, 0xeeee00, 0x00eeee, 0xee00ee]
  118. # #####################################################
  119. # Templates
  120. # #####################################################
  121. TEMPLATE_FILE_ASCII = u"""\
  122. // Converted from: %(fname)s
  123. // vertices: %(nvertex)d
  124. // faces: %(nface)d
  125. // normals: %(nnormal)d
  126. // colors: %(ncolor)d
  127. // uvs: %(nuv)d
  128. // materials: %(nmaterial)d
  129. // edges: %(nedge)d
  130. //
  131. // Generated with OBJ -> Three.js converter
  132. // http://github.com/alteredq/three.js/blob/master/utils/exporters/convert_obj_three.py
  133. var model = {
  134. "version" : 2,
  135. "scale" : %(scale)f,
  136. "materials": [%(materials)s],
  137. "vertices": [%(vertices)s],
  138. "morphTargets": [%(morphTargets)s],
  139. "morphColors": [%(morphColors)s],
  140. "normals": [%(normals)s],
  141. "colors": [%(colors)s],
  142. "uvs": [[%(uvs)s]],
  143. "faces": [%(faces)s],
  144. "edges" : [%(edges)s]
  145. };
  146. postMessage( model );
  147. close();
  148. """
  149. TEMPLATE_FILE_BIN = u"""\
  150. // Converted from: %(fname)s
  151. // vertices: %(nvertex)d
  152. // faces: %(nface)d
  153. // materials: %(nmaterial)d
  154. //
  155. // Generated with OBJ -> Three.js converter
  156. // http://github.com/alteredq/three.js/blob/master/utils/exporters/convert_obj_three.py
  157. var model = {
  158. "version" : 1,
  159. "materials": [%(materials)s],
  160. "buffers": "%(buffers)s"
  161. };
  162. postMessage( model );
  163. close();
  164. """
  165. TEMPLATE_VERTEX = "%f,%f,%f"
  166. TEMPLATE_VERTEX_TRUNCATE = "%d,%d,%d"
  167. TEMPLATE_N = "%f,%f,%f"
  168. TEMPLATE_UV = "%f,%f"
  169. TEMPLATE_COLOR = "%.3f,%.3f,%.3f"
  170. TEMPLATE_COLOR_DEC = "%d"
  171. TEMPLATE_EDGE = "%d,%d"
  172. TEMPLATE_MORPH_VERTICES = '\t{ "name": "%s", "vertices": [%s] }'
  173. TEMPLATE_MORPH_COLORS = '\t{ "name": "%s", "colors": [%s] }'
  174. # #####################################################
  175. # Utils
  176. # #####################################################
  177. def file_exists(filename):
  178. """Return true if file exists and is accessible for reading.
  179. Should be safer than just testing for existence due to links and
  180. permissions magic on Unix filesystems.
  181. @rtype: boolean
  182. """
  183. try:
  184. f = open(filename, 'r')
  185. f.close()
  186. return True
  187. except IOError:
  188. return False
  189. def get_name(fname):
  190. """Create model name based of filename ("path/fname.js" -> "fname").
  191. """
  192. return os.path.splitext(os.path.basename(fname))[0]
  193. def bbox(vertices):
  194. """Compute bounding box of vertex array.
  195. """
  196. if len(vertices)>0:
  197. minx = maxx = vertices[0][0]
  198. miny = maxy = vertices[0][1]
  199. minz = maxz = vertices[0][2]
  200. for v in vertices[1:]:
  201. if v[0]<minx:
  202. minx = v[0]
  203. elif v[0]>maxx:
  204. maxx = v[0]
  205. if v[1]<miny:
  206. miny = v[1]
  207. elif v[1]>maxy:
  208. maxy = v[1]
  209. if v[2]<minz:
  210. minz = v[2]
  211. elif v[2]>maxz:
  212. maxz = v[2]
  213. return { 'x':[minx,maxx], 'y':[miny,maxy], 'z':[minz,maxz] }
  214. else:
  215. return { 'x':[0,0], 'y':[0,0], 'z':[0,0] }
  216. def translate(vertices, t):
  217. """Translate array of vertices by vector t.
  218. """
  219. for i in xrange(len(vertices)):
  220. vertices[i][0] += t[0]
  221. vertices[i][1] += t[1]
  222. vertices[i][2] += t[2]
  223. def center(vertices):
  224. """Center model (middle of bounding box).
  225. """
  226. bb = bbox(vertices)
  227. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  228. cy = bb['y'][0] + (bb['y'][1] - bb['y'][0])/2.0
  229. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  230. translate(vertices, [-cx,-cy,-cz])
  231. def top(vertices):
  232. """Align top of the model with the floor (Y-axis) and center it around X and Z.
  233. """
  234. bb = bbox(vertices)
  235. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  236. cy = bb['y'][1]
  237. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  238. translate(vertices, [-cx,-cy,-cz])
  239. def bottom(vertices):
  240. """Align bottom of the model with the floor (Y-axis) and center it around X and Z.
  241. """
  242. bb = bbox(vertices)
  243. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  244. cy = bb['y'][0]
  245. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  246. translate(vertices, [-cx,-cy,-cz])
  247. def centerxz(vertices):
  248. """Center model around X and Z.
  249. """
  250. bb = bbox(vertices)
  251. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  252. cy = 0
  253. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  254. translate(vertices, [-cx,-cy,-cz])
  255. def normalize(v):
  256. """Normalize 3d vector"""
  257. l = math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
  258. if l:
  259. v[0] /= l
  260. v[1] /= l
  261. v[2] /= l
  262. def veckey3(v):
  263. return round(v[0], 6), round(v[1], 6), round(v[2], 6)
  264. # #####################################################
  265. # MTL parser
  266. # #####################################################
  267. def texture_relative_path(fullpath):
  268. texture_file = os.path.basename(fullpath)
  269. return texture_file
  270. def parse_mtl(fname):
  271. """Parse MTL file.
  272. """
  273. materials = {}
  274. for line in fileinput.input(fname):
  275. chunks = line.split()
  276. if len(chunks) > 0:
  277. # Material start
  278. # newmtl identifier
  279. if chunks[0] == "newmtl" and len(chunks) == 2:
  280. identifier = chunks[1]
  281. if not identifier in materials:
  282. materials[identifier] = {}
  283. # Diffuse color
  284. # Kd 1.000 1.000 1.000
  285. if chunks[0] == "Kd" and len(chunks) == 4:
  286. materials[identifier]["colorDiffuse"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  287. # Ambient color
  288. # Ka 1.000 1.000 1.000
  289. if chunks[0] == "Ka" and len(chunks) == 4:
  290. materials[identifier]["colorAmbient"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  291. # Specular color
  292. # Ks 1.000 1.000 1.000
  293. if chunks[0] == "Ks" and len(chunks) == 4:
  294. materials[identifier]["colorSpecular"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  295. # Specular coefficient
  296. # Ns 154.000
  297. if chunks[0] == "Ns" and len(chunks) == 2:
  298. materials[identifier]["specularCoef"] = float(chunks[1])
  299. # Transparency
  300. # Tr 0.9 or d 0.9
  301. if (chunks[0] == "Tr" or chunks[0] == "d") and len(chunks) == 2:
  302. if TRANSPARENCY == "invert":
  303. materials[identifier]["transparency"] = 1.0 - float(chunks[1])
  304. else:
  305. materials[identifier]["transparency"] = float(chunks[1])
  306. # Optical density
  307. # Ni 1.0
  308. if chunks[0] == "Ni" and len(chunks) == 2:
  309. materials[identifier]["opticalDensity"] = float(chunks[1])
  310. # Diffuse texture
  311. # map_Kd texture_diffuse.jpg
  312. if chunks[0] == "map_Kd" and len(chunks) == 2:
  313. materials[identifier]["mapDiffuse"] = texture_relative_path(chunks[1])
  314. # Ambient texture
  315. # map_Ka texture_ambient.jpg
  316. if chunks[0] == "map_Ka" and len(chunks) == 2:
  317. materials[identifier]["mapAmbient"] = texture_relative_path(chunks[1])
  318. # Specular texture
  319. # map_Ks texture_specular.jpg
  320. if chunks[0] == "map_Ks" and len(chunks) == 2:
  321. materials[identifier]["mapSpecular"] = texture_relative_path(chunks[1])
  322. # Alpha texture
  323. # map_d texture_alpha.png
  324. if chunks[0] == "map_d" and len(chunks) == 2:
  325. materials[identifier]["mapAlpha"] = texture_relative_path(chunks[1])
  326. # Bump texture
  327. # map_bump texture_bump.jpg or bump texture_bump.jpg
  328. if (chunks[0] == "map_bump" or chunks[0] == "bump") and len(chunks) == 2:
  329. materials[identifier]["mapBump"] = texture_relative_path(chunks[1])
  330. # Illumination
  331. # illum 2
  332. #
  333. # 0. Color on and Ambient off
  334. # 1. Color on and Ambient on
  335. # 2. Highlight on
  336. # 3. Reflection on and Ray trace on
  337. # 4. Transparency: Glass on, Reflection: Ray trace on
  338. # 5. Reflection: Fresnel on and Ray trace on
  339. # 6. Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  340. # 7. Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  341. # 8. Reflection on and Ray trace off
  342. # 9. Transparency: Glass on, Reflection: Ray trace off
  343. # 10. Casts shadows onto invisible surfaces
  344. if chunks[0] == "illum" and len(chunks) == 2:
  345. materials[identifier]["illumination"] = int(chunks[1])
  346. return materials
  347. # #####################################################
  348. # OBJ parser
  349. # #####################################################
  350. def parse_vertex(text):
  351. """Parse text chunk specifying single vertex.
  352. Possible formats:
  353. vertex index
  354. vertex index / texture index
  355. vertex index / texture index / normal index
  356. vertex index / / normal index
  357. """
  358. v = 0
  359. t = 0
  360. n = 0
  361. chunks = text.split("/")
  362. v = int(chunks[0])
  363. if len(chunks) > 1:
  364. if chunks[1]:
  365. t = int(chunks[1])
  366. if len(chunks) > 2:
  367. if chunks[2]:
  368. n = int(chunks[2])
  369. return { 'v':v, 't':t, 'n':n }
  370. def parse_obj(fname):
  371. """Parse OBJ file.
  372. """
  373. vertices = []
  374. normals = []
  375. uvs = []
  376. faces = []
  377. materials = {}
  378. mcounter = 0
  379. mcurrent = 0
  380. mtllib = ""
  381. # current face state
  382. group = 0
  383. object = 0
  384. smooth = 0
  385. for line in fileinput.input(fname):
  386. chunks = line.split()
  387. if len(chunks) > 0:
  388. # Vertices as (x,y,z) coordinates
  389. # v 0.123 0.234 0.345
  390. if chunks[0] == "v" and len(chunks) == 4:
  391. x = float(chunks[1])
  392. y = float(chunks[2])
  393. z = float(chunks[3])
  394. vertices.append([x,y,z])
  395. # Normals in (x,y,z) form; normals might not be unit
  396. # vn 0.707 0.000 0.707
  397. if chunks[0] == "vn" and len(chunks) == 4:
  398. x = float(chunks[1])
  399. y = float(chunks[2])
  400. z = float(chunks[3])
  401. normals.append([x,y,z])
  402. # Texture coordinates in (u,v[,w]) coordinates, w is optional
  403. # vt 0.500 -1.352 [0.234]
  404. if chunks[0] == "vt" and len(chunks) >= 3:
  405. u = float(chunks[1])
  406. v = float(chunks[2])
  407. w = 0
  408. if len(chunks)>3:
  409. w = float(chunks[3])
  410. uvs.append([u,v,w])
  411. # Face
  412. if chunks[0] == "f" and len(chunks) >= 4:
  413. vertex_index = []
  414. uv_index = []
  415. normal_index = []
  416. for v in chunks[1:]:
  417. vertex = parse_vertex(v)
  418. if vertex['v']:
  419. vertex_index.append(vertex['v'])
  420. if vertex['t']:
  421. uv_index.append(vertex['t'])
  422. if vertex['n']:
  423. normal_index.append(vertex['n'])
  424. faces.append({
  425. 'vertex':vertex_index,
  426. 'uv':uv_index,
  427. 'normal':normal_index,
  428. 'material':mcurrent,
  429. 'group':group,
  430. 'object':object,
  431. 'smooth':smooth,
  432. })
  433. # Group
  434. if chunks[0] == "g" and len(chunks) == 2:
  435. group = chunks[1]
  436. # Object
  437. if chunks[0] == "o" and len(chunks) == 2:
  438. object = chunks[1]
  439. # Materials definition
  440. if chunks[0] == "mtllib" and len(chunks) == 2:
  441. mtllib = chunks[1]
  442. # Material
  443. if chunks[0] == "usemtl" and len(chunks) == 2:
  444. material = chunks[1]
  445. if not material in materials:
  446. mcurrent = mcounter
  447. materials[material] = mcounter
  448. mcounter += 1
  449. else:
  450. mcurrent = materials[material]
  451. # Smooth shading
  452. if chunks[0] == "s" and len(chunks) == 2:
  453. smooth = chunks[1]
  454. return faces, vertices, uvs, normals, materials, mtllib
  455. # #####################################################
  456. # Generator - faces
  457. # #####################################################
  458. def setBit(value, position, on):
  459. if on:
  460. mask = 1 << position
  461. return (value | mask)
  462. else:
  463. mask = ~(1 << position)
  464. return (value & mask)
  465. def generate_face(f, fc):
  466. isTriangle = ( len(f['vertex']) == 3 )
  467. if isTriangle:
  468. nVertices = 3
  469. else:
  470. nVertices = 4
  471. hasMaterial = True # for the moment OBJs without materials get default material
  472. hasFaceUvs = False # not supported in OBJ
  473. hasFaceVertexUvs = ( len(f['uv']) >= nVertices )
  474. hasFaceNormals = False # don't export any face normals (as they are computed in engine)
  475. hasFaceVertexNormals = ( len(f["normal"]) >= nVertices and SHADING == "smooth" )
  476. hasFaceColors = BAKE_COLORS
  477. hasFaceVertexColors = False # not supported in OBJ
  478. faceType = 0
  479. faceType = setBit(faceType, 0, not isTriangle)
  480. faceType = setBit(faceType, 1, hasMaterial)
  481. faceType = setBit(faceType, 2, hasFaceUvs)
  482. faceType = setBit(faceType, 3, hasFaceVertexUvs)
  483. faceType = setBit(faceType, 4, hasFaceNormals)
  484. faceType = setBit(faceType, 5, hasFaceVertexNormals)
  485. faceType = setBit(faceType, 6, hasFaceColors)
  486. faceType = setBit(faceType, 7, hasFaceVertexColors)
  487. faceData = []
  488. # order is important, must match order in JSONLoader
  489. # face type
  490. # vertex indices
  491. # material index
  492. # face uvs index
  493. # face vertex uvs indices
  494. # face normal index
  495. # face vertex normals indices
  496. # face color index
  497. # face vertex colors indices
  498. faceData.append(faceType)
  499. # must clamp in case on polygons bigger than quads
  500. for i in xrange(nVertices):
  501. index = f['vertex'][i] - 1
  502. faceData.append(index)
  503. faceData.append( f['material'] )
  504. if hasFaceVertexUvs:
  505. for i in xrange(nVertices):
  506. index = f['uv'][i] - 1
  507. faceData.append(index)
  508. if hasFaceVertexNormals:
  509. for i in xrange(nVertices):
  510. index = f['normal'][i] - 1
  511. faceData.append(index)
  512. if hasFaceColors:
  513. index = fc['material']
  514. faceData.append(index)
  515. return ",".join( map(str, faceData) )
  516. # #####################################################
  517. # Generator - chunks
  518. # #####################################################
  519. def hexcolor(c):
  520. return ( int(c[0] * 255) << 16 ) + ( int(c[1] * 255) << 8 ) + int(c[2] * 255)
  521. def generate_vertex(v, option_vertices_truncate, scale):
  522. if not option_vertices_truncate:
  523. return TEMPLATE_VERTEX % (v[0], v[1], v[2])
  524. else:
  525. return TEMPLATE_VERTEX_TRUNCATE % (scale * v[0], scale * v[1], scale * v[2])
  526. def generate_normal(n):
  527. return TEMPLATE_N % (n[0], n[1], n[2])
  528. def generate_uv(uv):
  529. return TEMPLATE_UV % (uv[0], 1.0 - uv[1])
  530. def generate_color_rgb(c):
  531. return TEMPLATE_COLOR % (c[0], c[1], c[2])
  532. def generate_color_decimal(c):
  533. return TEMPLATE_COLOR_DEC % hexcolor(c)
  534. def generate_edge(e):
  535. return TEMPLATE_EDGE % (e[0], e[1])
  536. # #####################################################
  537. # Morphs
  538. # #####################################################
  539. def generate_morph_vertex(name, vertices):
  540. vertex_string = ",".join(generate_vertex(v, TRUNCATE, SCALE) for v in vertices)
  541. return TEMPLATE_MORPH_VERTICES % (name, vertex_string)
  542. def generate_morph_color(name, colors):
  543. color_string = ",".join(generate_color_rgb(c) for c in colors)
  544. return TEMPLATE_MORPH_COLORS % (name, color_string)
  545. def extract_material_colors(materials, mtlfilename, basename):
  546. """Extract diffuse colors from MTL materials
  547. """
  548. if not materials:
  549. materials = { 'default': 0 }
  550. mtl = create_materials(materials, mtlfilename, basename)
  551. mtlColorArraySrt = []
  552. for m in mtl:
  553. if m in materials:
  554. index = materials[m]
  555. color = mtl[m].get("colorDiffuse", [1,0,0])
  556. mtlColorArraySrt.append([index, color])
  557. mtlColorArraySrt.sort()
  558. mtlColorArray = [x[1] for x in mtlColorArraySrt]
  559. return mtlColorArray
  560. def extract_face_colors(faces, material_colors):
  561. """Extract colors from materials and assign them to faces
  562. """
  563. faceColors = []
  564. for face in faces:
  565. material_index = face['material']
  566. faceColors.append(material_colors[material_index])
  567. return faceColors
  568. def generate_morph_targets(morphfiles, n_vertices, infile):
  569. skipOriginalMorph = False
  570. norminfile = os.path.normpath(infile)
  571. morphVertexData = []
  572. for mfilepattern in morphfiles.split():
  573. matches = glob.glob(mfilepattern)
  574. matches.sort()
  575. for path in matches:
  576. normpath = os.path.normpath(path)
  577. if normpath != norminfile or not skipOriginalMorph:
  578. name = os.path.basename(normpath)
  579. morphFaces, morphVertices, morphUvs, morphNormals, morphMaterials, morphMtllib = parse_obj(normpath)
  580. n_morph_vertices = len(morphVertices)
  581. if n_vertices != n_morph_vertices:
  582. print "WARNING: skipping morph [%s] with different number of vertices [%d] than the original model [%d]" % (name, n_morph_vertices, n_vertices)
  583. else:
  584. if ALIGN == "center":
  585. center(morphVertices)
  586. elif ALIGN == "centerxz":
  587. centerxz(morphVertices)
  588. elif ALIGN == "bottom":
  589. bottom(morphVertices)
  590. elif ALIGN == "top":
  591. top(morphVertices)
  592. morphVertexData.append((get_name(name), morphVertices))
  593. print "adding [%s] with %d vertices" % (name, n_morph_vertices)
  594. morphTargets = ""
  595. if len(morphVertexData):
  596. morphTargets = "\n%s\n\t" % ",\n".join(generate_morph_vertex(name, vertices) for name, vertices in morphVertexData)
  597. return morphTargets
  598. def generate_morph_colors(colorfiles, n_vertices, n_faces):
  599. morphColorData = []
  600. colorFaces = []
  601. materialColors = []
  602. for mfilepattern in colorfiles.split():
  603. matches = glob.glob(mfilepattern)
  604. matches.sort()
  605. for path in matches:
  606. normpath = os.path.normpath(path)
  607. name = os.path.basename(normpath)
  608. morphFaces, morphVertices, morphUvs, morphNormals, morphMaterials, morphMtllib = parse_obj(normpath)
  609. n_morph_vertices = len(morphVertices)
  610. n_morph_faces = len(morphFaces)
  611. if n_vertices != n_morph_vertices:
  612. print "WARNING: skipping morph color map [%s] with different number of vertices [%d] than the original model [%d]" % (name, n_morph_vertices, n_vertices)
  613. elif n_faces != n_morph_faces:
  614. print "WARNING: skipping morph color map [%s] with different number of faces [%d] than the original model [%d]" % (name, n_morph_faces, n_faces)
  615. else:
  616. morphMaterialColors = extract_material_colors(morphMaterials, morphMtllib, normpath)
  617. morphFaceColors = extract_face_colors(morphFaces, morphMaterialColors)
  618. morphColorData.append((get_name(name), morphFaceColors))
  619. # take first color map for baking into face colors
  620. if len(colorFaces) == 0:
  621. colorFaces = morphFaces
  622. materialColors = morphMaterialColors
  623. print "adding [%s] with %d face colors" % (name, len(morphFaceColors))
  624. morphColors = ""
  625. if len(morphColorData):
  626. morphColors = "\n%s\n\t" % ",\n".join(generate_morph_color(name, colors) for name, colors in morphColorData)
  627. return morphColors, colorFaces, materialColors
  628. # #####################################################
  629. # Edges
  630. # #####################################################
  631. def edge_hash(a, b):
  632. return "%d_%d" % (min(a, b), max(a, b))
  633. def add_unique_edge(a, b, edge_set, edges):
  634. h = edge_hash(a[0], b[0])
  635. if h not in edge_set:
  636. x = min(a[1], b[1])
  637. y = max(a[1], b[1])
  638. edges.append([x, y])
  639. edge_set.add(h)
  640. def compute_edges(faces, vertices):
  641. edges = []
  642. # compute unique vertices
  643. unique_vertices = {}
  644. vertex_count = 0
  645. for i, v in enumerate(vertices):
  646. key = veckey3(v)
  647. if key not in unique_vertices:
  648. unique_vertices[key] = [vertex_count, i]
  649. vertex_count += 1
  650. # find edges between unique vertices
  651. edge_set = set()
  652. for f in faces:
  653. vertex_indices = f["vertex"]
  654. unique_indices = []
  655. for vi in vertex_indices:
  656. v = vertices[vi - 1]
  657. key = veckey3(v)
  658. unique_indices.append(unique_vertices[key])
  659. if len(unique_indices) == 3:
  660. a = unique_indices[0]
  661. b = unique_indices[1]
  662. c = unique_indices[2]
  663. add_unique_edge(a, b, edge_set, edges)
  664. add_unique_edge(b, c, edge_set, edges)
  665. add_unique_edge(a, c, edge_set, edges)
  666. elif len(unique_indices) == 4:
  667. a = unique_indices[0]
  668. b = unique_indices[1]
  669. c = unique_indices[2]
  670. d = unique_indices[3]
  671. # this should be inside edge of quad, should it go in?
  672. # add_unique_edge(b, d, edge_set, edges)
  673. add_unique_edge(a, b, edge_set, edges)
  674. add_unique_edge(a, d, edge_set, edges)
  675. add_unique_edge(b, c, edge_set, edges)
  676. add_unique_edge(c, d, edge_set, edges)
  677. edges.sort()
  678. return edges
  679. # #####################################################
  680. # Materials
  681. # #####################################################
  682. def generate_color(i):
  683. """Generate hex color corresponding to integer.
  684. Colors should have well defined ordering.
  685. First N colors are hardcoded, then colors are random
  686. (must seed random number generator with deterministic value
  687. before getting colors).
  688. """
  689. if i < len(COLORS):
  690. #return "0x%06x" % COLORS[i]
  691. return COLORS[i]
  692. else:
  693. #return "0x%06x" % int(0xffffff * random.random())
  694. return int(0xffffff * random.random())
  695. def value2string(v):
  696. if type(v)==str and v[0:2] != "0x":
  697. return '"%s"' % v
  698. elif type(v) == bool:
  699. return str(v).lower()
  700. return str(v)
  701. def generate_materials(mtl, materials):
  702. """Generate JS array of materials objects
  703. JS material objects are basically prettified one-to-one
  704. mappings of MTL properties in JSON format.
  705. """
  706. mtl_array = []
  707. for m in mtl:
  708. if m in materials:
  709. index = materials[m]
  710. # add debug information
  711. # materials should be sorted according to how
  712. # they appeared in OBJ file (for the first time)
  713. # this index is identifier used in face definitions
  714. mtl[m]['DbgName'] = m
  715. mtl[m]['DbgIndex'] = index
  716. mtl[m]['DbgColor'] = generate_color(index)
  717. if BAKE_COLORS:
  718. mtl[m]['vertexColors'] = "face"
  719. mtl_raw = ",\n".join(['\t"%s" : %s' % (n, value2string(v)) for n,v in sorted(mtl[m].items())])
  720. mtl_string = "\t{\n%s\n\t}" % mtl_raw
  721. mtl_array.append([index, mtl_string])
  722. return ",\n\n".join([m for i,m in sorted(mtl_array)])
  723. def generate_mtl(materials):
  724. """Generate dummy materials (if there is no MTL file).
  725. """
  726. mtl = {}
  727. for m in materials:
  728. index = materials[m]
  729. mtl[m] = {
  730. 'DbgName': m,
  731. 'DbgIndex': index,
  732. 'DbgColor': generate_color(index)
  733. }
  734. return mtl
  735. def generate_materials_string(materials, mtlfilename, basename):
  736. """Generate final materials string.
  737. """
  738. if not materials:
  739. materials = { 'default': 0 }
  740. mtl = create_materials(materials, mtlfilename, basename)
  741. return generate_materials(mtl, materials)
  742. def create_materials(materials, mtlfilename, basename):
  743. """Parse MTL file and create mapping between its materials and OBJ materials.
  744. Eventual edge cases are handled here (missing materials, missing MTL file).
  745. """
  746. random.seed(42) # to get well defined color order for debug colors
  747. # default materials with debug colors for when
  748. # there is no specified MTL / MTL loading failed,
  749. # or if there were no materials / null materials
  750. mtl = generate_mtl(materials)
  751. if mtlfilename:
  752. # create full pathname for MTL (included from OBJ)
  753. path = os.path.dirname(basename)
  754. fname = os.path.join(path, mtlfilename)
  755. if file_exists(fname):
  756. # override default materials with real ones from MTL
  757. # (where they exist, otherwise keep defaults)
  758. mtl.update(parse_mtl(fname))
  759. else:
  760. print "Couldn't find [%s]" % fname
  761. return mtl
  762. # #####################################################
  763. # Faces
  764. # #####################################################
  765. def is_triangle_flat(f):
  766. return len(f['vertex'])==3 and not (f["normal"] and SHADING == "smooth") and not f['uv']
  767. def is_triangle_flat_uv(f):
  768. return len(f['vertex'])==3 and not (f["normal"] and SHADING == "smooth") and len(f['uv'])==3
  769. def is_triangle_smooth(f):
  770. return len(f['vertex'])==3 and f["normal"] and SHADING == "smooth" and not f['uv']
  771. def is_triangle_smooth_uv(f):
  772. return len(f['vertex'])==3 and f["normal"] and SHADING == "smooth" and len(f['uv'])==3
  773. def is_quad_flat(f):
  774. return len(f['vertex'])==4 and not (f["normal"] and SHADING == "smooth") and not f['uv']
  775. def is_quad_flat_uv(f):
  776. return len(f['vertex'])==4 and not (f["normal"] and SHADING == "smooth") and len(f['uv'])==4
  777. def is_quad_smooth(f):
  778. return len(f['vertex'])==4 and f["normal"] and SHADING == "smooth" and not f['uv']
  779. def is_quad_smooth_uv(f):
  780. return len(f['vertex'])==4 and f["normal"] and SHADING == "smooth" and len(f['uv'])==4
  781. def sort_faces(faces):
  782. data = {
  783. 'triangles_flat': [],
  784. 'triangles_flat_uv': [],
  785. 'triangles_smooth': [],
  786. 'triangles_smooth_uv': [],
  787. 'quads_flat': [],
  788. 'quads_flat_uv': [],
  789. 'quads_smooth': [],
  790. 'quads_smooth_uv': []
  791. }
  792. for f in faces:
  793. if is_triangle_flat(f):
  794. data['triangles_flat'].append(f)
  795. elif is_triangle_flat_uv(f):
  796. data['triangles_flat_uv'].append(f)
  797. elif is_triangle_smooth(f):
  798. data['triangles_smooth'].append(f)
  799. elif is_triangle_smooth_uv(f):
  800. data['triangles_smooth_uv'].append(f)
  801. elif is_quad_flat(f):
  802. data['quads_flat'].append(f)
  803. elif is_quad_flat_uv(f):
  804. data['quads_flat_uv'].append(f)
  805. elif is_quad_smooth(f):
  806. data['quads_smooth'].append(f)
  807. elif is_quad_smooth_uv(f):
  808. data['quads_smooth_uv'].append(f)
  809. return data
  810. # #####################################################
  811. # API - ASCII converter
  812. # #####################################################
  813. def convert_ascii(infile, morphfiles, colorfiles, outfile):
  814. """Convert infile.obj to outfile.js
  815. Here is where everything happens. If you need to automate conversions,
  816. just import this file as Python module and call this method.
  817. """
  818. if not file_exists(infile):
  819. print "Couldn't find [%s]" % infile
  820. return
  821. # parse OBJ / MTL files
  822. faces, vertices, uvs, normals, materials, mtllib = parse_obj(infile)
  823. n_vertices = len(vertices)
  824. n_faces = len(faces)
  825. # align model
  826. if ALIGN == "center":
  827. center(vertices)
  828. elif ALIGN == "centerxz":
  829. centerxz(vertices)
  830. elif ALIGN == "bottom":
  831. bottom(vertices)
  832. elif ALIGN == "top":
  833. top(vertices)
  834. # generate normals string
  835. nnormal = 0
  836. normals_string = ""
  837. if SHADING == "smooth":
  838. normals_string = ",".join(generate_normal(n) for n in normals)
  839. nnormal = len(normals)
  840. # extract morph vertices
  841. morphTargets = generate_morph_targets(morphfiles, n_vertices, infile)
  842. # extract morph colors
  843. morphColors, colorFaces, materialColors = generate_morph_colors(colorfiles, n_vertices, n_faces)
  844. # generate colors string
  845. ncolor = 0
  846. colors_string = ""
  847. if len(colorFaces) < len(faces):
  848. colorFaces = faces
  849. materialColors = extract_material_colors(materials, mtllib, infile)
  850. if BAKE_COLORS:
  851. colors_string = ",".join(generate_color_decimal(c) for c in materialColors)
  852. ncolor = len(materialColors)
  853. # generate edges string
  854. nedge = 0
  855. edges_string = ""
  856. if EXPORT_EDGES:
  857. edges = compute_edges(faces, vertices)
  858. nedge = len(edges)
  859. edges_string = ",".join(generate_edge(e) for e in edges)
  860. # generate ascii model string
  861. text = TEMPLATE_FILE_ASCII % {
  862. "name" : get_name(outfile),
  863. "fname" : infile,
  864. "nvertex" : len(vertices),
  865. "nface" : len(faces),
  866. "nuv" : len(uvs),
  867. "nnormal" : nnormal,
  868. "ncolor" : ncolor,
  869. "nmaterial" : len(materials),
  870. "nedge" : nedge,
  871. "materials" : generate_materials_string(materials, mtllib, infile),
  872. "normals" : normals_string,
  873. "colors" : colors_string,
  874. "uvs" : ",".join(generate_uv(uv) for uv in uvs),
  875. "vertices" : ",".join(generate_vertex(v, TRUNCATE, SCALE) for v in vertices),
  876. "morphTargets" : morphTargets,
  877. "morphColors" : morphColors,
  878. "faces" : ",".join(generate_face(f, fc) for f, fc in zip(faces, colorFaces)),
  879. "edges" : edges_string,
  880. "scale" : SCALE
  881. }
  882. out = open(outfile, "w")
  883. out.write(text)
  884. out.close()
  885. print "%d vertices, %d faces, %d materials" % (len(vertices), len(faces), len(materials))
  886. # #############################################################################
  887. # API - Binary converter
  888. # #############################################################################
  889. def convert_binary(infile, outfile):
  890. """Convert infile.obj to outfile.js + outfile.bin
  891. """
  892. if not file_exists(infile):
  893. print "Couldn't find [%s]" % infile
  894. return
  895. binfile = get_name(outfile) + ".bin"
  896. faces, vertices, uvs, normals, materials, mtllib = parse_obj(infile)
  897. if ALIGN == "center":
  898. center(vertices)
  899. elif ALIGN == "centerxz":
  900. centerxz(vertices)
  901. elif ALIGN == "bottom":
  902. bottom(vertices)
  903. elif ALIGN == "top":
  904. top(vertices)
  905. sfaces = sort_faces(faces)
  906. # ###################
  907. # generate JS file
  908. # ###################
  909. text = TEMPLATE_FILE_BIN % {
  910. "name" : get_name(outfile),
  911. "materials" : generate_materials_string(materials, mtllib, infile),
  912. "buffers" : binfile,
  913. "fname" : infile,
  914. "nvertex" : len(vertices),
  915. "nface" : len(faces),
  916. "nmaterial" : len(materials)
  917. }
  918. out = open(outfile, "w")
  919. out.write(text)
  920. out.close()
  921. # ###################
  922. # generate BIN file
  923. # ###################
  924. if SHADING == "smooth":
  925. nnormals = len(normals)
  926. else:
  927. nnormals = 0
  928. buffer = []
  929. # header
  930. # ------
  931. header_bytes = struct.calcsize('<8s')
  932. header_bytes += struct.calcsize('<BBBBBBBB')
  933. header_bytes += struct.calcsize('<IIIIIIIIIII')
  934. # signature
  935. signature = struct.pack('<8s', 'Three.js')
  936. # metadata (all data is little-endian)
  937. vertex_coordinate_bytes = 4
  938. normal_coordinate_bytes = 1
  939. uv_coordinate_bytes = 4
  940. vertex_index_bytes = 4
  941. normal_index_bytes = 4
  942. uv_index_bytes = 4
  943. material_index_bytes = 2
  944. # header_bytes unsigned char 1
  945. # vertex_coordinate_bytes unsigned char 1
  946. # normal_coordinate_bytes unsigned char 1
  947. # uv_coordinate_bytes unsigned char 1
  948. # vertex_index_bytes unsigned char 1
  949. # normal_index_bytes unsigned char 1
  950. # uv_index_bytes unsigned char 1
  951. # material_index_bytes unsigned char 1
  952. bdata = struct.pack('<BBBBBBBB', header_bytes,
  953. vertex_coordinate_bytes,
  954. normal_coordinate_bytes,
  955. uv_coordinate_bytes,
  956. vertex_index_bytes,
  957. normal_index_bytes,
  958. uv_index_bytes,
  959. material_index_bytes)
  960. # nvertices unsigned int 4
  961. # nnormals unsigned int 4
  962. # nuvs unsigned int 4
  963. # ntri_flat unsigned int 4
  964. # ntri_smooth unsigned int 4
  965. # ntri_flat_uv unsigned int 4
  966. # ntri_smooth_uv unsigned int 4
  967. # nquad_flat unsigned int 4
  968. # nquad_smooth unsigned int 4
  969. # nquad_flat_uv unsigned int 4
  970. # nquad_smooth_uv unsigned int 4
  971. ndata = struct.pack('<IIIIIIIIIII', len(vertices),
  972. nnormals,
  973. len(uvs),
  974. len(sfaces['triangles_flat']),
  975. len(sfaces['triangles_smooth']),
  976. len(sfaces['triangles_flat_uv']),
  977. len(sfaces['triangles_smooth_uv']),
  978. len(sfaces['quads_flat']),
  979. len(sfaces['quads_smooth']),
  980. len(sfaces['quads_flat_uv']),
  981. len(sfaces['quads_smooth_uv']))
  982. buffer.append(signature)
  983. buffer.append(bdata)
  984. buffer.append(ndata)
  985. # 1. vertices
  986. # ------------
  987. # x float 4
  988. # y float 4
  989. # z float 4
  990. for v in vertices:
  991. data = struct.pack('<fff', v[0], v[1], v[2])
  992. buffer.append(data)
  993. # 2. normals
  994. # ---------------
  995. # x signed char 1
  996. # y signed char 1
  997. # z signed char 1
  998. if SHADING == "smooth":
  999. for n in normals:
  1000. normalize(n)
  1001. data = struct.pack('<bbb', math.floor(n[0]*127+0.5),
  1002. math.floor(n[1]*127+0.5),
  1003. math.floor(n[2]*127+0.5))
  1004. buffer.append(data)
  1005. # 3. uvs
  1006. # -----------
  1007. # u float 4
  1008. # v float 4
  1009. for uv in uvs:
  1010. data = struct.pack('<ff', uv[0], 1.0-uv[1])
  1011. buffer.append(data)
  1012. # 4. flat triangles
  1013. # ------------------
  1014. # a unsigned int 4
  1015. # b unsigned int 4
  1016. # c unsigned int 4
  1017. # m unsigned short 2
  1018. for f in sfaces['triangles_flat']:
  1019. vi = f['vertex']
  1020. data = struct.pack('<IIIH',
  1021. vi[0]-1, vi[1]-1, vi[2]-1,
  1022. f['material'])
  1023. buffer.append(data)
  1024. # 5. smooth triangles
  1025. # -------------------
  1026. # a unsigned int 4
  1027. # b unsigned int 4
  1028. # c unsigned int 4
  1029. # m unsigned short 2
  1030. # na unsigned int 4
  1031. # nb unsigned int 4
  1032. # nc unsigned int 4
  1033. for f in sfaces['triangles_smooth']:
  1034. vi = f['vertex']
  1035. ni = f['normal']
  1036. data = struct.pack('<IIIHIII',
  1037. vi[0]-1, vi[1]-1, vi[2]-1,
  1038. f['material'],
  1039. ni[0]-1, ni[1]-1, ni[2]-1)
  1040. buffer.append(data)
  1041. # 6. flat triangles uv
  1042. # --------------------
  1043. # a unsigned int 4
  1044. # b unsigned int 4
  1045. # c unsigned int 4
  1046. # m unsigned short 2
  1047. # ua unsigned int 4
  1048. # ub unsigned int 4
  1049. # uc unsigned int 4
  1050. for f in sfaces['triangles_flat_uv']:
  1051. vi = f['vertex']
  1052. ui = f['uv']
  1053. data = struct.pack('<IIIHIII',
  1054. vi[0]-1, vi[1]-1, vi[2]-1,
  1055. f['material'],
  1056. ui[0]-1, ui[1]-1, ui[2]-1)
  1057. buffer.append(data)
  1058. # 7. smooth triangles uv
  1059. # ----------------------
  1060. # a unsigned int 4
  1061. # b unsigned int 4
  1062. # c unsigned int 4
  1063. # m unsigned short 2
  1064. # na unsigned int 4
  1065. # nb unsigned int 4
  1066. # nc unsigned int 4
  1067. # ua unsigned int 4
  1068. # ub unsigned int 4
  1069. # uc unsigned int 4
  1070. for f in sfaces['triangles_smooth_uv']:
  1071. vi = f['vertex']
  1072. ni = f['normal']
  1073. ui = f['uv']
  1074. data = struct.pack('<IIIHIIIIII',
  1075. vi[0]-1, vi[1]-1, vi[2]-1,
  1076. f['material'],
  1077. ni[0]-1, ni[1]-1, ni[2]-1,
  1078. ui[0]-1, ui[1]-1, ui[2]-1)
  1079. buffer.append(data)
  1080. # 8. flat quads
  1081. # ------------------
  1082. # a unsigned int 4
  1083. # b unsigned int 4
  1084. # c unsigned int 4
  1085. # d unsigned int 4
  1086. # m unsigned short 2
  1087. for f in sfaces['quads_flat']:
  1088. vi = f['vertex']
  1089. data = struct.pack('<IIIIH',
  1090. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  1091. f['material'])
  1092. buffer.append(data)
  1093. # 9. smooth quads
  1094. # -------------------
  1095. # a unsigned int 4
  1096. # b unsigned int 4
  1097. # c unsigned int 4
  1098. # d unsigned int 4
  1099. # m unsigned short 2
  1100. # na unsigned int 4
  1101. # nb unsigned int 4
  1102. # nc unsigned int 4
  1103. # nd unsigned int 4
  1104. for f in sfaces['quads_smooth']:
  1105. vi = f['vertex']
  1106. ni = f['normal']
  1107. data = struct.pack('<IIIIHIIII',
  1108. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  1109. f['material'],
  1110. ni[0]-1, ni[1]-1, ni[2]-1, ni[3]-1)
  1111. buffer.append(data)
  1112. # 10. flat quads uv
  1113. # ------------------
  1114. # a unsigned int 4
  1115. # b unsigned int 4
  1116. # c unsigned int 4
  1117. # d unsigned int 4
  1118. # m unsigned short 2
  1119. # ua unsigned int 4
  1120. # ub unsigned int 4
  1121. # uc unsigned int 4
  1122. # ud unsigned int 4
  1123. for f in sfaces['quads_flat_uv']:
  1124. vi = f['vertex']
  1125. ui = f['uv']
  1126. data = struct.pack('<IIIIHIIII',
  1127. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  1128. f['material'],
  1129. ui[0]-1, ui[1]-1, ui[2]-1, ui[3]-1)
  1130. buffer.append(data)
  1131. # 11. smooth quads uv
  1132. # -------------------
  1133. # a unsigned int 4
  1134. # b unsigned int 4
  1135. # c unsigned int 4
  1136. # d unsigned int 4
  1137. # m unsigned short 2
  1138. # na unsigned int 4
  1139. # nb unsigned int 4
  1140. # nc unsigned int 4
  1141. # nd unsigned int 4
  1142. # ua unsigned int 4
  1143. # ub unsigned int 4
  1144. # uc unsigned int 4
  1145. # ud unsigned int 4
  1146. for f in sfaces['quads_smooth_uv']:
  1147. vi = f['vertex']
  1148. ni = f['normal']
  1149. ui = f['uv']
  1150. data = struct.pack('<IIIIHIIIIIIII',
  1151. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  1152. f['material'],
  1153. ni[0]-1, ni[1]-1, ni[2]-1, ni[3]-1,
  1154. ui[0]-1, ui[1]-1, ui[2]-1, ui[3]-1)
  1155. buffer.append(data)
  1156. path = os.path.dirname(outfile)
  1157. fname = os.path.join(path, binfile)
  1158. out = open(fname, "wb")
  1159. out.write("".join(buffer))
  1160. out.close()
  1161. # #############################################################################
  1162. # Helpers
  1163. # #############################################################################
  1164. def usage():
  1165. print "Usage: %s -i filename.obj -o filename.js [-m morphfiles*.obj] [-c morphcolors*.obj] [-a center|top|bottom] [-s flat|smooth] [-t binary|ascii] [-d invert|normal]" % os.path.basename(sys.argv[0])
  1166. # #####################################################
  1167. # Main
  1168. # #####################################################
  1169. if __name__ == "__main__":
  1170. # get parameters from the command line
  1171. try:
  1172. opts, args = getopt.getopt(sys.argv[1:], "hbei:m:c:b:o:a:s:t:d:x:", ["help", "bakecolors", "edges", "input=", "morphs=", "colors=", "output=", "align=", "shading=", "type=", "dissolve=", "truncatescale="])
  1173. except getopt.GetoptError:
  1174. usage()
  1175. sys.exit(2)
  1176. infile = outfile = ""
  1177. morphfiles = ""
  1178. colorfiles = ""
  1179. for o, a in opts:
  1180. if o in ("-h", "--help"):
  1181. usage()
  1182. sys.exit()
  1183. elif o in ("-i", "--input"):
  1184. infile = a
  1185. elif o in ("-m", "--morphs"):
  1186. morphfiles = a
  1187. elif o in ("-c", "--colors"):
  1188. colorfiles = a
  1189. elif o in ("-o", "--output"):
  1190. outfile = a
  1191. elif o in ("-a", "--align"):
  1192. if a in ("top", "bottom", "center", "centerxz", "none"):
  1193. ALIGN = a
  1194. elif o in ("-s", "--shading"):
  1195. if a in ("flat", "smooth"):
  1196. SHADING = a
  1197. elif o in ("-t", "--type"):
  1198. if a in ("binary", "ascii"):
  1199. TYPE = a
  1200. elif o in ("-d", "--dissolve"):
  1201. if a in ("normal", "invert"):
  1202. TRANSPARENCY = a
  1203. elif o in ("-b", "--bakecolors"):
  1204. BAKE_COLORS = True
  1205. elif o in ("-e", "--edges"):
  1206. EXPORT_EDGES = True
  1207. elif o in ("-x", "--truncatescale"):
  1208. TRUNCATE = True
  1209. SCALE = float(a)
  1210. if infile == "" or outfile == "":
  1211. usage()
  1212. sys.exit(2)
  1213. print "Converting [%s] into [%s] ..." % (infile, outfile)
  1214. if morphfiles:
  1215. print "Morphs [%s]" % morphfiles
  1216. if colorfiles:
  1217. print "Colors [%s]" % colorfiles
  1218. if TYPE == "ascii":
  1219. convert_ascii(infile, morphfiles, colorfiles, outfile)
  1220. elif TYPE == "binary":
  1221. convert_binary(infile, outfile)