From 64f9fbff414c6f17c2256dcd6c932b5d0c3f1380 Mon Sep 17 00:00:00 2001
From: Ludovic Pouzenc <ludovic@pouzenc.fr>
Date: Mon, 31 Dec 2018 18:41:06 +0100
Subject: Draft improvement

---
 drafts/print_mapfile_to_console.py | 34 ++++++++++++++++++++++++++--------
 1 file changed, 26 insertions(+), 8 deletions(-)

(limited to 'drafts')

diff --git a/drafts/print_mapfile_to_console.py b/drafts/print_mapfile_to_console.py
index 2f5d179..61a92ca 100755
--- a/drafts/print_mapfile_to_console.py
+++ b/drafts/print_mapfile_to_console.py
@@ -1,6 +1,8 @@
 import bpy
+import bmesh
 from mathutils import Vector
 
+# https://developer.valvesoftware.com/wiki/MAP_file_format
 def fmt3(vec3):
     return "%.10f %.10f %.10f"%(vec3.x, vec3.y, vec3.z)
 def fmt_plane(plane3dots):
@@ -24,7 +26,7 @@ def output_brush_start():
     print("\t{")
 
 def output_brush_face(plane3dots, tename, tev1, teoff1, tev2, teoff2, rot, scaleX, scaleY):
-    print("\t%s"%fmt_face(plane3dots, tename, tev1, teoff1, tev2, teoff2, rot, scaleX, scaleY))
+    print("\t\t%s"%fmt_face(plane3dots, tename, tev1, teoff1, tev2, teoff2, rot, scaleX, scaleY))
 
 def output_brush_end():
     print("\t}")
@@ -55,6 +57,7 @@ def debug(fano,plane3dots):
     print(fano-n)
     print()
 
+# https://developer.valvesoftware.com/wiki/MAP_file_format
 worldspawn_props = {
     'classname': 'worldspawn',
     'sounds': 1,
@@ -65,14 +68,29 @@ worldspawn_props = {
 
 blender_to_map_scale_factor = 100
 
-# https://developer.valvesoftware.com/wiki/MAP_file_format
-output_entity_start(worldspawn_props)
 
-for o in bpy.data.scenes[0].objects:
-    if o.type != 'MESH':
-        continue
-    mat_to_map = o.matrix_world * blender_to_map_scale_factor
-    mesh = o.data
+
+scene = bpy.context.scene
+# Simplify each mesh once (a mesh could be used by multiple objects)
+unique_meshes = set([ob.data for ob in scene.objects if ob.type == 'MESH'])
+for mesh in unique_meshes:
+    bm = bmesh.new()
+    bm.from_mesh(mesh)
+    bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.01)
+    bmesh.ops.holes_fill(bm, edges=bm.edges) #, sides=0
+    bmesh.ops.connect_verts_concave(bm, faces=bm.faces)
+    bmesh.ops.connect_verts_nonplanar(bm, faces=bm.faces) #, angle_limit=0.0
+    bmesh.ops.planar_faces(bm, faces=bm.faces)
+    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
+    bm.to_mesh(mesh)
+    bm.free()
+
+# Export each object in .map
+all_objects_with_mesh_type = [ob for ob in scene.objects if ob.type == 'MESH']
+output_entity_start(worldspawn_props)
+for ob in all_objects_with_mesh_type:
+    mat_to_map = ob.matrix_world * blender_to_map_scale_factor
+    mesh = ob.data
     mesh.update(calc_tessface=True)
     for fa in mesh.tessfaces:
         output_brush_start()
-- 
cgit v1.2.3