export_map.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. # ##### BEGIN GPL LICENSE BLOCK #####
  2. #
  3. # This program is free software; you can redistribute it and/or
  4. # modify it under the terms of the GNU General Public License
  5. # as published by the Free Software Foundation; either version 2
  6. # of the License, or (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software Foundation,
  15. # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. #
  17. # ##### END GPL LICENSE BLOCK #####
  18. # <pep8-80 compliant>
  19. import bpy
  20. import os
  21. # TODO, make options
  22. PREF_SCALE = 100
  23. PREF_FACE_THICK = 0.1
  24. PREF_GRID_SNAP = False
  25. # Quake 1/2?
  26. # Quake 3+?
  27. PREF_DEF_TEX_OPTS = '0 0 0 1 1 0 0 0' # not user settable yet
  28. PREF_NULL_TEX = 'NULL' # not user settable yet
  29. PREF_INVIS_TEX = 'common/caulk'
  30. def face_uv_get(face):
  31. """ Workaround 2.5x change.
  32. """
  33. me = face.id_data
  34. uv_faces = me.uv_textures.active
  35. if uv_faces:
  36. return uv_faces.data[face.index]
  37. else:
  38. return None
  39. def face_material_get(face):
  40. me = face.id_data
  41. try:
  42. return me.materials[face.material_index]
  43. except:
  44. return None
  45. def write_cube2brush(file, faces):
  46. """
  47. Takes 6 faces and writes a brush,
  48. these faces can be from 1 mesh, 1 cube within a mesh of larger cubes
  49. Faces could even come from different meshes or be contrived.
  50. """
  51. # comment only
  52. # file.write('// brush "%s", "%s"\n' % (ob.name, ob.data.name))
  53. file.write('// brush from cube\n{\n')
  54. if PREF_GRID_SNAP:
  55. format_vec = '( %d %d %d ) '
  56. else:
  57. format_vec = '( %.8f %.8f %.8f ) '
  58. for f in faces:
  59. # from 4 verts this gets them in reversed order and only 3 of them
  60. # 0,1,2,3 -> 2,1,0
  61. me = f.id_data # XXX25
  62. for v in f.vertices[:][2::-1]:
  63. file.write(format_vec % me.vertices[v].co[:])
  64. material = face_material_get(f)
  65. if material and material.game_settings.invisible:
  66. file.write(PREF_INVIS_TEX)
  67. else:
  68. uf = face_uv_get(f)
  69. image = uf.image if uf else None
  70. if image:
  71. file.write(os.path.splitext(
  72. bpy.path.basename(image.filepath))[0])
  73. else:
  74. file.write(PREF_NULL_TEX)
  75. # Texture stuff ignored for now
  76. file.write(" %s\n" % PREF_DEF_TEX_OPTS)
  77. file.write('}\n')
  78. def round_vec(v):
  79. if PREF_GRID_SNAP:
  80. return v.to_tuple(0)
  81. else:
  82. return v[:]
  83. def write_face2brush(file, face):
  84. """
  85. takes a face and writes it as a brush
  86. each face is a cube/brush
  87. """
  88. if PREF_GRID_SNAP:
  89. format_vec = '( %d %d %d ) '
  90. else:
  91. format_vec = '( %.8f %.8f %.8f ) '
  92. image_text = PREF_NULL_TEX
  93. material = face_material_get(face)
  94. if material and material.game_settings.invisible:
  95. image_text = PREF_INVIS_TEX
  96. else:
  97. uf = face_uv_get(face)
  98. image = uf.image if uf else None
  99. if image:
  100. image_text = os.path.splitext(bpy.path.basename(image.filepath))[0]
  101. # reuse face vertices
  102. _v = face.id_data.vertices # XXX25
  103. f_vertices = [_v[vi] for vi in face.vertices]
  104. del _v # XXX25
  105. # original verts as tuples for writing
  106. orig_vco = [v.co[:] for v in f_vertices]
  107. # new verts that give the face a thickness
  108. dist = PREF_SCALE * PREF_FACE_THICK
  109. new_vco = [round_vec(v.co - (v.normal * dist)) for v in f_vertices]
  110. #new_vco = [round_vec(v.co - (face.no * dist)) for v in face]
  111. file.write('// brush from face\n{\n')
  112. # front
  113. for co in orig_vco[2::-1]:
  114. file.write(format_vec % co)
  115. file.write(image_text)
  116. # Texture stuff ignored for now
  117. file.write(" %s\n" % PREF_DEF_TEX_OPTS)
  118. for co in new_vco[:3]:
  119. file.write(format_vec % co)
  120. if uf and uf.use_twoside:
  121. file.write(image_text)
  122. else:
  123. file.write(PREF_INVIS_TEX)
  124. # Texture stuff ignored for now
  125. file.write(" %s\n" % PREF_DEF_TEX_OPTS)
  126. # sides.
  127. if len(orig_vco) == 3: # Tri, it seemms tri brushes are supported.
  128. index_pairs = ((0, 1), (1, 2), (2, 0))
  129. else:
  130. index_pairs = ((0, 1), (1, 2), (2, 3), (3, 0))
  131. for i1, i2 in index_pairs:
  132. for co in orig_vco[i1], orig_vco[i2], new_vco[i2]:
  133. file.write(format_vec % co)
  134. file.write(PREF_INVIS_TEX)
  135. file.write(" %s\n" % PREF_DEF_TEX_OPTS)
  136. file.write('}\n')
  137. def is_cube_facegroup(faces):
  138. """
  139. Returns a bool, true if the faces make up a cube
  140. """
  141. # cube must have 6 faces
  142. if len(faces) != 6:
  143. # print('1')
  144. return False
  145. # Check for quads and that there are 6 unique verts
  146. verts = {}
  147. for f in faces:
  148. f_v = f.vertices[:]
  149. if len(f_v) != 4:
  150. return False
  151. for v in f_v:
  152. verts[v] = 0
  153. if len(verts) != 8:
  154. return False
  155. # Now check that each vert has 3 face users
  156. for f in faces:
  157. f_v = f.vertices[:]
  158. for v in f_v:
  159. verts[v] += 1
  160. for v in verts.values():
  161. if v != 3: # vert has 3 users?
  162. return False
  163. # Could we check for 12 unique edges??, probably not needed.
  164. return True
  165. def is_tricyl_facegroup(faces):
  166. """
  167. is the face group a tri cylinder
  168. Returns a bool, true if the faces make an extruded tri solid
  169. """
  170. # cube must have 5 faces
  171. if len(faces) != 5:
  172. # print('1')
  173. return False
  174. # Check for quads and that there are 6 unique verts
  175. verts = {}
  176. tottri = 0
  177. for f in faces:
  178. if len(f.vertices) == 3:
  179. tottri += 1
  180. for vi in f.vertices:
  181. verts[vi] = 0
  182. if len(verts) != 6 or tottri != 2:
  183. return False
  184. # Now check that each vert has 3 face users
  185. for f in faces:
  186. for vi in f.vertices:
  187. verts[vi] += 1
  188. for v in verts.values():
  189. if v != 3: # vert has 3 users?
  190. return False
  191. # Could we check for 12 unique edges??, probably not needed.
  192. return True
  193. def write_node_map(file, ob):
  194. """
  195. Writes the properties of an object (empty in this case)
  196. as a MAP node as long as it has the property name - classname
  197. returns True/False based on weather a node was written
  198. """
  199. props = [(p.name, p.value) for p in ob.game.properties]
  200. IS_MAP_NODE = False
  201. for name, value in props:
  202. if name == "classname":
  203. IS_MAP_NODE = True
  204. break
  205. if not IS_MAP_NODE:
  206. return False
  207. # Write a node
  208. file.write('{\n')
  209. for name_value in props:
  210. file.write('"%s" "%s"\n' % name_value)
  211. if PREF_GRID_SNAP:
  212. file.write('"origin" "%d %d %d"\n' %
  213. tuple([round(axis * PREF_SCALE)
  214. for axis in ob.matrix_world.to_translation()]))
  215. else:
  216. file.write('"origin" "%.6f %.6f %.6f"\n' %
  217. tuple([axis * PREF_SCALE
  218. for axis in ob.matrix_world.to_translation()]))
  219. file.write('}\n')
  220. return True
  221. def export_map(context, filepath):
  222. """
  223. pup_block = [\
  224. ('Scale:', PREF_SCALE, 1, 1000,
  225. 'Scale the blender scene by this value.'),\
  226. ('Face Width:', PREF_FACE_THICK, 0.01, 10,
  227. 'Thickness of faces exported as brushes.'),\
  228. ('Grid Snap', PREF_GRID_SNAP,
  229. 'snaps floating point values to whole numbers.'),\
  230. 'Null Texture',\
  231. ('', PREF_NULL_TEX, 1, 128,
  232. 'Export textureless faces with this texture'),\
  233. 'Unseen Texture',\
  234. ('', PREF_INVIS_TEX, 1, 128,
  235. 'Export invisible faces with this texture'),\
  236. ]
  237. if not Draw.PupBlock('map export', pup_block):
  238. return
  239. """
  240. import time
  241. from mathutils import Matrix
  242. from bpy_extras import mesh_utils
  243. t = time.time()
  244. print("Map Exporter 0.0")
  245. file = open(filepath, 'w')
  246. scene = context.scene
  247. objects = context.selected_objects
  248. obs_mesh = []
  249. obs_lamp = []
  250. obs_surf = []
  251. obs_empty = []
  252. SCALE_MAT = Matrix()
  253. SCALE_MAT[0][0] = SCALE_MAT[1][1] = SCALE_MAT[2][2] = PREF_SCALE
  254. TOTBRUSH = TOTLAMP = TOTNODE = 0
  255. for ob in objects:
  256. type = ob.type
  257. if type == 'MESH':
  258. obs_mesh.append(ob)
  259. elif type == 'SURFACE':
  260. obs_surf.append(ob)
  261. elif type == 'LAMP':
  262. obs_lamp.append(ob)
  263. elif type == 'EMPTY':
  264. obs_empty.append(ob)
  265. if obs_mesh or obs_surf:
  266. # brushes and surf's must be under worldspan
  267. file.write('\n// entity 0\n')
  268. file.write('{\n')
  269. file.write('"classname" "worldspawn"\n')
  270. print("\twriting cubes from meshes")
  271. for ob in obs_mesh:
  272. dummy_mesh = ob.to_mesh(scene, True, 'PREVIEW')
  273. #print len(mesh_split2connected(dummy_mesh))
  274. # Is the object 1 cube? - object-is-a-brush
  275. # 1 to tx the normals also
  276. dummy_mesh.transform(ob.matrix_world * SCALE_MAT)
  277. if PREF_GRID_SNAP:
  278. for v in dummy_mesh.vertices:
  279. v.co[:] = v.co.to_tuple(0)
  280. # High quality normals
  281. #XXX25: BPyMesh.meshCalcNormals(dummy_mesh)
  282. # We need tessfaces
  283. dummy_mesh.update(calc_tessface=True)
  284. # Split mesh into connected regions
  285. for face_group in mesh_utils.mesh_linked_tessfaces(dummy_mesh):
  286. if is_cube_facegroup(face_group):
  287. write_cube2brush(file, face_group)
  288. TOTBRUSH += 1
  289. elif is_tricyl_facegroup(face_group):
  290. write_cube2brush(file, face_group)
  291. TOTBRUSH += 1
  292. else:
  293. for f in face_group:
  294. write_face2brush(file, f)
  295. TOTBRUSH += 1
  296. #print 'warning, not exporting "%s" it is not a cube' % ob.name
  297. bpy.data.meshes.remove(dummy_mesh)
  298. valid_dims = 3, 5, 7, 9, 11, 13, 15
  299. for ob in obs_surf:
  300. '''
  301. Surf, patches
  302. '''
  303. data = ob.data
  304. surf_name = data.name
  305. mat = ob.matrix_world * SCALE_MAT
  306. # This is what a valid patch looks like
  307. """
  308. // brush 0
  309. {
  310. patchDef2
  311. {
  312. NULL
  313. ( 3 3 0 0 0 )
  314. (
  315. ( ( -64 -64 0 0 0 ) ( -64 0 0 0 -2 ) ( -64 64 0 0 -4 ) )
  316. ( ( 0 -64 0 2 0 ) ( 0 0 0 2 -2 ) ( 0 64 0 2 -4 ) )
  317. ( ( 64 -64 0 4 0 ) ( 64 0 0 4 -2 ) ( 80 88 0 4 -4 ) )
  318. )
  319. }
  320. }
  321. """
  322. for i, nurb in enumerate(data.splines):
  323. u = nurb.point_count_u
  324. v = nurb.point_count_v
  325. if u in valid_dims and v in valid_dims:
  326. file.write('// brush %d surf_name\n' % i)
  327. file.write('{\n')
  328. file.write('patchDef2\n')
  329. file.write('{\n')
  330. file.write('NULL\n')
  331. file.write('( %d %d 0 0 0 )\n' % (u, v))
  332. file.write('(\n')
  333. u_iter = 0
  334. for p in nurb.points:
  335. if u_iter == 0:
  336. file.write('(')
  337. u_iter += 1
  338. # add nmapping 0 0 ?
  339. if PREF_GRID_SNAP:
  340. file.write(" ( %d %d %d 0 0 )" %
  341. round_vec(mat * p.co.xyz))
  342. else:
  343. file.write(' ( %.6f %.6f %.6f 0 0 )' %
  344. (mat * p.co.xyz)[:])
  345. # Move to next line
  346. if u_iter == u:
  347. file.write(' )\n')
  348. u_iter = 0
  349. file.write(')\n')
  350. file.write('}\n')
  351. file.write('}\n')
  352. # Debugging
  353. # for p in nurb: print 'patch', p
  354. else:
  355. print("Warning: not exporting patch",
  356. surf_name, u, v, 'Unsupported')
  357. if obs_mesh or obs_surf:
  358. file.write('}\n') # end worldspan
  359. print("\twriting lamps")
  360. for ob in obs_lamp:
  361. print("\t\t%s" % ob.name)
  362. lamp = ob.data
  363. file.write('{\n')
  364. file.write('"classname" "light"\n')
  365. file.write('"light" "%.6f"\n' % (lamp.distance * PREF_SCALE))
  366. if PREF_GRID_SNAP:
  367. file.write('"origin" "%d %d %d"\n' %
  368. tuple([round(axis * PREF_SCALE)
  369. for axis in ob.matrix_world.to_translation()]))
  370. else:
  371. file.write('"origin" "%.6f %.6f %.6f"\n' %
  372. tuple([axis * PREF_SCALE
  373. for axis in ob.matrix_world.to_translation()]))
  374. file.write('"_color" "%.6f %.6f %.6f"\n' % tuple(lamp.color))
  375. file.write('"style" "0"\n')
  376. file.write('}\n')
  377. TOTLAMP += 1
  378. print("\twriting empty objects as nodes")
  379. for ob in obs_empty:
  380. if write_node_map(file, ob):
  381. print("\t\t%s" % ob.name)
  382. TOTNODE += 1
  383. else:
  384. print("\t\tignoring %s" % ob.name)
  385. file.close()
  386. print("Exported Map in %.4fsec" % (time.time() - t))
  387. print("Brushes: %d Nodes: %d Lamps %d\n" % (TOTBRUSH, TOTNODE, TOTLAMP))
  388. def save(operator,
  389. context,
  390. filepath=None,
  391. global_scale=100.0,
  392. face_thickness=0.1,
  393. texture_null="NULL",
  394. texture_opts='0 0 0 1 1 0 0 0',
  395. grid_snap=False,
  396. ):
  397. global PREF_SCALE
  398. global PREF_FACE_THICK
  399. global PREF_NULL_TEX
  400. global PREF_DEF_TEX_OPTS
  401. global PREF_GRID_SNAP
  402. PREF_SCALE = global_scale
  403. PREF_FACE_THICK = face_thickness
  404. PREF_NULL_TEX = texture_null
  405. PREF_DEF_TEX_OPTS = texture_opts
  406. PREF_GRID_SNAP = grid_snap
  407. export_map(context, filepath)
  408. return {'FINISHED'}