#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;

use lib 'lib';

use OpenGL qw(:all);
use SDL 2.5 qw(:init);
use SDL::Video;
use SDL::Surface;
use SDL::Event;
use SDL::Events;

use Math::Trig;
use Time::HiRes qw(sleep time);
use Dizzy::Handlers;
use Dizzy::Core;
use Dizzy::GLFeatures;

my %options = Dizzy::Core::init_arguments();

sub do_resize {
	my ($w, $h) = @_;

	# set default resolutions:
	if (!$w or !$h) {
		if ($options{fullscreen}) {
			# no specific resolution for fullscreen mode
			$w = $h = 0;
		} else {
			# 800x500 for windowed mode
			($w, $h) = (800, 500);
		}
	}

	my $surf = SDL::Video::set_video_mode($w, $h, 0,
		SDL_OPENGL() |
		SDL_HWSURFACE() |
		SDL_RESIZABLE() |
		($options{fullscreen} ? SDL_FULLSCREEN() : 0));

	if (!$surf) {
		print STDERR "fatal: SDL Error: " .  SDL::get_error() . "\n";
		exit(1);
	}

	# find out actual new window size and reset projection
	($w, $h) = ($surf->w, $surf->h);
	glViewport(0, 0, $w, $h);
	Dizzy::Render::init_projection($w / $h);
}

# initialize OpenGL
# (returns 0 on success, therefore "and", not "or")
SDL::init(SDL_INIT_VIDEO()) and die(SDL::get_error());
SDL::Video::wm_set_caption("Dizzy", "");
SDL::Video::GL_set_attribute(SDL_GL_DOUBLEBUFFER(), 1) and die(SDL::get_error());
do_resize($options{width}, $options{height});
if ($options{fullscreen}) {
	SDL::Mouse::show_cursor(0);
}

Dizzy::Handlers::register_last(
	render => sub {
		Dizzy::Core::_fps_tick();
		Dizzy::Handlers::GO_ON;
	},
	'exit' => sub {
		my $ev = SDL::Event->new();
		$ev->type(SDL_QUIT());
		SDL::Events::push_event($ev);
		Dizzy::Handlers::GO_ON;
	},
);

Dizzy::GLFeatures::update_capabilities();

# prepare for progress screen
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();

# initialize dizzy subsystems
Dizzy::Core::init_subsystems(%options,
	callback_texture_load => sub {
		my %args = @_;

		# if window is resized while displaying the progress bar, handle that
		my $event = SDL::Event->new();
		while (SDL::Events::poll_event($event)) {
			my $type = $event->type();
			if ($type == SDL_QUIT()) {
				print STDERR "warning: exiting during initialization\n";
				exit(2);
			} elsif ($type == SDL_VIDEORESIZE()) {
				do_resize($event->resize_w(), $event->resize_h());
			}
		}

		glClear(GL_COLOR_BUFFER_BIT);

		# bar background
		glColor3f((0.125) x 3);
		glRectf(-2.0, +0.0625, +2.0, -0.125);

		# bar itself
		glColor3f((1.0) x 3);
		glRectf(-2.0, +0.0625, -2.0 + 4.0 * ($args{current} / $args{total}), -0.125);

		glFlush();
		SDL::Video::GL_swap_buffers();
	},
);

if ($options{debug_time_startup}) {
	print "debug: startup complete, exiting as requested\n";
	exit(0);
}

my $event = SDL::Event->new();
while (1) {
	if (SDL::Events::poll_event($event)) {
		my $type = $event->type();
		if ($type == SDL_QUIT()) {
			exit(0);
		} elsif ($type == SDL_KEYDOWN()) {
			my $keysym = $event->key_sym();
			my $k;
			if ($keysym == SDLK_LEFT()) {
				$k = "LEFT";
			} elsif ($keysym == SDLK_RIGHT()) {
				$k = "RIGHT";
			} elsif ($keysym == SDLK_DOWN()) {
				$k = "DOWN";
			} elsif ($keysym == SDLK_UP()) {
				$k = "UP";
			} elsif ($keysym == SDLK_ESCAPE()) {
				$k = "\e";
			} elsif ($keysym == SDLK_q()) {
				$k = "q";
			} else {
				$k = "OTHER:$keysym";
			}

			Dizzy::Handlers::invoke("keyboard", key => $k);
		} elsif ($type == SDL_VIDEORESIZE()) {
			do_resize($event->resize_w(), $event->resize_h());
		}
	}

	Dizzy::Handlers::invoke("render");
	glFlush();
	SDL::Video::GL_swap_buffers();
}

__END__

=head1 NAME

B<dizzy> - a graphics demo that makes you dizzy using rotating textures

=head1 SYNOPSIS

B<dizzy> [B<-f>|B<-w> I<width> B<-h> I<height>] [B<-t> I<switch_module>] [B<-T> I<options>]

=head1 DESCRIPTION

B<dizzy> is a graphics demo that rotates planes of patterns on a colored
background to make you dizzy. Textures can be cross-faded and there is a mode
that automatically changes textures, allowing Dizzy to be run as a screensaver.

=head1 OPTIONS

=over

=item B<-w> I<width>

=item B<--width> I<width>

=item B<-h> I<height>

=item B<--height> I<height>

Sets the window width and height.

=item B<-f>

=item B<--fullscreen>

Attempts to switch into a true fullscreen mode, if possible. The window size
parameters are ignored.

=item B<-a>

=item B<--automode> I<time>

Automatically switches textures after a specified number of seconds has passed.
I<time> can be fractional and the decimal separator is always the period.

=item B<-t> I<module>

=item B<--texswitcher> I<module>

Selects the texture switching module to use. Default is B<Simple>.

See below for available texture switchers and their descriptions.

=item B<-T> I<option>=I<value>

=item B<--texswitcher-options> I<option>=I<value>

Passes an option I<option> with the value I<value> to the selected texture
switcher. The available options depend on the texture switcher used.

This option can be given multiple times to set multiple options.

=item B<-d> I<module>

=item B<--rotswitcher> I<module>

Selects the rotator switching module to use. Default is B<Simple>.

See below for available texture switchers and their descriptions.

=item B<-D> I<option>=I<value>

=item B<--rotswitcher-options> I<option>=I<value>

Passes an option I<option> with the value I<value> to the selected rotator
switcher. The available options depend on the rotator switcher used.

This option can be given multiple times to set multiple options.

=item B<-r> I<resolution>

=item B<--texture-resolution> I<resolution>

Changes the texture resolution. I<resolution> must be a power of two. The default
value is 256.

=item B<-R> I<resolution>

=item B<--shader-resolution> I<resolution>

Changes the resolution used when rendering using shaders. I<resolution> must be
a power of two. The default is 1024.

=item B<-z> I<zoom>

=item B<--zoom> I<zoom>

Zooms the textures. The default value is 100.

=item B<-c> I<path>

=item B<--cache-paths> I<path>

Use a different path for cached textures. This option can be specified multiple
times.

=item B<-C>

=item B<--disable-cache>

Don't use any texture cache at all.

=item B<--debug-show-planes>

Zooms out of the normal view so you can see how Dizzy creates the animation. A
white border will also be drawn around the area that would have been shown had
this option not been used.

=back

=head1 TEXTURE SWITCHERS

=head2 Simple

A simple texture switcher. It just sets the new texture when it is told to do
so. It takes no options.

=head2 Blend

A texture switcher that crossfades between textures to generate a smooth
transition. It takes one option:

=over

=item B<duration>=I<duration>

Sets the duration of a blend to I<duration> seconds. The value can be fractional
(the decimal separator is always a period).  The default value is 2.

Note that you have to add the time you specify here to the automode time, so if
you want the transition to take two seconds and every image to stay for five
seconds, you set the duration to 2 and automode to 7 (not 5).

=back

=head1 ROTATOR SWITCHERS

=head2 Simple

A simple switcher that just activates the new rotator without any transition.

=head1 KEYBOARD COMMANDS

=over

=item Cursor left

Select previous available texture.

=item Cursor right

Select next available texture.

=item Cursor down

Select previous available rotator function.

=item Cursor up

Select next available rotator function.

=item Escape

=item q

Exit Dizzy.

=back

=cut
