#!/usr/bin/perl


#Скрипт для обновления спрайтов (пересоздания всех персонажей)


use strict;
use warnings;
use utf8;
use Scalar::Util qw( looks_like_number );
use Encode qw(decode encode);
use Cwd 'abs_path';
use File::Basename;
use Term::ANSIColor;

binmode(STDOUT,':utf8');
binmode(STDIN,':utf8');


#Путь до скрипта
my $S_SELF_PATH = abs_path( $0 );
#Имя скрипта
my $S_SELF_NAME = `basename $S_SELF_PATH`;
chomp( $S_SELF_NAME );


#Выходная папка для спрайтов
my $s_out_dir = "./renpy_out";
system( "rm -rf " . $s_out_dir );
system( "mkdir -p " . $s_out_dir );


#Get utf8 file as array of lines
sub readUTF8FileAsStringArr
{
	my $s_file_path = shift();
	open( my $file, '<:encoding( utf8 )', $s_file_path ) or die "Can't open file " . $s_file_path . "!\n";
	
	my @s_arr_of_lines = <$file>;
	chomp( @s_arr_of_lines );
	
	close( $file );
	return @s_arr_of_lines;
}



#Функция чтения конфиг-файла
sub myConfFileReader
{
	my $s_file_path = shift();
	my @s_conf_lines = readUTF8FileAsStringArr( $s_file_path );
	
	my %conf_hash = ();
	
	for( my $i = 0; $i < @s_conf_lines; $i++ )
	{
		if( index( $s_conf_lines[ $i ], "#" ) != -1 ) { next; } #Комментарии пропускаем
		if( index( $s_conf_lines[ $i ], "=" ) == -1 ) { next; }
		
		my $n_index = index(  $s_conf_lines[ $i ], "=" );
		
		my $s_key = $s_conf_lines[ $i ];
		$s_key = substr( $s_conf_lines[ $i ], 0, $n_index ); #Удаляем все после "="
		$s_key =~ s/^\s+|\s+$//g; #Удалить пробелы в конце и начале строки
		$s_key =~ s/^\t+|\t+$//g; #Удалить табы в конце и начале строки
		
		my $s_value = $s_conf_lines[ $i ];
		$s_value = substr( $s_conf_lines[ $i ], $n_index + 1 ); #Удаляем все до "="
		$s_value =~ s/^\s+|\s+$//g; #Удалить пробелы в конце и начале строки
		$s_value =~ s/^\t+|\t+$//g; #Удалить табы в конце и начале строки
		$s_value =~ s/;+$//; #Удаляем ";" в конце строки 
		
		$conf_hash{ $s_key } = $s_value;
	}
	
	return %conf_hash;
}


#Обходим все директории персонажей
my @s_char_folders_names = `ls -d */`;
chomp( @s_char_folders_names );
for( my $n_char_index = 0; $n_char_index < @s_char_folders_names; $n_char_index++ )
{
	#Имя персонажа
	my $s_char_name = `basename $s_char_folders_names[ $n_char_index ]`;
	chomp( $s_char_name );
	
	if( $s_char_name eq "renpy_out" ) { next; }
	print color("BRIGHT_GREEN"), $s_char_name . "\n";
	
	
	#Обходим все папки спрайтов персонажей
	my @s_sprite_folders_names = `ls -d $s_char_folders_names[ $n_char_index ]*/`;
	chomp( @s_sprite_folders_names );
	for( my $n_sprite_index = 0; $n_sprite_index < @s_sprite_folders_names; $n_sprite_index++ )
	{
		#Проверяем наличие нужных дерикторий для спрайта, если нет - переходим к следующему
		if( !( -e $s_sprite_folders_names[ $n_sprite_index ] . "Base.png") ) { print color("BRIGHT_RED"), "Base.png - не найден, пропускаем спрайт...\n"; next; }
		if( !( -d $s_sprite_folders_names[ $n_sprite_index ] . "emo") ) { print color("BRIGHT_RED"), "emo - не найден, пропускаем спрайт...\n"; next; }
		if( !( -e $s_sprite_folders_names[ $n_sprite_index ] . "Full_Shadow.png") ) { print color("BRIGHT_RED"), "Full_Shadow.png - не найден, пропускаем спрайт...\n"; next; }
		if( !( -e $s_sprite_folders_names[ $n_sprite_index ] . "Normal_Shadow.png") ) { print color("BRIGHT_RED"), "Normal_Shadow.png - не найден, пропускаем спрайт...\n"; next; }
		if( !( -e $s_sprite_folders_names[ $n_sprite_index ] . "params.conf") ) { print color("BRIGHT_RED"), "params.con - не найден, пропускаем спрайт...\n"; next; }
		
		
		#Имя спрайта
		my $s_sprite_name = `basename $s_sprite_folders_names[ $n_sprite_index ]`;
		chomp( $s_sprite_name );
		print color("BRIGHT_YELLOW"), "\t" . $s_sprite_name . "\n";
		
		#СОЗДАЕМ ВСЕ КАРТИНКИ ДЛЯ СПРАЙТА
		my $s_sprite_path = "./" . $s_char_name . "/" . $s_sprite_name . "";
		
		#База (куда наклеиваем всё остальное)
		my $s_base_file = `ls -1 $s_sprite_path/Base.png`;
		chomp( $s_base_file );
		my $s_base_name = `basename $s_base_file`;
		chomp( $s_base_name );
		
		#Нормальная тень (под эмоциями)
		my $s_sub_shadow_file = `ls -1 $s_sprite_path/Normal_Shadow.png`;
		chomp( $s_sub_shadow_file );
		my $s_sub_shadow_name = `basename $s_sub_shadow_file`;
		chomp( $s_sub_shadow_name );
		
		#Полная тень (над эмоциями)
		my $s_front_shadow_file = `ls -1 $s_sprite_path/Full_Shadow.png`;
		chomp( $s_front_shadow_file );
		my $s_front_shadow_name = `basename $s_front_shadow_file`;
		chomp( $s_front_shadow_name );
		
		#Создаем нужные директории для спрайта
		my $s_day_out_dir = $s_out_dir . "/" . $s_char_name . "/" . $s_sprite_name . "/DAY/";
		my $s_night_out_dir = $s_out_dir . "/" . $s_char_name . "/" . $s_sprite_name . "/NIGHT/";
		my $s_evening_out_dir = $s_out_dir . "/" . $s_char_name . "/" . $s_sprite_name . "/EVENING/";
		my $s_bw_out_dir = $s_out_dir . "/" . $s_char_name . "/" . $s_sprite_name . "/BLACK_AND_WHITE/";
		
		system( "mkdir -p " . $s_day_out_dir );
		system( "mkdir -p " . $s_night_out_dir );
		system( "mkdir -p " . $s_evening_out_dir );
		system( "mkdir -p " . $s_bw_out_dir );
		
		system( "mkdir -p " . $s_day_out_dir . "emo" );
		system( "mkdir -p " . $s_night_out_dir . "emo" );
		system( "mkdir -p " . $s_evening_out_dir . "emo" );
		system( "mkdir -p " . $s_bw_out_dir . "emo" );
		
		#Конвертируем базы
		system( "cp " . $s_base_file . " " . $s_day_out_dir . "/" );
		system( "./colortemp -t 5000 " . $s_base_file . " " . $s_evening_out_dir . "" . $s_base_name );
		system( "./colortemp -t 11000 " . $s_base_file . " " . $s_night_out_dir . "" . $s_base_name );
		system( "convert " . $s_base_file . " -colorspace Gray " . $s_bw_out_dir . "/" . $s_base_name );
		
		#Конвертируем тени
		system( "cp " . $s_sub_shadow_file . " " . $s_day_out_dir . "" );
		system( "cp " . $s_front_shadow_file . " " . $s_day_out_dir . "" );
		system( "./colortemp -t 5000 " . $s_sub_shadow_file . " " . $s_evening_out_dir . "" . $s_sub_shadow_name );
		system( "./colortemp -t 5000 " . $s_front_shadow_file . " " . $s_evening_out_dir . "" . $s_front_shadow_name );
		system( "./colortemp -t 11000 " . $s_sub_shadow_file . " " . $s_night_out_dir . "" . $s_sub_shadow_name );
		system( "./colortemp -t 11000 " . $s_front_shadow_file . " " . $s_night_out_dir . "" . $s_front_shadow_name );
		system( "convert " . $s_sub_shadow_file . " -colorspace Gray " . $s_bw_out_dir . "" . $s_sub_shadow_name );
		system( "convert " . $s_front_shadow_file . " -colorspace Gray " . $s_bw_out_dir . "" . $s_front_shadow_name );
		
		#Конвертируем эмоции
		my @s_emo_files = `ls -1 $s_sprite_path/emo/*.png`;
		chomp( @s_emo_files );
		for( my $i = 0; $i < @s_emo_files; $i++ )
		{
			my $s_emo_name = `basename $s_emo_files[ $i ]`;
			print color("BRIGHT_WHITE"), "\t\t" . $s_emo_name;
			
			system( "cp " . $s_emo_files[ $i ] . " " . $s_day_out_dir . "/emo/"  );
			system( "./colortemp -t 5000 " . $s_emo_files[ $i ] . " " . $s_evening_out_dir . "/emo/" . $s_emo_name );
			system( "./colortemp -t 11000 " . $s_emo_files[ $i ] . " " . $s_night_out_dir . "/emo/" . $s_emo_name );
			system( "convert " . $s_emo_files[ $i ] . " -colorspace Gray " . $s_bw_out_dir . "/emo/" . $s_emo_name );
		}
		
		#СОЗДАЕМ .rpy ФАЙЛ ДЛЯ СПРАЙТА
		#ЗАПИСЫВАЕМ ДНЕВНЫЕ СПРАЙТЫ
		my %conf_hash = myConfFileReader( $s_sprite_path . "/params.conf" );
		my $d_sprite_zoom = $conf_hash{ "normal_zoom" };
		my $s_rpy_path = $s_out_dir . "/" . $s_char_name . "/" . $s_sprite_name . "/" . $s_sprite_name . ".rpy";
		system( "cat /dev/null > " . $s_rpy_path );
		open( FILE, '>', $s_rpy_path ) or die $!;
		
		print FILE "# Этот файл сгенерирован скриптом " . $S_SELF_PATH . "\n";
		print FILE "# НЕ ПРАВИТЬ! ВСЕ ПРАВКИ БУДУТ УНИЧТОЖЕНЫ!\n";
		print FILE "# Дата создания: " . `date \'+%Y.%m.%d %H:%M\'` . "\n\n\n";
		
		print FILE "layeredimage Day_" . $s_sprite_name . ":\n"; #Day_
		print FILE "    always:\n";
		print FILE "        \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/DAY/" . $s_base_name . "\"\n";
		print FILE "        zoom " .  $d_sprite_zoom . "\n";
		print FILE "\n";
		
		print FILE "    group sub_shadows:\n";
		print FILE "        attribute Normal_Shadow:\n";
		print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/DAY/" . $s_sub_shadow_name . "\"\n";
		print FILE "            zoom " .  $d_sprite_zoom . "\n";
		print FILE "\n";
		
		print FILE "    group emo:\n";
		for( my $i = 0; $i < @s_emo_files; $i++ )
		{
			my $s_emo_name = `basename $s_emo_files[ $i ]`;
			my $s_emo_filename = `basename $s_emo_files[ $i ]`;
			chomp( $s_emo_filename );
			chomp( $s_emo_name );
			$s_emo_name =~ s/\.[^.]+$//; #Удаляем расширение файла
			
			print FILE "        attribute " . $s_emo_name . ":\n";
			print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/DAY/emo/" . $s_emo_filename . "\"\n";
			print FILE "            zoom " .  $d_sprite_zoom . "\n";
		}
		
		print FILE "\n";
		print FILE "    group front_shadows:\n";
		print FILE "        attribute Full_Shadow:\n";
		print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/DAY/" . $s_front_shadow_name . "\"\n";
		print FILE "            zoom " .  $d_sprite_zoom . "\n\n";
		
		print FILE makeMiniEmotions( \%conf_hash );
		print FILE "\n";
		
		
		#ЗАПИСЫВАЕМ ВЕЧЕРНИЕ СПРАЙТЫ
		print FILE "layeredimage Evening_" . $s_sprite_name . ":\n"; #Evening_
		print FILE "    always:\n";
		print FILE "        \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/EVENING/" . $s_base_name . "\"\n";
		print FILE "        zoom " .  $d_sprite_zoom . "\n";
		print FILE "\n";
		
		print FILE "    group sub_shadows:\n";
		print FILE "        attribute Normal_Shadow:\n";
		print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/EVENING/" . $s_sub_shadow_name . "\"\n";
		print FILE "            zoom " .  $d_sprite_zoom . "\n";
		print FILE "\n";
		
		print FILE "    group emo:\n";
		for( my $i = 0; $i < @s_emo_files; $i++ )
		{
			my $s_emo_name = `basename $s_emo_files[ $i ]`;
			my $s_emo_filename = `basename $s_emo_files[ $i ]`;
			chomp( $s_emo_filename );
			chomp( $s_emo_name );
			$s_emo_name =~ s/\.[^.]+$//; #Удаляем расширение файла
			
			print FILE "        attribute " . $s_emo_name . ":\n";
			print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/EVENING/emo/" . $s_emo_filename . "\"\n";
			print FILE "            zoom " .  $d_sprite_zoom . "\n";
		}
		
		print FILE "\n";
		print FILE "    group front_shadows:\n";
		print FILE "        attribute Full_Shadow:\n";
		print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/EVENING/" . $s_front_shadow_name . "\"\n";
		print FILE "            zoom " .  $d_sprite_zoom . "\n\n";
		
		print FILE makeMiniEmotions( \%conf_hash );
		print FILE "\n";
		
		
		#ЗАПИСЫВАЕМ НОЧНЫЕ СПРАЙТЫ
		print FILE "layeredimage Night_" . $s_sprite_name . ":\n"; #Evening_
		print FILE "    always:\n";
		print FILE "        \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/NIGHT/" . $s_base_name . "\"\n";
		print FILE "        zoom " .  $d_sprite_zoom . "\n";
		print FILE "\n";
		
		print FILE "    group sub_shadows:\n";
		print FILE "        attribute Normal_Shadow:\n";
		print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/NIGHT/" . $s_sub_shadow_name . "\"\n";
		print FILE "            zoom " .  $d_sprite_zoom . "\n";
		print FILE "\n";
		
		print FILE "    group emo:\n";
		for( my $i = 0; $i < @s_emo_files; $i++ )
		{
			my $s_emo_name = `basename $s_emo_files[ $i ]`;
			my $s_emo_filename = `basename $s_emo_files[ $i ]`;
			chomp( $s_emo_filename );
			chomp( $s_emo_name );
			$s_emo_name =~ s/\.[^.]+$//; #Удаляем расширение файла
			
			print FILE "        attribute " . $s_emo_name . ":\n";
			print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/NIGHT/emo/" . $s_emo_filename . "\"\n";
			print FILE "            zoom " .  $d_sprite_zoom . "\n";
		}
		
		print FILE "\n";
		print FILE "    group front_shadows:\n";
		print FILE "        attribute Full_Shadow:\n";
		print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/NIGHT/" . $s_front_shadow_name . "\"\n";
		print FILE "            zoom " .  $d_sprite_zoom . "\n\n";
		
		#ЗАПИСЫВАЕМ ЧЕРНОБЕЛЫЕ СПРАЙТЫ
		print FILE "layeredimage BW_" . $s_sprite_name . ":\n"; #BW_
		print FILE "    always:\n";
		print FILE "        \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/BLACK_AND_WHITE/" . $s_base_name . "\"\n";
		print FILE "        zoom " .  $d_sprite_zoom . "\n";
		print FILE "\n";
		
		print FILE "    group sub_shadows:\n";
		print FILE "        attribute Normal_Shadow:\n";
		print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/BLACK_AND_WHITE/" . $s_sub_shadow_name . "\"\n";
		print FILE "            zoom " .  $d_sprite_zoom . "\n";
		print FILE "\n";
		
		print FILE "    group emo:\n";
		for( my $i = 0; $i < @s_emo_files; $i++ )
		{
			my $s_emo_name = `basename $s_emo_files[ $i ]`;
			my $s_emo_filename = `basename $s_emo_files[ $i ]`;
			chomp( $s_emo_filename );
			chomp( $s_emo_name );
			$s_emo_name =~ s/\.[^.]+$//; #Удаляем расширение файла
			
			print FILE "        attribute " . $s_emo_name . ":\n";
			print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/BLACK_AND_WHITE/emo/" . $s_emo_filename . "\"\n";
			print FILE "            zoom " .  $d_sprite_zoom . "\n";
		}
		
		print FILE "\n";
		print FILE "    group front_shadows:\n";
		print FILE "        attribute Full_Shadow:\n";
		print FILE "            \"images/sprites/" . $s_char_name . "/" . $s_sprite_name . "/BLACK_AND_WHITE/" . $s_front_shadow_name . "\"\n";
		print FILE "            zoom " .  $d_sprite_zoom . "\n\n";
		
		print FILE makeMiniEmotions( \%conf_hash );
	}
}


sub makeMiniEmotions
{
	my $conf_hash = shift();
	my $d_sprite_zoom = $conf_hash->{ "normal_zoom" };
	
	#Angry
	my $s_img_path = "./Micro_Emo/Angry/Angry_01.png";
	my $s_microemo_frame_width = `identify -ping -format "%w" $s_img_path`;
	my $s_microemo_frame_height = `identify -ping -format "%h" $s_img_path`;
	
	chomp( $s_microemo_frame_width );
	chomp( $s_microemo_frame_height );
	
	my $s_microemo_xpos = ( $conf_hash->{ "mini_xpos" } - ( $s_microemo_frame_width/2 ) ) * $d_sprite_zoom;
	my $s_microemo_ypos = ( $conf_hash->{ "mini_ypos" } - ( $s_microemo_frame_height/2 ) ) * $d_sprite_zoom;
	
	my $s_result = "    group micro_emo:\n";
	#$s_result .= "        pos( " . int( $s_microemo_xpos ) . ", " . int( $s_microemo_ypos ) . " )\n";
	$s_result .= "        attribute Micro_Angry:\n";
	$s_result .= "            \"Micro_Emo_Angry_Animated\"\n";
	$s_result .= "            xpos " . int( $s_microemo_xpos ) . "\n";
	$s_result .= "            ypos " . int( $s_microemo_ypos ) . "\n";
	$s_result .= "            zoom " .  $conf_hash->{ "normal_zoom" } . "\n\n";
	
	#Drop
	$s_img_path = "./Micro_Emo/Drop/Drop.png";
	$s_microemo_frame_width = `identify -ping -format "%w" $s_img_path`;
	$s_microemo_frame_height = `identify -ping -format "%h" $s_img_path`;
	
	chomp( $s_microemo_frame_width );
	chomp( $s_microemo_frame_height );
	
	$s_microemo_xpos = ( $conf_hash->{ "mini_xpos" } - ( $s_microemo_frame_width/2 ) ) * $d_sprite_zoom;
	$s_microemo_ypos = ( $conf_hash->{ "mini_ypos" } - ( $s_microemo_frame_height/2 ) ) * $d_sprite_zoom;
	
	$s_result .= "        attribute Micro_Drop:\n";
	$s_result .= "            \"Micro_Emo_Drop_Animated\"\n";
	$s_result .= "            xpos " . int( $s_microemo_xpos ) . "\n";
	$s_result .= "            ypos " . int( $s_microemo_ypos ) . "\n";
	$s_result .= "            zoom " .  $conf_hash->{ "normal_zoom" } . "\n\n";
	
	#Question
	$s_img_path = "./Micro_Emo/Question/Question_Mark_01.png";
	$s_microemo_frame_width = `identify -ping -format "%w" $s_img_path`;
	$s_microemo_frame_height = `identify -ping -format "%h" $s_img_path`;
	
	chomp( $s_microemo_frame_width );
	chomp( $s_microemo_frame_height );
	
	$s_microemo_xpos = ( $conf_hash->{ "mini_xpos" } - ( $s_microemo_frame_width/2 ) ) * $d_sprite_zoom;
	$s_microemo_ypos = ( $conf_hash->{ "mini_ypos" } - ( $s_microemo_frame_height/2 ) ) * $d_sprite_zoom;
	
	$s_result .= "        attribute Micro_Question:\n";
	$s_result .= "            \"Micro_Emo_Question_Animated\"\n";
	$s_result .= "            xpos " . int( $s_microemo_xpos ) . "\n";
	$s_result .= "            ypos " . int( $s_microemo_ypos ) . "\n";
	$s_result .= "            zoom " .  $conf_hash->{ "normal_zoom" } . "\n\n";
	
	#Empty
	$s_img_path = "./Micro_Emo/Empty/Empty.png";
	$s_microemo_frame_width = `identify -ping -format "%w" $s_img_path`;
	$s_microemo_frame_height = `identify -ping -format "%h" $s_img_path`;
	
	chomp( $s_microemo_frame_width );
	chomp( $s_microemo_frame_height );
	
	$s_microemo_xpos = ( $conf_hash->{ "mini_xpos" } - ( $s_microemo_frame_width/2 ) ) * $d_sprite_zoom;
	$s_microemo_ypos = ( $conf_hash->{ "mini_ypos" } - ( $s_microemo_frame_height/2 ) ) * $d_sprite_zoom;
	
	$s_result .= "        attribute Micro_Empty:\n";
	$s_result .= "            \"Micro_Emo_Empty\"\n";
	$s_result .= "            xpos " . int( $s_microemo_xpos ) . "\n";
	$s_result .= "            ypos " . int( $s_microemo_ypos ) . "\n";
	$s_result .= "            zoom " .  $conf_hash->{ "normal_zoom" } . "\n\n";
	
	return $s_result
}


print color("BRIGHT_WHITE"), "Copy to game folder...\n";
system( "cp -r ./renpy_out/* /home/daniel/Documents/Sources/renpy/projects/radiopulsarvn/game/images/sprites/" );
