import bpy
import math
import os

cameras = [cam for cam in bpy.context.scene.objects if cam.type == 'CAMERA']

basePath = '/Users/jordivallverdu/Documents/panos'
project = '2022_09_apartment'
jsonName = 'project'
objName = 'model'
textureName = 'texture'

# create dirs if necessary
if not os.path.exists('%s/%s/panos' % (basePath, project)):
    os.makedirs('%s/%s/panos' % (basePath, project))

jsonPath = '%s/%s/%s.json' % (basePath, project, jsonName)
objPath = '%s/%s/%s.obj' % (basePath, project, objName)
texturePath = '%s/%s/%s.png' % (basePath, project, textureName)
panoPath = '%s/%s/panos' % (basePath, project)


scene = bpy.context.scene
scene.render.image_settings.file_format = 'JPEG'

# setting render engine
scene.render.engine = 'CYCLES'
scene.cycles.samples = 10

# set the image resolution, you need to keep 2:1 aspect ratio
scene.render.resolution_x = 4000
scene.render.resolution_y = 2000

bpy.ops.export_scene.obj(filepath=objPath, check_existing=True, axis_forward='-Z', axis_up='Y', filter_glob="*.obj;*.mtl", use_selection=False, use_animation=False, use_mesh_modifiers=True, use_edges=True, use_smooth_groups=False, use_smooth_groups_bitflags=False, use_normals=True, use_uvs=True, use_materials=True, use_triangles=False, use_nurbs=False, use_vertex_groups=False, use_blen_objects=True, group_by_object=False, group_by_material=False, keep_vertex_order=False, global_scale=1, path_mode='AUTO')

f = open(jsonPath, 'w', encoding='utf-8')

f.write('{\n')
f.write('"model" :\n')
f.write('[\n')
f.write('{\n')
f.write(' "name": "%s",\n' % (objName))
f.write(' "modelPath": "%s",\n' % (objPath))
f.write(' "texturePath": "%s",\n' % (texturePath))
f.write('"id":0,\n')
f.write('"position":{"x":0.000,"y":0.000,"z":0.000},\n')
f.write('"rotation":{"x":0.000,"y":0.000,"z":0.000},\n')
f.write('"scale":{"x":1.000,"y":1.000,"z":1.000}\n')
f.write('}\n')
f.write('],\n')

f.write('"project": {\n')
f.write('"name": "%s",\n'  % (project))
f.write('"unit_system": "metric",\n')
f.write('"units": "mt",\n')
f.write('"align_panoramas": false\n')
f.write('},\n')

f.write('"panoramas" : \n')
f.write('[\n')

totalCameras = len(cameras)

for index, camera in enumerate(cameras) :
    
    # get location and rotation of the camera
    cam_loc = bpy.data.objects[camera.name].location
    cam_rot = bpy.data.objects[camera.name].rotation_euler

    # set the camera as a panorama
    bpy.data.objects[camera.name].data.type = 'PANO'
    bpy.data.objects[camera.name].data.cycles.panorama_type = 'EQUIRECTANGULAR'
    bpy.data.objects[camera.name].data.cycles.latitude_min = -math.pi
    bpy.data.objects[camera.name].data.cycles.latitude_max = math.pi/2
    bpy.data.objects[camera.name].data.cycles.longitude_min = -math.pi
    bpy.data.objects[camera.name].data.cycles.longitude_max = math.pi

    
    # Render cameraview
    scene.camera = camera
    scene.render.filepath = "%s/%s.jpg" % (panoPath, camera.name)
    # comment if you want to skip render the panorama
    bpy.ops.render.render(write_still=True)


    f.write('{\n')
    f.write(' "name": "%s",\n' % camera.name)
    f.write(' "path": "%s/%s.jpg",\n' % (panoPath, camera.name))
    f.write(' "position" : {"x":%5.3f, "y":%5.3f, "z":%5.3f},\n' % (cam_loc[0],cam_loc[2] , -cam_loc[1]))
    f.write(' "rotation" : {"x":%5.3f, "y":%5.3f, "z":%5.3f}\n' % (cam_rot.x - math.pi/2,cam_rot.y,cam_rot.z + math.pi))
    
    if index == totalCameras - 1 :
        f.write('}\n')
    else :
        f.write('},\n')

f.write(']\n')
f.write('}\n')

f.close()
