#!/usr/bin/perl
use strict;
use warnings;
use Tk;
use Tk::JPEG;
use Math::Trig qw(deg2rad);

# Parameters
my $input_image   = "sandown_pier001.jpg";
my $start_hfov    = 90;
my $end_hfov      = 150;
my $frames        = 10;
my $output_width  = 1024;
my $yaw           = 0;
my $pitch         = 0;
my $roll          = 0;
my $yaw_shift     = 0;
my $pitch_shift   = 0;
my $output_name   = "frame";

# Main Window
my $mw = MainWindow->new;
$mw->title("Fisheye Zoom Animator");

# Load Image
my $image = $mw->Photo(-file => $input_image);
my $img_width  = $image->width;
my $img_height = $image->height;

# Canvas to preview first frame
my $canvas = $mw->Canvas(-width => $img_width, -height => $img_height)->pack;
$canvas->createImage(0, 0, -image => $image, -anchor => 'nw');

# Controls
$mw->Label(-text => "Start HFOV")->pack;
$mw->Scale(-from => 10, -to => 180, -orient => 'horizontal', -length => 300, -variable => \$start_hfov)->pack;

$mw->Label(-text => "End HFOV")->pack;
$mw->Scale(-from => 10, -to => 180, -orient => 'horizontal', -length => 300, -variable => \$end_hfov)->pack;

$mw->Label(-text => "Frames")->pack;
$mw->Scale(-from => 2, -to => 100, -orient => 'horizontal', -length => 300, -variable => \$frames)->pack;

$mw->Label(-text => "Output Width")->pack;
$mw->Entry(-textvariable => \$output_width)->pack;

$mw->Button(-text => "Generate Animation", -command => \&generate_animation)->pack;

# Output log
my $log = $mw->Scrolled("Text", -width => 60, -height => 10)->pack;

sub calculate_output_height {
    my ($hfov) = @_;
    my $vfov_rad = deg2rad(90); # Assume vertical ~90°, can adjust
    my $hfov_rad = deg2rad($hfov);
    return int($output_width * (tan($vfov_rad/2) / tan($hfov_rad/2)) + 0.5);
}

sub generate_animation {
    $log->delete('1.0', 'end');
    mkdir "./frames" unless -d "./frames";
    for my $i (0 .. $frames-1) {
        my $hfov = $start_hfov + $i/($frames-1) * ($end_hfov - $start_hfov);
        my $output_height = calculate_output_height($hfov);
        my $pto_file = "/tmp/frame_${i}.pto";
        my $output_file = sprintf("./frames/${output_name}_%03d", $i);

        $log->insert('end', "Frame $i: HFOV=$hfov → ${output_width}x${output_height}\n");
        $mw->update;

        # PTO/Nano commands
        system("pto_gen --output=$pto_file $input_image") == 0 or die "pto_gen failed";
        system("pano_modify --output=$pto_file --projection=0 --fov=${hfov}x90 ".
               "--rotate=$yaw,$pitch,$roll --canvas=${output_width}x${output_height} $pto_file") == 0
            or die "pano_modify failed";
        system("nona -o $output_file $pto_file") == 0 or die "nona failed";
    }
    $log->insert('end', "Animation complete in ./frames/\n");
}

MainLoop;
