#!/usr/bin/perl
use strict;
use warnings;
use Tk;
use Tk::FileSelect;
use Tk::JPEG;
use Image::Imlib2;
use Math::Trig qw(deg2rad rad2deg pi asin tan atan);

# Rectilinear Extractor – direction + lens
# Preview uses a downscaled copy; extraction uses the original full-size file.
# Credit: original projection by user; focal-length controls + preview scaling by Grok (xAI)

my $input  = '';
my $output = 'output.jpg';

my ($yaw, $pitch) = (0, 0);
my $focal_mm = 55;
my ($width, $height) = (1800, 1200);   # output size (3:2)

my $sensor_width_mm = 36.0;
my ($hfov, $vfov) = (36.3, 24.7);

my $preview_max = 1600;   # max dimension of the preview image

### --- Helpers ---
sub hfov_from_focal {
    my ($f) = @_;
    return rad2deg(2 * atan($sensor_width_mm / (2 * $f)));
}

sub update_fov {
    my ($f) = @_;
    $focal_mm = $f;
    $hfov = hfov_from_focal($f);
    my $aspect = $height / $width;
    $vfov = rad2deg(2 * atan($aspect * tan(deg2rad($hfov)/2)));
}

### --- Window ---
my $mw = MainWindow->new;
$mw->title("Rectilinear Extractor – Direction + Lens");
$mw->optionAdd('*Font' => 'Helvetica 13');

$mw->Label(-text => "Input:")->grid(-row=>0, -column=>0, -sticky=>'w');
$mw->Entry(-textvariable => \$input, -width => 36)->grid(-row=>0, -column=>1);
$mw->Button(-text => "Browse", -command => sub {
    my $fs = $mw->FileSelect(-filter => '*.jpg');
    my $file = $fs->Show;
    if ($file) { $input = $file; load_image(); }
})->grid(-row=>0, -column=>2);

$mw->Label(-text => "Output:")->grid(-row=>1, -column=>0, -sticky=>'w');
$mw->Entry(-textvariable => \$output, -width => 36)->grid(-row=>1, -column=>1);

$mw->Label(-text => "Yaw")->grid(-row=>2, -column=>0, -sticky=>'w');
my $scale_yaw = $mw->Scale(-from=>-180, -to=>180, -orient=>'horizontal', -length=>380,
    -command => sub { $yaw = $_[0]; draw_grid(); }
)->grid(-row=>2, -column=>1, -columnspan=>2);

$mw->Label(-text => "Pitch")->grid(-row=>3, -column=>0, -sticky=>'w');
my $scale_pitch = $mw->Scale(-from=>-90, -to=>90, -orient=>'horizontal', -length=>380,
    -command => sub { $pitch = $_[0]; draw_grid(); }
)->grid(-row=>3, -column=>1, -columnspan=>2);

$mw->Label(-text => "Lens")->grid(-row=>4, -column=>0, -sticky=>'w');
my $lens_frame = $mw->Frame()->grid(-row=>4, -column=>1, -columnspan=>2, -sticky=>'w');
for my $f (24, 35, 50, 55, 85, 105, 135) {
    $lens_frame->Button(
        -text => "$f mm",
        -command => sub { update_fov($f); draw_grid(); }
    )->pack(-side=>'left', -padx=>3);
}
#######
# Output size
$mw->Label(-text => "Output width")->grid(-row=>6, -column=>0, -sticky=>'s');
my $scale_width = $mw->Scale(
    -from     => 800,
    -to       => 4000,
    -orient   => 'horizontal',
    -length   => 380,
    -variable => \$width,
    -command  => sub {
        $width  = int($_[0]);
        $height = int($width * 2 / 3);   # keep 3:2
        update_fov($focal_mm);
        draw_grid();
    }
)->grid(-row=>6, -column=>1, -columnspan=>2);

$mw->Label(-textvariable => \$height, -width => 6)->grid(-row=>6, -column=>3, -sticky=>'s');  # shows the derived height

######
$mw->Label(-text => "or mm:")->grid(-row=>5, -column=>0, -sticky=>'w');
my $focal_entry = $mw->Entry(-textvariable => \$focal_mm, -width => 8)->grid(-row=>5, -column=>1, -sticky=>'w');
$mw->Button(-text => "Apply", -command => sub { update_fov($focal_mm); draw_grid(); })->grid(-row=>7, -column=>2, -sticky=>'w');

$mw->Button(-text => "Generate", -command => sub {
    unless ($input && -e $input) {
        $mw->messageBox(-message => "Select a valid input image", -type => 'ok');
        return;
    }
    update_fov($focal_mm);
    extract_rectilinear($input, $output, $yaw, $pitch, $hfov, $vfov, $width, $height);
    $mw->messageBox(-message => "Saved to $output", -type => "ok");
})->grid(-row=>7, -column=>1, -pady=>8);

# Canvas
my $canvas_frame = $mw->Frame()->grid(-row=>8, -column=>0, -columnspan=>3, -sticky=>'nsew');
$mw->gridRowconfigure(7, -weight => 1);
$mw->gridColumnconfigure(1, -weight => 1);

my $canvas = $canvas_frame->Canvas(-background => 'black')->pack(-side=>'left', -expand=>1, -fill=>'both');
my $xs = $canvas_frame->Scrollbar(-orient=>'horizontal', -command => ['xview', $canvas])->pack(-side=>'bottom', -fill=>'x');
my $ys = $canvas_frame->Scrollbar(-orient=>'vertical',   -command => ['yview', $canvas])->pack(-side=>'right', -fill=>'y');
$canvas->configure(-xscrollcommand => ['set', $xs], -yscrollcommand => ['set', $ys]);

my ($photo, $img_w, $img_h);   # preview dimensions

sub load_image {
    return unless $input && -e $input;

    # Create a downscaled preview for the UI
    my $src = Image::Imlib2->load($input) or do {
        $mw->messageBox(-message => "Cannot load image", -type=>'ok');
        return;
    };
    my ($sw, $sh) = ($src->get_width, $src->get_height);
    my $scale = 1;
    if ($sw > $preview_max || $sh > $preview_max) {
        $scale = $preview_max / ($sw > $sh ? $sw : $sh);
    }
    my $pw = int($sw * $scale);
    my $ph = int($sh * $scale);
    my $preview = $src->create_scaled_image($pw, $ph);

    # Save temporary preview for Tk::Photo
    my $tmp = "/tmp/equirect_preview_$$.jpg";
    $preview->save($tmp);

    eval { $photo = $mw->Photo(-file => $tmp); };
    unlink $tmp;
    if ($@ || !$photo) {
        $mw->messageBox(-message => "Cannot display preview", -type=>'ok');
        return;
    }

    $img_w = $photo->width;
    $img_h = $photo->height;
    $canvas->configure(-width => $img_w, -height => $img_h, -scrollregion => [0,0,$img_w,$img_h]);
    $canvas->delete('all');
    $canvas->createImage(0, 0, -image => $photo, -anchor => 'nw', -tags => 'bg');
    draw_grid();
}

sub draw_grid {
    return unless $photo;
    $canvas->delete('grid');

    my $yaw_rad   = deg2rad($yaw);
    my $pitch_rad = deg2rad($pitch);
    my $hfov_rad  = deg2rad($hfov);
    my $vfov_rad  = deg2rad($vfov);
    my $hfov_half = $hfov_rad / 2;
    my $vfov_half = $vfov_rad / 2;

    my @coords;
    for my $corner ([-$hfov_half,  $vfov_half], [$hfov_half,  $vfov_half],
                    [$hfov_half, -$vfov_half], [-$hfov_half, -$vfov_half]) {
        my ($u, $v) = @$corner;
        my $dx = -tan($u);
        my $dy =  tan($v);
        my $dz = 1;
        my $len = sqrt($dx*$dx + $dy*$dy + $dz*$dz);
        $dx /= $len; $dy /= $len; $dz /= $len;

        my $dy2 = $dy * cos($pitch_rad) - $dz * sin($pitch_rad);
        my $dz2 = $dy * sin($pitch_rad) + $dz * cos($pitch_rad);
        my $dx2 = $dx;

        my $dx3 = $dx2 * cos($yaw_rad) + $dz2 * sin($yaw_rad);
        my $dz3 = -$dx2 * sin($yaw_rad) + $dz2 * cos($yaw_rad);
        my $dy3 = $dy2;

        my $lon = atan2($dz3, $dx3);
        my $lat = asin($dy3);

        push @coords, ($lon/(2*pi) + 0.5) * $img_w, ($lat/pi + 0.5) * $img_h;
    }
    $canvas->createPolygon(@coords, -outline => 'red', -width => 2, -fill => '', -tags => 'grid');
}

sub extract_rectilinear {
    my ($in, $out, $yaw_deg, $pitch_deg, $hfov_deg, $vfov_deg, $out_w, $out_h) = @_;
    my $src = Image::Imlib2->load($in) or return;
    $src->has_alpha(0);
    my ($sw, $sh) = ($src->get_width, $src->get_height);

    my $dst = Image::Imlib2->new($out_w, $out_h);
    $dst->has_alpha(0);
    $dst->fill_rectangle(0, 0, $out_w, $out_h);

    my $yaw_rad   = deg2rad($yaw_deg);
    my $pitch_rad = deg2rad($pitch_deg);
    my $hfov_rad  = deg2rad($hfov_deg);
    my $vfov_rad  = deg2rad($vfov_deg);

    for my $y (0 .. $out_h-1) {
        my $v = tan($vfov_rad/2) * (($y - $out_h/2) / ($out_h/2));
        for my $x (0 .. $out_w-1) {
            my $u = -tan($hfov_rad/2) * (($x - $out_w/2) / ($out_w/2));
            my ($dx, $dy, $dz) = ($u, $v, 1);
            my $len = sqrt($dx*$dx + $dy*$dy + $dz*$dz);
            $dx /= $len; $dy /= $len; $dz /= $len;

            my $dy2 = $dy*cos($pitch_rad) - $dz*sin($pitch_rad);
            my $dz2 = $dy*sin($pitch_rad) + $dz*cos($pitch_rad);
            my $dx2 = $dx;
            my $dx3 = $dx2*cos($yaw_rad) + $dz2*sin($yaw_rad);
            my $dz3 = -$dx2*sin($yaw_rad) + $dz2*cos($yaw_rad);
            my $dy3 = $dy2;

            my $lon = atan2($dz3, $dx3);
            my $lat = asin($dy3);
            my $sx = ($lon/(2*pi) + 0.5) * $sw;
            my $sy = ($lat/pi + 0.5) * $sh;

            # bilinear sampling
            my $x0 = int($sx) % $sw;
            my $y0 = int($sy);
            my $x1 = ($x0 + 1) % $sw;
            my $y1 = $y0 + 1;
            $y0 = 0 if $y0 < 0;
            $y1 = $sh-1 if $y1 >= $sh;
            my $fx = $sx - int($sx);
            my $fy = $sy - int($sy);

            my @c00 = $src->query_pixel($x0, $y0);
            my @c10 = $src->query_pixel($x1, $y0);
            my @c01 = $src->query_pixel($x0, $y1);
            my @c11 = $src->query_pixel($x1, $y1);
            my @c;
            for my $i (0..2) {
                my $c0 = $c00[$i]*(1-$fx) + $c10[$i]*$fx;
                my $c1 = $c01[$i]*(1-$fx) + $c11[$i]*$fx;
                $c[$i] = int($c0*(1-$fy) + $c1*$fy + 0.5);
            }
            $dst->set_colour(@c, 255);
            $dst->draw_point($x, $y);
        }
    }
    $dst->save($out);
}

update_fov(55);
load_image();
MainLoop;
