convert_obj_three.py 44 KB

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