convert_obj_three.py 46 KB

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