# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

bl_info = {
    "name": "Perspective correction",
    "author": "k Lsscpp",
    "version": (1,1),
    "blender": (3, 00, 0),
    "location": "Camera data properties",
    "description": "Adds a Perspective correction button in the sidebar",
    "warning": "",
    "category": "Camera",
}

import bpy
from math import degrees

# ================== Operator ==================

class OP_camrotation_2shift(bpy.types.Operator):
    '''Perspective correction: set camera parallel to the ground 
and shift lenses accordingly to keep the horizon in the same place.
This gives roughly the same shot framing, but with straight vertical lines.'''
    bl_label = "Perspective correction"
    bl_idname = "object.camrotation_2shift"
    bl_options = {'REGISTER', 'UNDO'}

    @classmethod
    def poll(cls, context):
        if len(bpy.context.selected_objects) > 0:
            return bpy.context.active_object.type == "CAMERA"

    def execute(self, context):
        cam = bpy.context.active_object
        cam.data.shift_y += (90-degrees(cam.rotation_euler[0]))*-(cam.data.lens/2000)
        cam.rotation_euler[0] = 1.5708
        return {'FINISHED'}

# ================== Panel ==================

class CAMERA_PT_perspective_correction(bpy.types.Panel):
    bl_label = "Perspective correction"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "data"

    @classmethod
    def poll(cls, context):
        return bpy.context.active_object.type == "CAMERA"
        
    def draw(self, context):
        layout = self.layout
        row = layout.row()
        row.operator("object.camrotation_2shift", text = "Perspective correction", icon ="VIEW_PERSPECTIVE")

# Register

classes = (
    OP_camrotation_2shift,
    CAMERA_PT_perspective_correction,
)

def register():
    for cl in classes:
        bpy.utils.register_class(cl)

def unregister():
    for cl in classes:
        bpy.utils.unregister_class(cl)
