#@gmic
#
#  File        : gmic_def.gmic
#                ( G'MIC default custom commands )
#
#  Description : Define recognized commands for the G'MIC interpreter
#                and available filters for GIMP plug-in.
#                ( http://gmic.sourceforge.net )
#
#                This file is also a part of the CImg Library project.
#                ( http://cimg.sourceforge.net )
#
#  Location    : If you are using the G'MIC plug-in for GIMP, and made
#                a filter refresh via Internet, then a copy of this file
#                should be found in the folder :
#
#                  $HOME/.gmic_def.xxxx    (on Unix-based OS).
#                  %APPDATA/.gmic_def.xxxx (on Windows-based OS).
#
#  Usage       : gmic [-m gmic_def.gmic] (...)
#
#  Copyright   : David Tschumperle
#                ( http://www.greyc.ensicaen.fr/~dtschump/ )
#
#  License     : CeCILL v2.0
#                ( http://www.cecill.info/licences/Licence_CeCILL_V2-en.html )
#
#  This software is governed by the CeCILL  license under French law and
#  abiding by the rules of distribution of free software.  You can  use,
#  modify and/ or redistribute the software under the terms of the CeCILL
#  license as circulated by CEA, CNRS and INRIA at the following URL
#  "http://www.cecill.info".
#
#  As a counterpart to the access to the source code and  rights to copy,
#  modify and redistribute granted by the license, users are provided only
#  with a limited warranty  and the software's author,  the holder of the
#  economic rights,  and the successive licensors  have only  limited
#  liability.
#
#  In this respect, the user's attention is drawn to the risks associated
#  with loading,  using,  modifying and/or developing or reproducing the
#  software by the user in light of its specific status of free software,
#  that may mean  that it is complicated to manipulate,  and  that  also
#  therefore means  that it is reserved for developers  and  experienced
#  professionals having in-depth computer knowledge. Users are therefore
#  encouraged to load and test the software's suitability as regards their
#  requirements in conditions enabling the security of their systems and/or
#  data to be ensured and,  more generally, to use and operate it in the
#  same conditions as regards security.
#
#  The fact that you are presently reading this means that you have had
#  knowledge of the CeCILL license and that you accept its terms.
#

#------ Syntax rules for a G'MIC command file :
#
#*** General syntax :
#
# - Each line starting with 'command_name :' starts a new G'MIC custom command definition.
# - Each line starting with '#' is a comment line.
# - Any other line is considered as the continuation of a previously started G'MIC custom command.
#
#*** Rules for 'gmic' (command-line interpreter) :
#
# - A comment line starting with '#@gmic' will be parsed by 'gmic' in order to display help for
#    G'MIC custom commands (when invoked with option '-h'). More precisely :
#
#      _ '#@gmic :: section' puts a new section separator in the displayed help.
#      _ '#@gmic command : arguments : description' starts a new command description
#      _ '#@gmic : description' add a new line to the last command description.
#
#*** Rules for 'gmic_gimp' (plug-in for GIMP) :
#
# - A comment line starting with '#@gimp' will be parsed by the GIMP plug-in to define the filter tree.
# - A comment line starting with '#@gimp_xx' will define a filter only for a specific language 'xx'
#    (e.g. 'en','fr'...).
# - More precisely, the syntax of a '#@gimp' comment line is be :
#
#    '#@gimp Group name'
#
# or
#
#    '#@gimp Command name : command, preview_command, parameter = typedef, parameter2 = typedef'
#    '#@gimp : parameter3 = typedef, parameter4 = typedef ...., parameterN = typedef'
#
#   where :
#
#      'command' is the G'MIC command name called to process the image.
#
#      'preview_command' is the G'MIC command name called to process the preview.
#
#           Note that you can optionally specify a float-valued factor>=0 between parentheses at the end of
#           the 'preview_command' to force the default zoom factor used by the GIMP preview for this filter.
#           Use (0) for a 1:1 preview, (1) for previewing the whole image, (2) for 1/2 image and so on...
#
#      'parameter = typedef' tells about the names, types and default values of the filter parameters.
#
#           'typedef' can be :
#
#      _ 'float(default_value,min_value,max_value)'       : Add a float-valued parameter (as a GUI float slider).
#      _ 'int(default_value,min_value,max_value)'         : Add a integer parameter (as a GUI integer slider).
#      _ 'bool(default_value={ 0 | 1 | false | true })'   : Add a boolean parameter (0 or 1) (as a GUI checkbutton).
#      _ 'choice(_default_indice,Choice0,..,ChoiceN)'     : Add a integer parameter (as a GUI combobox).
#      _ 'text(_default text)'                            : Add a text parameter (as a GUI text entry).
#      _ 'file(_default_filename)'                        : Add a filename parameter (as a GUI filechooser).
#      _ 'folder(_default_foldername)'                    : Add a foldername parameter (as a GUI folderchooser).
#      _ 'color(defaultR,defaultG,defaultB,_defaultA)'    : Add R,G,B[,A] parameters (as a GUI colorchooser).
#      _ 'note(_label)'                                   : Display a label, but do not add a new parameter.
#      _ 'link(_alignement,_label,URL)'                   : Display a label that link to a specified URL.
#      _ 'separator()'                                    : Display an horizontal separator.
#
#   Type separators '()' can be replaced by '[]' or '{}' if necessary (for instance if parentheses are required in
#   an argument of the typedef, e.g in a text). You can also replace 'typedef' by '_typedef' to tell the plug-in not
#   to update the image preview when the corresponding parameter is modified.
#
#   Use '_none_' as a special command or preview_command to tell the plug-in that the entry requires no G'MIC call.
#
#-----------------------------------------------------------------------------------------------------------------------

#---------------------------------
#
#@gmic :: Basic pixel manipulation
#
#---------------------------------

#@gmic replace_nan : _expression
#@gmic : Replace all NaN values in selected images by specified expression.
replace_nan : -skip ${1=0}
  -e[^-1] "Replace all NaN in image$? by expression $1"
  -v - -f if(i==i,i,$1) -v +

#@gmic replace_inf : _expression
#@gmic : Replace all infinite values in selected images by specified expression.
replace_inf : -skip ${1=0}
  -e[^-1] "Replace all infinite values in image$? by expression $1"
  -v - -f if(i==i+1,$1,i) -v +

#@gmic roundify : _gamma>=0
#@gmic : Apply roundify transformation on float-valued data, with specified gamma.
roundify : -check "$1>=0"
  -e[^-1] "Roundify image$?, with gamma $1."
  -if {$1==1} -return -endif
  -v - -repeat @#
    --round[-1] 1 --[-2] [-1]
    --*[-2] 2 -abs[-1] -pow[-1] $1 -sign[-3] -*[-3,-1] -*[-2] 0.5 -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic complex2polar
#@gmic : Compute complex to polar transforms of selected images.
complex2polar :
  -e[^-1] "Compute complex to polar transforms of image$?."
  -v - -repeat {int(@#/2)}
    -r[-1] [-2],3 --atan2[-1] [-2] -sqr[-3,-2] -+[-3,-2] -sqrt[-2]
  -mv[-2,-1] 0 -done -v +

#@gmic polar2complex
#@gmic : Compute polar to complex transforms of selected images.
polar2complex :
  -e[^-1] "Compute polar to complex transforms of image$?."
  -v - -repeat {int(@#/2)}
    -r[-1] [-2],3 --sin[-1] -cos[-2] -*[-1] [-3] -*[-3,-2]
  -mv[-2,-1] 0 -done -v +

#@gmic plot2value
#@gmic : Retrieve values from selected 2d graph plots.
plot2value :
  -e[^-1] "Retrieve values from 2d graph plot$?."
  -v - -t 50%
  -repeat @#
    (1,{w}) -r[-1] [-2],3 -*[-2,-1] -histogram[-1] {w},1,{w}
  -mv[-1] 0 -done -v +

#@gmic transfer_histogram
#@gmic : Transfer histogram of the last selected image to the other ones.
transfer_histogram :
  -e[^-1] "Transfer histogram of the last selected image to image$?."
  -v - -to_rgb -c 0,255 -equalize[0--2] 256 --histogram_cumul[-1] 256 -/[-1] @{-3,#} -*[-1] 255
  -repeat @#-2
    -s[-3] c -index[-5--3] [-1] -a[-5--3] c
  -mv[-3] 0 -done -rm[-1] -v +

#@gmic normalize_sum
#@gmic : Normalize selected images with a unitary sum.
normalize_sum :
  -e[^-1] "Normalize image$? with a unitary sum."
  -v - -repeat @#
    (@{-1,+}) -if {@-1>0} -/[-2] @-1 -endif -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic apply_gamma : gamma
#@gmic : Apply gamma correction to selected images.
apply_gamma : -skip ${1=1.2}
  -e[^-1] "Apply Gamma-correction to image$?, with gamma $1."
  -if {$1==1} -return -endif
  -v - -repeat @#
    (@{-1,m},@{-1,M}) -n[-2] 0,1 -pow[-2] {1/$1} -n[-2] @-1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic apply_curve : 0<=smoothness<=1,x0,y0,x1,y1,x2,y2,...,xN,yN
#@gmic : Apply curve transformation to image values.
apply_curve : -check "${1=1}>=0 && $1<=1" -skip ${2=0},${3=100}
  -e[^-1] "Apply intensity curve with smoothness $1 and keypoints (${2--1}) on image$?."
  -v - -function1d ${1--1} -map[0--2] [-1] -rm[-1] -v +

#@gmic negative
#@gmic : Compute negative of selected images.
negative :
  -e[^-1] "Compute negative of image$?."
  -v - -repeat @# --[-1] @{-1,M} -mv[-1] 0 -done -* -1 -v +

#@gmic tones : N>0
#@gmic : Get N tones masks from selected images.
tones : -skip ${1=3}
  -e[^-1] "Get $1 tones masks from image$?."
  -v - -norm -n 0,100000 -round 1 -repeat @#
    t0=0 -repeat {$1-1} t1={round((~>+1)*100000/$1-1)} --t2[{-1-~>}] $t0,$t1 t0=$t1+1 -done
    -t2[-$1] $t0,100% -mv[-$1] @#
  -mv[-$1--1] 0 -done -v +

#@gmic t2 : eq. to '-threshold2'.
t2 :
  -threshold2 ${^0}

#@gmic threshold2 : _min[%],_max[%]
#@gmic : Threshold selected images between the two given values.
#@gmic : (eq. to '-t2').
threshold2 :
  -e[^-1] "Hard-threshold image$? between values $1 and $2."
  -v - -repeat @#
    _t1=$1 _t2=$2
    -if {arg(-1,{'$1'})=={'%'}} _t1={im+(iM-im)*$1} -endif
    -if {arg(-1,{'$2'})=={'%'}} _t2={im+(iM-im)*$2} -endif
    t1={min($_t1,$_t2)} t2={max($_t1,$_t2)}
    --[-1] {($t1+$t2)/2} -abs[-1] -*[-1] -1 -t[-1] {($t1-$t2)/2}
  -mv[-1] 0 -done -v +

#@gmic chessboard : size1>0,_size2>0,_offset1,_offset2,_angle,_opacity,_color1,..,_color2,..
#@gmic : Draw chessboard on selected images.
chessboard : -check "${1=32}>0 && ${2=$1}>0" -skip ${3=0},${4=0},${5=0},${6=1},${7=0},${8=255}
  -e[^-1] "Draw chessboard on image$?, with sizes ($1,$2), offsets ($3,$4), angle $5 and opacity $6."
  -v - -i[0] (${7--1}) -r[0] {@{0,w}/2},1,1,2,-1 -permute[0] cyzx
  -repeat {@#-1}
    -p[0] {w} -p[1] {h} -p[2] {s} -p[3] {$5*pi/180}
    ($3,{$3+~0-1};$3,{$3+~0-1}^$4,$4;{$4+~1-1},{$4+~1-1}) -r[-1] ~0,~1,1,2,3
    -r[-1] {~0*~1},2,1,1,-1
    -i[-2] ({cos(~3)},{-sin(~3)};{sin(~3)},{cos(~3)}) -**[-2,-1]
    -r[-1] ~0,~1,1,2,-1
    -mod[-1] {$1+$2} ->=[-1] $1 -s[-1] c -xor[-2,-1] -map[-1] [0] -r[-1] 100%,100%,1,[-2]
    -image[-2] [-1],0,0,0,0,$6 -rm[-1]
  -mv[-1] 1 -done -rm[0] -v +

#@gmic polka_dots : _diameter,_density,_offset1,_offset2,_angle,_aliasing,_shading,_opacity,_color,...
#@gmic : Draw dots pattern on selected images.
polka_dots : -check "${1=10}>=0 && ${2=20}" -skip ${3=50},${4=50},${5=0},${6=10},${7=1},${8=1},${9=255}
  -e[^-1] "Draw polka dots on image$?, with diameter $1, density $2, angle $3, shift ($4,$5), aliasing $6 and shading $7."
  -v - theta={$5*pi/180} ct={cos($theta)} st={sin($theta)} mid1={$1/2} mid2={$2/2}
  -i[0] (${9--1}) -unroll[0] c
  -repeat {@#-1}
    WH={max(w,h)}
    100%,100%,100%,1,"xn = 100*x/"$WH"-$3; yn = 100*y/"$WH"-$4; \
                      xr = xn*"$ct"-yn*"$st"; yr = xn*"$st"+yn*"$ct"; \
                      xc = xr%$2-"$mid2"; yc = yr%$2-"$mid2"; \
                      "$mid1"-sqrt(xc*xc+yc*yc)"
    -*[-1] $6 -c[-1] 0,$7 -n[-1] 0,$8 (${9--1}) -unroll[-1] c -r[-1] [-2],[-2],[-2]
    -image[-3] [-1],0,0,0,0,1,[-2] -rm[-2,-1]
  -mv[-1] 1 -done -rm[0] -v +

#---------------------------------
#
#@gmic :: Geometric manipulation
#
#---------------------------------

#@gmic split_tiles : M!=0,_N!=0,_is_homogeneous={ 0 | 1 }
#@gmic : Split selected images as a MxN array of tiles.
split_tiles : -skip $1,${2=$1},${3=0}
  -if $3 -e[^-1] "Split image$? as an array of homogeneous tiles, with (M,N) = ($1,$2)."
  -else -e[^-1] "Split image$? as an array of tiles, with (M,N) = ($1,$2)."
  -endif
  -v - -repeat @#
    -l[-1] -s y,$2 -s x,$1 -if $3 -r [0],[0],100%,100%,0 -endif -endl
  -mv[{-$1*$2}--1] 0 -done -v +

#@gmic append_tiles : M>0,_N>0
#@gmic : Append MxN selected tiles as a new image.
append_tiles : -skip $1,${2=$1}
  -e[^-1] "Append $1x$2 tile$? as new image(s)."
  -v - -repeat {int(@#/($1*$2))} -l[{-$1*$2}--1]
    -repeat $2 -a[-$1--1] x -mv[-1] 0 -done -a y
  -endl -mv[-1] 0 -done -v +

#@gmic rr2d : eq. to '-resize_ratio2d'.
rr2d :
  -resize_ratio2d ${^0}

#@gmic resize_ratio2d : width>0,height>0,_mode={ 0=inside | 1=outside | 2=padded },0=<_interpolation_type<=6
#@gmic : Resize selected images while preserving their aspect ratio.
resize_ratio2d : -check "$1>0 && $2>0 && ${3=0}>=0 && $3<=2 && ${4=6}>=0 && $4<=6"
  -e[^-1] "Resize 2d image$? to $1x$2 with ratio-"\
          @{"-if {$3==0} -u inside -elif {$3==1} -u outside -else -u padded -endif"}\
          " mode and interpolation type $4."
  -v - -repeat @#
    -if {$3==0}   ratio={min($1/w,$2/h)}
    -elif {$3==1} ratio={max($1/w,$2/h)}
    -else         ratio={min($1/w,$2/h)}
    -endif
    -r[-1] {w*~ratio},{h*~ratio},100%,100%,$4
    -if {$3==2} -r[-1] $1,$2,100%,100%,0,0,0.5,0.5 -endif
  -mv[-1] 0 -done -v +

#@gmic r2dx : eq. to '-resize2dx'.
r2dx :
  -resize2dx ${^0}

#@gmic resize2dx : width>0,_interpolation_type={0,1,2,3,4,5}
#@gmic : Resize selected images along the X-axis, preserving 2d ratio.
#@gmic : (eq. to '-r2dx').
resize2dx : -check "$1>0 && ${2=2}>=0 && $2<=5"
  -e[^-1] "Resize 2d image$? to $1 pixels along the X-axis, preserving 2d ratio."
  -v - -repeat @#
    -r[-1] $1,{max(1,h*$1/w)},100%,100%,$2
  -mv[-1] 0 -done -v +

#@gmic r3dx : eq. to '-resize3dx'.
r3dx :
  -resize3dx ${^0}

#@gmic resize3dx : width>0,_interpolation_type={0,1,2,3,4,5}
#@gmic : Resize selected images along the X-axis, preserving 3d ratio.
#@gmic : (eq. to '-r3dx').
resize3dx : -check "$1>0 && ${2=2}>=0 && $2<=5"
  -e[^-1] "Resize 3d image$? to $1 pixels along the X-axis, preserving 3d ratio."
  -v - -repeat @#
    -r[-1] $1,{max(1,h*$1/w)},{max(1,d*$1/w)},100%,$2
  -mv[-1] 0 -done -v +

#@gmic r2dy : eq. to '-resize2dy'.
r2dy :
  -resize2dy ${^0}

#@gmic resize2dy : height>0,_interpolation_type={0,1,2,3,4,5}
#@gmic : Resize selected images along the Y-axis, preserving 2d ratio.
#@gmic : (eq. to '-r2dy').
resize2dy : -check "$1>0 && ${2=2}>=0 && $2<=5"
  -e[^-1] "Resize 2d image$? to $1 pixels along the Y-axis, preserving 2d ratio."
  -v - -repeat @#
    -r[-1] {max(1,w*$1/h)},$1,100%,100%,$2
  -mv[-1] 0 -done -v +

#@gmic r3dy : eq. to '-resize3dy'.
r3dy :
  -resize3dy ${^0}

#@gmic resize3dy : height>0,_interpolation_type={0,1,2,3,4,5}
#@gmic : Resize selected images along the Y-axis, preserving 3d ratio.
#@gmic : (eq. to '-r3dy').
resize3dy : -check "$1>0 && ${2=2}>=0 && $2<=5"
  -e[^-1] "Resize 3d image$? to $1 pixels along the Y-axis, preserving 3d ratio."
  -v - -repeat @#
    -r[-1] {max(1,w*$1/h)},$1,{max(1,d*$1/h)},100%,$2
  -mv[-1] 0 -done -v +

#@gmic r3dz : eq. to '-resize3dz'.
r3dz :
  -resize3dz ${^0}

#@gmic resize3dz : depth>0,_interpolation_type={0,1,2,3,4,5}
#@gmic : Resize selected images along the Z-axis, preserving 3d ratio.
#@gmic : (eq. to '-r3dz').
resize3dz : -check "$1>0 && ${2=2}>=0 && $2<=5"
  -e[^-1] "Resize 3d image$? to $1 pixels along the Z-axis, preserving 3d ratio."
  -v - -repeat @#
    -r[-1] {max(1,w*$1/d)},{max(1,h*$1/d)},$1,100%,$2
  -mv[-1] 0 -done -v +

#@gmic upscale_smart : width,height,_depth,smoothness>=0,_anisotropy=[0,1],sharpening>=0
#@gmic : Upscale selected images with an edge-preserving algorithm.
upscale_smart : -skip ${2=100%},${3=100%} -check "${4=2}>=0 && ${5=0.4}>=0 && $5<=1 && ${6=10}>=0"
  -e[^-1] "Upscale image$? to $1x$2x$3, with smoothness $4, anisotropy $5 and sharpening $6."
  -v - -repeat @#
    -p {w} -p {h}
    --edgetensors 0,$5,1.2,1.2
    -r[-2,-1] $1,$2,$3,100%,5
    -if {w<~-2" || "h<~-1}  # Test for downscaling
      -rm[-1] -f[-1] 0
    -else
      -smooth[-2] [-1],$4 -rm[-1]
      -apply_channels "-sharpen[-1] $6,1,10",3,0
    -endif
    -pp[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic expand_x : size_x>=0,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the X-axis.
expand_x : -check "$1>=0 && ${2=1}>=0 && $2<=2"
  -e[^-1] "Expand image$? along the X-axis with size $1 and border conditions $2."
  -v - -repeat @# -r[-1] {w+2*$1},100%,100%,100%,0,$2,0.5,0.5,0.5 -mv[-1] 0 -done -v +

#@gmic expand_y : size_y>=0,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the Y-axis.
expand_y : -check "$1>=0 && ${2=1}>=0 && $2<=2"
  -e[^-1] "Expand image$? along the Y-axis with size $1 and border conditions $2."
  -v - -repeat @# -r[-1] 100%,{h+2*$1},100%,100%,0,$2,0.5,0.5,0.5 -mv[-1] 0 -done -v +

#@gmic expand_z : size_z>=0,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the Z-axis.
expand_z : -check "$1>=0 && ${2=1}>=0 && $2<=2"
  -e[^-1] "Expand image$? along the Z-axis with size $1 and border conditions $2."
  -v - -repeat @# -r[-1] 100%,100%,{d+2*$1},100%,0,$2,0.5,0.5,0.5 -mv[-1] 0 -done -v +

#@gmic expand_xy : size>=0,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the XY-axes.
expand_xy : -check "$1>=0 && ${2=1}>=0 && $2<=2"
  -e[^-1] "Expand image$? along the XY-axes with size $1 and border conditions $2."
  -v - -repeat @# -r[-1] {w+2*$1},{h+2*$1},100%,100%,0,$2,0.5,0.5,0.5 -mv[-1] 0 -done -v +

#@gmic expand_xyz : size>=0,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the XYZ-axes.
expand_xyz : -check "$1>=0 && ${2=1}>=0 && $2<=2"
  -e[^-1] "Expand image$? along the XYZ-axes with size $1 and border conditions $2."
  -v - -repeat @# -r[-1] {w+2*$1},{h+2*$1},{d+2*$1},100%,0,$2,0.5,0.5,0.5 -mv[-1] 0 -done -v +

#@gmic shrink_x : size_x>=0
#@gmic : Shrink selected images along the X-axis.
shrink_x : -check "$1>=0"
  -e[^-1] "Shrink image$? along the X-axis with size $1."
  -v - -repeat @# -crop[-1] $1,{w-$1-1} -mv[-1] 0 -done -v +

#@gmic shrink_y : size_y>=0
#@gmic : Shrink selected images along the Y-axis.
shrink_y : -check "$1>=0"
  -e[^-1] "Shrink image$? along the Y-axis with size $1."
  -v - -repeat @# -crop[-1] 0,$1,100%,{h-$1-1} -mv[-1] 0 -done -v +

#@gmic shrink_z : size_z>=0
#@gmic : Shrink selected images along the Z-axis.
shrink_z : -check "$1>=0"
  -e[^-1] "Shrink image$? along the Z-axis with size $1."
  -v - -repeat @# -crop[-1] 0,0,$1,100%,100%,{d-$1-1} -mv[-1] 0 -done -v +

#@gmic shrink_xy : size>=0
#@gmic : Shrink selected images along the XY-axes.
shrink_xy : -check "$1>=0"
  -e[^-1] "Shrink image$? along the XY-axes with size $1."
  -v - -repeat @# -crop[-1] $1,$1,{w-$1-1},{h-$1-1} -mv[-1] 0 -done -v +

#@gmic elevate : _depth,_is_plain,_is_colored
#@gmic : Elevate selected 2d images into 3d volumes.
elevate : -check "${1=64}>0" -skip ${2=1},${3=1}
  -e[^-1] "Elevate 2d image$? into $1-slices volume(s)."
  -v - -r 100%,100%,1,100%
  -repeat @# -l[-1]
  --norm[0] -i 100%,100%,$1,{if($3,@{0,s},1)}
    -p @{-2,m} -p {@{-2,M}-~-1}
    -repeat $1
      -if $2
        --t[1] {~-2+~-1*(~>+1)/$1}
      -else
        --t2[1] {~-2+~-1*~>/$1},{~-2+~-1*(~>+1)/$1}
      -endif
      -r[-1] 100%,100%,1,[-2] -if $3 -*[-1] [0] -endif
      -image[-2] [-1],0,0,~> -rm[-1]
    -done
    -pp[-2,-1] -rm[0,1]
  -endl -mv[-1] 0 -done -v +

#-----------------------
#
#@gmic :: Input-Output
#
#-----------------------

#@gmic ow : eq. to '-outputw'.
ow :
  -outputw

#@gmic outputw
#@gmic : Output selected images by overwritting their original location.
#@gmic : (eq. to '-ow').
outputw :
  -if {@#>1} -e[0--3] "Output image$? as their initial location."
  -else -e[0--3] "Output image$? as its initial location."
  -endif
  -v - -repeat @# -o[~>] @{~>,n} -done -v +

#@gmic op : eq. to '-outputp'.
op : -skip ${1="_"}
  -outputp "$1"

#@gmic outputp : prefix
#@gmic : Output selected images as prefixed versions of their original filenames.
#@gmic : (eq. to '-op').
outputp : -skip ${1="_"}
  -if {@#>1} -e[0--3] "Output image$? as their initial locations, prefixed by '$1'."
  -else -e[0--3] "Output image$? as its initial location, prefixed by '$1'."
  -endif
  -v - -repeat @# -o[~>] @{~>,f}$1@{~>,b}.@{~>,x} -done -v +

#@gmic on : eq. to '-outputn'.
on :
  -outputn "$1"

#@gmic outputn : filename
#@gmic : Output selected images as automatically numbered filenames in repeat..done loops.
#@gmic : (eq. to '-on').
outputn :
  -v - -p[0] @{"-filename \"$1\","@{>}} -v +
  -e[^-1] "Output image$? as file '"~0"'."
  -v - -o ~0 -v +

#@gmic d0 : eq. to '-display0'.
d0 :
  -display0

#@gmic display0
#@gmic : Display selected images without value normalization.
#@gmic : (eq. to '-d0').
display0 :
  -v -
  -p[0] 0 -p[1] 0 -p[2] 0 -p[3] 0
  -repeat @#
    -p=[0] {~0+w}
    -p=[1] {max(~1,h)}
    -p=[2] {max(~2,d)}
    -p=[3] {max(~3,s)}
  -mv[-1] 0 -done
  -if {@#==1} -w -1,-1,0,0,@{0,n}\ (~0x~1x~2x~3)
  -elif {@#==2} -w -1,-1,0,0,@{0,n},@{-1,n}\ (~0x~1x~2x~3)
  -else -w -1,-1,0,0,@{0,n},..,@{-1,n}\ (~0x~1x~2x~3)
  -endif
  -v + -d
  -v - -w[] 0 -v +

#@gmic dfft : eq. to '-display_fft'.
dfft :
  -display_fft

#@gmic display_fft
#@gmic : Display fourier transform of selected images, with centered log-module and argument.
#@gmic : (eq. to '-dfft').
display_fft :
  -e[^-1] "Render fourier transform of image$? with centered log-module and argument."
  -v - -repeat @#
    -fftpolar[-1] -+[-2] 1 -log[-2] -n[-2,-1] 0,255 -a[-2,-1] x
  -mv[-1] 0 -done -s x,2 -v +

#@gmic drgba : eq. to '-display_rgba'.
drgba :
  -display_rgba

#@gmic display_rgba
#@gmic : Render selected RGBA images over a checkerboard background.
#@gmic : (eq. to '-drgba').
display_rgba :
  -e[^-1] "Render RGBA image$? over a checkerboard background."
  -v - -repeat @#
    -i[-2] (160,128;128,160) -r[-2] 16,16 -r[-2] [-1],[-1],1,3,0,2 -compose_rgba[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic dh : eq. to '-display_histogram'.
dh : -skip ${1=,}
  -display_histogram ${^0}

#@gmic display_histogram : _width>0,_height>0,_clusters>0,_max_value>0,_show_axes={ 0 | 1 }
#@gmic : Render a channel-by-channel histogram.
#@gmic : (eq. to '-dh').
display_histogram : -check "${1=512}>0 && ${2=200}>0 && ${3=256}>0 && ${4=255}" -skip ${5=1}
  -e[^-1] "Render $1x$2 channel-by-channel histogram of image$?, with $3 clusters and maximum value $4."
  -v -
  -repeat @#
    -l[-1] -s c -histogram $3,0,$4
    --max -p @{-1,M} -rm[-1]
    -repeat @#
      $1,$2,1,1,-255 -graph[-1] [-2],3,0,~-1,0,1,0,0
      -rm[-2]
    -mv[-1] 0 -done
    -a c
    -if $5 -axes[-1] 0,$4,~-1,0,1,-128 -endif
    -pp[-1]
    -endl
    -+[-1] 255
  -mv[-1] 0 -done -v +

#@gmic dt : eq. to '-display_tensors'.
dt : -skip ${1=,}
  -display_tensors ${^0}

#@gmic display_tensors :  _size_factor>0,_ellipse_factor>=0,_opacity,_pattern,_color1,..
#@gmic : Render field of 2x2 tensors with ellipses.
#@gmic : (eq. to '-dt').
display_tensors : -check "${1=16}>0 && ${2=0.9}>=0" -skip ${3=1},${4=255},${5=$4},${6=$5}
  -e[^-1] "Render field of 2x2 tensors with ellipses, from image$?."
  -v - -repeat @#
    -i[0] {$1*w},{$1*h},1,3
    -/[-1] {max(abs(im),abs(iM))}
    -repeat {h} -repeat {w}
      x=~>
      y=@{>,-2}
      a=@{-1,($x,$y,0,0)}
      b=@{-1,($x,$y,0,1)}
      c=@{-1,($x,$y,0,2)}
      ($a,$b;$b,$c) -eigen[-1]
      R=@{-2,0}
      r=@{-2,1}
      angle={atan2(@{-1,(0,1)},@{-1,(0,0)})*180/pi}
      -rm[-2,-1]
      -ellipse[0] {($x+0.5)*$1},{($y+0.5)*$1},{$2*$1*$R/2},{$2*$1*$r/2},$angle,${3--1}
    -done -done
  -rm[-1] -done -v +

#@gmic dg : eq. to '-display_graph'.
dg :  -skip ${1=,}
  -display_graph ${^0}

#@gmic display_graph : _width>32,_height>32,_plot_type,_vertex_type,_xmin,_xmax,_ymin,_ymax
#@gmic : Render graph plot from specified image data.
display_graph : -check "${1=640}>32 && ${2=480}>32" -skip ${3=1},${4=0},${5=0},${6=0},${7=0},${8=0}
  -e[^1] "Render graph plot from data of image$?."
  -v - -repeat @#

    # Determine xmin,xmax/ymin,ymax.
    one={$3!=3} siz={w*h*d}
    -if {$5==$6} xmin=0 xmax={$siz-$one} -else xmin={min($5,$6)} xmax={max($5,$6)} -endif
    -if {$7==$8} ymin={im} ymax={iM} -else ymin={min($7,$8)} ymax={max($7,$8)} -endif

    # Create plot canvas.
    gw={$1-32} gh={$2-32} gg={($gw-$one)/($siz-$one)}
    $gw,$gh,1,3,255
    -if {$siz<32} -grid[-1] $gg,$gg,0,0,0.25,0xCCCCCCCC,0
    -else -grid[-1] 10%,10%,0,0,0.25,0xCCCCCCCC,0
    -endif

    # Define color palette for curves.
    -if {@{-2,s}==1} (0,0,255)
    -elif {@{-2,s}<=3} (255,0,0;0,255,0;0,0,255)
    -else
      (0,255) -r[-1] 256,1,1,1,3 -map[-1] 2 -crop[-1] 2,100% -permute[-1] cxyz -r[-1] 3,{max(3,@{-3,s})},1,1,0,2
      -sh[-1] 0,2,0,0 -f[-1] 255,0,0,0,255,0,0,0,255 -rm[-1]
    -endif

    # Draw plot for each channel.
    -repeat @{-3,s} --sh[-3] ~>,~> -graph[-3] [-1],$3,$4,$ymax,$ymin,1,@{-2,0-2} -rm[-1] -shift[-1] 0,-1 -done
    -rm[-3,-1]
    -line[-1] 0,0,100%,0,1,110 -line[-1] 100%,0,100%,100%,1,110
    -line[-1] 100%,100%,0,100%,1,255 -line[-1] 0,100%,0,0,1,255
    -axes[-1] $xmin,{$xmin+($xmax-$xmin)*($siz-$one)/($siz-1)},$ymax,$ymin,1,0,0
    -frame[-1] 16,16,220
    1 -text[-1] "X-axis",0,0,13,1,-220,-220,-220 -image[-2] [-1],{(@{-2,w}-w)/2},{@{-2,h}-16},0,0,-1 -rm[-1]
    1 -text[-1] "Y-axis",0,0,13,1,-220,-220,-220 -rotate[-1] -90 -image[-2] [-1],2,{(@{-2,h}-h)/2},0,0,-1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic float2int8
#@gmic : Convert selected float-valued images to 8bits integer representations.
float2int8 :
  -e[^-1] "Convert float-valued image$? to 8bits integer representations."
  -v - -repeat @# -l[~>]
    -s c
    -repeat @#
      m=@{-1,m} M=@{-1,M} -quantize[-1] 16777216,0
      -->>[-1] 8 -and[-1] 255 --and[-2] 255 ->>[-3] 16
      ({'$m,$M'})
      -a[-4--1] y
    -mv[-1] 0 -done
    -a c
  -endl -done -v +

#@gmic int82float
#@gmic : Convert selected 8bits integer representations to float-valued images.
int82float :
  -e[^-1] "Convert 8bits integer representation$? to float-valued image$?."
  -v - -repeat @#
    -l[~>]
    -s c
    -repeat @#
      --sh[-1] {h-1},{h-1},0,0 m=@{-1,t} -rm[-1]
      -lines[-1] 0,{h-2} -s[-1] y,3 -*[-3] 65536 -*[-2] 256 -or[-3--1]
      -n[-1] $m
    -mv[-1] 0 -done
    -a c
  -endl -done -v +

#@gmic float2fft8
#@gmic : Convert selected float-valued images to 8bits fourier representations.
float2fft8 :
  -e[^-1] "Convert float-valued image$? to 8bits fourier representations."
  -v - -repeat @#
    -fftpolar[-1] -+[-2] 1 -log[-2] -float2int8[-2,-1] -a[-2,-1] y
  -mv[-1] 0 -done -v +

#@gmic fft82float
#@gmic : Convert selected 8bits fourier representations to float-valued images.
fft82float :
  -e[^-1] "Convert float-valued image$? to 8bits fourier representations."
  -v - -repeat @#
    -s[-1] y,2 -int82float[-2,-1] -exp[-2] --[-2] 1 -ifftpolar[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic apply_camera : _command,_camera_index>=-1,_skip_frames>=0
#@gmic : Apply specified command on live camera stream, and display it on display window [0].
apply_camera : -skip "${1=-skip 1}" -check "${2=-1}>=-1 && ${3=0}>=0"
  -v - -if {$2==-1} stream=\#default -else stream=\#$2 -endif
  -v + -e[^-1] "Apply command '$1' on camera stream "$stream", with $3 frames skip." -v -
  -l[] -do
    -camera $2,1,$3 $1 -w[-1] -1,-1,-1,-1,"(Camera "$stream", "{w}x{h}")"
    -if @{!,S} -o[-1] gmic_camera.png -endif
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,D}} -w[] {@{!,w}*1.5},{@{!,h}*1.5} -wait -1 -endif # Increase window size.
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,C}} -w[] {@{!,w}/1.5},{@{!,h}/1.5} -wait -1 -endif # Decrease window size.
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,R}} -w[] @{0,w},@{0,h} -wait -1 -endif             # Reset window size.
    -rm[-1]
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}} -endl -v +

#@gmic rainbow_lut
#@gmic : Generate a 256-entries RGB colormap of rainbow colors.
rainbow_lut :
  -e[^-1] "Generate RGB colormap of rainbow colors."
  -v -
  (2,10,13,13,15,16,15,15,18,23,26,31,33,37,38,39,42,42,44,45,44,44,45,45,44,42,44,45,45,49,50,52,54,55,56,57,56,56,57,57,58,57,58,58,59,58,60,59,58,59,59,59,59,59,60,60,59,59,59,59,60,59,59,59,59,59,59,59,58,58,58,56,56,54,51,48,44,39,33,20,5,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,25,50,66,81,90,102,109,118,129,137,144,152,158,168,178,183,190,199,207,213,220,227,230,236,242,246,250,255,255,253,253,253,252,251,250,250,249,248,248,247,248,246,246,246,245,246,245,245,245,246,246,246,246,246,246,246,246,245,245,245,245,245,244,245,244,245,245,245,245,245,245,245,245,245,244,244,245,245,243,239,235,230,226,220,216,211,204,201,194,190,184,176,171,164,160,152,144,138,130,122,114,107,96,87,78,69,57,50,46,38,31,19,5^3,10,14,15,17,18,19,18,19,23,25,30,31,35,37,39,42,44,45,48,49,50,51,52,53,56,59,63,66,66,68,69,71,73,74,75,76,76,77,78,79,79,80,81,81,82,82,83,84,84,84,84,84,85,85,86,86,86,86,87,88,87,86,86,86,86,88,89,89,90,92,92,94,96,99,102,104,107,111,117,120,126,130,136,142,149,155,161,167,172,176,178,179,179,178,178,178,178,177,177,177,176,176,176,176,175,173,173,174,173,172,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,171,173,173,173,175,176,178,178,178,181,182,184,186,186,190,192,193,195,198,200,201,204,206,209,211,208,206,202,197,194,190,185,182,178,172,167,162,157,152,144,139,132,127,121,115,108,102,98,92,87,79,75,69,64,62,58,55,52,50,49,47,47,47,47,47,47,47,47,46,46,46,46,45,44,44,42,42,41,41,40,39,38,37,36,34,31,30,29,30,30,31,32,32,32,33,33,34,34,33,34,33,32,31,31,30,29,26,25,23,21,19,15,13,13,16,18,18,18,17,15,13,12,9,2^6,19,25,32,41,49,55,65,71,79,84,90,96,102,106,111,117,121,128,132,134,139,143,146,149,152,155,156,157,159,159,160,161,162,163,164,164,165,166,167,166,165,166,166,167,167,168,168,168,169,169,169,169,170,170,170,170,170,170,170,171,170,170,170,170,170,171,171,172,173,173,173,175,177,179,180,183,185,187,190,193,198,201,206,213,219,225,227,227,223,218,214,204,199,192,184,179,172,168,162,156,151,145,139,133,126,120,113,106,98,90,85,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,82,84,84,82,82,82,82,82,83,83,81,81,81,80,80,78,78,78,76,74,73,73,71,72,69,68,67,65,62,59,58,56,51,50,49,45,43,40,38,37,35,32,31,32,32,33,33,34,34,35,36,36,37,38,39,42,44,45,46,46,47,48,49,48,48,48,48,48,48,48,48,48,48,47,47,47,47,46,45,45,43,43,42,41,40,39,38,37,38,38,37,37,38,38,38,38,39,40,39,40,39,40,40,39,39,38,38,37,35,34,32,30,28,26,23,20,16,14,12,16,16,18,18,17,16,14,13,9,2)
  -v +

#-------------------------------------
#
#@gmic :: Image creation and drawing
#
#-------------------------------------

#@gmic ball : _R,_G,_B
#@gmic : Draw a colored RGBA ball sprite on selected images.
ball : -skip ${1=255},${2=$1},${3=$2}
  -e[^-1] "Draw ball sprite on image$?, with color ($1,$2,$3)."
  -v - -to_rgba
  -repeat @#
    -p[0] {min(w,h)}
    --sh[-1] 3,3 -f[-1] 0 -rm[-1]
    -ellipse[-1] {0.5*~0},{0.5*~0},{0.5*~0-4},{0.5*~0-4},0,1,$1,$2,$3,1
    --sh[-1] 0,2 -*[-1] '(~0+y-x)/(2*w)' -rm[-1]
    -ellipse[-1] {~0*0.7},{~0*0.3},{min(30,~0*~0/512)},{min(30,~0*~0/512)},0,{min(~0/64,1)},255,255,255,1
    --sh[-1] 0,2 -blur[-1] {0.02*~0} -rm[-1]
    --sh[-1] 3,3 -*[-2] [-1] -dilate[-1] 3 -rm[-1]
    --sh[-1] 0,2 -+[-1] 'if(i&&(!i(x-1)||!i(x+1)||!i(x,y-1)||!i(x,y+1)),if(c==0,$1,if(c==1,$2,$3))/6,0)' -rm[-1]
    -pp[0]
  -mv[-1] 0 -done -v +

#@gmic sierpinski : recursion_level>=0
#@gmic : Draw Sierpinski triangle on selected images.
sierpinski : -check ${1=7}>=0 -skip ${2=50},${3=0},${4=0},${5=100},${6=100},${7=100}
  -e[^-1] "Draw Sierpinski triangle of degree $1 on image$?."
  -v - -_sierpinski ${2-7},$1  -v +

_sierpinski :
  -if {$7<=0} -polygon 3,$1%,$2%,$3%,$4%,$5%,$6%,1,255 -return -endif
  -_sierpinski $1,$2,{($1+$3)/2},{($2+$4)/2},{($1+$5)/2},{($2+$6)/2},{$7-1}
  -_sierpinski {($1+$3)/2},{($2+$4)/2},$3,$4,{($3+$5)/2},{($4+$6)/2},{$7-1}
  -_sierpinski {($1+$5)/2},{($2+$6)/2},$5,$6,{($3+$5)/2},{($4+$6)/2},{$7-1}

#@gmic text_outline : text,_x[%],_y[%],_font_height>0,_outline>=0,_opacity,_color1,..
#@gmic : Draw specified colored and outlined text string on selected images.
text_outline : -skip ${2=2},${3=2},${4=13},${5=2},${6=1},${7=255},${8=$-1},${9=$-1}
  -e[^-1] "Draw outlined text '$1' at position ($2,$3) on image$?, with font height $4, outline $5, opacity $6 and color ${7--1}."
  -v -
  -if $5
    1 -text[-1] "$1",0,0,$4,1,1 -expand_xy[-1] {1+$5},0 --dilate[-1] {2*$5+1}
    (${7--1}) -unroll[-1] c -r[-1] 2,1,1,100%,0,0,1 -map[-3] [-1] -rm[-1]
    -repeat {@#-2} -image[~>] [-2],$2,$3,0,0,$6,[-1] -done -rm[-2,-1]
  -else
    -text "$1",${2-4},${6--1}
  -endif
  -v +

#@gmic histogram_cumul : _nb_levels>0,_is_normalized={ 0 | 1 }
#@gmic : Compute cumulative histogram of selected images.
histogram_cumul : -check ${1=256}>0 -skip ${2=0}
  -if $2 -e[^-1] "Compute normalized cumulative histogram of image$?, using $1 levels."
  -else -e[^-1] "Compute cumulative histogram of image$?, using $1 levels." -endif
  -v - -histogram $1 -repeat @#
    -i[-2] [-1],1,1,1,0 -repeat {w} -+[-2] [-1] -shift[-1] 1 -done -rm[-1]
    -if $2 -/[-1] @{-1,M} -endif
  -mv[-1] 0 -done -v +

#@gmic direction2rgb
#@gmic : Compute RGB representation of selected 2d direction fields.
direction2rgb :
  -e[^-1] "Compute RGB representation of 2d direction field$?."
  -v - -repeat @#
    -channels[-1] 0,1 -s[-1] c -complex2polar[-2,-1]
    -*[-1] 128 -/[-1] 3.14159265359 -+[-1] 256 -mod[-1] 256 -map[-1] 1
    -to_rgb[-2] -n[-2] 0,1 -*[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic vector2tensor
#@gmic : Convert selected vector fields to corresponding diffusion tensor fields.
vector2tensor :
  -e[^-1] "Convert vector field$? to diffusion tensor field$?."
  -v - -repeat @# -l[-1]
    -s c
    -if {@#==2} --sqr[-1] -*[-2] [-3] -sqr[-3]
    -elif {@#==3} --sqr[-2] --*[-3] [-2] --sqr[-3] -*[-5,-4] [-6] -sqr[-6]
    -else -error[] "Invalid image : Dimensions "{w}","{h}","{d}","{s}" does not represent a field of 2d or 3d vectors."
    -endif
    -a c
  -endl -mv[-1] 0 -done -v +

#@gmic rgb2bayer : _start_pattern=0,_color=0
#@gmic : Transform selected color images to RGB-Bayer sampled images.
rgb2bayer : -skip ${1=0},${2=0}
  -if $2 -e[^-1] "Transform image$? to a RGB-Bayer color grid, starting from pattern '$1'."
  -else -e[^-1] "Transform image$? to a RGB-Bayer monochrome grid, starting from pattern '$1'."
  -endif
  -v - -to_rgb -repeat @#
    -_rgb2bayer$1 -r[-1] [-2],0,2 -*[-2,-1]
    -if $2 -else -s[-1] c -+[-3--1] -endif
  -mv[-1] 0 -done -v +

_rgb2bayer0 : (1,0;0,0^0,1;1,0^0,0;0,1)
_rgb2bayer1 : (0,0;0,1^0,1;1,0^1,0;0,0)
_rgb2bayer2 : (0,0;1,0^1,0;0,1^0,1;0,0)
_rgb2bayer3 : (0,1;0,0^1,0;0,1^0,0;1,0)

#@gmic bayer2rgb : _GM_smoothness,_RB_smoothness1,_RB_smoothness2
#@gmic : Transform selected RGB-Bayer sampled images to color images.
bayer2rgb : -skip ${1=1},${2=1},${3=0.5}
  -e[^-1] "Transform RGB-Bayer image$? to color images, with smoothness ($1,$2,$3)."
  -v - -channels 0 -repeat @#

    # Expand image size to avoid problems with borders.
    -expand_x[-1] {"2 + 4*$1"},0 -expand_y[-1] {"2 + 4*$1"},0

    # Compute green-magenta chromaticity.
    (-1,1;1,-1) -r[-1] [-2],[-2],1,1,0,2
    --*[-2] [-1]

    (0.25,0.5,0.25) -convolve[-2] [-1] -transpose[-1] -convolve[-2] [-1] -rm[-1]
    -blur[-1] $1

    -*[-2] [-1]
    --[-3,-2]

    # Compute red-blue chromaticity.
    (1,-1) -r[-1] [-2],[-2],1,1,0,2  # Horizontal estimate
    -*[-1] [-3]
    (0.25,0.5,0.25) -convolve[-2] [-1] -transpose[-1] -convolve[-2] [-1] -rm[-1]
    -blur_y[-1] $2 -blur_x[-1] $3

    (1;-1) -r[-1] [-2],[-2],1,1,0,2  # Vertical estimate
    -*[-1] [-4]
    (0.25,0.5,0.25) -convolve[-2] [-1] -transpose[-1] -convolve[-2] [-1] -rm[-1]
    -blur_x[-1] $2 -blur_y[-1] $3

    -+[-2,-1] -/[-1] 2

    # Luminance reconstruction.
    (2,0;0,-2) -r[-1] [-2],[-2],1,1,0,2
    -*[-1] [-2]
    --[-4,-1]

    # RGB reconstruction.
    -a[-3--1] c
    -mix_rgb[-1] 1,-1,2,1,1,0,1,-1,-2

    # Shrink to original image size.
    -shrink_x[-1] {"2 + 4*$1"},0 -shrink_y[-1] {"2 + 4*$1"},0
    -c[-1] 0,255

  -mv[-1] 0 -done -v +

#@gmic lic : _amplitude>0,_channels>0
#@gmic : Generate LIC representation of vector field.
lic : -skip ${1=30},${2=1}
  -e[^-1] "Generate LIC representation of 2d vector field$?, with amplitude $1 and $2 channel(s)."
  -v - -repeat @#
     -channels[-1] 0,1 -/[-1] {max(abs(@{-1,m}),abs(@{-1,M}))} -vector2tensor[-1]
     100%,100%,100%,$2 -rand[-1] 0,255 -smooth[-1] [-2],$1 -rm[-2]
     -equalize[-1] 256
  -mv[-1] 0 -done -v +

#@gmic gaussian : _sigma1[%],_sigma2[%],_angle
#@gmic : Draw a centered gaussian on selected images, with specified standard deviations and orientation.
gaussian : -skip ${1=3},${2=$1},${3=0}
  -e[^-1] "Draw centered gaussian on image$? with standard deviations ($1,$2) and angle $3°."
  -v -
  -p[0] {cos($3*pi/180)} -p[1] {sin($3*pi/180)}         # Push unit direction vector in stack (~0,~1).
  -if {isval($1)} -p[2] {-1/(0.1+2*$1^2)}               # Push opposite and inverse of standard deviation 1 in ~2.
  -else -p[2] {-1/(0.1+2*((${1}10000)*max(w,h)/100)^2)}
  -endif
  -if {isval($2)} -p[3] {-1/(0.1+2*$2^2)}               # Push opposite and inverse of standard deviation 2 in ~3.
  -else -p[3] {-1/(0.1+2*((${2}10000)*max(w,h)/100)^2)}
  -endif
  -repeat @#
    -p {w} -p {h} -rm[-1]
    (-~-2,~-2) (-~-1;~-1) -/[-2,-1] 2
    -r[-2,-1] ~-2,~-1,1,1,3 -pp[-2,-1]                  # x y
    --*[-2,-1] -sqr[-3,-2]                              # x^2 y^2 xy
    -*[-3] {(~0)^2*~2+(~1)^2*~3}                        # x^2(u^2/s1+v^2/s2) y^2 xy
    -*[-2] {(~1)^2*~2+(~0)^2*~3}                        # x^2(u^2/s1+v^2/s2) y^2(v^2/s1+u^2/s2) xy
    -*[-1] {2*(~0)*(~1)*(~2-~3)}                        # x^2(u^2/s1+v^2/s2) y^2(v^2/s1+u^2/s2) 2uvxy(1/s1-1/s2)
    -+[-3--1] -exp[-1]
  -mv[-1] 0 -done -v +

#@gmic function1d : 0<=smoothness<=1,x0,y0,x1,y1,...,xn,yn
#@gmic : Generate continuous 1d function from specified list of keypoints (xk,yk)
#@gmic : in range [0,max(xk)] (xk are integers).
function1d : -check "${1=1}>=0 && $1<=1" -skip ${2=0},${3=0}
  -e[^-1] "Generate continuous 1d function, with smoothness $1 and keypoints (${2--1})."
  -v -

  # Normalize input coordinates.
  -if {$#<5} {max(0,$2)+1},1,1,1,$3 -return -endif
  (${2--1}) -r[-1] 2,{w/2},1,1,-1 -sort[-1] +,y -s[-1] x,2 -round[-2] 1 -a[-2,-1] x

  # Estimate pointwise forward/backward slopes.
  --shift[-1] 0,1,0,0,1 --[-1] [-2] -*[-1] -1   # Backward derivatives.
  --shift[-2] 0,-1,0,0,1 --[-1] [-3]            # Forward derivatives.
  --*[-2] {$1/2} --*[-2] {1-$1/2} -+[-2,-1]     # Forward tangents.
  -*[-3] {1-$1/2} -*[-2] {$1/2} -+[-3,-2]       # Backward tangents.
  -s[-2,-1] x -+[-4,-2] 1e-10
  -/[-3] [-4] -/[-1] [-2] -rm[-4,-2]            # Forward and backward slopes.
  -a[-3--1] x                                   # Append slopes to coordinates.

  # Compute multi-spline curve.
  {@{-1,(0,{h-1})}+1}
  -repeat {@{-2,h}-1}
    xstart={if(~>,@{-2,0},0)}
    -_function1d @{-2,0-1},@{-2,3},@{-2,4-6},$xstart,@{-2,4} -image[-2] [-1],$xstart -rm[-1]
  -shift[-2] 0,-1 -done
  -rm[-2]
  -v +

# Generate single spline function from specified coordinates (x0,y0,s0)-(x1,y1,s1), in range [t0..t1]
_function1d :
  ({$1^3},{$1^2},$1,1;\
   {3*$1^2},{2*$1},1,0;\
   {$4^3},{$4^2},$4,1;\
   {3*$4^2},{2*$4},1,0)
  ($2;$3;$5;$6) -solve[-1] [-2] -rm[-2] -transpose[-1]
  ($7,$8) -r[-1] {1+$8-$7},1,1,1,3 --pow[-1] 3 --pow[-2] 2 --f[-1] 1 -mv[-4] -1 -a[-4--1] y
  -**[-2,-1]

#@gmic pointcloud
#@gmic : Convert a Nx1, Nx2 or Nx3 image as a point cloud in a 1d/2d or 3d binary image.
pointcloud :
  -e[^-1] "Convert image$? as point clouds."
  -v - -repeat @#
    -if {"h>3 || d>1 || s>1"} -error "Invalid input image ("{w}x{h}x{d}x{s}")." -endif

    # Retrieve coordinates infos.
    -round[-1] 1 -lines[-1] 0,2
    --sh[-1] 0,0,0,0 dx={iM+1} -rm[-1]
    --sh[-1] 2,2,0,0 dz={iM+1} -*[-1] $dx
    --sh[-2] 1,1,0,0 dy={iM+1}
    -+[-1] [-2] -f[-2] 0 -rm[-2,-1] -transpose[-1]
    nbp={h}

    # Create corresponding 3d object.
    -unroll[-1] y
    -i[-2] (67.5;73.5;109.5;103.5;51.5;100.5;\  # Magick number for CImg3d.
            $nbp;$nbp)                          # Number of vertices and primitives.
    (1,0;1,{$nbp-1}) -r[-1] 2,$nbp,1,1,3 -unroll[-1] y
    1,{5*$nbp},1,1,-128,1,1,1,1
    1,$nbp,1,1,1 -a[-5--1] y

    # Draw corresponding point cloud.
    $dx,{$dy*$dz} -object3d[-1] [-2],0,0,0,1,0 -rm[-2] -r[-1] $dx,$dy,$dz,1,-1

  -mv[-1] 0 -done -v +

#@gmic snowflake : _recursion>=0,_x0,_y0,_x1,_y1,_x2,_y2,_opacity,_col1,..._colN
#@gmic : Draw a Koch snowflake on selected images.
snowflake : -check ${1=4}>=0 -skip ${2=20},${3=70},${4=80},${5=70},${6=50},${7=10},${8=1},${9=255}
  -v -
  -polygon 3,$2%,$3%,$4%,$5%,$6%,$7%,${8--1}
  -_snowflake $1,$2,$3,$6,$7,${8--1}
  -_snowflake $1,$6,$7,$4,$5,${8--1}
  -_snowflake $1,$4,$5,$2,$3,${8--1}
  -v +

_snowflake :
  x0={$2+($4-$2)/3} y0={$3+($5-$3)/3}
  x1={$2+2*($4-$2)/3} y1={$3+2*($5-$3)/3}
  c={cos(-pi/3)} s={sin(-pi/3)}
  x2={$x0+($x1-$x0)*$c-($y1-$y0)*$s} y2={$y0+($x1-$x0)*$s+($y1-$y0)*$c}
  -polygon 3,$x0%,$y0%,$x1%,$y1%,$x2%,$y2%,${6--1}
  -if $1
    -_snowflake {$1-1},$2,$3,$x0,$y0,${6--1}
    -_snowflake {$1-1},$x0,$y0,$x2,$y2,${6--1}
    -_snowflake {$1-1},$x2,$y2,$x1,$y1,${6--1}
    -_snowflake {$1-1},$x1,$y1,$4,$5,${6--1}
  -endif

#-------------------------
#
#@gmic :: Image filtering
#
#-------------------------

#@gmic blur_x : amplitude[%]>=0,_borders={ 0 | 1 }
#@gmic : Blur selected images along the X-axis.
blur_x : -skip ${2=1}
  -deriche $1,0,x,$2

#@gmic blur_y : amplitude[%]>=0,_borders={ 0 | 1 }
#@gmic : Blur selected images along the Y-axis.
blur_y : -skip ${2=1}
  -deriche $1,0,y,$2

#@gmic blur_z : amplitude[%]>=0,_borders={ 0 | 1 }
#@gmic : Blur selected images along the Z-axis.
blur_z : -skip ${2=1}
  -deriche $1,0,z,$2

#@gmic blur_xy : amplitude_x[%],amplitude_y[%],_borders={ 0 | 1 }
#@gmic : Blur selected images along the X and Y axes.
blur_xy : -skip ${3=1}
  -deriche $1,0,x,$3 -deriche $2,0,y,$3

#@gmic blur_xyz : amplitude_x[%],amplitude_y[%],amplitude_z,_borders={ 0 | 1 }
#@gmic : Blur selected images along the X, Y and Z axes.
blur_xyz : -skip ${4=1}
  -deriche $1,0,x,$4 -deriche $2,0,y,$4 -deriche $3,0,z,$4

#@gmic blur_angular : _amplitude[%],_cx,_cy
#@gmic : Apply angular blur on selected images.
blur_angular : -skip ${1=3%},${2=0.5},${3=0.5}
  -e[^-1] "Apply angular blur on image$?, with amplitude $1 and center ($2,$3)."
  -v - -euclidean2polar $2,$3,1.3,1 -expand_y 16,2 -blur_y $1 -shrink_y 16 -polar2euclidean $2,$3,1.3,1 -v +

#@gmic blur_radial : _amplitude[%],_cx,_cy
#@gmic : Apply radial blur on selected images.
blur_radial : -skip ${1=3%},${2=0.5},${3=0.5}
  -e[^-1] "Apply radial blur on image$?, with amplitude $1 and center ($2,$3)."
  -v - -euclidean2polar $2,$3,5,1 -blur_x $1 -polar2euclidean $2,$3,5,1 -v +

#@gmic blur_linear : _amplitude1[%],_amplitude2[%],_angle=0,_borders={ 0=dirichlet | 1=neumann }
#@gmic : Apply linear blur on selected images, with specified angle and amplitudes.
blur_linear : -skip ${1=30%},${2=$1},${3=0},${4=1}
  -e[^-1] "Apply linear blur on image$?, with angle $3 and amplitudes ($1,$2)."
  -v -
  -if {isval($1)} -p $1 -else -p {(${1}10000)*max(w,h)/100} -endif
  -if {isval($2)} -p $2 -else -p {(${2}10000)*max(w,h)/100} -endif
  -p[0] {1.75*max(~-1,~-2)} -pp[-2,-1]
  -repeat @#
    -if {$4==1} -expand_xy[-1] ~0,1 -else -expand_xy[-1] ~0,0 -endif
    {2*~0},{2*~0} -gaussian[-1] $1,$2,$3 -normalize_sum[-1]
    -convolve_fft[-2,-1] -shrink_xy[-1] ~0
  -mv[-1] 0 -done -v +

#@gmic dog : _sigma1>=0[%],_sigma2>=0[%]
#@gmic : Compute difference of gaussian on selected images.
dog : -skip ${1=2%},${2=3%}
  -e[^-1] "Compute difference of gaussian on image$?, with standard deviations $1 and $2."
  -v - -repeat @#
    --blur[-1] $1 -blur[-2] $2 --[-2,-1] -norm[-1]
  -mv[-1] 0 -done -v +

#@gmic pde_flow : _nb_iter>=0,_dt,_velocity_command,_sequence_flag={ 0 | 1 }
#@gmic : Apply iterations of a generic PDE flow on selected images.
pde_flow : -skip ${1=10},${2=30},${3=laplacian},${4=0}
  -e[^-1] "Apply $1 iterations of the velocity flow '$3' on image$?, with time step $2."
  -v - -repeat @# -l[-1] -repeat $1
    --$3[-1] -*[-1] {$2/(0.01+max(abs(im),abs(iM)))}
    -if $4 -+[-1] [-2] -else -+[-2,-1] -endif
  -done -if $4 -rm[0] -endif -a x -endl
  -mv[-1] 0 -done -if $4 -s x,$1 -endif -v +

#@gmic heat_flow : _nb_iter>=0,_dt,_sequence_flag={ 0 | 1 }
#@gmic : Apply iterations of the heat flow on selected images.
heat_flow : -skip ${1=10},${2=30},${3=0}
  -e[^-1] "Apply $1 iterations of the heat flow on image$?, with time step $2."
  -v - -pde_flow $1,$2,laplacian,$3 -v +

#@gmic meancurvature_flow : _nb_iter>=0,_dt,_sequence_flag={ 0 | 1 }
#@gmic : Apply iterations of the mean curvature flow on selected images.
meancurvature_flow : -skip ${1=5},${2=30},${3=0}
  -e[^-1] "Apply $1 iterations of the mean curvature flow on image$?, with time step $2."
  -v - -pde_flow $1,$2,Iee,$3 -v +

#@gmic tv_flow : _nb_iter>=0,_dt,_sequence_flag={ 0 | 1 }
#@gmic : Apply iterations of the total variation flow on selected images.
tv_flow : -skip ${1=5},${2=30},${3=0}
  -e[^-1] "Apply $1 iterations of the total variation flow on image$?, with time step $2."
  -v - -pde_flow $1,$2,curvature,$3 -v +

#@gmic inpaint_flow : _nb_iter1>=0,_nb_iter2>=0,_dt>=0,_alpha,_sigma
#@gmic : Apply iteration of the inpainting flow on selected images.
inpaint_flow : -skip ${1=4},${2=15},${3=15},${4=1},${5=3}
  -e[^-1] "Apply $1 iteration of the inpainting flow on image$?."
  -v - -norm[0] -quantize[0] 2 -n[0] 0,1 -repeat @# -if ~> -l[0,~>]
  -r[0] [1] -inpaint[1] [0]
  -repeat $1
     --edgetensors[1] 0,1,$4,$5,0 -*[2] [0] -smooth[1] [2],$2,$3,0 -rm[2]
  -done
  -endl -endif -done -v +

#@gmic remove_hotpixels : _mask_size>0, _threshold[%]>0
#@gmic : Remove hot pixels in selected images.
remove_hotpixels : -check ${1=3}>0 -skip ${2=10%}
  -e[^-1] "Remove hot pixels in image$?, with mask size $1 and threshold $2."
  -v - -repeat @#
    --median[-1] $1 ---[-1,-2] -abs[-1] -t[-1] $2
    -*[-2] [-1]
    -*[-1] -1 -+[-1] 1
    -*[-3,-1] -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic richardson_lucy : amplitude[%]>=0,_nb_iter>=0,_dt>=0,_regul>=0,_regul_type={ 0=Tikhonov | 1=meancurv. | 2=TV }
#@gmic : Deconvolve image with the iterative Richardson-Lucy algorithm.
richardson_lucy : -check "${2=10}>=0 && ${3=20}>=0 && ${4=0.7}>=0" -skip ${1=2},${5=1}
  -e[^-1] "Deconvove image$? with the Richardson-Lucy algorithm, with sigma $1, $2 iterations, time step $3 and regularization $4."
  -v - -repeat @#
    [-1]
    -repeat $2
      -if {$5>=2} --curvature[-1]                         # TV regularization.
      -elif {$5>=1} --Iee[-1]                             # Meancurv. regularization.
      -else --laplacian[-1]                               # Tikhonov regularization.
      -endif
      -*[-1] $4
      --blur[-2] $1 --[-1] [-4]                           # Data fidelity term.
      --[-2,-1]
      -*[-1] {$3/(0.0001+max(abs(@{-1,m}),abs(@{-1,M})))} # Adaptive time step.
      -+[-2,-1]                                           # Update image.
    -done
    -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic oriented_richardson_lucy : amplitude1[%]>=0,_amplitude2[%]>=0,_angle,_nb_iter>=0,_dt>=0,_regul>=0,_regul_type={ 0=Tikhonov | 1=meancurv. | 2=TV }
#@gmic : Deconvolve image with the iterative Richardson-Lucy algorithm for oriented kernels.
oriented_richardson_lucy : -check "${2=$1}>=0 && ${4=10}>=0 && ${5=20}>=0 && ${6=0.7}>=0" -skip ${1=2},${3=0},${7=1}
  -e[^-1] "Deconvove image$? with the oriented Richardson-Lucy algorithm, with sigma ($1,$2), angle $3°, $4 iterations, time step $5 and regularization $6."
  -v - -repeat @#
    [-1]
    -repeat $4
      -if {$7>=2} --curvature[-1]                         # TV regularization.
      -elif {$7>=1} --Iee[-1]                             # Meancurv. regularization.
      -else --laplacian[-1]                               # Tikhonov regularization.
      -endif
      -*[-1] $6
      --blur_linear[-2] $1,$2,$3 --[-1] [-4]              # Data fidelity term.
      --[-2,-1]
      -*[-1] {$5/(0.0001+max(abs(@{-1,m}),abs(@{-1,M})))} # Adaptive time step.
      -+[-2,-1]                                           # Update image.
    -done
    -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic unsharp : _radius[%]>=0,_amount>=0,_threshold[%]>=0
#@gmic : Apply unsharp mask on selected images.
unsharp : -check "${2=2}>=0" -skip ${1=1},${3=0}
  -e[^-1] "Apply unsharp mask on image$?, with radius $1, amount $2 and threshold $3."
  -v - -repeat @#
    --blur[-1] $1 --[-1] [-2]
    -if $3 --norm[-1] -t[-1] $3 -*[-2,-1] -endif
    -*[-1] $2 --[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic unsharp_octave : _nb_scales>0,_radius[%]>=0,_amount>=0,threshold[%]>=0
#@gmic : Apply octave sharpening on selected images.
unsharp_octave : -check "${1=4}>0 && ${3=2}>=0" -skip ${2=1},${4=0}
  -e[^-1] "Apply octave sharpening on image$?, with $1 scales, radius $2, amount $3 and threshold $4."
  -v - -repeat @#
    -l[-1] --f 0 -p 0 -repeat $1
      --unsharp[0] {$2*2^-@{<,-1}},$3,$4 -*[-1] {2^-~>} -p=[-1] {~-1+2^-~>} -+[1,-1]
    -done -rm[0] -/[-1] ~-1 -pp[-1] -endl
  -mv[-1] 0 -done -v +

#@gmic normalize_local : _amplitude>=0,_radius>0,_n_smooth>=0[%],_a_smooth>=0[%],_is_cut={ 0 | 1 },_min=0,_max=255
#@gmic : Normalize selected images locally.
normalize_local :
  -check "${1=3}>=0 && ${2=16}>0 && isbool(${5=1})" -skip ${3=4%},${4=2%},${6=0},${7=255}
  -e[^-1] "Normalize image$? locally, with amplitude $1, radius $2, neighborhood smoothness $3 and average smoothness $4."
  -v - -repeat @#
    --l[-1] -erode {2*$2+1} -s c -min -endl
    --l[-2] -dilate {2*$2+1} -s c -max -endl
    --blur[-3] $4 -blur[-3,-2] $3
    ---[-2] [-3] -+[-1] 0.01 --[-5] [-4] -/[-5,-1]
    -*[-3,-2] {$1+1} -*[-1] -$1 -+[-3] [-1] -+[-2,-1]
    -if $5 -max[-2] $6 -min[-1] $7 -endif
    --[-1] [-2] -*[-3,-1] -+[-2,-1]
    -if $5 -c[-1] $6,$7 -endif
  -mv[-1] 0 -done -v +

#@gmic map_tones : _threshold>=0,_gamma>=0,_smoothness>=0,iter>=0
#@gmic : Apply tone mapping operator based on Poisson equation.
map_tones : -skip ${1=0.1},${2=0.8},${3=0.5},${4=30}
  -e[^-1] "Apply tone mapping operator with threshold $1, gamma $2, smoothness $3 and $4 iterations."
  -v - -repeat @#

    # Estimate target divergence for each channel.
    --l[-1] -s[-1] c -repeat @#
      -gradient[-1] xy,1 -a[-2,-1] c --norm[-1] -orientation[-2]
      -p {im},{iM} -blur[-1] $3 -n[-1] ~-1 -pp[-1]
      -*[-1] 'alpha=$1*iM;(alpha/(1e-10+i))*(i/(1e-10+alpha))^$2'
     -*[-2,-1] -s[-1] c -gradient[-2] x,-1 -gradient[-1] y,-1 -+[-2,-1]
    -mv[-1] 0 -done -a c -endl

    # Start PDE iterations
    -*[-1] 0.25
    -repeat $4
      --laplacian[-2] -*[-1] 0.25 -+[-1] [-3] --[-1] [-2] -*[-1] 800 -+[-3,-1] -/[-2] 801 -c[-2] 0,255
      -w[-2]
    -done -rm[-1]
  -mv[-1] 0 -done  -v +

#@gmic fftpolar
#@gmic : Compute fourier transform of selected images, as centered magnitude/phase images.
fftpolar :
  -e[^-1] "Compute fourier transform of image$?, as centered magnitude/phase images."
  -v - -repeat @#
    -fft[-1] -complex2polar[-2,-1]
    -shift[-2,-1] 50%,50%,50%,0,2
  -mv[-2,-1] 0 -done -v +

#@gmic ifftpolar
#@gmic : Compute inverse fourier transform of selected images, from centered magnitude/phase images.
ifftpolar :
  -e[^-1] "Compute inverse fourier transform of image$?, from centered magnitude/phase images."
  -v - -repeat {int(@#/2)}
    -shift[-2,-1] -50%,-50%,-50%,0,2
    -polar2complex[-2,-1] -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic convolve_fft
#@gmic : Convolve selected images two-by-two through fourier transforms.
convolve_fft :
  -e[^-1] "Convolve image$? two-by-two through fourier transforms."
  -v - -repeat {int(@#/2)}
    -r[-1] 100%,100%,100%,[-2],1 -r[-1] [-2],0,0,0.5,0.5,0.5,0.5 -shift[-1] -50%,-50%,-50%,0,2
    -fft[-2] -fft[-1] -shift[-1] -50%,-50%,-50%,0,2
    --*[-4] [-1] --*[-4] [-3] -+[-2,-1]
    -*[-5,-3] -*[-3,-2] --[-3,-2]
    -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic deconvolve_fft
#@gmic : Deconvolve selected images two-by-two through fourier transforms.
deconvolve_fft :
  -e[^-1] "Deconvolve image$? two-by-two through fourier transforms."
  -v - -repeat {int(@#/2)}
    -r[-1] 100%,100%,100%,[-2],1
    -r[-1] [-2],0,0,0.5,0.5,0.5,0.5
    -shift[-1] -50%,-50%,-50%,0,2
    -fft[-2] -fft[-1]
    -shift[-1] -50%,-50%,-50%,0,2                # a b c d
    --sqr[-2] --sqr[-2] -+[-2,-1] -+[-1] 0.0001  # a b c d (c^2+d^2)
    --*[-4] [-3]                                 # a b c d (c^2+d^2) bc
    --*[-6] [-3]                                 # a b c d (c^2+d^2) bc ad
    --[-2,-1]                                    # a b c d (c^2+d^2) bc-ad
    -*[-6,-4]                                    # ac b d (c^2+d^2) bc-ad
    -*[-4,-3]                                    # ac bd (c^2+d^2) bc-ad
    -+[-4,-3]                                    # ac+bd (c^2+d^2) bc-ad
    -/[-1] [-2] -/[-3,-2]                        # divide (ac+bd) and (bc-ad) by (c^2+d^2)
    -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic bandpass : _min_freq[%],_max_freq[%]
#@gmic : Apply bandpass filter to selected images.
bandpass : -skip ${1=0},${2=20%}
  -e[^-1] "Apply bandpass filter [$1,$2] to image$?."
  -v - -repeat @#
    100%,100%,100% -f[-1] "sqrt((x/w-0.5)^2 + (y/h-0.5)^2 + (z/d-0.5)^2)" -n[-1] 0,1 -t2[-1] $1,$2 -shift[-1] 50%,50%,50%,0,2
    -fft[-2] -*[-3] [-1] -*[-2,-1] -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic watermark_fourier : _text,_size>0
#@gmic : Add an textual watermark in the frequency domain of selected images.
watermark_fourier : -skip "${1=G'MIC}" -check ${2=32}>0
  -e[^-1] "Add textual watermark '$1' with size $2 in the frequency domain of image$?."
  -v - -i[0] 1 -text[0] "$1",0,0,$2,1,1 -autocrop[0] 0
  -repeat {@#-1}
  -fft[-1] -shift[-2,-1] 50%,50%,0,0,2
    [0],[0],1,{s}
    -image[-3,-2] [-1],3,3,0,0,1,[0]
    -mirror[0] x
    -image[-3,-2] [-1],{@{-2,w}-2-@{0,w}},3,0,0,1,[0]
    -mirror[0] y
    -image[-3,-2] [-1],{@{-2,w}-2-@{0,w}},{@{-2,h}-2-@{0,h}},0,0,1,[0]
    -mirror[0] x
    -image[-3,-2] [-1],3,{@{-2,h}-2-@{0,h}},0,0,1,[0]
    -mirror[0] y
    -rm[-1] -shift[-2,-1] -50%,-50%,0,0,2 -ifft[-2,-1] -rm[-1]
  -mv[-1] 1 -done
  -rm[0] -v +

#@gmic split_freq : smoothness>0[%]
#@gmic : Split selected images into low and high frequency parts.
split_freq : -skip ${1=2%}
  -e[^-1] "Split image$? into low and high frequency parts, with smoothness $1."
  -v - -repeat @#
    --blur[-1] $1 --[-2] [-1] -rv[-2,-1]
  -mv[-2,-1] 0 -done -v +

#@gmic compose_freq
#@gmic : Compose selected low and high frequency parts into new images.
compose_freq :
  -e[^-1] "Compose low and high frequency part$? into new images."
  -v - -repeat {int(@#/2)}
    -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic erode_oct : _size>=0
#@gmic : Apply octagonal erosion of selected images by specified size.
erode_oct : -check ${1=5}>=0
  -e[^-1] "Apply octagonal erosion of image$? by size $1."
  -v -
  -if {$1<2} -return -endif
  -i[0] (0,1,0;1,1,1;0,1,0) -i[1] (1,1,1;1,1,1;1,1,1)
  -repeat {@#-2}
    -repeat {0.5*$1*sqrt(2)/(1+sqrt(2))} -erode[-1] [0] -done
    -repeat {0.5*$1/(1+2*sqrt(2))} -erode[-1] [1] -done
  -mv[-1] 2 -done -rm[0,1] -v +

#@gmic dilate_oct : _size>=0
#@gmic : Apply octagonal dilation of selected image by specified size.
dilate_oct : -check ${1=5}>=0
  -e[^-1] "Apply octagonal dilation of image$? by size $1."
  -v -
  -if {$1<2} -return -endif
  -i[0] (0,1,0;1,1,1;0,1,0) -i[1] (1,1,1;1,1,1;1,1,1)
  -repeat {@#-2}
    -repeat {0.5*$1*sqrt(2)/(1+sqrt(2))} -dilate[-1] [0] -done
    -repeat {0.5*$1/(1+sqrt(2))} -dilate[-1] [1] -done
  -mv[-1] 2 -done -rm[0,1] -v +

#@gmic erode_circ : _size>=0
#@gmic : Apply circular erosion of selected images by specified size.
erode_circ : -check ${1=5}>=0
  -e[^-1] "Apply circular erosion of image$? by size $1."
  -v -
  -if {$1<2} -return -endif
  -_kr_circle $1 -erode[^-1] [-1] -rm[-1] -v +

#@gmic dilate_circ : _size>=0
#@gmic : Apply circular dilation of selected image by specified size.
dilate_circ : -check ${1=5}>=0
  -e[^-1] "Apply circular dilation of image$? by size $1."
  -v -
  -if {$1<2} -return -endif
  -_kr_circle $1 -dilate[^-1] [-1] -rm[-1] -v +

_kr_circle :
  -if {$1%2==0} -i 2,2,1,1,1 -else -i 1,1,1,1,1 -endif -r[-1] $1,$1,1,1,0,0,0.5,0.5
  -distance[-1] 1 -round[-1] 0.5 -t2[-1] 0,{$1/2}

#@gmic skeleton
#@gmic : Compute skeleton of binary shapes using morphological thinning.
skeleton :
  -e[^-1] "Compute skeleton of binary image$?, using morphological thinning."
  -v - -t 50% -* 2 -- 1
  (-1,-1,-1;0,1,0;1,1,1) (0,-1,-1;1,1,-1;0,1,0) --rotate[-2,-1] 90 --rotate[-2,-1] 90 --rotate[-2,-1] 90
  -repeat @#
    bavg=@{-9,+}
    -repeat 99999
      --correlate[-9] [-8] -t[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-7] -t[-1] 6 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-6] -t[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-5] -t[-1] 6 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-4] -t[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-3] -t[-1] 6 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-2] -t[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-1] -t[-1] 6 -*[-1] 2 --[-10,-1]
      aavg=@{-9,+} -if {$aavg==$bavg} -b -endif bavg=$aavg
    -done
  -mv[-9] 0 -done -rm[-8--1] -+ 1 -/ 2 -v +

#----------------------------------
#
#@gmic :: Contours and variations
#
#----------------------------------

#@gmic gradient_norm
#@gmic : Compute gradient norm of selected images.
gradient_norm :
  -e[^-1] "Compute gradient norm of image$?."
  -v - -repeat @#
    --gradient[-1] x -sqr[-1]
    --gradient[-2] y -sqr[-1] -+[-2,-1]
    -gradient[-2] z -sqr[-2] -+[-2,-1]
    -p {s} -s[-1] c -+[-~-1--1] -pp[-1]
    -sqrt[-1]
  -mv[-1] 0 -done -v +

#@gmic gradient_orientation : _dimension={1,2,3}
#@gmic : Compute N-D gradient orientation of selected images.
gradient_orientation : -check "${1=3}==1 || $1==2 || $1==3"
  -e[^-1] "Compute $1-D gradient orientation of image$?."
  -v - -repeat @#
    -if {$1==1} -gradient[-1] x --abs[-1] -+[-1] 1e-8 -/[-2,-1]
    -elif {$1==2} -gradient[-1] xy --sqr[-2--1] -+[-2,-1] -+[-1] 1e-8 -sqrt[-1] -/[-3] [-1] -/[-2,-1]
    -else -gradient[-1] xyz --sqr[-3--1] -+[-3--1] -+[-1] 1e-8 -sqrt[-1] -/[-4,-3] [-1] -/[-2,-1]
    -endif
  -mv[-$1--1] 0 -done -v +

#@gmic gradient2rgb : _orientation={ 0 | 1 }
#@gmic : Compute RGB representation of 2d gradient of selected images.
gradient2rgb : -check "isbool(${1=0})"
  -if $1 -e[^-1] "Compute RGB representation of 2d gradient orientation of image$?."
  -else -e[^-1] "Compute RGB representation of 2d gradient of image$?." -endif
  -v - -repeat @#
    -norm[-1]
    -if $1 -gradient_orientation[-1] 2 -else -gradient[-1] xy -endif
    -a[-2,-1] c -direction2rgb[-1]
  -mv[-1] 0 -done -v +

#@gmic laplacian
#@gmic : Compute Laplacian of selected images.
laplacian :
  -e[^-1] "Compute Laplacian of image $?."
  -v - -repeat @#
    -if {d==1} -hessian[-1] xxyy -+[-2,-1]
    -else -hessian[-1] xxyyzz -+[-3--1]
    -endif
  -mv[-1] 0 -done -v +

#@gmic divergence
#@gmic : Compute divergence of selected vector fields.
divergence :
  -e[^-1] "Compute divergence of vector field$?."
  -v - -repeat @#
    -if {s==1} -gradient[-1] x,0
    -elif {s==2} -s[-1] c -gradient[-2] x,0 -gradient[-1] y,0 -+[-2,-1]
    -elif {s==3} -s[-1] c -gradient[-3] x,0 -gradient[-2] y,0 -gradient[-1] z,0 -+[-3--1]
    -else -error[] "Cannot compute divergence of image ["~>"] (has "{s}">3 channels)."
    -endif
  -mv[-1] 0 -done -v +

#@gmic inn
#@gmic : Compute gradient-directed 2nd derivative of image(s).
Inn :
  -e[^-1] "Compute gradient-directed 2nd derivative of image$?."
  -v - -repeat @#
    -if {d==1}
      --gradient[-1] xy,0 -hessian[-3] xxxyyy                 # ixx ixy iyy ix iy
      -*[-5] [-2] -*[-4] [-1] -*[-4] 2                        # ixixx 2iyixy iyy ix iy
      -+[-5,-4] -*[-4] [-2]                                   # ix^2ixx+2ixiyixy iyy ix iy
      -sqr[-2,-1] -*[-3] [-1] -+[-4,-3]                       # ix^2ixx+2ixiyixy+iy^2iyy ix^2 iy^2
      -+[-2,-1] -+[-1] 1e-8 -/[-2,-1]                         # (ix^2ixx+2ixiyixy+iy^2iyy)/(ix^2+iy^2)
    -else
      --gradient[-1] xyz,0 -hessian[-4] xxxyxzyyyzzz          # ixx ixy ixz iyy iyz izz ix iy iz
      -*[-9] [-3] -*[-8] [-2] -*[-8] 2 -*[-7] [-1] -*[-7] 2   # ixixx 2iyixy 2izixz iyy iyz izz ix iy iz
      -+[-9--7] -*[-7] [-3]                                   # ix^2ixx+2ixiyixy+2ixizixy iyy iyz izz ix iy iz
      -*[-6] [-2] -*[-5] [-1] -*[-5] 2                        # ix^2ixx+2ixiyixy+2ixizixy iyiyy 2iziyz izz ix iy iz
      -+[-6,-5] -*[-5] [-2] -+[-6,-5]                         # ix^2ixx+2ixiyixy+2ixizixy+iy^2iyy+2iyiziyz izz ix iy iz
      -sqr[-3--1] -*[-4] [-1] -+[-5,-4]                       # ix^2ixx+2ixiyixy+2ixizixy+iy^2iyy+2iyiziyz+iz^2izz ix^2 iy^2 iz^2
      -+[-3--1] -+[-1] 1e-8 -/[-2,-1]                         # (ix^2ixx+2ixiyixy+2ixizixy+iy^2iyy+2iyiziyz+iz^2izz)/(ix^2+iy^2+iz^2)
    -endif
  -mv[-1] 0 -done -v +

#@gmic iee
#@gmic : Compute gradient-orthogonal-directed 2nd derivative of image(s).
Iee :
  -e[^-1] "Compute gradient-orthogonal-directed 2nd derivative of image$?."
  -v - -repeat @#
    -if {d==1}
      --gradient[-1] xy,0 -hessian[-3] xxxyyy                 # ixx ixy iyy ix iy
      -*[-3] [-2] -*[-4] [-1] -*[-4] -2                       # ixx -2iyixy ixiyy ix iy
      -+[-4,-3] -*[-3] [-2]                                   # ixx -2ixiyixy+ix^2iyy ix iy
      -sqr[-2,-1] -*[-4] [-1] -+[-4,-3]                       # iy^2ixx-2ixiyixy+ix^2iyy ix^2 iy^2
      -+[-2,-1] -+[-1] 1e-8 -/[-2,-1]                         # (iy^2ixx+2ixiyixy+ix^2iyy)/(ix^2+iy^2)
    -else
      --Inn[-1] -laplacian[-2] --[-2,-1]
    -endif
  -mv[-1] 0 -done -v +

#@gmic curvature
#@gmic : Compute isophote curvatures on selected images.
curvature :
  -e[^-1] "Compute isophote curvatures on image$?."
  -v - -repeat @#
    -if {d==1}
      --gradient[-1] xy,0 -hessian[-3] xxxyyy                 # ixx ixy iyy ix iy
      -*[-3] [-2] -*[-4] [-1] -*[-4] -2                       # ixx -2iyixy ixiyy ix iy
      -+[-4,-3] -*[-3] [-2]                                   # ixx -2ixiyixy+ix^2iyy ix iy
      -sqr[-2,-1] -*[-4] [-1] -+[-4,-3]                       # iy^2ixx-2ixiyixy+ix^2iyy ix^2 iy^2
      -+[-2,-1] -+[-1] 0.1 -pow[-1] 1.5 -/[-2,-1]             # (iy^2ixx+2ixiyixy+ix^2iyy)/(ix^2+iy^2)
    -else
      --Inn[-1] --gradient_norm[-2] -laplacian[-3]            # inn+iee inn in
      --[-3,-2] -+[-1] 0.1 -/[-2,-1]                          # iee in
      --Inn[-1] -laplacian[-2] --[-2,-1]                      # iee/in
    -endif
  -mv[-1] 0 -done -v +

#@gmic edges : _threshold[%]>=0
#@gmic : Estimate contours of selected images.
edges : -skip ${1=15%}
  -e[^-1] "Estimate image contours of image$?, with threshold $1."
  -v - -repeat @#
    -gradient_norm[-1] -blur[-1] 0.5 -t[-1] $1 -distance[-1] 0 -equalize[-1] 256
    -negative[-1] -c[-1] 30%,70% -n[-1] 0,1
  -mv[-1] 0 -done -v +

#@gmic isophotes : _nb_levels>0
#@gmic : Render isophotes of selected images on a transparent background.
isophotes : -skip ${1=64}
  -e[^-1] "Render isophote maps from images$?, with $1 levels."
  -v - -to_rgba -repeat @# -l[-1]
    --luminance -repeat $1 --isoline3d[1] {~>*255/($1-1)} -done -rm[1] -+3d[1--1] -col3d[-1] 1,1,1
    [0],[0] -object3d[-1] [-2],0,0 -rm[-2] -*[-2,-1]
  -endl -mv[-1] 0 -done -v +

#@gmic topographic_map : _nb_levels>0,_smoothness
#@gmic : Render selected images as topographic maps.
topographic_map : -skip ${1=16},${2=2}
  -e[^-1] "Render topographic maps from image$?, with $1 levels and smoothness $2."
  -v - -to_rgb -repeat @#
    --blur[-1] $2 -isophotes[-1] $1 -t[-1] 0.1 -to_rgb[-1] --norm[-1]
    -line[-2,-1] 100%,0,100%,100%,1,1 -line[-2,-1] 0,100%,100%,100%,1,1
    -line[-2,-1] 0,0,100%,0,1,1 -line[-2,-1] 0,0,0,100%,1,1
    -_topographic_map0[-3--1]
    -_topographic_map[-3--1]
    -rm[-3,-1]
  -mv[-1] 0 -done -v +

_topographic_map0 :
  -repeat 4000
    -p {?(w)},{?(h)}
    -if {@{-1,(~-1)}==0}
      -flood[-2] ~-1,0,0,1,@{-3,(~-1,0,0)},@{-3,(~-1,0,1)},@{-3,(~-1,0,2)}
      -flood[-1] ~-1,0,0,1,1
    -endif
    -pp[-1]
  -done

_topographic_map :
  -do
    (@{-1,c}) -p @{-1,0},@{-1,1} -rm[-1]
    -if {@{-1,(~-1)}==0}
      -flood[-2] ~-1,0,0,1,@{-3,(~-1,0,0)},@{-3,(~-1,0,1)},@{-3,(~-1,0,2)}
      -flood[-1] ~-1,0,0,1,1
      -pp[-1]
    -else -return
    -endif
  -while 1

#@gmic segment_watershed : _threshold>=0,_edge_threshold>0,_keep_watershed={ 0 | 1 }
#@gmic : Apply watershed segmentation on selected images.
segment_watershed : -check "${1=2}>=0 && ${2=11}>0" -skip ${3=1}
  -e[^-1] "Apply watershed segmentation on image$?, with edge threshold $1."
  -v - -repeat @#
    -p[0] {1+@{-1,m}} -+[-1] ~0
    --gradient_norm[-1]
    -if {d>1}
      --f[-1] "if(i<$1 && i<i(x+1) && i<i(x-1) && i<i(x,y+1) && i<i(x,y-1) && i<i(x,y,z+1) && i<i(x,y,z-1),1,0)"
    -else
      --f[-1] "if(i<$1 && i<i(x+1) && i<i(x-1) && i<i(x,y+1) && i<i(x,y-1),1,0)"
    -endif
    -*[-3,-1] -*[-1] -1
    -watershed[-2] [-1],$3 -rm[-1]
    -pp[0]
  -mv[-1] 0 -done -v +

#-------------------------------
#
#@gmic :: Arrays and frames
#
#-------------------------------

#@gmic array : _M>0,_N>0,_expand_type={0,1,2}
#@gmic : Create MxN array from selected images.
array : -skip ${1=3},${2=$1},${3=0}
  -e[^-1] "Create $1x$2 array from image$?, with expand type $3."
  -v - -repeat @#
    -array_expand$3 $1,$2 [-1]x$1 -rm[-1] -a[-$1--1] x [-1]x$2 -rm[-1] -a[-$2--1] y
  -mv[-1] 0 -done -v +
array_expand0 :
  (100) ($1,$2) -/[-2] @{-1,M} -rm[-1] -r[-2] @-1%,@-1%,1,100%,2 -rm[-1]
array_expand1 :
  (100) ($1,$2) -/[-2] @{-1,m} -rm[-1] -r[-2] @-1%,@-1%,1,100%,2 -rm[-1]
array_expand2 :
  -skip ${^0}

#@gmic array_fade : _M>0,_N>0,0<=_fade_start<=100,0<=_fade_end<=100,_expand_type={0,1,2}
#@gmic : Create MxN array from selected images.
array_fade : -skip ${1=3},${2=$1},${3=60},${4=90},${5=1}
  -e[^-1] "Create $1x$2 array of ($3%,$4%) faded tiles from image$?, with expand type $5."
  -v - -repeat @#
    --shift[-1] 50%,50%,1,1,2 -mv[-1] -2 -fade_diamond[-2,-1] $3,$4 -array[-1] $1,$2,$5
  -mv[-1] 0 -done -v +

#@gmic array_mirror : _N>=0,_dir={0,1,2},_expand_type={ 0 | 1 }
#@gmic : Create 2^Nx2^N array from selected images.
array_mirror : -skip ${1=2},${2=2},${3=0}
  -e[^-1] "Create a 2^$1x2^$1 mirrored-array from image$?, with expand type $2."
  -v - -repeat $1
    -if {$3==0} -r 50%,50%,100%,100%,2 -endif
    -repeat @#
      -if {$2==0} --mirror[-1] x -a[-2,-1] x
      -elif {$2==1} --mirror[-1] y -a[-2,-1] y
      -else --mirror[-1] x -a[-2,-1] x --mirror[-1] y -a[-2,-1] y
      -endif
    -mv[-1] 0 -done
  -done -v +

#@gmic array_random : _Ms>0,_Ns>0,_Md>0,_Nd>0
#@gmic : Create MdxNd array of tiles from selected MsxNs source arrays.
array_random : -skip ${1=5},${2=$1},${3=$1},${4=$2}
  -e[^-1] "Create $3x$4 array of tiles from $1x$2 array$?."
  -v - -repeat @#
    -l[-1] -split_tiles $1,$2
    -repeat $3 -repeat $4 [{?($1*$2-1)}] -done -done
    -rm[0-{$1*$2-1}] -append_tiles $3,$4
  -endl -mv[-1] 0 -done -v +

#@gmic array_pattern : _M>0,_N>0,_density>=0,_angle>=0,_zoom>=0,_opacity,_expand_type={0,1,2}
#@gmic : Create random MxN array from selected images.
array_pattern : -skip ${1=10},${2=10},${3=80},${4=180},${5=30},${6=1},${7=0}
  -e[^-1] "Create $1x$2 pattern array from image$?, with density $3, angle $4, zoom $5, opacity $6 and expand type $7."
  -v - -repeat @#
    -array_expand$7 $1,$2 -set[-1] 0,0,0,0,3
    --crop[-1] 0,0,0,0,0,0,0,100% ($1,$2) (@{-3,w},@{-3,h}) -*[-2,-1] -r[-2] @-1,1,100% -rm[-1]
    $1,$2,1,1,-1 -noise[-1] $3,2 -t[-1] 0 -unroll[-1] y
    -repeat $1 -repeat $2
      -if @{-1,0}
        ({?(-$5,$5)}) -+[-1] 100 --r[-4] @-1%,@-1%,1,100%,3 -rm[-2] --f[-1] 1
        (@{>,-2--1}) (@{-6,w},@{-6,h}) -*[-2,-1]
        ({?(-$4,$4)}) -rotate[-4] @-1,1,2 -rotate[-3] @-1,0,0 -rm[-1]
        -image[-5] [-3],@{-1},0,0,$6,[-2] -rm[-3--1]
      -endif
    -shift[-1] 0,-1 -done -done -rm[-3,-1]
  -mv[-1] 0 -done -v +

#@gmic taquin : _M>0,_N>0
#@gmic : Create MxN taquin puzzle from selected images.
taquin : -skip ${1=4},${2=$1}
 -e[^-1] "Create $1x$2 taquin puzzle from image $?."
 -v - -repeat @# -l[-1]
   -split_tiles $1,$2,1 -repeat {$1*$2} -mv[~>] {?(@#)} -done -append_tiles $1,$2
 -endl -mv[-1] 0 -done -v +

#@gmic imagegrid : _M>0,_N>0
#@gmic : Create MxN image grid from selected images.
imagegrid : -skip ${1=10},${2=$1}
  -e[^-1] "Create $1x$2 image grid from image$?."
  -v - -repeat @#
    ({w},{h}) ($1,$2) -/[-2,-1] -round[-1] 1 -r[-2] @-1,[-2],[-2],2 -rm[-1]
    ({w},{h}) ($1,$2) -*[-2,-1] -r[-2] @-1,[-2],[-2],2 -rm[-1]
    $1,$2,1,[-1],1 -shift[-1] 1,1 -r[-1] [-2],0,2 -*[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic frame : _size_x[%]>=0,_size_y[%]>=0,_col1,...,_colN
#@gmic : Insert RGBA-colored frame in selected images.
frame : -skip ${1=20},${2=$1},${3=255},${4=$3},${5=$4}
  -e[^-1] "Insert $1x$2 outer frame in image$?, with color (${3--1})."
  -v - -repeat @#
    -if {$1} -i[-2] $1,[-1],[-1],[-1] -fc[-2] ${3--1} [-2] -a[-3--1] x -endif
    -if {$2} -i[-2] [-1],$2,[-1],[-1] -fc[-2] ${3--1} [-2] -a[-3--1] y -endif
  -mv[-1] 0 -done -v +

#@gmic frame_fuzzy : _size_x>=0,_size_y>=0,_fuzzyness>=0,_smoothness>=0,_R,_G,_B,_A
#@gmic : Draw RGBA-colored fuzzy frame in selected images.
frame_fuzzy : -skip ${1=20},${2=$1},${3=5},${4=1},${5=255},${6=$5},${7=$6},${8=255}
  -e[^-1] "Draw $1x$2 fuzzy frame on image$?, with fuzzyness $3, smoothness $4 and RGBA color ($5,$6,$7,$8)."
  -v - -to_rgba -repeat @#
    -i[0] ($1;$2) -*[0] 2 ($5^$6^$7^$8) -r[-1] [-2] 100%,100%
    -polygon[-1] 4,0,0,100%,0,100%,@{0,1},0,@{0,1},1,1
    -polygon[-1] 4,0,0,@{0,0},0,@{0,0},100%,0,100%,1,1
    -rm[0] -shift[-1] -$1,-$2,0,0,2 -spread[-1] $3 -blur[-1] $4 -_fade 50,80
  -mv[-1] 0 -done -v +

#@gmic frame_round : _sharpness>0,_size>=0,_smoothness,_shade,_R,_G,_B,_A
#@gmic : Draw RGBA-colored round frame in selected images.
frame_round : -skip ${1=10},${2=10},${3=0},${4=0},${5=255},${6=$5},${7=$6},${8=255}
  -e[^-1] "Draw "\
          @{"-if $4 -u \"shaded \" -else -u \"\" -endif"}\
          "round frame on image$?, with sharpness $1, size $2, smoothness $3 and RGBA color ($5,$6,$7,$8)."
  -v - -to_rgba -repeat @#
    100%,100%,1,1,"-(abs(x/w-0.5)^$1 + abs(y/h-0.5)^$1)^(1/$1)" -t[-1] $2%
    -if $4 -distance[-1] 1 -n[-1] 0,1 -*[-1] -1 -+[-1] 1 -pow[-1] {1/$4} -endif
    -blur[-1] $3
    -i[-3] 100%,100%,1,4 -fc[-3] $5,$6,$7,$8
    -compose_fade[-3--1]
  -mv[-1] 0 -done -v +

#@gmic frame_blur : _sharpness>0,_size>=0,_smoothness,_shade,_blur
#@gmic : Draw RGBA-colored round frame in selected images.
frame_blur : -skip ${1=10},${2=30},${3=0},${4=1},${5=3%}
  -e[^-1] "Draw "\
          @{"-if $4 -u \"shaded \" -else -u \"\" -endif"}\
          "round frame on image$?, with sharpness $1, size $2, smoothness $3 and blur $5."
  -v - -to_rgba -repeat @#
    100%,100%,1,1,"-(abs(x/w-0.5)^$1 + abs(y/h-0.5)^$1)^(1/$1)" -t[-1] $2%
    -if $4 -distance[-1] 1 -n[-1] 0,1 -*[-1] -1 -+[-1] 1 -pow[-1] {1/$4} -endif
    -blur[-1] $3
    --blur[-2] $5 -mv[-1] -3
    -compose_fade[-3--1]
  -mv[-1] 0 -done -v +

#@gmic frame_pattern : _M>=3,_pattern = { 0=first image | 1=self },_constrain_size = { 0 | 1 }
#@gmic : Insert selected pattern frame in selected images.
frame_pattern : -check "${1=10}>=3" -skip ${2=0},${3=0}
  -v - -to_colormode 0
  -if {@#==1||$2} # Self-framing
    -v + -e[^-1] "Insert $1x$1 self-pattern frame on image$?." -v -
    -repeat @#
      -p[0] {w},{h}
      --r[-1] {w/($1-2)},{h/($1-2)},1,100%,2
      -r[-2] {$1*w},{$1*h},1,100%,0,0,0.5,0.5
      [-1]x{$1+2} -a[{-$1-2}--1] x -image[-3] [-1],0,0 -image[-3] [-1],0,{@{-3,h}-1-h} -rm[-1]
      [-1]x{$1+1} -a[{-$1-2}--1] y -image[-2] [-1],0,0 -image[-2] [-1],{@{-2,w}-1-w} -rm[-1]
      -if $3 -r[-1] ~0,1,100%,2 -endif -pp[0]
    -mv[-1] 0 -done
  -else # Frame from image[0]
    -v + -e[^-1] "Insert $1x$1 pattern frame on image$?, using first image." -v -
    -repeat {@#-1}
    -p[0] {w},{h}
      --r[0] {w/($1-2)},{h/($1-2)},1,100%,2
      -r[-2] {@{-2,w}+2*w},{@{-2,h}+2*h},1,100%,0,0,0.5,0.5
      [-1]x{$1+2} -a[{-$1-2}--1] x -image[-3] [-1],0,0 -image[-3] [-1],0,{@{-3,h}-1-h} -rm[-1]
      [-1]x{$1+1} -a[{-$1-2}--1] y -image[-2] [-1],0,0 -image[-2] [-1],{@{-2,w}-1-w} -rm[-1]
      -if $3 -r[-1] ~0,1,100%,2 -endif -pp[0]
    -mv[-1] 1 -done
  -endif
  -v +

#@gmic rotate_tiles : _angle,_M>0,N>0
#@gmic : Apply MxN tiled-rotation effect on selected images.
rotate_tiles : -skip ${1=5},${2=8},${3=$2}
  -e[^-1] "Apply $2x$3 tiled-rotation effect on image$?, with angle $1."
  -v - -split_tiles $2,$3,1 -rotate $1 -append_tiles $2,$3 -v +

#@gmic shift_tiles : _M>0,_N>0,_amplitude
#@gmic : Apply MxN tiled-shift effect on selected images.
shift_tiles : -skip ${1=8},${2=8},${3=20}
  -e[^-1] "Apply $1x$2 tiled-shift effect on image$?, with amplitude $3."
  -v - -repeat @#
    $1,$2,1,2 -noise[-1] $3 -r[-1] [-2],[-2],1,2 -warp[-2] [-1],1,1,0 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic linearize_tiles : _M>0,_N>0
#@gmic : Linearize MxN tiles on selected images.
linearize_tiles : -check "${1=10}>0 && ${2=$1}>0"
  -e[^-1] "Linearize $1x$2 tiles on image$?."
  -v -
  -repeat @# -l[-1]
    -p {s} -split_tiles $1,$2 -s c # Split as tiles for all channels.
    -repeat @#
      -p {w},{h}
      --f[-1] x --f[-1] y --f[-1] 1 -unroll[-4--1] y -a[-3--1] x
      -solve[-2] [-1] -rm[-1]
      -i ~-1,1,1,@{-1,0}"*x + "@{-1,1}"*y + "@{-1,2} -rm[-2]
      -pp[-1]
    -mv[-1] 0 -done
    -repeat {int(@#/~-1)} -a[-~-1--1] c -mv[-1] 0 -done -append_tiles $1,$2 -pp[-1]
  -endl -mv[-1] 0 -done -v +

#@gmic quadratize_tiles : _M>0,_N>0
#@gmic : Quadratize MxN tiles on selected images.
quadratize_tiles : -check "${1=10}>0 && ${2=$1}>0"
  -e[^-1] "Quadratize $1x$2 tiles on image$?."
  -v -
  -repeat @# -l[-1]
    -p {s} -split_tiles $1,$2 -s c # Split as tiles for all channels.
    -repeat @#
      -p {w},{h}
      --f[-1] x^2 --f[-1] y^2 --f[-1] x*y --f[-1] x --f[-1] y --f[-1] 1 -unroll[-7--1] y -a[-6--1] x
      -solve[-2] [-1] -rm[-1]
      -i ~-1,1,1,@{-1,0}"*x^2 + "@{-1,1}"*y^2 + "@{-1,2}"*x*y +"@{-1,3}"*x + "@{-1,4}"*y + "@{-1,5} -rm[-2]
      -pp[-1]
    -mv[-1] 0 -done
    -repeat {int(@#/~-1)} -a[-~-1--1] c -mv[-1] 0 -done -append_tiles $1,$2 -pp[-1]
  -endl -mv[-1] 0 -done -v +

#@gmic tunnel : _level>=0,_factor>0,_cx,_cy,_opacity.
#@gmic : Apply tunnel effect on selected images.
tunnel : -check "${1=9}>=0 && ${2=80%}>0" -skip ${3=0.5},${4=0.5},${5=0.1}
  -e[^-1] "Apply tunnel effect on image$?, with depth $1, factor $2, centering ($3,$4) and opacity $5."
  -v - -repeat @#
    -repeat $1 --r[-1] $2,$2,1,100%,5 -image[-2] [-1],{(@{-2,w}-w)*$3},{(@{-2,h}-h)*$4},0,0,$5 -rm[-1] -done
  -mv[-1] 0 -done -v +

#-----------------------------
#
#@gmic :: Artistic effects
#
#-----------------------------

#@gmic polaroid : _size1>=0,_size2>=0
#@gmic : Create polaroid effect in selected images.
polaroid : -skip ${1=10},${2=20}
  -e[^-1] "Create polaroid effect in image$?, with borders sizes $1 and $2."
  -v - -- 255 -r {100+$1}%,{100+$1}%,1,100%,0,0,0.5,0.5 -r 100%,{100+$2}%,1,100%,0,0,0 -+ 255 -v +

#@gmic drop_shadow : _offset_x[%],_offset_y[%],_smoothness[%]
#@gmic : Drop shadow behind selected images.
drop_shadow : -skip ${1=20},${2=$1},${3=5}
  -e[^-1] "Drop shadow behind image$?, with offsets ($1,$2) and smoothness $3."
  -v - -to_rgba -repeat @#
    -r[-1] 150%,150%,1,100%,0,0,0.5,0.5 -s[-1] c --blur[-1] $3 -shift[-1] $1,$2 -or[-2,-1] -a[-4--1] c
    -autocrop 0,0,0,0
  -mv[-1] 0 -done -v +

#@gmic tetris : _scale>0
#@gmic : Apply tetris effect on selected images.
tetris : -skip ${1=10}
  -e[^-1] "Apply tetris effect on image$?, with scale $1."
  -v - -repeat @#
    --r[-1] $1%,$1%,$1%,3,2 -n[-1] 0,255 -quantize[-1] 10
    -r[-1] [-2] -rm[-2] -blur[-1] 2 -sharpen[-1] 300,1
  -mv[-1] 0 -done -v +

#@gmic mosaic : _density>=0,_edges={ 0 | 1 }
#@gmic : Create random mosaic from selected images.
mosaic : -skip ${1=0.8},${2=1}
  -e[^-1] "Apply mosaic effect on image$?, with density $1."
  -v - -repeat @#
    -p[0] {1+@{-1,m}} -+[-1] ~0
    100%,100% -noise[-1] $1,2 -*[-2] [-1] -distance[-1] 1 -*[-1] -1 -watershed[-2] [-1],{if($2,0,1)} -rm[-1]
    -if $2 --l[-1] -t 0.0001 -s c -and -endl --[-2] ~0 -*[-2,-1] -else --[-1] ~0 -endif
    -pp[0]
  -mv[-1] 0 -done -v +

#@gmic puzzle : _scale>=0
#@gmic : Apply puzzle effect on selected images.
puzzle : -skip ${1=5}
  -e[^-1] "Apply puzzle effect on image$?, with scale $1%."
  -v - -repeat @#
    [-1] -r[-1] $1%,$1%,100%,100%,2 -noise[-1] 0.1 -r[-1] [-2] -rm[-2]
    [-1]x2 -shift[-1] -1,-1 --[-2,-1] -norm[-1] -t[-1] 0.01 -*[-1] -1
    -+[-1] 1 -r[-1] [-2] -*[-1,-2] 10%,10%,10%,2 -noise[-1] 5,1
    -r[-1] [-2],[-2],1,2,5 -warp[-2] [-1],1,1,1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic sponge : _size>0
#@gmic : Apply sponge effect on selected images.
sponge : -skip ${1=13}
  -e[^-1] "Apply sponge filter on image$?, with brush size $1."
  -v - -repeat @#
    100%,100%,1,1 -noise[-1] 20,2 -r[-1] [-2] -n[-1] 0,1 -*[-1,-2]
    -_circle $1 -dilate[-2] [-1] -rm[-1]
  -mv[-1] 0 -done -v +

_circle :
  -if {$1%2==0} -i 2,2 -else -i 1 -endif
  -+[-1] 1 -r[-1] $1,$1,1,1,0,0,0.5,0.5 -distance[-1] 1 -n[-1] 0,1 -sqrt[-1] -c[-1] 0.85,0.86 -*[-1] -1 -n[-1] 0,1

#@gmic hearts : _density>=0
#@gmic : Apply heart effect on selected images.
hearts : -skip ${1=10}
  -e[^-1] "Apply heart filter on image$?, with density $1."
  -v - -repeat @#
    100%,100%,1 -noise[-1] $1,2 -r[-1] [-2] -n[-1] 0,1 -*[-1,-2] -_heart9x7
    -mirror[-1] y -dilate[-2] [-1] -rm[-1]
  -mv[-1] 0 -done -v +

_heart9x7 :
  (0,1,1,0,0,0,1,1,0;1,1,1,1,0,1,1,1,1;1,1,1,1,1,1,1,1,1;0,1,1,1,1,1,1,1,0;0,0,1,1,1,1,1,0,0;0,0,0,1,1,1,0,0,0;0,0,0,0,1,0,0,0,0)

#@gmic color_ellipses : _count>0,_radius>=0,_opacity>=0
#@gmic : Add random color ellipses to selected images.
color_ellipses : -skip ${1=1400},${2=5},${3=0.1}
  -e[^-1] "Add $1 random color ellipses to image$?, with maximum radius $2 and opacity $1."
  -v - -repeat @#
    -repeat $1 -ellipse[-1] {?(0,100)}%,{?(0,100)}%,{?(0,$2)}%,{?(0,$2)}%,{?(0,360)},$3,{?(60,255)},{?(60,255)},{?(60,255)} -done
  -mv[-1] 0 -done -v +

#@gmic ellipsionism : _R>0[%],_r>0[%],_smoothness>=0[%],_opacity,_outline>0,_density>0
#@gmic : Apply ellipsionism filter to selected images.
ellipsionism : -check "${1=10}>0 && ${2=3}>0 && ${5=8}>0 && ${6=0.6}>0" -skip ${3=1%},${4=0.7}
  -e[^-1] "Apply ellipsionism filter to image$?, with radii ($1,$2), smoothness $3, opacity $4 and outline $5."
  -v - -to_rgba -repeat @#

    # Compute contour angle.
    --luminance[-1] -gradient[-1] xy -a[-2,-1] c -blur[-1] $3 -orientation[-1]
    --sh[-1] 0,0 --sh[-2] 1,1 -atan2[-1] [-2] -*[-1] {180/pi} -+[-1] 90 -rm[-2,-1]
    -channels[-1] 1,1

    # Render ellipses.
    [-2],[-2],1,[-2]
    -repeat {$6*w*h/max($1,$2)}
      -p[0] {?(w)} -p[1] {?(h)}
      -ellipse[-1] ~0,~1,$1,$2,@{-2,(~0,~1)},$4,\
                   @{-3,(~0,~1,0,0)},@{-3,(~0,~1,0,1)},@{-3,(~0,~1,0,2)},@{-3,(~0,~1,0,3)}
      -ellipse[-1] ~0,~1,$1,$2,@{-2,(~0,~1)},$4,0x1,\
                   {@{-3,(~0,~1,0,0)}/$5},{@{-3,(~0,~1,0,1)}/$5},{@{-3,(~0,~1,0,2)}/$5},{@{-3,(~0,~1,0,3)}/$5}
      -pp[0,1]
    -done
    -rm[-2]

    # Renormalize and prepare next image.
    -n[-1] [-2]
    -compose_rgba[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic whirls : _texture>=0,_smoothness>=0,_darkness>=0,_lightness>=0
#@gmic : Add random whirl texture to selected images.
whirls : -skip ${1=3},${2=6},${3=0.5},${4=1.8}
  -e[^-1] "Add random whirl texture to image$?, with texture $1, smoothness $2, darkness $3 and lightness $4."
  -v - -repeat @#
    100%,100% -noise[-1] 0.3,2 -repeat $1 -blur[-1] $2 -gradient_norm[-1] -pow[-1] 0.2 -done
    -n[-1] $3,$4 -r[-1] [-2] -*[-2,-1] -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic cartoon : _smoothness,_sharpening,_threshold>=0,_thickness>=0,_color>=0,quantization>0
#@gmic : Apply cartoon effect on selected images.
cartoon : -skip ${1=2},${2=200},${3=15},${4=0.25},${5=1.5},${6=8}
  -e[^-1] "Apply cartoon effect on image$?, with smoothness $1, sharpening $2, threshold $3, thickness $4, color $5 and quantization $6."
  -v - -to_rgb -blur $1 -sharpen $2,1 -c 0,255 -n 0,255 -repeat @#
    --edges[-1] $3 -blur[-1] $4 -t[-1] 0.9
    -rgb2lab[-2] -s[-2] c -*[-3,-2] $5 -a[-4--2] c -lab2rgb[-2] -quantize[-2] $6 -n[-2] 0,255
    -*[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic drawing : _amplitude>=0
#@gmic : Apply drawing effect on selected images.
drawing : -skip ${1=200}
  -e[^-1] "Apply drawing effect on image$? with amplitude $1."
  -v - -repeat @#
    -smooth[-1] $1,0.2,1,3,3 -blur[-1] 2 -sharpen[-1] 1000 [-1]
    -r[-2] 20,20,1,3,2 -equalize[-2] 256 -index[-1] [-2],1,1 -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic draw_whirl : _amplitude>=0
#@gmic : Apply whirl drawing effect on selected images.
draw_whirl : -skip ${1=100}
  -e[^-1] "Apply whirl drawing effect on image$? with amplitude $1."
  -v - -repeat @#
    100%,100% -noise[-1] 70,2 -*[-1] 255 -r[-1] [-2] -and[-1,-2] -smooth[-1] $1,0,1,2,2
    -sqrt[-1] -n[-1] 0,255 -equalize[-1] 256
  -mv[-1] 0 -done -v +

#@gmic stencil : _radius[%]>=0,_smoothness>=0,_iterations>=0
#@gmic : Apply stencil filter on selected images.
stencil : -check "${1=3}>=0 && ${2=1}>=0 && ${3=8}>=0"
  -e[^-1] "Apply stencil filter on image$?, with radius $1, smoothness $2 and $3 iterations."
  -v -
  -n 0,1 -repeat $3 -blur $1 -unsharp {$1+$2},1000 -c 0,255 -done
  -v +

#@gmic stencilbw : _edges>=0,_smoothness>=0
#@gmic : Apply B&W stencil effect on selected images.
stencilbw : -skip ${1=15},${2=10}
  -e[^-1] "Apply B&W stencil effect on image$?, with edges $1 and smoothness $2."
  -v - -repeat @#
    -r[-1] 100%,100%,1,100% --edges[-1] $1 -quantize[-2] 3 -blur[-2] $2
    -sharpen[-2] 1000000 -norm[-2] -n[-2] 0,1 -*[-1,-2] -n[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic pencilbw : _size>=0,_amplitude>=0
#@gmic : Apply B&W pencil effect on selected images.
pencilbw : -skip ${1=0.3},${2=60}
  -e[^-1] "Apply B&W pencil effect on image$?, with size $1 and amplitude $2."
  -v - -repeat @#
    -to_rgb[-1] -norm[-1] -blur[-1] $1 -sharpen[-1] 4000 -smooth[-1] $2,0,1 -equalize[-1] 256 -sqrt[-1] -n[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic hardsketchbw : _amplitude>=0,_sampling>=0,_opacity,0<=_edge_threshold<=100
#@gmic : Apply hard B&W sketch effect on selected images.
hardsketchbw : -skip ${1=1000},${2=3},${3=0.1},${4=20}
  -e[^-1] "Apply hard B&W sketch effect on image$?, with amplitude $1, sampling $2, opacity $3 and edge threshold $4."
  -v - -luminance -n 0,1
  -repeat @#
    -gradient[-1] xy -rv[-2,-1] -*[-2] -1 -a[-2,-1] c
    -if $4 --norm[-1] -t[-1] $4% -*[-2,-1] -endif
    100%,100%,1,1,255 -quiver[-1] [-2],$2,$1,0,$3 -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic sketchbw
#@gmic : _nb_orients>0,_start_angle,_angle_range>=0,_length>=0,_threshold>=0,
#@gmic : _opacity,_bgfactor>=0,_density>0,_sharpness>=0,
#@gmic : _anisotropy>=0,_smoothness>=0,_coherence>=0,_is_boost={ 0 | 1 },_is_curved={ 0 | 1 }\n
#@gmic : Apply sketch effect to selected images.
sketchbw :
  -check "${1=2}>0 && ${3=180}>=0 && ${4=30}>=0 && ${5=1}>=0 && ${7=0}>=0 && ${8=0.6}>0 && ${9=0.1}>=0 && ${10=0.6}>=0 && ${11=0.25}>=0 && ${12=1}>=0"
  -skip ${2=45},${6=0.03},${13=0},${14=1}
  -e[^-1] "Apply B&W sketch effect on image$?."
  -v - -edgetensors $9,$10,$11,$12
  -p[0] 1 -p[1] 1 -i[0] 1

  -repeat {@#-1}
    -/[-1] {max(iM,im)} -s[-1] c     # Normalize and split tensor coefficients.
    100%,100%,1,1,255                # Create rendering B&W image.

    -if {~0!=w||~1!=h}               # Create set of random coordinates, if necessary.
      -rm[0] {$8*w*h/($1*sqrt($4))}
      --rand[-1] 0,{@{-2,h}-1} -rand[-2] 0,{@{-3,w}-1} -a[-2,-1] y -mv[-1] 0
      -p=[0] {w} -p=[1] {h}
    -endif

    -if $14 # Render sketch with curved strokes
      -repeat $1
        -p {($2+~>*$3/$1)*pi/180}
        --*[-4] {cos(~-1)} --*[-4] {sin(~-1)} -+[-2,-1]
        --*[-4] {cos(~-1)} --*[-4] {sin(~-1)} -+[-2,-1]
        -pp[-1] -a[-2,-1] c -channels[-1] 0,2
        -if $13 -orientation[-1] -endif
        -repeat @{0,w}
          -p @{0,(~>,0)},@{0,(~>,1)}
          -if {@{-5,(~-1)}+@{-3,(~-1)}<$5} -p $6 -else -p {$7*$6} -endif
          -if ~-1
            --streamline3d[-1] ~-2,0,$4,0.8,0,0,1 -col3d[-1] 0,0,0 -object3d[-3] [-1],0,0,0,~-1,0 -rm[-1]
            --streamline3d[-1] ~-2,0,$4,0.8,0,1,1 -col3d[-1] 0,0,0 -object3d[-3] [-1],0,0,0,~-1,0 -rm[-1]
          -endif
          -pp[-2--1]
        -done
        -rm[-1]
      -done

    -else # Render sketch with straight strokes
      -repeat $1
        -p {($2+~>*$3/$1)*pi/180}
        --*[-4] {cos(~-1)} --*[-4] {sin(~-1)} -+[-2,-1]
        --*[-4] {cos(~-1)} --*[-4] {sin(~-1)} -+[-2,-1]
        -pp[-1] -a[-2,-1] c
        -if $13 -orientation[-1] -endif
        -repeat @{0,w}
          -p @{0,(~>,0)} -p @{0,(~>,1)}
          -if {@{-5,(~-2,~-1)}+@{-3,(~-2,~-1)}<$5} -p $6 -else -p {$7*$6} -endif
          -if ~-1
            -line[-2] {~-3-$4*@{-1,(~-3,~-2,0,0)}},{~-2-$4*@{-1,(~-3,~-2,0,1)}},\
                      {~-3+$4*@{-1,(~-3,~-2,0,0)}},{~-2+$4*@{-1,(~-3,~-2,0,1)}},\
                      {3*~-1},0
          -endif
          -pp[-3--1]
        -done
        -rm[-1]
      -done

    -endif
    -rm[-4--2]
  -mv[-1] 1 -done -rm[0] -v +

#@gmic ditheredbw
#@gmic : Create dithered B&W version of selected images.
ditheredbw :
  -e[^-1] "Create dithered B&W version of image$?."
  -v - -repeat @#
    -n[-1] 0,255 -r[-1] 100%,100%,100%,3 2,1,1,3,0,255 -index[-2] [-1],1,1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic dotsbw : _nb_scales>=0,_resolution>0,_radius>=0
#@gmic : Apply B&W dots effect on selected images.
dotsbw : -check "${1=4}>=0 && ${2=10}>0 && ${3=3}>=0"
  -e[^-1] "Apply B&W dots effect on image$?, with $1 scale(s), resolution $2% and radius %3."
  -v - -r {max(1,w*$2/100)},{max(1,h*$2/100)},1,100%,2
  -repeat @#
    -p[0] {w*100/$2},{h*100/$2} ~0,1,100%
    -repeat $1
      --t[-2] {100*(~>+1)/($1+1)}%
      -r[-1] ~0,1,100%,4,0,0.5,0.5
      -blur[-1] {$3*(~>+1)/($1+1)},0
      -t[-1] 20%
      -or[-2,-1]
    -done
    -rm[-2] -pp[0]
  -mv[-1] 0 -done -v +

#@gmic warhol : _M>0,_N>0,_smoothness>=0,_color>=0
#@gmic : Create MxN Andy Warhol-like artwork from selected images.
warhol : -skip ${1=3},${2=$1},${3=2},${4=20}
  -e[^-1] "Create $1x$2 Andy Warhol-like artwork from image$?."
  -v - -repeat @#
    -norm[-1] -blur[-1] $3 -array_expand0 $1,$2 -quantize[-1] 6 -n[-1] 0,5 -round[-1] 1
    -l[-1] -repeat $1 -repeat $2
      (0,1,2,3,4,5) -n[-1] 32,224 6,1,1,2,128 -noise[-1] $4,0 -c[-1] 0,255 -a[-2,-1] c -ycbcr2rgb[-1] --map[0] [-1] -rm[-2]
    -done -done -append_tiles[1--1] $1,$2 -rm[0] -endl
  -mv[-1] 0 -done -v +

#@gmic cubism : _nb_iter>=0,_bloc_size>0,_max_angle,_opacity,_smoothness>=0
#@gmic : Apply cubism effect on selected images.
cubism : -skip ${1=160},${2=10},${3=75},${4=0.7},${5=0}
  -e[^-1] "Apply cubism effect on image$?, with $1 iterations, bloc size $2%, maximum angle $3, opacity $4 and smoothness $5."
  -v - -repeat @#
    -p {$2*max(w,h)/200}
    -repeat $1
      ({?(0,w)},{?(0,h)})
      --crop[-2] {@{-1,0}-~-1},{@{-1,1}-~-1},{@{-1,0}+~-1},{@{-1,1}+~-1},1
      -blur[-1] $5 --f[-1] 1 -rotate[-2,-1] {?(-$3,$3)},0,0
      -image[-4] [-2],{@{-3,0}-~-1},{@{-3,1}-~-1},0,0,$4,[-1] -rm[-3--1]
    -done
    -pp[-1]
  -mv[-1] 0 -done -v +

#@gmic glow : _amplitude>=0
#@gmic : Add soft glow on selected images.
glow : -skip ${1=1%}
  -e[^-1] "Add soft glow on image$?, with amplitude $1."
  -v - -repeat @#
    --blur[-1] $1 -n[-1] [-2] -compose_edges[-2,-1] 1
  -mv[-1] 0 -done -v +

#@gmic old_photo
#@gmic : Apply old photo effect on selected images.
old_photo :
  -e[^-1] "Apply old photo effect on image$?."
  -v - -noise 20 -bilateral 30,60 -blur 2 -sharpen 100 -frame_fuzzy 20,20,6,3 -shadow_patch 0.75 -n 0,255 -sepia -v +

#------------------------------------
#
#@gmic :: Spatial warping
#
#------------------------------------

#@gmic euclidean2polar : _cx,_cx,_n>0,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply euclidean to polar transform on selected images.
euclidean2polar : -skip ${1=0.5},${2=0.5},${3=1},${4=1}
  -e[^-1] "Apply euclidean to polar transform on image$?."
  -v - -repeat @#
    ({w},{h}) ($1,$2) -*[-2,-1] ({"sqrt(max("@{-1,0}","@{-2,w}"-"@{-1,0}")^2 + max("@{-1,1}","@{-2,h}"-"@{-1,1}")^2)"})
    -a[-2,-1] x
    [-2],[-2],1,1,@{-1,2}"*(x/w)^$3*cos(y*2*pi/h)" -+[-1] @{-2,0}
    [-1],[-1],1,1,@{-2,2}"*(x/w)^$3*sin(y*2*pi/h)" -+[-1] @{-3,1}
    -rm[-3] -a[-2,-1] c -warp[-2] [-1],0,1,$4 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic polar2euclidean : _cx,_cy,_n>0,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply polar to euclidean transform on selected images.
polar2euclidean : -skip ${1=0.5},${2=0.5},${3=1},${4=1}
  -e[^-1] "Apply polar to euclidean transform on image$?."
  -v - -repeat @#
    ({w},{h}) ($1,$2) -*[-2,-1] ({"sqrt(max("@{-1,0}","@{-2,w}"-"@{-1,0}")^2 + max("@{-1,1}","@{-2,h}"-"@{-1,1}")^2)"})
    -a[-2,-1] x
    [-2],[-2],1,1,"w*(sqrt((x-"@{-1,0}")^2 + (y-"@{-1,1}")^2)/"@{-1,2}")^(1/$3)"
    [-1],[-1],1,1,"(atan2(y-"@{-2,1}",x-"@{-2,0}")*h/(2*pi)+h)%h"
    -rm[-3] -a[-2,-1] c -warp[-2] [-1],0,1,$4 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic warp_perspective : _x-angle,_y-angle,_zoom>0,_x-center,_y-center,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Warp selected images with perspective deformation.
warp_perspective : -skip ${1=1.5},${2=0},${3=1},${4=50},${5=50},${6=2}
  -e[^-1] "Apply perspective warp on image$?, with angles ($1,$2), zoom $3 and offsets ($4,$5)."
  -v - -repeat @#
    (0,100) --[-1] $4 -/[-1] 100 (0;100) --[-1] $5 -/[-1] 100 -r[-2,-1] [-3],[-3],[-3],1,3
    --*[-2] $2 --*[-2] $1 -+[-2,-1] -+[-1] $3 -/[-3] [-1] -/[-2,-1]
    -*[-2] 100 -+[-2] $4 -/[-2] 100 -*[-2] @{-3,w}
    -*[-1] 100 -+[-1] $5 -/[-1] 100 -*[-1] @{-3,h}
    -a[-2,-1] c -warp[-2] [-1],0,1,$6 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic water : _amplitude>=0,_smoothness>=0
#@gmic : Apply water deformation on selected images.
water : -skip ${1=30},${2=1.5}
  -e[^-1] "Apply water deformation on image$?, with amplitude $1 and smoothness $2."
  -v - -repeat @#
    25%,25%,25%,1 -noise[-1] $1 -gradient[-1] xyz -+[-1,-2,-3] -blur[-1] $2 -*[-1] 2 -r[-1] [-2],[-2],1,2,3 -warp[-2] [-1],1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic wave : _amplitude>=0,_frequency>=0,_center_x,_center_y
#@gmic : Apply wave deformation on selected images.
wave : -skip ${1=4},${2=0.4},${3=50},${4=50}
  -e[^-1] "Apply wave deformation on image$?, with amplitude $1, frequency $2 and center at ($3%,$4%)."
  -v - -repeat @#
    100%,100% -=[-1] 1,$3%,$4% -distance[-1] 1
    -*[-1] $2 --sin[-1] -cos[-2] -a[-2,-1] c -*[-1] $1
    -warp[-2] [-1],1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic twirl : _amplitude,_cx,_cy,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply twirl deformation on selected images.
twirl : -skip ${1=1},${2=0.5},${3=0.5},${4=1}
  -e[^-1] "Apply twirl deformation on image$?, with amplitude $1 and center at ($2%,$3%)."
  -v - -repeat @#
    -euclidean2polar[-1] $2,$3,1,$4 100%,100%,1,1,$1*x -channels[-1] -1,0
    -warp[-2] [-1],1,1,2 -rm[-1] -polar2euclidean[-1] $2,$3,1,1
  -mv[-1] 0 -done -v +

#@gmic map_sphere : _width>0,_height>0,_radius,_dilation>0
#@gmic : Map selected images on a sphere.
map_sphere : -skip ${1=512},${2=512},${3=100},${4=0.5}
   -e[^-1] "Map image$? on spheres in $1x$2 images, with radius $3 and dilation $4."
   -v -
   -p {($3*min($1,$2)/200)^2} # Compute squared radius.
   -repeat @#
     -i[-2] 100%,1,1,100%,0 -a[-2,-1] y # Add one border line to have a sphere exterior.
     ({-$1/2},{$1/2}) ({-$2/2};{$2/2}) -r[-2,-1] $1,$2,1,1,3 -atan2[-1] [-2] -rm[-2] # Compute theta angle.
     $1,$2 -=[-1] 1,50%,50% -distance[-1] 1 -sqr[-1] -/[-1] ~-1 -sqrt[-1] -c[-1] 0,1 -asin[-1] # Compute phi angle.
     -+[-2] {pi} -*[-2] {(@{-3,w}-1)/(2*pi)} # Normalize theta to X-coordinates
     -*[-1] {2/pi} -pow[-1] $4 -*[-1] {@{-3,h}-1} -*[-1] -1 -+[-1] {@{-3,h}-1} # Normalize phi to Y-coordinates
     -a[-2,-1] c -warp[-2] [-1],0,1,1 -rm[-1] # Apply image warping
   -mv[-1] 0 -done -v +

#@gmic flower : _amplitude,_frequency,_offset_r[%],_angle,_cx,_cy,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply flower deformation on selected images.
flower : -skip ${1=30},${2=6},${3=0},${4=0},${5=0.5},${6=0.5},${7=2}
  -e[^-1] "Apply flower deformation on image$?, with amplitude $1, frequency $2, offset $3, angle $4 and center ($1,$2)."
  -v - -repeat @#
    -euclidean2polar[-1] $5,$6,1,$7 -shift[-1] $3,0,0,0,2
    100%,100%,1,1,y -/[-1] {h} -*[-1] $2 ({$4/360}) -+[-2] @-1 -rm[-1] -*[-1] 6.2831853 -sin[-1]
    -*[-1] $1 -*[-1] {w} -/[-1] 100
    -channels[-1] 0,1 -warp[-2] [-1],1,1,$7 -rm[-1]
    -polar2euclidean[-1] $5,$6,1,1
  -mv[-1] 0 -done -v +

#@gmic zoom : _factor,_cx,_cy,_cz,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply zoom factor to selected images.
zoom : -skip ${1=2},${2=0.5},${3=0.5},${4=0.5},${5=0}
  -e[^-1] "Apply zoom effect on image$?, with factor $1 and center ($2,$3)."
  -v - -repeat @#
    -if {d==1} # 2d image.
       ({(w-1)*$2*(1-1/$1)},{(w-1)*($2+(1-$2)/$1)})
       ({(@{-2,h}-1)*$3*(1-1/$1)};{(@{-2,h}-1)*($3+(1-$3)/$1)})
       -r[-2--1] [-3],[-3],1,1,3 -a[-2--1] c -warp[-2] [-1],0,1,$5
    -else # 3d image.
       ({(w-1)*$2*(1-1/$1)},{(w-1)*($2+(1-$2)/$1)})
       ({(@{-2,h}-1)*$3*(1-1/$1)};{(@{-2,h}-1)*($3+(1-$3)/$1)})
       ({(@{-3,d}-1)*$4*(1-1/$1)}/{(@{-3,d}-1)*($4+(1-$4)/$1)})
       -r[-3--1] [-4],[-4],[-4],1,3 -a[-3--1] c -warp[-2] [-1],0,1,$5
    -endif
    -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic deform : _amplitude>=0
#@gmic : Apply random smooth deformation on selected images.
deform : -skip ${1=10}
  -e[^-1] "Apply random smooth deformation on image$?, with amplitude $1."
  -v - -repeat @#
    2%,2%,1,2 -noise[-1] $1 -r[-1] [-2],[-2],1,2,5 -warp[-2] [-1],1,1,1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic fish_eye : _x,_y,0<=_radius<=100,_amplitude>=0
#@gmic : Apply fish-eye deformation on selected images.
fish_eye : -skip ${1=50},${2=50},${3=50},${4=1.2}
  -if {$4==0} -return -endif
  -e[^-1] "Apply Fish-eye effect on image$?, centered at ($1%,$2%) with radius $3% and amplitude $4."
  -v - -repeat @#
    100%,100%,1,1 -=[-1] 1,$1%,$2% -distance[-1] 1 -c[-1] 0,$3% -*[-1] -1 -n[-1] 0,1 -pow[-1] {1/$4}
    -i[-2] ({-$1/100},{1-$1/100};{-$1/100},{1-$1/100}^{-$2/100},{-$2/100};{1-$2/100},{1-$2/100}) -r[-2] [-1],[-1],1,2,3
    -n[-1] 0,{max(w,h)} -*[-2,-1]
    -warp[-2] [-1],1,1,1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic transform_polar : "expr_radius",_"expr_angle",_x_center,_y_center,_borders={ 0 | 1 }
#@gmic : Apply user-defined transform on polar representation of selected images.
transform_polar : -skip "${1=R-r}","${2=a}",${3=50},${4=50},${5=1}
  -e[^-1] "Apply custom polar transform with 'new_r = $1', 'new_a = $2', centered at ($3%,$4%)."
  -v -
  -repeat @#
  -p {"sqrt((max($3,100-$3)*w/100)^2 + (max($4,100-$4)*h/100)^2)"}
  -p {"$3*w/100"}
  -p {"$4*h/100"}
  -f "R ="~-3";
      r = sqrt((x-"~-2")^2 + (y-"~-1")^2);
      a = atan2(y-"~-1",x-"~-2");
      nr = $1;
      na = $2;
      i("~-2" + nr*cos(na), "~-1" + nr*sin(na), z, c, $5)"
  -pp[-3--1]
  -mv[-1] 0 -done -v +

#@gmic kaleidoscope : _cx,_cy,_radius,_angle,_borders={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Create kaleidoscope effect from selected images.
kaleidoscope : -skip ${1=0.5},${2=0.5},${3=100},${4=30},${5=1}
  -e[^-1] "Create kaleidoscope effect from image$?, with center ($1,$2), radius $3, angle $4."
  -v - -euclidean2polar $1,$2,1,$5 -repeat @#
    --columns[-1] 0,$3% -lines[-1] 0,$4% -r[-1] [-2],0,2 -rm[-2]
  -mv[-1] 0 -done -polar2euclidean $1,$2,1,$5 -v +

#@gmic rotoidoscope : _cx,_cy,_tiles>0,_smoothness[%]>=0,_borders={ 0=dirichlet | 1=neumann | 2=cyclic}
#@gmic : Create rotational kaleidoscope effect from selected images.
rotoidoscope : -skip ${1=50%},${2=50%},${5=1} -check "${3=10}>0 && ${4=1}>=0"
  -e[^-1] "Create rotational kaleidoscope effect from image$?, with center ($1,$2), $3 tiles and smoothness $4."
  -v - -repeat @# -l[-1]
    -repeat $3 --rotate[0] {360/$3},$5,1,$1,$2 -compose_edges $4 -done
  -endl -mv[-1] 0 -done -v +

#-----------------------------
#
#@gmic :: Image degradation
#
#-----------------------------

#@gmic spread : _dx>=0,_dy>=0,_dz>=0
#@gmic : Spread pixel values of selected images randomly along x,y and z.
spread : -skip ${1=3},${2=$1},${3=0}
  -e[^-1] "Spread pixel of image$? randomly, with amplitudes ($1,$2,$3)."
  -v - -repeat @#
    100%,100%,100%,1 [-1]x2 -noise[-3] $1,0 -noise[-2] $2,0 -noise[-1] $3,0 -a[-3--1] c -warp[-2] [-1],1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic shade_stripes : _frequency>=0,_direction={ 0 | 1 },_darkness>=0,_lightness>=0
#@gmic : Add shade stripes to selected images.
shade_stripes : -skip ${1=5},${2=1},${3=0.8},${4=2}
  -v - -repeat @#
    -n[-1] 0,255
    -if $2 -v + -e[^-1] "Add vertical shaded stripes to image$?, with frequency $1, darkness $3 and lightness $4." -v - 100%
    -else -v + -e[^-1] "Add horizontal shaded stripes to image$?, with frequency $1, darkness $3 and lightness $4." -v - 1,100%
    -endif
    -noise[-1] $1,2 -distance[-1] 1
    -r[-1] [-2] -n[-1] $3,$4 -*[-1,-2] -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic stripes_y : _frequency>=0
#@gmic : Add vertical stripes to selected images.
stripes_y : -skip ${1=10}
  -e[^-1] "Add vertical stripes to image$?, with frequency $1."
  -v - -repeat @#
    -n[-1] 0,255 100% -noise[-1] $1,2 -*[-1] 255 -r[-1] [-2]
    -*[-1] 0.15 -+[-1,-2] -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic shadow_patch : _opacity>=0
#@gmic : Add shadow patches to selected images.
shadow_patch : -skip ${1=0.7}
  -e[^-1] "Apply shadow patches to image$?, with opacity $1."
  -v - -repeat @#
    100%,100%,1,1 -shift[-1] -2,-2 -shift[-1] 1,1
    -plasma[-1] 3,0.3 -abs[-1] -blur[-1] 1 -c[-1] 3%,15% -r[-1] [-2]
    -n[-1] $1,1 -*[-1,-2]
  -mv[-1] 0 -done -v +

#@gmic light_patch : _density>0,_darkness>=0,_lightness>=0
#@gmic : Add light patches to selected images.
light_patch : -skip ${1=10},${2=0.9},${3=1.7}
  -e[^-1] "Apply light patches to image$?, with density $1, darkness $2 and lightness $3."
  -v - -repeat @#
    -n[-1] 0,255 $1,$1 -noise[-1] 40 -r[-1] [-2],5 -c[-1] 0,255
    -n[-1] $2,$3 -*[-2,-1] -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic light_relief : _ambient_light,_specular_light,_specular_size,_darkness,_xl,_yl,_zl,_zscale,_opacity_bumpmap={ 0 | 1 }
#@gmic : Apply relief light to selected images.
light_relief : -skip ${1=0.3},${2=0.5},${3=0.2},${4=0},${5=0.2},${6=0.5},${7=0.5},${8=1},${9=1},${10=0}
  -e[^-1] "Apply relief light to image$?."
  -v - -repeat @#
    ({-$6},{1-$6};{-$6},{1-$6}^{-$7},{-$7};{1-$7},{1-$7}^$8,$8;$8,$8) -r[-1] [-2],[-2],1,3,3  # Create light vector field.
    -if $10 --channels[-2] 3 -to_rgb[-3] -else --to_rgb[-2] -norm[-1] -endif
    -blur[-1] $5% -gradient[-1] xy 100%,100%,1,1,$9  -a[-3--1] c                              # Create normal vector field.
    -orientation[-2,-1] -*[-2,-1] -s[-1] c -+[-3--1]                                          # Normalized scalar product.
    100%,100% -=[-1] 1,{$6*100}%,{$7*100}% -distance[-1] 1 -sqr[-1] -*[-1] -1                 # Compute specular attenuation.
    -/[-1] {($3*max(w,h))^2} -exp[-1] -*[-1] $2 -+[-1] $1
    -*[-2,-1] --[-1] $4 -*[-1] @{-2,M}
    -l[-2,-1] -split_opacity -rv[0--2]                                                        # Add light property to non-opaque part of the image.
    -+[-2,-1] -c[-1] 0,255
    -rv -a c -endl
  -mv[-1] 0 -done -v +

#@gmic noise_hurl : _amplitude>=0
#@gmic : Add hurl noise to selected images.
noise_hurl : -skip ${1=10}
  -e[^-1] "Add hurl noise to image$?, with amplitude $1%."
  -v - -repeat @#
    --f[-1] 0 -noise[-1] 10 -n[-1] @{-2,m,M} 100%,100%,1,1,-2
    -noise[-1] $1,2 -t[-1] 0 -r[-1] [-2]
    -*[-2] [-1] -*[-1] -1 -+[-1] 1 -*[-3,-1] -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic pixelize : _scale_x>0,_scale_y>0,_scale_z>0
#@gmic : Pixelize selected images with specified scales.
pixelize : -skip ${1=20},${2=$1},${3=$1}
  -e[^-1] "Pixelize image$? with scales ($1%,$2%,$3%)."
  -v - -repeat @#
    ({w},{h},{d}) -r[-2] $1%,$2%,$3%,[-2],2 -r[-2] @-1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic paper
#@gmic : Add paper texture to selected images.
paper :
  -e[^-1] "Add paper texture to image$?."
  -v - -repeat @#
    [-1] 30%,30% -noise[-1] 1,2 -r[-1] [-2],[-2],[-2],1,0 -ifft[-1]
    -rm[-1] -shift[-1] 50%,50%,50%,0,2 -sharpen[-1] 1 -n[-1] 1,1.2 -r[-1] [-2]
    -*[-2,-1] -c[-1] [-2],[-2] -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic cracks : _density>=0,_amplitude,_relief={ 0 | 1 }
#@gmic : Add random cracks to selected images.
cracks : -skip ${1=0.2},${2=40},${3=0}
  -e[^-1] "Add random cracks to image$?, with density $1."
  -v - -repeat @#
    (@{-1,m},@{-1,M}) [-2],[-2],1,1 -noise[-1] $1,2 -distance[-1] 1 -sharpen[-1] 10000
    -if $3 -gradient[-1] xy -+[-2,-1] -n[-1] -1,1 -else -n[-1] 0,1 -endif
    -*[-1] $2 -+[-3,-1] -c[-2] @-1 -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic watermark_visible : _text,0<_opacity<1,_size>0,_angle,_mode={ 0=remove | 1=add }
#@gmic : Add or remove a visible watermark on selected images (value range must be [0,255]).
watermark_visible : -skip "${1=\251\ G'MIC}" -check "${2=0.3}>0 && $2<1 && ${3=57}>0" -skip ${4=25},${5=1}
  -e[^-1] @{"-v - -if $5 -u Add -else -u Remove -endif -v +"}" visible watermark '$1' on image$?, with opacity $2, size $3, angle $4."
  -v -
  -repeat @#
    1 -text[-1] "$1",0,0,$3,1,255 -rotate[-1] $4,0,0 -r[-1] [-2],0,2 -+[-1] [-2] -c[-1] 0,255  # Generate opaque watermark image
    -if $5 -*[-1] $2 -*[-2] {1-$2} -+[-2,-1]  # Add watermark
    -else -*[-1] $2 --[-2,-1] -/[-1] {1-$2}   # Remove watermak
    -endif
    -c[-1] 0,255
  -mv[-1] 0 -done
  -v +

#--------------------------------
#
#@gmic :: Color-related filters
#
#--------------------------------

#@gmic apply_channels : "command",_channels={All,RGBA,RGB,Y,CbCr,Cb,Cr,L,ab,a,b,H,S,V,K,A,ch,c,h},_normalize={ 0=cut | 1=normalize }
#@gmic : Apply specified command on chosen normalized channels of each selected images.
apply_channels : -skip ${3=0}

  # Process all channels.
  -if {$2==0}
    -e[^-1] "Apply command '$1' on image$?." -v -
    -repeat @# -l[-1]
      -_apply_channels "$1"
      -if $3 -n 0,255 -else -c 0,255 -endif
    -endl -mv[-1] 0 -done

  # Process RGBA channels.
  -elif {$2==1}
    -e[^-1] "Apply command '$1' on RGBA channels of image$?." -v -
    -to_rgba -repeat @# -l[-1]
      -_apply_channels "$1"
      -if $3 -n 0,255 -else -c 0,255 -endif
    -endl -mv[-1] 0 -done

  # Process RGB channels.
  -elif {$2==2}
    -e[^-1] "Apply command '$1' on RGB channels of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0]
      -_apply_channels[0] "$1"
      -if $3 -n[0] 0,255 -else -c[0] 0,255 -endif
      -to_rgb[0]
      -a c
    -endl -mv[-1] 0 -done

  # Process Y channel.
  -elif {$2==3}
    -e[^-1] "Apply command '$1' on luminance of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2ycbcr[0] -s[0] c
      -_apply_channels[0] "$1" -channels[0] 0
      -if $3 -n[0] 0,255 -else -c[0] 0,255 -endif
      -a[0-2] c -ycbcr2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process CbCr channels.
  -elif {$2==4}
    -e[^-1] "Apply command '$1' on blue and red chrominances of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2ycbcr[0] -s[0] c
      -_apply_channels[1] "$1" -_apply_channels[2] "$1" -channels[1,2] 0
      -if $3 -n[1,2] 0,255 -else -c[1,2] 0,255 -endif
      -a[0-2] c -ycbcr2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process Cb channel.
  -elif {$2==5}
    -e[^-1] "Apply command '$1' on blue chrominance of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2ycbcr[0] -s[0] c
      -_apply_channels[1] "$1" -channels[1] 0
      -if $3 -n[1] 0,255 -else -c[1] 0,255 -endif
      -a[0-2] c -ycbcr2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process Cr channel.
  -elif {$2==6}
    -e[^-1] "Apply command '$1' on red chrominance of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2ycbcr[0] -s[0] c
      -_apply_channels[2] "$1" -channels[2] 0
      -if $3 -n[2] 0,255 -else -c[2] 0,255 -endif
      -a[0-2] c -ycbcr2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process L channel.
  -elif {$2==7}
    -e[^-1] "Apply command '$1' on lightness of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lab[0] -s[0] c
      -*[0] 2.55 -_apply_channels[0] "$1" -channels[0] 0 -/[0] 2.55
      -if $3 -n[0] 0,100 -else -c[0] 0,100 -endif
      -a[0-2] c -lab2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process a-b channels.
  -elif {$2==8}
    -e[^-1] "Apply command '$1' on a-b channels of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lab[0] -s[0] c
      -+[1] 86 -*[1] 1.38587 -+[2] 108 -*[2] 1.25616 -_apply_channels[1] "$1" -_apply_channels[2] "$1"
      -channels[1,2] 0 -/[1] 1.38587 --[1] 86 -/[2] 1.25616 --[2] 108
      -if $3 -n[1] -86,98 -n[2] -108,95 -endif
      -a[0-2] c -lab2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process a-channel.
  -elif {$2==9}
    -e[^-1] "Apply command '$1' on a-channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lab[0] -s[0] c
      -+[1] 86 -*[1] 1.38587 -_apply_channels[1] "$1" -channels[1] 0 -/[1] 1.38587 --[1] 86
      -if $3 -n[1] -86,98 -endif
      -a[0-2] c -lab2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process b-channel.
  -elif {$2==10}
    -e[^-1] "Apply command '$1' on b-channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lab[0] -s[0] c
      -+[2] 108 -*[2] 1.25616 -_apply_channels[2] "$1" -channels[2] 0 -/[2] 1.25616 --[2] 108
      -if $3 -n[1] -108,95 -endif
      -a[0-2] c -lab2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process H channel.
  -elif {$2==11}
    -e[^-1] "Apply command '$1' on hue of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2hsv[0] -s[0] c
      -*[0] 0.708333 -_apply_channels[0] "$1" -channels[0] 0 -/[0] 0.708333
      -if $3 -n[0] 0,360 -else -mod[0] 360 -endif
      -a[0-2] c -hsv2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process S channel.
  -elif {$2==12}
    -e[^-1] "Apply command '$1' on saturation of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2hsv[0] -s[0] c
      -*[1] 255 -_apply_channels[1] "$1" -channels[1] 0 -/[1] 255
      -if $3 -n[1] 0,1 -else -c[1] 0,1 -endif
      -a[0-2] c -hsv2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process V channel.
  -elif {$2==13}
    -e[^-1] "Apply command '$1' on value of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2hsv[0] -s[0] c
      -*[2] 255 -_apply_channels[2] "$1" -channels[2] 0 -/[2] 255
      -if $3 -n[2] 0,1 -else -c[2] 0,1 -endif
      -a[0-2] c -hsv2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process K channel.
  -elif {$2==14}
    -e[^-1] "Apply command '$1' on key channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2cmyk[0] -s[0] c
      -_apply_channels[3] "$1" -channels[3] 0
      -if $3 -n[3] 0,255 -else -c[3] 0,255 -endif
      -a[0-3] c -cmyk2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process Alpha channel.
  -elif {$2==15}
    -e[^-1] "Apply command(s) '$1' on alpha channel of image$?." -v -
    -repeat @# -l[-1]
      -to_rgba -split_opacity
      -_apply_channels[1] "$1" -channels[1] 0
      -if $3 -n[1] 0,255 -else -c[1] 0,255 -endif
      -a c
    -endl -mv[-1] 0 -done

  # Process c-h channels.
  -elif {$2==16}
    -e[^-1] "Apply command '$1' on c-h channels of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lch[0] -s[0] c
      -*[1] 2.55 -+[2] {pi} -*[2] {255/(2*pi)} -_apply_channels[1] "$1" -_apply_channels[2] "$1"
      -channels[1,2] 0 -/[1] 2.55 -/[2] {255/(2*pi)} --[2] {pi}
      -if $3 -n[1] 0,100 -n[2] -{pi},{pi} -endif
      -a[0-2] c -lch2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process c-channel.
  -elif {$2==17}
    -e[^-1] "Apply command '$1' on c-channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lch[0] -s[0] c
      -*[1] 2.55 -_apply_channels[1] "$1" -channels[1] 0 -/[1] 2.55
      -if $3 -n[1] 0,100 -else -c[1] 0,100 -endif
      -a[0-2] c -lch2rgb[0] -a c
    -endl -mv[-1] 0 -done

  # Process h-channel.
  -else
    -e[^-1] "Apply command '$1' on h-channel of image$?." -v -
    -repeat @# -l[-1]
      -split_opacity -to_rgb[0] -rgb2lch[0] -s[0] c
      -+[2] {pi} -*[2] {255/(2*pi)} -_apply_channels[2] "$1" -channels[2] 0 -/[2] {255/(2*pi)} --[2] {pi}
      -if $3 -n[2] -{pi},{pi} -endif
      -a[0-2] c -lch2rgb[0] -a c
    -endl -mv[-1] 0 -done
  -endif
  -v +

_apply_channels :
  ${^0} -k[0]

#@gmic to_gray
#@gmic : Force selected images to be in GRAY mode.
to_gray :
  -e[^-1] "Force image$? to be in GRAY mode."
  -v - -repeat @#
    -if {s>4} -error[] "Image ["@{<,-1}"] is not a G,GA,RGB or RGBA image."
    -elif {s>=3} -channels[-1] 0,2 -luminance[-1]
    -elif {s==2} -r[-1] 100%,100%,100%,1,0
    -endif
  -mv[-1] 0 -done -v +

#@gmic to_graya
#@gmic : Force selected images to be in GRAYA mode.
to_graya :
  -e[^-1] "Force image$? to be in GRAYA mode."
  -v - -repeat @#
    -if {s>4} -error[] "Image ["@{<,-1}"] is not a G,GA,RGB or RGBA image."
    -elif {s==4} --channels[-1] 3 -channels[-2] 0,2 -luminance[-2] -a[-2,-1] c
    -elif {s==3} -luminance[-1] -channels[-1] 0,1 --sh[-1] 1,1 -f[-1] 255 -rm[-1]
    -elif {s==1} -channels[-1] 0,1 --sh[-1] 1,1 -f[-1] 255 -rm[-1]
    -endif
  -mv[-1] 0 -done -v +

#@gmic to_rgb
#@gmic : Force selected images to be in RGB mode.
to_rgb :
   -e[^-1] "Force image$? to be in RGB mode."
   -v - -repeat @#
     -if {s>4} -error[] "Image ["@{<,-1}"] is not a G,GA,RGB or RGBA image."
     -elif {s==4} -channels[-1] 0,2
     -elif {s==2} -channels[-1] 0,0 -r[-1] 100%,100%,100%,3
     -elif {s==1} -r[-1] 100%,100%,1,3
     -endif
   -mv[-1] 0 -done -v +

#@gmic to_rgba
#@gmic : Force selected images to be in RGBA mode.
to_rgba :
   -e[^-1] "Force image$? to be in RGBA mode."
   -v - -repeat @#
     -if {s>4} -error[] "Image ["@{<,-1}"] is not a G,GA,RGB or RGBA image."
     -elif {s==3} -channels[-1] 0,3 --sh[-1] 3,3 -f[-1] 255 -rm[-1]
     -elif {s==2} -r[-1] 100%,100%,100%,4 --sh[-1] 2,2 -f[-1] [-2] -rm[-1]
     -elif {s==1} -r[-1] 100%,100%,1,4 --sh[-1] 3,3 -f[-1] 255 -rm[-1]
     -endif
   -mv[-1] 0 -done -v +

#@gmic to_colormode : mode={ 0=adaptive | 1=G | 2=GA | 3=RGB | 4=RGBA }
#@gmic : Force selected images to be in a given color mode.
to_colormode : -skip ${1=0}
  -if {$1==1} -to_gray
  -elif {$1==2} -to_graya
  -elif {$1==3} -to_rgb
  -elif {$1==4} -to_rgba
  -else
    -p 1 -repeat @#
      -if {@{~>,s}>4} -error "Image ["~>"] is not a G,GA,RGB or RGBA image."
      -else -p=[-1] {max(~-1,@{~>,s})}
      -endif
    -done -to_colormode ~-1
  -endif

#@gmic remove_opacity
#@gmic : Remove opacity channel of selected images.
remove_opacity :
  -e[^-1] "Remove opacity channel of image$?."
  -v - -repeat @#
    -if {s==2} -channels[-1] 0,0
    -elif {s==4} -channels[-1] 0,2
    -endif
  -mv[-1] 0 -done -v +

#@gmic select_color : _tolerance[%]>=0,col1,..,colN
#@gmic : Select pixels with specified color in selected images.
select_color : -skip ${1=1}
  -e[^-1] "Select color (${2--1}) in image$?, with tolerance $1."
  -v - -repeat @#
    (${2--1}) -unroll[-1] c -r[-1] [-2] --[-2,-1] -norm[-1] -t[-1] $1 -*[-1] -1 -+[-1] 1
  -mv[-1] 0 -done -v +

#@gmic replace_color : _tolerance[%]>=0,_smoothness[%]>=0,src1,...,srcN,dest1,...,destN
#@gmic : Replace pixels from/to specified colors in selected images.
replace_color :
  -v - (${3--1}) -unroll[-1] c -s[-1] c,2
  -v + -e[^-1] "Replace color ("@-2") to color ("@-1") in image$?, with tolerance $1 and smoothness $2." -v -
  -rm[-2,-1] -repeat @#
    (${3--1}) -unroll[-1] c -s[-1] c,2 -r[-2,-1] 1,1,1,@{-3,s} --[-1] [-2]
    -r[-2] [-3] --[-2] [-3] -norm[-2] -t[-2] {$1+1e-8} -blur[-2] $2 -*[-2] -1 -+[-2] 1
    -mv[-2] @# -r[-2] [-1],[-1] -*[-2,-1] -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic fc : eq. to '-fill_color'.
fc :
  -fill_color ${^0}

#@gmic fill_color : col1,...,colN
#@gmic : Fill selected images with specified color.
#@gmic : (eq. to '-fc').
fill_color :
  -e[^-1] "Fill image$? with color (${^0})."
  -v - -repeat @#
    -repeat {s} --sh[-1] ~>,~> -f[-1] {arg(1+~>,${1--1})} -rm[-1] -done
  -mv[-1] 0 -done -v +

#@gmic luminance
#@gmic : Compute luminance of selected images.
luminance :
  -e[^-1] "Compute luminance of image$?."
  -v - -to_rgb -rgb2ycbcr -channels 0 -v +

#@gmic mix_rgb : a11,a12,a13,a21,a22,a23,a31,a32,a33
#@gmic : Apply 3x3 specified matrix to RGB colors of selected images.
mix_rgb : -skip ${1=1},${2=0},${3=0},${4=0},${5=1},${6=0},${7=0},${8=0},${9=1}
  -e[^-1] "Apply matrix [ $1 $2 $3 ; $4 $5 $6 ; $7 $8 $9 ] to RGB colors of image$?."
  -v - -repeat @#
    -r[-1] 100%,100%,1,3,0,2 -s[-1] c
    --*[-3] $4 --*[-3] $5 -+[-1,-2] --*[-2] $6 -+[-1,-2]
    --*[-4] $7 --*[-4] $8 -+[-1,-2] --*[-3] $9 -+[-1,-2]
    -*[-5] $1 -*[-4] $2 -*[-3] $3 -+[-5--3] -a[-3--1] c
  -mv[-1] 0 -done -v +

#@gmic mix_channels : (a00,...,aMN)
#@gmic : Apply specified matrix to channels of selected images.
mix_channels :
  -e[^-1] "Apply matrix $1 to channels of image$?."
  -v - -repeat @#
    -p {w},{h},{d}
    -r[-1] {w*h*d},{s},1,1,-1
    -i[-2] ${^0} -**[-2,-1]
    -r[-1] ~-1,{h},-1 -pp[-1]
  -mv[-1] 0 -done -v +

#@gmic solarize
#@gmic : Solarize selected images.
solarize :
  -e[^-1] "Solarize image$?."
  -v - -luminance -n 0,128 -map 1 -v +

#@gmic sepia
#@gmic : Apply sepia tones effect on selected images.
sepia :
  -e[^-1] "Apply sepia tones effect on image$?."
  -v - -luminance (0,44,115,143,196,244^0,20,84,119,184,235^0,5,44,73,144,200)
  -r[-1] 256,1,1,3,3 -map[0--2] [-1] -rm[-1] -v +

#@gmic split_opacity
#@gmic : Split color and opacity parts of selected images.
split_opacity :
  -e[^-1] "Split color and opacity parts of image$?."
  -v - -repeat @#
    -if {s==2} -s[-1] c -mv[-2,-1] 0
    -elif {s==4} --channels[-1] 3,3 -channels[-2] 0,2 -mv[-2,-1] 0
    -else -mv[-1] 0
    -endif
  -done -v +

#@gmic red_eye : 0<=_threshold<=100,_smoothness>=0,0<=attenuation<=1
#@gmic : Attenuate red-eye effect in selected images.
red_eye : -skip ${1=75},${2=3.5},${3=0.1}
  -e[^-1] "Attenuate red-eye effect in image$?, with threshold $1, smoothness $2 and attenuation $3."
  -v - -to_rgb -rgb2ycbcr -repeat @#
    -s[-1] c --[-1] 128 --t[-1] $1% -blur[-1] $2 -sqrt[-1] -*[-1] -1 -+[-1] 1
    -n[-1] $3,1 -*[-2,-1] -+[-1] 128 -a[-3--1] c -ycbcr2rgb[-1]
  -mv[-1] 0 -done -v +

#@gmic rgb2lch
#@gmic : Convert selected images from RGB to Lch color bases.
rgb2lch :
  -e[^-1] "Convert image$? from RGB to Lch color bases."
  -v - -rgb2lab -lab2lch -v +

#@gmic lch2rgb
#@gmic : Convert selected images from Lch to RGB color bases.
lch2rgb :
  -e[^-1] "Convert image$? from Lch to RGB color bases."
  -v - -lch2lab -lab2rgb -v +

#@gmic lab2lch
#@gmic : Convert selected images from Lab to Lch color bases.
lab2lch :
  -e[^-1] "Convert image$? from Lab to Lch color bases."
  -v - -r 100%,100%,100%,3 -repeat @#
    -s[-1] c --sqr[-1,-2] -+[-1,-2] -sqrt[-1] --atan2[-3] [-2] -rm[-3,-4] -a[-3--1] c
  -mv[-1] 0 -done -v +

#@gmic lch2lab
#@gmic : Convert selected images from Lch to Lab color bases.
lch2lab :
  -e[^-1] "Convert image$? from Lch to Lab color bases."
  -v - -r 100%,100%,100%,3 -repeat @#
    -s[-1] c --sin[-1] --cos[-2] -*[-2,-1] [-4] -a[-5,-2,-1] c -rm[-1,-2]
  -mv[-1] 0 -done -v +

#--------------------------------------
#
#@gmic :: Image fading and composition
#
#--------------------------------------

#@gmic fade_x : 0<=_start<=100,0<=_end<=100
#@gmic : Create horizontal fading from selected images.
fade_x : -skip ${1=30},${2=70}
  -e[^-1] "Create ($1%,$2%) horizontal fading from image$?."
  -v - -repeat {int(@#/2)}
    (0,1) -_fade $1,$2
  -mv[-1] 0 -done -v +

#@gmic fade_y : 0<=_start<=100,0<=_end<=100
#@gmic : Create vertical fading from selected images.
fade_y : -skip ${1=30},${2=70}
  -e[^-1] "Create ($1%,$2%) vertical fading from image$?."
  -v - -repeat {int(@#/2)}
    (0;1) -_fade $1,$2
  -mv[-1] 0 -done -v +

#@gmic fade_z : 0<=_start<=100,0<=_end<=100
#@gmic : Create transversal fading from selected images.
fade_z : -skip ${1=30},${2=70}
  -e[^-1] "Create ($1%,$2%) transversal fading from image$?."
  -v - -repeat {int(@#/2)}
    (0/1) -_fade $1,$2
  -mv[-1] 0 -done -v +

#@gmic fade_radial : 0<=_start<=100,0<=_end<=100
#@gmic : Create radial fading from selected images.
fade_radial : -skip ${1=30},${2=70}
  -e[^-1] "Create ($1%,$2%) radial fading from image$?."
  -v - -repeat {int(@#/2)}
    100%,100% -point 50%,50%,0,1,1 -distance[-1] 1 -_fade $1,$2
  -mv[-1] 0 -done -v +

#@gmic fade_diamond : 0<=_start<=100,0<=_end<=100
#@gmic : Create diamond fading from selected images.
fade_diamond : -skip ${1=70},${2=90}
  -e[^-1] "Create ($1%,$2%) diamond-shaped fading from image$?."
  -v - -repeat {int(@#/2)}
    (0,1,0;1,1,1;0,1,0) -_fade $1,$2
  -mv[-1] 0 -done -v +

#@gmic fade_linear : _angle,0<=_start<=100,0<=_end<=100
#@gmic : Create linear fading from selected images.
fade_linear : -skip ${1=45},${2=30},${3=70}
  -e[^-1] "Create ($2%,$3%) linear fading from image$?, with angle $1."
  -v - -repeat {int(@#/2)}
     64,64,1,1,"x*cos($1*pi/180) + y*sin($1*pi/180)" -_fade $2,$3
  -mv[-1] 0 -done -v +

_fade :
  -r[-2] [-3],5 -r[-1] [-2],3 -c[-1] $1%,$2% -n[-1] 0,1 --*[-1] -1 -+[-1] 1 -*[-4,-1] -*[-2,-1] -+[-2,-1]

#@gmic compose_rgba
#@gmic : Compose selected RGBA images two-by-two, over RGB background.
compose_rgba :
  -e[^-1] "Compose RGBA image$? two-by-two, over RGB background."
  -v - -repeat {int(@#/2)}
    -to_rgb[-2] -r[-1] [-2],[-2],1,100%,0 -to_rgba[-1]
    -s[-1] c -a[-4--2] c -/[-1] 255 [-1] -negative[-1] -r[-4--1] 100%,100%,1,3
    -*[-4,-1] -*[-2,-1] -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic compose_channels
#@gmic : Compose all channels of each selected image, using specified arithmetic operator (+,-,or,min,...).
compose_channels : -skip ${1="+"}
  -e[^-1] "Compose all channels of image$?, with operator '$1'."
  -v - -repeat @#
    --sh[-1] 0,0
    -repeat {@{-2,s}-1} --sh[-2] {~>+1},{~>+1} -$1[-2,-1] -done
    -rm[-1] -r[-1] 100%,100%,100%,1,-1
  -mv[-1] 0 -done -v +

#@gmic compose_average
#@gmic : Compose selected images two-by-two, using average mode.
compose_average :
  -e[^-1] "Compose image$? two-by-two, using average mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 -+[-2,-1] -/[-1] 2
  -mv[-1] 0 -done -v +

#@gmic compose_multiply
#@gmic : Compose selected images two-by-two, using multiply mode.
compose_multiply :
  -e[^-1] "Compose image$? two-by-two, using multiply mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 -*[-2,-1] -/[-1] 256
  -mv[-1] 0 -done -v +

#@gmic compose_screen
#@gmic : Compose selected images two-by-two, using screen mode.
compose_screen :
  -e[^-1] "Compose image$? two-by-two, using screen mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 --[-2,-1] 255 -*[-2,-1] -/[-1] 256 --[-1] 255 -*[-1] -1
  -mv[-1] 0 -done -v +

#@gmic compose_darken
#@gmic : Compose selected images two-by-two, using darken mode.
compose_darken :
  -e[^-1] "Compose image$? two-by-two, using darken mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 -min[-2] [-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic compose_lighten
#@gmic : Compose selected images two-by-two, using lighten mode.
compose_lighten :
  -e[^-1] "Compose image$? two-by-two, using lighten mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 -max[-2] [-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic compose_difference
#@gmic : Compose selected images two-by-two, using difference mode.
compose_difference :
  -e[^-1] "Compose image$? two-by-two, using difference mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 --[-2,-1] -abs[-1]
  -mv[-1] 0 -done -v +

#@gmic compose_negation
#@gmic : Compose selected images two-by-two, using negation mode.
compose_negation :
  -e[^-1] "Compose image$? two-by-two, using negation mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 -+[-2,-1] --[-1] 255 -abs[-1] --[-1] 255 -*[-1] -1
  -mv[-1] 0 -done -v +

#@gmic compose_exclusion
#@gmic : Compose selected images two-by-two, using exclusion mode.
compose_exclusion :
  -e[^-1] "Compose image$? two-by-two, using exclusion mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 --*[-2] [-1] -/[-1] -128 -+[-3--1]
  -mv[-1] 0 -done -v +

#@gmic compose_overlay
#@gmic : Compose selected images two-by-two, using overlay mode.
compose_overlay :
  -e[^-1] "Compose image$? two-by-two, using overlay mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0
    --t[-2] 128
    --*[-3] [-2] -/[-1] 128
    --[-4,-3] 255 -*[-4,-3] -/[-3] 128 --[-3] 255 -*[-3] -1
    -*[-3] [-2] -*[-2] -1 -+[-2] 1 -*[-2,-1]
    -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic compose_hardlight
#@gmic : Compose selected images two-by-two, using hard light mode.
compose_hardlight :
  -e[^-1] "Compose image$? two-by-two, using hard light mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0
    --t[-1] 128
    --*[-3] [-2] -/[-1] 128
    --[-4,-3] 255 -*[-4,-3] -/[-3] 128 --[-3] 255 -*[-3] -1
    -*[-3] [-2] -*[-2] -1 -+[-2] 1 -*[-2,-1]
    -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic compose_softlight
#@gmic : Compose selected images two-by-two, using soft light mode.
compose_softlight :
  -e[^-1] "Compose image$? two-by-two, using soft light mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 -/[-2,-1] 256 --*[-2] [-1] -*[-1] 2 -sqr[-3] -*[-2] [-3] -*[-2] -2 -+[-3--1] -*[-1] 256
  -mv[-1] 0 -done -v +

#@gmic compose_dodge
#@gmic : Compose selected images two-by-two, using dodge mode.
compose_dodge :
  -e[^-1] "Compose image$? two-by-two, using dodge mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 --[-1] 255.1 -/[-2,-1] -*[-1] -256 -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic compose_colorburn
#@gmic : Compose selected images two-by-two, using color burn mode.
compose_colorburn :
  -e[^-1] "Compose image$? two-by-two, using colorburn mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 --[-2] 255 -+[-1] 0.1 -/[-2,-1] -*[-1] 256 -+[-1] 255 -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic compose_reflect
#@gmic : Compose selected images two-by-two, using reflect mode.
compose_reflect :
  -e[^-1] "Compose image$? two-by-two, using reflect mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 -sqr[-2] --[-1] 255.1 -/[-2,-1] -*[-1] -1 -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic compose_freeze
#@gmic : Compose selected images two-by-two, using freeze mode.
compose_freeze :
  -e[^-1] "Compose image$? two-by-two, using freeze mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 --[-2] 255 -sqr[-2] -+[-1] 0.1 -/[-2,-1] --[-1] 255 -*[-1] -1 -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic compose_stamp
#@gmic : Compose selected images two-by-two, using stamp mode.
compose_stamp :
  -e[^-1] "Compose image$? two-by-two, using stamp mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 -*[-1] 2 -+[-2,-1] --[-1] 255 -c[-1] 0,255
  -mv[-1] 0 -done -v +

#@gmic compose_interpolation
#@gmic : Compose selected images two-by-two, using interpolation mode.
compose_interpolation :
  -e[^-1] "Compose image$? two-by-two, using interpolation mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 -*[-2,-1] 0.012271846 -cos[-2,-1] -/[-2,-1] -4 -+[-2,-1] -+[-1] 0.5 -*[-1] 256
  -mv[-1] 0 -done -v +

#@gmic compose_xor
#@gmic : Compose selected images two-by-two, using xor mode.
compose_xor :
  -e[^-1] "Compose image$? two-by-two, using xor mode."
  -v - -remove_opacity -to_colormode 0 -repeat {int(@#/2)}
    -r[-1] [-2],0 -xor[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic compose_edges : _smoothness[%]>=0
#@gmic : Compose selected images togethers using edge composition.
compose_edges : -check {{$1}>=0}
  -e[^-1] "Compose image$? using edge composition, with smoothness $1."
  -if {@#>1} -v - -to_rgb -repeat @#
    --gradient_norm[-1] -+[-1] 1 -blur[-1] $1 -n[-1] 1,10 -sqr[-1] -s[-2] c -*[-4--2] [-1] -a[-4--1] c
  -mv[-1] 0 -done -r[1--1] [0],0,0,0.5,0.5 -+ -s[-1] c -/[-4--2] [-1] -rm[-1] -a[-3--1] c -v + -endif

#@gmic compose_fade
#@gmic : Compose selected images togethers using a given fading (defined as the latest image).
compose_fade :
  -e[^-1] "Compose image$? using fading composition."
  -v - -r[1--1] @{"-max_whd"},100%,3
  -r[1--2] 100%,100%,100%,@{"-max_s"} -channels[-1] 0
  -repeat {@#-1}
    ---[-1] ~> -abs[-1] --[-1] 1 -*[-1] -1 -max[-1] 0 -*[~>,-1]
  -done
  -rm[-1] -+ -v +

#@gmic compose_shapeaverage
#@gmic : Compose selected images two-by-two, using shape average mode.
compose_shapeaverage :
  -e[^-1] "Compose image$? two-by-two, using shape average mode."
  -v - -repeat {int(@#/2)} -l[-2,-1]
    -to_colormode[-1] @{-2,s} -r[-1] [-2],1 -t[-1] 50% -s c
    -p[0] {int(@#/2)} -repeat ~0 -_compose_shapeaverage[0,~0] -p=[0] {~0-1} -mv[0] @# -done -pp[0]
    -a c
  -endl -mv[-1] 0 -done -v +

_compose_shapeaverage :
  -+[-2] 1000 -*[-2,-1]
  -repeat {sqrt(w*h*d)/2} # Start with random filling (fast).
    ({?(w)},{?(h)},{?(d)})
    -if {@{-2,(@-1)}>=1000}
      --flood[-2] @{-1,0-2},256,1,10000
      -t[-1] 9999 -p[0] @{-1,+} -*[-1] [-3]
      -flood[-3] @{-2,0-2},256,1,{@{-1,+}/~0-1000}
      -rm[-2,-1] -pp[0]
    -else -rm[-1]
    -endif
  -done
  -do  # Complete with deterministic filling (slow).
    (@{-1,C})
    -if {@{-2,(@-1)}>=1000}
      --flood[-2] @{-1,0-2},256,1,10000
      -t[-1] 9999 -p[0] @{-1,+} -*[-1] [-3]
      -flood[-3] @{-2,0-2},256,1,{@{-1,+}/~0-1000}
      -rm[-2,-1] -pp[0]
    -else -rm[-1] -b
    -endif
  -while 1

#---------------------------------------------
#
#@gmic :: Motion-related and video processing
#
#---------------------------------------------

#@gmic cross_correlation
#@gmic : Compute cross-correlation using two-by-two selected images.
cross_correlation :
  -e[^-1] "Compute cross-correlation using two-by-two image$?."
  -v - -repeat {int(@#/2)}
    -norm[-2,-1] -fft[-2] -fft[-1] [-2,-1] -mul[-2] [-5] -mul[-1] [-6]
    --[-2,-1] -*[-5,-3] -*[-3,-2] -+[-3,-2] -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic normalized_cross_correlation
#@gmic : Compute normalized cross-correlation using two-by-two selected images.
normalized_cross_correlation :
  -e[^-1] "Compute normalized cross-correlation using two-by-two image$?."
  -v - -repeat {int(@#/2)}
    -norm[-2,-1] -fft[-2] -fft[-1] [-2,-1] -mul[-2] [-5] -mul[-1] [-6]
    --[-2,-1] -*[-5,-3] -*[-3,-2] -+[-3,-2] [-2,-1] -a[-2,-1] c -norm[-1]
    -/[-3] [-1] -/[-2,-1] -ifft[-2,-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic phase_correlation
#@gmic : Estimate translation vector using two-by-two selected images.
phase_correlation :
  -e[^-1] "Estimate translation vector using two-by-two image$?."
  -v - -repeat {int(@#/2)}
    -normalized_cross_correlation[-2,-1]
    (@{-1,C}) -*[-1] 2 -s[-1] x -rm[-1]
    -if {@-3>@{-4,w}} --[-3] @{-4,w} --[-3] @{-4,w} -endif
    -if {@-2>@{-4,h}} --[-2] @{-4,h} --[-2] @{-4,h} -endif
    -if {@-1>@{-4,d}} --[-1] @{-4,d} --[-1] @{-4,d} -endif
    -a[-3--1] c -/[-1] 2 -*[-1] -1 -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic morph : nb_frames>0,_smoothness>=0,_precision>0
#@gmic : Create morphing sequence between selected images.
morph : -skip $1,${2=0.2},${3=0.1}
  -e[^-1] "Create morphing sequence between image$?, with $1 intra-frames, smoothness $2 and precision $3.\n"
  -v - -r[1--1] [0],3 -i[0] (@#) --[0] 1 -repeat @0
   -v + -e[] "\r > Morph image "~>" to image "{~>+1}".    " -v -
    --equalize[-2,-1] 256 -n[-2,-1] 0,255
    --displacement[-2] [-1],$2,$3 --warp[-5] [-1],1,1,1,$1 -a[-$1--1] z -rm[-2]
    --displacement[-2] [-3],$2,$3 --warp[-5] [-1],1,1,1,$1 -a[-$1--1] z -rm[-7--4,-2]
    (1/0) -r[-1] [-2],3 -*[-3] [-1] -*[-2,-1] -mirror[-1] z -+[-2,-1] -s[-1] z
    -mv[-$1--1] 1 -mv[1] @#
  -done -mv[-1] 1 -rm[0] -v +

#@gmic register_nonrigid : _smoothness>=0,_precision>0,_nb_scale>=0
#@gmic : Register selected images with non-rigid warp.
register_nonrigid : -skip ${1=0.2},${2=0.1},${3=0}
  -e[^-1] "Register image$? with non-rigid warp, smoothness $1, precision $2 and $3 scale(s)."
  -v - --equalize[0] 256 -n[-1] 0,255 -mv[-1] 1
  -repeat @# -if {~>>1}
    --equalize[-1] 256 -n[-1] 0,255 -displacement[-1] [1],$1,$2,$3
    -warp[-2] [-1],1,1,1 -rm[-1]
  -mv[-1] 2 -endif -done -rm[1] -v +

#@gmic register_rigid : _smoothness>=0
#@gmic : Register selected images with rigid warp.
register_rigid : -skip ${1=1}
  -e[^-1] "Register image$? with rigid warp and smoothness $1."
  -v - --equalize[0] 256 -blur[-1] $1 -n[-1] 0,255 -mv[-1] 1
  -repeat @# -if {~>>1}
    --equalize[-1] 256 -blur[-1] $1 -n[-1] 0,255 --phase_correlation[1,-1] -rm[-2] -*[-1] -1 -round[-1] 1
    -shift[-2] @-1,0,1 -rm[-1]
  -mv[-1] 2 -endif -done -rm[1] -v +

#@gmic deinterlace : _method={ 0 | 1 }
#@gmic : Deinterlace selected images ('method' can be { 0=standard or 1=motion-compensated }).
deinterlace : -skip ${1=0}
  -if $1 -e[^-1] "Deinterlace image$? with motion-compensated method."
  -else  -e[^-1] "Deinterlace image$? with standard method."
  -endif
  -v - -repeat @#
    -i[-2] ({w},{h})
    -if {$1==0}
      -l[-1] -s y -a[0--1:2] y -a[1--1] y -r[-2] [-1],0 -r[-2,-1] 100%,200%,100%,100%,5
      -+[-2,-1] -/[-1] 2 -c[-1] 0,255 -endl
    -else
      -l[-1] -s y -a[0--1:2] y -a[1--1] y -r[-2] [-1],0 -r[-2,-1] 100%,200%,1,100%,5
      --displacement[-2] [-1],0.05 -warp[-3] [-1],1,1,1 -rm[-1]
      -+[-2,-1] -/[-1] 2 -c[-1] 0,255 -endl
    -endif
    -r[-1] @-2 -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic animate
#@gmic : filter_name,"param1_start,..,paramN_start","param1_end,..,paramN_end",nb_frames>=0,_output_frames={ 0 | 1 },_filename |
#@gmic : delay>0\n
#@gmic : Animate filter from starting parameters to ending parameters.
animate : -skip ${1=30},${2=0},${3=""},${4=0},${5=1},${6=""}
  -if {isval($1)}
    -if $2 -e[0--4] "Animate image$?, with a delay of $1 ms, and ping-pong mode."
    -else -e[0--4] "Animate image$?, with a delay of $1 ms."
    -endif
    -if {!@#} -return -endif
    -v -
    -p $1    # Animation speed
    -p 1     # Animation direction.
    -p 0     # Current frame.
    -do
      -w[~-1] -1,-1,1,0,@{~-1,b}.@{~-1,x}
      -p=[-1] {~-1+~-2}
      -if $2
        -if {~-1==-1} -p=[-1] 0 -p=[-2] 1
        -elif {~-1==@#} -p=[-1] {@#-1} -p=[-2] -1
        -endif
      -else -p=[-1] {~-1%@#}
      -endif
      -wait ~-3
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,D}} -w[] {@{!,w}*1.5},{@{!,h}*1.5} -wait -1 -endif # Increase window size.
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,C}} -w[] {@{!,w}/1.5},{@{!,h}/1.5} -wait -1 -endif # Decrease window size.
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,R}} -w[] @{0,w},@{0,h} -wait -1 -endif             # Reset window size.
      -if @{!,o} -p=[-3] {min(500,max(10,~-3+10*@{!,o}))} -wait -1 -endif
    -while {@!" && "!@{!,Q}" && "!@{!,ESC}} -v +
  -else
    -e[0--3] "Compute animated version of filter '$1', from parameters $2 to $3 with $4 frames."
    -if {!($5||narg("$6"))} -return -endif
    -v - ($2) ($3) -unroll[-2,-1] x -a[-2,-1] y -r[-1] 100%,$4,1,1,3 -mv[-1] 0 -progress 0
    -repeat {@#-1}
      -v + -e[] " > Animate image ["~>"]" -v -
      -repeat $4 --l[0,1]
        -$1[-1] @{0,{~>*@{0,w}}-{(~>+1)*@{0,w}-1}} -rm[0]
        -if {narg("$6")} -o @{"-filename \"$6\","@{>,-2},~>} -endif
        -if {!$5} -rm -endif
        -progress {100*(~>+1)/$4}
        -v + -e[] "\r > Animate image ["@{>,-2}"] : Frame "{~>+1}"/$4    " -v -
      -endl -done
    -rm[1] -done -rm[0] -v +
  -endif

#------------------------------
#
#@gmic ::  3d-related filters
#
#------------------------------

#@gmic empty3d
#@gmic : Create new empty 3d object.
empty3d :
  -e[^-1] "Create new empty 3d object."
  -v - (67.5;73.5;109.5;103.5;51.5;100.5;0;0) -v +

#@gmic apply_pose3d : p1,..,p12
#@gmic : Apply 3d pose matrix to selected 3d objects.
apply_pose3d :
  -e[^-1] "Apply 3d pose matrix [ $1,$2,$3,$4; $5,$6,$7,$8; $9,$10,$11,$12 ] to 3d object$?."
  -v - -repeat @# -l[-1] -s3d
    -r[2] 3,{@{2,#}/3},1,1,-1 -s[2] x
    --*[2] $5 --*[3] $6 --*[4] $7 -+[-3--1] -+[-1] $8
    --*[2] $9 --*[3] $10 --*[4] $11 -+[-3--1] -+[-1] $12
    -*[2] $1 -*[3] $2 -*[4] $3 -+[2-4] -+[2] $4
    -a[2,-2,-1] x -r[2] 1,{@{2,#}},1,1,-1
  -a y -endl -mv[-1] 0 -done -v +

#@gmic animate3d : _width>0,_height>0,_dx,_dy,_dz,_zoom>=0,_filename
#@gmic : Animate selected 3d objects in a window.
animate3d : -skip ${1=640},${2=480},${3=0},${4=10},${5=0},"${7=""}" -check ${6=1}>=0
  -e[^-1] "Animate 3d object$?, in a $1x$2 window with angle velocities ($3,$4,$5)."
  -v - -repeat @#
    --n3d[~>] -*3d[-1] {$6*min($1,$2)/1.5} -c3d[-1] (0,0,0)
    -p[0] 0
    -do
       --rot3d[-2] 1,0,0,@{-1,0} -rot3d[-1] 0,1,0,@{-2,1} -rot3d[-1] 0,0,1,@{-2,2} ($3,$4,$5) -+[-3,-1]
       $1,$2,1,3,64 -object3d[-1] [-2],50%,50%,0,1
       -if {narg("$7")} -o[-1] @{"-filename \"$7\","~>,~0} -p=[0] {~0+1} -endif
       -w[-1] {w},{h},0,0,@{~>,n} -wait 20 -rm[-2,-1]
    -while {@!" && "!@{!,ESC}" && "!@{!,Q}} -rm[-1] -w 0
    -pp[0]
  -done -v +

#@gmic histogram3d
#@gmic : Generate 3d color histogram of selected image$?.
histogram3d :
  -e[^-1] "Generate 3d color histogram of image$?."
  -v - -to_rgb -permute "cxyz" -unroll y
  -repeat @#
    nbp={h/3}
    -i[-2] (67.5;73.5;109.5;103.5;51.5;100.5;\          # Magick number for CImg3d.
            $nbp;$nbp)                                  # Number of vertices and primitives.
    (1,0;1,{$nbp-1}) -r[-1] 2,$nbp,1,1,3 -unroll[-1] y  # Primitive description.
    [-2] -n[-3] 0,1                                     # Colors.
    1,$nbp,1,1,1                                        # Opacities.
    -a[-5--1] y                                         # Build 3d object.
  -box3d 1 -p3d[-1] 1 -o3d[-1] 0.3 -+3d[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic balls3d : _size>0,_R,_G,_B,_opacity
#@gmic : Convert selected 3d objects into 3d ball sets.
balls3d : -check "${1=32}>0" -skip ${2=255},${3=$2},${4=$3},${5=1}
  -e[^-1] "Convert 3d object$? into 3d ball sets, with size $1 and color ($2,$3,$4)."
  -v - -repeat @#
    -p[0] @{-1,6}
    $1,$1,1,4 -ball[-1] $2,$3,$4

    # Create object header.
    -i (@{-2,0-5},~0,~0)

    # Create vertices.
    -lines[-3] 8,{7+~0*3} -mv[-3] @#

    # Create point primitives.
    -i 1,~0,1,1,1 (0;{~0-1}) -r[-1] 1,~0,1,1,3 -a[-2,-1] x

    # Create colored sprites.
    (-128;$1;$1;3) --to_rgb[0] -unroll[-1] y
    -i 1,{4*(~0-1)} -f[-1] -128,0,0,0 -a[-3--1] y

    # Create opacity.
    (-128;$1;$1;1) -channels[-6] 3,3 -mv[-6] @# -unroll[-1] y -*[-1] $5
    -i 1,{4*(~0-1)} -f[-1] -128,0,0,0 -a[-3--1] y

    # Append all data into a CImg3d object.
    -unroll[-5,-3] y -a[-5--1] y -pp[0]

  -mv[-1] 0 -done -v +

#@gmic imageplane3d
#@gmic : Generate 3d mapped planes from selected images.
imageplane3d :
  -e[^-1] "Generate 3d mapped planes from image$?."
  -v - -repeat @#
    -p[0] {w-1} -p[1] {h-1}
    -i[-2] (67.5;73.5;109.5;103.5;51.5;100.5;\  # Magick number for CImg3d.
            4;1;\                               # Number of vertices and primitives.
            -0.5;-0.5;0;\                       # Vertex coordinates.
            0.5;-0.5;0;\
            0.5;0.5;0;\
            -0.5;0.5;0;\
            12;0;3;2;1;0;0;0;~1;~0;~1;~0;0;\    # Primitives description.
            -128;{w};{h};{s})                   # Texture map.
    -pp[0,1] -unroll[-1] y
    (1)  # Opacity.
    -a[-3--1] y
  -mv[-1] 0 -done -v +

#@gmic imagesphere3d
#@gmic : Generate 3d mapped sphere from selected images.
imagesphere3d :
  -e[^-1] "Generate 3d mapped spheres from image$?."
  -v - -repeat @#
    -sphere3d 1 -t3d[-1] [-2] -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic imagecube3d
#@gmic : Generate 3d mapped cubes from selected images.
imagecube3d :
  -e[^-1] "Generate 3d mapped cubes from image$?."
  -v - -repeat @#
    -p[0] {w-1} -p[1] {h-1}
    -i[-2] (67.5;73.5;109.5;103.5;51.5;100.5;\  # Magick number for CImg3d.
            8;6;\                               # Number of vertices and primitives.
            -0.5;-0.5;-0.5;\                    # Vertex coordinates.
            0.5;-0.5;-0.5;\
            0.5;0.5;-0.5;\
            -0.5;0.5;-0.5;\
            -0.5;-0.5;0.5;\
            0.5;-0.5;0.5;\
            0.5;0.5;0.5;\
            -0.5;0.5;0.5;\
            12;0;3;2;1;0;0;0;~1;~0;~1;~0;0;\    # Primitives description.
            12;1;2;6;5;0;0;0;~1;~0;~1;~0;0;\
            12;5;6;7;4;0;0;0;~1;~0;~1;~0;0;\
            12;4;7;3;0;0;0;0;~1;~0;~1;~0;0;\
            12;4;0;1;5;0;0;0;~1;~0;~1;~0;0;\
            12;3;7;6;2;0;0;0;~1;~0;~1;~0;0;\
            -128;{w};{h};{s})       # Texture map for the first face.
    -pp[0,1] -unroll[-1] y
    (-128;0;0;0;-128;0;0;0;-128;0;0;0;-128;0;0;0;-128;0;0;0;1;1;1;1;1;1)  # Other faces and opacities.
    -a[-3--1] y
  -mv[-1] 0 -done -v +

#@gmic image6cube3d
#@gmic : Generate 3d mapped cubes from selected sets of 6 selected images.
image6cube3d :
  -e[^-1] "Generate 3d mapped cubes from sets of image$?."
  -v - -imageplane3d -repeat {int(@#/6)}
    -+3d[-6] 0,0,-0.5
    -rot3d[-5] 1,0,0,180 -+3d[-5] 0,0,0.5
    -rot3d[-4] 0,1,0,-90 -+3d[-4] -0.5,0,0
    -rot3d[-3] 0,1,0,90 -+3d[-3] 0.5,0,0
    -rot3d[-2] 1,0,0,90 -+3d[-2] 0,-0.5,0
    -rot3d[-1] 1,0,0,-90 -+3d[-1] 0,0.5,0
    -+3d[-6--1]
  -mv[-1] 0 -done -v +

#@gmic imagepyramid3d
#@gmic : Generate 3d mapped pyramides from selected images.
imagepyramid3d :
  -e[^-1] "Generate 3d mapped pyramids from image$?."
  -v - -repeat @#
    -p[0] {w-1} -p[1] {h-1} -p[2] {w/2}
    -i[-2] (67.5;73.5;109.5;103.5;51.5;100.5;\  # Magick number for CImg3d.
            5;5;\                               # Number of vertices and primitives.
            -0.5;-0.5;-0.5;\                    # Vertex coordinates.
            0.5;-0.5;-0.5;\
            0.5;0.5;-0.5;\
            -0.5;0.5;-0.5;\
            0;0;0.5;\
            12;0;3;2;1;0;0;0;~1;~0;~1;~0;0;\    # Primitives description.
            9;0;4;3;0;~1;~2;0;~0;~1;\
            9;1;4;0;0;~1;~2;0;~0;~1;\
            9;2;4;1;0;~1;~2;0;~0;~1;\
            9;3;4;2;0;~1;~2;0;~0;~1;\
            -128;{w};{h};{s})                   # Texture map for the first face.
    -pp[0-2] -unroll[-1] y
    (-128;0;0;0;-128;0;0;0;-128;0;0;0;-128;0;0;0;1;1;1;1;1)  # Other faces and opacities.
    -a[-3--1] y
  -mv[-1] 0 -done -v +

#@gmic pyramid3d : _width,_height
#@gmic : Generate 3d pyramid at (0,0,0), with specified geometry.
pyramid3d : -skip ${1=1},${2=1}
  -e[^-1] "Create new 3d pyramid, with width $1 and height $2."
  -v -
  (67.5;73.5;109.5;103.5;51.5;100.5;\  # Magick number for CImg3d.
   5;5;\                               # Number of vertices and primitives.
   {-$1/2};{-$1/2};{-$2/2};\           # Vertex coordinates.
   {$1/2};{-$1/2};{-$2/2};\
   {$1/2};{$1/2};{-$2/2};\
   {-$1/2};{$1/2};{-$2/2};\
   0;0;{$2/2};\
   4;0;3;2;1;\                         # Primitives description.
   3;0;4;3;\
   3;1;4;0;\
   3;2;4;1;\
   3;3;4;2)
  1,15,1,1,200 1,5,1,1,1 -a[-3--1] y
  -v +

#@gmic gyroid3d : _resolution>0,_zoom
#@gmic : Generate 3d gyroid at (0,0,0), with specified resolution.
gyroid3d : -check ${1=32}>0 -skip ${2=5}
  -e[^-1] "Create new 3d gyroid, with resolution $1 and range $2."
  -v -
  -isosurface3d "'\
    0.49*(\
    cos( 2*x + y + z - pi) + cos( 2*x - y + z - pi)\
    + cos(- 2*x + y - z - pi) + cos(- 2*x - y - z - pi)\
    + cos( x + 2*y + z - pi) + cos( x + 2*y - z - pi)\
    + cos(- x - 2*y + z - pi) + cos(- x - 2*y - z - pi)\
    + cos( x + y + 2*z - pi) + cos(- x + y + 2*z - pi)\
    + cos( x - y - 2*z - pi) + cos(- x - y - 2*z - pi)\
    + cos(- 2*x + y + z) + cos( 2*x + y - z)\
    + cos(- 2*x - y + z) + cos( 2*x - y - z)\
    + cos(- x + 2*y + z) + cos( x - 2*y + z)\
    + cos(- x + 2*y - z) + cos( x - 2*y - z)\
    + cos( x - y + 2*z) + cos( x + y - 2*z)\
    + cos(- x - y + 2*z) + cos(- x + y - 2*z)\
    ) + 0.27*( \
    cos(- 2*x + 2*y - pi) + cos( 2*x - 2*y - pi)\
    + cos( 2*x + 2*y - pi) + cos(- 2*x - 2*y - pi)\
    + cos(- 2*y + 2*z - pi) + cos( 2*y - 2*z - pi)\
    + cos( 2*y + 2*z - pi) + cos(- 2*y - 2*z - pi)\
    + cos(- 2*z + 2*x - pi) + cos( 2*z - 2*x - pi)\
    + cos( 2*z + 2*x - pi) + cos(- 2*z - 2*x - pi)\
    ) - 0.69'",0,{-$2},{-$2},{-$2},$2,$2,$2,$1,$1,$1
  -c3d[-1] -n3d[-1]
  -v +

#@gmic weird3d : _resolution>0
#@gmic : Generate 3d weird object at (0,0,0), with specified resolution.
weird3d : -skip ${1=32}
  -e[^-1] "Create new 3d weird object, with resolution $1."
  -v -
  -isosurface3d "'\
    T = 1.61803399;\
    2 - (cos(x + T*y) + cos(x - T*y) + cos(y + T*z) + cos(y - T*z) + cos(z - T*x) + cos(z + T*x))\
    '",0,-4.7,-4.7,-4.7,4.7,4.7,4.7,$1,$1,$1
  -c3d[-1] -n3d[-1]
  -v +

#@gmic text3d : text,_font_height>0,_depth>0,_smoothness
#@gmic : Generate a 3d text object from specified text.
text3d : -skip ${2=57},${3=10},${4=1.5}
  -e[^-1] "Generate 3d text object '$1' with size $2, depth $3 and smoothness $4."
  -v - -i 1024,{10*$2},1,1 -text[-1] "$1",0,0,$2,1,1 -autocrop[-1] 0
  -r[-1] 100%,100%,$3 -r[-1] {w+12},{h+12},{d+12},1,0,0,0.5,0.5,0.5
  -blur[-1] $4 -n[-1] 0,1 -isosurface3d[-1] 0.5 -rv3d[-1] -v +

#@gmic gmic3d
#@gmic : Generate a 3d G'MIC logo.
gmic3d :
  -e[^-1] "Generate 3d G'MIC logo."
  -v -
  -text3d G,60,20,2 -col3d[-1] 16,64,255
  -text3d \',60,20,2 -+3d[-1] 30 -col3d[-1] 64,128,255
  -text3d M,60,20,2 -+3d[-1] 40 -col3d[-1] 96,196,255
  -text3d I,60,20,2 -+3d[-1] 70 -col3d[-1] 64,128,255
  -text3d C,60,20,2 -+3d[-1] 95 -color3d[-1] 16,64,255
  -sphere3d 8 -+3d[-1] 85,-10,15 -col3d[-1] 192,128,255
  -+3d[-6--1] -c3d[-1]
  -repeat 30
    -box3d {min(3+@{<,-1}/2,10)} -col3d[-1] {30*~>},{20+80*~>},{10*~>},0.5
    -rot3d[-1] 1,1,1,{~>*12}
    -+3d[-1] {80*cos(0.5+1.02*~>*12*pi/180)},{30*sin(0.8+~>*12*pi/180)},{2*~>-75}
  -done
  -+3d[-30--1] -+3d[-1] 0,5,30 -+3d[-2--1]
  -v +

#@gmic extrude3d : _depth>0,_resolution>0,_smoothness[%]>=0
#@gmic : Generated extruded 3d object from selected binary profiles.
extrude3d : -check "${1=16}>0 && ${2=1024}>0 && ${3=0.5%}>=0"
  -e[^-1] "Generate extruded 3d object from XY-profile$?, with depth $1, resolution $2 and smoothness $3."
  -v - -norm -n 0,1 -autocrop 0 -repeat @#
    wr={round(max(1,if(w>h,min($2,w),min($2,h)*w/h)))}
    hr={round(max(1,if(w>h,min($2,w)*h/w,min($2,h))))}
    fact={$1/max(w/$wr,h/$hr)}
    -blur[-1] $3,0 -r[-1] $wr,$hr,1,1,2 -expand_xyz[-1] 1,0
    -isosurface3d[-1] 50% -*3d[-1] 1,1,$fact -rv3d[-1]
  -mv[-1] 0 -done -v +

#@gmic lathe3d : _resolution>0,_smoothness[%]>=0,_max_angle>=0
#@gmic : Generate 3d object from selected binary XY-profiles.
lathe3d : -check "${1=128}>0 && ${2=0.5%}>=0 && ${3=361}>=0"
  -e[^-1] "Generate lathed 3d object from XY-profile$?, with resolution $1, smoothness $2 and maximum angle $3."
  tmax={($3-180)*pi/180}
  -v - -norm -n 0,1 -autocrop 0 -repeat @#
    wr={max(1,w2=2*w;if(w2>h,min($1,w2),min($1,h)*w2/h))}
    hr={max(1,w2=2*w;if(w2>h,min($1,w2)*h/w2,min($1,h)))}
    rmax={sqrt($wr*$wr+$hr*$hr)/2}
    $wr,1,$wr,1,"xc=x-w/2; zc=z-d/2; t=atan2(zc,xc); if(t>"$tmax","$rmax",sqrt(xc*xc+zc*zc))"
    -*[-1] {2*(@{-2,w}-1)/(w-1)} -r[-1] $wr,$hr,$wr
    (0;{@{-2,h}-1}) -r[-1] $wr,$hr,$wr,1,3 -a[-2--1] c
    -warp[-2] [-1],0,1,0 -rm[-1] -expand_xyz[-1] 10,0
    -blur[-1] $2 -isosurface3d[-1] 50% -rv3d[-1]
  -mv[-1] 0 -done -v +

#@gmic cup3d : _resolution>0
#@gmic : Generate a new 3d cup object.
cup3d : -check ${1=128}>0
  -e[^-1] "Generate a new 3d cup, with resolution $1."
  -v -
  100,200
  -ellipse[-1] 0%,0%,40%,40%,0,1,1
  -ellipse[-1] 0,0,35%,35%,0,1,0
  -polygon[-1] 4,0,45%,8%,45%,20%,90%,0,90%,1,1
  -ellipse[-1] 0%,100%,30%,10%,0,1,1
  -lathe3d[-1] $1,2
  -v +

#@gmic sierpinski3d : _recursion_level>=0,_width,_height
#@gmic : Generate new 3d Sierpinski pyramid.
sierpinski3d : -check ${1=4}>=0 -skip ${2=1},${3=1}
  -e[^-1] "Generate new 3d Sierpinski pyramid of degree $1, with width $2 and height $3."
  -v - -l[] -_sierpinski3d {-$2/2},{-$2/2},{-$3/2},{$2/2},{-$2/2},{-$3/2},{$2/2},{$2/2},{-$3/2},{-$2/2},{$2/2},{-$3/2},0,0,{$3/2},$1 -+3d -endl -v +

_sierpinski3d :
  -if {$16<=0}
    (67.5;73.5;109.5;103.5;51.5;100.5;\
     5;5;\
     $1;$2;$3;\
     $4;$5;$6;\
     $7;$8;$9;\
     $10;$11;$12;\
     $13;$14;$15;\
     4;0;3;2;1;\
     3;0;4;3;\
     3;1;4;0;\
     3;2;4;1;\
     3;3;4;2)
    1,15,1,1,200 1,5,1,1,1 -a[-3--1] y
  -return -endif
  -_sierpinski3d $1,$2,$3,\
                 {($1+$4)/2},{($2+$5)/2},{($3+$6)/2},\
                 {($1+$4+$7+$10)/4},{($2+$5+$8+$11)/4},{($3+$6+$9+$12)/4},\
                 {($1+$10)/2},{($2+$11)/2},{($3+$12)/2},\
                 {($1+$13)/2},{($2+$14)/2},{($3+$15)/2},\
                 {$16-1}
  -_sierpinski3d {($1+$4)/2},{($2+$5)/2},{($3+$6)/2},\
                 $4,$5,$6,\
                 {($4+$7)/2},{($5+$8)/2},{($6+$9)/2},\
                 {($1+$4+$7+$10)/4},{($2+$5+$8+$11)/4},{($3+$6+$9+$12)/4},\
                 {($4+$13)/2},{($5+$14)/2},{($6+$15)/2},\
                 {$16-1}
  -_sierpinski3d {($1+$4+$7+$10)/4},{($2+$5+$8+$11)/4},{($3+$6+$9+$12)/4},\
                 {($4+$7)/2},{($5+$8)/2},{($6+$9)/2},\
                 $7,$8,$9,\
                 {($7+$10)/2},{($8+$11)/2},{($9+$12)/2},\
                 {($7+$13)/2},{($8+$14)/2},{($9+$15)/2},\
                 {$16-1}
  -_sierpinski3d {($1+$10)/2},{($2+$11)/2},{($3+$12)/2},\
                 {($1+$4+$7+$10)/4},{($2+$5+$8+$11)/4},{($3+$6+$9+$12)/4},\
                 {($7+$10)/2},{($8+$11)/2},{($9+$12)/2},\
                 $10,$11,$12,\
                 {($10+$13)/2},{($11+$14)/2},{($12+$15)/2},\
                 {$16-1}
  -_sierpinski3d {($1+$13)/2},{($2+$14)/2},{($3+$15)/2},\
                 {($4+$13)/2},{($5+$14)/2},{($6+$15)/2},\
                 {($7+$13)/2},{($8+$14)/2},{($9+$15)/2},\
                 {($10+$13)/2},{($11+$14)/2},{($12+$15)/2},\
                 $13,$14,$15,\
                 {$16-1}

#@gmic parametric3d : _x(a,b),_y(a,b),_z(a,b),_amin,_amax,_bmin,_bmax,_res_a>0,_res_b>0,_res_x>0,_res_y>0,_res_z>0,_smoothness>=0,_isovalue>=0
#@gmic : Generate new 3d object from specified parametric surface (x(a,b),y(a,b),z(a,b)).
parametric3d : -skip "${1=(2+cos(b))*sin(a)}","${2=(2+cos(b))*cos(a)}","${3=sin(b)}"
               -skip ${4={-pi}},${5={pi}},${6={-pi}},${7={pi}}
               -check "${8=512}>0 && ${9=$8}>0 && ${10=64}>0 && ${11=$10}>0 && ${12=$11}>0 && \
                       ${13=2%}>=0 && ${14=10%}>=0"
  -e[^-1] "Generate new 3d object from parametric surface ($1,$2,$3)."
  -v -
  # Compute (x(a,b),y(a,b),z(a,b)) and normalize it.
  ($4,$5;$4,$5^$6,$6;$7,$7) -r[-1] $8,$9,1,2,3 -channels[-1] 0,2
  -f[-1] "a=i(x,y,0,0);b=i(x,y,0,1);if(c==0,$1,if(c==1,$2,$3))"
  --sh[-1] 0,0 xmin={im} xmax={iM} -n[-1] 16,{$10-17} -rm[-1]
  --sh[-1] 1,1 ymin={im} ymax={iM} -n[-1] 16,{$11-17} -rm[-1]
  --sh[-1] 2,2 zmin={im} zmax={iM} -n[-1] 16,{$12-17} -rm[-1]
  -r[-1] {w*h},3,1,1,-1

  # Extract 3d surface.
  -pointcloud[-1] -r[-1] $10,$11,$12,1,0 -blur[-1] $13,0
  -isosurface3d[-1] $14
  -c3d[-1] -n3d[-1] -*3d[-1] {$xmax-$xmin},{$ymax-$ymin},{$zmax-$zmin}
  -v +

#@gmic snapshot3d : _size>0,_zoom>=0,_backgroundR,_backgroundG,_backgroundB
#@gmic : Create 2d snapshots of selected 3d objects.
#@gmic : Set 'zoom' to 0 to disable object auto-scaling.
snapshot3d : -check "${1=512}>0 && ${2=1}>=0" -skip ${3=""}
  -if {narg($3)}
    -e[^-2,-1] "Create $1x$1 snapshot$? from 3d object$?, with zoom factor $2 and background color ${3--1}."
  -else
    -e[^-2,-1] "Create $1x$1 snapshot$? from 3d object$?, with zoom factor $2."
  -endif
  -v - -repeat @#
    -if {$2!=0} -c3d[-1] -n3d[-1] -*3d[-1] {3*$1*$2/4} -endif
    -if {narg($3)} (${3--1}) -unroll[-1] c -else 1,2,1,3,32,64,32,116,64,96 -endif -r[-1] $1,$1,1,3,3
    -object3d[-1] [-2],50%,50%,0,1,1 -name[-1] @{-2,n}
    -rm[-2]
  -mv[-1] 0 -done -v +

#@gmic label_points3d : _label_size>0,_opacity
#@gmic : Add a numbered label to all vertices of selected 3d objects.
label_points3d : -check ${1=13}>0 -skip ${2=0.8}
  -e[^-1] "Label vertices of 3d object$?."
  -v - -repeat @#
    --p3d[~>] 0 -l[-1] -s3d -rm[-3--1]
    nbp=@{-2,0} -=[-2] $nbp,0,1                                 # Set correct number of primitives
    (1,0;1,{$nbp-1}) -r[-1] 2,$nbp,1,1,3 -r[-1] 1,{2*h},1,1,-1  # Create new primitive data
    -repeat $nbp                                                # Create texture labels as primitive colors.
      1 -text[-1] ~>,0,0,$1,1,255,255,255 -autocrop[-1] 0
      -i[-2] (-128;{w};{h};3) -unroll[-1] y
    -done
    -repeat $nbp                                                # Create texture masks as primitive opacities.
      1 -text[-1] ~>,0,0,$1,1,$2 -autocrop[-1] 0
      -i[-2] (-128;{w};{h};1) -unroll[-1] y
    -done
    -a y  # Merge final object data.
    -endl
    -+3d[-2,-1]
  -mv[-1] 0 -done -v +

#-----------------------------
#
#@gmic :: Interactive demos
#
#-----------------------------

#@gmic x_mandelbrot : _julia={ 0 | 1 },_c0r,_c0i
#@gmic : Launch Mandelbrot/Julia explorer.
x_mandelbrot : -skip ${1=0},${2=0.317},${3=0.03}
  -e[] "\n
------ Mandelbrot/Julia explorer -----------------\n
----\n
---- Select zooming region with mouse.\n
---- Click once to reset zoom factor.\n
---- Keys 'ESC' or 'Q' to exit.\n
---- Key 'C' to print current fractal coordinates.\n
----\n
--------------------------------------------------"

  # Init variables and display.
  -v -
  -rm -w 512,512,0,0 -_x_mandelbrot_coords $1 -_x_mandelbrot_palette

  # Start event loop.
  -do
    -p {min(@{!,w},@{!,h})}                                                                       # Push desired window dimension.
    ~-1,~-1 -mandelbrot[-1] @0,256,$1,{if($1,$2,0)},{if($1,$3,0)} -map[-1] [1]                    # Render fractal.
    -if $1 -w[-1] ~-1,~-1,0,0,"Julia set c=("@{0,0}","@{0,1}")-("@{0,2}","@{0,3}"), c0=($2,$3)"   # Display on window.
    -else -w[-1] ~-1,~-1,0,0,"Mandelbrot set c=("@{0,0}","@{0,1}")-("@{0,2}","@{0,3}")" -endif
    -p {w} -p {h} -select[-1] 2                                                                   # Get the user selection.

    -if {@{-1,0}>0}                                                                      # If valid selection found.
      -p {max(@{-1,3}-@{-1,0},@{-1,4}-@{-1,1})}                                          # Compute max dimension of selected rectangle.
      -if {~-1<5} -_x_mandelbrot_coords $1 -rm[1] -_x_mandelbrot_palette -mv[-1] 1   # If selection too small, reset the view,
      -else ({@{0,0}+@{-1,0}*(@{0,2}-@{0,0})/~-3};\                                  # Else compute new fractal coordinates.
             {@{0,1}+@{-1,1}*(@{0,3}-@{0,1})/~-2};\
             {@{0,0}+(@{-1,0}+~-1)*(@{0,2}-@{0,0})/~-3};\
             {@{0,1}+(@{-1,1}+~-1)*(@{0,3}-@{0,1})/~-2})
      -endif
      -pp[-1] -rm[0] -mv[-1] 0                                                  # Validate new coordinates.
    -endif
    -rm[-1]                                                                     # Delete latest rendering.
    -if {@{!,C}}                                                                # If 'C' key has been pressed.
      -if $1 -v + -e[0--4] "Julia set, at c = ("@{0,0-1}")-("@{0,2-3}"), with c0 = ($2,$3)." -v -
      -else -v + -e[0--4] "Mandelbrot set, at c = ("@{0,0-1}")-("@{0,2-3}")." -v -
      -endif
    -endif
    -pp[-3--1]
    -if {!@!" || "@{!,ESC}" || "@{!,Q}} -rm -w 0 -v + -return -endif
    -wait -1
  -while 1

_x_mandelbrot_coords :
  -if $1 (-2;-2;2;2) -else (-2.1;-1.5;1.2;1.5) -endif

_x_mandelbrot_palette :
  6,1,1,3 -rand[-1] 20,255 -r[-1] 32,1,1,3,3 -r[-1] 1024,1,1,3,0,2 -=[-1] 0,0,0,0,0 -=[-1] 0,0,0,0,1 -=[-1] 0,0,0,0,2

#@gmic x_fish_eye
#@gmic : Launch fish-eye demo.
x_fish_eye :
  -e[] "\n
------ Fish-eye demo --------------------\n
----\n
---- Mouse pointer moves fish-eye center.\n
---- Mouse buttons set fish-eye size.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"

  -v -
  -if {@#>0} -a x -n 0,255 -r2dy 220 -else
  120,90,1,3 -rand[-1] 0,255 -plasma[-1] 0.3,3 -n 0,255
  -text "  G'MIC\nFISH-EYE\n  DEMO",15,13,24,1,255 -resize2x -blur 5 -sharpen 1000
  -f i+150-4*abs(y-h/2) -c[-1] 0,255 -frame_fuzzy[-1] 15,10,15,1.5,0 -to_rgb[-1]
  -endif
  -torus3d 20,6 -col3d[-1] {?(30,255)},{?(30,255)},{?(30,255)} --rot3d[-1] 1,0,0,90
  -col3d[-1] {?(30,255)},{?(30,255)},{?(30,255)} -+3d[-1] 15 -+3d[-2,-1] -db3d 0 -c3d[-1]
  -p[0] 30
  -w[-2] {2*@{-2,w}},{2*@{-2,h}},0,0,"Fish-Eye Demo"
  -repeat 100000
    -wait 40
    -if {@{!,b}==1} -p=[0] {min(80,~0+8)} -endif
    -if {@{!,b}==2} -p=[0] {max(3,~0-8)} -endif
    --object3d[-2] [-1],{50+30*cos(~>/20)}%,{50+30*sin(~>/31)}%,{50+330*sin(~>/19)},0.7,0 -rot3d[-2] 1,0.2,0.6,3
    -if {@{!,x}>=0}
    -fish_eye[-1] {@{!,x}*100/@{!,w}},{@{!,y}*100/@{!,h}},~0
    -endif
    -w[-1] -rm[-1]
    -if {@!==0" || "@{!,ESC}" || "@{!,Q}} -rm[-2,-1] -pp[0] -w 0 -v + -return -endif
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,D}} -w[] {@{!,w}*1.5},{@{!,h}*1.5} -wait -1 -endif
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,C}} -w[] {@{!,w}/1.5},{@{!,h}/1.5} -wait -1 -endif
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,R}} -w[] @{0,w},@{0,h} -wait -1 -endif
  -done

#@gmic x_spline
#@gmic : Launch spline curve editor.
x_spline :
  -e[] "\n
------ Spline curve editor --------------------------\n
----\n
---- Mouse to insert/move/delete points.\n
---- Key 'R' to reset the curve.\n
---- Key 'SPACE' to shows/hide spline curve.\n
---- Key 'P' to shows/hide control points.\n
---- Key 'ENTER' to shows/hide control polygon.\n
---- Key 'T' to shows/hide point tangents.\n
---- Key 'I' to shows/hide point indices.\n
---- Key 'C' to shows/hide point coordinates.\n
---- Keys '+' and '-' to increase/decrease roundness.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------------------"

  # Init display and variables.
  -v -
  -if @# -a x -n 0,255 -to_rgb -else (0;0^0;128^0;0) -r[-1] 512,512,1,3,3 -name[-1] "Spline Editor" -endif
  -w[0] @{0,w},@{0,h},0,0,@{-1,n} -r[0] @{!,w},@{!,h},1,3,1
  -i[1] 1 # Point coordinates
  -p 0.5  # Stack[-4] : Curve sharpness
  -p 23   # Stack[-3] : Visualisation flags
  -p -1   # Stack[-2] : Nearest point
  -p -1   # Stack[-1] : Active point

  # Start event loop.
  -do

    # Init coordinates [1] if necessary.
    -if {@{1,#}==1}
      -rm[1] -p=[-4] 0.5 -p=[-2] -1 -p=[-1] -1
      -i[1] ({0.2*w},{0.2*h};\
             {0.2*w},{0.8*h};\
             {0.8*w},{0.8*h};\
             {0.8*w},{0.2*h})
    -endif

    # Estimate screen-normalized coordinates [2], curve tangents [3] and tangent orientations [4].
    [1] ({@{!,w}/@{0,w}},{@{!,h}/@{0,h}}) -*[-2,-1]                       # Normalized coordinates.
    --shift[2] 0,-1,0,0,2 --shift[2] 0,1,0,0,2 --[-2,-1] -*[-1] ~-4       # Curve tangents.
    --s[-1] x -sqr[-2,-1] -+[-2,-1] -sqrt[-1] -r[-1] 2 --/[-2,-1] -rm[-2] # Tangent orientations.

    # Display curve, control points, polygon and tangents.
    --r[0] @{!,w},@{!,h},1,3
    -if {~-3"&4"} -polygon[-1] @{2,h},@2,0.3,128,200,255 -endif
    -repeat @{1,h}
      -line[-1] @{2,0-3},0.3,255,255,0
      -if {~-3"&1"} -spline[-1] @{2,0-1},@{3,0-1},@{2,2-3},@{3,2-3},1,255 -endif
      -if {~-3"&8"} -line[-1] {@{2,0}-@{4,0}*20},{@{2,1}-@{4,1}*20},{@{2,0}+@{4,0}*20},{@{2,1}+@{4,1}*20},1,0,255,0 -endif
      -if {~-3"&16"} -text[-1] ~>,{@{2,0}-3},{@{2,1}-18},13,1,255,255,0 -endif
      -if {~-3"&32"} -text[-1] "("{round(@{1,0})}","{round(@{1,1})}")",{@{2,0}-16},{@{2,1}+10},13,1,100,200,255 -endif
      -shift[1-4] 0,-1,0,0,2
    -done
    -if {~-3"&2"} -repeat @{1,h}
      -ellipse[-1] @{2,0-1},4,4,0,1,0,0,0 -ellipse[-1] @{2,0-1},2,2,0,1,255,100,155 -shift[2] 0,1,0,0,2
    -done -endif
    -w[-1] -rm[3,4,-1] -wait

    # Handle key events.
    -if @{!,SPACE} -p=[-3] {~-3"+if("~-3"&1,-1,1)"} -wait -1 -endif  # Show/hide spline.
    -if @{!,P} -p=[-3] {~-3"+if("~-3"&2,-2,2)"} -wait -1 -endif      # Show/hide points.
    -if @{!,ENTER} -p=[-3] {~-3"+if("~-3"&4,-4,4)"} -wait -1 -endif  # Show/hide polygon.
    -if @{!,T} -p=[-3] {~-3"+if("~-3"&8,-8,8)"} -wait -1 -endif      # Show/hide tangents.
    -if @{!,I} -p=[-3] {~-3"+if("~-3"&16,-16,16)"} -wait -1 -endif   # Show/hide indices.
    -if {@{!,C}" && "!@{!,CTRLLEFT}" && "!@{!,CTRLRIGHT}} -p=[-3] {~-3"+if("~-3"&32,-32,32)"} -wait -1 -endif # Show/hide coordinates.
    -if {@{!,PADADD}" && "~-4<1} -p=[-4] {~-4*1.1} -wait -1 -endif       # Increase roundness.
    -if {@{!,PADSUB}" && "~-4>0.1} -p=[-4] {~-4*0.9} -wait -1 -endif     # Decrease roundness.
    -if {@{!,R}" && "!@{!,CTRLLEFT}" && "!@{!,CTRLRIGHT}} -rm[-1] -i[1] 1 -wait -1 -endif # Reset curve.
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,D}} -w[] {@{!,w}*1.5},{@{!,h}*1.5} -endif # Increase window size.
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,C}} -w[] {@{!,w}/1.5},{@{!,h}/1.5} -endif # Decrease window size.
    -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,R}} -w[] @{0,w},@{0,h} -endif             # Reset window size.
    -if @{!,r} -w[] -endif # Resize window if necessary.

    # Set/unset active point.
    -if {@{!,b}==0} -p=[-1] -1                                      # Unset active point if mouse button is released.
    -elif {@{!,x}>=0" && "@{!,b}" && "~-1==-1}                  # Find new active point.
      [2] (@{!,x},@{!,y}) --[-2,-1] -sqr[-1] -s[-1] x -+[-2,-1]     # Compute distance vector to points.
      (@{-1,c}) -p=[-2] @{-1,1} -rm[-1]                             # Set nearest point.
      -if {@{-1,m}<64} -p=[-1] ~-2 -endif                       # Set it as active point, if near enough.
      -rm[-1]
    -endif
    -rm[2]

    # Move active point.
    -if {@{!,b}"&1 && "@{!,x}>=0" && "~-1!=-1}
      -=[1] {@{!,x}*@{0,w}/@{!,w}},0,~-1
      -=[1] {@{!,y}*@{0,h}/@{!,h}},1,~-1

    # Delete nearest point.
    -elif {@{!,b}"&2 && "@{!,x}>=0" && "@{1,h}>3}
      -l[1] -s y -rm[~-2] -a y -endl -wait -1

    # Insert new active point.
    -elif {@{!,b}"&1 && "@{!,x}>=0}
      -p ({@{!,x}*@{0,w}/@{!,w}},{@{!,y}*@{0,h}/@{!,h}})              # Point coordinates in the image basis.
      --shift[1] 0,-1,0,0,2 -+[-1] [1] -/[-1] 2                       # Compute center of segments.
      ~-1 --[-2,-1] -sqr[-1] -s[-1] x -+[-2,-1]                       # Compute distance vector to segments.
      (@{-1,c}) -p @{-1,1} -rm[-2,-1]                                 # Push nearest segment.
      -l[1] -s y -i[{~-1+1}] ~-2 -a y -endl                           # Insert new point at right position.
      -p {~-1+1} -pp[-4--2]                                           # Set new active point as newly inserted.
    -endif

  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}

  # Render spline as a tertiary mask for output.
  --shift[1] 0,-1,0,0,2 --shift[1] 0,1,0,0,2 --[-2,-1] -*[-1] ~-4
  [0],[0],1,1,2 -rm[0]
  -repeat @{1,h} -spline[-1] @{0,0-1},@{1,0-1},@{0,2-3},@{1,2-3},1,1 -shift[0] 0,-1,0,0,2 -shift[1] 0,-1,0,0,2 -done
  -flood[-1] 0,0,0,0,1,0

  # Exit properly.
  -rm[0,1] -w 0 -v +

#@gmic x_tictactoe
#@gmic : Launch tic-tac-toe game.
x_tictactoe :
  -e[] "\n
------ Tic-Tac-Toe game -----------------\n
----\n
---- Use mouse to select positions of the\n
---- symbols. Close window to exit game.\n
----\n
-----------------------------------------"
  -v -                            # Become quiet.

  # Allocate variables.
  -p 0                            # [-7] : State message.
  -p 0                            # [-6] : Turn counter (0 to 8).
  -p 0                            # [-5] : Current player (0 or 1).
  -p 0                            # [-4] : Board state.
  -p 0                            # [-3] : Temporary variable 3.
  -p 0                            # [-2] : Temporary variable 2.
  -p 0                            # [-1] : Temporary variable 1.
  -_x_tictactoe2                  # Generate board.
  -w[-1] -1,-1,0,0," "            # Init display window.

  # Start main loop.
  -do

    # Set state message depending on the current player.
    -if ~-5 -p=[-7] "Tic-Tac-Toe (O to play)"
    -else -p=[-7] "Tic-Tac-Toe (X to play)"
    -endif

    # Select position by the user.
    -do                                                                       # Enter event loop.
      -w[] {w},{h},0,0,~-7 -wait                                              # Wait for events and force window size if necessary.
      -if {!@!} -pp[-7--1] -w[] 0 -v + -return -endif                           # Quit properly if window has been closed.
      -if {@{!,b}"&1 && "@{!,x}>20" && "@{!,y}>20" && "@{!,x}<400" && "@{!,y}<400} # If mouse button has been pressed on the board area.
        -p=[-3] {int((@{!,x}-15)/130)}                                          # Get x-coord of the selected position (0,1 or 2).
        -p=[-2] {int((@{!,y}-15)/130)}                                          # Get y-coord of the selected position (0,1 or 2).
        -p=[-1] {4^(~-2*3+~-3)}                                                 # Get state code of the selected position.
        -if {int(~-4/~-1)%4} -p=[-1] -1 -endif                                  # Check availability of the selected position.
      -else -p=[-1] -1 -endif                                                   # If no mouse button, do nothing but loop.
    -while {~-1<0}                                                            # Go on until a valid position has been selected.

    # Draw symbol on selected position and update board state.
    -_x_tictactoe{~-5%2}                                                      # Generate the symbol sprite and his mask.
    -image[-3] [-2],{"130*"~-3" + 15+?(-5,5)"},\                              # Draw symbol at its position (with some fuzzyness).
                    {"130*"~-2" + 15+?(-5,5)"},0,0,1,[-1]
    -rm[-2--1]                                                                # Delete the sprite and the mask (not needed anymore).
    -w[-1]                                                                    # Update display window.
    -p=[-4] {~-4+(1+~-5)*~-1}                                                 # Update the board state.

    # Check for a winning configuration.
    (21,1344,86016,4161,16644,66576,65793,4368;\                              # The list of winning configurations.
     0,0,0,0,1,2,0,0;\                                                        # Corresponding X coords for the stroke.
     0,1,2,0,0,0,0,0;\                                                        # Corresponding Y coords for the stroke.
     3,3,3,4,4,4,5,6)                                                         # Corresponding indice of the stroke sprite.
    -repeat {w}                                                               # Start to check configurations.
      -p=[-1] @{-1,~>}                                                        # Save the current configuration code (used several times).
      -if {(~-4" & "~-1)==~-1||(~-4" & "(2*~-1))==2*~-1}                        # If a winner has been found.
        -_x_tictactoe@{-1,(~>,3)}                                               # Generate the stroke symbol and his mask.
        -image[-4] [-2],{130*@{-3,(~>,1)}+?(-5,5)},\                            # And display it on the board at its position.
                        {130*@{-3,(~>,2)}+?(-5,5)},0,0,1,[-1] -rm[-2--1]
        -if {(~-4" & "~-1)==~-1} -w[-2] -1,-1,0,0,"Tic-Tac-Toe (X won !)"
        -else -w[-2] -1,-1,0,0,"Tic-Tac-Toe (O won !)"                            # Update display window.
        -endif
        -do -wait -w[] @{!,w},@{!,h} -while @!                                    # Wait for the window to be closed.
        -rm[-1] -pp[-7--1] -w[-1] 0 -v + -return                                  # And return properly.
      -endif
    -done                                                                     # Go on until all configurations have been checked.
    -rm[-1]                                                                   # Delete winning configuration data.

    -p=[-5] {(~-5+1)%2}                                                     # Select next player.
    -p=[-6] {~-6+1}                                                         # Increment turn counter.
  -while {~-6<9}                                                            # Loop to next move until all positions have been filled.

  # Here, the game has been ended without winners.
  -w[] -1,-1,0,0,"Tic-Tac-Toe (Tied game !)"                                # Change window title.
  -do -wait -w[] @{!,w},@{!,h} -while @!                                    # Wait for the window to be closed.
  -pp[-7--1] -w[] 0 -v +                                                    # Return properly.

# Generate Tic-Tac-Toe graphics.
_x_tictactoe : # Apply a hand-drawing effect.
  -spread[-1] 4 -blur[-1] 6 -sharpen[-1] 0.8 -n[-1] 0,1

__x_tictactoe : # Apply color to last image and generate corresponding opacity mask.
  --f[-1] 1-i --n[-2] $2,255 --n[-3] $3,255 -n[-4] $1,255 -a[-4,-2,-1] c

_x_tictactoe0 : # Generate a 'X' and his mask.
  128,128,1,1,1 -line[-1] 15%,15%,85%,85%,1,0 -line[-1] 15%,85%,85%,15%,1,0 -erode[-1] 12 -_x_tictactoe -deform[-1] 4 -__x_tictactoe 40,40,160

_x_tictactoe1 : # Generate a 'O' and his mask.
  128,128,1,1,1 -ellipse[-1] 50%,50%,22%,22%,0,1,0 -ellipse[-1] 50%,50%,15%,15%,0,1,1 -_x_tictactoe -deform[-1] 4 -__x_tictactoe 160,40,160

_x_tictactoe2 : # Generate the board.
  391,391,1,1,"!(x%130) || !(y%130)" -r[-1] 421,421,1,1,0,0,0.5,0.5 -dilate[-1] 3 -_x_tictactoe -f[-1] 1-i
  100%,100% -noise[-1] 10 -blur[-1] 8,0 -sharpen[-1] 1.5 -n[-1] 220,255 -*[-2,-1] -to_rgb[-1]

_x_tictactoe3 : # Generate an horizontal stroke and his mask.
  421,130,1,1,1 -line[-1] 10%,60%,90%,60%,1,0 -erode[-1] 6 -_x_tictactoe -rotate[-1] {?(-6,6)},1,1,50%,50% -__x_tictactoe 180,10,10

_x_tictactoe4 : # Generate a vertical stroke and his mask.
  -_x_tictactoe3 -transpose[-2--1]

_x_tictactoe5 : # Generate a ++ diagonal stroke and his mask.
  421,421,1,1,1 -line[-1] 10%,10%,90%,90%,1,0 -erode[-1] 6 -_x_tictactoe -__x_tictactoe 180,10,10

_x_tictactoe6 : # Generate a +- diagonal stroke and his mask.
  421,421,1,1,1 -line[-1] 10%,90%,90%,10%,1,0 -erode[-1] 6 -_x_tictactoe -__x_tictactoe 180,10,10

#@gmic x_fourier
#@gmic : Launch fourier filtering demo.
x_fourier :
  -e[] "\n
------ Fourier-filtering demo -----------------------------------\n
----\n
---- Mouse buttons on the right image to set min/max frequencies.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------------------------------"

  -if {!@#} -e[] "\n No images have been specified. At least one image is required.\n" -return -endif
  -v -
  -repeat @# -l[~>]

    # Init variables.
    -p[0] 1               # need_update (boolean)
    -p[1] 0               # min freq. (in %)
    -p[2] 100             # max freq. (in %)

    -if {w>3*@{!,u}/5} -r2dx[-1] {3*@{!,u}/10} -endif  # Reduce image size if necessary.
    -if {h>3*@{!,v}/5} -r2dy[-1] {3*@{!,v}/5} -endif

    # Compute fourier transform.
    --fft[-1]

    # Generate log-magnitude image.
    --sqr[-2,-1] -+[-2,-1] -sqrt[-1] -+[-1] 1 -log[-1] -to_colormode @{-2,s} -n[-1] 0,255 -shift[-1] 50%,50%,0,0,2

    # Enter user event-loop.
    -do

      -if ~0 # If image must be updated.

        # Generated filtering mask.
        100%,100%
        -p {sqrt(w^2+h^2)*~2/200} -ellipse[-1] 50%,50%,~-1,~-1,0,1,1 -pp[-1]
        -p {max(0,sqrt(w^2+h^2)*~1/200-1)} -ellipse[-1] 50%,50%,~-1,~-1,0,1,0 -pp[-1]

        # Compute filtered log-magnitude.
        --*[-2] [-1] -+[-1] [-3] -/[-1] 2

        # Compute filtered fourier representation.
        -shift[-2] -50%,-50%,0,0,2
        --*[-5,-4] [-2]
        -rm[-4]

        # Compute filtered image by inverse fourier.
        -ifft[5,6] -rm[-1] -n[-1] 0,255

        # Display filtered image.
        -rv[-2,-1]
        -if @! -r[-2,-1] {@{!,w}/2},@{!,h} -endif
        -text[-1] "Freq. Min/Max = "{int(~1)}"% / "{int(~2)}"%",5,5,13,1,255
        -w[-2,-1] -1,-1,0,0,"Fourier Filtering Demo"
        -rm[-2,-1]
        -p=[0] 0

      -endif

      -wait

      -if {@{!,b}" && "@{!,x}>=@{!,w}/2}  # If mouse button pressed on the right pane.
        -p {200*sqrt((@{!,x}-3*@{!,w}/4)^2+(@{!,y}-@{!,h}/2)^2)/\ # Compute selected radius (in %).
            sqrt((@{!,w}/2)^2+@{!,h}^2)}
        -if {@{!,b}" & "1} -p=[2] ~-1                   # Update max freq. if left button.
        -else -p=[1] {max(0,~-1-3)}                     # Update min freq. if other button.
        -endif
        -pp[-1]
        -if {~1>=~2} -p=[1] ~2 -endif                   # Check that the min/max freq. are ordered.
        -p=[0] 1                                        # Tell that the image must be updated.
      -endif

      -if @{!,r} -p=[0] 1 -endif
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,D}} -w[] {@{!,w}*1.5},{@{!,h}*1.5} -p=[0] 1 -endif # Increase window size.
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,C}} -w[] {@{!,w}/1.5},{@{!,h}/1.5} -p=[0] 1 -endif # Decrease window size.
      -if {(@{!,CTRLLEFT}" || "@{!,CTRLRIGHT})" && "@{!,R}} -w[] {2*@{0,w}},@{0,h} -p=[0] 1 -endif         # Reset window size.

    -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
    -pp[0-2]    # Clean local stack.
    -rm[-3--1]  # Clean images.
  -endl -done -w 0 -v +

#@gmic x_life
#@gmic : Launch the game of life.
x_life :
  -e[] "\n
------ The game of life --------------------------------------\n
----\n
---- The goal is to create the biggest possible biological\n
---- system. You start with a stock of cells which you can\n
---- spread over the board. For each new cells created\n
---- simultaneously and spontaneously by your system, you\n
---- gain more new cells to scatter.\n
----\n
---- Left mouse button to scatter cells in stock.\n
---- Right mouse button to reset game.\n
---- Key 'S' to save snapshot of the current view.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------------------"
  -v -
  -i[0] 90,90,1,1,0                                             # Image[0] = game state.
  -i[1] [0] -f[1] 0                                             # Image[1] = generation counter.
  -i[2] 400,400,1,3                                             # Image[2] = visualization.
  -i[3] 1                                                       # Image[3] = colormap (to be initialized).
  -p[0] 0                                                       # Stack[0] = Iteration counter.
  -p[1] 0                                                       # Stack[1] = Current score.
  -p[2] 0                                                       # Stack[2] = Best score.
  -p[3] 500                                                     # Stack[3] = Remaining cells.
  -w[0] 400,400,0,0,"The Game of Life"                          # Initialize display window.

  # Start user-event loop.
  -do
    (1,1,1;1,0,1;1,1,1) --correlate[0] [-1],0 -rm[-2]           # Count numbers of neighboring living cells.
    --t2[-1] 2,2 -and[-1] [0] -t2[-2] 3,3 -or[-2,-1]            # Make the game evolve (kill or create cells).
    -rv[0,-1]                                                   # Update game state.
    -if {@{!,x}>0" && "@{!,b}==1" && "~3>0}                     # Add random cells to the game if user presses mouse button.
      -p {?*7}
      -repeat ~-1
        -p {@{!,x}/@{!,w}*@{0,w}+?(-4,4)}
        -p {@{!,y}/@{!,h}*@{0,h}+?(-3,3)}
        -=[0] 1,~-2,~-1
        -=[1] ~0,~-2,~-1
        -point[2] {~-2*@{2,w}/@{0,w}},{~-1*@{2,h}/@{0,h}},0,0.8,255
        -pp[-2,-1]
      -done
      -p=[3] {round(max(0,~3-~-1))} -pp[-1]
    -endif

    --[-1] [0] -*[-1] -1                                        # Compute difference between consecutive states.
    -p=[3] {~3-2*(min(0,int(@{-1,+}/16*~1/150)))}               # Increment available cells if the evolution is fast.
    -+[1] [0]                                                   # Increment generation counter for still existing cells.
    -min[-1] 0 -+[-1] 1 -*[1,-1]                                # Reset generation counter for died cells.

    -if {@{!,b}==2}                                             # Reset game if right mouse button has been pressed.
      -f[0-2] 0 -p=[0-2] 0 -p=[3] 500 -rm[3] -i[3] 1
    -endif

    -if {@{3,w}==1}                                             # Create color palette if necessary.
      -rm[3] -i[3] {?(3,12)},1,1,3,?(100,255)
      -r[3] {?(100,300)}%,1,1,3,4
      -point[3] 0,0,0,1,0
      -r[3] {?(100,600)}%,1,1,3,5 -c[3] 0,255
    -endif

    --r[1] @{2,w},@{2,h} -and[-1] 7 -blur[-1] {1+~1*0.05}       # Render colored image of the game and display it.
    -n[-1] 0,@{3,w} -map[-1] [3] -*[-1] 0.1 -+[2,-1] -/[2] 1.1
    [2] -if {@{!,x}>0}                                          # Add a small target icon at the mouse position.
      -p {0.7*min(1,~3/500)} -p {min(500,~3)*cos(~0)/100}
      -ellipse[-1] @{!,x},@{!,y},{15+~-1},{15+~-1},0,~-2,0,196,0
      -ellipse[-1] @{!,x},@{!,y},{10+~-1},{10+~-1},0,~-2,32,64,16
      -ellipse[-1] @{!,x},@{!,y},{5+~-1},{5+~-1},0,~-2,255,230,0
      -pp[-2,-1]
    -endif
    -text[-1] "Living cells : "~1"\n"\                          # Add score description.
              "Stock : "~3"\n"\
              "Score : "~2,5,3,22,0.7,255
    -w[-1] @{!,w},@{!,h}
    -if @{!,S} -o[-1] gmic_life.png -endif                      # Save snapshot if requested.
    -rm[-1]

    -if {!(~0%10)} -p=[1] @{0,+} -p=[2] {max(~1,~2)} -endif     # Re-compute current and best scores, every 10th iterations.
    -wait 60
    -p=[0] {~0+1}
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}

  # End game and quit properly.
  -rm[0-3] -w 0 -v +

#@gmic x_fire
#@gmic : Launch the fire demo.
x_fire : -skip "${1=G'MIC}"
  -e[] "\n
------ Fire demo ------------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v -

 # Init image data.
 -i[0] 100,32 -w[0] 600,300,0,0,"Fire demo"
 -i[1] (0,255,255,255,255^0,0,255,255,255^0,0,0,128,255) -r[1] 256,1,1,3,3
 -i[2] (0,0,0;0,0,0;1,1,1;0,1,0) -*[2] 0.23
 -text3d "$1",34,3,1 -mv[-1] 3 -c3d[3] -n3d[3] -*3d[3] 320 -col3d[3] 255,205,130 -db3d 0 -f3d 300
 100,100 -rand[-1] 0,255 -ellipse[-1] 50%,50%,5,5,0,1,300 -blur[-1] 10
 -sharpen[-1] 1000 -shrink_xy[-1] 1 -n[-1] 0,255 -to_rgb[-1] -light3d [-1] -rm[-1]

 # Start animation loop.
 -p[0] 0
 -do
   -correlate[0] [2]                                                # Apply fire effect.
   @{0,w},1 -rand[-1] 128,256 -image[0] [-1],0,{@{0,h}-1} -rm[-1]   # Add new random values at the bottom line.
   --r[0] 400,200,1,1,3 -map[-1] [1]                                # Map fire palette
   --rot3d[3] 0,1,0,~0 -m3d 5 -object3d[-2] [-1],50%,50%            # Draw 3d object.
   -*3d[-1] 0.25,0.16,1 -m3d 3 -object3d[0] [-1],50%,50%
   -rm[-1]
   -p=[0] {~0+3}                                                    # Update 3d angle.
   -w[-1] -rm[-1] -wait 40                                          # Display 3d object.
 -while {@!" && "!@{!,ESC}" && "!@{!,Q}}

 # Exit properly.
 -rm[0-3] -w 0
 -v +


#@gmic x_light
#@gmic : Launch the light demo.
x_light :
  -e[] "\n
------ Light demo ------------------------\n
----\n
---- Move light position with mouse.\n
---- Mouse buttons fade light in/out.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v -

  # Create warping and color images.
  1 -text[-1] "   G'MIC\nLight Demo",0,0,57,1,255 -expand_xy[-1] 15,0 -blur[-1] 3
  [-1] -n[-2] 0,1 -r[-2] 100%,100%,1,3
  --sh[-2] 0,0 -*[-1] 120 -rm[-1]
  --sh[-2] 1,1 -*[-1] 70 -rm[-1]
  --sh[-2] 0,50%,0,2 -*[-1] 120 -rm[-1]
  25%,25%,1,1 -rand[-1] -20,20 -smooth[-1] 10,0,1,1,4 -r[-1] [-2],3 -blur[-1] 3 -n[-1] -60,60
  -+[-2,-1] -gradient[-1] xy -a[-2,-1] c -n[-1] -150,150
  -w[] {2*@{-2,w}},{2*@{-2,h}},0,0,"Light Demo"  # Init display window.

  # Create a large light image.
  light=70
  512,512 -gaussian[-1] $light -n[-1] 0,255
  t=0

  # Start animation.
  -do

    # Manage light position and intensity.
    -if {@{!,x}>=0}
      X={round((w-@{!,x})/2)}
      Y={round((h-@{!,y})/2)}
    -else
      X={round((w-@{-2,w}*(1+cos(2*$t)))/2)}
      Y={round((h-@{-2,h}*(1+sin(2.5*$t)))/2)}
      t={$t+0.02}
    -endif
    -if {@{!,b}\&1} light={min(200,$light+10)} -gaussian[-1] $light -n[-1] 0,255 -endif
    -if {@{!,b}\&2} light={max(10,$light-10)} -gaussian[-1] $light -n[-1] 0,255 -endif

    # Render lightened image.
    --crop[-1] $X,$Y,{$X+@{-2,w}-1},{$Y+@{-2,h}-1}
    -warp[-1] [-3],1,0,1
    -r[-1] 100%,100%,1,3 -+[-1] [-4] -c[-1] 0,255
    -w[-1] {2*w},{2*h}
    -rm[-1] -if {@{!,x}>=0" && "!@{!,b}} -wait -else -wait 20 -endif
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -w[] 0 -rm[-3--1] -v +

#@gmic x_jawbreaker : 0<_width<20,0<_height<20,0<_balls<=8
#@gmic : Launch the Jawbreaker game.
x_jawbreaker : -check "${1=12}>0 && $1<20 && ${2=13}>0 && $2<20 && ${3=5}>0 && $3<=8"
  -e[] "\n
------ Jawbreaker --------------------------------------------\n
----\n
---- The goal of the game is to remove the maximum number of\n
---- balls on the board, simply by clicking on them. But a\n
---- colored ball can disappear only if it is grouped with at\n
---- least one ball of the same color. The score is higher if\n
---- you destroy larger sets of connected colored balls.\n
----\n
---- Left mouse button to select/destroy balls on board.\n
---- Key 'BACKSPACE' or 'SPACE' to undo the last move.\n
---- Key 'S' to save snapshot of the current view.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------------------"
  -v -

  # Init images and variables.
  -i[board] $1,$2 -rand[board] 1,$3 -round[board] 1
  -i[undo] [-1]
  -i[balls] 32,32 -ball[-1] 255,255,255 -autocrop[-1] 0 -expand_xy[-1] 1,0 -*[-1] 1.5 -c[-1] 0,255 -r[-1] {@{&board,w}*w},{@{&board,h}*h},1,1,0,2 -/[-1] 255
  -i[back] {w},{h},1,3 -l[-1]
    -rand 0,255 -blur_xy 6,20 -equalize 100,0,255 -blur_xy 2,4
    --sh 0,0 --sh[-2] 1,1 --sh[-3] 2,2 -/[-3] 4 -/[-2] 8 -/[-1] 2 -rm[-3--1]
  -endl
  -i[visu] [back]
  score=0
  undoscore=0
  render_board=1
  shapescorey=0
  shapescore=0

  # Enter user-event loop.
  -do

    # Render board graphics.
    -if $render_board
      --abs[board] --[-1] 1 -*[-1] {360/$3} --t[board] 0 -*[-1] 0.9 -r[-2,-1] [balls] [balls]
       -a[-3--1] c -hsv2rgb[-1]
      --compose_channels[-1] + -t[-1] 0.1 -dilate[-1] 3
      -image[visu] [back] -image[visu] [-2],0,0,0,0,1,[-1] -rm[-2,-1]
      -if {!$shapescorey} -w[visu] @{&back,w},@{&back,h},0,0,"Jawbreaker (score : "$score")" -endif
      render_board=0
    -endif

    # Add shape score sprite if necessary.
    -if $shapescorey
      --text[visu] "+"$shapescore,@{!,x},{@{!,y}-64+$shapescorey},32,{($shapescorey-1)/31},255
      shapescorey={max(0,$shapescorey-1)}
      -w[-1] @{&back,w},@{&back,h},0,0,"Jawbreaker (score : "$score")" -rm[-1] -wait 25
    -else -wait -endif

    # Check for the end of the game.
    --f[board] "if(i,i(x-1,y,0,0,0)==i || i(x+1,y,0,0,0)==i || i(x,y+1,0,0,0)==i || i(x,y-1,0,0,0)==i,0)"
    -if {!@{-1,+}} -rm[-1] -b -endif -rm[-1]

    # Manage user-events
    -if @{!,r} render_board=1                   # Will resize window to initial size, if resized.
    -elif @{!,S} -o[visu] gmic_jawbreaker.png   # Save snapshot if requested.
    -elif {@{!,BACKSPACE}" || "@{!,SPACE}}      # Manage undo move.
      -abs[undo] -image[board] [undo]
      score=$undoscore
      render_board=1

    -elif {@{!,x}">=0 && "@{!,b}}               # Manage button click.

      # Retrieve board coordinates.
      -wait -1
      x={"int("@{!,x}"*"@{&board,w}"/"@{!,w}")"}
      y={"int("@{!,y}"*"@{&board,h}"/"@{!,h}")"}

      # When selecting a ball -> display selection and init new shape score sprite.
      -if {@{&board,($x,$y)}>0}
        -abs[board] -flood[board] $x,$y,0,0,1,-@{&board,($x,$y)}
        --t[board] 0 --[-1] 1
        shapescore={(@{-1,+}+1)^2} shapescorey={if($shapescore,32,0)} -rm[-1]

      # When confirming selection of a ball -> remove set of connected balls.
      -elif @{&board,($x,$y)}

        --flood[board] $x,$y,0,0,1,-1 -==[-1] -1
        -if {@{-1,+}>1} # If selected ball is connected to at least one ball.

          # Save undo state.
          -image[undo] [board]
          undoscore=$score

          # Manage board shifts (vertical and horizontal).
          -flood[board] $x,$y,0,0,1,0
          -repeat @{&board,w}
            --columns[board] ~> -mirror[-1] y
            h=@{&board,h} -l[-1] -s 0,- -a y -if @# -r 1,$h,1,1,0 -mirror y -else -i 1,$h -endif -endl -pp[h]
            -image[board] [-1],~> -rm[-1]
          -done
          -lines[board] -1,100% -f[board] "if(y==0,if(i(x,h-1),x,w),i)" -sort[board] +,x -lines[board] 1,100%

          # Update score.
          score={$score+int((@{-1,+}-1)^2)}

        -endif
        -rm[-1] # Remove selection mask.

      -else -abs[board]  # Remove previous selection if clicked outside balls.
      -endif

      render_board=1
      -pp[x,y]
    -endif

  -while {@!" && "!@{!,Q}" && "!@{!,ESC}}

  # Game over.
  -if {@!" && "!@{!,ESC}}
    -w[] @{&visu,w},@{&visu,h},0,0,"Jawbreaker (final score : "$score")"
    -i[gameover] 230,85 -text[-1] "Game Over !",3,0,57,1,1 -text[-1] "Score : "$score,24,54,32,1,1
    --dilate[-1] 5 -nm[-1] "mgameover" -*[-2] 255 -r[-2] 100%,100%,1,3
    -repeat 25
      --r[gameover,mgameover] {400-12*(~>+1)}%,{400-12*(~>+1)}%
      --image[visu] [-2],{(@{&visu,w}-w)/2},{(@{&visu,h}-h)/2},0,0,{~>/25},[-1]
      -w[-1] -rm[-3--1] -wait 25
    -done
    -do
      -wait -if @{!,r} -w[] @{!,w},@{!,h} -wait -1 -endif
      -while {@!" && "!@{!,Q}" && "!@{!,ESC}" && "!@{!,b}}
    -rm[gameover,mgameover]
  -endif

  # End properly.
  -rm[board,undo,balls,back,visu]
  -w 0 -v +

#@gmic x_paint
#@gmic : Launch the interactive painter.
x_paint :
  -e[] "\n
------ Interactive painter -----------------------\n
----\n
---- Use mouse to select color and brush.\n
---- Left button draws a colored stroke.\n
---- Right button fills a colored region.\n
---- Arrow keys or SPACE and BACKSPACE to swap\n
---- between available images.\n
---- Key 'S' to save snapshot of the current view.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------"
  -v - -to_rgb

  # Init variables and images.
  -if {!@#} -i[0] 512,512,1,3,255 -endif
  color=0,0,0
  saturation=1
  brushsize=3
  brushopacity=0
  brushangle=90
  brushthickness=1
  image=0
  refresh_palette=1
  refresh_image=1
  refresh_brush=1
  ox1=-1
  oy1=-1
  1 1    # Palette image [-2] and brush image [-1]

  # Start user event loop.
  -do

    # Open/refresh palette window.
    -if $refresh_palette
      -rm[-2] (0,359;0,359^$saturation,$saturation;$saturation,$saturation^1,1;0,0) -r[-1] 256,64,1,3,3 -hsv2rgb[-1]
      (255;0) -r[-1] 16,@{-2,h},1,3,3 -line[-1] 0,0,0,100%,1,0 -a[-2,-1] x
      {w},16,1,3 -text[-1] "Selected color",4,2,13,1,255
      -polygon[-1] 4,80,3,100,3,100,13,80,13,1,$color
      -polygon[-1] 4,80,3,100,3,100,13,80,13,1,0xFFFFFFFF,255,255,255
      -a[-2,-1] y -w2[-1] {w},{h},0,0,"Palette" -mv[-1] -2
      refresh_palette=0
    -endif

    # Open/refresh brush window.
    -if $refresh_brush
      -rm[-1] (32,64;64,32) -r[-1] 16,16,1,3,1 -r[-1] {8*48},{4*48},1,3,0,2
      -repeat 4 -repeat 8
        -ellipse[-1] {48*~>+24},{48*@{>,-2}+24},{2*~>+1},{(2*~>+1)*$brushthickness},$brushangle,{1-@{>,-2}/4},255
      -done -done
      -polygon[-1] 4,{$brushsize*48},{$brushopacity*48},\
                     {$brushsize*48+47},{$brushopacity*48},\
                     {$brushsize*48+47},{$brushopacity*48+47},\
                     {$brushsize*48},{$brushopacity*48+47},\
                     1,0xFFFFFFFF,255,128,128
      {w},16,1,3 -line[-1] 0,50%,100%,50%,1,0x55555555,128,64,128
      bx={$brushangle*w/180}
      -polygon[-1] 4,{$bx-16},20%,{$bx+16},20%,{$bx+16},80%,{$bx-16},80%,1,128
      -line[-1] {$bx-16},20%,{$bx+16},20%,1,255 -line[-1] {$bx+16},20%,{$bx+16},80%,1,255
      -line[-1] {$bx-16},80%,{$bx+16},80%,1,64 -line[-1] {$bx-16},20%,{$bx-16},80%,1,64
      -a[-2,-1] y
      16,{h-16},1,3 -line[-1] 50%,0,50%,100%,1,0x55555555,128,64,128
      by={$brushthickness*(h-16)}
      -polygon[-1] 4,20%,{$by-16},80%,{$by-16},80%,{$by+16},20%,{$by+16},1,128
      -line[-1] 20%,{$by-16},80%,{$by-16},1,255 -line[-1] 80%,{$by-16},80%,{$by+16},1,255
      -line[-1] 20%,{$by-16},20%,{$by+16},1,64 -line[-1] 20%,{$by+16},80%,{$by+16},1,64
      -a[-2,-1] x
      -w3[-1] {w},{h},0,0,"Brush"
      refresh_brush=0
    -endif

    # Open/refresh image window.
    -if $refresh_image
      -w1[$image] @{$image,w},@{$image,h},0,0,"Image "#$image" : "@{$image,b}.@{$image,x}
      refresh_image=0
    -endif

    # Manage user events.
    x1=@{!1,x} y1=@{!1,y}
    x2=@{!2,x} y2=@{!2,y}
    x3=@{!3,x} y3=@{!3,y}

    -if {$x1>=0}                        # Event in the image window.
      -if {@{!1,b}\&1}                  # Left button -> draw brush stroke.
        ox1={if($ox1<0,$x1,$ox1)}
        oy1={if($oy1<0,$y1,$oy1)}
        delta={max(abs($x1-$ox1),abs($y1-$oy1))}
        r1={2*$brushsize+1}
        r2={$r1*$brushthickness}
        dx={2*($x1-$ox1)/max(1,$delta)}
        dy={2*($y1-$oy1)/max(1,$delta)}
        o={1-($brushopacity/4)^0.04}
        -repeat {max(1,($delta+1)/2)}
          -ellipse[$image] {$ox1+~>*$dx},{$oy1+~>*$dy},$r1,$r2,$brushangle,$o,$color
        -done
        ox1=$x1 oy1=$y1
        refresh_image=1
      -else
        ox1=-1 oy1=-1
        -if {@{!1,b}\&2}              # Right button -> fill region.
          -flood[$image] $x1,$y1,0,10,1,$color
          refresh_image=1
        -endif
      -endif
    -endif

    -if {@{!1,ARROWRIGHT}" || "@{!2,ARROWRIGHT}" || "@{!3,ARROWRIGHT}" || "\  # Manage image selection.
         @{!1,ARROWUP}" || "@{!2,ARROWUP}" || "@{!3,ARROWUP}" || "\
         @{!1,SPACE}" || "@{!2,SPACE}" || "@{!3,SPACE}}
      image={($image+1)%(@#-2)} refresh_image=1
    -elif {@{!1,ARROWLEFT}" || "@{!2,ARROWLEFT}" || "@{!3,ARROWLEFT}" || "\
           @{!1,ARROWDOWN}" || "@{!2,ARROWDOWN}" || "@{!3,ARROWDOWN}" || "\
           @{!1,BACKSPACE}" || "@{!2,BACKSPACE}" || "@{!3,BACKSPACE}}
      image={($image-1)%(@#-2)} refresh_image=1
    -endif

    -if @{!1,S} -o[$image] gmic_paint.png -endif  # Save snapshot if requested.

    -if {@{!2,b}" && "$x2>=0" && "$y2<64}  # Manage color selection from the palette window.
      -if {$x2>=256} saturation={1-$y2/63}
      -elif {$x2>=0} color=@{-2,($x2,$y2,0,0)},@{-2,($x2,$y2,0,1)},@{-2,($x2,$y2,0,2)}
      -endif
      refresh_palette=1
    -endif

    -if {@{!3,b}" && "$x3>=0}  # Manage brush selection.
      -if {$x3<384" && "$y3>=192}   # Bottom slider -> select brush angle.
        brushangle={$x3*180/(@{-1,w}-16)}
      -elif {$x3>=384" && "$y3<192} # Right slider -> select brush thickness.
        brushthickness={$y3/(@{-1,h}-16)}
      -elif {$x3<384" && "$y3<192}
        brushsize={int($x3*8/(@{-1,w}-16))}
        brushopacity={int($y3*4/(@{-1,h}-16))}
      -endif
      refresh_brush=1
    -endif
    -wait
    -while {@{!1}" && "!@{!1,Q}" && "!@{!1,ESC}}

  # Exit properly.
  -w1[] 0 -w2[] 0 -w3[] 0 -rm[-2,-1] -v +


#--------------------------
#
# 'Undocumented' commands
#
#--------------------------

# Function useful to display help of commands, in interactive shell mode (linux only).
help : -skip ${1=""}
  -v -
  -if {narg($1)}
    -x "gmic -h $1 | tail -n +6 | head -n -1"
  -else
    -x "gmic -h | head -n 5"
  -endif
  -v +
h :
  -help ${^0}

# path_tmp
# Return a path to store temporary files (OS-dependent).
path_tmp :
  -u ""
  -if {narg({'${TMP}'})} -u ${TMP}
  -elif {narg({'${TEMP}'})} -u ${TEMP}
  -elif {narg({'${TMPDIR}'})} -u ${TMPDIR}
  -elif {narg({'${HOME}'})} -u "/tmp"
  -endif

# path_user
# Return a path to store persistent configuration files for one user (OS-dependent).
path_user :
  -u ""
  -if {narg({'${APPDATA}'})} -u ${APPDATA}
  -elif {narg({'${HOME}'})} -u ${HOME}
  -endif

# RGB
# Return a random RGB color
RGB :
  3,1,1,1,round(?(255)) -u @-1 -rm[-1]

# RGBA
# Return a random RGBA color
RGBA :
  4,1,1,1,round(?(255)) -u @-1 -rm[-1]

# strcmp : string1,string2
# Return the comparison value between two strings.
strcmp :
  (0,{'$1'}) ({w},{'$2'}) -=[-2] {w} --[-2,-1] -abs[-1] -u {!@{-1,+}} -rm[-1]

# fact : value
# Return the factorial of specified value.
fact : -check isint($1)
  res=1 -repeat $1 res={$res*(~>+1)} -done -u $res

# filename : filename,_number1,_number2,...,_numberN
# Return a filename numbered with specified indices.
filename : -skip "${1=default}"
  -if {$#==1} -u "$1"
  -else
  (${2--1}) -name[-1] "$1" -u @{-1,f}@{-1,b}
  -repeat {w}
    -u @{}_{int(i/100000)%10}{int(i/10000)%10}{int(i/1000)%10}{int(i/100)%10}{int(i/10)%10}{i%10}
    -shift[-1] -1
  -done
  -if {narg({'@{-1,x}'})} -u @{}.@{-1,x} -endif
  -rm[-1]
  -endif

# max_whds
# Return the maximal wxhxdxs size of selected images.
max_whds :
  -_max_whds 4

_max_whds :
  -p[0] 0 -p[1] 0 -p[2] 0 -p[3] 0
  -repeat @#
    -p=[0] {max(~0,w)}
    -p=[1] {max(~1,h)}
    -p=[2] {max(~2,d)}
    -p=[3] {max(~3,s)}
  -mv[-1] 0 -done
  -if {$1>=4} -u ~0,~1,~2,~3
  -elif {$1==3} -u ~0,~1,~2
  -elif {$1==2} -u ~0,~1
  -else -u ~0
  -endif

# max_whd
# Return the maximal wxhxd size of selected images.
max_whd :
  -_max_whds 3

# max_wh
# Return the maximal wxh size of selected images.
max_wh :
  -_max_whds 2

# max_s
# Return the maximal s size of selected images.
max_s :
  -_max_s @{"-_max_whds 4"}

_max_s :
  -u $4

# min_whds
# Return the minimal wxhxdxs size of selected images.
min_whds :
  -_min_whds 4

_min_whds :
  -p[0] 0 -p[1] 0 -p[2] 0 -p[3] 0
  -repeat @#
    -p=[0] {min(~0,w)}
    -p=[1] {min(~1,h)}
    -p=[2] {min(~2,d)}
    -p=[3] {min(~3,s)}
  -mv[-1] 0 -done
  -if {$1>=4} -u ~0,~1,~2,~3
  -elif {$1==3} -u ~0,~1,~2
  -elif {$1==2} -u ~0,~1
  -else -u ~0
  -endif

# min_whd
# Return the minimal wxhxd size of selected images.
min_whd :
  -_min_whds 3

# min_wh
# Return the minimal wxh size of selected images.
min_wh :
  -_min_whds 2

# min_s
# Return the minimal s size of selected images.
min_s :
  -_min_s @{"-_min_whds 4"}

_min_s :
  -u $4

# fitratio_wh : min_width,min_height,ratio_wh
# Return a 2D dimension 'width,height' which is bigger than 'min_width,min_height' and has the specified w/h ratio.
fitratio_wh :
  -if {$3*$2>$1} -u {int($3*$2)},$2 -else -u $1,{int($1/$3)} -endif

#--------------------------
#
# Define menu entries
# for the GIMP plug-in.
#
#--------------------------

# Generate a splitted preview, with arguments "command",_split_type={ 0=full | 1=forw. horiz. | 2=forw. vert. | 3=back. horiz. | 4=back. vert. }
_before :
  33,11 -text[-1] "Before",1,-1,13,1,1
_after :
  26,11 -text[-1] "After",1,-1,13,1,1

gimp_split_preview :
  -repeat @#
    -if {$2==0} -l[-1] $1 -endl -mv[-1] 0 -continue -endif  # No split.
    -if {!($2%2)} # Vertical split.
      -s[-1] x,2
      -if {$2==2} -l[-1] $1 -endl -to_colormode[-2,-1] {max(@{-2,s},s)} -_before -_after
      -else -l[-2] $1 -endl -to_colormode[-2,-1] {max(@{-2,s},s)} -_after -_before
      -endif
      -line[-3] 0,0,0,@{-3,h},1,0,0,0,255 -a[-4,-3] x
    -else # Horizontal split.
      -s[-1] y,2
      -if {$2==1} -l[-1] $1 -endl -to_colormode[-2,-1] {max(@{-2,s},s)} -_before -_after
      -else -l[-2] $1 -endl -to_colormode[-2,-1] {max(@{-2,s},s)} -_after -_before
      -endif
      -line[-3] 0,0,@{-3,w},0,1,0,0,0,255 -a[-4,-3] y
    -endif
    --dilate[-2,-1] 3 -*[-4,-3] 255 -to_colormode[-4,-3] @{-5,s} # If splited, display "before/after" text.
    -image[-5] [-4],1,1,0,0,0.8,[-2] -image[-5] [-3],{@{-5,w}-w-1},{@{-5,h}-h-1},0,0,0.8,[-1]
    -rm[-4--1]
  -mv[-1] 0 -done

# Generate a 'no-preview' image.
gimp_no_preview :
  -if {@#>0} -k[0] -else 256,256,1,1,128 -endif
  118,50 -text[-1] "No preview\navailable",2,1,24,1,255 -r[-1] [-2],[-2],1,1,0,0,0.5,0.5 -to_colormode[-1] @{-2,s}
  (1.5,0,1.5;0,0,0;1.5,0,1.5) -r[-1] [-3],3 -*[-3,-1] -c[-2] 0,255 -or
  -skip ${^0}

# Do not forget to ucomment this entry for a deprecated version of the G'MIC plug-in !
# #@gimp <span foreground="red"><b>UPDATE INFORMATION</b></span> : _none_, gimp_logo_en
# #@gimp : note = note{"A <b>new version</b> of the G'MIC plug-in for GIMP is available !
# #@gimp : You are strongly encouraged to download and install this updated version, by clicking on one of the following urls :"}
# #@gimp : note = note{"\n<span foreground="purple"><u>Windows version :</u></span>"}
# #@gimp : url = link{"Download G'MIC plug-in for Windows (32 bits)","http://downloads.sourceforge.net/gmic/gmic_gimp_win32.exe"}
# #@gimp : note = note{"<b>Installation </b>: unzip the archive files and copy them into folder\n
# #@gimp :              <i>C:\\Program Files\\GIMP\\lib\\gimp\\2.0\\plug-ins\</i>"}
# #@gimp : note = note{"\n<span foreground="purple"><u>Linux version :</u></span>"}
# #@gimp : url = link{"Download plug-in for Linux (32 bits)","http://downloads.sourceforge.net/gmic/gmic_gimp_linux32.zip"}
# #@gimp : url = link{"Download plug-in for Linux (64 bits)","http://downloads.sourceforge.net/gmic/gmic_gimp_linux64.zip"}
# #@gimp : note = note{"<b>Installation </b>: unzip the archive files and copy them in folder\n
# #@gimp :              <i>/usr/lib/gimp/2.0/plug-ins/</i>"}
# #@gimp : note = note{"\nNote that there will be no updated filters anymore for your current plug-in version.
# #@gimp : Installing the G'MIC plug-in for GIMP is easy and fast, so there are no reasons not for doing it :).\n\n
# #@gimp : Best regards,\n\n <i>The G'MIC team.</i>"}



#----------------------
# English translations
#----------------------

#@gimp_en <i>About</i>
#----------------------

#@gimp_en G'MIC for GIMP : _none_, gimp_logo_en
#@gimp_en : note = note{"
#@gimp_en : <span foreground="purple">( <b>G</b>REYC's <b>M</b>agic <b>I</b>mage <b>C</b>onverter )</span>\n\nis proposed to you by"}
#@gimp_en : note = link("David Tschumperl\303\251","http://www.greyc.ensicaen.fr/~dtschump")
#@gimp_en : note = link{"( IMAGE Team / GREYC Laboratory - CNRS UMR 6072 )","http://www.greyc.ensicaen.fr/EquipeImage"}
#@gimp_en : note = note{"
#@gimp_en : This plug-in is based on our open-source libraries <b>G'MIC</b> and <b>CImg</b> (C++ Template Image Processing Library),
#@gimp_en : available at :"}
#@gimp_en : note = link("http://gmic.sourceforge.net/")
#@gimp_en : note = note{"and"}
#@gimp_en : note = link("http://cimg.sourceforge.net/")
#@gimp_en : note = note{"\n
#@gimp_en : If you appreciate <b>G'MIC</b>, you are welcome to send us a nice postcard from your place, at :\n\n
#@gimp_en : <small><tt>David Tschumperl&#233;,\n Laboratoire GREYC (CNRS UMR 6072), Equipe Image,\n
#@gimp_en :  6 Bd du Mar&#233;chal Juin,\n 14050 Caen Cedex / France.</tt></small>\n\n
#@gimp_en : Postcards senders automatically enter the <i>Friends Hall of Fame</i> :) !
#@gimp_en : "}
gimp_logo :
  -if @# -p[0] {w/h} -else -p[0] 1 -endif
  -rm 118,44,1,1 -text "G'MIC",3,-6,57,1,255 -r 100%,100%,10,1 -r 100%,100%,20,1,0,0,0.5,0.5,0.5 -blur 1.5
  -isosurface3d 50%
  -col3d {?(150,255)},{?(150,255)},{?(150,255)}
  -sphere3d 8 -col3d[-1] {?(150,255)},{?(150,255)},{?(150,255)} -+3d[-1] 72,-6 -+3d -c3d[-1] -rv3d
  -db3d 0 -m3d 4 -sl3d 0.2 -ss3d 1.3 -rot3d[-1] 1,0,0,30 -f3d 120 -*3d[-1] 1.5
  230,120,1,3 -object3d[-1] [-2],50%,30%,0,1 -rm[-2] -text "$1",12%,75%,24,1,255
  -to_rgba -replace_color 0,0,0,0,0,255,0,0,0,0 -drop_shadow 6,6,2
  -i[-2] @{"-fitratio_wh 230,120,"~0},1,3
  -rand[-2] 0,255 --sh[-2] 0,0 -/[-1] 2 -rm[-1]
  -blur_radial[-2] 10 -sharpen[-2] 600
  -r[-1] [-2],[-2],1,4,0,0,0.5,0.5 -compose_rgba

gimp_logo_en :
  -gimp_logo "Plug-in for GIMP"

#@gimp_en Filters design : _none_, _none_
#@gimp_en : note = note{"
#@gimp_en : <b>G'MIC</b> is an <b>open</b> image processing framework. Thus, including
#@gimp_en : <b>user-defined filters</b> into this plug-in is possible.\n\n
#@gimp_en : To do so, you need to create a <span foreground="purple" style="italic">.gmic</span>
#@gimp_en : file (do not forget the first dot !) in your <i>Home</i> folder (or <i>Applications Data/</i> on Windows).
#@gimp_en : It will be read each time the plug-in is launched, or when the <i>Refresh</i>
#@gimp_en : button (under the central pane) is pressed. It must be a regular ASCII file, containing the declarations and
#@gimp_en : implementations of the filters (written in the <b>G'MIC</b> language) that will be added
#@gimp_en : to the list of available ones.\n\n
#@gimp_en : Existing filters are already defined this way.
#@gimp_en : The current implementations can be seen at :"}
#@gimp_en : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_en : note = note{"
#@gimp_en : Writting a new filter in <b>G'MIC</b> is not particularly awful (nor trivial) and
#@gimp_en : can be generally done in very few lines.\n\n
#@gimp_en : <span foreground="purple" underline="single">Example of a valid <i>.gmic</i> entry :</span>\n\n
#@gimp_en : <tt>#@gimp My effect : my_effect, my_effect\n
#@gimp_en : #@gimp : Sigma = float(2,0,10)\n
#@gimp_en : my_effect :\n     --blur $1 -n 0,255 -xor</tt>\n\n
#@gimp_en : By the way, you are encouraged to share your nice custom filters on the dedicated forum,
#@gimp_en : for inclusion into next releases of <b>G'MIC</b> :
#@gimp_en : "}
#@gimp_en : note = link("Go to the G'MIC forum","http://www.flickr.com/groups/gmic/discuss/")

#@gimp_en Filters update : _none_, _none_
#@gimp_en : note = note{"
#@gimp_en : Thanks to its openness, <b>G'MIC</b> is able to <b>update</b> his list of filters
#@gimp_en : from the Internet. Pushing the <i>Refresh</i> button (under the central pane)
#@gimp_en : makes <b>G'MIC</b> connect to the update server and download the latest filter definitions.
#@gimp_en : This is actually the only network operation allowed in <b>G'MIC</b>.\n\n
#@gimp_en : Technically speaking, this update procedure creates/replaces the file
#@gimp_en : <span foreground="purple" style="italic">.gmic_def.xxxx</span> in your <i>Home</i> folder
#@gimp_en : (or <i>Application Data/</i> on Windows),
#@gimp_en : where <i>xxxx</i> are the four digits of the <b>G'MIC</b> version number.
#@gimp_en : In case of connecting troubles, you can then manually do the update by retrieving the filter
#@gimp_en : definition file directly from :"}
#@gimp_en : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_en : note = note{"
#@gimp_en : Just copy and rename this file as your <span foreground="purple" style="italic">.gmic_def.xxxx</span>
#@gimp_en : (do not forget the first dot, and replace the <i>xxxx</i> by the 4 digits of your <b>G'MIC</b> version number)
#@gimp_en : and you are done.
#@gimp_en : By the way, deleting this file resets all the filters to their initial state.
#@gimp_en : "}

#---------------------
# French translations
#---------------------

#@gimp_fr <i>&#192; propos</i>
#------------------------------

#@gimp_fr G'MIC pour GIMP : _none_, gimp_logo_fr
#@gimp_fr : note = note{"
#@gimp_fr : <span foreground="purple">( <b>G</b>REYC's <b>M</b>agic <b>I</b>mage <b>C</b>onverter )</span>\n\nvous est proposé par"}
#@gimp_fr : note = link("David Tschumperl\303\251","http://www.greyc.ensicaen.fr/~dtschump")
#@gimp_fr : note = link{"( Equipe IMAGE / Laboratoire GREYC - CNRS UMR 6072 )","http://www.greyc.ensicaen.fr/EquipeImage"}
#@gimp_fr : note = note{"
#@gimp_fr : Ce greffon est bas&#233; sur nos biblioth&#232;ques libres <b>G'MIC</b> et <b>CImg</b> (C++ Template Image Processing Library),
#@gimp_fr : disponibles aux adresses :"}
#@gimp_fr : note = link("http://gmic.sourceforge.net/")
#@gimp_fr : note = note{"et"}
#@gimp_fr : note = link("http://cimg.sourceforge.net/")
#@gimp_fr : note = note{"\n
#@gimp_fr : Si vous appr&#233;ciez <b>G'MIC</b>, vous pouvez nous le faire savoir en nous envoyant une jolie carte
#@gimp_fr : postale de votre ville ou r&#233;gion, &#224; l'adresse :\n\n
#@gimp_fr : <small><tt>David Tschumperl&#233;,\n Laboratoire GREYC (CNRS UMR 6072), Equipe Image,\n
#@gimp_fr :  6 Bd du Mar&#233;chal Juin,\n 14050 Caen Cedex / France.</tt></small>\n\n
#@gimp_fr : Envoyer une carte postale vous fera rentrer <i>de facto</i> dans le <i>Friends Hall of Fame</i> :) !
#@gimp_fr : "}
gimp_logo_fr :
  -gimp_logo "Greffon pour GIMP"

#@gimp_fr Cr&#233;ation de filtres : _none_, _none_
#@gimp_fr : note = note{"
#@gimp_fr : <b>G'MIC</b> est un système <b>ouvert</b> de traitement d'image. Il est ainsi possible
#@gimp_fr : d'ajouter vos <b>propres filtres personnalisés</b> à l'intérieur même de ce greffon.\n\n
#@gimp_fr : Pour cela, il vous suffit de cr&#233;er un fichier <span foreground="purple" style="italic">.gmic</span>
#@gimp_fr : (ne pas oublier le premier point !) dans votre dossier <i>Home</i> (ou <i>Applications Data/</i> sous Windows).
#@gimp_fr : Ce fichier va être lu &#224; chaque d&#233;marrage du greffon, ou lorsque le bouton <i>Actualiser</i>
#@gimp_fr : (sous le panneau central) sera cliqu&#233;. Ce fichier ASCII va contenir les déclarations et les
#@gimp_fr : implémentations des filtres (écrits en langage <b>G'MIC</b>) qui vont s'ajouter à la liste des filtres disponibles.\n\n
#@gimp_fr : Tous les filtres existants sont déjà définis de cette façon. Les impl&#233;mentations actuelles sont visibles
#@gimp_fr : &#224; l'adresse :"}
#@gimp_fr : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_fr : note = note{"
#@gimp_fr : Ecrire un filtre en langage <b>G'MIC</b> n'est pas particulièrement difficile (sans être trivial),
#@gimp_fr : et ne n&#233;cessite souvent que quelques lignes.\n\n
#@gimp_fr : <span foreground="purple" underline="single">Exemple de fichier <i>.gmic</i> valide :</span>\n\n
#@gimp_fr : <tt>#@gimp My effect : my_effect, my_effect, Sigma = float(2,0,10)\n
#@gimp_fr : my_effect :\n     --blur $1 -n 0,255 -xor</tt>\n\n
#@gimp_fr : Vous &#234;tes bien s&#251;r encourag&#233;s &#224; partager vos propres filtres sur le forum pr&#233;vu &#224;
#@gimp_fr : cet effet, pour une inclusion éventuelle dans les prochaines versions de <b>G'MIC</b> :
#@gimp_fr : "}
#@gimp_fr : note = link("Participer au forum G'MIC","http://sourceforge.net/projects/gmic/forums/forum/849382")

#@gimp_fr Mise &#224; jour des filtres : _none_, _none_
#@gimp_fr : note = note{"
#@gimp_fr : De par son architecture ouverte, <b>G'MIC</b> est capable de <b>mettre &#224; jour</b> sa liste
#@gimp_fr : de filtres. L'appui sur le bouton <i>Actualiser</i> (sous le panneau central)
#@gimp_fr : va permettre la connexion au serveur de mises &#224; jour, et le t&#233;l&#233;chargement
#@gimp_fr : des derni&#232;res d&#233;finitions de filtres. C'est la seule op&#233;ration r&#233;seau
#@gimp_fr : que nous avons autoris&#233;e dans <b>G'MIC</b>.\n\n
#@gimp_fr : Techniquement, cette proc&#233;dure cr&#233;&#233;/remplace le fichier
#@gimp_fr : <span foreground="purple" style="italic">.gmic_def.xxxx</span> dans votre r&#233;pertoire <i>Home</i>
#@gimp_fr : (ou <i>Application Data/</i> sous Windows),
#@gimp_fr : o&#249; <i>xxxx</i> sont les quatres chiffres du num&#233;ro de version du greffon <b>G'MIC</b>.
#@gimp_fr : En cas de probl&#232;me, vous pouvez donc toujours mettre &#224; jour vos filtres manuellement,
#@gimp_fr : en t&#233;l&#233;chargeant le fichier suivant :"}
#@gimp_fr : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_fr : note = note{"
#@gimp_fr : Copiez juste ce fichier &#224; la bonne place, et renommez le en <span foreground="purple" style="italic">.gmic_def.xxxx</span>
#@gimp_fr : (n'oubliez pas le premier point, et remplacez les <i>xxxx</i> par le num&#233;ro de version de votre greffon <b>G'MIC</b>)
#@gimp_fr : et la proc&#233;dure de mise &#224; jour sera effectu&#233;e.
#@gimp_fr : Bien entendu, effacer ce fichier réinitialise l'ensemble des d&#233;finitions des filtres &#224; leurs &#233;tats initiaux.
#@gimp_fr : "}

#----------------------
# Catalan translations
#----------------------

#@gimp_ca <i>About</i>
#----------------------

#@gimp_ca G'MIC per al GIMP : _none_, gimp_logo_ca
#@gimp_ca : note = note{"
#@gimp_ca : <span foreground="purple">( <b>G</b>REYC's <b>M</b>agic <b>I</b>mage <b>C</b>onverter )</span>\n\n &#233;s una gentilesa de"}
#@gimp_ca : note = link("David Tschumperl\303\251","http://www.greyc.ensicaen.fr/~dtschump")
#@gimp_ca : note = link{"( IMAGE Team / GREYC Laboratory - CNRS UMR 6072 )","http://www.greyc.ensicaen.fr/EquipeImage"}
#@gimp_ca : note = note{"
#@gimp_ca : Aquest connector est&#224; basat en les biblioteques de codi obert <b>G'MIC</b> i <b>CImg</b> (C++ Template Image Processing Library),
#@gimp_ca : disponibles a :"}
#@gimp_ca : note = link("http://gmic.sourceforge.net/")
#@gimp_ca : note = note{"i"}
#@gimp_ca : note = link("http://cimg.sourceforge.net/")
#@gimp_ca : note = note{"\n
#@gimp_ca : Si t'agrada el <b>G'MIC</b>, pots enviar-nos una postal del lloc on vius, a :\n\n
#@gimp_ca : <small><tt>David Tschumperl&#233;,\n Laboratoire GREYC (CNRS UMR 6072), Equipe Image,\n
#@gimp_ca :  6 Bd du Mar&#233;chal Juin,\n 14050 Caen Cedex / France.</tt></small>\n\n
#@gimp_ca : Tot aquell que envi&#239; una postal apareixer&#224; al <i>Friends Hall of Fame</i> :) !
#@gimp_ca : "}
gimp_logo_ca :
  -gimp_logo "  per al GIMP"

#@gimp_ca Filters design : _none_, _none_
#@gimp_ca : note = note{"
#@gimp_ca : Si voleu podeu afegir els vostres <b>filtres d'usuari</b> al connector <b>G'MIC</b> :\n\n
#@gimp_ca : Per a fer-ho, cal que creeu un fitxer <span foreground="purple" style="italic">.gmic</span> (no oblideu el primer punt !)
#@gimp_ca : a la vostra <i>Carpeta d'inici</i> (o a la carpeta <i>Application Data</i> al Windows).
#@gimp_ca : El connector el llegir&#224; cada vegada que s'arranqui, o quan premeu el bot&#243; <i>Actualitzar els filtres</i>.
#@gimp_ca : Aquest fitxer ha de ser un arxiu de command del <b>G'MIC</b>, i ha de contindre les definicions de filtre
#@gimp_ca : que han d'apar&#232;ixer a la llista de filtres.
#@gimp_ca : Podeu veure un exemple d'un arxiu d'aquesta mena a :"}
#@gimp_ca : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_ca : note = note{"
#@gimp_ca : Escriure un nou filtre amb el llenguatge <b>G'MIC</b> no &#233;s trivial del tot (per&#242; tampoc una cosa inabastable), per&#242;
#@gimp_ca : normalment es pot fer en unes quantes l&#237;nies.\n\n
#@gimp_ca : <span foreground="purple" underline="single">Example d'un fitxer <i>.gmic</i> v&#224;lid :</span>\n\n
#@gimp_ca : <tt>#@gimp My effect : my_effect, my_effect, Sigma = float(2,0,10)\n
#@gimp_ca : my_effect :\n  --blur $1 -n 0,255 -xor</tt>\n\n
#@gimp_ca : Per cert, us encoratgem a que compartiu els vostres filtres personalitzats al f&#242;rum espec&#237;fic de <b>G'MIC</b> :
#@gimp_ca : "}
#@gimp_ca : note = link("Enlla\303\247a al f\303\262rum G'MIC","http://sourceforge.net/projects/gmic/forums/forum/849382")

#@gimp_ca Filters update : _none_, _none_
#@gimp_ca : note = note{"
#@gimp_ca : El connector <b>G'MIC</b> &#233;s capa&#231; d'<b>actualitzar</b> la seva llista de definicions de filtres
#@gimp_ca : des d'Internet. Prement el bot&#243; <i>Actualitzar els filtres</i> al plaf&#243; de l'esquerra
#@gimp_ca : fa que <b>G'MIC</b> es connecti amb el servidor d'actualitzacions
#@gimp_ca : i que descarregui les darreres definicions de filtres disponibles.\n\n
#@gimp_ca : B&#224;sicament, aquest procediment crea un fitxer
#@gimp_ca : <span foreground="purple" style="italic">.gmic_def.xxxx</span> a la vostra <i>Carpeta d'inici</i>
#@gimp_ca : (o a la carpeta <i>Application Data</i> a Windows),
#@gimp_ca : on <i>xxxx</i> s&#243;n els quatre d&#237;gits de la versi&#243; del connector <b>G'MIC</b>.
#@gimp_ca : En cas que tingueu problemes, podeu actualitzar manualment els vostres filtres, baixant-vos el fitxer d'actualitzaci&#243; des de:"}
#@gimp_ca : note = link("http://gmic.sourceforge.net/gmic_def.xxxx")
#@gimp_ca : note = note{"
#@gimp_ca : Llavors, nom&#233;s cal que copieu i canvieu el nom d'aquest fitxer com a <span foreground="purple" style="italic">.gmic_def.xxxx</span>
#@gimp_ca : (no oblideu el primer punt, i substitu&#239;u <i>xxxx</i> per el n&#250;mero de versi&#243; del vostre <b>G'MIC</b>)
#@gimp_ca : i ja est&#224;!
#@gimp_ca : Per cert, si esborreu aquest fitxer, tornareu a establir les definicions de filtres originals.
#@gimp_ca : "}

#----------------------
# Untranslated filters
#----------------------

#@gimp Release notes : _none_, _none_
#@gimp : note = note{"
#@gimp : - <b>2009/01/13</b> : version <i>1.3</i> (Initial).\n
#@gimp : - <b>2010/09/03</b> : version <i>1.4</i>.\n
#@gimp : - <span foreground="purple"><b>2010/11/17</b> : version <i>1.4.5.2</i> (Current).</span>\n
#@gimp : "}

#@gimp Contributors : _none_, _none_
#@gimp : note = note{"
#@gimp : We would like to thank all these people who contributed to <b>G'MIC</b> in one way or another.
#@gimp : A big hug to : \n\n
#@gimp : <b> -</b> <i>Claude Bulin</i> <small>(packaging)</small>
#@gimp : <b> -</b> <i>J&#233;rome Ferrari</i> <small>(testing)</small>
#@gimp : <b> -</b> <i>Jalal Fadili</i> <small>(compiling)</small>
#@gimp : <b> -</b> <i>Angelo Lama</i> <small>(testing)</small>
#@gimp : <b> -</b> <i>PhotoComiX</i> <small>(testing &amp; Italian translation)</small>
#@gimp : <b> -</b> <i>Gilmoth</i> <small>(Italian translation)</small>
#@gimp : <b> -</b> <i>Stepanekos</i> <small>(German translation)</small>
#@gimp : <b> -</b> <i>Fran&#231;ois Collard</i> <small>(testing)</small>
#@gimp : <b> -</b> <i>Karsten Rodenacker</i> <small>(mac support)</small>
#@gimp : <b> -</b> <i>Yuri Shemanin</i> <small>(debugging)</small>
#@gimp : <b> -</b> <i>St&#233;phane de la Linuxerie</i> <small>(design)</small>
#@gimp : <b> -</b> <i>Dani Sard&#224;</i> <small>(Catalan translation)</small>
#@gimp : <b> -</b> <i>Mark</i> <small>(Dutch translation)</small>
#@gimp : <b> -</b> <i>Claes Holmerson</i> <small>(tutorials)</small>
#@gimp : <b> -</b> <i>The GIMP users at Flickr</i> <small>(testing and suggestions)</small>
#@gimp : <b> -</b>"}

#@gimp Friends Hall of Fame : _none_, gimp_friends
#@gimp : note = note{"\n<span foreground="purple" underline="single">Donators :</span>"}
#@gimp : note = note{" <b>-</b> We've received <b>1</b> donation from <b>G'MIC</b> mega-enthusiasts so far.
#@gimp :               You could be the 2nd donator :)"}
#@gimp : note = note{" <b>-</b> A big hug goes to these folks (recently received first) :"}
#@gimp : link = link(0,"[1] Lyle Kroll","http://www.artwanted.com/artist.cfm?artid=10918")
#@gimp : sep = separator()
#@gimp : note = note{"\n<span foreground="purple" underline="single">Postcard senders :</span>"}
#@gimp : note = note{" <b>-</b> We've received <b>9</b> postcards from <b>G'MIC</b> enthusiasts so far.
#@gimp :               You could be the 10th sender :)"}
#@gimp : note = note{" <b>-</b> A big hug goes to these folks (recently received first) :"}
#@gimp : link = link(0,"[1] Mahvin - Portland/USA","http://cimg.sourceforge.net/img/postcard27.jpg")
#@gimp : link = link(0,"[2] Vincent Roullier - Caen/France","http://cimg.sourceforge.net/img/postcard26.jpg")
#@gimp : link = link(0,"[3] M???? - Munich/Germany","http://cimg.sourceforge.net/img/postcard24.jpg")
#@gimp : link = link(0,"[4] F. Albior - Jaca/Spain","http://cimg.sourceforge.net/img/postcard23.jpg")
#@gimp : link = link(0,"[5] PhotoComIX - Frascati/Italy","http://cimg.sourceforge.net/img/postcard22.jpg")
#@gimp : link = link(0,"[6] Guy Poizat - Cabestany/France","http://cimg.sourceforge.net/img/postcard21.jpg")
#@gimp : link = link(0,"[7] Institut for Biomathematik und Biometrie - Neuherberg/Germany","http://cimg.sourceforge.net/img/postcard20.jpg")
#@gimp : link = link(0,"[8] Jaime - Barcelona/Spain","http://cimg.sourceforge.net/img/postcard14.jpg")
#@gimp : link = link(0,"[9] Jean-Michel Webbe - Guadeloupe/France","http://cimg.sourceforge.net/img/postcard15.jpg")

#@gimp : sep = separator()
#@gimp : note = note{"\nMay the force be with you !"}
gimp_friends :
  -if @# -p[0] {w/h} -else -p[0] 1 -endif
  -rm -_heart80x73 -resize3x -r 150%,150%,1,1,0,0,0.5,0.5
  --*[-1] 70 --*[-2] 110 --*[-3] 255 -*[-4] 255 -a c
  -blur_radial 4 -sharpen 300
  -i[-2] @{"-fitratio_wh "@{-1,w},@{-1,h},~0},1,3
  -rand[-2] 0,255 --sh[-2] 1,2 -/[-1] 2 -rm[-1]
  -blur_radial[-2] 10 -sharpen[-2] 600
  -r[-1] [-2],[-2],1,4,0,0,0.5,0.5 -compose_rgba
  135,67,1,1,0 -text[-1] "Greetings to\n  all G'MIC\n  friends !",2,-2,24,1,1
  --dilate[-1] 3 -*[-2] 255 -to_rgb[-2] -image[-3] [-2],{(@{-3,w}-@{-2,w})/2},{(@{-3,h}-@{-2,h})/2.2},0,0,1,[-1]
  -rm[-2,-1]

_heart80x73 :
  40,73,1,1,0 -ellipse 22,22,20,20,0,1,1 -polygon 3,7,37,42,72,42,27,1,1 --mirror x -a x


#@gimp Tutorials : _none_, _none_
#@gimp : note = note{"\nSome nice people have written tutorials about the use of the G'MIC framework.
#@gimp : They provide useful resources to see what G'MIC is able to do and how you can use it to achieve cool effects.
#@gimp : Feel free to visit the URL below. A big hug goes to them for their efforts !\n"}
#@gimp : sep = separator(), note = note("<b>Features overview</b>")
#@gimp : link = link{0,"1. Preview of some G'MIC filters (in french)","http://aljacom.com/~gmic/"}
#@gimp : sep = separator(), note = note("<b>G'MIC syntax</b>")
#@gimp : link = link{0,"1. Initiation to the G'MIC language","http://zonderr.wordpress.com/2010/09/13/gmic-command-first-steps/"}
#@gimp : link = link{0,"2. Images and formats","http://zonderr.wordpress.com/2010/10/06/gmic-image-and-format/"}
#@gimp : link = link{0,"3. The command line behind the plug-in","http://zonderr.wordpress.com/2010/09/18/gmic-from-the-gimp-plugin-to-the-command-line/"}
#@gimp : link = link{0,"4. Adding a custom filter to the plug-in","http://zonderr.wordpress.com/2010/11/13/howto-create-a-custom-filter-in-the-gmic-plug-in/"}
#@gimp : sep = separator(), note = note("<b>Workflow</b>")
#@gimp : link = link{0,"1. Developping RAW images","http://gmic.sourceforge.net/tutorial.shtml"}
#@gimp : sep = separator(), note = note("<b>Special effects</b>")
#@gimp : link = link{0,"1. How to make caricatures","http://www.mahvin.com/?p=1091"}
#@gimp : link = link{0,"2. Quick Tie-Dye Backgrounds","http://www.mahvin.com/?p=1243"}
#@gimp : link = link{0,"3. How to turn a photo into a realistic handmade sketch","http://www.flickr.com/groups/gmic/discuss/72157624446298923/"}
#@gimp : link = link{0,"4. Playing with the Fourier Transform","http://www.flickr.com/groups/gmic/discuss/72157624462331405"}
#@gimp : sep = separator(), note = note("<b>Video tutorials</b>")
#@gimp : link = link{0,"1. Turn a photo into a graffiti (in german)","http://vimeo.com/7023686"}
#@gimp : link = link{0,"2. Make an old movie from a photo","http://www.youtube.com/watch?v=Qvt5WQWfw9Y"}


#@gimp _<b>Arrays &amp; frames</b>
#----------------------------------


#@gimp Regular array : gimp_array, gimp_array_preview(1)
#@gimp : X-tiles = int(2,1,10)
#@gimp : Y-tiles = int(2,1,10)
#@gimp : X-offset = float(0,0,100)
#@gimp : Y-offset = float(0,0,100)
#@gimp : Mirror = choice("None","X-axis","Y-axis","XY-axes")
#@gimp : Size = _choice("Shrink", "Expand", "Repeat [Memory consuming !]")
gimp_array_preview :
  -gimp_array $1,$2,$3,$4,$5,0

gimp_array :
  -shift -$3%,-$4%,0,0,2
  -if {$5\&1} -mirror x -endif -if {$5>1} -mirror y -endif
  -array $1,$2,$6

#@gimp Faded array : gimp_array_fade, gimp_array_fade_preview(1)
#@gimp : X-tiles = int(2,1,10)
#@gimp : Y-tiles = int(2,1,10)
#@gimp : X-offset = float(0,0,100)
#@gimp : Y-offset = float(0,0,100)
#@gimp : Fade start = float(80,1,100)
#@gimp : Fade end = float(90,1,100)
#@gimp : Mirror = choice("None","X-axis","Y-axis","XY-axes")
#@gimp : Size = _choice("Shrink", "Expand", "Repeat [Memory consuming !]")
gimp_array_fade :
  -if {$7\&1} -mirror x -endif -if {$7>1} -mirror y -endif
  -array_fade $1,$2,$5,$6,$8
  -shift -$3%,-$4%,0,0,2

gimp_array_fade_preview :
  -gimp_array_fade $1,$2,$3,$4,$5,$6,$7,0

#@gimp Mirrored array : gimp_array_mirror, gimp_array_mirror_preview(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : X-offset = float(0,0,100)
#@gimp : Y-offset = float(0,0,100)
#@gimp : Array mode = choice(2,"X-axis","Y-axis","XY-axes")
#@gimp : Mirror = choice("None","X-axis","Y-axis","XY-axes")
#@gimp : Expand size = _bool(false)
gimp_array_mirror :
  -if {$5\&1} -mirror x -endif
  -if {$5>1} -mirror y -endif
  -array_mirror $1,$4,$6
  -shift -$2%,-$3%,0,0,2

gimp_array_mirror_preview :
  -gimp_array_mirror $1,$2,$3,$4,$5,0

#@gimp Random array : array_random, array_random(1)
#@gimp : Source X-tiles = int(5,1,20)
#@gimp : Source Y-tiles = int(5,1,20)
#@gimp : Destination X-tiles = int(7,1,20)
#@gimp : Destination Y-tiles = int(7,1,20)

#@gimp Random color array : gimp_array_color, gimp_array_color(1)
#@gimp : X-tiles = int(5,1,20)
#@gimp : Y-tiles = int(5,1,20)
#@gimp : Opacity = float(0.5,0,1)
gimp_array_color :
  -repeat @# -l[-1]
    $1,$2,1,3 -rand[-1] 0,255 -to_colormode[-1] @{-2,s} -r[-1] [-2] -*[-1] $3 -*[-2] {1-$3} -+[-2,-1]
  -endl -mv[-1] 0 -done

#@gimp Tiled rotation : gimp_rotate_tiles, gimp_rotate_tiles(1)
#@gimp : X-tiles = int(5,1,80)
#@gimp : Y-tiles = int(5,1,80)
#@gimp : Angle = float(15,0,360)
#@gimp : Opacity = float(1,0,1)
gimp_rotate_tiles :
  -to_rgba -rotate_tiles $3,$1,$2
  -if {$4<1} -repeat @# -s[-1] c -*[-1] $4 -a[-4--1] c -mv[-1] 0 -done -endif

#@gimp Tiled normalization : gimp_normalize_tiles, gimp_normalize_tiles(1)
#@gimp : X-tiles = int(25,1,80)
#@gimp : Y-tiles = int(25,1,80)
#@gimp : Minimal value = float(0,0,255)
#@gimp : Maximal value = float(255,0,255)
gimp_normalize_tiles :
  -repeat @# -l[-1] -split_tiles $1,$2 -n $3,$4 -append_tiles $1,$2 -endl -mv[-1] 0 -done

#@gimp Tiled random shift : gimp_shift_tiles, gimp_shift_tiles(1)
#@gimp : X-tiles = int(10,1,30)
#@gimp : Y-tiles = int(10,1,30)
#@gimp : Amplitude = float(10,0,100)
#@gimp : Opacity = float(1,0,1)
gimp_shift_tiles :
  -to_rgba -shift_tiles $1,$2,$3
  -if {$4<1} -repeat @# -s[-1] c -*[-1] $4 -a[-4--1] c -mv[-1] 0 -done -endif

#@gimp Tiled parameterization : gimp_parameterize_tiles, gimp_parameterize_tiles(1)
#@gimp : X-tiles = int(10,1,30)
#@gimp : Y-tiles = int(10,1,30)
#@gimp : Fitting function = choice("Linear","Quadratic")
gimp_parameterize_tiles :
  -if $3
    -quadratize_tiles $1,$2
  -else
    -linearize_tiles $1,$2
  -endif
  -c 0,255

#@gimp Image grid : gimp_imagegrid, gimp_imagegrid(0)
#@gimp : X-size = int(10,2,100)
#@gimp : Y-size = int(10,2,100)
gimp_imagegrid :
  -to_rgba -imagegrid $1,$2

#@gimp Taquin puzzle : taquin, taquin(1)
#@gimp : X-tiles = int(7,1,20)
#@gimp : Y-tiles = int(7,1,20)

#@gimp Random pattern : gimp_array_pattern, gimp_array_pattern_preview(1)
#@gimp : X-tiles = int(10,1,30)
#@gimp : Y-tiles = int(10,1,30)
#@gimp : Density = float(80,0,100)
#@gimp : Angle = float(180,0,180)
#@gimp : Zoom = float(30,0,100)
#@gimp : Opacity = float(1,0,1)
#@gimp : Image size = _choice("Shrink", "Expand", "Repeat [Memory consuming !]")
gimp_array_pattern :
  -to_rgba -array_pattern $1,$2,$3,$4,$5,$6,0

gimp_array_pattern_preview :
  -to_rgba -array_pattern $1,$2,$3,$4,$5,$6,$7

#@gimp Regular frame : gimp_frame, gimp_frame(1)
#@gimp : note = note("<b>Crop parameters :</b>")
#@gimp : X-start = int(0,0,100)
#@gimp : X-end = int(100,0,100)
#@gimp : Y-start = int(0,0,100)
#@gimp : Y-end = int(100,0,100)
#@gimp : sep = separator(), note = note("<b>Frame parameters :</b>")
#@gimp : Width = int(10,0,100)
#@gimp : Height = int(10,0,100)
#@gimp : Color = color(0,0,0,255)
#@gimp : Outline size = int(1,0,100)
#@gimp : Outline color = color(255,255,255,255)
gimp_frame :
 -to_rgba -repeat @#
   -crop[-1] $1%,$3%,$2%,$4%
   -frame[-1] $11,$11,${12-15}
   -frame[-1] $5%,$6%,${7-10}
 -mv[-1] 0 -done

#@gimp Pattern frame : gimp_frame_pattern, gimp_frame_pattern_preview(1)
#@gimp : Tiles = int(10,3,30)
#@gimp : Pattern = choice(1,"Top layer","Self image")
#@gimp : Iterations = int(1,1,10)
#@gimp : Constrain image size = _bool(1)
gimp_frame_pattern :
  -repeat $3 -frame_pattern $1,$2,$4 -done

gimp_frame_pattern_preview :
  -gimp_frame_pattern $1,$2,$3,1

#@gimp Fuzzy frame : gimp_frame_fuzzy, gimp_frame_fuzzy(0)
#@gimp : Width = int(10,0,99)
#@gimp : Height = int(10,0,99)
#@gimp : Fuzzyness = float(10,0,40)
#@gimp : Smoothness = float(1,0,5)
#@gimp : Color = color(255,255,255,255)
gimp_frame_fuzzy :
  -repeat @#
    ({w*$1/200},{h*$2/200}) -round[-1] 1
    -frame_fuzzy[-2] @-1,$3,$4,$5,$6,$7,$8 -rm[-1]
  -mv[-1] 0 -done

#@gimp Round frame : gimp_frame_round, gimp_frame_round(1)
#@gimp : Sharpness = float(6,0.1,40)
#@gimp : Size = float(20,0,100)
#@gimp : Smoothness = float(0.1,0,15)
#@gimp : Shade = float(0,0,1)
#@gimp : Color = color(255,255,255,255)
#@gimp : Blur frame = float(0,0,100)
#@gimp : Blur shade = float(0.1,0,1)
#@gimp : Blur amplitude = float(3,0,10)
gimp_frame_round :
  -frame_round ${1-8}
  -if $9 -frame_blur $1,{min(99,$1+$9)},$3,$10,$11% -endif

#@gimp Tunnel : gimp_tunnel,gimp_tunnel(1)
#@gimp : Depth = int(4,1,100)
#@gimp : Factor = float(80,1,99)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Opacity = float(0.2,0,1)
gimp_tunnel :
  -tunnel $1,$2%,$3,$4,$5


#@gimp _<b>Artistic</b>
#-----------------------


#@gimp Polaroid : gimp_polaroid, gimp_polaroid(1)
#@gimp : Frame size = int(10,1,400)
#@gimp : Bottom size = int(20,1,400)
#@gimp : X-shadow = float(0,-20,20)
#@gimp : Y-shadow = float(0,-20,20)
#@gimp : Smoothness = float(3,0,5)
#@gimp : Angle = float(20,0,360)
gimp_polaroid :
  -polaroid $1,$2 -drop_shadow $3%,$4%,$5% -rotate $6,0

#@gimp Old photograph : old_photo, old_photo(1)

#@gimp Reflection : gimp_reflect, gimp_reflect(1)
#@gimp : Height = float(50,0,100)
#@gimp : Attenuation = float(1,0.1,4)
#@gimp : Color = color(110,160,190,64)
#@gimp : Waves amplitude = float(0,0,100)
#@gimp : Waves smoothness = float(1.5,0,4)
#@gimp : X-angle = float(0,-10,10)
#@gimp : Y-angle = float(-3.30,-10,10)
#@gimp : Focale = float(7,0,10)
#@gimp : Zoom = float(1.5,1,5)
gimp_reflect :
  -repeat @#
    -to_rgba[-1] --lines[-1] {100-$1}%,100% -mirror[-1] y -water[-1] $7,$8
    -s[-1] c
    -f[-4] "(i*(255-$6) + $6*$3)/255"
    -f[-3] "(i*(255-$6) + $6*$4)/255"
    -f[-2] "(i*(255-$6) + $6*$5)/255" -a[-4--1] c
    -*[-1] '(h^$2-y^$2)/h^$2' -a[-2,-1] y
    100%,100%,100%,1,$11*$12*(x/w-0.5)
    100%,100%,100%,1,$11*$12*(y/h-0.5)
    100%,100%,100%,1,"$10*(x/w-0.5) + $9*(y/h-0.5) + $11"
    -/[-3] [-1] -+[-3] 0.5 -*[-3] @{-3,w}
    -/[-2,-1] -+[-1] 0.5 -*[-1] {h}
    -a[-2,-1] c -warp[-2] [-1],0,1,0 -rm[-1]
  -mv[-1] 0 -done
  -autocrop 0,0,0,0

#@gimp Random color ellipses : gimp_color_ellipses, gimp_color_ellipses(1)
#@gimp : Density = int(400,0,3000)
#@gimp : Radius = float(8,0,30)
#@gimp : Opacity = float(0.1,0.01,0.5)
gimp_color_ellipses :
  -to_rgb -color_ellipses $1,$2,$3

#@gimp Ellipsionism : gimp_ellipsionism, gimp_ellipsionism_preview(0)
#@gimp : Primary radius = float(20,1,100)
#@gimp : Secondary radius = float(10,1,100)
#@gimp : Smoothness = float(0.5,0,10)
#@gimp : Opacity = float(0.7,0,1)
#@gimp : Outline = float(8,1,3)
#@gimp : Density = float(0.5,0.1,2)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_ellipsionism :
  -ellipsionism ${1--1}

gimp_ellipsionism_preview :
  -gimp_split_preview "-gimp_ellipsionism ${1--2}",$-1

#@gimp Cartoon : cartoon, gimp_cartoon_preview(0)
#@gimp : Smoothness = float(2,0,10)
#@gimp : Sharpening = float(200,0,400)
#@gimp : Edge threshold = float(10,1,30)
#@gimp : Edge thickness = float(0.25,0,1)
#@gimp : Color strength = float(1.5,0,3)
#@gimp : Color quantization = int(32,2,256)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_cartoon_preview :
  -gimp_split_preview "-cartoon ${1--2}",$-1

#@gimp Pen drawing : gimp_pen_drawing, gimp_pen_drawing_preview(0)
#@gimp : Amplitude = float(10,0,30)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_pen_drawing :
  -to_rgb -drawing $1

gimp_pen_drawing_preview :
  -gimp_split_preview "-gimp_pen_drawing ${1--2}",$-1

#@gimp Whirl drawing : draw_whirl, gimp_draw_whirl_preview(0)
#@gimp : Amplitude = float(20,0,100)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_draw_whirl_preview :
  -gimp_split_preview "-draw_whirl ${1--2}",$-1

#@gimp Painting : gimp_painting, gimp_painting(0)
#@gimp : Abstraction = int(1,1,10)
#@gimp : Smoothness = float(1.5,0,5)
#@gimp : Color = float(2,0,4)
gimp_painting :
  -repeat @# -l[~>]
    -to_colormode {max(3,s)} -split_opacity -rv
    -repeat $1 -gimp_normalize_local[-1] 10,6,5,20,1,3 -done
    -gimp_anisotropic_smoothing[-1] {100*$2},0.2,1,$2,{2*$2},0.8,90,2,0,1,1,2,1
    -gimp_mix_lab[-1] 1,0,0,$3,0,0.5,$3,0,0.5,0,2,0
    -rv -a c
  -endl -done

#@gimp Cubism : cubism, cubism(1)
#@gimp : Iterations = int(300,1,2000)
#@gimp : Bloc size = float(10,0,40)
#@gimp : Angle = float(90,0,360)
#@gimp : Opacity = float(0.7,0.01,1)
#@gimp : Smoothness = float(0,0,5)

#@gimp Kaleidoscope : gimp_kaleidoscope, gimp_kaleidoscope(1)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : X-offset = float(0,0,100)
#@gimp : Y-offset = float(0,0,100)
#@gimp : Radius cut = float(100,0,100)
#@gimp : Angle cut = float(10,0,100)
#@gimp : Borders = choice(2,"Black","Nearest","Repeat")
gimp_kaleidoscope :
  -shift $3%,$4%,0,0,2 -kaleidoscope $1,$2,$5,$6,$7

#@gimp Rotoidoscope : gimp_rotoidoscope, gimp_rotoidoscope(1)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Angular tiles = int(10,1,72)
#@gimp : Smoothness = float(0.5,0,5)
#@gimp : Borders = choice(2,"Black","Nearest","Repeat")
gimp_rotoidoscope :
  -rotoidoscope {$1*100}%,{$2*100}%,$3,$4%,$5

#@gimp B&amp;W stencil : gimp_stencilbw, gimp_stencilbw_preview(0)
#@gimp : Threshold = float(10,0,30)
#@gimp : Smoothness = float(10,0,30)
#@gimp : Hue = float(0,0,360)
#@gimp : Saturation = float(0,0,1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_stencilbw :
  -stencilbw $1,$2
  -if {$3||$4} -/ 255 -repeat @# -i[-2] 100%,100%,1,1,$4 -i[-3] 100%,100%,1,1,$3 -a[-3--1] c -hsv2rgb[-1] -mv[-1] 0 -done -endif

gimp_stencilbw_preview :
  -gimp_split_preview "-gimp_stencilbw ${1--2}",$-1

#@gimp B&amp;W pencil : gimp_pencilbw, gimp_pencilbw_preview(0)
#@gimp : Size = float(0.3,0,5)
#@gimp : Amplitude = float(60,0,200)
#@gimp : Hue = float(0,0,360)
#@gimp : Saturation = float(0,0,1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_pencilbw :
  -pencilbw $1,$2
  -if {$3||$4} -/ 255 -repeat @# -i[-2] 100%,100%,1,1,$4 -i[-3] 100%,100%,1,1,$3 -a[-3--1] c -hsv2rgb[-1] -mv[-1] 0 -done -endif

gimp_pencilbw_preview :
  -gimp_split_preview "-gimp_pencilbw ${1--2}",$-1

#@gimp B&amp;W hard sketch : gimp_hardsketchbw, gimp_hardsketchbw_preview(0)
#@gimp : Amplitude = float(1000,0,4000)
#@gimp : Sampling = float(3,1,10)
#@gimp : Smoothness = float(1,0,10)
#@gimp : Opacity = float(0.1,0,1)
#@gimp : Edge = float(20,0,100)
#@gimp : Negative = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_hardsketchbw :
  -blur $3 -hardsketchbw $1,$2,$4,$5
  -if $6 -negative -endif

gimp_hardsketchbw_preview :
  -gimp_split_preview "-gimp_hardsketchbw ${1--2}",$-1

#@gimp B&amp;W sketch : gimp_sketchbw, gimp_sketchbw_preview(0)
#@gimp : Number of orientations = int(2,1,16)
#@gimp : Starting angle = float(45,0,180)
#@gimp : Angle range = float(180,0,180)
#@gimp : Stroke length = float(30,0,1000)
#@gimp : Contour threshold = float(1,0,3)
#@gimp : Opacity = float(0.03,0,0.3)
#@gimp : Background intensity = float(0,0,2)
#@gimp : Density = float(0.6,0,5)
#@gimp : Sharpness = float(0.1,0,1.5)
#@gimp : Anisotropy = float(0.6,0,1)
#@gimp : Smoothness = float(0.25,0,10)
#@gimp : Coherence = float(1,0,10)
#@gimp : Boost stroke = bool(0)
#@gimp : Curved stroke = bool(1)
#@gimp : Color model = choice("Black on white","White on black","Black on transparent white","White on transparent black")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_sketchbw :
  -sketchbw ${1-14}
  -if {$15\&1} -negative -endif
  -if {$15==2} -r 100%,100%,1,4 -repeat @# --sh[~>] 3,3 -*[-1] -2 -+[-1] {2*255} -c[-1] 0,255 -rm[-1] -done
  -elif {$15==3} -r 100%,100%,1,4 -repeat @# --sh[~>] 3,3 -*[-1] 2 -c[-1] 0,255 -rm[-1] -done
  -endif

gimp_sketchbw_preview :
  -gimp_split_preview "-gimp_sketchbw ${1--2}",$-1

#@gimp Warhol : warhol, warhol(1)
#@gimp : X-tiles = int(3,1,10)
#@gimp : Y-tiles = int(3,1,10)
#@gimp : Smoothness = float(2,0,10)
#@gimp : Color = float(40,0,60)

#@gimp Soft glow : gimp_glow, gimp_glow_preview(0)
#@gimp : Amplitude = float(1,0,20)
#@gimp : note = note()
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_glow :
  -apply_channels "-glow $1",$2,0

gimp_glow_preview :
  -gimp_split_preview "-gimp_glow ${1--2}",$-1

#@gimp Tetris effect : gimp_tetris, gimp_tetris(0)
#@gimp : Scale = int(10,1,20)
gimp_tetris :
  -to_rgb -tetris $1


#@gimp _<b>Colors</b>
#---------------------


#@gimp RGB mixer : gimp_mix_rgb, gimp_mix_rgb_preview(1)
#@gimp : Red contrast = float(1,0,4)
#@gimp : Red brightness = float(0,-255,255)
#@gimp : Red smoothness = float(0,0,10)
#@gimp : Green contrast = float(1,0,4)
#@gimp : Green brightness = float(0,-255,255)
#@gimp : Green smoothness = float(0,0,10)
#@gimp : Blue contrast = float(1,0,4)
#@gimp : Blue brightness = float(0,-255,255)
#@gimp : Blue smoothness = float(0,0,10)
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_start_mix :
  -if {$1==1} --tones[-1] 3 -+[-2,-1] -blur[-2,-1] $2% -r[-2,-1] [-3] -*[-1] [-3] -mv[-3] @#
  -elif {$1==2} --tones[-1] 3 -+[-3,-1] -blur[-2,-1] $2% -r[-2,-1] [-3] -*[-2] [-3] -mv[-3] @#
  -elif {$1==3} --tones[-1] 3 -+[-3,-2] -blur[-2,-1] $2% -r[-2,-1] [-3] -*[-2] [-3] -mv[-3] @#
  -endif
gimp_end_mix :
  -if {$1==1} -*[-3,-1] -+[-2,-1]
  -elif {$1==2} -*[-2,-1] -+[-2,-1]
  -elif {$1==3} -*[-2,-1] -+[-2,-1]
  -endif

gimp_mix_rgb :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $10,$11
    --[-1] 128 -s[-1] c
    -*[-3] $1 -+[-3] $2 -blur[-3] $3%
    -*[-2] $4 -+[-2] $5 -blur[-2] $6%
    -*[-1] $7 -+[-1] $8 -blur[-1] $9%
    -a[-3--1] c -+[-1] 128 -c[-1] 0,255
    -gimp_end_mix $10
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_mix_rgb_preview :
  -gimp_split_preview "-gimp_mix_rgb ${1--2}",$-1

#@gimp YCbCr mixer : gimp_mix_ycbcr, gimp_mix_ycbcr_preview(1)
#@gimp : Luminance contrast = float(1,0,4)
#@gimp : Luminance brightness = float(0,-255,255)
#@gimp : Luminance smoothness = float(0,0,10)
#@gimp : Blue chroma contrast = float(1,0,4)
#@gimp : Blue chroma brightness = float(0,-255,255)
#@gimp : Blue chroma smoothness = float(0,0,10)
#@gimp : Red chroma contrast = float(1,0,4)
#@gimp : Red chroma brightness = float(0,-255,255)
#@gimp : Red chroma smoothness = float(0,0,10)
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_mix_ycbcr :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $10,$11
    -rgb2ycbcr[-1] --[-1] 128 -s[-1] c
    -*[-3] $1 -+[-3] $2 -blur[-3] $3%
    -*[-2] $4 -+[-2] $5 -blur[-2] $6%
    -*[-1] $7 -+[-1] $8 -blur[-1] $9%
    -a[-3--1] c -+[-1] 128 -c[-1] 0,255 -ycbcr2rgb[-1]
    -gimp_end_mix $10
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_mix_ycbcr_preview :
  -gimp_split_preview "-gimp_mix_ycbcr ${1--2}",$-1

#@gimp HSV mixer : gimp_mix_hsv, gimp_mix_hsv_preview(1)
#@gimp : Hue contrast = float(1,0,4)
#@gimp : Hue brightness = float(0,-180,180)
#@gimp : Hue smoothness = float(0,0,10)
#@gimp : Saturation contrast = float(1,0,4)
#@gimp : Saturation brightness = float(0,-1,1)
#@gimp : Saturation smoothness = float(0,0,10)
#@gimp : Value contrast = float(1,0,4)
#@gimp : Value brightness = float(0,-1,1)
#@gimp : Value smoothness = float(0,0,10)
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_mix_hsv :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $10,$11
    -rgb2hsv[-1] -s[-1] c --[-2,-1] 0.5
    -*[-3] $1 -+[-3] $2 -blur[-3] $3%
    -*[-2] $4 -+[-2] $5 -blur[-2] $6%
    -*[-1] $7 -+[-1] $8 -blur[-1] $9%
    -mod[-3] 360 -+[-2,-1] 0.5 -c[-2,-1] 0,1 -a[-3--1] c -hsv2rgb[-1]
    -gimp_end_mix $10
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_mix_hsv_preview :
  -gimp_split_preview "-gimp_mix_hsv ${1--2}",$-1

#@gimp Lab mixer : gimp_mix_lab, gimp_mix_lab_preview(1)
#@gimp : Lightness contrast = float(1,0.5,1.5)
#@gimp : Lightness brightness = float(0,-50,50)
#@gimp : Lightness smoothness = float(0,0,10)
#@gimp : A-color contrast = float(1,0,4)
#@gimp : A-color brightness = float(0,-20,20)
#@gimp : A-color smoothness = float(0,0,10)
#@gimp : B-color contrast = float(1,0,4)
#@gimp : B-color brightness = float(0,-20,20)
#@gimp : B-color smoothness = float(0,0,10)
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_mix_lab :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $10,$11
    -rgb2lab[-1] -s[-1] c
    -*[-3] $1 -+[-3] $2 -blur[-3] $3%
    -*[-2] $4 -+[-2] $5 -blur[-2] $6%
    -*[-1] $7 -+[-1] $8 -blur[-1] $9%
    -a[-3--1] c -lab2rgb[-1]
    -gimp_end_mix $10
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_mix_lab_preview :
  -gimp_split_preview "-gimp_mix_lab ${1--2}",$-1

#@gimp CMYK mixer : gimp_mix_cmyk, gimp_mix_cmyk_preview(1)
#@gimp : Cyan contrast = float(1,0,4)
#@gimp : Cyan brightness = float(0,-255,255)
#@gimp : Cyan smoothness = float(0,0,10)
#@gimp : Magenta contrast = float(1,0,4)
#@gimp : Magenta brightness = float(0,-255,255)
#@gimp : Magenta smoothness = float(0,0,10)
#@gimp : Yellow contrast = float(1,0,4)
#@gimp : Yellow brightness = float(0,-255,255)
#@gimp : Yellow smoothness = float(0,0,10)
#@gimp : Key contrast = float(1,0,4)
#@gimp : Key brightness = float(0,-255,255)
#@gimp : Key smoothness = float(0,0,10)
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_mix_cmyk :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $13,$14
    -rgb2cmyk[-1] -s[-1] c
    -*[-4] $1 -+[-4] $2 -blur[-4] $3%
    -*[-3] $4 -+[-3] $5 -blur[-3] $6%
    -*[-2] $7 -+[-2] $8 -blur[-2] $9%
    -*[-1] $10 -+[-1] $11 -blur[-1] $12%
    -a[-4--1] c -cmyk2rgb[-1]
    -gimp_end_mix $13
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_mix_cmyk_preview :
  -gimp_split_preview "-gimp_mix_cmyk ${1--2}",$-1

#@gimp Channel processing : gimp_channel_processing, gimp_channel_processing_preview(1)
#@gimp : Gamma = float(1,0.01,5)
#@gimp : Contrast = float(1,0,4)
#@gimp : Brightness = float(0,-255,255)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Value action = choice("None","Cut","Cut & Normalize","Normalize","Threshold")
#@gimp : Low value = float(0,0,100)
#@gimp : High value = float(100,0,100)
#@gimp : Quantization = int(256,1,256)
#@gimp : Equalization = bool()
#@gimp : Negation = bool()
#@gimp : note = note()
#@gimp : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gimp : Tones smoothness = float(2,0,10)
#@gimp : note = note()
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
_gimp_channel_processing :
  -apply_gamma[-1] $1
  -if {$2!=1} --[-1] 128 -*[-1] $2 -+[-1] 128 -endif
  -+[-1] $3
  -blur[-1] $4% -c[-1] 0,255
  -if {$5==1} -c[-1] $6%,$7%
  -elif {$5==2} -c[-1] $6%,$7% -n[-1] 0,255
  -elif {$5==3} -n[-1] $6%,$7%
  -elif {$5==4} -t2[-1] $6%,$7% -*[-1] 255
  -endif
  -if {$8!=256} -quantize[-1] $8 -endif
  -if $9 -equalize[-1] 256 -endif
  -if $10 -negative[-1] -endif

gimp_channel_processing :
  -repeat @# -l[-1] -split_opacity -rv -to_rgb[-1]
    -gimp_start_mix $11,$12
    -apply_channels[-1] "-_gimp_channel_processing $1,$2,$3,$4,$5,$6,$7,$8,$9,$10",$13,0
    -gimp_end_mix $11
  -if {@#!=3} -rv -a c -endif -endl -mv[-1] 0 -done

gimp_channel_processing_preview :
  -gimp_split_preview "-gimp_channel_processing ${1--2}",$-1

#@gimp Curves : gimp_apply_curve, gimp_apply_curve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_apply_curve :
  -apply_channels "-_gimp_apply_curve ${1-13}",$14,$15

_gimp_apply_curve :
  -apply_curve $13,0,$1,\
                   @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                   @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                   @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                   @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                   @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                   255,$12

gimp_apply_curve_preview :
  -function1d $13,0,$1,\
                  @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                  @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                  @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                  @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                  @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                  255,$12
  -mv[-1] 0
  -repeat {@#-1}
    --gimp_split_preview[-1] "-gimp_apply_curve ${1--2}",$-1
    -axes[-1] 0,255,255,0,1,255 -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,255
    -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
    -if $-2
      [-1],[-1],1,1,-{$-2*255/100} -to_gray[-3] -histogram[-3] 256,0,255 -graph[-1] [-3],3,0,0,0,1,0
      -rm[-3] -+[-1] {$-2*255/100} -+[-2,-1] -c[-1] 0,255
     -else -rm[-2] -endif
     -graph[-1] [0],1,0,255,0,1,255
     -_gimp_apply_curve_preview 0,$1,0 -_gimp_apply_curve_preview $2,$3,1
     -_gimp_apply_curve_preview $4,$5,2 -_gimp_apply_curve_preview $6,$7,3
     -_gimp_apply_curve_preview $8,$9,4 -_gimp_apply_curve_preview $10,$11,5
     -_gimp_apply_curve_preview 255,$12,6
  -mv[-1] 1 -done -rm[0]

_gimp_apply_curve_preview :
  -if {$1>=0}
    x={$1*100/255}% y={100-$2*100/255}%
    -ellipse[-1] $x,$y,3,3,0,1,0xFFFFFFFF,0,0,0 -ellipse[-1] $x,$y,2,2,0,1,0,255,0
    -text[-1] $3,$x,{$y*h-20},13,1,255
  -endif


#@gimp RGB Curves
#@gimp Red : gimp_apply_RGBcurve, gimp_apply_Rcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")

#@gimp Green : gimp_apply_RGBcurve, gimp_apply_Gcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")

#@gimp Blue : gimp_apply_RGBcurve, gimp_apply_Bcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_apply_RGBcurve : -skip $1
  -gimp_apply_RGBcurve_configfile
  -repeat {@#-1} -l[~>,-1]
    -to_colormode[0] {max(3,s)}
    --sh[0] 0,0 -_gimp_apply_RGBcurve[-1] @{-2,0-12} -rm[-1]
    --sh[0] 1,1 -_gimp_apply_RGBcurve[-1] @{-2,13-25} -rm[-1]
    --sh[0] 2,2 -_gimp_apply_RGBcurve[-1] @{-2,26-38} -rm[-1]
  -endl -done
  -rm[-1]

_gimp_apply_RGBcurve :
  -apply_curve $13,0,$1,\
                   @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                   @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                   @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                   @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                   @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                   255,$12
  -c 0,255

gimp_apply_Rcurve_preview :
  -gimp_apply_RGBcurve_configfile
  --sh[-1] 0,0,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_RGBcurve_preview[0--2] @-1,0,${-2,-1} -rm[-1]

gimp_apply_Gcurve_preview :
  -gimp_apply_RGBcurve_configfile
  --sh[-1] 1,1,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_RGBcurve_preview[0--2] @-1,1,${-2,-1} -rm[-1]

gimp_apply_Bcurve_preview :
  -gimp_apply_RGBcurve_configfile
  --sh[-1] 2,2,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_RGBcurve_preview[0--2] @-1,2,${-2,-1} -rm[-1]

gimp_apply_RGBcurve_configfile :
  filename=@{-path_tmp}/.gmic_RGBcurve.dlm
  -if $filename $filename -else (0,-1,128,-1,128,-1,128,-1,128,-1,128,255,1) -r[-1] 100%,3 -endif

gimp_apply_RGBcurve_preview :
  (${1--3}) -r[-1] 13,3,1,1,-1 -o[-1] @{-path_tmp}/.gmic_RGBcurve.dlm -rm[-1]
  -function1d $13,0,$1,\
                  @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                  @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                  @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                  @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                  @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                  255,$12
  -function1d $26,0,$14,\
                  @{"-if {$15>=0} -u $15,$16, -else -u \"\" -endif"}\
                  @{"-if {$17>=0} -u $17,$18, -else -u \"\" -endif"}\
                  @{"-if {$19>=0} -u $19,$20, -else -u \"\" -endif"}\
                  @{"-if {$21>=0} -u $21,$22, -else -u \"\" -endif"}\
                  @{"-if {$23>=0} -u $23,$24, -else -u \"\" -endif"}\
                  255,$25
  -function1d $39,0,$27,\
                  @{"-if {$28>=0} -u $28,$29, -else -u \"\" -endif"}\
                  @{"-if {$30>=0} -u $30,$31, -else -u \"\" -endif"}\
                  @{"-if {$32>=0} -u $32,$33, -else -u \"\" -endif"}\
                  @{"-if {$34>=0} -u $34,$35, -else -u \"\" -endif"}\
                  @{"-if {$36>=0} -u $36,$37, -else -u \"\" -endif"}\
                  255,$38
  -a[-3--1] y -mv[-1] 0
  -repeat {@#-1}
    [-1]
    --gimp_split_preview[-1] "-gimp_apply_RGBcurve 0",$-1
    -axes[-1] 0,255,255,0,1,255 -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,255
    -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     -if $-2
        [-1],[-1],1,1,-{$-2*255/100} -to_gray[-3] -histogram[-3] 256,0,255 -graph[-1] [-3],3,0,0,0,1,0
        -rm[-3] -+[-1] {$-2*255/100} -+[-2,-1] -c[-1] 0,255
     -else -rm[-2] -endif
     -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     --sh[0] 0,0,0,0
     -graph[-2] [-1],1,0,255,0,1,255,128,128 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,200,0,0 -rm[-1]
     --sh[0] 1,1,0,0
     -graph[-2] [-1],1,0,255,0,1,128,255,128 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,0,200,0 -rm[-1]
     --sh[0] 2,2,0,0
     -graph[-2] [-1],1,0,255,0,1,128,128,255 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,0,0,200 -rm[-1]
     -if {$40==0}
       -_gimp_apply_curve_preview 0,$1,0 -_gimp_apply_curve_preview $2,$3,1
       -_gimp_apply_curve_preview $4,$5,2 -_gimp_apply_curve_preview $6,$7,3
       -_gimp_apply_curve_preview $8,$9,4 -_gimp_apply_curve_preview $10,$11,5
       -_gimp_apply_curve_preview 255,$12,6
     -elif {$40==1}
       -_gimp_apply_curve_preview 0,$14,0 -_gimp_apply_curve_preview $15,$16,1
       -_gimp_apply_curve_preview $17,$18,2 -_gimp_apply_curve_preview $19,$20,3
       -_gimp_apply_curve_preview $21,$22,4 -_gimp_apply_curve_preview $23,$24,5
       -_gimp_apply_curve_preview 255,$25,6
     -else
       -_gimp_apply_curve_preview 0,$27,0 -_gimp_apply_curve_preview $28,$29,1
       -_gimp_apply_curve_preview $30,$31,2 -_gimp_apply_curve_preview $32,$33,3
       -_gimp_apply_curve_preview $34,$35,4 -_gimp_apply_curve_preview $36,$37,5
       -_gimp_apply_curve_preview 255,$38,6
     -endif
  -mv[-1] 1 -done -rm[0]

#@gimp _YCbCr Curves
#@gimp Luminance : gimp_apply_YCbCrcurve, gimp_apply_Ycurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")

#@gimp Blue chrominance : gimp_apply_YCbCrcurve, gimp_apply_Cbcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")

#@gimp Red Chrominance : gimp_apply_YCbCrcurve, gimp_apply_Crcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_apply_YCbCrcurve : -skip $1
  -gimp_apply_YCbCrcurve_configfile
  -repeat {@#-1} -l[~>,-1]
    -to_colormode[0] {max(3,s)} --sh[0] 0,2 -rgb2ycbcr[-1] -rm[-1]
    --sh[0] 0,0 -_gimp_apply_YCbCrcurve[-1] @{-2,0-12} -rm[-1]
    --sh[0] 1,1 -_gimp_apply_YCbCrcurve[-1] @{-2,13-25} -rm[-1]
    --sh[0] 2,2 -_gimp_apply_YCbCrcurve[-1] @{-2,26-38} -rm[-1]
    --sh[0] 0,2 -ycbcr2rgb[-1] -rm[-1]
  -endl -done
  -rm[-1]

_gimp_apply_YCbCrcurve :
  -apply_curve $13,0,$1,\
                   @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                   @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                   @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                   @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                   @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                   255,$12
  -c 0,255

gimp_apply_Ycurve_preview :
  -gimp_apply_YCbCrcurve_configfile
  --sh[-1] 0,0,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_YCbCrcurve_preview[0--2] @-1,0,${-2,-1} -rm[-1]

gimp_apply_Cbcurve_preview :
  -gimp_apply_YCbCrcurve_configfile
  --sh[-1] 1,1,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_YCbCrcurve_preview[0--2] @-1,1,${-2,-1} -rm[-1]

gimp_apply_Crcurve_preview :
  -gimp_apply_YCbCrcurve_configfile
  --sh[-1] 2,2,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_YCbCrcurve_preview[0--2] @-1,2,${-2,-1} -rm[-1]

gimp_apply_YCbCrcurve_configfile :
  filename=@{-path_tmp}/.gmic_YCbCrcurve.dlm
  -if $filename $filename -else (0,-1,128,-1,128,-1,128,-1,128,-1,128,255,1) -r[-1] 100%,3 -endif

gimp_apply_YCbCrcurve_preview :
  (${1--3}) -r[-1] 13,3,1,1,-1 -o[-1] @{-path_tmp}/.gmic_YCbCrcurve.dlm -rm[-1]
  -function1d $13,0,$1,\
                  @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                  @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                  @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                  @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                  @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                  255,$12
  -function1d $26,0,$14,\
                  @{"-if {$15>=0} -u $15,$16, -else -u \"\" -endif"}\
                  @{"-if {$17>=0} -u $17,$18, -else -u \"\" -endif"}\
                  @{"-if {$19>=0} -u $19,$20, -else -u \"\" -endif"}\
                  @{"-if {$21>=0} -u $21,$22, -else -u \"\" -endif"}\
                  @{"-if {$23>=0} -u $23,$24, -else -u \"\" -endif"}\
                  255,$25
  -function1d $39,0,$27,\
                  @{"-if {$28>=0} -u $28,$29, -else -u \"\" -endif"}\
                  @{"-if {$30>=0} -u $30,$31, -else -u \"\" -endif"}\
                  @{"-if {$32>=0} -u $32,$33, -else -u \"\" -endif"}\
                  @{"-if {$34>=0} -u $34,$35, -else -u \"\" -endif"}\
                  @{"-if {$36>=0} -u $36,$37, -else -u \"\" -endif"}\
                  255,$38
  -a[-3--1] y -mv[-1] 0
  -repeat {@#-1}
    [-1]
    --gimp_split_preview[-1] "-gimp_apply_YCbCrcurve 0",$-1
    -axes[-1] 0,255,255,0,1,255 -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,255
    -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     -if $-2
        [-1],[-1],1,1,-{$-2*255/100} -to_gray[-3] -histogram[-3] 256,0,255 -graph[-1] [-3],3,0,0,0,1,0
        -rm[-3] -+[-1] {$-2*255/100} -+[-2,-1] -c[-1] 0,255
     -else -rm[-2] -endif
     -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     --sh[0] 0,0,0,0
     -graph[-2] [-1],1,0,255,0,1,255,255,255 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,200,200,200 -rm[-1]
     --sh[0] 1,1,0,0
     -graph[-2] [-1],1,0,255,0,1,128,128,255 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,0,0,200 -rm[-1]
     --sh[0] 2,2,0,0
     -graph[-2] [-1],1,0,255,0,1,255,128,128 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,200,0,0 -rm[-1]
     -if {$40==0}
       -_gimp_apply_curve_preview 0,$1,0 -_gimp_apply_curve_preview $2,$3,1
       -_gimp_apply_curve_preview $4,$5,2 -_gimp_apply_curve_preview $6,$7,3
       -_gimp_apply_curve_preview $8,$9,4 -_gimp_apply_curve_preview $10,$11,5
       -_gimp_apply_curve_preview 255,$12,6
     -elif {$40==1}
       -_gimp_apply_curve_preview 0,$14,0 -_gimp_apply_curve_preview $15,$16,1
       -_gimp_apply_curve_preview $17,$18,2 -_gimp_apply_curve_preview $19,$20,3
       -_gimp_apply_curve_preview $21,$22,4 -_gimp_apply_curve_preview $23,$24,5
       -_gimp_apply_curve_preview 255,$25,6
     -else
       -_gimp_apply_curve_preview 0,$27,0 -_gimp_apply_curve_preview $28,$29,1
       -_gimp_apply_curve_preview $30,$31,2 -_gimp_apply_curve_preview $32,$33,3
       -_gimp_apply_curve_preview $34,$35,4 -_gimp_apply_curve_preview $36,$37,5
       -_gimp_apply_curve_preview 255,$38,6
     -endif
  -mv[-1] 1 -done -rm[0]


#@gimp _Lab Curves
#@gimp Lightness : gimp_apply_Labcurve, gimp_apply_Lcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")

#@gimp A-color : gimp_apply_Labcurve, gimp_apply_acurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")

#@gimp B-color : gimp_apply_Labcurve, gimp_apply_bcurve_preview
#@gimp : Starting Y = int(0,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(1) = int(-1,-1,255)
#@gimp : Y-coord(1) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(2) = int(-1,-1,255)
#@gimp : Y-coord(2) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(3) = int(-1,-1,255)
#@gimp : Y-coord(3) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(4) = int(-1,-1,255)
#@gimp : Y-coord(4) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : X-coord(5) = int(-1,-1,255)
#@gimp : Y-coord(5) = int(128,0,255)
#@gimp : sep = separator()
#@gimp : Ending Y = int(255,0,255)
#@gimp : sep = separator()
#@gimp : Curve smoothness = float(1,0,1)
#@gimp : Display histogram = float(0,0,100)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_apply_Labcurve : -skip $1
  -gimp_apply_Labcurve_configfile
  -repeat {@#-1} -l[~>,-1]
    -to_colormode[0] {max(3,s)} --sh[0] 0,2 -rgb2lab[-1] -rm[-1]
    --sh[0] 0,0 -*[-1] 2.55 -_gimp_apply_Labcurve[-1] @{-2,0-12} -/[-1] 2.55 -rm[-1]
    --sh[0] 1,1 -+[-1] 86 -*[-1] 1.38587 -_gimp_apply_Labcurve[-1] @{-2,13-25} -/[-1] 1.38587 --[-1] 86 -rm[-1]
    --sh[0] 2,2 -+[-1] 108 -*[-1] 1.25616 -_gimp_apply_Labcurve[-1] @{-2,26-38} -/[-1] 1.25616 --[-1] 108 -rm[-1]
    --sh[0] 0,2 -lab2rgb[-1] -rm[-1]
  -endl -done
  -rm[-1]

_gimp_apply_Labcurve :
  -apply_curve $13,0,$1,\
                   @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                   @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                   @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                   @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                   @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                   255,$12
  -c 0,255

gimp_apply_Lcurve_preview :
  -gimp_apply_Labcurve_configfile
  --sh[-1] 0,0,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_Labcurve_preview[0--2] @-1,0,${-2,-1} -rm[-1]

gimp_apply_acurve_preview :
  -gimp_apply_Labcurve_configfile
  --sh[-1] 1,1,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_Labcurve_preview[0--2] @-1,1,${-2,-1} -rm[-1]

gimp_apply_bcurve_preview :
  -gimp_apply_Labcurve_configfile
  --sh[-1] 2,2,0,0 -f[-1] ${1--3} -rm[-1]
  -gimp_apply_Labcurve_preview[0--2] @-1,2,${-2,-1} -rm[-1]

gimp_apply_Labcurve_configfile :
  filename=@{-path_tmp}/.gmic_Labcurve.dlm
  -if $filename $filename -else (0,-1,128,-1,128,-1,128,-1,128,-1,128,255,1) -r[-1] 100%,3 -endif

gimp_apply_Labcurve_preview :
  (${1--3}) -r[-1] 13,3,1,1,-1 -o[-1] @{-path_tmp}/.gmic_Labcurve.dlm -rm[-1]
  -function1d $13,0,$1,\
                  @{"-if {$2>=0} -u $2,$3, -else -u \"\" -endif"}\
                  @{"-if {$4>=0} -u $4,$5, -else -u \"\" -endif"}\
                  @{"-if {$6>=0} -u $6,$7, -else -u \"\" -endif"}\
                  @{"-if {$8>=0} -u $8,$9, -else -u \"\" -endif"}\
                  @{"-if {$10>=0} -u $10,$11, -else -u \"\" -endif"}\
                  255,$12
  -function1d $26,0,$14,\
                  @{"-if {$15>=0} -u $15,$16, -else -u \"\" -endif"}\
                  @{"-if {$17>=0} -u $17,$18, -else -u \"\" -endif"}\
                  @{"-if {$19>=0} -u $19,$20, -else -u \"\" -endif"}\
                  @{"-if {$21>=0} -u $21,$22, -else -u \"\" -endif"}\
                  @{"-if {$23>=0} -u $23,$24, -else -u \"\" -endif"}\
                  255,$25
  -function1d $39,0,$27,\
                  @{"-if {$28>=0} -u $28,$29, -else -u \"\" -endif"}\
                  @{"-if {$30>=0} -u $30,$31, -else -u \"\" -endif"}\
                  @{"-if {$32>=0} -u $32,$33, -else -u \"\" -endif"}\
                  @{"-if {$34>=0} -u $34,$35, -else -u \"\" -endif"}\
                  @{"-if {$36>=0} -u $36,$37, -else -u \"\" -endif"}\
                  255,$38
  -a[-3--1] y -mv[-1] 0
  -repeat {@#-1}
    [-1]
    --gimp_split_preview[-1] "-gimp_apply_Labcurve 0",$-1
    -axes[-1] 0,255,255,0,1,255 -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,255
    -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     -if $-2
        [-1],[-1],1,1,-{$-2*255/100} -to_gray[-3] -histogram[-3] 256,0,255 -graph[-1] [-3],3,0,0,0,1,0
        -rm[-3] -+[-1] {$-2*255/100} -+[-2,-1] -c[-1] 0,255
     -else -rm[-2] -endif
     -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
     --sh[0] 0,0,0,0
     -graph[-2] [-1],1,0,255,0,1,255,255,255 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,200,200,200 -rm[-1]
     --sh[0] 1,1,0,0
     -graph[-2] [-1],1,0,255,0,1,255,128,128 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,200,0,0 -rm[-1]
     --sh[0] 2,2,0,0
     -graph[-2] [-1],1,0,255,0,1,128,128,255 --[-1] 1
     -graph[-2] [-1],1,0,255,0,0.5,0,0,200 -rm[-1]
     -if {$40==0}
       -_gimp_apply_curve_preview 0,$1,0 -_gimp_apply_curve_preview $2,$3,1
       -_gimp_apply_curve_preview $4,$5,2 -_gimp_apply_curve_preview $6,$7,3
       -_gimp_apply_curve_preview $8,$9,4 -_gimp_apply_curve_preview $10,$11,5
       -_gimp_apply_curve_preview 255,$12,6
     -elif {$40==1}
       -_gimp_apply_curve_preview 0,$14,0 -_gimp_apply_curve_preview $15,$16,1
       -_gimp_apply_curve_preview $17,$18,2 -_gimp_apply_curve_preview $19,$20,3
       -_gimp_apply_curve_preview $21,$22,4 -_gimp_apply_curve_preview $23,$24,5
       -_gimp_apply_curve_preview 255,$25,6
     -else
       -_gimp_apply_curve_preview 0,$27,0 -_gimp_apply_curve_preview $28,$29,1
       -_gimp_apply_curve_preview $30,$31,2 -_gimp_apply_curve_preview $32,$33,3
       -_gimp_apply_curve_preview $34,$35,4 -_gimp_apply_curve_preview $36,$37,5
       -_gimp_apply_curve_preview 255,$38,6
     -endif
  -mv[-1] 1 -done -rm[0]

#@gimp _Black &amp; White : gimp_blackandwhite, gimp_blackandwhite_preview(1)
#@gimp : Red level = float(0.299,0,1)
#@gimp : Red smoothness = float(0,0,10)
#@gimp : Green level = float(0.587,0,1)
#@gimp : Green smoothness = float(0,0,10)
#@gimp : Blue level = float(0.114,0,1)
#@gimp : Blue smoothness = float(0,0,10)
#@gimp : sep = separator()
#@gimp : Gamma = float(1,0.01,5)
#@gimp : Contrast = float(1,0,4)
#@gimp : Brightness = float(0,-255,255)
#@gimp : Hue = float(0,0,360)
#@gimp : Saturation = float(0,0,1)
#@gimp : sep = separator()
#@gimp : Grain (shadows) = float(0,0,200)
#@gimp : Grain (midtones) = float(0,0,200)
#@gimp : Grain (highlights) = float(0,0,200)
#@gimp : Grain tone fading = float(2,0,10)
#@gimp : Grain scale = float(0,0,3)
#@gimp : Grain type = choice("Gaussian","Uniform","Salt and pepper","Poisson")
#@gimp : sep = separator()
#@gimp : Local contrast = float(0,0,60)
#@gimp : Radius = int(16,1,512)
#@gimp : Contrast smoothness = float(4,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_blackandwhite :
  -repeat @#
    -l[-1] -split_opacity -rv -to_rgb[-1] -s[-1] c          # Isolate opacity
    -*[-3] $1 -blur[-3] $2%                                 # Red contrast + smoothness
    -*[-2] $3 -blur[-2] $4%                                 # Green contrast + smoothness
    -*[-1] $5 -blur[-1] $6%                                 # Blue contrast + smoothness
    -+[-3--1] -/[-1] {$1+$3+$5} -c[-1] 0,255                # (R,G,B) -> B&W

    -apply_gamma[-1] $7                                     # Gamma correction
    --[-1] 128 -*[-1] $8 -+[-1] 128 -+[-1] $9 -c[-1] 0,255  # B&W contrast and brightness.

    100%,100% [-1]x2                                        # Create noise for shadows, midtones and highlights.
    -noise[-3] 100,$17 -blur[-3] $16% -n[-3] -$12,$12       # Scaled grain on shadows.
    -noise[-2] 100,$17 -blur[-2] $16% -n[-2] -$13,$13       # Scaled grain on midtones.
    -noise[-1] 100,$17 -blur[-1] $16% -n[-1] -$14,$14       # Scaled grain on highlights.

    --tones[-4] 3 -blur[-3--1] $15%                         # Get smoothed tones.
    -*[-6,-3] -*[-4,-2] -*[-2,-1]                           # Get noisy tones.
    -+[-4--1] -c[-1] 0,255                                  # Compose them with the B&W image.

    -if {$10||$11}
      -/[-1] 255
      -i[-2] 100%,100%,1,1,$11
      -i[-3] 100%,100%,1,1,$10
      -a[-3--1] c -hsv2rgb[-1]
    -endif

    -rv -a c -endl -mv[-1] 0 -done                          # Re-compose opacity and loop to next image.
  -normalize_local $18,$19,$20,2%,1,0,255

gimp_blackandwhite_preview :
  -gimp_split_preview "-gimp_blackandwhite ${1--2}",$-1

#@gimp Sepia : gimp_sepia, gimp_sepia_preview
#@gimp : Gamma = float(1,0.01,5)
#@gimp : Contrast = float(1,0,4)
#@gimp : Brightness = float(0,-255,255)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_sepia :
  -sepia
  -repeat @#
    --sh[-1] 0,2
    -apply_gamma[-1] $1 --[-1] 128 -*[-1] $2 -+[-1] {128+$3} -c[-1] 0,255
  -rm[-1] -mv[-1] 0 -done

gimp_sepia_preview :
  -gimp_split_preview "-gimp_sepia ${1--2}",$-1

#@gimp B&amp;W recolorize : gimp_bwrecolorize, gimp_bwrecolorize_preview
#@gimp : Gamma = float(1,0.01,5)
#@gimp : Contrast = float(1,0,4)
#@gimp : Brightness = float(0,-255,255)
#@gimp : Normalize = bool(0)
#@gimp : sep = separator()
#@gimp : Gradient preset = choice("User-defined","Black to white","White to black","Sepia","Solarize")
#@gimp : Interpolation type = choice(1,"Nearest","Linear","Cubic","Lanczos")
#@gimp : Preserve initial brightness = bool(0)
#@gimp : sep = separator(), note = note("<small><u>User-defined gradient :</u></small>")
#@gimp : Number of tones = int(5,2,8)
#@gimp : 1st tone = color(0,0,0,255)
#@gimp : 2nd tone = color(43,25,55,255)
#@gimp : 3rd tone = color(158,137,189,255)
#@gimp : 4th tone = color(224,191,228,255)
#@gimp : 5th tone = color(255,255,255,255)
#@gimp : 6th tone = color(255,255,255,255)
#@gimp : 7th tone = color(255,255,255,255)
#@gimp : 8th tone = color(255,255,255,255)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_bwrecolorize :
  -if $4 -n 0,255 -endif
  -if {$5==0}  # User-defined gradient
    -to_rgba (${9--2}) -r[-1] 4,$8,1,1,-1 -permute[-1] yzcx
  -elif {$5==1} # Black to white
    (0,255^0,255^0,255^255,255)
  -elif {$5==2} # White to black
    (255,0^255,0^255,0^255,255)
  -elif {$5==3} # Sepia
    (0,44,115,143,196,244^0,20,84,119,184,235^0,5,44,73,144,200^255,255,255,255,255,255)
  -else         # Solarize
    (0,359^1,1^1,1^255,255) -r[-1] 256,1,1,4,3 --sh[-1] 0,2 -hsv2rgb[-1] -rm[-1]
  -endif
  -if {$6==0} -r[-1] 256,1,1,4,1
  -elif {$6==1} -r[-1] 256,1,1,4,3
  -elif {$6==2} -r[-1] 256,1,1,4,5 -c[-1] 0,255
  -else -r[-1] 256,1,1,4,6
  -endif
  -if {$7==1} --sh[-1] 0,2 -rgb2hsv[-1] --sh[-1] 2,2 -f[-1] x/w -hsv2rgb[-2] -rm[-2,-1] -endif
  -repeat {@#-1}
    -p @{~>,s}
    -luminance[~>] -apply_gamma[~>] $1 --[~>] 128 -*[~>] $2 -+[~>] {$3+128} -c[~>] 0,255
    -map[~>] [-1] -to_colormode[~>] ~-1
    -pp[-1]
  -done
  -rm[-1]

gimp_bwrecolorize_preview :
  -gimp_split_preview "-gimp_bwrecolorize ${1--1}",$-1

#@gimp B&amp;W dithering : gimp_ditheredbw, gimp_ditheredbw_preview(0)
#@gimp : Gamma = float(1,0.01,5)
#@gimp : Contrast = float(1,0,4)
#@gimp : Brightness = float(0,-255,255)
#@gimp : Smoothness = float(0,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_ditheredbw :
  -apply_gamma[-1] $1 -- 128 -* $2 -+ 128 -+ $3 -blur $4 -c 0,255 -ditheredbw

gimp_ditheredbw_preview :
  -gimp_split_preview "-gimp_ditheredbw ${1--2}",$-1

#@gimp Tone mapping : gimp_map_tones, gimp_map_tones_preview(0)
#@gimp : Threshold = float(0.5,0,1)
#@gimp : Gamma = float(0.7,0,1)
#@gimp : Smoothness = float(0.1,0,10)
#@gimp : Iterations = int(30,0,500)
#@gimp : Channel(s) = choice(3,"All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_map_tones :
  -apply_channels "-map_tones ${1-4}",$5,0
  -n 0,255

gimp_map_tones_preview :
  -gimp_split_preview "-gimp_map_tones ${1--2}",$-1

#@gimp Local normalization : gimp_normalize_local, gimp_normalize_local_preview(0)
#@gimp : Amplitude = float(2,0,60)
#@gimp : Radius = int(6,1,64)
#@gimp : Neighborhood smoothness = float(5,0,40)
#@gimp : Average smoothness = float(20,0,40)
#@gimp : Constrain values = bool(1)
#@gimp : Channel(s) = choice(3,"All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_normalize_local :
  -apply_channels "-normalize_local $1,$2,$3,$4,$5,0,255",$6,0

gimp_normalize_local_preview :
  -gimp_split_preview "-gimp_normalize_local ${1--2}",$-1

#@gimp Select color : gimp_select_color, gimp_select_color(1)
#@gimp : Similarity space = choice(0,"RGB[A]","RGB","YCbCr","Red","Green","Blue","Opacity","Luminance","Blue & Red chrominances","Hue","Saturation")
#@gimp : Tolerance = float(20,0,100)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Selected color = color(255,255,255,255)
#@gimp : Output as = choice(0,"Selected colors","Selected mask")
#@gimp : Invert selection = bool(0)
_gimp_select_color :
  -if {$1==1} -to_rgb                            # RGB
  -elif {$1==2} -to_rgb -rgb2ycbcr               # YCbCr
  -elif {$1==3} -channels 0                      # R
  -elif {$1==4} -channels 1                      # G
  -elif {$1==5} -channels 2                      # B
  -elif {$1==6} -to_rgba -channels 3             # Opacity
  -elif {$1==7} -to_rgb -rgb2ycbcr -channels 0   # Luminance
  -elif {$1==8} -to_rgb -rgb2ycbcr -channels 1,2 # B&R chrominances
  -elif {$1==9} -to_rgb -rgb2hsv -channels 0     # Hue
  -elif {$1==10} -to_rgb -rgb2hsv -channels 1    # Saturation
  -endif

gimp_select_color :
  ($4^$5^$6^$7) -_gimp_select_color[-1] $1 -p @-1 -rm[-1]
  -repeat @#
    -if {$8==0}                                  # Output selected colors.
      --_gimp_select_color[-1] $1
      -select_color[-1] $2%,~-1
      -blur[-1] $3%
      -if $9 -*[-1] -1 -+[-1] 1 -endif
      -to_rgba[-2] -s[-2] c -*[-2,-1] -a[-4--1] c
    -else
      -_gimp_select_color[-1] $1
      -select_color[-1] $2%,~-1
      -blur[-1] $3
      -if $9 -*[-1] -1 -+[-1] 1 -endif
      -*[-1] 255 -r[-1] 100%,100%,1,4
    -endif
  -mv[-1] 0 -done

#@gimp Replace color : gimp_replace_color, gimp_replace_color(0)
#@gimp : Tolerance = float(100,1,450)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Selected color = color(255,255,255,255)
#@gimp : Replaced color = color(0,0,0,0)
gimp_replace_color :
  -to_rgba -replace_color $1,$2%,${3--1} -c 0,255

#@gimp User-defined : gimp_custom_transform, gimp_custom_transform
#@gimp : Red - Green - Blue - Alpha = text{"i"}
#@gimp : Red - Green - Blue = text{"i + 90*(x/w)*cos(i/10)"}
#@gimp : Red = text{"i"}
#@gimp : Green = text{"i"}
#@gimp : Blue = text{"i"}
#@gimp : Alpha = text{"i"}
#@gimp : Value normalization = choice("None","RGB","RGBA")
gimp_custom_transform :
  -to_rgba -repeat @#
    -f[-1] "$1"
    -s[-1] c -a[-4--2] c -f[-2] "$2"
    -s[-2] c -f[-4] "$3" -f[-3] "$4" -f[-2] "$5" -f[-1] "$6"
    -if {$7==0} -a[-4--1] c -c[-1] 0,255
    -elif {$7==1} -a[-4--2] c -n[-2] 0,255 -c[-1] 0,255 -a[-2,-1] c
    -else -a[-4--1] c -n[-1] 0,255
    -endif
  -mv[-1] 0 -done

#@gimp Linear gradient : gimp_linear_gradient, gimp_linear_gradient
#@gimp : Starting color = color(0,0,0,255)
#@gimp : Ending color = color(255,255,255,255)
#@gimp : Swap colors = bool(0)
#@gimp : Angle = float(45,0,360)
#@gimp : Fade start = float(0,0,100)
#@gimp : Fade end = float(100,0,100)
gimp_linear_gradient :
  -repeat @#
    ({w},{h}) -rm[-2]
    ($1^$2^$3^$4) ($5^$6^$7^$8)
    -if $9 -rv[-2,-1] -endif
    -r[-2,-1] @-3 -rm[-3]
    -fade_linear $10,$11,$12
  -mv[-1] 0 -done

#@gimp Radial gradient : gimp_radial_gradient, gimp_radial_gradient
#@gimp : Starting color = color(0,0,0,255)
#@gimp : Ending color = color(255,255,255,255)
#@gimp : Swap colors = bool(0)
#@gimp : Fade start = float(0,0,100)
#@gimp : Fade end = float(100,0,100)
#@gimp : X-center = float(50,0,100)
#@gimp : Y-center = float(50,0,100)
gimp_radial_gradient :
  -repeat @#
    ({w},{h}) -rm[-2]
    ($1^$2^$3^$4) ($5^$6^$7^$8)
    -if $9 -rv[-2,-1] -endif
    -r[-2,-1] @-3 -rm[-3]
    100%,100% -=[-1] 1,$12%,$13% -distance[-1] 1 -_fade $10,$11
  -mv[-1] 0 -done

#@gimp Corner gradient : gimp_corner_gradient, gimp_corner_gradient
#@gimp : Color 1 (up/left corner) = color(255,255,255,128)
#@gimp : Color 2 (up/right corner) = color(255,0,0,255)
#@gimp : Color 3 (bottom/left corner) = color(0,255,0,255)
#@gimp : Color 4 (bottom/right corner) = color(0,0,255,255)
gimp_corner_gradient :
  -repeat @#
    ({w},{h}) -rm[-2]
    ($1,$5;$9,$13^$2,$6;$10,$14^$3,$7;$11,$15^$4,$8;$12,$16) -r[-1] @-2,1,4,3 -rm[-2]
  -mv[-1] 0 -done


#@gimp _<b>Contours</b>
#----------------------

#@gimp Gradient norm : gimp_gradient_norm, gimp_gradient_norm_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Linearity = float(0.5,0,1.5)
#@gimp : Min threshold = float(0,0,100)
#@gimp : Max threshold = float(100,0,100)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_gradient_norm :
  -blur $1 -gradient_norm -pow $2
  -c $3%,$4%
  -if $5 -negative -endif
  -n 0,255

gimp_gradient_norm_preview :
  -gimp_split_preview "-gimp_gradient_norm ${1--1}",$-1

#@gimp RGB Gradient : gimp_gradient2rgb, gimp_gradient2rgb_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Min threshold = float(0,0,100)
#@gimp : Max threshold = float(100,0,100)
#@gimp : Orientation only = bool(0)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_gradient2rgb :
  -blur $1 -gradient2rgb $4
  -c $2%,$3%
  -if $5 -negative -endif
  -n 0,255

gimp_gradient2rgb_preview :
  -gimp_split_preview "-gimp_gradient2rgb ${1--1}",$-1

#@gimp Local orientation : gimp_local_orientation, gimp_local_orientation_preview(1)
#@gimp : Smoothness = float(0,0,5)
#@gimp : Min threshold = float(0,0,100)
#@gimp : Max threshold = float(100,0,100)
#@gimp : Negative colors = bool(0)
#@gimp : Channel(s) = choice(3,"All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
_gimp_local_orientation :
  -blur $1% -gradient_orientation 2 -complex2polar -rm[0--1:2]
  -c $2%,$3%
  -if $4 -negative -endif

gimp_local_orientation :
  -apply_channels "-_gimp_local_orientation $1,$2,$3,$4",$5,1

gimp_local_orientation_preview :
  -gimp_split_preview "-gimp_local_orientation ${1--1}",$-1

#@gimp Laplacian : gimp_laplacian, gimp_laplacian_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Min threshold = float(0,0,100)
#@gimp : Max threshold = float(100,0,100)
#@gimp : Absolute value = bool(0)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_laplacian :
  -blur $1 -laplacian
  -if $4 -abs -endif
  -c $2%,$3%
  -if $5 -negative -endif
  -n 0,255

gimp_laplacian_preview :
  -gimp_split_preview "-gimp_laplacian ${1--1}",$-1

#@gimp Curvature : gimp_curvature, gimp_curvature_preview(0)
#@gimp : Smoothness = float(2,0,10)
#@gimp : Min threshold = float(0,0,100)
#@gimp : Max threshold = float(100,0,100)
#@gimp : Absolute value = bool(0)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_curvature :
  -blur $1 -Iee
  -if $4 -abs -endif
  -c $2%,$3%
  -if $5 -negative -endif
  -n 0,255

gimp_curvature_preview :
  -gimp_split_preview "-gimp_curvature ${1--1}",$-1

#@gimp Edges : gimp_edges, gimp_edges_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Threshold = float(15,0,50)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_edges :
  -to_rgb -blur $1% -edges $2%
  -if $3 -negative -endif
  -n 0,255

gimp_edges_preview :
  -gimp_split_preview "-gimp_edges ${1--1}",$-1

#@gimp Thin edges : gimp_thin_edges, gimp_thin_edges_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Threshold = float(15,0,50)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_thin_edges :
  -blur $1% -gradient_norm -t $2% -skeleton
  -if {!$3} -negative -endif
  -n 0,255

gimp_thin_edges_preview :
  -gimp_split_preview "-gimp_thin_edges ${1--1}",$-1

#@gimp Edge offsets : gimp_edge_offsets, gimp_edge_offsets_preview(0)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Threshold = float(15,0,50)
#@gimp : Scale = int(4,0,32)
#@gimp : Thickness = int(1,0,16)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_edge_offsets :
  -repeat @#
    os={s}
    -blur[-1] $1% -gradient_norm[-1] -t[-1] $2% -skeleton[-1] -distance[-1] 1 -round[-1] 1 -mod[-1] $3 -t[-1] {max(1,$3-$4)}
    -if {!$5} -negative[-1] -endif
    -n[-1] 0,255 -to_colormode[-1] $os
  -mv[-1] 0 -done

gimp_edge_offsets_preview :
  -gimp_split_preview "-gimp_edge_offsets ${1--1}",$-1

#@gimp Isophotes : gimp_isophotes, gimp_isophotes_preview(0)
#@gimp : Levels = int(16,1,256)
#@gimp : Smoothness = float(0,0,5)
#@gimp : Filling = choice(0,"Transparent","Colors")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_isophotes :
  -if $3
    -topographic_map $1,$2
  -else
    -blur $2 -isophotes $1
  -endif

gimp_isophotes_preview :
  -gimp_split_preview "-gimp_isophotes ${1--1}",$-1

#@gimp Segmentation : gimp_segment_watershed, gimp_segment_watershed_preview(0)
#@gimp : Edge threshold = float(2,0,5)
#@gimp : Smoothness = float(1,0,5)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_segment_watershed :
  -apply_channels "-blur $2 -segment_watershed $1",$3,0

gimp_segment_watershed_preview :
  -gimp_split_preview "-gimp_segment_watershed ${1--1}",$-1

#@gimp Difference of gaussians : gimp_dog, gimp_dog_preview(1)
#@gimp : 1st Variance = float(1.4,0,5)
#@gimp : 2nd Variance = float(1.5,0,5)
#@gimp : Threshold = float(0,0,49)
#@gimp : Negative colors = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_dog :
  -dog $1%,$2%
  -c $3%,{100-$3}%
  -if $4 -negative -endif
  -n 0,255

gimp_dog_preview :
  -gimp_split_preview "-gimp_dog ${1--1}",$-1

#@gimp Morphological filter : gimp_morpho, gimp_morpho_preview(0)
#@gimp : Action = choice("Erosion","Dilation","Opening","Closing",
#@gimp : "Original - Erosion","Dilation - Original","Original - Opening","Closing - Original")
#@gimp : Size = int(5,2,60)
#@gimp : Invert colors = bool(false)
#@gimp : Shape = choice(0,"Square","Octagonal","Circular")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : Scale = bool(true)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_morpho :
  -apply_channels "-__gimp_morpho ${1--1}",$5,$6

gimp_morpho_preview :
  -gimp_split_preview "-gimp_morpho ${1--1}",$-1

__gimp_morpho :
  -if {$4==1}
   -if {$1==0} -erode_oct $2
   -elif {$1==1} -dilate_oct $2
   -elif {$1==2} -erode_oct $2 -dilate_oct $2
   -elif {$1==3} -dilate_oct $2 -erode_oct $2
   -elif {$1==4} -repeat @# --erode_oct $2 --[-2,-1] -mv[-1] 0 -done
   -elif {$1==5} -repeat @# --dilate_oct $2 -rv[-2,-1] --[-2,-1] -mv[-1] 0 -done
   -elif {$1==6} -repeat @# --erode_oct $2 -dilate_oct[-1] $2 --[-2,-1] -mv[-1] 0 -done
   -else -repeat @# --dilate_oct $2 -erode_oct[-1] $2 -rv[-2,-1] --[-2,-1] -mv[-1] 0 -done
   -endif
  -elif {$4==0}
   -if {$1==0} -erode $2
   -elif {$1==1} -dilate $2
   -elif {$1==2} -erode $2 -dilate $2
   -elif {$1==3} -dilate $2 -erode $2
   -elif {$1==4} -repeat @# --erode $2 --[-2,-1] -mv[-1] 0 -done
   -elif {$1==5} -repeat @# --dilate $2 -rv[-2,-1] --[-2,-1] -mv[-1] 0 -done
   -elif {$1==6} -repeat @# --erode $2 -dilate[-1] $2 --[-2,-1] -mv[-1] 0 -done
   -else -repeat @# --dilate $2 -erode[-1] $2 -rv[-2,-1] --[-2,-1] -mv[-1] 0 -done
   -endif
  -else
   -if {$1==0} -erode_circ $2
   -elif {$1==1} -dilate_circ $2
   -elif {$1==2} -erode_circ $2 -dilate_circ $2
   -elif {$1==3} -dilate_circ $2 -erode_circ $2
   -elif {$1==4} -repeat @# --erode_circ $2 --[-2,-1] -mv[-1] 0 -done
   -elif {$1==5} -repeat @# --dilate_circ $2 -rv[-2,-1] --[-2,-1] -mv[-1] 0 -done
   -elif {$1==6} -repeat @# --erode_circ $2 -dilate_circ[-1] $2 --[-2,-1] -mv[-1] 0 -done
   -else -repeat @# --dilate_circ $2 -erode_circ[-1] $2 -rv[-2,-1] --[-2,-1] -mv[-1] 0 -done
   -endif
  -endif
  -if $3 -negative -endif

#@gimp Skeleton : gimp_skeleton, gimp_skeleton_preview(1)
#@gimp : Smoothness = float(0,0,10)
gimp_skeleton :
  -norm -blur $1% -skeleton -* 255

gimp_skeleton_preview :
  -norm -r 45%,45%,1,100%,2 -gimp_skeleton $1


#@gimp _<b>Deformations</b>
#--------------------------


#@gimp Zoom : gimp_zoom, gimp_zoom(1)
#@gimp : Factor = float(2,0.01,10)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Borders = choice(0,"Black","Nearest","Repeat")
gimp_zoom :
  -if {$1<1} -to_rgba -endif
  -zoom $1,$2,$3,0,$4

#@gimp Water : water, water(0)
#@gimp : Amplitude = float(30,0,300)
#@gimp : Smoothness = float(1.5,0,4)

#@gimp Wave : wave, wave(1)
#@gimp : Amplitude = float(10,0,30)
#@gimp : Frequency = float(0.4,0,2)
#@gimp : X-center = float(50,0,100)
#@gimp : Y-center = float(50,0,100)

#@gimp Twirl : twirl, twirl(1)
#@gimp : Amplitude = float(1,-5,5)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Borders = choice(1,"Black","Nearest","Repeat")

#@gimp Flower : gimp_flower, gimp_flower(1)
#@gimp : Amplitude = float(30,-100,100)
#@gimp : Petals = int(6,0,20)
#@gimp : Offset = float(0,0,100)
#@gimp : Angle = float(0,0,360)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Borders = choice(1,"Black","Nearest","Repeat")
gimp_flower :
  -flower $1,$2,$3%,$4,$5,$6,$7

#@gimp Random : deform, deform(0)
#@gimp : Amplitude = float(10,0,100)

#@gimp Fish-eye : fish_eye, fish_eye(1)
#@gimp : X-center = float(50,0,100)
#@gimp : Y-center = float(50,0,100)
#@gimp : Radius = float(70,0,100)
#@gimp : Amplitude = float(1,0,2)

#@gimp Sphere : gimp_map_sphere, gimp_map_sphere_preview(1)
#@gimp : Width = _int(512,1,4096)
#@gimp : Height = _int(512,1,4096)
#@gimp : Radius = float(90,0,400)
#@gimp : Dilation = float(0.5,0,1)
#@gimp : Angle = float(0,-50,50)
gimp_map_sphere :
  -shift $5%,0,0,0,2 -to_rgba -map_sphere $1,$2,$3,$4

gimp_map_sphere_preview :
  -gimp_map_sphere {w},{h},$3,$4,$5

#@gimp Perspective : gimp_warp_perspective, gimp_warp_perspective(1)
#@gimp : X-angle = float(1.73,-4,4)
#@gimp : Y-angle = float(0,-4,4)
#@gimp : Zoom = float(1,0.1,4)
#@gimp : X-center = float(50,0,100)
#@gimp : Y-center = float(50,0,100)
#@gimp : X-offset = float(0,0,100)
#@gimp : Y-offset = float(0,0,100)
#@gimp : Borders = choice(2,"Black","Nearest","Repeat")
gimp_warp_perspective :
  -shift $6%,$7%,0,0,2 -warp_perspective $1,$2,$3,$4,$5,$8

#@gimp Euclidean - Polar : gimp_euclidean2polar, gimp_euclidean2polar(1)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Dilation = float(1,0.1,10)
#@gimp : Borders = choice(1,"Black","Nearest","Repeat")
#@gimp : Inverse transform = bool(0)
gimp_euclidean2polar :
  -if $5 -polar2euclidean $1,$2,$3,$4 -else -euclidean2polar $1,$2,$3,$4 -endif

#@gimp Cartesian transform : gimp_custom_deformation, gimp_custom_deformation(1)
#@gimp : X-warping = text{"(w+h)/20 * cos(y*20/h)"}
#@gimp : Y-warping = text{"(w+h)/20 * sin(x*20/w)"}
#@gimp : Relative warping = bool(1)
#@gimp : Interpolation = choice(1,"Nearest neighbor","Linear")
#@gimp : Borders = choice(1,"Black","Nearest","Repeat")
gimp_custom_deformation :
   -repeat @#
    --norm[-1] [-1] -f[-2] "$1" -f[-1] "$2"
    -a[-2,-1] c -warp[-2] [-1],$3,$4,$5,1 -rm[-1]
  -mv[-1] 0 -done

#@gimp Polar transform : gimp_transform_polar, gimp_transform_polar(1)
#@gimp : Preset = choice("Custom transform","Inverse radius","Swap radius/angle")
#@gimp : X-center = float(50,0,100)
#@gimp : Y-center = float(50,0,100)
#@gimp : Radius = text{"r + R/10*cos(a*5)"}
#@gimp : Angle = text{"a"}
#@gimp : Borders = choice(1,"Black","Nearest","Repeat")
gimp_transform_polar :
  -if {$1==0}
    -transform_polar "$4","$5",$2,$3,$6
  -elif {$1==1}
    -transform_polar R-r,a,$2,$3,$6
  -else
    -transform_polar a*R/(2*pi),r*2*pi/R,$2,$3,$6
  -endif


#@gimp _<b>Degradations</b>
#---------------------------


#@gimp Additive noise : gimp_noise, gimp_noise_preview(0)
#@gimp : Amplitude = float(10,0,200)
#@gimp : Noise type = choice("Gaussian","Uniform","Salt and pepper","Poisson")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_noise :
  -apply_channels "-noise $1,$2",$3,$4

gimp_noise_preview :
  -gimp_split_preview "-gimp_noise ${1--2}",$-1

#@gimp Spread noise : gimp_spread, gimp_spread_preview(0)
#@gimp : X-variations = float(4,0,20)
#@gimp : Y-variations = float(4,0,20)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_spread :
  -apply_channels "-spread $1,$2",$3,0

gimp_spread_preview :
  -gimp_split_preview "-gimp_spread ${1--2}",$-1

#@gimp Random shade stripes : gimp_shade_stripes, gimp_shade_stripes_preview(1)
#@gimp : Frequency = float(30,1,100)
#@gimp : Orientation = choice(1,"Horizontal","Vertical")
#@gimp : Darkness = float(0.8,0,3)
#@gimp : Lightness = float(1.3,0,3)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_shade_stripes :
  -apply_channels "-shade_stripes $1,$2,$3,$4",$5,0

gimp_shade_stripes_preview :
  -gimp_split_preview "-gimp_shade_stripes ${1--2}",$-1

#@gimp Old-movie stripes : gimp_stripes_y, gimp_stripes_y_preview(1)
#@gimp : Frequency = float(10,0,100)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_stripes_y :
  -apply_channels "-stripes_y $1",$2,0

gimp_stripes_y_preview :
  -gimp_split_preview "-gimp_stripes_y ${1--2}",$-1

#@gimp Visible watermak : gimp_watermark_visible, gimp_watermark_visible(0)
#@gimp : Text = text("\251 G'MIC")
#@gimp : Opacity = float(0.4,0.1,0.9)
#@gimp : Size = int(57,13,128)
#@gimp : Angle = float(25,0,360)
#@gimp : Lightness = choice(1,"Darker","Brighter")
gimp_watermark_visible :
  -watermark_visible "$1",$2,$3,$4,$5

#@gimp Gaussian blur : gimp_gaussian_blur, gimp_gaussian_blur_preview(0)
#@gimp : XY-amplitude = float(3,0,20)
#@gimp : X-amplitude = float(0,0,20)
#@gimp : Y-amplitude = float(0,0,20)
#@gimp : Border conditions = choice(1,"Black","Nearest")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
_gimp_gaussian_blur :
  -blur $1,$4
  -if {$2>0} -repeat @# -l[-1] -s y -blur $2,$4 -a y -endl -mv[-1] 0 -done -endif
  -if {$3>0} -repeat @# -l[-1] -s x -blur $3,$4 -a x -endl -mv[-1] 0 -done -endif

gimp_gaussian_blur :
  -apply_channels "-_gimp_gaussian_blur $1,$2,$3,$4",$5,$6

gimp_gaussian_blur_preview :
  -gimp_split_preview "-gimp_gaussian_blur ${1--2}",$-1

#@gimp Linear blur : gimp_blur_linear, gimp_blur_linear_preview(1)
#@gimp : Tangent radius = float(10,0,100)
#@gimp : Orthogonal radius = float(0.5,0,100)
#@gimp : Angle = float(0,0,180)
#@gimp : Border conditions = choice(1,"Black","Nearest")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_blur_linear :
  -apply_channels "-blur_linear $1,{$2*$1/100},$3,$4",$5,$6

gimp_blur_linear_preview :
  -gimp_split_preview "-gimp_blur_linear ${1--2}",$-1

#@gimp Radial blur : gimp_blur_radial, gimp_blur_radial(1)
#@gimp : Amplitude = float(3,0,20)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : Value range = choice("Cut","Normalize")
gimp_blur_radial :
  -apply_channels "-blur_radial $1%,$2,$3",$4,$5

#@gimp Angular blur : gimp_blur_angular, gimp_blur_angular(1)
#@gimp : Amplitude = float(2,0,10)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : Value range = choice("Cut","Normalize")
gimp_blur_angular :
  -apply_channels "-blur_angular $1%,$2,$3",$4,$5

#@gimp Bandpass filter : gimp_bandpass, gimp_bandpass_preview(0)
#@gimp : Low frequency = float(0,0,100)
#@gimp : High frequency = float(100,0,100)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : Value range = choice(1,"Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_bandpass :
  -apply_channels "-bandpass $1%,$2%",$3,$4

gimp_bandpass_preview :
  -gimp_split_preview "-gimp_bandpass ${1--2}",$-1

#@gimp RGB Bayer mask : rgb2bayer, rgb2bayer(0)
#@gimp : Starting pattern = choice(0,"Red-Green","Blue-Green","Green-Red","Green-Blue")
#@gimp : Keep colors = bool(1)

#@gimp Bayer reconstruction : bayer2rgb, gimp_no_preview
#@gimp : G/M smoothness = _float(6,0,20)
#@gimp : R/B smoothness (principal) = _float(6,0,20)
#@gimp : R/B smoothness (secondary) = _float(4,0,20)


#@gimp _<b>Enhancement</b>
#--------------------------


#@gimp Anisotropic smoothing : gimp_anisotropic_smoothing, gimp_anisotropic_smoothing_preview(0)
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.7,0,2)
#@gimp : Anisotropy = float(0.3,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
#@gimp : Spatial precision = float(0.8,0.1,2)
#@gimp : Angular precision = float(30,1,180)
#@gimp : Value precision = float(2,0.1,5)
#@gimp : Interpolation = choice(0,"Nearest neighbor","Linear","Runge-Kutta")
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : Tiles = int(1,1,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_anisotropic_smoothing :
  -repeat @# -l[~>]
    -split_tiles $13,$13
    -apply_channels "-repeat $11 -smooth $1,$2,$3,$4,$5,$6,$7,$8,$9,$10 -done",$12,0
    -append_tiles $13,$13
  -endl -done -c 0,255

gimp_anisotropic_smoothing_preview :
  -gimp_split_preview "-gimp_anisotropic_smoothing ${1--2}",$-1

#@gimp Patch-based smoothing : gimp_patch_smoothing, gimp_patch_smoothing_preview(0)
#@gimp : Spatial variance = float(10,0.1,200)
#@gimp : Patch variance = float(10,0.1,200)
#@gimp : Patch size = int(3,2,21)
#@gimp : Lookup size = int(5,2,21)
#@gimp : Patch smoothness = float(0,0,4)
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_patch_smoothing :
  -apply_channels "-repeat $7 -denoise $1,$2,$3,$4,$5,$6 -done",$8,0 -c 0,255

gimp_patch_smoothing_preview :
  -gimp_split_preview "-gimp_patch_smoothing ${1--2}",$-1

#@gimp Bilateral filtering : gimp_bilateral, gimp_bilateral_preview(0)
#@gimp : Spatial variance = float(10,0,100)
#@gimp : Value variance = float(7,0,100)
#@gimp : Iterations = int(2,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_bilateral :
  -apply_channels "-repeat $3 -bilateral $1,$2 -done",$4,0

gimp_bilateral_preview :
  -gimp_split_preview "-gimp_bilateral ${1--2}",$-1

#@gimp Hot pixels filtering : gimp_remove_hotpixels, gimp_remove_hotpixels_preview(0)
#@gimp : Mask size = int(3,3,20)
#@gimp : Threshold = float(10,0,200)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_remove_hotpixels :
  -remove_hotpixels $1,$2

gimp_remove_hotpixels_preview :
  -gimp_split_preview "-gimp_remove_hotpixels ${1--2}",$-1

#@gimp Median filtering : gimp_median, gimp_median_preview(0)
#@gimp : Radius = int(3,1,20)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_median :
  -apply_channels "-median $1",$2,0

gimp_median_preview :
  -gimp_split_preview "-gimp_median ${1--2}",$-1

#@gimp Edge-preserving flow : gimp_edgepreserving_smoothing, gimp_edgepreserving_smoothing_preview(0)
#@gimp : Sharpness = float(0.7,0,2)
#@gimp : Anisotropy = float(0.3,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
#@gimp : Time step = float(15,5,50)
#@gimp : Iterations = int(8,1,100)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_edgepreserving_smoothing :
  -apply_channels "-smooth $6,$1,$2,$3,$4,$5,0",$7,0 -c 0,255

gimp_edgepreserving_smoothing_preview :
  -gimp_split_preview "-gimp_edgepreserving_smoothing ${1--2}",$-1

#@gimp Mean-curvature flow : gimp_meancurvature_smoothing, gimp_meancurvature_smoothing_preview(0)
#@gimp : Time step = float(30,5,50)
#@gimp : Iterations = int(4,1,10)
#@gimp : Keep iterations as different layers = bool(false)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_meancurvature_smoothing :
  -apply_channels "-meancurvature_flow $2,$1,$3",$4,0 -c 0,255

gimp_meancurvature_smoothing_preview :
  -gimp_split_preview "-gimp_meancurvature_smoothing ${1--2}",$-1

#@gimp Total-variation flow : gimp_tv_smoothing, gimp_tv_smoothing_preview(0)
#@gimp : Time step = float(30,5,100)
#@gimp : Iterations = int(10,1,40)
#@gimp : Keep iterations as different layers = bool(false)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_tv_smoothing :
  -apply_channels "-tv_flow $2,$1,$3",$4,0 -c 0,255

gimp_tv_smoothing_preview :
  -gimp_split_preview "-gimp_tv_smoothing ${1--2}",$-1

#@gimp Unsharp mask : gimp_unsharp, gimp_unsharp_preview(0)
#@gimp : Sharpening type = choice(0,"Gaussian","Bilateral")
#@gimp : Spatial radius = float(1.25,0,20)
#@gimp : Bilateral radius = float(30,0,60)
#@gimp : Amount = float(3,0,10)
#@gimp : Threshold = float(0,0,20)
#@gimp : Darkness level = float(1,0,4)
#@gimp : Lightness level = float(1,0,4)
#@gimp : Iterations = int(1,1,10)
#@gimp : Negative effect = bool(0)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : note = note{"\n\n<small><b>Note : </b>
#@gimp : This filter is inspired by the original <i>Unsharp Mask</i> filter in GIMP, with additional parameters.
#@gimp : </small>"}
_gimp_unsharp :
  -repeat @# -repeat $8
    -if {$1==0} --blur[-1] $2 -else --bilateral[-1] $2,$3 -endif
    --[-1] [-2] -*[-1] -$4
    --norm[-1] -t[-1] $5% -r[-1] [-2] -*[-2,-1]
    -if $9 -*[-1] -1 -endif
    --c[-1] 0,100% -c[-2] -100%,0 -*[-2] $6 -*[-1] $7 -+[-2,-1]
    -+[-2,-1] -c[-1] 0,255
  -done -mv[-1] 0 -done

gimp_unsharp :
  -apply_channels "-_gimp_unsharp $1,$2,$3,$4,$5,$6,$7,$8,$9",$10,0

gimp_unsharp_preview :
  -gimp_split_preview "-gimp_unsharp ${1--2}",$-1

#@gimp Octave sharpening : gimp_unsharp_octave, gimp_unsharp_octave_preview(0)
#@gimp : Scales = int(4,1,10)
#@gimp : Maximal radius = float(5,0,20)
#@gimp : Amount = float(3,0,10)
#@gimp : Threshold = float(0,0,255)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_unsharp_octave :
  -apply_channels "-unsharp_octave $1,$2,$3,$4",$5,0

gimp_unsharp_octave_preview :
  -gimp_split_preview "-gimp_unsharp_octave ${1--2}",$-1

#@gimp Inverse diffusion : gimp_sharpen_inversediff, gimp_sharpen_inversediff_preview(0)
#@gimp : Amplitude = float(50,1,300)
#@gimp : Iterations = int(2,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_sharpen_inversediff :
  -apply_channels "-repeat $2 -sharpen $1,0 -c 0,255 -done",$3,0

gimp_sharpen_inversediff_preview :
  -gimp_split_preview "-gimp_sharpen_inversediff ${1--2}",$-1

#@gimp Shock filters : gimp_sharpen_shock, gimp_sharpen_shock_preview(0)
#@gimp : Amplitude = float(150,1,400)
#@gimp : Edge threshold = float(0.1,0,0.7)
#@gimp : Gradient smoothness = float(0.8,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_sharpen_shock :
  -apply_channels "-repeat $5 -sharpen $1,1,$2,$3,$4 -c 0,255 -done",$6,0

gimp_sharpen_shock_preview :
  -gimp_split_preview "-gimp_sharpen_shock ${1--2}",$-1

#@gimp Deconvolution : gimp_richardson_lucy, gimp_richardson_lucy_preview(0)
#@gimp : Radius = float(2,0,20)
#@gimp : Iterations = int(10,0,100)
#@gimp : Time step = float(20,0,50)
#@gimp : Smoothness = float(0.1,0,10)
#@gimp : Regularization = choice(1,"Tikhonov","Mean curvature","Total variation")
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_richardson_lucy :
  -apply_channels "-richardson_lucy ${1-5} -c 0,255",$6,0

gimp_richardson_lucy_preview :
  -gimp_split_preview "-gimp_richardson_lucy ${1--2}",$-1

#@gimp Region inpainting : gimp_inpaint, gimp_inpaint_preview(0)
#@gimp : Smooth inpaint = bool(true)
#@gimp : Global iterations = int(10,1,30)
#@gimp : Local iterations = int(10,1,30)
#@gimp : Time step = float(20,5,50)
#@gimp : Gradient smoothness = float(0.7,0,5)
#@gimp : Tensor smoothness = float(1.2,0,5)
#@gimp : note = note("<small><b>Note :</b>
#@gimp : This filter tries to reconstruct the content of image regions.
#@gimp : The inpainted region is defined as a white area in the top layer.
#@gimp : </small>")
gimp_inpaint :
  -if {@#==1} -return -endif
  -if $1 -inpaint_flow $2,$3,$4,-$5,-$6 -c 0,255 -else -inpaint[1--1] [0] -endif
  -to_rgba[0] -f[0] 0

gimp_inpaint_preview :
  -if {@#==1} -return -endif
  -gimp_inpaint ${^0} -rm[0]

#@gimp Deinterlace : deinterlace, gimp_deinterlace_preview(0)
#@gimp : Algorithm = choice("Standard","Motion-compensated")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_deinterlace :
  -deinterlace 0 -skip ${^0}

gimp_deinterlace_preview :
  -gimp_split_preview "-gimp_deinterlace ${1--2}",$-1

#@gimp Red-Eye attenuation : red_eye, red_eye
#@gimp : Threshold = float(75,0,100)
#@gimp : Smoothness = float(3.5,0,20)
#@gimp : Factor = float(0.1,0,1)

#@gimp Scale2x algorithm : gimp_scalenx, gimp_scalenx_preview(0)
#@gimp : Scaling factor = choice("x 2","x 3","x 4","x 6","x 8","x 9","x 12","x 16","x 18","x 27")
#@gimp : note = note{"\n<small><b>Note : </b>
#@gimp : This filter re-implements the scaling algorithm described at :
#@gimp : </small>"}
#@gimp : note = link("http://scale2x.sourceforge.net")
#@gimp : note = note{"<small>
#@gimp : This filter is useful for resizing images that have very few colors
#@gimp : (e.g. indexed images). It is generally useless for true colors images.
#@gimp : </small>"}
gimp_scalenx :
  -if {$1==0} -resize2x
  -elif {$1==1} -resize3x
  -elif {$1==2} -resize2x -resize2x
  -elif {$1==3} -resize3x -resize2x
  -elif {$1==4} -resize2x -resize2x -resize2x
  -elif {$1==5} -resize3x -resize3x
  -elif {$1==6} -resize3x -resize2x -resize2x
  -elif {$1==7} -resize2x -resize2x -resize2x -resize2x
  -elif {$1==8} -resize3x -resize3x -resize2x
  -elif {$1==9} -resize3x -resize3x -resize3x
  -endif

gimp_scalenx_preview :
  -crop 40%,40%,60%,60% -gimp_scalenx $1

#@gimp Smart upscale : gimp_upscale_smart, gimp_upscale_smart_preview(0)
#@gimp : Width = text("200%")
#@gimp : Height = text("200%")
#@gimp : Smoothness = float(2,0,20)
#@gimp : Anisotropy = float(0.4,0,1)
#@gimp : Sharpness = float(10,0,100)
gimp_upscale_smart :
  -to_rgb -upscale_smart $1,$2,1,$3,$4,$5 -c 0,255

gimp_upscale_smart_preview :
  -repeat @#
    --r[-1] $1,$2,1,1,0
    -if {w<@{-2,w}||h<@{-2,h}}  # Test for downscaling
      -rm[-1] -/[-1] 4
      1 -text[-1] "Downscaling is\nnot allowed !",5,5,20,1,255 -r[-1] [-2],[-2],1,1,0,0,0.5,0.5
      -or[-2,-1]
    -else
      -crop[-2] {50-50*@{-2,w}/w}%,{50-50*@{-2,h}/h}%,{50+50*@{-2,w}/w}%,{50+50*@{-2,h}/h}%
      -rm[-1] -gimp_upscale_smart[-1] $1,$2,$3,$4,$5 -c[-1] 0,255
    -endif
  -mv[-1] 0 -done



#@gimp _<b>Layers</b>
#---------------------


#@gimp Average : compose_average, compose_average
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Multiply : compose_multiply, compose_multiply
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Screen : compose_screen, compose_screen
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Darken : compose_darken, compose_darken
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Lighten : compose_lighten, compose_lighten
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Difference : compose_difference, compose_difference
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Negation : compose_negation, compose_negation
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Exclusion : compose_exclusion, compose_exclusion
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Overlay : compose_overlay, compose_overlay
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Hard light : compose_hardlight, compose_hardlight
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Soft light : compose_softlight, compose_softlight
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Dodge : compose_dodge, compose_dodge
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Color burn : compose_colorburn, compose_colorburn
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Reflect : compose_reflect, compose_reflect
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Freeze : compose_freeze, compose_freeze
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Stamp : compose_stamp, compose_stamp
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Interpolation : compose_interpolation, compose_interpolation
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp XOR : compose_xor, compose_xor
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Fade : gimp_compose_fade, gimp_compose_fade(1)
#@gimp : Preset = choice{1,"Custom","Linear","Circular","Wave","Keftales"}
#@gimp : Offset = float(0,-1,1)
#@gimp : Thinness = float(0,0,10)
#@gimp : Sharpness = float(5,1,20)
#@gimp : Sharpest = bool(0)
#@gimp : Revert layers = bool(0)
#@gimp : Note = note{\n<small>
#@gimp : The parameters below are used in most presets.
#@gimp : </small>}
#@gimp : 1st parameter = float(0,-1,1)
#@gimp : 2nd parameter = float(0,-1,1)
#@gimp : 3rd parameter = float(0,-1,1)
#@gimp : Note = note{\n<small>
#@gimp : The formula below is used for the <i>Custom</i> preset.
#@gimp : </small>}
#@gimp : Formula = text{"cos(4*pi*x/w) * sin(4*pi*y/h)"}
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
gimp_compose_fade :
  -if {@#==1} -return -endif
  -to_colormode 4
  -if {$1==0} [0],[0],1,1,"$10"
  -else -_gimp_compose_fade$1 $7,$8,$9 -r[-1] [0],[0],1,1,3
  -endif
  -n[-1] {-(@#-2)*$3},{(@#-2)*(1+$3)}
  --[-1] {$2*(1+$3)*(@#-2)}
  -c[-1] 0,{@#-2}
  -if $6 -rv[0--2] -endif
  -if $5 -round[-1] 1
  -else -roundify[-1] $4
  -endif
  -compose_fade
  -c 0,255

_gimp_compose_fade1 : [0],[0],1,1,"a=$1*pi/2; x*cos(a) + y*sin(a)"
_gimp_compose_fade2 : [0],[0],1,1,0 -=[-1] 1,{($1+1)*50}%,{($2+1)*50}% -distance[-1] 1
_gimp_compose_fade3 : [0],[0],1,1,0 -=[-1] 1,{($1+1)*50}%,{($2+1)*50}% -distance[-1] 1 -*[-1] {0.01+$3/2} -cos[-1]
_gimp_compose_fade4 : [0],[0],1,1,"((x-w*($1+0.5))*(y-h*($2+0.5)))%(0.2*w*h*(1.001+$3))"

#@gimp Shape average : gimp_compose_shapeaverage, gimp_compose_shapeaverage(0)
#@gimp : Preserve shading = bool(1)
#@gimp : Transparency = bool(0)
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
gimp_compose_shapeaverage :
  -to_rgb
  -repeat {int(@#/2)}
    -rv[-2,-1]
    -if $1 -i[0] [-1] -endif
    -t[-1] 50% -compose_shapeaverage[-2,-1]
    -if $1 -*[0,-1] -/[0] 255 -mv[0] @# -endif
    -if $2 -to_rgba[-1] -replace_color[-1] 0,0,0,0,0,255,0,0,0,0 -endif
  -mv[-1] 0 -done

#@gimp Edges merging : compose_edges, compose_edges(0)
#@gimp : Smoothness = float(0.8,0,5)
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}

#@gimp Transparent difference : gimp_transparent_diff, gimp_transparent_diff(1)
#@gimp : Threshold = float(1,0,100)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Opaque pixels = choice(0,"From 1st layer","From 2nd layer")
#@gimp : Transparent pixels = choice(1,"From same values","From different values")
gimp_transparent_diff :
  -repeat {int(@#/2)}
    -if $3
      --[-2] [-1] -norm[-2] -blur[-2] $2% -t[-2] $1% -rv[-2,-1]
    -else
      --[-1] [-2] -norm[-1] -blur[-1] $2% -t[-1] $1%
    -endif
    -if {!$4} -negative[-1] -endif
    -to_rgba[-2] -*[-2,-1]
  -mv[-1] 0 -done

#@gimp Layers alignment : gimp_align_layers, gimp_align_layers_preview
#@gimp : Alignment type = choice(0,"Rigid","Non-rigid")
#@gimp : Smoothness = float(0.7,0,1)
#@gimp : Scales = choice(0,"Auto","1","2","3","4","5","6","7","8")
gimp_align_layers :
  -remove_opacity
  -if $1 -register_nonrigid $2,0.1,$3
  -else ($2) -*[-1] 3 -register_rigid[0--2] @-1 -rm[-1]
  -endif

gimp_align_layers_preview :
  -gimp_align_layers $1,$2,0 -compose_edges 0.1

#@gimp Layers morphing : gimp_morph, gimp_no_preview
#@gimp : Frames = _int(10,2,100)
#@gimp : Smoothness = _float(0.2,0,2)
#@gimp : Precision = _float(0.1,0,2)
gimp_morph :
  -to_rgb -morph $1,$2,$3

#@gimp Tiles to layers : split_tiles, gimp_split_tiles(1)
#@gimp : X-tiles = int(3,1,100)
#@gimp : Y-tiles = int(3,1,100)
#@gimp : Homogeneous tiles = _bool(false)
gimp_split_tiles :
  -split_tiles $1,$2,$3 -k[50%]

#@gimp Layers to tiles : append_tiles, gimp_append_tiles_preview(1)
#@gimp : X-tiles = int(3,1,100)
#@gimp : Y-tiles = int(3,1,100)
gimp_append_tiles_preview :
  -frame 1,1,0,0,0,255 -append_tiles $1,$2

#@gimp Split tones : gimp_split_tones, gimp_split_tones_preview(0)
#@gimp : Number of tones = int(3,2,10)
gimp_split_tones :
  -repeat @#
    --tones[-1] $1 -r[-$1--1] [-{$1+1}] -*[-$1--1] [-{$1+1}] -rm[-{$1+1}]
  -mv[-$1--1] 0 -done

gimp_split_tones_preview :
  -gimp_split_tones $1 -a x

#@gimp _<b>Lights &amp; Shadows</b>
#----------------------------------


#@gimp Drop shadow : gimp_drop_shadow, gimp_drop_shadow(1)
#@gimp : X-shadow = float(3,-20,20)
#@gimp : Y-shadow = float(3,-20,20)
#@gimp : Smoothness = float(1.8,0,5)
#@gimp : Angle = float(0,0,360)
gimp_drop_shadow :
  -drop_shadow $1%,$2%,$3% -rotate $4,0

#@gimp Shadow patch : gimp_shadow_patch, gimp_shadow_patch(1)
#@gimp : Opacity = float(0.7,0,1)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
gimp_shadow_patch :
  -apply_channels "-shadow_patch $1",$2,0

#@gimp Light patch : gimp_light_patch, gimp_light_patch(0)
#@gimp : Density = int(5,2,30)
#@gimp : Darkness = float(0.7,0,1)
#@gimp : Lightness = float(2.5,1,4)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
gimp_light_patch :
  -apply_channels "-light_patch $1,$2,$3",$4,0

#@gimp Relief light : gimp_light_relief, gimp_light_relief(1)
#@gimp : Ambient lightness = float(0.3,0,5)
#@gimp : Specular lightness = float(0.2,0,2)
#@gimp : Specular size = float(0.2,0,1)
#@gimp : Darkness = float(0,0,1)
#@gimp : Light smoothness = float(0.5,0,5)
#@gimp : X-light = float(0.5,0,1)
#@gimp : Y-light = float(0.5,0,1)
#@gimp : Z-light = float(5,0,20)
#@gimp : Z-scale = float(0.5,0,3)
#@gimp : Opacity as bumpmap = bool(0)
#@gimp : Image smoothness = float(0,0,10)
gimp_light_relief :
  -blur $11% -light_relief ${1-10}


#@gimp _<b>Patterns</b>
#-----------------------


#@gimp Stencil : gimp_stencil, gimp_stencil_preview(0)
#@gimp : Radius = float(3,0,10)
#@gimp : Smoothness = float(0,0,30)
#@gimp : Iterations = int(8,1,100)
#@gimp : Aliasing = float(0,0,5)
#@gimp : Stencil type = choice(0,"Black & White","Shaded","Color")
#@gimp : Transparency = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")gimp_stencil :
gimp_stencil :
  -v -
  -if {$5==0}    # B&W stencil
    -norm -stencil $1,$2,$3

  -elif {$5==1}  # Shaded stencil
    -stencil $1,$2,$3

  -else          # Color stencil
    -repeat @#
      --luminance[-1] -stencil[-1] $1,$2,$3 -t[-1] 50% -_stencil
    -mv[-1] 0 -done
  -endif
  -if $6 -to_rgba -replace_color 0,0,0,0,0,255,0,0,0,0 -endif
  -if $4 -smooth {30*$4},0,1,1 -endif


_stencil :
  -*[-1] -65535 -to_colormode[-1] @{-2,s}
  -p[0] 0 -p[1] {sqrt(w*h*d)/2.5} -do # Start random filling (fast).
    ({?(w)},{?(h)},{?(d)})
    -if {@{-2,(@-1)}==-65535} -flood[-2] @{-1,0-2},0,1,@{-3,(@{-1,0-2},0)},@{-3,(@{-1,0-2},1)},@{-3,(@{-1,0-2},2)} -p=[0] 0
    -else -p=[0] {~0+1} -endif
    -rm[-1] -if {~0>~1} -b -endif
  -while 1 -pp[0,1]
  -do   # Complete with deterministic filling (slower).
    (@{-1,c})
    -if {@{-2,(@-1)}==-65535} -flood[-2] @{-1,0-2},0,1,@{-3,(@{-1,0-2},0)},@{-3,(@{-1,0-2},1)},@{-3,(@{-1,0-2},2)}
    -else -rm[-1] -b -endif
    -rm[-1]
  -while 1
  -rm[-2]

gimp_stencil_preview :
  -gimp_split_preview "-gimp_stencil ${1--2}",$-1

#@gimp Dots : gimp_dots, gimp_dots_preview(0)
#@gimp : Number of scales = int(10,1,20)
#@gimp : Resolution = float(10,1,100)
#@gimp : Radius = float(3,0.1,10)
#@gimp : Stencil type = choice(0,"Black & White","Shaded","Color")
#@gimp : Transparency = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_dots :
  -v -
  -if {$4==0} -luminance -dotsbw $1,$2,$3 -* 255
  -elif {$4==1} -dotsbw $1,$2,$3 -* 255
  -else
    -repeat @#
      --luminance[-1] -dotsbw[-1] $1,$2,$3 -_stencil
    -mv[-1] 0 -done
  -endif
  -if $5 -to_rgba -replace_color 0,0,0,0,0,255,0,0,0,0 -endif


gimp_dots_preview :
  -gimp_split_preview "-gimp_dots ${1--2}",$-1

#@gimp Puzzle : gimp_puzzle, gimp_puzzle_preview(0)
#@gimp : Scale = float(6,1,20)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_puzzle :
  -apply_channels "-puzzle $1",$2,0

gimp_puzzle_preview :
  -gimp_split_preview "-gimp_puzzle ${1--2}",$-1

#@gimp Mosaic : gimp_mosaic, gimp_mosaic_preview(0)
#@gimp : Density = float(1,0.1,10)
#@gimp : Keep edges = bool(true)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_mosaic :
  -apply_channels "-mosaic $1,$2",$3,0

gimp_mosaic_preview :
  -gimp_split_preview "-gimp_mosaic ${1--2}",$-1

#@gimp Cracks : gimp_cracks, gimp_cracks_preview(0)
#@gimp : Density = float(1,0.1,10)
#@gimp : Amplitude = float(-80,-255,255)
#@gimp : Relief = bool(true)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_cracks :
  -apply_channels "-cracks $1,$2,$3",$4,0

gimp_cracks_preview :
  -gimp_split_preview "-gimp_cracks ${1--2}",$-1

#@gimp Whirls : gimp_whirls, gimp_whirls_preview(0)
#@gimp : Density = int(7,3,20)
#@gimp : Smoothness = float(2,0,10)
#@gimp : Darkness = float(0.2,0,1)
#@gimp : Lightness = float(1.8,1,3)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_whirls :
  -apply_channels "-whirls $1,$2,$3,$4",$5,0

gimp_whirls_preview :
  -gimp_split_preview "-gimp_whirls ${1--2}",$-1

#@gimp Paper : gimp_paper, gimp_paper_preview(0)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_paper :
  -apply_channels "-paper",$1,0

gimp_paper_preview :
  -gimp_split_preview "-gimp_paper ${1--2}",$-1

#@gimp Hearts : gimp_hearts, gimp_hearts_preview(0)
#@gimp : Density = float(10,0,100)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_hearts :
  -apply_channels "-hearts $1",$2,0

gimp_hearts_preview :
  -gimp_split_preview "-gimp_hearts ${1--2}",$-1

#@gimp Sponge : gimp_sponge, gimp_sponge_preview(0)
#@gimp : Size = int(13,3,21)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_sponge :
  -apply_channels "-sponge $1",$2,0

gimp_sponge_preview :
  -gimp_split_preview "-gimp_sponge ${1--2}",$-1

#@gimp Canvas : gimp_canvas, gimp_canvas_preview(0)
#@gimp : note = note{"<b>First direction :</b>"}
#@gimp : Amplitude = float(70,0,300)
#@gimp : Angle = float(45,0,180)
#@gimp : Sharpness = float(400,0,2000)
#@gimp : note = note{"\n<b>Second direction : </b>"}
#@gimp : Activate second direction = bool(true)
#@gimp : Amplitude = float(70,0,300)
#@gimp : Angle = float(135,0,180)
#@gimp : Sharpness = float(400,0,2000)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_canvas :
  -repeat @# -l[-1]
    -if $4
      ({cos($2*pi/180)}^{sin($2*pi/180)}) -vector2tensor[-1] -r[-1] [-2],[-2] --smooth[-2] [-1],$1 -rm[-2] -sharpen[-1] $3 -c[-1] 0,255
      ({cos($6*pi/180)}^{sin($6*pi/180)}) -vector2tensor[-1] -r[-1] [-2],[-2] -smooth[-3] [-1],$5 -rm[-1] -sharpen[-2] $7 -c[-2] 0,255 -+[-2,-1] -/[-1] 2
    -else
      ({cos($2*pi/180)}^{sin($2*pi/180)}) -vector2tensor[-1] -r[-1] [-2],[-2] -smooth[-2] [-1],$1 -rm[-1] -sharpen[-1] $3 -c[-1] 0,255
    -endif
  -endl -mv[-1] 0 -done

gimp_canvas_preview :
  -gimp_split_preview "-gimp_canvas ${1--2}",$-1


#@gimp _<b>Presets</b>
#----------------------


#@gimp PhotoComiX smoothing : gimp_anisotropic_smoothing, gimp_anisotropic_smoothing(0)
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.16,0,2)
#@gimp : Anisotropy = float(0.63,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(2.35,0,10)
#@gimp : Spatial precision = float(0.8,0.1,2)
#@gimp : Angular precision = float(30,1,180)
#@gimp : Value precision = float(2,0.1,5)
#@gimp : Interpolation = choice(0,"Nearest neighbor","Linear","Runge-Kutta")
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("RGB","Luminance","Blue & Red chrominances","Blue chrominance","Red chrominance")
#@gimp : Tiles = int(1,1,10)
#@gimp : note = note{"\n<small><b>Note : </b>This set of anisotropic smoothing parameters has been suggested by PhotoComiX.</small>"}

#@gimp Thin brush smoothing : gimp_anisotropic_smoothing, gimp_anisotropic_smoothing(0)
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.9,0,2)
#@gimp : Anisotropy = float(0.64,0,1)
#@gimp : Gradient smoothness = float(3.1,0,10)
#@gimp : Tensor smoothness = float(1.10,0,10)
#@gimp : Spatial precision = float(0.8,0.1,2)
#@gimp : Angular precision = float(30,1,180)
#@gimp : Value precision = float(2,0.1,5)
#@gimp : Interpolation = choice(0,"Nearest neighbor","Linear","Runge-Kutta")
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("RGB","Luminance","Blue & Red chrominances","Blue chrominance","Red chrominance")
#@gimp : Tiles = int(1,1,10)
#@gimp : note = note{"\n<small><b>Note : </b>This set of anisotropic smoothing parameters has been suggested by PhotoComiX.</small>"}

#@gimp Lylejk stencil : gimp_lylejk_stencil, gimp_lylejk_stencil(0)
#@gimp : Amplitude = int(5,1,10)
#@gimp : Sharpness = float(10,0,100)
#@gimp : Radius = float(3,0,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
gimp_lylejk_stencil :
  -apply_channels "-repeat $1 -blur $3 -unsharp $3,$2 -c 0,255 -mv[-1] 0 -done",$4,0


#@gimp _<b>Rendering</b>
#------------------------

# Generic function to render a 3d image, with usual rendering parameters :
# $1 = Width
# $2 = Height
# $3 = Object size
# $4 = X-angle
# $5 = Y-angle
# $6 = Z-angle
# $7 = FOV
# $8 = X-light
# $9 = Y-light
# $10 = Z-light
# $11 = Specularity
# $12 = Shininess
# $13 = Rendering mode.
gimp_render3d :
  -n3d -c3d -m3d $13 f3d={0.5*max($1,$2)/tan($7*pi/360)}
  -f3d $f3d -l3d {$8*$f3d},{$9*$f3d},{$10*$f3d} -sl3d $11 -ss3d $12
  -repeat @# -l[~>]
    -*3d {$3*max($1,$2)} -rot3d 0,0,1,$6 -rot3d 0,1,0,$5 -rot3d 1,0,0,$4
    $1,$2,1,3,-1 -object3d[-1] [-2],50%,50% -rm[-2]
    -to_rgba -replace_color 0,0,-1,-1,-1,255,0,0,0,0
  -endl -done

#@gimp 3d elevation : gimp_elevation3d, gimp_elevation3d_preview(1)
#@gimp : Factor = float(100,-1000,1000)
#@gimp : Smoothness = float(1,0,10)
#@gimp : sep = separator()
#@gimp : Width = _int(1024,8,4096)
#@gimp : Height = _int(1024,8,4096)
#@gimp : Size = float(0.8,0,3)
#@gimp : X-angle = float(25,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(21,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : Rendering = choice(2,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : sep = separator(), note = note{"<small><b>Note :</b> Add a top layer to define object texture.</small>"}
_gimp_elevation3d :
  -repeat {@#/2} -l[~>,{min(~>+1,@#-1)}]
    -if {@#==1} --norm -else -r[1] [0],3 -endif
    -n[1] 0,$1 -blur[1] $2
    -elevation3d[0] [1] -rm[1]
  -endl -done
  -db3d 1

gimp_elevation3d :
  -_gimp_elevation3d ${1-2} -gimp_render3d ${3--1}

gimp_elevation3d_preview :
  -gimp_elevation3d ${1-2},{w},{h},${5--1}

#@gimp 3d image object : gimp_imageobject3d, gimp_imageobject3d_preview(1)
#@gimp : Type = choice{1,"Plane","Cube","Pyramid","Sphere","Torus","Gyroid","Weird","Cup"}
#@gimp : sep = separator()
#@gimp : Width = _int(1024,1,4096)
#@gimp : Height = _int(1024,1,4096)
#@gimp : Size = float(0.5,0,3)
#@gimp : X-angle = float(57,0,360)
#@gimp : Y-angle = float(41,0,360)
#@gimp : Z-angle = float(21,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
_gimp_imageobject3d :
  -to_rgb -repeat @# -l[~>] -_gimp_imageobject3d$1$2 -endl -done
  -db3d 0

gimp_imageobject3d :
  -_gimp_imageobject3d "_",$1 -gimp_render3d ${2--1}

gimp_imageobject3d_preview :
  w={w} h={h} -_gimp_imageobject3d "_preview_",$1 -gimp_render3d $w,$h,${4--1}

_gimp_imageobject3d_0 : -imageplane3d
_gimp_imageobject3d_1 : -imagecube3d
_gimp_imageobject3d_2 : -imagepyramid3d
_gimp_imageobject3d_3 : -imagesphere3d
_gimp_imageobject3d_4 : -torus3d 100 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_5 : -gyroid3d 24 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_6 : -weird3d 32 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_7 : -cup3d 0.7 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_preview_0 : -imageplane3d
_gimp_imageobject3d_preview_1 : -imagecube3d
_gimp_imageobject3d_preview_2 : -imagepyramid3d
_gimp_imageobject3d_preview_3 : -sphere3d 1,2 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_preview_4 : -torus3d 100 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_preview_5 : -gyroid3d 8 -c3d[-1] -n3d[-1] -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_preview_6 : -weird3d 12 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_preview_7 : -cup3d 0.3 -n3d[-1] -t3d[-1] [-2] -rm[-2]

#@gimp 3d lathing : gimp_lathing3d, gimp_lathing3d_preview(1)
#@gimp : Resolution = int(76,1,1024)
#@gimp : Smoothness = float(0.6,0,3)
#@gimp : Max angle = float(361,0,361)
#@gimp : sep = separator()
#@gimp : Width = _int(1024,1,4096)
#@gimp : Height = _int(1024,1,4096)
#@gimp : Size = float(0.5,0,3)
#@gimp : X-angle = float(57,0,360)
#@gimp : Y-angle = float(41,0,360)
#@gimp : Z-angle = float(21,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : sep = separator(), note = note{"<small><b>Note :</b> Add a top layer to define object texture.</small>"}
_gimp_lathing3d :
  -repeat {@#/2} -l[~>,{min(~>+1,@#-1)}]
    -lathe3d[-1] $1,$2%,$3
    -if {@#==2} -t3d[-1] [-2] -rm[-2] -endif
  -endl -done
  -db3d 0

gimp_lathing3d :
  -_gimp_lathing3d ${1-3} -gimp_render3d ${4--1}

gimp_lathing3d_preview :
  -gimp_lathing3d ${1-3},{w},{h},${6--1}

#@gimp 3d extrusion : gimp_extrude3d, gimp_extrude3d_preview(1)
#@gimp : Depth = float(10,1,256)
#@gimp : Resolution = int(512,1,1024)
#@gimp : Smoothness = float(0.6,0,3)
#@gimp : sep = separator()
#@gimp : Width = _int(1024,1,4096)
#@gimp : Height = _int(1024,1,4096)
#@gimp : Size = float(0.5,0,3)
#@gimp : X-angle = float(57,0,360)
#@gimp : Y-angle = float(41,0,360)
#@gimp : Z-angle = float(21,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : sep = separator(), note = note{"<small><b>Note :</b> Add a top layer to define object texture.</small>"}
_gimp_extrude3d :
  -repeat {@#/2} -l[~>,{min(~>+1,@#-1)}]
    -extrude3d[-1] $1,$2,$3%
    -if {@#==2} -t3d[-1] [-2] -rm[-2] -endif
  -endl -done
  -db3d 0

gimp_extrude3d :
  -_gimp_extrude3d ${1-3} -gimp_render3d ${4--1}

gimp_extrude3d_preview :
  -gimp_extrude3d ${1-3},{w},{h},${6--1}

#@gimp 3d random objects : gimp_random3d, gimp_random3d(1)
#@gimp : Type = choice("Cube","Cone","Cylinder","Sphere","Torus")
#@gimp : Density = int(50,1,300)
#@gimp : Size = float(3,1,20)
#@gimp : Z-range = float(100,0,300)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : Rendering = choice(3,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : Opacity = float(1,0,1)
gimp_random3d :
  -m3d $11 -db3d 0
  -repeat @# -l[~>]
    f3d={0.5*max(w,h)/tan($5*pi/360)} -f3d $f3d -l3d {$6*$f3d},{$7*$f3d},{$8*$f3d} -sl3d $9 -ss3d $10
    -to_rgb ({w},{h},{d},{s}) -/[-1] 2 -repeat $2
    (@{1,0}) -+[-1] @{1,1} -*[-1] $3 -/[-1] 100 -_gimp_random3d$1 @-1 -rm[-2]
    -rot3d[-1] 1,1,0,{?(0,360)}
    ({?(-1,1)}) -*[-1] @{1,0} ({?(-1,1)}) -*[-1] @{1,1}
    -+3d[-3] @-2,@-1,{?(-$4,$4)} -rm[-2,-1]
    -col3d[-1] {?(255)},{?(255)},{?(255)} -done -+3d[2--1] -object3d[0] [-1],50%,50%,0,$12,1
    -k[0]
  -endl -done

_gimp_random3d0 : -box3d $1
_gimp_random3d1 : ($1) -/[-1] 2 -cone3d @-1,$1 -rm[-2]
_gimp_random3d2 : ($1) -/[-1] 2 -cylinder3d @-1,$1 -rm[-2]
_gimp_random3d3 : -sphere3d $1,2
_gimp_random3d4 : ($1) -/[-1] 3 -torus3d $1,@-1 -rm[-2]

#@gimp Mandelbrot / Julia sets : gimp_mandelbrot, gimp_mandelbrot_preview
#@gimp : X-center = float(0,-2,2)
#@gimp : Y-center = float(0,-2,2)
#@gimp : Zoom = float(0,0,100)
#@gimp : Iterations = int(128,1,512)
#@gimp : Fractal set = choice(Mandelbrot, Julia)
#@gimp : X-seed (Julia) = text("0.317")
#@gimp : Y-seed (Julia) = text("0.03")
#@gimp : Color 1 = color(0,0,255)
#@gimp : Color 2 = color(0,255,0)
#@gimp : Color 3 = color(255,0,0)
#@gimp : Color 4 = color(255,0,255)
gimp_mandelbrot :
  (0^0^0) ($8^$9^$10) ($11^$12^$13) ($14^$15^$16) ($17^$18^$19)
  -a[-4--1] x -r[-1] $4,1,1,3,3 -a[-2,-1] x -mv[-1] 0
  -repeat {@#-1}
    -p {w},{h} -rm[-1] ~-1 -pp[-1]
    -mandelbrot[-1] {$1-2/(1+$3)},{$2-2/(1+$3)},{$1+2/(1+$3)},{$2+2/(1+$3)},$4,$5,{if($5,$6,0)},{if($5,$7,0)}
    -map[-1] [0]
  -mv[-1] 1 -done -rm[0]

gimp_mandelbrot_preview :
  -gimp_mandelbrot ${^0}
  -line 0,50%,100%,50%,0.5,255
  -line 50%,0,50%,100%,0.5,255

#@gimp Chessboard : gimp_chessboard, gimp_chessboard_preview(0)
#@gimp : First size = int(64,1,512)
#@gimp : Second size = int(64,1,512)
#@gimp : First offset = int(0,0,512)
#@gimp : Second offset = int(0,0,512)
#@gimp : Angle = float(0,0,180)
#@gimp : Opacity = float(0.5,0,1)
#@gimp : First color = color(0,0,0,255)
#@gimp : Second color = color(255,255,255,255)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
gimp_chessboard :
  -to_rgba -chessboard ${1--1}

gimp_chessboard_preview :
  -gimp_split_preview "-gimp_chessboard ${1--2}",$-1

#@gimp Polka dots : gimp_polka_dots, gimp_polka_dots(1)
#@gimp : Size = float(80,0,100)
#@gimp : Density = float(20,0.1,100)
#@gimp : First offset = float(50,0,100)
#@gimp : Second offset = float(50,0,100)
#@gimp : Angle = float(0,0,180)
#@gimp : Aliasing = float(0.5,0.1,1)
#@gimp : Shading = float(0.1,0.1,1)
#@gimp : Opacity = float(1,0,1)
#@gimp : Color = color(255,0,0,255)
gimp_polka_dots :
  -to_rgba -polka_dots {$1*$2/100},${2--1}

#@gimp Rainbow : gimp_rainbow, gimp_rainbow
#@gimp : Left position = float(80,0,100)
#@gimp : Right position = float(80,0,100)
#@gimp : Left slope = float(175,0,400)
#@gimp : Right slope = float(175,0,400)
#@gimp : Thinness = float(3,0.1,8)
#@gimp : Opacity = float(80,0,199)
gimp_rainbow :
  -channels 0 -f 0
  -spline 0,$1%,100,{-$3}%,100%,$2%,100,$4%,1,1
  -flood 0,0,0,0,1,1 -flood {w-1},0,0,0,1,1
  -distance 0 -c 0,255 -n 0,{$5*255}
  -rainbow_lut --luminance[-1] -c[-1] 0,{min(100,200-$6)}% -n[-1] 0,255 -a[-2,-1] c
  -map[0--2] [-1] -rm[-1]
  -if {$6<100} -repeat @# -sh[~>] 3,3 -*[-1] {$6/100} -rm[-1] -done -endif

#@gimp Sierpinski triangle : sierpinski, sierpinski(1)
#@gimp : Recursions = int(6,0,10)
#@gimp : 1st X-coord = float(50,0,100)
#@gimp : 1st Y-coord = float(0,0,100)
#@gimp : 2nd X-coord = float(0,0,100)
#@gimp : 2nd Y-coord = float(100,0,100)
#@gimp : 3rd X-coord = float(100,0,100)
#@gimp : 3rd Y-coord = float(100,0,100)

#@gimp Snowflake : snowflake, snowflake(1)
#@gimp : Recursions = int(3,0,5)
#@gimp : 1st X-coord = float(20,0,100)
#@gimp : 1st Y-coord = float(70,0,100)
#@gimp : 2nd X-coord = float(80,0,100)
#@gimp : 2nd Y-coord = float(70,0,100)
#@gimp : 3rd X-coord = float(50,0,100)
#@gimp : 3rd Y-coord = float(10,0,100)
#@gimp : Opacity = float(1,0,1)
#@gimp : Color = color(255,255,255)

#@gimp Equation plot : gimp_equation_plot, gimp_equation_plot
#@gimp : Equation = text{"X*c+10*cos(X+c+?)"}
#@gimp : X-min = float(-10,-100,100)
#@gimp : X-max = float(10,-100,100)
#@gimp : Resolution = int(100,2,1024)
#@gimp : Channels = int(3,1,32)
#@gimp : Plot type = choice(2,"None","Lines","Splines","Bars")
#@gimp : Vertex type = choice(0,"None","Points","Crosses 1","Crosses 2","Circles 1","Circles 2","Square 1","Square 2")
#@gimp : sep = separator()
#@gimp : note = note("<b>Note</b> :
#@gimp : Use variable 'X' instead of 'x' in the equation to take care of X-min/max settings.
#@gimp : Variable 'c' refers to the current channel number. Reduce resolution to be able to view
#@gimp : separate graph vertices.")
gimp_equation_plot :
  -repeat @#
    w={w} h={h} -rm[-1]
    $4,1,1,$5,"X=$2+($3-$2)*x/($4-1);$1"
    -dg $w,$h,$6,$7,$2,$3
  -mv[-1] 0 -done

#@gimp _<b>Sequences</b>
#-----------------------

#gimp_animate_preview : _command,_parameters1,_parameters2,_compute_half={ 0 | 1 },_width>=0,_height>=0
# Generate a preview with start/end rendering of an animation.
gimp_animate_preview : -skip ${4=1},${5=0},${6=$5}
  -repeat @#
    -if $5 width=$5 -else width={w} -endif
    -if $6 height=$6 -else height={h} -endif
    -if $4 -s[-1] x,2 -else [-1] -endif
    -$1[-2] $2 -$1[-1] $3   # Assume this is a 1->1 filter.
    -r[-2,-1] {max(w,@{-2,w})},{max(h,@{-2,h})},1,100%,3
    -if {!$4} -columns[-2] 0,50% -columns[-1] 50%,100% -endif
    -a[-2,-1] x -r[-1] $width,$height,1,100%,2 -drgba[-1]
    -line[-1] 50%,0,50%,100%,1,0,0,0,255
    -text_outline[-1] "Start",1,0,13,1,1,255 -text_outline[-1] "End",{w-23},{h-16},13,1,1,255
  -mv[-1] 0 -done

#@gimp Polaroid : gimp_animate_polaroid, gimp_animate_polaroid_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output frames = _bool(1)
#@gimp : Output files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Frame size = int(10,1,400)
#@gimp : Bottom size = int(20,1,400)
#@gimp : X-shadow = float(0,-20,20)
#@gimp : Y-shadow = float(0,-20,20)
#@gimp : Smoothness = float(3,0,5)
#@gimp : Angle = float(0,0,360)
#@gimp : Zoom = float(1,0.01,1)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Frame size = int(10,1,400)
#@gimp : Bottom size = int(20,1,400)
#@gimp : X-shadow = float(0,-20,20)
#@gimp : Y-shadow = float(0,-20,20)
#@gimp : Smoothness = float(3,0,5)
#@gimp : Angle = float(20,0,360)
#@gimp : Zoom = float(1,0.01,1)
gimp_animate_polaroid :
  -if $3 -p "$4/gmic_polaroid.png" -else -p "" -endif
  -animate gimp_polaroid,"${5-11}",\
                         "${12-18}",$1,$2,~-1
  -r @{"-max_whds"},0,0,0.5,0.5

gimp_animate_polaroid_preview :
  -gimp_animate_preview gimp_polaroid,"${5-11}",\
                                      "${12-18}",0

#@gimp Edges : gimp_animate_edges, gimp_animate_edges_preview(0)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output frames = _bool(1)
#@gimp : Output files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Negative colors = bool(0)
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Smoothness = float(0,0,10)
#@gimp : Edge threshold = float(10,0,30)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Smoothness = float(0,0,10)
#@gimp : Edge threshold = float(30,0,30)
gimp_animate_edges :
  -if $3 -p "$4/gmic_edges.png" -else -p "" -endif
  -animate gimp_edges,"${6-7},$5",\
                      "${8-9},$5",$1,$2,~-1

gimp_animate_edges_preview :
  -gimp_animate_preview gimp_edges,"${6-7},$5",\
                                   "${8-9},$5"

#@gimp Cartoon : gimp_animate_cartoon, gimp_animate_cartoon_preview(0)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output frames = _bool(1)
#@gimp : Output files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Color quantization = int(4,2,256)
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Smoothness = float(0.5,0,2)
#@gimp : Sharpening = float(200,0,400)
#@gimp : Edge threshold = float(10,1,30)
#@gimp : Edge thickness = float(0.1,0,1)
#@gimp : Color strength = float(1.5,0,3)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Smoothness = float(3,0,2)
#@gimp : Sharpening = float(200,0,400)
#@gimp : Edge threshold = float(10,1,30)
#@gimp : Edge thickness = float(0.1,0,1)
#@gimp : Color strength = float(1.5,0,3)
gimp_animate_cartoon :
  -if $3 -p "$4/gmic_cartoon.png" -else -p "" -endif
  -animate cartoon,"${6-10},$5",\
                   "${11-15},$5",$1,$2,~-1

gimp_animate_cartoon_preview :
  -gimp_animate_preview cartoon,"${6-10},$5",\
                                "${11-15},$5"

#@gimp B&amp;W stencil : gimp_animate_stencilbw, gimp_animate_stencilbw_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output frames = _bool(1)
#@gimp : Output files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Edge threshold = float(10,0,30)
#@gimp : Smoothness = float(10,0,30)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Edge threshold = float(10,0,30)
#@gimp : Smoothness = float(20,0,30)
gimp_animate_stencilbw :
  -if $3 -p "$4/gmic_stencilbw.png" -else -p "" -endif
  -animate stencilbw,"${5-6}",\
                     "${7-8}",$1,$2,~-1

gimp_animate_stencilbw_preview :
  -gimp_animate_preview stencilbw,"${5-6}",\
                                  "${7-8}"

#@gimp B&amp;W pencil : gimp_animate_pencilbw, gimp_animate_pencilbw_preview(0)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output frames = _bool(1)
#@gimp : Output files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Pencil type = float(2.3,0,5)
#@gimp : Amplitude = float(100,0,200)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Pencil type = float(0.3,0,5)
#@gimp : Amplitude = float(60,0,200)
gimp_animate_pencilbw :
  -if $3 -p "$4/gmic_pencilbw.png" -else -p "" -endif
  -animate pencilbw,"${5-6}",\
                    "${7-8}",$1,$2,~-1

gimp_animate_pencilbw_preview :
  -gimp_animate_preview pencilbw,"${5-6}",\
                                 "${7-8}"

#@gimp Soft glow : gimp_animate_glow, gimp_animate_glow_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Amplitude = float(0,0,8)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Amplitude = float(3,0,8)
gimp_animate_glow :
  -if $3 -p "$4/gmic_glow.png" -else -p "" -endif
  -animate glow,"$5",\
                "$6",$1,$2,~-1

gimp_animate_glow_preview :
  -gimp_animate_preview glow,"$5",\
                             "$6"

#@gimp Morphological filter : gimp_animate_morpho, gimp_animate_morpho_preview(0)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Action = choice("Erosion","Dilation","Opening","Closing",
#@gimp : "Original - Erosion","Dilation - Original","Original - Opening","Closing - Original")
#@gimp : Invert colors = bool(false)
#@gimp : Shape = choice(0,"Square","Octagonal","Circular")
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Size = int(5,1,100)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Size = int(50,2,100)
gimp_animate_morpho :
  -if $3 -p "$4/gmic_morpho.png" -else -p "" -endif
  -animate gimp_morpho,"$5,$8,$6,$7,0,1",\
                       "$5,$9,$6,$7,0,1",$1,$2,~-1

gimp_animate_morpho_preview :
  -gimp_animate_preview gimp_morpho,"$5,$8,$6,$7,0,1",\
                                    "$5,$9,$6,$7,0,1"

#@gimp Anisotropic smoothing : gimp_animate_anisotropic_smoothing, gimp_animate_anisotropic_smoothing_preview(0)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Spatial precision = float(0.8,0.1,2)
#@gimp : Angular precision = float(30,1,180)
#@gimp : Value precision = float(2,0.1,5)
#@gimp : Interpolation type = choice(0,"Nearest neighbor","Linear","Runge-Kutta")
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Alpha")
#@gimp : Tile subdivisions = int(1,1,10)
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.7,0,2)
#@gimp : Anisotropy = float(0.3,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.7,0,2)
#@gimp : Anisotropy = float(0.3,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
gimp_animate_anisotropic_smoothing :
  -if $3 -p "$4/gmic_anisotropic_smoothing.png" -else -p "" -endif
  -animate gimp_anisotropic_smoothing,"${13-17},${5-12}",\
                                      "${18-22},${5-12}",$1,$2,~-1

gimp_animate_anisotropic_smoothing_preview :
  -gimp_animate_preview gimp_anisotropic_smoothing,"${13-17},${5-12}",\
                                                   "${18-22},${5-12}",0

#@gimp 3d image object : gimp_animate_imageobject3d, gimp_animate_imageobject3d_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Type = choice{1,"Plane","Cube","Pyramid","Sphere","Torus","Gyroid","Weird","Cup"}
#@gimp : Width = _int(1024,1,4096)
#@gimp : Height = _int(1024,1,4096)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Size = float(0.5,0,3)
#@gimp : X-angle = float(57,0,360)
#@gimp : Y-angle = float(41,0,360)
#@gimp : Z-angle = float(21,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Size = float(0.5,0,3)
#@gimp : X-angle = float(57,0,1440)
#@gimp : Y-angle = float(401,0,1440)
#@gimp : Z-angle = float(21,0,1440)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
gimp_animate_imageobject3d :
  -if $3 -p "$4/gmic_imageobject3d.png" -else -p "" -endif
  -_gimp_imageobject3d "_",$5
  -animate gimp_render3d,"${6-7},${9-18},$8",\
                         "${6-7},${19-28},$8",$1,$2,~-1

gimp_animate_imageobject3d_preview :
  w={w} h={h}
  -_gimp_imageobject3d "_preview_",$5
  -gimp_animate_preview gimp_render3d,$w","$h",${9-18},$8",\
                                      $w","$h",${19-28},$8",0,$w,$h

#@gimp 3d elevation : gimp_animate_elevation3d, gimp_animate_elevation3d_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Factor = float(100,-1000,1000)
#@gimp : Smoothness = float(1,0,10)
#@gimp : Width = _int(1024,8,4096)
#@gimp : Height = _int(1024,8,4096)
#@gimp : Rendering = choice(2,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Size = float(0.8,0,3)
#@gimp : X-angle = float(35,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Size = float(0.8,0,3)
#@gimp : X-angle = float(35,0,1440)
#@gimp : Y-angle = float(0,0,1440)
#@gimp : Z-angle = float(360,0,1440)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
gimp_animate_elevation3d :
  -if $3 -p "$4/gmic_elevation3d.png" -else -p "" -endif
  -_gimp_elevation3d ${5-6}
  -animate gimp_render3d,"${7-8},${10-19},$9",\
                         "${7-8},${20-29},$9",$1,$2,~-1

gimp_animate_elevation3d_preview :
  w={w} h={h}
  -_gimp_elevation3d ${5-6}
  -gimp_animate_preview gimp_render3d,$w","$h",${10-19},$9",\
                                      $w","$h",${20-29},$9",0,$w,$h

#@gimp 3d extrusion : gimp_animate_extrude3d, gimp_animate_extrude3d_preview(1)
#@gimp : Frames = _int(10,2,100)
#@gimp : Output as frames = _bool(1)
#@gimp : Output as files = _bool(0)
#@gimp : Output folder = _folder()
#@gimp : note = note{"\n<b>Global parameters :</b>"}
#@gimp : Depth = float(10,1,256)
#@gimp : Resolution = int(512,1,1024)
#@gimp : Smoothness = float(0.6,0,3)
#@gimp : Width = _int(1024,8,4096)
#@gimp : Height = _int(1024,8,4096)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Size = float(0.8,0,3)
#@gimp : X-angle = float(35,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Size = float(0.8,0,3)
#@gimp : X-angle = float(35,0,1440)
#@gimp : Y-angle = float(360,0,1440)
#@gimp : Z-angle = float(0,0,1440)
#@gimp : FOV = float(45,1,90)
#@gimp : X-light = float(0,-100,100)
#@gimp : Y-light = float(0,-100,100)
#@gimp : Z-light = float(-100,-100,0)
#@gimp : Specularity = float(0.5,0,1)
#@gimp : Shininess = float(0.7,0,3)
gimp_animate_extrude3d :
  -if $3 -p "$4/gmic_extrude3d.png" -else -p "" -endif
  -_gimp_extrude3d ${5-7}
  -animate gimp_render3d,"${8-9},${11-20},$10",\
                         "${8-9},${21-30},$10",$1,$2,~-1

gimp_animate_extrude3d_preview :
  w={w} h={h}
  -_gimp_extrude3d ${5-7}
  -gimp_animate_preview gimp_render3d,$w","$h",${11-20},$10",\
                                      $w","$h",${21-30},$10",0,$w,$h

#@gimp _<b>Spectral handling</b>
#-------------------------------

#@gimp Fourier analysis : gimp_display_fft, gimp_display_fft(1)
gimp_display_fft :
  -to_rgb -display_fft

#@gimp Fourier transform : gimp_fourier, gimp_fourier_preview(1)
#@gimp : Transform = choice(0,"Direct","Inverse")
gimp_fourier :
  -if $1 -fft82float -c 0,255
  -else -float2fft8
  -endif

gimp_fourier_preview :
  -if $1 -gimp_no_preview 0
  -else -dfft
  -endif

#@gimp Fourier watermark : gimp_watermark_fourier, _none_
#@gimp : Text = text("\251 G'MIC")
#@gimp : Size = int(57,13,128)
#@gimp : sep = separator()
#@gimp : note = note("<small><b>Note : </b> To make the watermark visible afterwards, use the 'Fourier Analysis' filter. </small>")
gimp_watermark_fourier :
  -watermark_fourier "$1",$2 -c 0,255

#@gimp Frequency merging : gimp_compose_freq, gimp_compose_freq(1)
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter needs two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
gimp_compose_freq :
  -repeat {int(@#/2)}
    --[-1] 128 -*[-1] 2 -+[-2,-1] -c[-1] 0,255
  -mv[-1] 0 -done

#@gimp Frequency splitting : gimp_split_freq, gimp_split_freq_preview(1)
#@gimp : Smoothness = float(3,0,20)
#@gimp : Note = note{"<small><b>Note :</b>
#@gimp : This filter splits an image layer into two layers, one containing the low frequencies (colors), the other with the high frequencies (contours). You can thus process each layer separately, then recompose them with the previous <b>Frequency merging</b> filter.
#@gimp : </small>"}
gimp_split_freq_preview :
  -gimp_split_freq $1 -k[0,1] -a x

gimp_split_freq :
  -repeat @#
    --blur[-1] $1 --[-2] [-1] -/[-2] 2 -+[-2] 128 -rv[-2,-1]
  -mv[-2,-1] 0 -done


#@gimp _<b>Various</b>
#----------------------


#@gimp Histogram analysis : _none_, gimp_display_histogram(1)
#@gimp : Clusters = int(256,2,256)
#@gimp : Monochrome = bool(0)
gimp_display_histogram :
  -to_rgb -if $2 -luminance -endif
  -repeat @#
    -display_histogram[-1] {w},{h},$1,255
  -mv[-1] 0 -done

#@gimp Import data : gimp_import_image, gimp_no_preview
#@gimp : Filename = file()
#@gimp : Normalize = bool(1)
#@gimp : note = note{"\n<small><b>Note : </b>
#@gimp : This filter can import any image data read by the <b>G'MIC</b> language interpreter.
#@gimp : It includes exotic formats as : <i>Pandore, CImg, Inrimage, AVI/MPEG (requires FFMPEG installed), ...</i>
#@gimp : </small>"}
gimp_import_image :
  -rm -i "$1" -s z -if $2 -n 0,255 -else -c 0,255 -endif

#@gimp Custom G'MIC command : gimp_custom_command, gimp_custom_command
#@gimp : Command = text("-to_rgb --deform 20 -compose_edges 3")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : Enable channel processing = bool(0)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : note = note{"\n<small><b>Note : </b>
#@gimp : This filter can execute any set of instructions understood by the <b>G'MIC</b> language interpreter.
#@gimp : Here, you can then test some commands before creating your own G'MIC custom commands and GIMP menu entries.\n\n
#@gimp : Please look at the documentation reference web page :</small>"}
#@gimp : note = link("http://gmic.sourceforge.net/reference.shtml")
#@gimp : note = note{"<small>
#@gimp : to learn more about available <b>G'MIC</b> commands.
#@gimp : </small>"}
gimp_custom_command : -skip "${1=-return}"
  -if $3
    -apply_channels "$1",$4,$2
  -else
    $1 -if $2 -n 0,255 -else -c 0,255 -endif
  -endif

#@gimp Quick copyright : gimp_quick_copyright, gimp_quick_copyright(0)
#@gimp : Text = text("\251 G'MIC")
#@gimp : Size = int(24,13,128)
#@gimp : Color = color(255,255,255,128)
#@gimp : Outline = int(1,0,4)
#@gimp : Position = choice(3,"Up-left","Up-right","Bottom-left","Bottom-right")
#@gimp : Offset = int(5,0,40)
#@gimp : Orientation = choice(1,"-90 deg.","0 deg.","+90 deg.","+180 deg.")
gimp_quick_copyright :
  -i[0] 1 -text[0] "$1",0,0,$2,1,$3,$4,$5 -autocrop[0] 0 -r[0] {@{0,w}+2*$7},{@{0,h}+2*$7},1,3,0,0,0.5,0.5
  -i[1] 1 -text[1] "$1",0,0,$2,1,1 -autocrop[1] 0 -r[1] {@{1,w}+2*$7},{@{1,h}+2*$7},1,1,0,0,0.5,0.5 -dilate[1] {1+2*$7}
  -rotate[0,1] {90*($10-1)}
  -repeat {@#-2}
  -if {$8==0} -image[-1] [0],$9,$9,0,0,{$6/255},[1]
  -elif {$8==1} -image[-1] [0],{w-1-@{0,w}-$9},$9,0,0,{$6/255},[1]
  -elif {$8==2} -image[-1] [0],$9,{h-1-@{0,h}-$9},0,0,{$6/255},[1]
  -else -image[-1] [0],{w-1-@{0,w}-$9},{h-1-@{0,h}-$9},0,0,{$6/255},[1]
  -endif
  -mv[-1] 2 -done
  -rm[0,1]

#@gimp Do nothing : gimp_do_nothing, gimp_do_nothing
#@gimp : note = note("<b>Note</b> : This filters does nothing on the image. Use it to manipulate layers in cunjunction with the input/output options of the G'MIC plug-in.")
gimp_do_nothing :
  -return

#@gimp <b>Experimental</b>
#--------------------------

#@gimp Anisotropic smoothing (16bits) : gimp_anisotropic_smoothing16, gimp_anisotropic_smoothing16_preview(0)
#@gimp : Input image = file()
#@gimp : Output image = text("gmic_anisotropic16.png")
#@gimp : note = note("\n<b>Filter parameters :</b>")
#@gimp : Amplitude = float(60,0,1000)
#@gimp : Sharpness = float(0.7,0,2)
#@gimp : Anisotropy = float(0.3,0,1)
#@gimp : Gradient smoothness = float(0.6,0,10)
#@gimp : Tensor smoothness = float(1.1,0,10)
#@gimp : Spatial precision = float(0.8,0.1,2)
#@gimp : Angular precision = float(30,1,180)
#@gimp : Value precision = float(2,0.1,5)
#@gimp : Interpolation = choice(0,"Nearest neighbor","Linear","Runge-Kutta")
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : Tiles = int(1,1,10)
gimp_anisotropic_smoothing16 :
  -rm -i $1 -/ 256
  -gimp_anisotropic_smoothing ${3--1}
  -* 256 -if {narg($2)} -o $2 -endif -/ 256

gimp_anisotropic_smoothing16_preview :
  -i $1 -crop[-1] {max(0,(w-@{-2,w})/2)},{max(0,(h-@{-2,h})/2)},{min(w-1,(w+@{-2,w})/2)},{min(h-1,(h+@{-2,h})/2)} -rm[0--2] -/ 256
  -gimp_anisotropic_smoothing ${3--1}

#@gimp Patch-based smoothing (16bits) : gimp_patch_smoothing16, gimp_patch_smoothing16_preview(0)
#@gimp : Input image = file()
#@gimp : Output image = text("gmic_patch16.png")
#@gimp : note = note("\n<b>Filter parameters :</b>")
#@gimp : Spatial variance = float(10,0.1,200)
#@gimp : Patch variance = float(10,0.1,200)
#@gimp : Patch size = int(3,2,21)
#@gimp : Lookup size = int(5,2,21)
#@gimp : Patch smoothness = float(0,0,4)
#@gimp : Fast approximation = bool(1)
#@gimp : Iterations = int(1,1,10)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
gimp_patch_smoothing16 :
  -rm -i $1 -/ 256
  -gimp_patch_smoothing ${3--1}
  -* 256 -if {narg($2)} -o $2 -endif -/ 256

gimp_patch_smoothing16_preview :
  -i $1 -crop[-1] {max(0,(w-@{-2,w})/2)},{max(0,(h-@{-2,h})/2)},{min(w-1,(w+@{-2,w})/2)},{min(h-1,(h+@{-2,h})/2)} -rm[0--2] -/ 256
  -gimp_patch_smoothing ${3--1}

#@gimp Unsharp mask (16bits) : gimp_unsharp16, gimp_unsharp16_preview(0)
#@gimp : Input image = file()
#@gimp : Output image = text("gmic_unsharp16.png")
#@gimp : note = note("\n<b>Filter parameters :</b>")
#@gimp : Sharpening type = choice(0,"Gaussian","Bilateral")
#@gimp : Spatial radius = float(1.25,0,20)
#@gimp : Bilateral radius = float(30,0,60)
#@gimp : Amount = float(3,0,10)
#@gimp : Threshold = float(0,0,20)
#@gimp : Darkness level = float(1,0,4)
#@gimp : Lightness level = float(1,0,4)
#@gimp : Iterations = int(1,1,10)
#@gimp : Negative effect = bool(0)
#@gimp : Channel(s) = choice("All","RGBA","RGB","Luminance","Blue/red chrominances","Blue chrominance","Red chrominance","Lightness","ab-components","a-component","b-component","Hue","Saturation","Value","Key","Alpha","ch-components","c-component","h-component")
#@gimp : note = note{"\n\n<small><b>Note : </b>
#@gimp : This filter is inspired by the original <i>Unsharp Mask</i> filter in GIMP, with additional parameters.
#@gimp : </small>"}
gimp_unsharp16 :
  -rm -i $1 -/ 256
  -gimp_unsharp ${3--1}
  -* 256 -if {narg($2)} -o $2 -endif -/ 256

gimp_unsharp16_preview :
  -i $1 -crop[-1] {max(0,(w-@{-2,w})/2)},{max(0,(h-@{-2,h})/2)},{min(w-1,(w+@{-2,w})/2)},{min(h-1,(h+@{-2,h})/2)} -rm[0--2] -/ 256
  -gimp_unsharp ${3--1}



#@gimp __<i>Initial G'MIC filters</i>
#-----------------------------------


#@gimp About this section : _none_, _none_
#@gimp : note = note{"
#@gimp : This section contains the implementations of all the <i>initial</i> filters,
#@gimp : <i>i.e.</i> the ones defined in the stable release archive of <b>G'MIC</b>.
#@gimp : They are kept, so that in case of updating problems, the original filters are still accessible.
#@gimp : If no entries appear below, then you did probably not update your filters definitions yet."}

# Local Variables:
# mode: sh
# End:
#
# (End of G'MIC custom commands)
