convert_obj_three.py 47 KB

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