convert_obj_three.py 46 KB

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