#!/bin/bash
#
# Developed by Fred Weinhaus 12/8/2012 .......... revised 4/25/2015
#
# ------------------------------------------------------------------------------
# 
# Licensing:
# 
# Copyright © Fred Weinhaus
# 
# My scripts are available free of charge for non-commercial use, ONLY.
# 
# For use of my scripts in commercial (for-profit) environments or 
# non-free applications, please contact me (Fred Weinhaus) for 
# licensing arrangements. My email address is fmw at alink dot net.
# 
# If you: 1) redistribute, 2) incorporate any of these scripts into other 
# free applications or 3) reprogram them in another scripting language, 
# then you must contact me for permission, especially if the result might 
# be used in a commercial or for-profit environment.
# 
# My scripts are also subject, in a subordinate manner, to the ImageMagick 
# license, which can be found at: http://www.imagemagick.org/script/license.php
# 
# ------------------------------------------------------------------------------
# 
####
#
# USAGE: slantedlight [-a angles] [-i intensities] [-d distances] [-s smooth] 
# [-p percent] [-c color] infile outfile
# 
# USAGE: slantedlight [-h or -help]
# 
# OPTIONS:
# 
# -a     angles          angles towards which the light is directed; one or more 
#                        comma or space separated values; 0<=integers<=360; 
#                        angle directions are clockwise from east; default=0
# -i     intensities     intensities corresponding to each light; 
#                        integers>=0; default=100
# -d     distances       distances for which each light is directed; 
#                        integers>=0; default=30
# -s     smooth          smoothing (softening) of soft lights; float>=0; 
#                        default=0 (no smoothing)
# -p     percent         percent of white from thresholding; 0<=float<=100; 
#                        default=2
# -c     color           color of softlight; any valid opaque IM color; 
#                        default=white
# 
###
# 
# NAME: SLANTEDLIGHT 
# 
# PURPOSE: To apply slanted lighting to an image.
# 
# DESCRIPTION: SLANTEDLIGHT applies slanted lighting to an image. Multiple 
# directions of light may be applied with different intensities and lengths.
# 
# 
# ARGUMENTS: 
# 
# -a angles ... ANGLES towards which the light is directed. One or more 
# comma or space separated values enclosed in quotes. Values are 
# integers between 0 and 360 (degrees). Angle directions are clockwise from 
# east. The default=0.
# 
# -i intensities ... INTENSITIES corresponding to each light. One or more 
# comma or space separated values enclosed in quotes. If the list of 
# intensities is shorter than the list of angles, then the first intensity 
# value will be used for missing entries. Values are integers greater then 0. 
# The default=100.
# 
# -d distances ... DISTANCES corresponding to each angle for which each light 
# is directed. One or more comma or space separated values enclosed in quotes. 
# If the list of intensities is shorter than the list of angles, then the first 
# intensity value will be used for missing entries. Values are integers greater 
# than or equal to 0. The default=30.
# 
# -s smooth ... SMOOTH is the smoothing amount of the slanted lights. Values 
# are floats greater than or equal to 0.  The default=0 (no smoothing).
# 
# -p percent ...PERCENT of white from thresholding used to create the slanted 
# lights. Values are floats between 0 and 100. The default=2.
# 
# -c color ... COLOR of the soft light. Any valid opaque IM color is allowed. 
# The default=white.
# 
# CAVEAT: No guarantee that this script will work on all platforms, 
# nor that trapping of inconsistent parameters is complete and 
# foolproof. Use At Your Own Risk. 
# 
######
# 

# set default values
angles="0"					# angles light is pointing
intensities="100"			# strength (intensity, attenuation)
distances="30"				# motion blur extent of directional light; motion-blur sigma
smooth=0					# smoothing; blur sigma
percent=2					# percent white threshold
color="white"				# light color

# set directory for temporary files
dir="."    # suggestions are dir="." or dir="/tmp"

# set up functions to report Usage and Usage with Description
PROGNAME=`type $0 | awk '{print $3}'`  # search for executable on path
PROGDIR=`dirname $PROGNAME`            # extract directory of program
PROGNAME=`basename $PROGNAME`          # base name of program
usage1() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^###/g;  /^#/!q;  s/^#//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}
usage2() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^######/g;  /^#/!q;  s/^#*//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}


# function to report error messages
errMsg()
	{
	echo ""
	echo $1
	echo ""
	usage1
	exit 1
	}


# function to test for minus at start of value of second part of option 1 or 2
checkMinus()
	{
	test=`echo "$1" | grep -c '^-.*$'`   # returns 1 if match; 0 otherwise
    [ $test -eq 1 ] && errMsg "$errorMsg"
	}

getMinMax()
	{
	img="$1"
	# statistics computed as percent (of dynamic range) values
	if [ "$im_version" -ge "06030901" ]
		then 
		min=`convert $img -format "%[min]" info:`
		max=`convert $img -format "%[max]" info:`
		min=`convert xc: -format "%[fx:100*$min/quantumrange]" info:`
		max=`convert xc: -format "%[fx:100*$max/quantumrange]" info:`
	else
		data=`convert $img -verbose info:`
		min=`echo "$data" | sed -n 's/^.*[Mm]in:.*[(]\([0-9.]*\).*$/\1/p ' | head -1`
		max=`echo "$data" | sed -n 's/^.*[Mm]ax:.*[(]\([0-9.]*\).*$/\1/p ' | head -1`
		min=`convert xc: -format "%[fx:100*$min]" info:`
		max=`convert xc: -format "%[fx:100*$max]" info:`
	fi
	}

# test for correct number of arguments and get values
if [ $# -eq 0 ]
	then
	# help information
   echo ""
   usage2
   exit 0
elif [ $# -gt 14 ]
	then
	errMsg "--- TOO MANY ARGUMENTS WERE PROVIDED ---"
else
	while [ $# -gt 0 ]
		do
			# get parameter values
			case "$1" in
		  -h|-help)    # help information
					   echo ""
					   usage2
					   exit 0
					   ;;
				-a)    # get angles
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID ANGLES SPECIFICATION ---"
					   checkMinus "$1"
					   angles=`expr "$1" : '\([ ,0-9]*\)'`
					   [ "$angles" = "" ] && errMsg "--- ANGLES=$angles MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   ;;
				-i)    # get intensities
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID INTENSITIES SPECIFICATION ---"
					   checkMinus "$1"
					   intensities=`expr "$1" : '\([ ,0-9]*\)'`
					   [ "$intensities" = "" ] && errMsg "--- INTENSITIES=$intensities MUST BE A NON-NEGATIVE INTEGER (with no sign) ---"
					   ;;
				-d)    # get distances
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID DISTANCES SPECIFICATION ---"
					   checkMinus "$1"
					   distances=`expr "$1" : '\([ ,0-9]*\)'`
					   [ "$distances" = "" ] && errMsg "--- DISTANCES=$distances MUST BE A NON-NEGATIVE INTEGER (with no sign) ---"
					   ;;
				-s)    # get smooth
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID SMOOTH SPECIFICATION ---"
					   checkMinus "$1"
					   smooth=`expr "$1" : '\([.0-9]*\)'`
					   [ "$smooth" = "" ] && errMsg "--- SMOOTH=$smooth MUST BE A NON-NEGATIVE FLOAT ---"
					   ;;
				-p)    # get percent
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID PERCENT SPECIFICATION ---"
					   checkMinus "$1"
					   percent=`expr "$1" : '\([.0-9]*\)'`
					   [ "$percent" = "" ] && errMsg "--- PERCENT=$percent MUST BE A NON-NEGATIVE FLOAT VALUE (with no sign) ---"
					   test1=`echo "$percent < 0" | bc`
					   test2=`echo "$percent > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- PERCENT=$percent MUST BE A FLOAT BETWEEN 0 AND 100 ---"
					   ;;
				-c)    # get color
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID COLOR SPECIFICATION ---"
					   checkMinus "$1"
					   color="$1"
					   ;;
				 -)    # STDIN and end of arguments
					   break
					   ;;
				-*)    # any other - argument
					   errMsg "--- UNKNOWN OPTION ---"
					   ;;
		     	 *)    # end of arguments
					   break
					   ;;
			esac
			shift   # next option
	done
	#
	# get infile and outfile
	infile="$1"
	outfile="$2"
fi

# test that infile provided
[ "$infile" = "" ] && errMsg "NO INPUT FILE SPECIFIED"

# test that outfile provided
[ "$outfile" = "" ] && errMsg "NO OUTPUT FILE SPECIFIED"


# set up temp files
tmpA1="$dir/slantedlight_A_$$.mpc"
tmpA2="$dir/slantedlight_A_$$.cache"
tmpB1="$dir/slantedlight_B_$$.mpc"
tmpB2="$dir/slantedlight_B_$$.cache"
tmpC1="$dir/slantedlight_C_$$.mpc"
tmpC2="$dir/slantedlight_C_$$.cache"
trap "rm -f $tmpA1 $tmpA2 $tmpB1 $tmpB2 $tmpC1 $tmpC2;" 0
trap "rm -f $tmpA1 $tmpA2 $tmpB1 $tmpB2 $tmpC1 $tmpC2; exit 1" 1 2 3 15
trap "rm -f $tmpA1 $tmpA2 $tmpB1 $tmpB2 $tmpC1 $tmpC2; exit 1" ERR

# get im version
im_version=`convert -list configure | \
	sed '/^LIB_VERSION_NUMBER */!d; s//,/;  s/,/,0/g;  s/,0*\([0-9][0-9]\)/\1/g' | head -n 1`

# colorspace RGB and sRGB swapped between 6.7.5.5 and 6.7.6.7 
# though probably not resolved until the latter
# then -colorspace gray changed to linear between 6.7.6.7 and 6.7.8.2 
# then -separate converted to linear gray channels between 6.7.6.7 and 6.7.8.2,
# though probably not resolved until the latter
# so -colorspace HSL/HSB -separate and -colorspace gray became linear
# but we need to use -set colorspace RGB before using them at appropriate times
# so that results stay as in original script
# The following was determined from various version tests using softglow.
# with IM 6.7.4.10, 6.7.6.10, 6.8.0.7
if [ "$im_version" -lt "06070607" -o "$im_version" -gt "06070707" ]; then
	setcspace="-set colorspace RGB"
else
	setcspace=""
fi
# no need for setcspace for grayscale or channels after 6.8.5.4
if [ "$im_version" -gt "06080504" ]; then
	setcspace=""
fi


# read input image
convert -quiet "$infile" $setcspace +repage $tmpA1 ||
	errMsg  "--- FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE  ---"


angleArr=(`echo "$angles" | sed 's/[, ][, ]*/ /g'`)
intensityArr=(`echo "$intensities" | sed 's/[, ][, ]*/ /g'`)
distanceArr=(`echo "$distances" | sed 's/[, ][, ]*/ /g'`)
numa=${#angleArr[*]}
numi=${#intensityArr[*]}
numd=${#distanceArr[*]}
[ "$numa" = "" ] && errMsg "--- NO ANGLES SUPPLIED ---"
[ "$numi" = "" ] && errMsg "--- NO INTENSITIES SUPPLIED ---"
[ "$numd" = "" ] && errMsg "--- NO DISTANCES SUPPLIED ---"
[ $numi -gt $numa ] && errMsg "--- NUMBER OF INTENSITIES IS LARGER THAN NUMBER OF ANGLES ---"
[ $numi -gt $numd ] && errMsg "--- NUMBER OF DISTANCES IS LARGER THAN NUMBER OF ANGLES ---"

for ((i=0; i<numa; i++)); do
	if [ "${intensityArr[$i]}" = "" ]; then
		intensityArr[$i]=${intensityArr[0]}
	fi
	if [ "${distanceArr[$i]}" = "" ]; then
		distanceArr[$i]=${distanceArr[0]}
	fi
done
	
	
if [ "$smooth" = "0" ]; then
	smoothing=""
else
	smoothing="-blur 0x$smooth"
fi


# get mask of top percent closest to white
# approximated using negated saturation and brightness channels multiplied
convert $tmpA1 -colorspace HSB -channel G -negate -channel GB -separate +channel \
		-compose multiply -composite -contrast-stretch 0,${percent}% \
		-fill black +opaque white $smoothing $tmpB1
		

# set up auto level
if [ "$im_version" -lt "06050501" ]; then
	getMinMax $tmpA1
	autoleveling="-level $min%,$max%"
else
	autoleveling="-auto-level"
fi

# process mask into slanted lights
convert $tmpB1 -fill black -colorize 100% $tmpC1	
for ((i=0; i<numa; i++)); do
	angle=${angleArr[$i]}
	[ $angle -lt 0 -o $angle -gt 360 ] && errMsg "--- ANGLE VALUES MUST BE BETWEEN 0 AND 360 ---" 
	intensity=`convert xc: -format "%[fx:${intensityArr[$i]}/100]" info:`
	distance=${distanceArr[$i]}
	angle=`convert xc: -format "%[fx:mod(($angle+180),360)]" info:`
#	echo "angle=$angle; intensity=$intensity; distance=$distance;"
	convert $tmpC1 \
		\( $tmpB1 -motion-blur 0x${distance}+$angle $autoleveling -evaluate multiply $intensity \) \
		-compose lighten -composite $tmpC1
done


convert $tmpA1 \
	\( -clone 0 -fill $color -colorize 100% \) $tmpC1 \
	-compose over -composite "$outfile"
		
exit 0

