import bpy
import os

bl_info = {
        "name": "Funnymap export",
        "author": "kotofyt",
        "version": (1, 0),
        "blender": (4, 3, 0),
        "location": "File > Export > Funnymap (.map)",
        "description": "Export meshes as funnymaps",
        "category": "Import-Export",
        }


import bpy
import os
from bpy_extras.io_utils import ExportHelper
from bpy.types import Operator
from bpy.props import StringProperty

class ExportFunnymap(Operator, ExportHelper):
    """Export to Funnymap"""
    bl_idname = "export_scene.fmap"
    bl_label = "Export Funnymap"
    filename_ext = ".map"

    filter_glob: StringProperty(
            default="*.map",
            options={'HIDDEN'},
            )

    def execute(self, context):
        return export_my_format(self.filepath)

def export_my_format(filepath):
    with open(filepath, 'w') as f:
        f.write("{\n")
        f.write("\"classname\" \"worldspawn\"\n")
        f.write("{\n")

        for obj in bpy.context.scene.objects:
            if obj.type == 'MESH':
                mesh = obj.to_mesh()
                mesh.calc_loop_triangles()
                uv_layer = mesh.uv_layers.active.data if mesh.uv_layers.active else None
                for tri in mesh.loop_triangles:
                    for loop_index in tri.loops:
                        vert = mesh.vertices[mesh.loops[loop_index].vertex_index]
                        world_pos = obj.matrix_world @ vert.co
                        f.write(f"({world_pos.x:.6f} {world_pos.y:.6f} {world_pos.z:.6f}) ")
                    for loop_index in tri.loops:
                        if uv_layer:
                            uv = uv_layer[loop_index].uv
                            f.write(f"({uv.x:.6f} {uv.y:.6f}) ")
                    f.write(f"BRICK1\n");
        f.write("}\n")
        f.write("}\n")
        for obj in bpy.context.scene.objects:
            if obj.type == 'LIGHT':
                light = obj.data
                f.write("{\n")
                f.write("\"classname\" \"light\"\n")
                f.write(f"\"intensity\" \"{light.energy/128}\"\n")
                f.write("}\n")

    return {'FINISHED'}

def menu_func_export(self, context):
    self.layout.operator(ExportFunnymap.bl_idname, text="Funnymap (.map)")

def register():
    bpy.utils.register_class(ExportFunnymap)
    bpy.types.TOPBAR_MT_file_export.append(menu_func_export)

def unregister():
    bpy.utils.unregister_class(ExportFunnymap)
    bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)

if __name__ == "__main__":
    register()
