convert_obj_three.py 46 KB

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