convert_obj_three.py 47 KB

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