convert_obj_three.py 47 KB

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