convert_obj_three.py 47 KB

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