#@gmic
#
#  File        : gmic_def.gmic
#                ( G'MIC commands file )
#
#  Description : Define the set of standard G'MIC commands, as well as
#                the filters for the G'MIC plug-in for GIMP, and for the
#                web service G'MIC Online.
#                ( 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 update via Internet, a copy of this file
#                should be located in the folder :
#
#                  $HOME/.gmic_def.xxxx    (on Unix-based OS).
#                  %APPDATA/gmic_def.xxxx  (on Windows-based OS).
#
#  Copyright   : David Tschumperle
#                ( http://tschumperle.users.greyc.fr/ )
#
#  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 definition of the G'MIC custom command '-command_name'.
# - Each line starting with '#' is a comment line.
# - Any other line is considered as the continuation of a previously started G'MIC custom command.
#
#*** Specific 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 :: subsection' defines a new command subsection in the displayed help.
#      _ '#@gmic command_name : arguments_format1 : arguments_format2 : ... : (qualifier)' starts a new command description.
#      _ '#@gmic : description' add a new description line to the current command description.
#
#*** Specific 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 filters 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 :
#
#    '#@gimp Folder 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(_is_multiline={ 0 | 1 },_default text)'    : Add a single or multi-line 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.
#
#*** Specific rules for 'gmicol' (G'MIC web service) :
#
# - Same rules as for 'gmic_gimp', except that comment lines start with '#@gmicol'.
#
#-----------------------------------------------------------------------------------------------------------------------

#---------------------------------
#
#@gmic :: Global options
#
#---------------------------------

#@gmic debug : (*)
#@gmic : Activate debug mode.
#@gmic : When activated, the G'MIC interpreter becomes very verbose and outputs additionnal log
#@gmic : messages about its internal state on the standard output.
#@gmic : This option can be useful when debugging the execution of a custom command.

#@gmic h : eq. to '-help'. : (*)
h :
  -help $*

#@gmic help : _command : (no args) : (*)
#@gmic : Display help (optionally for specified command only) and exit.
#@gmic : (eq. to '-h').
help : -skip ${1=""},${2=1}
  -if {!@#} -return -endif
  -y y -a y
  --_help $1,$2 -k[0]
  -if {narg(@{})} -_help[0] @{},0 -endif
  -rm

_help : -skip ${1=""}
  -v -1
  -if {!narg("$1")} -__help ascii -v + -e[] "" -v - -rm -u "" -return -endif # Global help.
  ({'"$1"'}) -autocrop[-1] {'-'}
  -if {@{-1,100%}=={']'}" && "i!={'['}} -l[-1] -s -,{'['} -k[0] -endl -endif
  command=@{-1,t} -rm[-1]

  # Help requested for a specific command.
  ks0="0" ks1="-k[0]"
  -if $2 -__help_header_ascii[] -endif
  -r 1,{h+1},1,1,0,0,0,1
  -s +,{'"#@gmic "$command" :"'}
  -if {@#==1} -s +,{'"#@gmic "$command":"'} -endif
  -if {@#==1} -s +,{'"#@gmic "$command"\n"'} -endif
  -if {@#==1} -v + -e[] "\n[gmic] Command '"$command"' has no description. Try 'gmic -h' for global help.\n\n" -v - -rm -u "" -return -endif
  -rm[0] -a y -s -,10
  stopflag=0
  is_example=0
  -_document_gmic_header_ascii[] 0
  -repeat @# -l[$>] -if {h>7" && "{@{-1,0-5}'=='{'"#@gmic"'}}}
    -rows 7,100% -autocrop {'" "'}  # Discard '#@gmic'.
    -if {i!={':'}} # Command declaration.
      -s -,{'": "'} -autocrop {'" "'}
      -if {@{0,t}'=='$command}
        -_document_gmic_declaration_ascii
        -if $_shortcut  # Found shortcut command.
          -v + -e[] "\n    -"$command": Equivalent to '"$_shortcutlink0"'." -v -
          -u $_shortcutlink0 -return
        -endif
        -else stopflag=1
      -endif
    -else
      -rows 1,100% # Discard ':' char.
      -if {i=={':'}} stopflag=1 # Subsection
      -else
        -autocrop {'" "'}
        -if {i=={'$'}} # Example of use.
          -rows 1,100% -autocrop {'" "'} # Discard '$' character.
          -if $is_example -i[0] ({'"            "'})
          -else -i[0] ({'"\n        Example(s): "'}) is_example=1 -endif
          -y[0] y -a y
        -endif
        -_document_gmic_description_ascii 0
      -endif
    -endif
  -else stopflag=1 -endif ${ks{@#!=0}} -endl -if $stopflag -break -endif -done
  -v + -e[] "\n" -v - -rm
  -u ""

__help :
  -m "_help_section : -_help_section_$1 \"$""1\""
  -m "_help_paragraph : -_help_paragraph_$1 \"$""1\""
  -_help_header_$1[]
  -_help_usage[]
  -document_gmic $1,"img/",0
  -_help_examples[]
  -_help_footer_$1[]

# Commands to output help in latex format.
_help_header_latex :
  -if {narg($_gmic_is_beta)} strbeta=" (beta)" -else strbeta="" -endif
  -if {narg($_gmic_version)} strver=$_gmic_version -else strver=@{-strver} -endif
  -v + -e[] "\\documentclass[a4paper,11pt,twoside]{book}
\n\\usepackage{hyperref,fancyhdr,graphicx,amssymb,amsmath,times,makeidx,listings}
\n\\graphicspath{{img/}}
\n\\pagestyle{fancyplain}
\n\\lhead[\\fancyplain{}{\\textbf\\thepage}]{\\fancyplain{}{\\rightmark}}
\n\\rhead[\\fancyplain{}{\\leftmark}]{\\fancyplain{}{\\textbf\\thepage}}
\n\\cfoot{}
\n\\setlength{\\textwidth}{5.875in}
\n\\setlength{\\parindent}{0pc}
\n\\setlength{\\hoffset}{-0.8cm}
\n\\setcounter{tocdepth}{1}
\n\\sloppy{}
\n\\title{\\fbox{\\parbox{\\textwidth}{\\begin{center}\\vspace*{2cm}\\includegraphics[height=7cm]{logo2.png}\\\\\\vspace*{1cm}{\\Huge \\textbf{The Handbook}\\\\{\\small Version "$strver$strbeta"}\\\\\\vspace*{1cm}}\\end{center}}}}
\n\\author{\\Large \\bf David Tschumperl\\'e}
\n\\renewcommand\\indexname{Index of commands}
\n\\makeindex
\n\\lstset{columns=fullflexible,basicstyle=\\normalfont}
\n\\begin{document}
\n\\maketitle
\n\\tableofcontents
\n\\chapter*{Preamble}
\n\\section*{License}
\nThis document is distributed under the \\textbf{GNU Free Documentation License}, version 1.3.\\\\
\nRead the full license terms at \\texttt{http://www.gnu.org/licenses/fdl-1.3.txt}.\\\\~\\\\
\nAn online version of this documentation is available at:\\\\\\texttt{http://gmic.sourceforge.net/reference.shtml}.
\n\\section*{Motivations}
\nG'MIC stands for GREYC's Magic Image Converter. This project aims to:
\n\\begin{itemize}
\n\\item Define a lightweight but powerful script language (G'MIC) dedicated to the design of image processing pipelines.
\nProvide an interpreter of this language, distributed as a C++ open-source library embeddable in third-party applications.
\nPropose four different user interfaces for this image processing framework:
\n\\begin{itemize}
\n\\item The command-line executable gmic to use the G'MIC framework from a shell.
\nIn this setting, G'MIC may be seen as a direct (and friendly) competitor of the ImageMagick or GraphicsMagick software suites.
\n\\item The interactive and extensible plug-in gmic\\_gimp to bring G'MIC capabilities to the image retouching software GIMP.
\n\\item ZArt, a real-time interface for webcam images manipulation.
\n\\item G'MIC Online, a web service allowing users to apply G'MIC-based filters on their images, directly from a web browser.
\n\\end{itemize}
\n\\end{itemize}
\nG'MIC is focused on the design of possibly complex pipelines for converting, manipulating, filtering and visualizing generic 1d/2d/3d multi-spectral image datasets. This includes of course color images, but also more complex data as image sequences or 3d(+t) volumetric float-valued datasets.\\\\
\n
\nG'MIC is an open framework: the default language can be extended with custom G'MIC-written commands, defining thus new available image filters or effects. By the way, G'MIC already contains a substantial set of pre-defined image processing algorithms and pipelines (more than 1000).\\\\
\n
\nG'MIC has been designed with portability in mind and runs on different platforms (Windows, Unix, MacOSX). It is distributed under the CeCILL license (GPL-compatible). Since 2008, it is developed in the Image Team of the GREYC laboratory, in Caen/France, by permanent researchers working in the field of image processing on a daily basis.
\n\\section*{Version}
\n
\n gmic: GREYC's Magic Image Converter.
\n
\n        Version "$strver$strbeta", Copyright (C) 2008-2012, David Tschumperl\\'e
\n        (http://gmic.sourceforge.net)
\n\\chapter{Usage}
"
  -v -

_help_section_latex : -skip "$1"
  -v +
  -e[] "\\section{$1}"
  -v -

_help_paragraph_latex : -skip "$1"
  -v +
  -e[] "\\small"
  -e[] "\\begin{lstlisting}"
  -e[] "$1"
  -e[] "\\end{lstlisting}"
  -e[] "\\normalsize"
  -v -

_help_footer_latex :
  -v +
  -e[] "
\n\\printindex
\n~\\\\$\\square$~End of document.
\n\n\\end{document}"
  -v -

# Commands to output help in html format.
_help_header_html :
  _section=0
  -if {narg($_gmic_is_beta)} strbeta=" (beta)" -else strbeta="" -endif
  -if {narg($_gmic_version)} strver=$_gmic_version -else strver=@{-strver} -endif
  -v +
-e[] "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
\n<!--#include file=\"header.html\" -->
\n<link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\">
\n<div id=\"bloc_option\">
\n<div id=\"top_rouge\"><div id=\"text_top\">Reference</div></div>
\n<div id=\"center\"><div id=\"text_centre_intro\">
\n<h2><font color=\"brown\"><u>Preamble</u></font></h2>
\n<ul>
\n<li>This document is distributed under the <a href=\"http://www.gnu.org/licenses/fdl-1.3.txt\">GNU Free Documentation License</a>, version 1.3.</li>
\n<li>A <a href=\"gmic_reference.pdf\">.pdf version</a> of this document is available.</li>
\n</ul>
\n<h2><font color=\"brown\"><u>Table of contents</u></font></h2>
\n<ul>
\n<li><a href=\"#section0\">Version</a></li>
\n<li><a href=\"#section1\">Usage</a></li>
\n<ul>
\n<li><a href=\"#section2\">Overall context</a></li>
\n<li><a href=\"#section3\">Image definition and terminology</a></li>
\n<li><a href=\"#section4\">Items of a processing pipeline</a></li>
\n<li><a href=\"#section5\">Input data items</a></li>
\n<li><a href=\"#section6\">Command items and selections</a></li>
\n<li><a href=\"#section7\">Input/output properties</a></li>
\n<li><a href=\"#section8\">Substitution rules</a></li>
\n<li><a href=\"#section9\">Mathematical expressions</a></li>
\n<li><a href=\"#section10\">Image and data viewers</a></li>
\n<li><a href=\"#section11\">Adding custom commands</a></li>
\n</ul>
\n<li><a href=\"#section12\">List of commands</a></li>
\n<ul>
\n<li><a href=\"#subsection1\">Global options</a></li>
\n<li><a href=\"#subsection2\">Inputs/outputs</a></li>
\n<li><a href=\"#subsection3\">List manipulation</a></li>
\n<li><a href=\"#subsection4\">Mathematical operators</a></li>
\n<li><a href=\"#subsection5\">Values manipulation</a></li>
\n<li><a href=\"#subsection6\">Colors manipulation</a></li>
\n<li><a href=\"#subsection7\">Geometry manipulation</a></li>
\n<li><a href=\"#subsection8\">Filtering</a></li>
\n<li><a href=\"#subsection9\">Features extraction</a></li>
\n<li><a href=\"#subsection10\">Image drawing</a></li>
\n<li><a href=\"#subsection11\">Matrix computation</a></li>
\n<li><a href=\"#subsection12\">3d rendering</a></li>
\n<li><a href=\"#subsection13\">Program controls</a></li>
\n<li><a href=\"#subsection14\">Arrays and frames</a></li>
\n<li><a href=\"#subsection15\">Artistic</a></li>
\n<li><a href=\"#subsection16\">Warpings</a></li>
\n<li><a href=\"#subsection17\">Degradations</a></li>
\n<li><a href=\"#subsection18\">Blending and fading</a></li>
\n<li><a href=\"#subsection19\">Image sequences</a></li>
\n<li><a href=\"#subsection20\">Interactive demos</a></li>
\n<li><a href=\"#subsection21\">PINK-library operators</a></li>
\n<li><a href=\"#subsection22\">Convenience functions</a></li>
\n<li><a href=\"#subsection23\">Others</a></li>
\n<li><a href=\"#subsection24\">Commands shortcuts</a></li>
\n</ul>
\n<li><a href=\"#section13\">Examples of use</a></li>
\n</ul>
\n<a name=\"section0\"><h2><font color=\"brown\"><u>Version</u></font></h2></a>
\n<pre><font color=\"blue\">gmic</font>: GREYC's Magic Image Converter.
\n
\n       Version "$strver$strbeta", Copyright (C) 2008-2012, David Tschumperle
\n       (<a href=\"http://gmic.sourceforge.net\">http://gmic.sourceforge.net</a>)
\n</pre>
"
-v -
-_help_section "Usage"

_help_section_html :
  _section={$_section+1}
  -v +
  -e[] "<a name=\"section"$_section"\"><h2><font color=\"brown\"><u>$1</u></font></h2></a>"
  -v -

_help_paragraph_html :
  -v +
  -e[] "<pre>$*</pre>"
  -v -

_help_footer_html :
  -v +
  -e[] "
\n<br/><b><font color=\"brown\">** G'MIC comes with ABSOLUTELY NO WARRANTY; for details visit <a href=\"http://gmic.sourceforge.net\">http://gmic.sourceforge.net **</a></font></b>
\n</tt>
\n</div>
\n</div>
\n<div id=\"footer\"><img src=\"images/footer.jpg\" /></div>
\n</div>
\n<!--#include file=\"copyright.html\" -->
\n<!--#include file=\"footer.html\" -->
"
  -v -

# Commands to output help in ascii format.
_help_header_ascii :
  -__help_header_ascii
  _section=0 _space1="" _space2=" "
  -_help_section "Usage"

__help_header_ascii :
  -if {narg($_gmic_is_beta)} strbeta=" (beta)" -else strbeta="" -endif
  -if {narg($_gmic_version)} strver=$_gmic_version -else strver=@{-strver} -endif
  -v +
  -e[] "
\n gmic: GREYC's Magic Image Converter.
\n
\n        Version "$strver$strbeta", Copyright (C) 2008-2012, David Tschumperle.
\n        (http://gmic.sourceforge.net)"
  -v -

_help_section_ascii :
  _section={$_section+1}
  {narg({'"$1"'})},1,1,1,{'-'}
  -v +
  -e[] "\n "$_section". $1"
  -e[] "    "${_space{narg({'$_section'})}}@{-1,t}"\n"
  -v -
  -rm[-1]

_help_paragraph_ascii :
  -v +
  -e[] "$*"
  -v -

_help_footer_ascii :
  -v +
  -e[] " ** G'MIC comes with ABSOLUTELY NO WARRANTY; for details visit http://gmic.sourceforge.net **"
  -v -

# Command to write general usage (used by all types of output).
_help_usage :

  -_help_paragraph " gmic [command1 [arg1_1,arg1_2,..]] .. [commandN [argN_1,argN_2,..]]
\n
\n 'gmic' is an open-source interpreter of the G'MIC language, a script-based programming
\n  language dedicated to design image processing pipelines. It can be used to convert,
\n  manipulate, filter and visualize datasets made of one or several 1d/2d or 3d multi-
\n  spectral images.
\n
\n This documentation proposes a complete description of the G'MIC language basics and rules."

  -_help_section "Overall context"

  -_help_paragraph "  - At any time, G'MIC manages one list of numbered (and optionally named) pixel-based
\n     images, entirely stored in computer memory.
\n  - The first image of the list has indice '0' and is denoted by '[0]'. The second image of
\n     the list is denoted by '[1]', the third by '[2]' and so on.
\n  - Negative indices are treated in a cyclic way: '[-1]' refers to the last image of the
\n     list, '[-2]' to the penultimate one, etc. Thus, if the list has 4 images, '[1]' and '[-3]'
\n     both designate the second image of the list.
\n  - A named image may be denoted by '[name]' if 'name' uses characters set [a-zA-Z0-9_] and
\n     does not start with a number. Image names can be set or reassigned at any moment during
\n     the processing pipeline (see commands '-name' and '-input').
\n  - G'MIC defines a set of various commands and substitution mechanisms to allow the design
\n     of complex pipelines managing this list of images, in a very flexible way:
\n     You can insert or remove images in the list, rearrange image indices, process images
\n     (individually or as a group), merge image data together and output image files.
\n  - Such a pipeline can be written itself as a custom G'MIC command storable in a custom
\n     commands file, which can be re-used afterwards in another bigger pipeline if necessary."

  -_help_section "Image definition and terminology"

  -_help_paragraph "  - In G'MIC, an image is modeled as a 1d, 2d, 3d or 4d array of scalar values, uniformly
\n     discretized on a rectangular/parallelepipedic domain.
\n  - The four dimensions of these arrays are respectively denoted by:
\n    . 'width', the number of image columns (size along the 'x'-axis).
\n    . 'height', the number of image rows (size along the 'y'-axis).
\n    . 'depth', the number of image slices (size along the 'z'-axis).
\n        The depth is equal to 1 for usual 2d color or grayscale images.
\n    . 'spectrum', the number of image channels (size along the 'c'-axis).
\n        The spectrum is respectively equal to 3 and 4 for usual RGB and RGBA color images.
\n  - There are no size limitations on each image dimensions. Particularly, the number of image
\n     slices or channels can be of arbitrary size within the limits of available memory.
\n  - The width, height and depth of an image are considered as 'spatial' dimensions, while the
\n     spectrum has a 'multi-spectral' meaning. Thus, a 4d image in G'MIC should be most often
\n     regarded as a 3d dataset of multi-spectral voxels. Most of the G'MIC commands will stick
\n     with this idea (e.g. command '-blur' will blur images only along the 'xyz' axes).
\n  - All pixel values of all images of the list have the same datatype. It can be one among:
\n    . 'bool': Stands for 'boolean'. Value range is { 0=false | 1=true }.
\n    . 'uchar': Stands for 'unsigned char'. Value range is [0,255] (8bits).
\n        This type of pixel coding is commonly used to store 8bits/channels RGB[A] images.
\n    . 'char': Value range is [-128,127] (8bits).
\n    . 'ushort': Stands for 'unsigned short'. Value range is [0,65535] (16bits).
\n        This type of pixel coding is commonly used to store 16bits/channels RGB[A] images.
\n    . 'short': Value range is [-32768,32767] (16bits).
\n    . 'uint': Stands for 'unsigned int'. Value range is [0,2^32-1] (32bits).
\n    . 'int': Value range is [-2^31,2^31-1] (32 bits).
\n    . 'float': Value range is [-3.4E38,+3.4E38] (32bits).
\n        This type of coding is able to store pixels as 32 bits float-valued numbers. This is
\n        the default datatype used by G'MIC image processing operations.
\n    . 'double': Value range is [-1.7E308,1.7E308] (64bits).
\n        This type of coding is able to store pixels as 64 bits float-valued numbers.
\n  - Considering pixel datatypes different than 'float' is generally useless, except to force
\n     the input/output of image data to a prescribed binary format. Hence, most G'MIC image
\n     image processing commands are available only for the default 'float' pixel datatype
\n     (see command '-type' if you need to switch to another pixel datatype)."

  -_help_section "Items of a processing pipeline"

  -_help_paragraph "  - In G'MIC, an image processing pipeline is described as a sequence of items separated by
\n     the space character ' '. Such items are interpreted and executed from the left to the
\n     right. For instance, the expression:
\n       'input.jpg -blur 3,0 -sharpen 10 -resize 200%,200% -output output.jpg'
\n     defines a valid pipeline composed of nine G'MIC items.
\n  - A G'MIC item is a string which represents either a command, a set of command arguments,
\n     a filename, or a special input string.
\n  - Escape characters '\\' and double quotes '\"' can be used (as usual) to define items
\n     containing spaces, or any other character sequences. For instance, the strings
\n     'single\\ item' and '\"single item\"' define the same string item, with a space in it."

  -_help_section "Input data items"

  -_help_paragraph "  - If a specified G'MIC item appears to be an existing filename, the corresponding image
\n     data are loaded and inserted at the end of the image list.
\n  - Special filenames '-' and '-.ext' stand for the standard input/output streams, optionally
\n     forced to be in a specific 'ext' file format (e.g. '-.jpg' or '-.png').
\n  - The following special input strings may be used as G'MIC items to create and insert new
\n     images with prescribed values, at the end of the image list:
\n    . '[selection]' or '[selection]xN': Insert 1 or N copies of selected existing images.
\n       'selection' may contain one or several images (see next section for details).
\n    . 'width[%],_height[%],_depth[%],_spectrum[%],_values': Insert a new image with
\n       specified size and values (adding '%' to a dimension means 'percentage of the size
\n       along the same axis, taken from the last image '[-1]''). Any specified dimension
\n       can be also written as '[image]', and is then set to the size (along the same axis)
\n       of the existing specified image [image]. 'values' can be either a sequence of numbers
\n       separated by commas ',', or a mathematical expression, as e.g. in input item
\n       '256,256,1,3,if(c==0,x,if(c==1,y,0))' which creates a 256x256 RGB color image with a
\n       spatial shading on the red and green channels.
\n    . '(v1,v2,..)': Insert a new image from specified prescribed values.
\n       Value separator inside parentheses can be ',' (column separator.), ';' (row sep.),
\n       '/' (slice sep.) or '^' (channel sep.). For instance, expression
\n       '(1,2,3;4,5,6;7,8,9)' creates a 3x3 matrix (scalar image), with values from 1 to 9.
\n    . '0': Insert a new 'empty' image, containing no pixel data. Empty images are used only
\n       in rare occasions.
\n  - Input item 'name=value' declares a new local or global variable 'name', or assign a new
\n     value to an existing variable. Variable names use characters set [a-zA-Z0-9_] and cannot
\n     start with a number. A variable definition is always local to the current command except
\n     when it starts by the underscore character '_'. In that case, it becomes also accessible
\n     by any command invoked outside the current command scope."

  -_help_section "Command items and selections"

  -_help_paragraph "  - A G'MIC item starting by '-' designates a command, most of the time. Generally, commands
\n     perform image processing operations on one or several available images of the list.
\n  - Common commands have two equivalent names (regular and short). For instance, command
\n     names '-resize' and '-r' refer to the same image resizing action.
\n  - A G'MIC command may have mandatory or optional arguments. Command arguments must be
\n     specified in the next item on the command line. Commas ',' are used to separate multiple
\n     arguments, if any required.
\n  - The execution of a G'MIC command may be restricted only to a subset of the image list, by
\n     appending '[subset]' to the command name. Examples of valid syntaxes for 'subset' are:
\n    . '-com[0,1,3]': Apply command only on images [0],[1] and [3].
\n    . '-com[3-5]': Apply command only on images [3] to [5] (i.e, [3],[4] and [5]).
\n    . '-com[50%-100%]': Apply command only on the second half of the image list.
\n    . '-com[0,-4--1]': Apply command only on the first and the four latest images.
\n    . '-com[0-9:3]': Apply command only on images [0] to [9], with a step of 3
\n                      (i.e. on images [0], [3], [6] and [9]).
\n    . '-com[0--1:2]': Apply command only on images of the list with even indices.
\n    . '-com[0,2-4,50%--1]': Apply command on images [0],[2],[3],[4] and on the second half
\n                             of the image list.
\n    . '-com[^0,1]': Apply command on all images except the first two.
\n    . '-com[name1,name2]': Apply command on named images 'name1' and 'name2'.
\n  - Indices in selections are always sorted in increasing order, and duplicate indices are
\n     discarded. For instance, selections '[3-1,1-3]' and '[1,1,1,3,2]' are both equivalent to
\n     '[1-3]'. If you want to repeat a single command multiple times on an image, use a
\n     '-repeat..-done' loop. Inverting the order of images in a selection can be achieved by
\n     inverting first the order of the images in the list, with command '-reverse[selection]'.
\n  - G'MIC commands invoked without '[subset]' are applied on all images of the list.
\n  - A G'MIC command starting with '--' instead of '-' does not act 'in-place' but inserts its
\n     result as one or several new images at the end of the image list.
\n  - There are two different types of commands that can be run by the G'MIC interpreter:
\n    . Native commands, are hard-coded functionalities in the interpreter core.
\n       They are thus compiled as machine code and run quickly, most of the time.
\n       Omitting an argument when invoking a native command is not permitted, except if all
\n       following arguments are also omitted. For instance, call to '-plasma 10,,5' is invalid
\n       but '-plasma 10' is correct.
\n    . Custom commands, are defined as G'MIC pipelines of native or custom commands.
\n       They are interpreted by the G'MIC interpreter, and run slower than native commands.
\n       But omitting arguments when invoking a custom command is permitted. For instance,
\n       expressions '-flower ,,,100,,2' or '-flower ,' are correct.
\n  - A user may easily add its own custom commands to the G'MIC interpreter (see section
\n     'Adding custom commands'). Native commands cannot be added unless you modify the G'MIC
\n     interpreter source code."

  -_help_section "Inputs / outputs properties"

  -_help_paragraph "  - G'MIC is able to read/write most of the classical image file formats, including:
\n    . 2d grayscale/color files: .png, .jpeg, .gif, .pnm, .tif, .bmp, ..
\n    . 3d volumetric files: .dcm, .hdr, .nii, .pan, .inr, .pnk, ..
\n    . Image sequences: .mpeg, .avi, .mov, .ogg, .flv, ..
\n    . Generic ascii or binary data files: .cimg, .cimgz, .dlm, .asc, .pfm, .raw, .txt, .h.
\n    . 3d object files: .off.
\n  - When dealing with color images, G'MIC generally reads, writes and displays data using the
\n     usual RGB color space.
\n  - G'MIC is able to manage 3d objects that may be read from files or generated by G'MIC
\n     commands. They are stored as one-column scalar images containing the object data, in the
\n     following order: { magic_number; sizes; vertices; primitives; colors; opacities }.
\n     These 3d representations can be processed as regular float-valued images.
\n     (see command '-split3d' for accessing each of these 3d object data separately).
\n  - Be aware that usual file formats may be sometimes not adapted to store all the available
\n     image data, since G'MIC uses float-valued coding of image pixels. For instance, saving
\n     an image that was initially loaded as a 16bits/channel image, as a .jpg file will result
\n     in loss of informations. Use the .cimg file extension (or .cimgz, its compressed
\n     version) to ensure that all data precision will be preserved when saving images.
\n  - File options can/must be set for these specific file formats:
\n    . Video files: Only sub-frames of an image sequence may be loaded, using the input
\n       expression 'filename.ext,[first_frame[%][,last_frame[%][,step]]]'.
\n       Output framerate and bitrate (in Kb/s) can be also set by using the output expression
\n       'file.mpg,_fps,_bitrate'.
\n    . .raw binary files: Image dimensions and input pixel type may be specified when loading
\n       .raw files with input expresssion 'filename.raw,width[,type][,height[,depth[,dim]]]]'.
\n       If no dimensions are specified, the resulting image is a one-column vector with
\n       maximum possible height. Pixel type can also be specified with the output
\n       expression 'file.raw[,type]'.
\n       'type' can be { bool | uchar | char | ushort | short | uint | int | float | double }.
\n    . .yuv files: Image dimensions must be specified, and only sub-frames of an image
\n       sequence may be loaded, using the input expression
\n      'filename.yuv,width,height[,first_frame[,last_frame[,step]]]'.
\n    . .gif files: Animated gif files can be saved, using the input expression
\n      'filename.gif,fps,nb_loops'.
\n      Specify 'nb_loops=0' to get an infinite number of animation loops.
\n    . .jpeg files: The output quality may be specified (in %), using the output expression
\n       'filename.jpg,30' (here, to get a 30% quality output).
\n    . .mnc files: The output header can set from another file, using the output expression
\n       'filename.mnc,header_template.mnc'.
\n    . Filenames with extension '.gmic' are assumed to be G'MIC custom commands files. Loading
\n       such a file will add the commands it defines to the interpreter.
\n    . Inserting 'ext:' on the beginning of a filename (e.g. 'jpg:filename') forces G'MIC to
\n       read/write the file as it would have been done if it had the specified extension.
\n  - Some input/output formats and options may not be supported by your current version of
\n     'gmic', depending on the configuration flags set for the build of the 'gmic' binaries."

  -_help_section "Substitution rules"

  -_help_paragraph "  - G'MIC items containing '@', '$' or '{}' may be substituted before being interpreted. Use
\n     the substituting expressions below to access data from the interpreter environment:
\n    . '@#' is substituted by the current number of images in the list.
\n    . '@.' is substituted by the current version number of the G'MIC interpreter
\n    . '@%' is substituted by the pid of the current process.
\n    . '@|' is substituted by the current value (expressed in seconds) of a millisecond
\n       precision timer.
\n    . '@?' is substituted by the current data type of image pixels.
\n    . '@/' is substituted by the current number of levels in the command scope.
\n    . '@{/}' or '@{/,subset}' are substituted by the content of the global scope, or a
\n       subset of it. If specified subset refers to multiple scope items, they are separated
\n       by slashes '/'.
\n    . '@>' and '@<' are equivalent. They are both substituted by the number of nested
\n       'repeat-done' loops that are currently running.
\n    . '@{>}' or '@{>,subset}' are substituted by the indice values (or a subset of them) of
\n       the running 'repeat-done' loops, expressed in the ascending order, starting from 0.
\n       If specified subset refers to multiple indices, they are separated by commas ','.
\n    . '@{<}' or '@{<,subset}' do the same but in descending order.
\n    . '@indice' or '@{indice,feature}' are substituted by the list of pixel values of the
\n       image [indice] (separated by commas), or by a specific feature (or subset) of it.
\n       'indice' can be an indice or an image name. Requested 'featured' can be one of:
\n         . 'w': image width (number of image columns).
\n         . 'h': image height (number of image rows).
\n         . 'd': image depth (number of image slices).
\n         . 's': image spectrum (number of image channels).
\n         . 'wh': image width x image height.
\n         . 'whd': image width x image height x image depth.
\n         . 'whds': image width x image height x image depth x image spectrum.
\n                   (i.e. number of values in the specified image, eq. to '#').
\n         . 'r': image shared state (1, if the pixel buffer is shared, 0 otherwise).
\n         . 'n': image name or filename (if the image has been read from a file).
\n         . 'b': image basename (i.e. filename without the folder path nor extension).
\n         . 'x': image extension (i.e last characters after the last '.' in the filename).
\n         . 'f': image folder name.
\n         . '#': number of image values (i.e. width x height x depth x spectrum).
\n         . '+': sum of all pixel values.
\n         . '-': difference of all pixel values.
\n         . '*': product of all pixel values.
\n         . '/': quotient of all pixel values.
\n         . 'm': minimum pixel value.
\n         . 'M': maximum pixel value.
\n         . 'a': average pixel value.
\n         . 'v': variance of pixel values.
\n         . 't': text string built from the image values, regarded as ascii codes.
\n         . 'c': (x,y,z,c) coordinates of the minimum value, separated by commas ','.
\n         . 'C': (x,y,z,c) coordinates of the maximum value, separated by commas ','.
\n         . '(x[%],_y[%],_z[%],_c[%],_boundary)': pixel value at (x[%],y[%],z[%],c[%]), with
\n            specified boundary conditions { 0=dirichlet | 1=neumann | 2=cyclic }.
\n         . Any other 'feature' is considered either as a specified subset of image values, or
\n            as a mathematical expression to evaluate (associated to selected image).
\n            For instance, '@{-1,0-50%}' is substituted by the sequence of numerical values
\n            coming from the first half data of the last image, separated by commas ','.
\n            Expression '@{0,w+h}' is substituted by the sum of the width and height of the
\n            first image.
\n    . '@!' is substituted by the visibility state of the instant display window [0]
\n       (can be { 0=closed | 1=visible }).
\n    . '@{!,feature}' or '@{!indice,feature}' is substituted by a specific feature of the
\n       instant display window [0] (or [indice], if specified). Requested 'feature' can be:
\n         . 'w': display width (i.e. width of the display area managed by the window).
\n         . 'h': display height (i.e. height of the display area managed by the window).
\n         . 'wh': display width x display height.
\n         . 'd': window width (i.e. width of the window widget).
\n         . 'e': window height (i.e. height of the window widget).
\n         . 'de': window width x window height.
\n         . 'u': screen width (actually independent on the window size).
\n         .' v': screen height (actually independent on the window size).
\n         . 'uv': screen width x screen height.
\n         . 'x': X-coordinate of the mouse position (or -1, if outside the display area).
\n         . 'y': Y-coordinate of the mouse position (or -1, if outside the display area).
\n         . 'b': state of the mouse buttons { 1=left-but. | 2=right-but. | 4=middle-but. }.
\n         . 'o': state of the mouse wheel.
\n         . 'k': decimal code of the pressed key if any, 0 otherwise.
\n         . 'n': current normalization type of the instant display.
\n         . 'c': boolean (0 or 1) telling if the instant display has been closed recently.
\n         . 'r': boolean telling if the instant display has been resized recently.
\n         . 'm': boolean telling if the instant display has been moved recently.
\n         . Any other 'feature' stands for a keycode name in capital letters, and is substi-
\n            tuted by a boolean describing the current key state { 0=pressed | 1=released }.
\n    . '@{\"command line\"}' is substituted by the status value set by the execution of the
\n       specified command line (see command '-status'). Verbosity level is decremented before
\n       the execution of the command, and incremented back afterwards.
\n    . Expression '@{}' stands thus for the current status value.
\n  - $name and '${name}' are both substituted by the value of the specified named variable
\n     (set previously by item 'name=value'), or by the current positive indice of the named
\n     image '[name]', or by the value of the named OS environment variable (in this order).
\n  - '$>' and '$<' (resp. '${>}' and '${<}') are shortcuts respectively for '@{>,-1}' and
\n     '@{<,-1}'. They refer to the increasing/decreasing indice of the latest (currently
\n     running) 'repeat..done' loop.
\n  - Any other expression inside braces (as in '{expression}') is considered as a mathematical
\n     expression, and is evaluated, except for the three following cases:
\n    . If expression starts and ends by single quotes, it is substituted by the sequence of
\n       ascii codes that composes the specified string, separated by commas ','. For instance,
\n       item '{'foo'}' is substituted by '102,111,111'.
\n    . If expression starts and ends with backquotes '`', it is substituted by the string
\n       whose ascii codes are given by the list of values in between the backquotes.
\n       For instance, item '{`102,111,111`}' is substituted by 'foo'.
\n    . If expression contains operator ''=='' or ''!='', it is substituted by 0 or 1, whether
\n       the strings beside the operator are the same or not (case-sensitive). For instance,
\n       both items '{foo'=='foo}' and '{foo'!='FOO}' are substituted by '1'.
\n    . If expression starts with an underscore '_', it is substituted by the mathematical
\n       evaluation of the expression, truncated to a readable format.
\n  - Item substitution is never done in items between double quotes. One must break the quotes
\n    to enable substitution if needed, as in \"3+8 kg = \"{3+8}\" kg\". Using double quotes
\n    is then a convenient way to disable the substitutions mechanism in items, when necessary.
\n  - One can also disable the substitution mechanism on items outside double quotes, by
\n     escaping the '@','{','}' or '$' characters, as in '\\{3+4\\}\\ doesn't\\ evaluate'."

  -_help_section "Mathematical expressions"

  -_help_paragraph "  - G'MIC has an embedded mathematical parser. It is used to evaluate expressions inside
\n     braces '{}', or formulas in commands that may take one as an argument (e.g. '-fill').
\n  - When used in commands, a formula is evaluated for each pixel of the selected images.
\n  - The math parser understands the following set of functions, operators and variables:
\n    _ Usual operators: || (logical or), && (logical and), | (bitwise or), & (bitwise and),
\n       !=, ==, <=, >=, <, >, << (left bitwise shift), >> (right bitwise shift), -, +, *, /,
\n       % (modulo), ^ (power), ! (logical not), ~ (bitwise not).
\n    _ Usual functions: sin(), cos(), tan(), asin(), acos(), atan(), sinh(), cosh(), tanh(),
\n       log(), log2(), log10(), exp(), sign(), abs(), atan2(), round(), narg(), arg(),
\n       isval(), isnan(), isinf(), isint(), isbool(), rol() (left bit rotation),
\n       ror() (right bit rotation), min(), max(), sinc(), int().
\n       Function 'atan2()' is the version of atan() with two arguments 'y,x' (as in C/C++).
\n       Function 'narg()' returns the number of specified arguments.
\n       Function 'arg(i,a_1,..,a_n)' returns the ith argument a_i.
\n       Functions 'min()' and 'max()' can be called with an arbitrary number of arguments.
\n       Functions 'isval()', 'isnan()', 'isinf()', 'isbool()' can be used to test the type of
\n       a given number or expression.
\n    _ The variable names below are pre-defined. They cannot be overloaded:
\n         . 'w': width of the associated image, if any (0 otherwise).
\n         . 'h': height of the associated image, if any (0 otherwise).
\n         . 'd': depth of the associated image, if any (0 otherwise).
\n         . 's': spectrum of the associated image, if any (0 otherwise).
\n         . 'x': current processed column of the associated image, if any (0 otherwise).
\n         . 'y': current processed row of the associated image, if any (0 otherwise).
\n         . 'z': current processed slice of the associated image, if any (0 otherwise).
\n         . 'c': current processed channel of the associated image, if any (0 otherwise).
\n         . 'i': current processed pixel value (i.e. value located at (x,y,z,c)) of the
\n            associated image, if any (0 otherwise).
\n         . 'im','iM','ia','iv': Respectively the minimum, maximum, average values and
\n            variance of the associated image, if any (0 otherwise).
\n         . 'xm','ym','zm','cm': The pixel coordinates of the minimum value in the associated
\n            image, if any (0 otherwise).
\n         . 'xM','yM','zM','cM': The pixel coordinates of the maximum value in the
\n            associated image, if any (0 otherwise).
\n         . 'pi': value of pi, i.e. 3.1415926..
\n         . 'e': value of e, i.e. 2.71828..
\n         . '?' or 'u': a random value between [0,1], following a uniform distribution.
\n         . 'g': a random value, following a gaussian distribution of variance 1
\n            (roughly in [-5,5]).
\n    _ These special operators can be used:
\n         . ';': expression separator. The returned value is always the last encountered
\n            expression. For instance expression '1;2;pi' is evaluated as 'pi'.
\n         . '=': variable assignment. Variables in mathematical parser can only refer to.
\n            numerical values. Variable names are case-sensitive. Use this operator in
\n            conjunction with ';' to define complex evaluable expressions, such as
\n             't=cos(x);3*t^2+2*t+1'.
\n            These variables remain local to the mathematical parser and cannot be accessed
\n            outside the evaluated expression.
\n    _ The following specific functions are also defined:
\n         . 'if(expr_cond,expr_then,expr_else)': return value of 'expr_then' or 'expr_else',
\n            depending on the value of 'expr_cond' (0=false, other=true). For instance,
\n            G'MIC command '-fill if(x%10==0,255,i)' will draw blank vertical lines on every
\n            10th column of an image.
\n         . '?(max)' or '?(min,max)': return a random value between [0,max] or [min,max],
\n            following a uniform distribution. 'u(max)' and 'u(0,max)' mean the same.
\n         . 'i(a,_b,_c,_d,_interpolation,_boundary)': return the value of the pixel located
\n            at position (a,b,c,d) in the associated image, if any (0 otherwise).
\n            Interpolation parameter can be { 0=nearest neighbor | other=linear }.
\n            Boundary conditions can be { 0=dirichlet | 1=neumann | 2=cyclic }.
\n            Omitted coordinates are replaced by their default values which are respectively
\n            x, y, z, c and 0.
\n            For instance command '-fill 0.5*(i(x+1)-i(x-1))' will estimate the X-derivative
\n            of an image with a classical finite difference scheme.
\n  - The last image of the list is always associated to the evaluations of '{expressions}',
\n     e.g. G'MIC sequence '256,128 -f {w}' will create a 256x128 image filled with value 256."

  -_help_section "Image and data viewers"

  -_help_paragraph "  - G'MIC has some very handy embedded visualization modules, for 1d signals
\n     (command '-plot'), 1d/2d/3d images (command '-display') and 3d objects
\n     (command '-display3d'). It enables an interactive view of the selected image data.
\n  - The following keyboard shortcuts are available in the interactive viewers:
\n    . CTRL+D: Increase window size.
\n    . CTRL+C: Decrease window size.
\n    . CTRL+R: Reset window size.
\n    . CTRL+F: Toggle fullscreen mode.
\n    . CTRL+S: Save current window snapshot as numbered file 'gmic_xxxx.bmp'.
\n    . CTRL+O: Save current instance of the viewed data, as numbered file 'gmic_xxxx.cimgz'.
\n  - Shortcuts specific to the 1d/2d/3d image viewer are:
\n    . CTRL+P: Play z-stack of frames as a movie (for volumetric 3d images).
\n    . CTRL+V: Enable/disable 3D view (for volumetric 3d images).
\n    . CTRL+(mousewheel): Zoom in/out.
\n    . SHIFT+(mousewheel): Go left/right.
\n    . ALT+(mousewheel): Go up/down.
\n    . Numeric PAD: Zoom in/out (+/-) and move through zoomed image (digits).
\n    . BACKSPACE: Reset zoom scale.
\n  - Shortcuts specific to the 3d object viewer are:
\n    . (mouse)+(left mouse button): Rotate 3d object.
\n    . (mouse)+(right mouse button): Zoom 3d object.
\n    . (mouse)+(middle mouse button): Shift 3d object.
\n    . (mousewheel): Zoom in/out.
\n    . CTRL+F1 .. CTRL+F6: Switch between different 3d rendering modes.
\n    . CTRL+Z: Enable/disable z-buffered rendering.
\n    . CTRL+A: Show/hide 3d axes.
\n    . CTRL+G: Save 3d object, as numbered file 'gmic_xxxx.off'.
\n    . CTRL+T: Switch between single/double-sided 3d modes."

  -_help_section "Adding custom commands"

  -_help_paragraph "  - Custom commands can be defined by a user, through the use of G'MIC custom commands files.
\n  - A command file is a simple ascii text file, where each line starts either by
\n     'command_name: command_definition' or 'command_definition (continuation)'.
\n  - Custom command names must use characters [a-zA-Z0-9_] and cannot start with a number.
\n  - Any ' \# comment' expression found in a custom commands file is discarded by the G'MIC
\n     interpreter, wherever it is located in a line.
\n  - A default command file is already provided within the G'MIC package. It is located
\n     at 'http://gmic.sourceforge.net/gmic_def.xxxx', where 'xxxx' has to be replaced by
\n     the 4 digits of the current G'MIC version number. Looking at it is a good place to start
\n     learning to create your own custom commands. All the commands from this default command
\n     file are already included by default in the current version of the G'MIC interpreter.
\n  - The default command file located at 'http://gmic.sourceforge.net/gmic_def.xxxx' may be
\n     updated/corrected by the G'MIC developers. You can thus download and include it with the
\n     '-command' directive to update your default command definitions as well.
\n  - In custom commands, the following $-expressions are substituted:
\n    . '$""*' is substituted by a verbatim copy of the specified arguments string.
\n    . '$""#' is substituted by the maximum indice of known arguments (either specified by the
\n       user or set to a default value in the custom command).
\n    . '$""?' is substituted by a string telling about the command subset restriction (only
\n       useful when custom commands need to output descriptive messages).
\n    . '$i' and '${i}' are both substituted by the i-th specified argument. Negative indices
\n       such as '${-j}' are allowed and refer to the j^th latest argument. '$""0' is substituted
\n       by the custom command name.
\n    . '${i=default}' is substituted by the value of $i (if defined) or by its new value set
\n        to 'default' otherwise ('default' may be a $-expression as well).
\n    . '${subset}' is substituted by the arguments values (separated by commas ',') of a
\n       specified argument subset. For instance expression '$""{2--2}' is substitued by all
\n       specified arguments except the first and the last one. Expression '$""{^0}' is then
\n       substituted by all arguments of the invoked command (eq. to '$""*' if all specified
\n       arguments have indeed a value).
\n    . '$""=var' is substituted by the set of instructions that will assign each argument $i
\n       to the named variable 'var$i' (for i in [0..$""#]). This is particularly useful when a
\n       custom command want to manage variable numbers of arguments. Variables names must
\n       use characters [a-zA-Z0-9_] and cannot start with a number.
\n  - These particular $-expressions are always substituted, even in double quoted items or
\n     when the dollar sign '$' is escaped with a backslash '\\'. To avoid substitution, place
\n     an empty double quoted string just after the '$' (as in '$\"\"1').
\n  - Specifying arguments may be skipped when invoking a custom command, by replacing them by
\n     commas ',' as in expression '-flower ,,3'. Omitted arguments are set to their default
\n     values, which must be thus explicitely defined in the code of the corresponding custom
\n     command (using default argument expressions as '$""{1=default}').
\n  - If one numbered argument requested in a custom command has no value, an error is thrown
\n     by the interpreter."

  -_help_section "List of commands"

  -_help_paragraph " All available G'MIC commands are listed below, classified by themes.
\n When several choices of command arguments are possible, they appear separated by '|'.
\n An argument specified inside '[]' or starting by '_' is optional except when standing for an
\n existing image [image], where 'image' can be either an indice number or an image name.
\n In this case, the '[]' characters are mandatory when writing the item. A command marked with
\n '(*)' or '(+)' is a native command. '(*)' means the command is available for all pixel types,
\n otherwise only for the default 'float' pixel type.
\n Remember that native commands run faster than custom commands, so use then when possible."

_help_examples :
  -_help_section "Examples of use"

  -_help_paragraph " 'gmic' is a generic image processing tool which can be used in a wide variety of situations.
\n The few examples below illustrate possible uses of this tool:
\n
\n  - View a list of images:
\n     gmic file1.bmp file2.jpeg
\n
\n  - Convert an image file:
\n     gmic input.bmp -o output.jpg
\n
\n  - Create a volumetric image from a movie sequence:
\n     gmic input.mpg -a z -o output.hdr
\n
\n  - Compute image gradient norm:
\n     gmic input.bmp -gradient_norm
\n
\n  - Denoise a color image:
\n     gmic image.jpg -denoise 30,10 -o denoised.jpg
\n
\n  - Compose two images using overlay fading:
\n     gmic image1.jpg image2.jpg -compose_overlay -o composed.jpg
\n
\n  - Evaluate a mathematical expression:
\n     gmic -e \"cos(pi/4)^2+sin(pi/4)^2={cos(pi/4)^2+sin(pi/4)^2}\"
\n
\n  - Plot a 2d function:
\n     gmic 1000,1,1,2 -f \"X=3*(x-500)/500;X^2*sin(3*X^2)+if(c==0,u(0,-1),cos(X*10))\" -plot
\n
\n  - Plot a 3d elevated function in random colors:
\n     gmic 128,128,1,3,\"?(0,255)\" -plasma 10,3 -blur 4 -sharpen 10000 \\
\n      -elevation3d[-1] \"'X=(x-64)/6;Y=(y-64)/6;100*exp(-(X^2+Y^2)/30)*abs(cos(X)*sin(Y))'\"
\n
\n  - Plot the isosurface of a 3d volume:
\n     gmic -m3d 5 -md3d 5 -db3d 0 -isosurface3d \"'x^2+y^2+abs(z)^abs(4*cos(x*y*z*3))'\",3
\n
\n  - Render a G'MIC 3d logo:
\n     gmic 1 -text G\\'MIC,0,0,57,1,1,1,1 -expand_xy 10,0 -blur 2 -n 0,100 --plasma 0.4 -+ \\
\n      -blur 1 -elevation3d -0.1 -md3d 4
\n
\n  - Generate a 3d ring of torii:
\n     gmic -repeat 20 -torus3d 15,2 -col3d[-1] \"{?(60,255)},{?(60,255)},{?(60,255)}\" \\
\n      -*3d[-1] 0.5,1 -if \"{$>%2}\" -r3d[-1] 0,1,0,90 -endif -+3d[-1] 70 -+3d \\
\n      -r3d 0,0,1,18 -done -md3d 3 -m3d 5 -db3d 0
\n
\n  - Create a vase from a 3d isosurface:
\n     gmic -md3d 4 -isosurface3d \"'x^2+2*abs(y/2)*sin(2*y)^2+z^2-3',0\" -sphere3d 1.5 \\
\n      --3d[-1] 0,5 -plane3d 15,15 -r3d[-1] 1,0,0,90 -c3d[-1] -+3d[-1] 0,3.2 \\
\n      -col3d[-1] 180,150,255 -col3d[-2] 128,255,0 -col3d[-3] 255,128,0 -+3d
\n
\n  - Display filtered webcam stream:
\n     gmic -apply_camera \\\"--mirror x --mirror y -+ -/ 4\\\"
\n
\n  - Launch a set of G'MIC interactive demos:
\n     gmic -x_fisheye -x_fire G\\'MIC -x_tictactoe -rm -x_spline -x_mandelbrot 0 -x_light \\
\n          -x_whirl , -x_life -x_jawbreaker , -x_blobs -x_tetris
\n"

#@gmic version : (*)
#@gmic : Display current version number and exit.
version :
  -v - -__help_header_ascii[] -v +
  -e[] ""

#---------------------------------
#
#@gmic :: Inputs / outputs
#
#---------------------------------

#@gmic apply_camera : _command,_camera_index>=-1,_skip_frames>=0,_output_filename
#@gmic : Apply specified command on live camera stream, and display it on display window [0].
#@gmic : Default values: 'command=""', 'camera_index=-1','skip_frames=0' and 'filename=""'.
apply_camera : -skip "${1=},${4=}" -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 and filename '$4'." -v -
  -l[] frame=0 -do
    -camera $2,1,$3 $1 -w[-1] -1,-1,-1,-1,"(Camera "$stream", "{w}x{h}")"
    -if {narg("$4")} -o[-1] @{"-filename \"$4\","$frame} frame={$frame+1} -endif
    -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 camera : _camera_index>=-1,_nb_frames>0,_skip_frames>=0,release_camera={ 0 | 1 } : (*)
#@gmic : Insert one or several frames from specified camera, with custom delay between frames (in ms).
#@gmic : Set 'camera_index' to -1 to use the default camera device.
#@gmic : When 'release_camera==1', the camera stream is released instead of capturing new images.
#@gmic : Default values: 'camera_index=-1', 'nb_frames=1', 'skip_frames=0' and 'release_camera=0'.

#@gmic m : eq. to '-command'. : (*)

#@gmic command : filename : http[s]://URL : "string" : (*)
#@gmic : Import G'MIC custom commands from specified file, URL or string.
#@gmic : (eq. to '-m').
#@gmic : Imported commands are available directly after the '-command' invokation.
#@gmic : $ image.jpg -command "foo : -mirror y -deform $""1" --foo[0] 5 --foo[0] 15

#@gmic d : eq. to '-display'. : (+)

#@gmic display : _X,_Y,_Z : (+)
#@gmic : Display selected images in an interactive viewer (use the instant window [0] if opened).
#@gmic : Arguments 'X','Y','Z' determine the initial selection view, for 3d volumetric images.
#@gmic : (eq. to '-d').

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

#@gmic display0
#@gmic : Display selected images without value normalization.
#@gmic : (eq. to '-d0').
display0 :
  -_display0

_display0 :
  -v -
  w=0 h=0 d=0 s=0
  -repeat @# -l[$>] w={$w+w} h={max($h,h)} d={max($d,d)} s={max($s,s)} -endl -done
  -if {@#==1} -w -1,-1,0,0,@{0,n}\ ($wx$hx$dx$s)
  -elif {@#==2} -w -1,-1,0,0,@{0,n},@{-1,n}\ ($wx$hx$dx$s)
  -else -w -1,-1,0,0,@{0,n},..,@{-1,n}\ ($wx$hx$dx$s)
  -endif
  -v + -d
  -v - -w[] 0 -v +

#@gmic d3d : eq. to '-display3d'. : (+)

#@gmic display3d : (+)
#@gmic : Display selected 3d objects in an interactive viewer (use the instant window [0] if opened).
#@gmic : (eq. to '-d3d').

#@gmic da : eq. to '-display_array'.
da :
  -_display_array $*

#@gmic display_array : _width>0,_height>0
#@gmic : Display images in interactive windows where pixel neighborhoods can be explored.
#@gmic : Default values: 'width=13' and 'height=width'.
display_array :
  -_display_array $*

_display_array : -check ${1=13}>0" && "${2=$1}>0
  -e[0--3] "Display $1x$2 array of pixel values for image$?."
  -v -
  dxb={round($1/2,1,1)} dxf={$1-1-$dxb}
  dyb={round($2/2,1,1)} dyf={$2-1-$dyb}

  -repeat @# -l[$>]
    -if {w<128" && "h<128} -r 128,128,100%,100%,0,0,0.5,0.5 -endif    # Manage cases of small and large images.
    x0=0 y0=0 w={w} h={h}
    wmax={0.9*@{!,u}} hmax={0.9*@{!,v}}
    -do
      -if {w>=$wmax||h>=$hmax}
        n=@{-1,n} -nm[-1] "Image "'@{-1,b}.@{-1,x}'" is too large, please select a sub-image."
        --select[-1] 2 x0={i(0,0)} y0={i(0,1)} w={1+i(0,3)-i(0,0)} h={1+i(0,4)-i(0,1)}
        -rm[-1] -nm[-1] $n
      -endif
      --z[-1] $x0,$y0,0,{$x0+$w-1},{$y0+$h-1},0 -round[-1] 1 -n[-1] 0,255
    -while {w>=$wmax||h>=$hmax}

    x1=-1 y1=-1 c1=0 ox1=-1 oy1=-1 oc1=-1
    x2=-1 y2=-1 c2=0 ox2=-1 oy2=-1 oc2=-1
    x3=-1 y3=-1 c3=0 ox3=-1 oy3=-1 oc3=-1
    c0=0 oxm=-1 oym=-1
    -w[-1] -1,-1,0,0,@{-2,b}.@{-2,x}
    -do  # Enter event loop.

      # Manage user interactions.
      -wait[0-3]
      oc0=$c0
      -repeat 4
        -if {$>" && "!@{!$>}" && "${x$>}>=0} -w$> 0 x$>=-1 y$>=-1 c$>=0 -endif
        -if @{!$>,o} c$>={(${c$>}+sign(@{!$>,o}))%s} -wait[$>] -1 -endif
        -if {@{!$>,SPACE}" || "@{!$>,ENTER}" || "@{!$>,ARROWRIGHT}" || "@{!$>,ARROWDOWN}} c$>={(${c$>}+1)%s} -wait[$>] -1 -endif
        -if {@{!$>,BACKSPACE}" || "@{!$>,ARROWLEFT}" || "@{!$>,ARROWUP}} c$>={(${c$>}-1)%s} -wait[$>] -1 -endif
      -done
      -if {$oc0!=$c0} c1=$c0 c2=$c0 c3=$c0 -endif
      xm=@{!,x} ym=@{!,y}
      -if {$xm>=0" && "@{!,b}&1} x1=$xm y1=$ym -endif
      -if {$xm>=0" && "@{!,b}&2} x2=$xm y2=$ym -endif
      -if {$xm>=0" && "@{!,b}&4} x3=$xm y3=$ym -endif

      # Generate main image view.
      -if {$xm>=0" && "($oxm!=$xm" || "$oym!=$ym)} -w[] -1,-1,-1,-1,@{-2,b}.@{-2,x}" - ("$xm,$ym")" -endif
      -if {$x1!=$ox1" || "$y1!=$oy1" || "$x2!=$ox2" || "$y2!=$oy2" || "$x3!=$ox3" || "$y3!=$oy3}
        [-1]
        -if {$x1>=0}
          xb={$x1-$dxb} yb={$y1-$dyb} xe={$x1+$dxf} ye={$y1+$dyf}
          -rectangle[-1] $xb,$yb,$xe,$ye,0.2,0,255,255
          -rectangle[-1] $xb,$yb,$xe,$ye,1,0xFFFFFFFF,0,255,255
        -endif
        -if {$x2>=0}
          xb={$x2-$dxb} yb={$y2-$dyb} xe={$x2+$dxf} ye={$y2+$dyf}
          -rectangle[-1] $xb,$yb,$xe,$ye,0.2,255,32,255
          -rectangle[-1] $xb,$yb,$xe,$ye,1,0xFFFFFFFF,255,32,255
        -endif
        -if {$x3>=0}
          xb={$x3-$dxb} yb={$y3-$dyb} xe={$x3+$dxf} ye={$y3+$dyf}
          -rectangle[-1] $xb,$yb,$xe,$ye,0.2,255,255,0
          -rectangle[-1] $xb,$yb,$xe,$ye,1,0xFFFFFFFF,255,255,0
        -endif
        -w[-1] @{-2,w},@{-2,h} -rm[-1] oxm=$xm oym=$ym
      -endif

      # Generate zoomed views.
      -if {$x1>=0" && "($ox1!=$x1" || "$oy1!=$y1" || "$oc1!=$c1)}
        --z[-2] {$x1-$dxb},{$y1-$dyb},0,$c1,{$x1+$dxf},{$y1+$dyf},0,$c1
        --z[-2] {$x1-$dxb},{$y1-$dyb},0,{$x1+$dxf},{$y1+$dyf},0
        -__display_array[-2,-1] $1,$2,0,255,255
        -w1[-1] {w},{h},0,0,@{-3,b}" - ("$x1,$y1,c=$c1")"
        -rm[-1] ox1=$x1 oy1=$y1 oc1=$c1
      -endif
      -if {$x2>=0" && "($ox2!=$x2" || "$oy2!=$y2" || "$oc2!=$c2)}
        --z[-2] {$x2-$dxb},{$y2-$dyb},0,$c2,{$x2+$dxf},{$y2+$dyf},0,$c2
        --z[-2] {$x2-$dxb},{$y2-$dyb},0,{$x2+$dxf},{$y2+$dyf},0
        -__display_array[-2,-1] $1,$2,255,32,255
        -w2[-1] {w},{h},0,0,@{-3,b}" - ("$x2,$y2,c=$c2")"
        -rm[-1] ox2=$x2 oy2=$y2 oc2=$c2
      -endif
      -if {$x3>=0" && "($ox3!=$x3" || "$oy3!=$y3" || "$oc3!=$c3)}
        --z[-2] {$x3-$dxb},{$y3-$dyb},0,$c3,{$x3+$dxf},{$y3+$dyf},0,$c3
        --z[-2] {$x3-$dxb},{$y3-$dyb},0,{$x3+$dxf},{$y3+$dyf},0
        -__display_array[-2,-1] $1,$2,255,255,0
        -w3[-1] {w},{h},0,0,@{-3,b}" - ("$x3,$y3,c=$c3")"
        -rm[-1] ox3=$x3 oy3=$y3 oc3=$c3
      -endif
    -while {@!" && "\
            !@{!,ESC}" && "!@{!,Q}" && "\
            !@{!1,ESC}" && "!@{!1,Q}" && "\
            !@{!2,ESC}" && "!@{!2,Q}" && "\
            !@{!3,ESC}" && "!@{!3,Q}}
    -k[0] -w 0 -w1 0 -w2 0 -w3 0
  -endl -done -v +

__display_array :
  -round[-2] 1 -c[-2] 0,999 -r[-1] 100%,100%,1,3,{if(s==1,1,0)}
  --luminance[-1] -r[-2] {$1*24},{$2*24} -grid[-2] {100/$1}%,{100/$2}%,0,0,1,0
  xb={24*int($1/2)} yb={24*int($2/2)} xe={$xb+24} ye={$yb+24}
  -rectangle[-2] $xb,$yb,$xe,$ye,1,0xFFFFFFFF,$3,$4,$5
  -repeat $2 yg=$>
    -repeat $1 xg=$>
      -t[-2] @{-3,($xg,$yg)},{5+$xg*24},{5+$yg*24},13,0.8,{if(@{-1,($xg,$yg)}>128,0,255)}
    -done
  -done
  -rm[-3,-1]

#@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').
#@gmic : $ image.jpg --display_fft
display_fft :
  -_display_fft

_display_fft :
  -e[0--3] "Render fourier transform of image$? with centered log-module and argument."
  -v - -repeat @# -l[$>] -fftpolar -+[-2] 1 -log[-2] -n 0,255 -a x -endl -done -s x,2 -v +

#@gmic dg : eq. to '-display_graph'.
dg : -check "${1=640}>32 && ${2=480}>32" -skip ${3=1},${4=0},${5=0},${6=0},${7=0},${8=0},"${9=X-axis}","${10=Y-axis}"
  -_display_graph ${1-8},"$9","$10"

#@gmic display_graph : _width>32,_height>32,_plot_type,_vertex_type,_xmin,_xmax,_ymin,_ymax,_xlabel,_ylabel
#@gmic : Render graph plot from selected image data.
#@gmic : Default values: 'width=640', 'height=480', 'plot_type=1', 'vertex_type=1', 'xmin=xmax=ymin=ymax=0', 'xlabel="X-axis"' and 'ylabel="Y-axis"'.
#@gmic : $ 128,1,1,1,'cos(x/10+?)' --display_graph 400,300,3
display_graph : -check "${1=640}>32 && ${2=480}>32" -skip ${3=1},${4=0},${5=0},${6=0},${7=0},${8=0},"${9=X-axis}","${10=Y-axis}"
  -_display_graph ${1-8},"$9","$10"

_display_graph : -check "${1=640}>32 && ${2=480}>32" -skip ${3=1},${4=0},${5=0},${6=0},${7=0},${8=0},"${9=X-axis}","${10=Y-axis}"
  -e[0--3] "Render $1x$2 graph plot from data of image$?."
  -v - -repeat @# -l[$>] nm=@{0,n}

    # 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-(iM-im)/20} ymax={iM+(iM-im)/20} -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} (120,120,200)
    -elif {@{-2,s}<=3} (220,10,10;10,220,10;10,10,220)
    -else
      (0,255) -r[-1] 256,1,1,1,3 -map[-1] 2 -z[-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

    100%,100%,1,1,255
    xmax_={$xmin+($xmax-$xmin)*($siz-$one)/($siz-1)}
    -v + -axes[-1] $xmin,$xmax_,$ymax,$ymin,13,1,0 -v -
    -if {$xmin>0} -axes[-1] 0,0,$ymax,$ymin,13,1,160 -endif
    -if {$xmax<0} -axes[-1] {w-1},{w-1},$ymax,$ymin,13,1,160 -endif
    -if {$ymin>0} -axes[-1] $xmin,$xmax_,{h-1},{h-1},13,1,160 -endif
    -if {$ymax<0} -axes[-1] $xmin,$xmax_,0,0,13,1,160 -endif
    --erode[-1] 3 -neq[-1] 255 -r[-2] 100%,100%,1,3 -j[-3] [-2],0,0,0,0,1,[-1],1 -rm[-2,-1]

    -frame[-1] 16,16,220
    0 -t[-1] "$9",0,0,13,1,-220,-220,-220 -j[-2] [-1],{(@{-2,w}-w)/2},{@{-2,h}-16},0,0,-1 -rm[-1]
    0 -t[-1] "$10",0,0,13,1,-220,-220,-220 -rotate[-1] -90 -j[-2] [-1],2,{(@{-2,h}-h)/2},0,0,-1 -rm[-1]

  -nm $nm,1 -endl -done -c 0,255 -v +

#@gmic dh : eq. to '-display_histogram'.
dh :
  -_display_histogram $*

#@gmic display_histogram : _width>0,_height>0,_clusters>0,_min_value[%],_max_value[%],_show_axes={ 0 | 1 }
#@gmic : Render a channel-by-channel histogram.
#@gmic : (eq. to '-dh').
#@gmic : Default values: 'width=512', 'height=300', 'clusters=256', 'min_value=0%', 'max_value=100%' and 'show_axes=1'.
#@gmic : $ image.jpg --display_histogram 512,300
display_histogram :
  -_display_histogram $*

_display_histogram : -check "${1=512}>0 && ${2=300}>0 && ${3=256}>0" -skip ${4=0%},${5=100%},${6=1}
  -e[0--3] "Render $1x$2 channel-by-channel histogram of image$?, with $3 clusters and maximum value $4."
  -v - -repeat @# -l[$>] nm=@{0,n}
    -if @{"-is_percent $4"} m={im+(iM-im)*$4} -else m=$4 -endif
    -if @{"-is_percent $5"} M={im+(iM-im)*$5} -else M=$5 -endif
    -s c -histogram $3,$m,$M -a c vM={iM}
    $1,$2,1,{s},-255
    -repeat {s} -sh[-2,-1] $>,$> -graph[-1] [-2],3,0,$vM,0,1,0 -rm[-2,-1] -done
    -rm[-2] -+ 255
    -if $6 100%,100% -axes[-1] $m,$M,$vM,0,13,1,255 --dilate[-1] 3 -r[-2] [-3] -j[-3] [-2],0,0,0,0,1,[-1],255 -rm[-2,-1] -endif
  -nm $nm,1 -endl -done -v +

#@gmic dp : eq. to '-display_polar'.
dp :
  -_display_polar $*

#@gmic display_polar : _width>32,_height>32,_outline_type,_fill_R,_fill_G,_fill_B,_theta_start,_theta_end
#@gmic : Render polar curve from selected image data.
#@gmic : (eq. to '-dp').
#@gmic : 'outline_type' can be { r<0=dots with radius -r | 0=no outline | r>0=lines+dots with radius r }.
#@gmic : 'fill_color' can be { -1=no fill | R,G,B=fill with specified color }.
#@gmic : Default values: 'width=500', 'height=width', 'outline_type=1', 'fill_R=fill_G=fill_B=200', 'theta_start=0' and 'theta_end=360'.
#@gmic : $ 300,1,1,1,'0.3+abs(cos(10*pi*x/w))+?(0.4)' -display_polar 512,512,4,200,255,200
#@gmic : $ 3000,1,1,1,'x^3/1e10' -display_polar 400,400,1,-1,,,0,{15*360}
display_polar :
  -_display_polar $*

_display_polar : -check "${1=500}>32 && ${2=$1}>32" -skip ${3=1},${4=200},${5=$4},${6=$5},${7=0},${8=360}
  -e[0--3] "Render $1x$2 polar graph plot from data of image$?, with outline $4 and fill color ($4,$5,$6)."
  -v - -repeat @# -l[$>] nm=@{0,n}

    # Compute (x,y) coordinates of the polar curve points.
    M={max(abs(iM),abs(im))}
    -* {0.48*min($1,$2)/$M}
    -y y ({$7*pi/180};{-$8*pi/180}) -r[-1] 1,[-2],1,1,3
    --sin[-1] -cos[-2] -*[-1] [-3] -*[-3,-2]
    -a[-2,-1] x N={h}
    -nm[-1] coords

    # Generate 3d object for curve outline.
    -if $3
      ({'CImg3d'}) -+[-1] 0.5 ($N,$N)
      --z[coords] 0,2
      1,$N,1,1,2 1,$N,1,1,'y' --+[-1] 1 -a[-3--1] x -=[-1] 0,2,100%
      3,$N,1,1,0 1,$N,1,1,1 -y[-6--1] y -a[-6--1] y
      -nm[-1] _plot_polar_outline
    -endif

    # Generate 3d object for filling.
    -if {"$4>=0 && $5>=0 && $6>=0"}
      ({'CImg3d'}) -+[-1] 0.5 ({$N+1},$N)
      --z[coords] 0,-1,2,100% -z[-1] 0,2
      1,$N,1,1,3 1,$N 1,$N,1,1,'1+y' --+[-1] 1 -a[-4--1] x -=[-1] 1,3,100%
      3,$N,1,1,$4,$5,$6 1,$N,1,1,1
      -y[-6--1] y -a[-6--1] y
      -nm[-1] _plot_polar_fill
    -endif
    -rm[coords]  # Remove original curve coordinates.

    # Render graph image.
    {$1-32},{$2-32},1,3,255
    L={0.1*max($1,$2)} -grid[-1] $L,$L,0,0,0.25,0xCCCCCCCC,0  # Draw background grid.
    -if {"$4>=0 && $5>=0 && $6>=0"}                           # Draw curve filling.
      -object3d[-1] [_plot_polar_fill],50%,50%,0,1,2,0,0
      -rm[_plot_polar_fill]
    -endif
    -if $3
      -if {$3>=0}                                             # Draw curve outline.
        -object3d[-1] [_plot_polar_outline],50%,50%,0,1,1,0,0
      -endif
      -if {$3!=0}                                             # Draw curve vertices.
        -if {abs($3)>1} -circles3d[_plot_polar_outline] {abs($3)} -endif
        -object3d[-1] [_plot_polar_outline],50%,50%,0,0.2,2,0,0
      -endif
      -rm[_plot_polar_outline]
    -endif

    # Draw axes and frame.
    nM={$M/0.96}
    100%,100% -axes[-1] {-$nM},$nM,$nM,{-$nM},13,1,1
    --dilate[-1] 3 --[-1] [-2] -*[-1] 200 -eq[-2] 0
    -*[-3,-2] -+[-2,-1] -c[-1] 0,255
    -frame[-1] 1,1,128 -frame[-1] 15,15,220

  -nm $nm,1 -endl -done -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').
#@gmic : $ image.jpg --norm -threshold[-1] 40% -blur[-1] 3 -normalize[-1] 0,255 -append c -display_rgba
display_rgba :
  -_display_rgba

_display_rgba :
  -e[0--3] "Render RGBA image$? over a checkerboard background."
  -v - -to_a -repeat @# -l[$>]
    -i[0] (160,128;128,160) -nm[0] @{1,n} -r[0] 16,16 -r[0] [1],[1],1,{s-1},0,2 -compose_alpha
  -endl -done -v +

#@gmic dt : eq. to '-display_tensors'.
dt :
  -_display_tensors $*

#@gmic display_tensors : _size_factor>0,_ellipse_factor>=0,_colored_mode={ 0 | 1 }
#@gmic : Render selected mask field of 2x2 tensors with ellipses.
#@gmic : (eq. to '-dt').
#@gmic : Default values: 'size_factor=16', 'ellipse_factor=0.92', 'color_mode=1'.
#@gmic : $ image.jpg -diffusiontensors 0.7,0.6 -crop 60,10,90,30 --display_tensors ,
display_tensors :
  -_display_tensors $*

_display_tensors : -check "${1=16}>0 && ${2=0.92}>=0" -skip "${3=1}"
  -e[0--3] "Render field of 2x2 tensors from image$?, with size factor $1, ellipse factor $2 in "@{"s1=colored s0=masked -u $s$3"}" mode."
  -v -
  -if {$3} -repeat @# -l[$>]
    --_display_tensors $1,$2,0
    -s[0] c --min[0,2] -*[1] -1 -+[1,-1] -a[0-2] c
    -r[0] [-1],[-1] -n[0] 0,255 -*
  -endl -done -else -repeat @# -l[$>]
    w={w} h={h}
    -* {($2*$1/2)^2/max(abs(im),abs(iM))}     # Normalize tensor values.
    -s c -i[-2] [-2] -a c -s yx -r 2,2,1,1,-1 # Decompose field into list of 2x2 matrices.
    (0.5,0;0,0.5) -+[^-1] [-1] -rm[-1]        # Add 0.5*Id to ensure tensor positivity.
    -invert -y c -r $1,$1                     # Optimized code for ellipses drawing.
    $1,$1,1,1,'x' --[-1] {w/2}
    $1,$1,1,1,'y' --[-1] {h/2}
    --sqr[-1] -*[-2] [-3] -sqr[-3] -i[-2] [-2] -a[-4--1] c
    -*[^-1] [-1] -rm[-1] -compose_channels + -le 1
    -append_tiles $w,$h                       # Recompose ellipses as a tensor field.
  -endl -done -endif
  -v +

#@gmic dw : eq. to '-display_warp'.
dw :
  -_display_warp $*

#@gmic display_warp : _cell_size>0
#@gmic : Render selected 2d warping fields.
#@gmic : (eq. to '-dw').
#@gmic : Default value: 'cell_size=15'.
#@gmic : $ image.jpg -luminance -blur 5 -gradient -append c -display_warp ,
display_warp :
  -_display_warp $*

_display_warp : -check "${1=15}>0"
  -e[0--3] "Render 2d warping field$?, with cell size $1."
  -v - -repeat @# -l[$>]
    -if {d!=1||s!=2}
      -error[0--3] "Invalid image ["{@#-$>-1}"]: Dimensions "{w}","{h}","{d}","{s}" does not represent a 2d field of 2d vectors."
    -endif
    -i[0] 100%,100%,1,1,1 -grid[0] $1,$1 -nm[0] @{1,n}
    -warp[0] [1],1,1,0 -rm[1]
  -endl -done -* 255 -v +

#@gmic document_gmic : _format={ ascii | html | xml | bash | images },_image_path,_write_wrapper={ 0 | 1 }
#@gmic : Create documentation of .gmic command files (loaded as raw 'uchar' images), in specified format.
#@gmic : Default values: 'format=ascii', 'image_path=""' and 'write_wrapper=1'.\n
#@gmic : Example(s) : raw:file.gmic,uchar -document_gmic html,img
document_gmic : -skip ${1="ascii"},${2=""},${3=1}
  -if {!@#} -return -endif
  -v -1

  # Concatenate command data and split them into lines.
  _name=@{0,b} # Basename for the commands definition file.
  -if {@#>1} -i[1--2] (10) -endif -a y -m @{-1,t} -s -,10

  # Output header.
  -_document_gmic_header_$1[] $3

  # Define parsing variables.
  _subsection=0                              # Indice of current subsection.
  _example=0                                 # Indice of current example.
  _command=0                                 # Indice of current command.
  _path="$2"                                 # Path of example images.
  ks0="0" ks1="-k[0]"

  # Parse lines of the commands file.
  -repeat @# -l[$>] -if {h>7" && "{@{-1,0-5}'=='{'"#@gmic"'}}" && "(i(0,6)=={'" "'}" || "i(0,6)=={':'})} # Process only lines starting with '#@gmic'.
    -rows 7,100% -autocrop {'" "'}  # Discard '#@gmic'.
    -if {i!={':'}}

      # Reached line as '#@gmic Command : Arguments_line1 : Arguments_line2 : (qualifier)'.
      _command={$_command+1}
      -s -,{'": "'} -autocrop {'" "'}
      -_document_gmic_declaration_$1

    -else
      -rows 1,100% # Discard ':' char.
      -if {i=={':'}}

        # Reached line as '#@gmic :: Subsection name'.
        _subsection={$_subsection+1}
        -rows 1,100% -autocrop {'" "'} # Discard ':' character.
        -_document_gmic_subsection_$1

      -else
        -autocrop {'" "'}
        -if {i=={'$'}}

          # Reached line as '#@gmic : $ Example of use'.
          _example={$_example+1}
          -rows 1,100% -autocrop {'" "'} # Discard '$' character.
          _filename=$_path$_name$_example.jpg
          -_document_gmic_example_$1

        -else

          # Reached line as '#@gmic : description.'
          -_document_gmic_description_$1
        -endif
      -endif
    -endif
  -endif ${ks{@#!=0}} -endl -done
  -rm
  -_document_gmic_footer_$1[] $3


# Define document_gmic commands for html output.
_document_gmic_header_html :
  -if $1 -v + -e[] "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
\n<head>
\n<script type=\"text/javascript\" src=\"highslide/highslide.js\"></script>
\n<link rel=\"stylesheet\" type=\"text/css\" href=\"highslide/highslide.css\" />
\n<script type=\"text/javascript\">
\nhs.graphicsDir = 'highslide/graphics/';
\nhs.wrapperClassName = 'wide-border';
\n</script>
\n</head>
\n<body>
\n"
  -v - -endif
  -m "don : -_document_gmic_desc_on_html"
  -m "doff : -_document_gmic_desc_off_html"
  -m "eon : -_document_gmic_ex_on_html"
  -m "eoff : -_document_gmic_ex_off_html"
  _is_desc=0
  _is_ex=0
  _shortcut=0

_document_gmic_desc_on_html :
  -if $_is_desc
    -u "<br/>"
  -else
    -u "<p style=\"margin-left:100px\"><tt>"
    _is_desc=1
  -endif

_document_gmic_desc_off_html :
  -if $_is_desc
    -u "</tt></p>"
    _is_desc=0
  -else -u ""
  -endif

_document_gmic_ex_on_html :
  -if $_is_ex
    -u ""
  -else
    -u "<br/><table style=\"margin-left:100px\" width=\"75%\" bgcolor=\"#EEEEEE\" bordercolor=\"black\" border=\"1\" cellpadding=\"4\" cellspacing=\"0\">"\
       "<tr><td colspan=\"2\" bgcolor=\"#777777\"><font color=\"white\"><b>Example(s) of use:</b></font></td></tr>"
    _is_ex=1
  -endif

_document_gmic_ex_off_html :
  -if $_is_ex
    -u "</table>"
    _is_ex=0
  -else
    -u ""
  -endif

_document_gmic_subsection_html :
  -v +
  -e[] @{-eoff}@{-doff}"<br/><a name=\"subsection"$_subsection"\"><h3><font color=\"purple\">** <u>"@{0,t}"</u></font></h3></a>"
  -v -

_document_gmic_declaration_html :
  -if {{@{-1,t}'=='"(*)"}" || "{@{-1,t}'=='"(+)"}} qualifier=" "@{-1,t} -rm[-1] -else qualifier="" -endif
  s1="\n" s0=" |<br/>"
  -if {@#>1" && "{@{-1,0-6}'=='{'"eq. to "'}}}  # Declaration of a shortcut command.
    -rows[-1] 7,100% -autocrop[-1] {'.'} -autocrop[-1] {'" "'} -autocrop[-1] 39
    _shortcut$_shortcut=@{0,t}
    _shortcutlink$_shortcut=@{-1,t}
    _shortcutqualifier$_shortcut=$qualifier
    _shortcut={$_shortcut+1}
  -else                                         # Declaration of a regular command.
    -v +
    -e[] @{-eoff}@{-doff}"<p style=\"margin-left:20px\"><font color=\"green\">&nbsp;&nbsp;<b>-"@{0,t}$qualifier"</b>:</font>"
    -if {@#>1}
      -e[] "<p style=\"margin-left:150px\"><tt><i><font color=\"purple\">"
      -repeat {@#-1}
        -e[] @{{1+$>},t}${s{$<==0}}
      -done
      -e[] "</font></i></tt></p>"
    -else -e[] ""
    -endif
    -v -
  -endif

_document_gmic_description_html :
  -if {@{-1,0-12}'=='{'"Default value"'}}  # Reached line as '#@gmic : Default value(s) : ... '.
    -s +,{':'} -l[^0] -a y -endl -autocrop {':'} -autocrop {'" "'}
    -v +
    -if {@#>1} -e[] @{-don}"<br/><b>"@{0,t}"</b>: "@{-1,t}
    -else -e[] @{-don}"<br/>"@{0,t}
    -endif
    -v -

  -elif {@{-1,0-7}'=='{'"(eq. to "'}}      # Reached line as '#@gmic : (eq. to -shortcut)'.
    -v + -e[] @{-don}"<i><font color=\"blue\">"@{-1,t}"</font></i>" -v -

  -else                                    # Reached line as '#@gmic : description'.
    -if {(i<{'A'}" || "i>{'Z'})" && "i!=40" && "i!=39} -v + -e[] @{-don}"&nbsp;"@{-1,t} -v -
    -else -v + -e[] @{-don}@{-1,t} -v -
    -endif

  -endif

_document_gmic_example_html :
  -if $_filename -else # Generate picture only if the file doesn't yet exist.
     -m "foo : "@{-1,t}
     -l[] -v -99 -reset -foo -v -1 -_document_gmic -o $_filename,85 -rm -endl
     -uncommand foo
  -endif
  -v +
  -e[] @{-eon}"<tr><td width=\"40\"><div><a href=\""$_filename"\" class=\"highslide\" onclick=\"return hs.expand(this)\">"\
       "<font color=\"blue\">(view)</font></a><div class=\"highslide-caption\">"@{-1,t}"</div></div></td><td><tt>"@{-1,t}"</tt></td></tr>"
  -v -

_document_gmic_footer_html : -skip $1
  -if $_shortcut # Document shortcuts.
    _subsection={$_subsection+1}
    ({'"Commands shortcuts"'}) -_document_gmic_subsection_html[-1] -rm[-1]
    -v + -e[] "<p style=\"margin-left:20px\">"
    -repeat $_shortcut
      -e[] "<font color=\"green\"><b>&nbsp;&nbsp;-"${_shortcut$>}" "${_shortcutqualifier$>}"</b>:</font>"
      -e[] "<font color=\"blue\"><i>eq. to '"${_shortcutlink$>}"'</i></font><br/>"
    -done
    -e[] "</p>" -v -
  -endif
  -v +
  -e[] @{-eoff}@{-doff}"<p style=\"margin-left:100px\"><font color=\"blue\"><b>[ Total number of commands: "$_command" ]</b></font>"
  -v -
  -uncommand don
  -uncommand doff
  -uncommand eon
  -uncommand eoff

# Define document_gmic commands for XML output.
_document_gmic_header_xml :
  -if $1 -v +
    -e[] "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
\n<?xml-stylesheet href=\"gmic_doc.xsl\" type=\"text/xsl\"?>"
  -v - -endif
  -v +
  -e[] "<gmic-package xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"gmic_doc.xsd\">
\n<name>"$_name"</name>
\n<section>
\n  <name>List of commands</name>"
  -v -
  -m "don : -_document_gmic_desc_on_xml"
  -m "doff : -_document_gmic_desc_off_xml"
  _is_subsection=0
  _is_command=0
  _is_desc=0

_document_gmic_desc_on_xml :
  -if $_is_desc
    -u ""
  -else
    -u "    <description>\n"
    _is_desc=1
  -endif

_document_gmic_desc_off_xml :
  -if $_is_desc
    -u "    </description>\n"
    _is_desc=0
  -else -u ""
  -endif

_document_gmic_subsection_xml :
  -v +
  -if $_is_subsection
    -if $_is_command -e[] @{-doff}"  </function>" -endif
    -e[] @{-doff}"</subsection>"
  -endif
  -e[] @{-doff}"<subsection>
\n  <name>"@{0,t}"</name>"
  -v -
  _is_subsection=1
  _is_command=0

_document_gmic_declaration_xml :
  -_document_gmic_replace_xml
  -v +
  -if $_is_command -e[] @{-doff}"  </function>" -endif
  -e[] @{-doff}"  <function>"
  -v -
  _is_command=1
  -if {{@{-1,t}'=='"(*)"}" || "{@{-1,t}'=='"(+)"}} qualifier=" "@{-1,t} -rm[-1] -else qualifier="" -endif
  s1="" s0=" |"
  -v +
  -e[] "    <name>"@{0,t}"</name>"
  -if {@#>1}
    -e[] "    <arguments>"
    -repeat {@#-1}
      -e[] "      "@{{1+$>},t}${s{$<==0}}
    -done
    -e[] "    </arguments>"
  -endif
  -v -

_document_gmic_description_xml :
  -_document_gmic_replace_xml
  -v +
  -e[] @{-don}"      "@{0,t}
  -v -

_document_gmic_example_xml :
  -_document_gmic_replace_xml
   -if $_filename -else # Generate picture only if the file doesn't yet exist.
      -m "foo : "@{-1,t}
      -l[] -v -99 -reset -foo -v -1 -_document_gmic -o $_filename,85 -rm -endl
      -uncommand foo
   -endif
   -v +
   -e[] @{-doff}"    <example>"
   -e[] "      <command>"@{0,t}"</command>"
   -e[] "      <result>"$_filename"</result>"
   -e[] "    </example>"
   -v -

_document_gmic_footer_xml : -skip $1
  -v +
  -if $_is_command -e[] @{-doff}"</function>" -endif
  -if $_is_subsection -e[] @{-doff}"</subsection>" -endif
  -e[] @{-doff}"</section>
\n</gmic-package>"
  -v -
  -uncommand don
  -uncommand doff

_document_gmic_replace_xml :
  -replace_seq {'&'},@{-quote\ {'&amp;'}} # Replace '&'
  -replace_seq {'<'},@{-quote\ {'&lt;'}}  # Replace '<'
  -replace_seq {'>'},@{-quote\ {'&gt;'}}  # Replace '>'


# Define document_gmic commands for LateX output.
_document_gmic_header_latex :
  -if $1 -v +
    -e[] "\\documentclass[a4paper,10pt,twoside]{book}
\n\\usepackage{hyperref,fancyhdr,graphicx,amssymb,amsmath,times,makeidx}
\n\\graphicspath{{"$_path"}}
\n\\pagestyle{fancyplain}
\n\\lhead[\\fancyplain{}{\\textbf\\thepage}]{\\fancyplain{}{\\rightmark}}
\n\\rhead[\\fancyplain{}{\\leftmark}]{\\fancyplain{}{\\textbf\\thepage}}
\n\\cfoot{}
\n\\setlength{\\textwidth}{5.875in}
\n\\setlength{\\parindent}{0pc}
\n\\setlength{\\hoffset}{-0.8cm}
\n\\setcounter{tocdepth}{1}
\n\\sloppy{}
\n\\renewcommand\\indexname{Index of commands}
\n\\makeindex
\n\\begin{document}
\n\\tableofcontents"
  -v - -endif
  -v + -e[] "\n\\chapter{List of commands}" -v -
  -m "eon : -_document_gmic_ex_on_latex"
  -m "eoff : -_document_gmic_ex_off_latex"
  _is_desc=0
  _is_ex=0
  _shortcut=0

_document_gmic_ex_on_latex :
  -if $_is_ex
    -u "\\\\"
  -else
    -u "\\begin{center}"
    _is_ex=1
  -endif

_document_gmic_ex_off_latex :
  -if $_is_ex
    -u "\\end{center}"
    _is_ex=0
  -else
    -u ""
  -endif

_document_gmic_subsection_latex :
  _is_desc=0
  -_document_gmic_replace_latex
  -v + -e[] @{-eoff}"\n\\section{"@{0,t}"}" -v -

_document_gmic_declaration_latex :
  _is_desc=0
  -if {{@{-1,t}'=='"(*)"}" || "{@{-1,t}'=='"(+)"}} qualifier=@{-1,t} -rm[-1] -else qualifier="" -endif
  e1="\\\\~\\\\" e0="~~~$|$\\\\"
  s1="\\hspace*{2.2cm}" s0=""
  -_document_gmic_replace_latex

  -if {@#>1" && "{@{-1,0-6}'=='{'"eq. to "'}}}  # Declaration of a shortcut command.
    -rows[-1] 7,100% -autocrop[-1] {'.'} -autocrop[-1] {'" "'} -autocrop[-1] 39
    _shortcut$_shortcut=@{0,t}
    _shortcutlink$_shortcut=@{-1,t}
    _shortcutqualifier$_shortcut=$qualifier
    _shortcut={$_shortcut+1}
  -else                                         # Declaration of a regular command.
    -v +
    -e[] @{-eoff}"\n\n\\subsection{\\emph{-"@{0,t}"\\index{-"@{0,t}"}} "$qualifier"}\\vspace*{-0.5em}"
    -if {@#>1}
      -e[] "~\\\\\\textbf{Arguments: } "
      -repeat {@#-1}
         -e[] ${s{$>!=0}}"{\\small \\texttt{"@{{1+$>},t}"}}"${e{$<==0}}
      -done
    -endif
    -v -
  -endif

_document_gmic_description_latex :
  s0="" s1="~\\\\" s=${s$_is_desc}
  -_document_gmic_replace_latex
  -if {@{-1,0-12}'=='{'"Default value"'}}  # Reached line as '#@gmic : Default value(s) : ... '.
    -s +,{':'} -l[^0] -a y -endl -autocrop {':'} -autocrop {'" "'}
    -if {@#>1}
      -replace_seq[1] @{-quote\ {'" and "'}},@{-quote\ {'"} and \\\\texttt{"'}}
      -v + -e[] @{-eoff}$s"~\\\\\\textbf{"@{0,t}"}: {\\small \\texttt{"@{-1,t}"}}" -v -
    -else -v + -e[] @{-eoff}$s"~\\\\"@{0,t} -v -
    -endif
  -elif {@{-1,0-7}'=='{'"(eq. to "'}}      # Reached line as '#@gmic : (eq. to '-shortcut').'.
    -rows[-1] 8,100% -autocrop[-1] {'.'} -autocrop[-1] {')'} -autocrop[-1] {'" "'}
    -v + -e[] @{-eoff}$s"(\\emph{eq. to} {\\small \\texttt{"@{-1,t}"}})." -v -
  -else                                    # Reached line as '#@gmic : description'.
    -if {(i<{'A'}" || "i>{'Z'})" && "i!=40" && "i!=39} -v + -e[] @{-eoff}@{-1,t} -v -
    -else -v + -e[] @{-eoff}$s@{-1,t} -v -
    -endif
  -endif
  _is_desc=1

_document_gmic_example_latex :
  _is_desc=0
  -if $_filename -else # Generate picture only if the file doesn't yet exist.
     -m "foo : "@{-1,t}
     -l[] -v -99 -reset -foo -v -1 -_document_gmic -o $_filename,85 -rm -endl
     -uncommand foo
  -endif
  -_document_gmic_replace_latex
  -v +
  -e[] @{-eon}"\\includegraphics[keepaspectratio=true,height=7cm,width=\\textwidth]{"$_filename"}\\\\"
  -e[] "{\\footnotesize \\textbf{Example "$_example"~:} \\texttt{"@{-1,t}"}}"
  -v -

_document_gmic_footer_latex :
  -if $_shortcut # Document shortcuts.
    ({'"Commands shortcuts"'}) -_document_gmic_subsection_latex[-1] -rm[-1]
    -v + -repeat $_shortcut
      -e[] "$\\bullet$~'\\texttt{-"${_shortcut$>}"}' "${_shortcutqualifier$>}"~is equivalent to~~'\\texttt{"${_shortcutlink$>}"}'.\\\\"
    -done -v -
  -endif
  -if $1
    -v +
    -e[] "
\n\\printindex
\n~\\\\$\\square$~End of document.
\n\n\\end{document}"
    -v -
  -endif
  -uncommand eon
  -uncommand eoff

_document_gmic_replace_latex :
  -replace_seq {'\\'},@{-quote\ {'"\\\\textbackslash "'}} # Replace '\'
  -replace_seq {'_'},@{-quote\ {'\\\\_'}} # Replace '_'
  -replace_seq {'%'},@{-quote\ {'\\\\%'}} # Replace '%'
  -replace_seq {'#'},@{-quote\ {'\\\\%'}} # Replace '#'
  -replace_seq {'^'},@{-quote\ {'"\\\\textasciicircum "'}} # Replace '^'
  -replace_seq {'$'},@{-quote\ {'\\\\$'}} # Replace '$'
  -replace_seq {'\{'},@{-quote\ {'\\\\\{'}} # Replace '{'
  -replace_seq {'\}'},@{-quote\ {'\\\\\}'}} # Replace '}'
  -replace_seq {'&'},@{-quote\ {'\\\\&'}} # Replace '&'
  -replace_seq {'|'},@{-quote\ {'~$|$~'}} # Replace '|'
  -replace_seq {'<'},@{-quote\ {'$\<$'}} # Replace '<'
  -replace_seq {'>'},@{-quote\ {'$\>$'}} # Replace '>'

# Define document_gmic commands for images-only output.
_document_gmic_header_images : -skip $1
  -v +
  -e[] "\n - Generate example images from set of commands '"$_name"'.\n"
  -v -

_document_gmic_subsection_images : -_document_gmic_subsection_ascii
_document_gmic_declaration_images : _command_name=@{0,t}
_document_gmic_description_images :

_document_gmic_example_images :
  -v +
  -e[] "    . Command '-"$_command_name"': $ "@{-1,t}
  -v -
  -if $_filename -else # Generate picture only if the file doesn't yet exist.
     -m "foo : "@{-1,t}
     -l[] -v -1 -reset -v -99 -foo -v -1 -_document_gmic -o $_filename,85 -rm -endl
     -uncommand foo
  -endif

_document_gmic_footer_images : -skip $1
  -v +
  -e[] "\n - [ All done! ]\n\n"
  -v -

# Define document_gmic commands for ascii output.
_document_gmic_header_ascii : -skip $1
  _shortcut=0

_document_gmic_subsection_ascii :
  -v +
  -e[] "\n ** "@{0,t}":"
  -v -

_document_gmic_declaration_ascii :
  -if {{@{-1,t}'=='"(*)"}" || "{@{-1,t}'=='"(+)"}} qualifier=" "@{-1,t} -rm[-1] -else qualifier="" -endif
  -if {@#>1" && "{@{-1,0-6}'=='{'"eq. to "'}}}  # Declaration of a shortcut command.
    -rows[-1] 7,100% -autocrop[-1] {'.'} -autocrop[-1] {'" "'} -autocrop[-1] 39
    _shortcut$_shortcut=@{0,t}
    _shortcutlink$_shortcut=@{-1,t}
    _shortcutqualifier$_shortcut=$qualifier
    _shortcut={$_shortcut+1}
  -else                                         # Declaration of a regular command.
    -v + -e[] "\n    -"@{0,t}${qualifier}":" -v - -rm[0]
    -if @#
      s="                        "
      -y x
      -repeat {@#-1} ({'" |"'}) -a[$>,-1] x -done  # Insert ' |'.
      -repeat @# -l[$>] -s x,-80
        -repeat {@#-1} ({'\\\\\n$s"  "'}) -a[$>,-1] x -done # Split with '\\'.
        -a x -v + -e[] $s@{0,t} -v -
      -endl -done
    -endif
    -v + -e[] "" -v -
  -endif

_document_gmic_description_ascii :
  s="        "
  -y x -s x,-96
  -if {@#>1} -repeat {@#-1} ({'\\\\\n$s"  "'}) -a[$>,-1] x -done -a x -endif
  -v + -repeat @# -e[] $s@{$>,t} -v - -done

_document_gmic_example_ascii :

_document_gmic_footer_ascii : -skip $1
  -if $_shortcut # Document shortcuts.
    ({'"Commands shortcuts"'}) -_document_gmic_subsection_ascii[-1] -v + -e[] "" -v - -rm[-1]
    -v + -repeat $_shortcut
      -e[] "    -"${_shortcut$>}" "${_shortcutqualifier$>}": eq. to '"${_shortcutlink$>}"'."
    -done -v -
  -endif
  -v + -e[] "\n   [ Total number of commands: "$_command" ]" -v -

# Define document_gmic commands for bash auto-completion script output.
_document_gmic_header_bash : -skip $1
  -v +
  -e[] "\#
\n\#  Bash completion rules for 'gmic'.
\n\#
\n\# This file has been generated automatically.
\n\# Do not edit!
\n\#
\n\# This file should be copied/renamed in '/etc/bash_completion.d/gmic'.
\n\#
\n
\n_"$_name"()
\n{
\n\tlocal cur prev opts coms
\n\tCOMPREPLY=()
\n\tcur=\"${COMP_WORDS[COMP_CWORD]}\"
\n\tprev=\"${COMP_WORDS[COMP_CWORD-1]}\"
"
  -v -
  _opts="\topts=\""
  _coms="\tcoms=\""
  _argcommand=0
  _shortcut=0

_document_gmic_subsection_bash :
_document_gmic_description_bash :
_document_gmic_example_bash :

_document_gmic_declaration_bash :
  _opts=$_opts-@{0,t}" "--@{0,t}" "
  _coms=$_coms@{0,t}" "
  -if {{@{0,t}'=='"input"}" || "{@{0,t}'=='"i"}" || "\ # Manage special commands (remove arguments).
       {@{0,t}'=='"output"}" || "{@{0,t}'=='"o"}" || "\
       {@{0,t}'=='"command"}" || "{@{0,t}'=='"m"}} -return -endif
  -repeat @# -if {{@{$<,t}'=='"(*)"}||{@{$<,t}'=='"(+)"}} -rm[$<] -endif -done # Discard '(*)' and '(+)' qualifiers.
  -if {@#==2" && "{@{-1,0-6}'=='{'"eq. to "'}}} # Command is a shortcut.
    -rows[-1] 7,100% -autocrop[-1] {'.'} -autocrop[-1] {'" "'} -autocrop[-1] 39 -autocrop[-1] {'-'}
    _shortcut$_shortcut=@{0,t}
    _shortcutlink$_shortcut=@{-str2hex\ @{1,t}}
    -rm[-1]
    _shortcut={$_shortcut+1}
  -elif {@#>1} # Command is regular and has arguments.
    _command$_argcommand=@{0,t}
    -if {@{0,t}'=='"help"} _argument$_argcommand="$coms\" -- \"$cur"  # Manage help command.
    -else
      -if {@#==2} ({'>'}) -endif # Add shadow parameter when single argument.
      -discard[^0] {'" "'} -i[2--2] ({'" "'}) -a[^0] y
      _argument$_argcommand=@{1,t}
    -endif
    _argumentlink@{-str2hex\ @{0,t}}=${_argument$_argcommand}
    _argcommand={$_argcommand+1}
  -endif

_document_gmic_footer_bash : -skip $1
  -v +
  -e[] $_opts\"
  -e[] "\n"$_coms\"
  -e[] "\n\tcase \"${prev}\" in"
  -repeat $_argcommand  # Regular commands with arguments.
    -e[] "\t\t\"-"${_command$>}"\" | \"--"${_command$>}"\")"
    -e[] "\t\tCOMPREPLY=( $(compgen -W \""${_argument$>}"\") )\n\t\treturn 0\n\t\t;;"
  -done
  -repeat $_shortcut # Shortcut commands (with arguments).
    -if {narg(${_argumentlink${_shortcutlink$>}})}
      -e[] "\t\t\"-"${_shortcut$>}"\" | \"--"${_shortcut$>}"\")"
      -e[] "\t\tCOMPREPLY=( $(compgen -W \""${_argumentlink${_shortcutlink$>}}"\") )\n\t\treturn 0\n\t\t;;"
    -endif
  -done
  -e[] "\tesac"
  -e[] "\n\tif [[ \"$cur\" == -* ]] ; then
\n\t\tCOMPREPLY=( $(compgen -W \"$opts\" -- \"$cur\") )
\n\telse
\n\t\t_filedir
\n\tfi
\n
\n}
\n
complete -F _"$_name" -o filenames gmic"
  -v -

# Generate a single image from a list of images, for the reference documentation.
_document_gmic :
  -repeat @# -l[$>] W$>={w} H$>={h} D$>={d} S$>={s} IS_3D$>=@{-is_3d} -endl -done
  -repeat @# -l[$>] -if @{-is_3d} -+3d 0 -r3d 1,1,0,-80 -r3d 0,1,0,80 -snapshot3d 400 -else -n 0,255 -endif -endl -done
  --append_tiles , -if {w>900} r={round(900*100/w,0.1)} -r[^-1] $r%,$r%,1,100%,2 -endif -rm[-1]
  -repeat @# -l[$>]
    -if {s==1} -r {w},{h},1,3 -else -r {w},{h},1,3,0 -endif
    -if {w<=h&&h<256} -r2dy 256 -elif {h<=w&&w<256} -r2dx 256 -endif
    -if {w<=h&&h>512} -r2dy 512 -elif {h<=w&&w>512} -r2dx 512 -endif
    -if {h<48} -r 100%,48 -endif
    -if {w<48} -r 48,100% -endif
    -frame 1,1,0 -frame 4,4,255
  -endl -done
  N=@# -repeat $N -l[$>]
    {w},24,1,3,255
    -if {w>75}
      -if {$N>1} -if {w>110} -t[-1] Image\ [$>]:,3,3,17 -else -t[-1] [$>]:,3,3,17 -endif -endif
      -if ${IS_3D$>} 0 -t[-1] (3d\ object),0,0,13,1,255
      -else 0 -t[-1] (${W$>}x${H$>}x${D$>}x${S$>}),0,0,13,1,255
      -endif
      -negative[-1] -n[-1] 0,255 -+[-1] 164 -c[-1] 0,255 -to_rgb[-1]
      -j[-2] [-1],{@{-2,w}-w-5},{@{-2,h}-h-5} -rm[-1]
    -else -t[-1] [$>]:,3,3,17 -endif
    -rv[-2,-1] -a[-2,-1] y
  -endl -done
  -- 255 -append_tiles , -+ 255

#@gmic e : eq. to '-echo'. : (*)

#@gmic echo : message : (*)
#@gmic : Output specified message, on the standard output.
#@gmic : (eq. to '-e').
#@gmic : Command subset (if any) stands for displayed scope indices instead of image indices.

#@gmic function1d : 0<=smoothness<=1,x0>=0,y0,x1>=0,y1,...,xn>=0,yn
#@gmic : Input continuous 1d function from specified list of keypoints (xk,yk)
#@gmic : in range [0,max(xk)] (xk are positive integers).
#@gmic : Default values: 'smoothness=1' and 'x0=y0=0'.
#@gmic : $ -function1d 1,0,0,10,30,40,20,70,30,80,0 --display_graph 400,300
function1d : -check "${1=1}>=0 && $1<=1" -skip ${2=0},${3=0}
  -e[^-1] "Input continuous 1d function, with smoothness $1 and keypoints (${2--1})."
  -v -

  # Normalize input coordinates.
  -if {$#<5} {max(0,$2)+1},1,1,1,$3 -v + -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} -j[-2] [-1],$xstart -rm[-1]
  -shift[-2] 0,-1 -done
  -rm[-2] -nm[-1] "[1d function (${2--1})]"
  -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 --^[-1] 3 --^[-2] 2 --f[-1] 1 -mv[-4] -1 -a[-4--1] y
  -**[-2,-1]

#@gmic gmicky
#@gmic : Load a new image of the G'MIC mascot 'Gmicky'.
#@gmic : $ -gmicky
gmicky :
  -e[^-1] "Load image of the G'MIC mascot 'Gmicky'."
  -v - -i http://gmic.sourceforge.net/img/gmicky_large.cimgz -nm[-1] [gmicky] -v +

#@gmic gmicky_wilber
#@gmic : Load a new image of the G'MIC mascot 'Gmicky' together with GIMP mascot 'Wilber'.
#@gmic : $ -gmicky_wilber
gmicky_wilber :
  -e[^-1] "Load image of the G'MIC mascot 'Gmicky' together with GIMP mascot 'Wilber'."
  -v - -i http://gmic.sourceforge.net/img/gmicky_wilber_large.cimgz -nm[-1] [gmicky_wilber] -v +

#@gmic i : eq. to '-input'. : (*)

#@gmic input : [type:]filename : [type:]http://URL : [selection]x_nb_copies>0 : { width>0[%] | [image_w] },{ _height>0[%] | [image_h] },{ _depth>0[%] | [image_d] },{ _spectrum>0[%] | [image_s] },_{ value1,_value2,.. | 'formula' } : (value1{,|;|/|^}value2{,|;|/|^}..) : 0 : (*)
#@gmic : Insert a new image taken from a filename or from a copy of an existing image ['indice'],"
#@gmic : or insert new image with specified dimensions and values. Single quotes may be omitted in
#@gmic : 'formula'. Specifying argument '0' inserts an 'empty' image.
#@gmic : (eq. to '-i' | (no args)).
#@gmic : Default values: 'nb_copies=1', 'height=depth=spectrum=1' and 'value1=0'.
#@gmic : $ -input image.jpg
#@gmic : $ -i (1,2,3;4,5,6;7,8,9^9,8,7;6,5,4;3,2,1)
#@gmic : $ image.jpg (1,2,3;4,5,6;7,8,9) (255^128^64) 400,400,1,3,'if(x>w/2,x,y)*c'

#@gmic o : eq. to '-output'. : (*)

#@gmic output : [type:]filename,_format_options : (*)
#@gmic : Output selected images as one or several numbered file(s).
#@gmic : (eq. to '-o').
#@gmic : Default value: 'format_options'=(undefined).

#@gmic on : eq. to '-outputn'.
on :
  -_outputn $*

#@gmic outputn : filename
#@gmic : Output selected images as automatically numbered filenames in repeat..done loops.
#@gmic : (eq. to '-on').
outputn :
  -_outputn $*

_outputn :
  -v - filename=@{"-filename \"$1\","@{>}} -v +
  -e[0--3] "Output image$? as file '"$filename"'."
  -v - -o $filename -v +

#@gmic op : eq. to '-outputp'.
op :
  -_outputp $*

#@gmic outputp : prefix
#@gmic : Output selected images as prefixed versions of their original filenames.
#@gmic : (eq. to '-op').
#@gmic : Default value: 'prefix=_'.
outputp :
  -_outputp $*

_outputp : -skip ${1="_"}
  -if {@#>1} -e[0--4] "Output image$? as their initial locations, prefixed by '$1'."
  -else -e[0--4] "Output image$? as its initial location, prefixed by '$1'."
  -endif
  -v - -repeat @# -o[$>] @{$>,f}$1@{$>,b}.@{$>,x} -done -v +

#@gmic ow : eq. to '-outputw'.
ow :
  -_outputw $*

#@gmic outputw
#@gmic : Output selected images by overwritting their original location.
#@gmic : (eq. to '-ow').
outputw :
  -_outputw $*

_outputw :
  -if {@#>1} -e[0--4] "Output image$? as their initial location."
  -else -e[0--4] "Output image$? as its initial location."
  -endif
  -v - -repeat @# -o[$>] @{$>,n} -done -v +

#@gmic plot : _plot_type,_vertex_type,_xmin,_xmax,_ymin,_ymax : 'formula',_resolution>=0,_plot_type,_vertex_type,_xmin,xmax,_ymin,_ymax : (+)
#@gmic : Display selected image or formula in an interactive viewer (use the instant window [0] if opened).
#@gmic : 'plot_type' can be { 0=none | 1=lines | 2=splines | 3=bar }.
#@gmic : 'vertex_type' can be { 0=none | 1=points | 2,3=crosses | 4,5=circles | 6,7=squares }.
#@gmic : 'xmin','xmax','ymin','ymax' set the coordinates of the displayed xy-axes.
#@gmic : Default values: 'plot_type=1', 'vertex_type=1' and 'xmin=xmax=ymin=ymax=0 (auto)'.

#@gmic p : eq. to '-print'. : (*)

#@gmic print : (*)
#@gmic : Output informations on selected images, on the standard output.
#@gmic : (eq. to '-p').

#@gmic rainbow_lut
#@gmic : Input a 256-entries RGB colormap of rainbow colors.
#@gmic : $ image.jpg -rainbow_lut --luminance[-2] -map[-1] [-2]
rainbow_lut :
  -e[^-1] "Input RGB colormap of 256 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)
  -nm[-1] [rainbow\ lut]
  -v +

#@gmic roddy
#@gmic : Load a new image of the G'MIC Rodilius mascot 'Roddy'.
#@gmic : $ -roddy
roddy :
  -e[^-1] "Load image of the G'MIC Rodilius mascot 'Roddy'."
  -v - -i http://gmic.sourceforge.net/img/roddy_large.cimgz -nm[-1] [roddy] -v +

#@gmic rm_duplicates
#@gmic : Remove duplicates images in the selected images list.
#@gmic : $ (1,2,3,4,2,4,3,1,3,4,2,1) -split x -rm_duplicates -append x
rm_duplicates :
  -e[^-1] "Remove duplicates images in selected list of image$?."
  -v - -repeat @#
    base=$> off=0
    -repeat {@#-$>-1}
      comp={$base+1+$>-$off}
      -if {$comp>=@#} -break -endif
      ---[$base,$comp] -abs[-1] is_duplicate={!@{-1,+}} -rm[-1]
      -if $is_duplicate -rm[$comp] off={$off+1} -endif
    -done
  -done -v +

#@gmic select : feature_type,_X,_Y,_Z : (+)
#@gmic : Interactively select a feature from selected images (use the instant window [0] if opened).
#@gmic : 'feature_type' can be { 0=point | 1=segment | 2=rectangle | 3=ellipse }.
#@gmic : Arguments 'X','Y','Z' determine the initial selection view, for 3d volumetric images.
#@gmic : The retrieved feature is returned as a 3d or 6d vector containing the feature coordinates.

#@gmic sh : eq. to '-shared'. : (*)

#@gmic shared : x0[%],x1[%],y[%],z[%],v[%] : y0[%],y1[%],z[%],v[%] : z0[%],z1[%],v[%] : v0[%],v1[%] : (no args) : (*)
#@gmic : Insert shared buffers from (opt. points/rows/planes/channels of) selected images.
#@gmic : (eq. to '-sh').
#@gmic : $ image.jpg --shared 1,1 -blur[-1] 3 -remove[-1]
#@gmic : $ image.jpg -repeat {s} --shared 25%,75%,0,$> -mirror[-1] x -remove[-1] -done

#@gmic sort_list : _ordering={ + | - },_x,_y,_z,_c
#@gmic : Sort list of selected images according to their value located at (x,y,z,c).
#@gmic : Default values: 'ordering=+', 'x=0', 'y=0', 'z=0' and 'c=0'.
#@gmic : $ (1;4;7;3;9;2;4;7;6;3;9;1;0;3;3;2) -split y -sort_list + -append y
sort_list : -skip ${1=+},${2=0},${3=0},${4=0},${5=0}
  -e[^-1] "Sort list of image$? in "@{"-if {$1'=='+} -u ascending -else -u descending -endif"}" order, "\
          "according to their value located at ($2,$3,$4,$5)."
  -v - -if @#
    i=@# --z $2,$3,$4,$5,$2,$3,$4,$5 -a[$i--1] y --f[-1] 'y' -a[-2,-1] x -sort[-1] $1,y -z[-1] 1,1
    -repeat {h} nm$>=@{$>,n} -nm[$>] sortlist$> -done
    -repeat {h} -mv[sortlist{i(0,$>)}] -1 -done
    -repeat {h} -nm[$>] ${nm{i(0,$>)}} -done
  -rm[-1] -endif -v +

#@gmic srand : value : (no args) : (*)
#@gmic : Set random generator seed.
#@gmic : If no argument is specified, a random value is used as the random generator seed.

#@gmic testimage2d : _width>0,_height>0,_spectrum>0
#@gmic : Input a 2d synthetic image.
#@gmic : Default values: 'width=512', 'height=width' and 'spectrum=3'.
#@gmic : $ -testimage2d 512
testimage2d : -check "${1=512}>0 && ${2=$1}>0 && ${3=3}>0"
  -e[^-1] "Input 2d synthetic image of size $1x$2x$3."
  -v -
  Dmax2={0.15*min($1,$2)^2}
  $1,$2,1,$3,'X=x-w/2;Y=y-h/2;a=atan2(Y,X);if(X^2+Y^2<=$Dmax2,255*abs(cos(c+200*(x/w-0.5)*(y/h-0.5))),850*(a%(0.1*(c+1))))'
  -polygon[-1] 4,20%,20%,60%,20%,70%,70%,35%,45%,0.9,0,255,0
  -torus3d {$1/7},{$1/20} -r3d[-1] 0,1,1,80 -col3d[-1] 128,200,255
  -object3d[-2] [-1],30%,70%,0,1,5,0,0 -rm[-1] -nm[-1] "[2d test image]"
  -v +

#@gmic text2img : text,_line_separator
#@gmic : Input a 2d image whose values are ASCII characters of specified input text.
#@gmic : Default value: 'line_separator= '.
#@gmic : $ -text2img "There are 4 words"
text2img : -skip "${2= }"
  -e[^-1] "Input image from text \"$1\", with line separator '$2'."
  -v - ({'"$1"'}) -l[-1] -s -,{'"$2"'} -y x -a y -nm "[\"$1\"]" -endl -v +

#@gmic type : datatype : (*)
#@gmic : Set pixel datatype for all images of the list.
#@gmic : 'datatype' can be { bool | uchar | char | ushort | short | uint | int | float | double }.

#@gmic uncommand : command_name : * : (*)
#@gmic : Discard last definition of specified custom command.
#@gmic : Set argument to '*' for discarding all existing custom commands.

#@gmic up : eq. to '-update'.
up :
  -_update

#@gmic update
#@gmic : Update commands from the latest definition file on the G'MIC server.
#@gmic : This requires an active Internet connection and an access to the external
#@gmic : tools 'curl' or 'wget'.
#@gmic : (eq. to '-up').
update :
  -_update

_update :
  -e[0--3] "Update commands from the latest definition file on the G'MIC server."
  -v - -m http://gmic.sourceforge.net/gmic_def.@. -v +

#@gmic v : eq. to '-verbose.' : (*)

#@gmic verbose : level : { + | - } : (*)
#@gmic : Set or increment/decrement the verbosity level.
#@gmic : (eq. to '-v').
#@gmic : When 'level'>=0, G'MIC log messages are displayed on the standard output.
#@gmic : Default value for the verbosity level is 0.

#@gmic wait : delay : (no args) : (+)
#@gmic : Wait for a given delay (in ms) or for a user event occuring on the selected instant window.
#@gmic : 'delay' can be { <0=delay+flush |  0=event | >0=delay }.
#@gmic : Command subset (if any) stands for instant window indices instead of image indices.

#@gmic warn : message : (*)
#@gmic : Print specified warning message, on the standard output.
#@gmic : Command subset (if any) stands for displayed scope indices instead of image indices.

#@gmic w : eq. to '-window'. : (+)

#@gmic window : _width[%]>=-1,_height[%]>=-1,_normalization,_fullscreen,_title : (+)
#@gmic : Display selected images into an instant window with specified size, normalization type,
#@gmic : fullscreen mode and title.
#@gmic : (eq. to '-w').
#@gmic : If 'width' or 'height' is set to -1, the corresponding dimension is adjusted to the window
#@gmic : or image size.
#@gmic : 'width'=0 or 'height'=0 closes the instant window.
#@gmic : 'normalization' can be { -1=keep same | 0=none | 1=always | 2=1st-time | 3=auto }.
#@gmic : 'fullscreen' can be { -1=keep same | 0=no | 1=yes }.
#@gmic : You can manage up to 10 different instant windows by using the numbered variants
#@gmic : '-w0' (default, eq. to '-w'),'-w1',..,'-w9' of the command '-w'.
#@gmic : Default values: 'width=height=normalization=fullscreen=-1' and 'title=(undefined)'.

#---------------------------------
#
#@gmic :: List manipulation
#
#---------------------------------

#@gmic k : eq. to '-keep'. : (*)

#@gmic keep : (*)
#@gmic : Keep only selected images.
#@gmic : (eq. to '-k').
#@gmic : $ image.jpg -split x -keep[0-50%:2] -append x
#@gmic : $ image.jpg -split x -keep[^30%-70%] -append x

#@gmic mv : eq. to '-move'. : (*)

#@gmic move : position[%] : (*)
#@gmic : Move selected images at specified position.
#@gmic : (eq. to '-mv').
#@gmic : $ image.jpg -split x,3 -move[1] 0
#@gmic : $ image.jpg -split x -move[50%--1:2] 0 -append x

#@gmic nm : eq. to '-name'. : (*)

#@gmic name : name,_is_modified={ 0 | 1 } : (*)
#@gmic : Set name of selected images.
#@gmic : (eq. to '-nm').
#@gmic : Argument 'is_modified' tells about the modified state of selected images.
#@gmic : Default value: 'is_modified=0'.
#@gmic : $ image.jpg -name image -blur[image] 2

#@gmic rm : eq. to '-remove'. : (*)

#@gmic remove : (*)
#@gmic : Remove selected images.
#@gmic : (eq. to '-rm').
#@gmic : $ image.jpg -split x -remove[30%-70%] -append x
#@gmic : $ image.jpg -split x -remove[0-50%:2] -append x

#@gmic rv : eq. to '-reverse'. : (*)

#@gmic reverse : (*)
#@gmic : Reverse positions of selected images.
#@gmic : (eq. to '-rv').
#@gmic : $ image.jpg -split x,3 -reverse[-2,-1]
#@gmic : $ image.jpg -split x,-16 -reverse[50%-100%] -append x

#---------------------------------
#
#@gmic :: Mathematical operators
#
#---------------------------------

#@gmic abs : (+)
#@gmic : Compute the pointwise absolute values of selected images.
#@gmic : $ image.jpg --sub {ia} -abs[-1]
#@gmic : $ 300,1,1,1,'cos(20*x/w)' --abs -display_graph 400,300

#@gmic acos : (+)
#@gmic : Compute the pointwise arc-cosine of selected images.
#@gmic : $ image.jpg --normalize -1,1 -acos[-1]
#@gmic : $ 300,1,1,1,'x/w+0.1*u' --acos -display_graph 400,300

#@gmic + : eq. to '-add'. : (+)

#@gmic add : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Add specified value, image or mathematical expression to selected images,
#@gmic : or compute the pointwise sum of selected images.
#@gmic : (eq. to '-+').
#@gmic : $ image.jpg --add 30% -cut 0,255
#@gmic : $ image.jpg --blur 5 -normalize 0,255 -add[1] [0]
#@gmic : $ image.jpg -add '80*cos(80*(x/w-0.5)*(y/w-0.5)+c)' -cut 0,255
#@gmic : $ image.jpg -repeat 9 --rotate[0] {$>*36},0,1,50%,50% -done -add -div 10

#@gmic and : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the bitwise AND of selected images with specified value, image or mathematical
#@gmic : expression, or compute the pointwise sequential bitwise AND of selected images.
#@gmic : $ image.jpg -and {128+64}
#@gmic : $ image.jpg --mirror x -and

#@gmic asin : (+)
#@gmic : Compute the pointwise arc-sine of selected images.
#@gmic : $ image.jpg --normalize -1,1 -asin[-1]
#@gmic : $ 300,1,1,1,'x/w+0.1*u' --asin -display_graph 400,300

#@gmic atan : (+)
#@gmic : Compute the pointwise arc-tangent of selected images.
#@gmic : $ image.jpg --normalize 0,8 -atan[-1]
#@gmic : $ 300,1,1,1,'4*x/w+u' --atan -display_graph 400,300

#@gmic atan2 : [x_argument] : (+)
#@gmic : Compute the pointwise oriented arc-tangent of selected images.
#@gmic : Each selected image is regarded as the y-argument of the arc-tangent function, while the
#@gmic : specified image gives the corresponding x-argument.
#@gmic : $ (-1,1) (-1;1) -resize 400,400,1,1,3 -atan2[1] [0] -keep[1] -mod {pi/8}

#@gmic << : eq. to '-bsl'. : (+)

#@gmic bsl : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the bitwise left shift of selected images with specified value, image or
#@gmic : mathematical expression, or compute the pointwise sequential bitwise left shift of
#@gmic : selected images.
#@gmic : (eq. to '-<<').
#@gmic : $ image.jpg -bsl 'round(3*x/w,0)' -cut 0,255

#@gmic >> : eq. to '-bsr'. : (+)

#@gmic bsr : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the bitwise right shift of selected images with specified value, image or"
#@gmic : mathematical expression, or compute the pointwise sequential bitwise right shift of
#@gmic : selected images.
#@gmic : (eq. to '->>').
#@gmic : $ image.jpg -bsr 'round(3*x/w,0)' -cut 0,255

#@gmic cos : (+)
#@gmic : Compute the pointwise cosine of selected images.
#@gmic : $ image.jpg --normalize 0,{2*pi} -cos[-1]
#@gmic : $ 300,1,1,1,'20*x/w+u' --cos -display_graph 400,300

#@gmic cosh : (+)
#@gmic : Compute the pointwise hyperbolic cosine of selected images.
#@gmic : $ image.jpg --normalize -3,3 -cosh[-1]
#@gmic : $ 300,1,1,1,'4*x/w+u' --cosh -display_graph 400,300

#@gmic / : eq. to '-div'. : (+)

#@gmic div : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Divide selected image by specified value, image or mathematical expression,
#@gmic : or compute the pointwise quotient of selected images.
#@gmic : (eq. to '-/').
#@gmic : $ image.jpg -div '1+abs(cos(x/10)*sin(y/10))'
#@gmic : $ image.jpg --luminance --div

#@gmic == : eq. to '-eq'. : (+)

#@gmic eq : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the boolean equality of selected images with specified value, image or
#@gmic : mathematical expression, or compute the boolean equality of selected images.
#@gmic : (eq. to '-==').
#@gmic : $ image.jpg -round 40 -eq {round(ia,40)}
#@gmic : $ image.jpg --mirror x -eq

#@gmic exp : (+)
#@gmic : Compute the pointwise exponential of selected images.
#@gmic : $ image.jpg --normalize 0,2 -exp[-1]
#@gmic : $ 300,1,1,1,'7*x/w+u' --exp -display_graph 400,300

#@gmic >= : eq. to '-ge'. : (+)

#@gmic ge : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the boolean 'greater or equal than' of selected images with specified value, image
#@gmic : or mathematical expression, or compute the boolean 'greater or equal than' of selected images.
#@gmic : (eq. to '->=').
#@gmic : $ image.jpg -ge {ia}
#@gmic : $ image.jpg --mirror x -ge

#@gmic > : eq. to '-gt'. : (+)

#@gmic gt : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the boolean 'greater than' of selected images with specified value, image or
#@gmic : mathematical expression, or compute the boolean 'greater than' of selected images.
#@gmic : (eq. to '->').
#@gmic : $ image.jpg -gt {ia}
#@gmic : $ image.jpg --mirror x -gt

#@gmic <= : eq. to '-le'. : (+)

#@gmic le : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the boolean 'less or equal than' of selected images with specified value, image or
#@gmic : mathematical expression, or compute the boolean 'less or equal than' of selected images.
#@gmic : (eq. to '-<=').
#@gmic : $ image.jpg -le {ia}
#@gmic : $ image.jpg --mirror x -le

#@gmic < : eq. to '-lt'. : (+)

#@gmic lt : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the boolean 'less than' of selected images with specified value, image or
#@gmic : mathematical expression, or compute the boolean 'less than' of selected images.
#@gmic : (eq. to '-<').
#@gmic : $ image.jpg -lt {ia}
#@gmic : $ image.jpg --mirror x -lt

#@gmic log : (+)
#@gmic : Compute the pointwise base-e logarithm of selected images.
#@gmic : $ image.jpg --add 1 -log[-1]
#@gmic : $ 300,1,1,1,'7*x/w+u' --log -display_graph 400,300

#@gmic log10 : (+)
#@gmic : Compute the pointwise base-10 logarithm of selected images.
#@gmic : $ image.jpg --add 1 -log10[-1]
#@gmic : $ 300,1,1,1,'7*x/w+u' --log10 -display_graph 400,300

#@gmic log2 : (+)
#@gmic : Compute the pointwise base-2 logarithm of selected images
#@gmic : $ image.jpg --add 1 -log2[-1]
#@gmic : $ 300,1,1,1,'7*x/w+u' --log2 -display_graph 400,300

#@gmic max : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the maximum between selected images and specified value, image or
#@gmic : mathematical expression, or compute the pointwise maxima between selected images.
#@gmic : $ image.jpg --mirror x -max
#@gmic : $ image.jpg -max 'R=((x/w-0.5)^2+(y/h-0.5)^2)^0.5;255*R'

#@gmic // : eq. to '-mdiv'. : (+)

#@gmic mdiv : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the matrix division of selected matrices/vectors by specified value, image or
#@gmic : mathematical expression, or compute the matrix division of selected images.
#@gmic : (eq. to '-//').

#@gmic min : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the minimum between selected images and specified value, image or
#@gmic : mathematical expression, or compute the pointwise minima between selected images.
#@gmic : $ image.jpg --mirror x -min
#@gmic : $ image.jpg -min 'R=((x/w-0.5)^2+(y/h-0.5)^2)^0.5;255*R'

#@gmic % : eq. to '-mod'. : (+)

#@gmic mod : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the modulo of selected images with specified value, image or mathematical
#@gmic : expression, or compute the pointwise sequential modulo of selected images.
#@gmic : (eq. to '-%').
#@gmic : $ image.jpg --mirror x -mod
#@gmic : $ image.jpg -mod 'R=((x/w-0.5)^2+(y/h-0.5)^2)^0.5;255*R'

#@gmic ** : eq. to '-mmul'. : (+)

#@gmic mmul : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the matrix multiplication of selected matrices/vectors by specified value, image or
#@gmic : mathematical expression, or compute the matrix multiplication of selected images.
#@gmic : (eq. to '-**').
#@gmic : $ (0,1,0;0,0,1;1,0,0) (1;2;3) --mmul

#@gmic * : eq. to '-mul'. : (+)

#@gmic mul : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Multiply selected images by specified value, image or mathematical expression,
#@gmic : or compute the pointwise product of selected images.
#@gmic : (eq. to '-*').
#@gmic : $ image.jpg --mul 2 -cut 0,255
#@gmic : $ image.jpg (1,2,3,4,5,6,7,8) -resize[-1] [0] -mul[0] [-1]
#@gmic : $ image.jpg -mul '1-3*abs(x/w-0.5)' -cut 0,255
#@gmic : $ image.jpg --luminance -negative[-1] --mul

#@gmic != : eq. to '-neq'. : (+)

#@gmic neq : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the boolean inequality of selected images with specified value, image or
#@gmic : mathematical expression, or compute the boolean inequality of selected images.
#@gmic : (eq. to '-!=').
#@gmic : $ image.jpg -round 40 -neq {round(ia,40)}

#@gmic or : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the bitwise OR of selected images with specified value, image or mathematical
#@gmic : expression, or compute the pointwise sequential bitwise OR of selected images.
#@gmic : $ image.jpg -or 128
#@gmic : $ image.jpg --mirror x -or

#@gmic ^ : eq. to '-pow'. : (+)

#@gmic pow : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Raise selected image to the power of specified value, image or mathematical
#@gmic : expression, or compute the pointwise sequential powers of selected images.
#@gmic : (eq. to '-^').
#@gmic : $ image.jpg -div 255 --pow 0.5 -mul 255
#@gmic : $ image.jpg -gradient -pow 2 -add -pow 0.2

#@gmic rol : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the bitwise left rotation of selected images with specified value, image or
#@gmic : mathematical expression, or compute the pointwise sequential bitwise left rotation of
#@gmic : selected images.
#@gmic : $ image.jpg -rol 'round(3*x/w,0)' -cut 0,255

#@gmic ror : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the bitwise right rotation of selected images with specified value, image or
#@gmic : mathematical expression, or compute the pointwise sequential bitwise right rotation of
#@gmic : selected images.
#@gmic : $ image.jpg -ror 'round(3*x/w,0)' -cut 0,255

#@gmic sign : (+)
#@gmic : Compute the pointwise sign of selected images.
#@gmic : $ image.jpg --sub {ia} -sign[-1]
#@gmic : $ 300,1,1,1,'cos(20*x/w+u)' --sign -display_graph 400,300

#@gmic sin : (+)
#@gmic : Compute the pointwise sine of selected images.
#@gmic : $ image.jpg --normalize 0,{2*pi} -sin[-1]
#@gmic : $ 300,1,1,1,'20*x/w+u' --sin -display_graph 400,300

#@gmic sinc : (+)
#@gmic : Compute the pointwise sinc function of selected images.
#@gmic : $ image.jpg --normalize {-2*pi},{2*pi} -sinc[-1]
#@gmic : $ 300,1,1,1,'20*x/w+u' --sinc -display_graph 400,300

#@gmic sinh : (+)
#@gmic : Compute the pointwise hyperbolic sine of selected images.
#@gmic : $ image.jpg --normalize -3,3 -sinh[-1]
#@gmic : $ 300,1,1,1,'4*x/w+u' --sinh -display_graph 400,300

#@gmic sqr : (+)
#@gmic : Compute the pointwise square function of selected images.
#@gmic : $ image.jpg --sqr
#@gmic : $ 300,1,1,1,'40*x/w+u' --sqr -display_graph 400,300

#@gmic sqrt : (+)
#@gmic : Compute the pointwise square root of selected images.
#@gmic : $ image.jpg --sqrt
#@gmic : $ 300,1,1,1,'40*x/w+u' --sqrt -display_graph 400,300

#@gmic - : eq. to '-sub'. : (+)

#@gmic sub : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Subtract specified value, image or mathematical expression to selected images,
#@gmic : or compute the pointwise difference of selected images.
#@gmic : (eq. to '--').
#@gmic : $ image.jpg --sub 30% -cut 0,255
#@gmic : $ image.jpg --mirror x -sub[-1] [0]
#@gmic : $ image.jpg -sub 'i(w/2+0.9*(x-w/2),y)'
#@gmic : $ image.jpg --mirror x -sub

#@gmic tan : (+)
#@gmic : Compute the pointwise tangent of selected images.
#@gmic : $ image.jpg --normalize {-0.47*pi},{0.47*pi} -tan[-1]
#@gmic : $ 300,1,1,1,'20*x/w+u' --tan -display_graph 400,300

#@gmic tanh : (+)
#@gmic : Compute the pointwise hyperbolic tangent of selected images.
#@gmic : $ image.jpg --normalize -3,3 -tanh[-1]
#@gmic : $ 300,1,1,1,'4*x/w+u' --tanh -display_graph 400,300

#@gmic xor : value[%] : [image] : 'formula' : (no args) : (+)
#@gmic : Compute the bitwise XOR of selected images with specified value, image or mathematical
#@gmic : expression, or compute the pointwise sequential bitwise XOR of selected images.
#@gmic : $ image.jpg -xor 128
#@gmic : $ image.jpg --mirror x -xor

#---------------------------------
#
#@gmic :: Values manipulation
#
#---------------------------------

#@gmic apply_curve : 0<=smoothness<=1,x0,y0,x1,y1,x2,y2,...,xN,yN
#@gmic : Apply curve transformation to image values.
#@gmic : Default values: 'smoothness=1', 'x0=0', 'y0=100'.
#@gmic : $ image.jpg --apply_curve 1,0,0,128,255,255,0
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 ${^0} -map[^-1] [-1] -rm[-1] -v +

#@gmic apply_gamma : gamma>=0
#@gmic : Apply gamma correction to selected images.
#@gmic : $ image.jpg --apply_gamma 2
apply_gamma : -check $1>=0
  -e[^-1] "Apply Gamma-correction to image$?, with gamma $1."
  -if {$1==1} -return -endif
  -v - -repeat @# -l[$>] mM={im},{iM} -n 0,1 -^ {1/$1} -n $mM -endl -done -v +

#@gmic balance_gamma : _ref_color1,...
#@gmic : Apply color balance transformation on selected image, with respect to specified reference color.
#@gmic : Default values: 'ref_color1=128'.
#@gmic : $ image.jpg --balance_gamma 128,64,64
balance_gamma : -skip ${1=128}
  -e[^-1] "Apply color balance transformation on image$?, with gamma curve and reference color ("${^0}")."
  -v - -repeat @# -l[$>]
    (${^0}) -r[-1] @{-2,s},1,1,1,0,1 -s[-2] c -/[-1] 255
    -repeat {@#-1} -/[$>] 255 -^[$>] {log(@{-1,$>})/log(@{$>,a})} -*[$>] 255 -done
    -rm[-1] -a c -n 0,255
  -endl -done -v +

#@gmic complex2polar
#@gmic : Compute complex to polar transforms of selected images.
#@gmic : $ image.jpg --fft -complex2polar[-2,-1] -log[-2] -shift[-2] 50%,50%,0,0,2 -remove[-1]
complex2polar :
  -e[^-1] "Compute complex to polar transforms of image$?."
  -v - -repeat {int(@#/2)} -l[{2*$>},{2*$>+1}]
    -r[1] [0],3 --atan2[1] [0] -nm[-1] @{1,n},1 -sqr[-3,-2] -+[-3,-2] -sqrt[-2]
  -endl -done -v +

#@gmic cumul
#@gmic : Compute the cumulative function of specified image data.
#@gmic : $ image.jpg --histogram 256 --cumul[-1] -display_graph[-2,-1] 400,300,3
cumul :
  -e[^-1] "Compute cumulative of function$?."
  -v - -repeat @# -l[$>]
    dim={w},{h},{d},{s} -y x
    -repeat {round(log2(w),1,1)} --shift[-1] {2^$>} -+[-2,-1] -done
    -r $dim,-1
  -endl -done -v +

#@gmic c : eq. to '-cut'. : (+)

#@gmic cut : { value0[%] | [image0] },{ value1[%] | [image1] } : [image] : (no args) : (+)
#@gmic : Cut values of selected images in specified range.
#@gmic : (eq. to '-c').
#@gmic : (noargs) runs interactive mode (uses the instant window [0] if opened).
#@gmic : $ image.jpg --add 30% -cut[-1] 0,255
#@gmic : $ image.jpg --cut 25%,75%

#@gmic discard : value,_remove_if_not_found = { 0 | 1 }.
#@gmic : Remove specified value in selected images and return results as single-column vector.
#@gmic : Default value: 'remove_if_not_found=0'.
#@gmic : $ (1;2;3;4;3;2;1) --discard 2
discard : -skip ${2=0}
  -e[^-1] "Remove value $1 in image$?."
  -v - -repeat @# -l[$>]
    -s -,$1 -a y
    -if {!@#" && "!$2} 1,1,1,1,$1 -endif
  -endl -done -v +

#@gmic eigen2tensor
#@gmic : Recompose selected pairs of eigenvalues/eigenvectors as 2x2 or 3x3 tensor fields.
eigen2tensor :
  -e[^-1] "Recompose pairs in eigen field$? as 2x2 or 3x3 tensor fields."
  -v - -repeat {@#/2} -l[$>,{$>+1}] nm=@{0,n}
    -if {s==2} # 2d tensors.
      -s[-1] c
      --sqr[-1] -*[-2] [-3] -sqr[-3] # u^2 uv v^2
      -sh[-1] --*[-3] -1
      -sh[-5]     # v^2 -uv u^2
      -a[-3--1] c -a[-4--2] c
      -sh[-3] 0,0 -*[-3,-1]          # l1*(u^2;uv;v^2)
      -sh[-3] 1,1 -*[-2,-1]          # l2*(v^2;-uv;u^2)
      -rm[-3] -+[-2,-1]
    -elif {s==6} # 3d tensors.
      -s[-1] c
      -l[-6--4] --sqr[-2] --*[-2,-3] --sqr[-3] -*[-5] [-6] -*[-4] [-6] -sqr[-6] -a c -endl
      -l[-3--1] --sqr[-2] --*[-2,-3] --sqr[-3] -*[-5] [-6] -*[-4] [-6] -sqr[-6] -a c -endl
      -s[-3] c
      --[-5] [-3] --[-4] [-3] -*[-2] [-5] -*[-1] [-4]
      (1^0^0^1^0^1) -r[-1] [-3] -*[-1] [-4] -rm[-6--4] -+[-3--1]
    -else -error[0--3] "Invalid image ["{@#-$>-1}"] : Dimensions "{w}","{h}","{d}","{s}" does not represent a field of 2d or 3d eigenvectors."
    -endif
  -nm $nm,1 -endl -done -v +

#@gmic endian : (*)
#@gmic : Reverse data endianness of selected images.

#@gmic equalize : _nb_levels>0[%],_value_min[%],_value_max[%]
#@gmic : Equalize histograms of selected images.
#@gmic : If value range is specified, the equalization is done only for pixels in the specified
#@gmic : value range.
#@gmic : Default values: 'value_min=0%' and 'value_max=100%'.
#@gmic : $ image.jpg --equalize 256
#@gmic : $ image.jpg --equalize 4,0,128

#@gmic f : eq. to '-fill'. : (+)

#@gmic fill : value1,_value2,.. : [image] : 'formula' : (+)
#@gmic : Fill selected images with values read from the specified value list, existing image
#@gmic : or mathematical expression. Single quotes may be omitted in 'formula'.
#@gmic : (eq. to '-f').
#@gmic : $ 4,4 -fill 1,2,3,4,5,6,7
#@gmic : $ 4,4 (1,2,3,4,5,6,7) -fill[-2] [-1]
#@gmic : $ 400,400,1,3 -fill "X=x-w/2; Y=y-h/2; R=sqrt(X^2+Y^2); a=atan2(Y,X); if (R<=180,255*abs(cos(c+200*(x/w-0.5)*(y/h-0.5))),850*(a%(0.1*(c+1))))"

#@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 @# -l[$>]
      m={im} M={iM} -quantize 16777216,0
      -->> 8 -and[-1] 255 --and[-2] 255 ->>[-3] 16
      ({'$m,$M'}) -a y
    -endl -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 @# -l[$>]
      -sh[-1] {h-1},{h-1},0,0 m=@{-1,t} -rm[-1]
      -rows 0,{h-2} -s y,3 -*[-3] 65536 -*[-2] 256 -or -n $m
    -endl -done -a c
  -endl -done -v +

#@gmic index : { [palette] | predefined_palette },0<=_dithering<=1,_map_palette={ 0 | 1 } : (+)
#@gmic : Index selected vector-valued images by specified vector-valued palette.
#@gmic : 'predefined_palette' can be { 0=default | 1=HSV | 2=lines | 3=hot | 4=cool | 5=jet | 6=flag | 7=cube }.
#@gmic : Default values: 'dithering=0' and 'map_palette=0'.
#@gmic : $ image.jpg --index 1,1,1
#@gmic : $ image.jpg (0;255;255^0;128;255^0;0;255) --index[-2] [-1],1,1

#@gmic map : [palette] : predefined_palette : (+)
#@gmic : Map specified vector-valued palette to selected indexed scalar images.
#@gmic : 'predefined_palette' can be { 0=default | 1=HSV | 2=lines | 3=hot | 4=cool | 5=jet | 6=flag | 7=cube }.
#@gmic : $ image.jpg --luminance -map[-1] 3
#@gmic : $ image.jpg --rgb2ycbcr -split[-1] c (0,255,0) -resize[-1] 256,1,1,1,3 -map[-4] [-1] -remove[-1] -append[-3--1] c -ycbcr2rgb[-1]

#@gmic mix_channels : (a00,...,aMN)
#@gmic : Apply specified matrix to channels of selected images.
#@gmic : $ image.jpg --mix_channels (0,1,0;1,0,0;0,0,1)
mix_channels :
  -e[^-1] "Apply matrix $1 to channels of image$?."
  -v - -repeat @# -l[$>] nm=@{0,n}
    whd={w},{h},{d} -r {w*h*d},{s},1,1,-1 -i[0] ${^0} -** -r $whd,{h},-1
  -nm $nm,1 -endl -done -v +

#@gmic negative
#@gmic : Compute negative of selected images.
#@gmic : $ image.jpg --negative
negative :
  -e[^-1] "Compute negative of image$?."
  -v - -repeat @# -l[$>] -- {iM} -endl -done -* -1 -v +

#@gmic noise : std_variation>=0[%],_noise_type : (+)
#@gmic : Add random noise to selected images.
#@gmic : 'noise_type' can be { 0=gaussian | 1=uniform | 2=salt&pepper | 3=poisson | 4=rice }.
#@gmic : Default value: 'noise_type=0'.
#@gmic : $ image.jpg --noise[0] 50,0 --noise[0] 50,1 --noise[0] 10,2 -cut 0,255
#@gmic : $ 300,300,1,3 [0] -noise[0] 20,0 -noise[1] 20,1 --histogram 100 -display_graph[-2,-1] 400,300,3

#@gmic norm
#@gmic : Compute the pointwise euclidean norm of vector-valued pixels in selected images.
#@gmic : $ image.jpg --norm
norm :
  -e[^-1] "Compute pointwise euclidean norm of vectors, in image$?."
  -v - -sqr -compose_channels + -sqrt -v +

#@gmic n : eq. to '-normalize'. : (+)

#@gmic normalize : { value0[%] | [image0] },{ value1[%] | [image1] } : [image] : (+)
#@gmic : Linearly normalize values of selected images in specified range.
#@gmic : (eq. to '-n').
#@gmic : $ image.jpg -split x,2 -normalize[-1] 64,196 -append x

#@gmic normalize_sum
#@gmic : Normalize selected images with a unitary sum.
#@gmic : $ image.jpg --histogram[-1] 256 -normalize_sum[-1] -display_graph[-1] 400,300
normalize_sum :
  -e[^-1] "Normalize image$? with a unitary sum."
  -v - -repeat @# sum=@{$>,+} -if {$sum!=0} -/[$>] $sum -endif -done -v +

#@gmic orientation
#@gmic : Compute the pointwise orientation of vector-valued pixels in selected images.
#@gmic : $ image.jpg --orientation --norm[-2] -negative[-1] -mul[-2] [-1] -reverse[-2,-1]
orientation :
  -e[^-1] "Compute pointwise orientation vectors, in image$?."
  -v - -repeat @# --norm[$>] -replace[-1] 0,1 -/[$>,-1] -done -v +

#@gmic otsu : _nb_levels>0
#@gmic : Hard-threshold image using Otsu's method.
#@gmic : Default value: 'nb_levels=256'.
#@gmic : $ image.jpg -luminance --otsu ,
otsu : -check "isint(${1=256}) && $1>0"
  -e[^-1] "Hard-threshold image$? using Otsu's method, with $1 histogram levels."
  -v - -n 0,{$1-1} -repeat @# -l[$>]
    --histogram $1 total=@{-1,+}
    --*[-1] 'x' sum=@{-1,+} -rm[-1]
    sumB=0 wB=0 wF=0 varMax=0 threshold=0
    -repeat $1
      wB={$wB+@{-1,$>}}
      -if {$wB==0} -continue -endif
      wF={$total-$wB}
      -if {$wF==0} -break -endif
      sumB={$sumB+$>*@{-1,$>}}
      mB={$sumB/$wB}
      mF={($sum-$sumB)/$wF}
      varBetween={$wB*$wF*($mB-$mF)^2}
      -if {$varBetween>$varMax} varMax=$varBetween threshold=$> -endif
    -done
    -rm[-1] -ge[-1] $threshold
    -v + -e[] "  > Threshold for image ["$>"] ("@{-1,b}") : "$threshold -v -
  -endl -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)} -l[{2*$>},{2*$>+1}]
    -r[1] [0],3 --sin[-1] -cos[-2] -*[-1] [-3] -*[-3,-2]
  -endl -done -v +

#@gmic quantize : nb_levels>=1,_preserve_value_range={ 0 | 1 }
#@gmic : Uniformly quantize selected images.
#@gmic : Default value: 'preserve_value_range=1'.
#@gmic : $ image.jpg -luminance --quantize 3
#@gmic : $ 200,200,1,1,'cos(x/10)*sin(y/10)' --quantize[0] 6 --quantize[0] 4 --quantize[0] 3 --quantize[0] 2
quantize : -check $1>=1 -skip ${2=1}
  -e[^-1] "Quantize image$? using $1 levels, with"@{"s0=out s1=\"\" -u ${s{$2!=0}}"}" keeping value range."
  -v - -if $2 -repeat @# -l[$>] mM={im},{iM} -n 0,$1 -round 1,-1 -min {$1-1} -n $mM -endl -done
  -else -n 0,$1 -round 1,-1 -min {$1-1} -endif -v +

#@gmic rand : { value0[%] | [image0] },{ value1[%] | [image1] } : [image] : (+)
#@gmic : Fill selected images with random values uniformly distributed in the specified range.
#@gmic : $ 400,400,1,3 -rand -10,10 --blur 10 -sign[-1]

#@gmic replace : value_src,value_dest
#@gmic : Replace pixel values in selected images.
#@gmic : $ (1;2;3;4) --replace 2,3
replace :
  -e[^-1] "Replace pixel values $1 with $2 in image$?."
  -v - -repeat @# -l[$>] --== $1 -*[-1] {$2-$1} -+ -endl -done -v +

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

#@gmic replace_nan : _expression
#@gmic : Replace all NaN values in selected images by specified expression.
#@gmic : $ (-1;0;2) -sqrt --replace_nan 2
replace_nan :
  -e[^-1] "Replace all NaN values in images$? by expression '$1'."
  -v - -f "if(i>=0 || i<=0,i,$1)" -v +

#@gmic replace_seq : "search_seq","replace_seq"
#@gmic : Search and replace a sequence of values in selected images.
#@gmic : $ (1;2;3;4;5) --replace_seq "2,3,4","7,8"
replace_seq :
  -e[^-1] "Replace value sequence '$1' by value sequence '$2' in image$?."
  -v - ($1) ($2) -repeat {@#-2} -l[$>,-2,-1]
    -s[0] +,$1 -s y,-@{-2,w}
    -repeat {@#-2} -if {@{$>,t}'=='@{-2,t}} -rows[$>] 0,{w-1} -f[$>] [-1] -endif -done
    -a[0--3] y
  -endl -done -rm[-2,-1] -v +

#@gmic round : rounding_value>=0,_rounding_type : (no args) : (+)
#@gmic : Round values of selected images.
#@gmic : 'rounding_type' can be { -1=backward | 0=nearest | 1=forward }.
#@gmic : Default value: 'rounding_type=0'.
#@gmic : $ image.jpg --round 100
#@gmic : $ image.jpg -mul {pi/180} -sin --round

#@gmic roundify : gamma>=0
#@gmic : Apply roundify transformation on float-valued data, with specified gamma.
#@gmic : Default value: 'gamma=0'.
#@gmic : $ 1000 -fill '4*x/w' -repeat 5 --roundify[0] {$>*0.2} -done -append c -display_graph 400,300
roundify : -check $1>=0
  -e[^-1] "Roundify image$?, with gamma $1."
  -if {$1==1} -return -endif
  -v - -repeat @# -l[$>]
    --round 1 --[-2] [-1] --*[-2] 2 -abs[-1] -^[-1] $1 -sign[-3] -*[-3,-1] -*[-2] 0.5 -+
  -endl -done -v +

#@gmic = : eq. to '-set'. : (+)

#@gmic set : value,_x[%],_y[%],_z[%],_c[%] : (*)
#@gmic : Set pixel value in selected images, at specified coordinates.
#@gmic : (eq. to '-=').
#@gmic : If specified coordinates are outside the image bounds, no action is performed.
#@gmic : Default values: 'x=y=z=c=0'.
#@gmic : $ 2,2 -set 1,0,0 -set 2,1,0 -set 3,0,1 -set 4,1,1
#@gmic : $ image.jpg -repeat 10000 -set 255,{?(100)}%,{?(100)}%,0,{?(100)}% -done

#@gmic threshold : value[%],_is_soft : (no args) : (+)
#@gmic : Threshold values of selected images.
#@gmic : 'soft' can be { 0=hard-thresholding | 1=soft-thresholding }.
#@gmic : (noargs) runs interactive mode (uses the instant window [0] if opened).
#@gmic : Default value: 'is_soft=0'.
#@gmic : $ image.jpg --threshold[0] 50% --threshold[0] 50%,1

#@gmic t2 : eq. to '-threshold2'.
t2 :
  -_threshold2 $*

#@gmic threshold2 : min[%],max[%]
#@gmic : Threshold selected images between the two given values.
#@gmic : (eq. to '-t2').
#@gmic : $ image.jpg --threshold2 25%,75%
threshold2 :
  -_threshold2 $*

_threshold2 :
  -e[0--3] "Hard-threshold image$? between values $1 and $2."
  -v - -- {0.5*($1+$2)} -abs -le {0.5*abs($2-$1)} -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[$>]
    -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[0--4] "Invalid image ["{@#-$>-1}"] : Dimensions "{w}","{h}","{d}","{s}" does not represent a field of 2d or 3d vectors."
    -endif
    -a c
  -endl -done -v +

#---------------------------------
#
#@gmic :: Colors manipulation
#
#---------------------------------

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

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

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

  # Process RGB channels.
  -elif {$2==2}
    -e[^-1] "Apply command '$1' on RGB channels of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

  # Process Y channel.
  -elif {$2==3}
    -e[^-1] "Apply command '$1' on luminance of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

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

  # Process Cb channel.
  -elif {$2==5}
    -e[^-1] "Apply command '$1' on blue chrominance of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

  # Process Cr channel.
  -elif {$2==6}
    -e[^-1] "Apply command '$1' on red chrominance of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

  # Process L channel.
  -elif {$2==7}
    -e[^-1] "Apply command '$1' on lightness of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

  # Process a-b channels.
  -elif {$2==8}
    -e[^-1] "Apply command '$1' on a-b channels of image$?." -v -
    -repeat @# -l[$>]
      -split_opacity -to_rgb[0] -rgb2lab[0] -s[0] c
      -+[1] 86 -*[1] 1.38587 -+[2] 108 -*[2] 1.25616
      -a[1,2] c -_apply_channels[1] "$1" -channels[1] 0,1 -s[1] c
      -/[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 -done

  # Process a-channel.
  -elif {$2==9}
    -e[^-1] "Apply command '$1' on a-channel of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

  # Process b-channel.
  -elif {$2==10}
    -e[^-1] "Apply command '$1' on b-channel of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

  # Process H channel.
  -elif {$2==11}
    -e[^-1] "Apply command '$1' on hue of image$?." -v -
    -repeat @# -l[$>]
      -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 -%[0] 360 -endif
      -a[0-2] c -hsv2rgb[0] -a c
    -endl -done

  # Process S channel.
  -elif {$2==12}
    -e[^-1] "Apply command '$1' on saturation of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

  # Process V channel.
  -elif {$2==13}
    -e[^-1] "Apply command '$1' on value of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

  # Process K channel.
  -elif {$2==14}
    -e[^-1] "Apply command '$1' on key channel of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

  # Process Alpha channel.
  -elif {$2==15}
    -e[^-1] "Apply command(s) '$1' on alpha channel of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

  # Process c-h channels.
  -elif {$2==16}
    -e[^-1] "Apply command '$1' on c-h channels of image$?." -v -
    -repeat @# -l[$>]
      -split_opacity -to_rgb[0] -rgb2lch[0] -s[0] c
      -*[1] 2.55 -+[2] {pi} -*[2] {255/(2*pi)}
      -a[1,2] c -_apply_channels[1] "$1" -channels[1] 0,1 -s[1] c
      -/[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 -done

  # Process c-channel.
  -elif {$2==17}
    -e[^-1] "Apply command '$1' on c-channel of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

  # Process h-channel.
  -elif {$2==18}
    -e[^-1] "Apply command '$1' on h-channel of image$?." -v -
    -repeat @# -l[$>]
      -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 -done

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

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

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

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

  -endif
  -v +

_apply_channels :
  $* -k[0]

#@gmic autoindex : nb_colors>0,_dithering>=0,_method={ 0=median-cut | 1=k-means }
#@gmic : Index selected vector-valued images by adapted colormaps.
#@gmic : Default values: 'dithering=0' and 'method=0'.
#@gmic : $ image.jpg --autoindex[0] 4 --autoindex[0] 8 --autoindex[0] 16
autoindex : -check "isint($1) && $1>0 && ${2=0}>=0" -skip ${3=0}
  -e[^-1] "Index colors in images$? by adapted colormap with $1 entries, dithering level $2 and "\
          @{"-if $3 -u k-means -else -u median-cut -endif"}" method."
  -v - -repeat @# -l[$>]
    -if {w>h} -if {w>256} --r2dx 256 -else [0] -endif
    -else -if {h>256} --r2dy 256 -else [0] -endif
    -endif
    -colormap[1] $1,$3
    -index[0] [1],$2,1 -rm[1]
  -endl -done -v +

#@gmic bayer2rgb : _GM_smoothness,_RB_smoothness1,_RB_smoothness2
#@gmic : Transform selected RGB-Bayer sampled images to color images.
#@gmic : Default values: 'GM_smoothness=RB_smoothness=1' and 'RB_smoothness2=0.5'.
#@gmic : $ image.jpg -rgb2bayer 0 --bayer2rgb 1,1,0.5
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 @# -l[$>]

    # Expand image size to avoid problems with borders.
    -expand_x {"2 + 4*$1"},0 -expand_y {"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]
    -b[-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 {"2 + 4*$1"},0 -shrink_y {"2 + 4*$1"},0
    -c 0,255

  -endl -done -v +

#@gmic cmy2rgb
#@gmic : Convert selected images from CMY to RGB colorbases.
cmy2rgb :
  -e[^-1] "Convert image$? from CMY to RGB color bases."
  -v - -rgb2cmy -v +

#@gmic cmyk2rgb
#@gmic : Convert selected images from CMYK to RGB colorbases.
cmyk2rgb :
  -e[^-1] "Convert image$? from CMYK to RGB color bases."
  -v - -repeat @# -l[$>]
    -s c --/[-1] -255 -+[-1] 1 -*[0-2] [-1] -rm[-1] -+[0-2] [-1] -rm[-1]
    -a c -cmy2rgb
  -endl -done -v +

#@gmic colormap : nb_colors>0,_method={ 0=median-cut | 1=k-means }
#@gmic : Estimate best-fitting colormap with 'nb_colors' entries, to index selected images.
#@gmic : Default value: 'method=0'.
#@gmic : $ image.jpg --colormap[0] 4 --colormap[0] 8 --colormap[0] 16
colormap : -check "isint($1) && $1>0" -skip ${2=0}
  -e[^-1] "Estimate colormap with $1 entries for image$?, by "\
          @{"-if $2 -u k-means -else -u median-cut -endif"}" method."
  -v - -repeat @# -l[$>]
    -r {w*h},1,1,100%,-1
    -if {!$2} -_colormap $1                                 # Just run the median-cut algorithm.
    -else
      m={im} M={iM} -n[-1] 0,255                            # Keep track of the initial statistics.
      --_colormap $1 --index[-2] [-1] -*[-1] 256 -+[-3,-1]  # Initialize k-means labels and add them on the image.

      # Start k-means iterations.
      -do
        -repeat {s}                                             # Estimate new colormap.
          -sh[0] $>,$> --histogram[-1] {$1*256},0,{$1*256-1} -rm[-2]
          -i[-2] 256,1,1,1,'x' -r[-2] {w},1,1,1,0,2 -*[-2] [-1] -r[-2,-1] $1,1,1,1,2 -max[-1] 0.01 -/[-2,-1]
        -done -a[2--1] c
        --[-2] [-1] -abs[-2] diff={@{-2,+}/w} -rm[-2]           # Compute colormap difference.
        -and[-2] 255 --index[-2] [-1],0,0 -*[-1] 256 -+[-3,-1]  # Compute new k-means labels.
      -while {$diff>0.5}
      -rm[-2] -*[-1] {($M-$m)/255} -+[-1] $m                    # Convert colormap values back to initial value range.
    -endif
    -nm "[colormap of "@{-1,b}"]"
  -endl -done -v +

_colormap : # Implementation of the median-cut algorithm.
  -repeat {$1-1}
    @#,{s} -repeat {@#-1} # Compute box variances along all axes and find highest one.
      n=$> -repeat @{$n,s} -sh[$n] $>,$> -=[-2] {iv},$n,$> -rm[-1] -done
    -done
    c=@{-1,C}
    b=@{-arg\ 1,$c}  # Indice of boxe with highest variance.
    a=@{-arg\ 2,$c}  # Indice of axe with highest variance inside box 'b'.
    -rm[-1] -shift[$b] 0,0,0,{-$a},2 -sort[$b] +,x -shift[$b] 0,0,0,$a,2 -s[$b] x,2 # Split selected box along its median axis.
  -done
  -r 1,1,1,100%,2 -a x # Average value in each box and append as final colormap.

#@gmic direction2rgb
#@gmic : Compute RGB representation of selected 2d direction fields.
#@gmic : $ image.jpg -luminance -gradient -append c -blur 2 -orientation --direction2rgb
direction2rgb :
  -e[^-1] "Compute RGB representation of 2d direction field$?."
  -v - -channels 0,1 -repeat @# -l[$>] nm=@{0,n}
    -s c -complex2polar -round[-2] 0.001
    -*[-1] {180/pi} -%[-1] 360 100%,100%,1,1,1 -mv[-3] @#
    -if {im!=iM} -n[-1] 0,1 -else -f[-1] 1 -endif
    -a c -hsv2rgb
  -nm $nm,1 -endl -done -v +

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

#@gmic fc : eq. to '-fill_color'.
fc :
  -_fill_color $*

#@gmic fill_color : col1,...,colN
#@gmic : Fill selected images with specified color.
#@gmic : (eq. to '-fc').
#@gmic : $ image.jpg --fill_color 255,0,255
fill_color :
  -_fill_color $*

_fill_color :
  -e[0--3] "Fill image$? with color (${^0})."
  -v - -repeat @# -l[$>]
    -repeat {s} -sh[-1] $>,$> -f[-1] {arg(1+$>,${^0})} -rm[-1] -done
  -nm @{-1,n},1 -endl -done -v +

#@gmic gradient2rgb : _is_orientation={ 0 | 1 }
#@gmic : Compute RGB representation of 2d gradient of selected images.
#@gmic : Default value: 'is_orientation=0'.
#@gmic : $ image.jpg --gradient2rgb 0 -equalize[-1] 256
gradient2rgb : -check "isbool(${1=0})"
  -e[^-1] "Compute RGB representation of 2d gradient "@{"s0=\"\" s1=\"orientation \" -u ${s{$1!=0}}"}"of image$?."
  -v - -norm -repeat @# -l[$>]
    -if $1 -gradient_orientation 2 -else -g xy -endif
    -a c -direction2rgb
  -endl -done -v +

#@gmic hsi2rgb : (+)
#@gmic : Convert selected images from HSI to RGB colorbases.

#@gmic hsi82rgb
#@gmic : Convert selected images from HSI8 to RGB color bases.
hsi82rgb :
  -e[^-1] "Convert image$? from HSI8 to RGB color bases."
  -v - -_hsx82rgb -hsi2rgb -v +

#@gmic hsl2rgb : (+)
#@gmic : Convert selected images from HSL to RGB colorbases.

#@gmic hsl82rgb
#@gmic : Convert selected images from HSL8 to RGB color bases.
hsl82rgb :
  -e[^-1] "Convert image$? from HSL8 to RGB color bases."
  -v - -_hsx82rgb -hsl2rgb -v +

#@gmic hsv2rgb : (+)
#@gmic : Convert selected images from HSV to RGB colorbases.
#@gmic : $ (0,360;0,360^0,0;1,1^1,1;1,1) -resize 400,400,1,3,3 -hsv2rgb

#@gmic hsv82rgb
#@gmic : Convert selected images from HSV8 to RGB color bases.
hsv82rgb :
  -e[^-1] "Convert image$? from HSV8 to RGB color bases."
  -v - -_hsx82rgb -hsv2rgb -v +

_hsx82rgb :
 -repeat @#
   -sh[$>] 0,0 -/[-1] 0.708333 -rm[-1]
   -sh[$>] 1,2 -/[-1] 255 -rm[-1]
 -done -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 @# -l[$>]
    -s c -complex2polar[-2,-1] -a c
  -endl -done -v +

#@gmic lab2rgb : (+)
#@gmic : Convert selected images from Lab to RGB colorbases.
#@gmic : $ (50,50;50,50^-3,3;-3,3^-3,-3;3,3) -resize 400,400,1,3,3 -lab2rgb

#@gmic lab82rgb
#@gmic : Convert selected images from Lab8 to RGB color bases.
lab82rgb :
  -e[^-1] "Convert image$? from Lab8 to RGB color bases."
  -v - -repeat @#
    -sh[$>] 0,0 -/[-1] 2.55 -rm[-1]
    -sh[$>] 1,1 -/[-1] 1.275 --[-1] 100 -rm[-1]
    -sh[$>] 2,2 -/[-1] 1.15909 --[-1] 110 -rm[-1]
  -done -lab2rgb -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 @# -l[$>]
    -s c -polar2complex[-2,-1] -a c
  -endl -done -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 lch82rgb
#@gmic : Convert selected images from Lch8 to RGB color bases.
lch82rgb :
  -e[^-1] "Convert image$? from Lch8 to RGB color bases."
  -v - -repeat @#
    -sh[$>] 0,0 -/[-1] 2.55 -rm[-1]
    -sh[$>] 1,1 -/[-1] 1.88889 -rm[-1]
    -sh[$>] 2,2 -/[-1] 40.5845 --[-1] 3.14159 -rm[-1]
  -done -lch2rgb -v +

#@gmic luminance
#@gmic : Compute luminance of selected images.
#@gmic : $ image.jpg --luminance
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.
#@gmic : Default values: 'a11=1', 'a12=a13=a21=0', 'a22=1', 'a23=a31=a32=0' and 'a33=1'.
#@gmic : $ image.jpg --mix_rgb 0,1,0,1,0,0,0,0,1
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 @# -l[$>]
    -r 100%,100%,1,3,0,2 -s 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 c
  -endl -done -v +

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

#@gmic replace_color : tolerance[%]>=0,smoothness[%]>=0,src1,src2,...,dest1,dest2,...
#@gmic : Replace pixels from/to specified colors in selected images.
#@gmic : $ image.jpg --replace_color 40,3,204,153,110,255,0,0
replace_color : -check "$1>=0 && $2>=0"
  -v - -l[] (${3--1}) -y c -s c,2 col1=@0 col2=@1 -rm -endl -v +
  -e[^-1] "Replace color ("$col1") by color ("$col2") in image$?, with tolerance $1 and smoothness $2."
  -v - -repeat @# -l[$>]
    1,1,1,100%,$col1 -r[1] [0]
    -if $1 --[1] [0] -norm[1] -le[1] $1 -else -==[1] [0] -l[1] -s c -and -endl -endif
    -b[1] $2
    1,1,1,@{0,s},$col2 -r[2] [0] -j[0] [2],0,0,0,0,1,[1] -k[0]
  -endl -done -v +

#@gmic rgb2bayer : _start_pattern=0,_color_grid=0
#@gmic : Transform selected color images to RGB-Bayer sampled images.
#@gmic : Default values: 'start_pattern=0' and 'color_grid=0'.
#@gmic : $ image.jpg --rgb2bayer 0
rgb2bayer : -skip ${1=0},${2=0}
  -e[^-1] "Transform image$? to a RGB-Bayer "@{"s0=monochrome s1=color -u ${s{$2!=0}}"}" grid, starting from pattern '$1'."
  -v - -to_rgb -repeat @# -l[$>]
    -_rgb2bayer$1 -r[1] [0],0,2 -* -if {!$2} -s c -+ -endif
  -endl -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 rgb2cmy
#@gmic : Convert selected images from RGB to CMY colorbases.
#@gmic : $ image.jpg -rgb2cmy -split c
rgb2cmy :
  -e[^-1] "Convert image$? from RGB to CMY color bases."
  -v - -to_rgb -c 0,255 -* -1 -+ 255 -v +

#@gmic rgb2cmyk
#@gmic : Convert selected images from RGB to CMYK colorbases.
#@gmic : $ image.jpg -rgb2cmyk -split c
#@gmic : $ image.jpg -rgb2cmyk -split c -fill[3] 0 -append c -cmyk2rgb
rgb2cmyk :
  -e[^-1] "Convert image$? from RGB to CMYK color bases."
  -v - -rgb2cmy -repeat @# -l[$>]
    -s c --min --[0-2] [-1] --/[-1] 255 --[-1] 1 -*[-1] -1 --eq[-1] 0 -+[-2,-1]
    -/[0-2] [-1] -rm[-1] -a c
  -endl -done -v +

#@gmic rgb2hsi : (+)
#@gmic : Convert selected images from RGB to HSI colorbases.
#@gmic : $ image.jpg -rgb2hsi -split c

#@gmic rgb2hsi8
#@gmic : Convert selected images from RGB to HSI8 color bases.
#@gmic : $ image.jpg -rgb2hsi8 -split c
rgb2hsi8 :
  -e[^-1] "Convert image$? from RGB to HSI8 color bases."
  -v - -rgb2hsi -_rgb2hsx8 -v +

#@gmic rgb2hsl : (+)
#@gmic : Convert selected images from RGB to HSL colorbases.
#@gmic : $ image.jpg -rgb2hsl -split c
#@gmic : $ image.jpg -rgb2hsl --split c -add[-3] 100 -mod[-3] 360 -append[-3--1] c -hsl2rgb

#@gmic rgb2hsl8
#@gmic : Convert selected images from RGB to HSL8 color bases.
#@gmic : $ image.jpg -rgb2hsl8 -split c
rgb2hsl8 :
  -e[^-1] "Convert image$? from RGB to HSL8 color bases."
  -v - -rgb2hsl -_rgb2hsx8 -v +

#@gmic rgb2hsv : (+)
#@gmic : Convert selected images from RGB to HSV colorbases.
#@gmic : $ image.jpg -rgb2hsv -split c
#@gmic : $ image.jpg -rgb2hsv --split c -add[-2] 0.3 -cut[-2] 0,1 -append[-3--1] c -hsv2rgb

#@gmic rgb2hsv8
#@gmic : Convert selected images from RGB to HSV8 color bases.
#@gmic : $ image.jpg -rgb2hsv8 -split c
rgb2hsv8 :
  -e[^-1] "Convert image$? from RGB to HSV8 color bases."
  -v - -rgb2hsv -_rgb2hsx8 -v +

_rgb2hsx8 :
  -repeat @#
    -sh[$>] 0,0 -*[-1] 0.708333 -rm[-1]
    -sh[$>] 1,2 -*[-1] 255 -rm[-1]
  -done

#@gmic rgb2lab : (+)
#@gmic : Convert selected images from RGB to Lab colorbases.
#@gmic : $ image.jpg -rgb2lab -split c
#@gmic : $ image.jpg -rgb2lab --split c -mul[-2,-1] 2.5 -append[-3--1] c -lab2rgb

#@gmic rgb2lab8
#@gmic : Convert selected images from RGB to Lab8 color bases.
#@gmic : $ image.jpg -rgb2lab8 -split c
rgb2lab8 :
  -e[^-1] "Convert image$? from RGB to Lab8 color bases."
  -v - -rgb2lab -repeat @#
    -sh[$>] 0,0 -*[-1] 2.55 -rm[-1]
    -sh[$>] 1,1 -+[-1] 100 -*[-1] 1.275 -rm[-1]
    -sh[$>] 2,2 -+[-1] 110 -*[-1] 1.15909 -rm[-1]
  -done -v +

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

#@gmic rgb2lch8
#@gmic : Convert selected images from RGB to Lch8 color bases.
#@gmic : $ image.jpg -rgb2lch8 -split c
rgb2lch8 :
  -e[^-1] "Convert image$? from RGB to Lch8 color bases."
  -v - -rgb2lch -repeat @#
    -sh[$>] 0,0 -*[-1] 2.55 -rm[-1]
    -sh[$>] 1,1 -*[-1] 1.88889 -rm[-1]
    -sh[$>] 2,2 -+[-1] 3.14159 -*[-1] 40.5845 -rm[-1]
  -done -v +

#@gmic rgb2luv
#@gmic : Convert selected images from RGB to LUV color bases.
#@gmic : $ image.jpg -rgb2luv -split c
rgb2luv :
  -e[^-1] "Convert image$? from RGB to LUV color bases."
  -v - -repeat @# -l[$>]
    --rgb2xyz -rgb2lab[-2] -channels[-2] 0 -s[-1] c
    -*[-1] 3 --*[-2] 15 -+[-2,-1] -+[-1] [-3] -+[-1] 1e-8  # Z <- X+15Y+3Z
    -*[-3] 4 -*[-2] 9 -/[-3,-2] [-1] -rm[-1]
    --[-2] 0.2009 --[-1] 0.4610
    --*[-3] 13 -*[-3] [-1] -*[-2,-1] -a c
  -endl -done -v +

#@gmic rgb2srgb : (+)
#@gmic : Convert selected images from RGB to sRGB colorbases.

#@gmic rgb2xyz
#@gmic : Convert selected images from RGB to XYZ colorbases.
#@gmic : the D65 illuminant is used as the white point).
#@gmic : $ image.jpg -rgb2xyz -split c
rgb2xyz :
  -e[^-1] "Convert image$? from RGB to XYZ color bases."
  -v - -/ 255 -mix_channels (0.412453,0.357580,0.180423;\
                             0.212671,0.715160,0.072169;\
                             0.019334,0.119193,0.950227) -v +

#@gmic rgb2xyz8
#@gmic : Convert selected images from RGB to XYZ8 color bases.
#@gmic : $ image.jpg -rgb2xyz8 -split c
rgb2xyz8 :
  -e[^-1] "Convert image$? from RGB to XYZ8 color bases."
  -v - -rgb2xyz -repeat @#
    -sh[$>] 0,0 -*[-1] 255 -rm[-1]
    -sh[$>] 1,1 -*[-1] 255 -rm[-1]
    -sh[$>] 2,2 -*[-1] 231.8182 -rm[-1]
  -done -v +

#@gmic rgb2ycbcr
#@gmic : Convert selected images from RGB to YCbCr colorbases.
#@gmic : $ image.jpg -rgb2ycbcr -split c
rgb2ycbcr :
  -e[^-1] "Convert image$? from RGB to YCbCr color bases."
  -v - -mix_channels (66,129,25;-38,-74,112;112,-94,-18) -+ 128 -/ 256
  -repeat @# -l[$>] -sh 0,0 -+[-1] 16 -rm[-1] -sh 1,2 -+[-1] 128 -rm[-1] -endl -done
  -v +

#@gmic rgb2yuv
#@gmic : Convert selected images from RGB to YUV colorbases.
#@gmic : $ image.jpg -rgb2yuv -split c
rgb2yuv :
  -e[^-1] "Convert image$? from RGB to YUV color bases."
  -v - -/ 255 -mix_channels (0.299,0.587,0.114;\
                             -0.14713,-0.28886,0.436;\
                             0.615,-0.51498,-0.10001) -v +

#@gmic rgb2yuv8
#@gmic : Convert selected images from RGB to YUV8 color bases.
#@gmic : $ image.jpg -rgb2yuv8 -split c
rgb2yuv8 :
  -e[^-1] "Convert image$? from RGB to YUV8 color bases."
  -v - -rgb2yuv -repeat @#
    -sh[$>] 0,0 -*[-1] 255 -rm[-1]
    -sh[$>] 1,1 -+[-1] 0.44 -*[-1] 289.773 -rm[-1]
    -sh[$>] 2,2 -+[-1] 0.62 -*[-1] 205.645 -rm[-1]
  -done -v +

#@gmic select_color : tolerance[%]>=0,col1,..,colN
#@gmic : Select pixels with specified color in selected images.
#@gmic : $ image.jpg --select_color 40,204,153,110
select_color : -skip ${1=0}
  -e[^-1] "Select color (${2--1}) in image$?, with tolerance $1."
  -v - -repeat @# -l[$>]
    (${2--1}) -y[1] c -r[1] [0] -- -norm -ge $1 -== 0
  -endl -done -v +

#@gmic sepia
#@gmic : Apply sepia tones effect on selected images.
#@gmic : $ image.jpg --sepia
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[^-1] [-1] -rm[-1] -v +

#@gmic solarize
#@gmic : Solarize selected images.
#@gmic : $ image.jpg --solarize
solarize :
  -e[^-1] "Solarize image$?."
  -v - -luminance -n 0,128 -map 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 @# -l[$<] -s c,{if(s==4,-3,if(s==2,1,-s))} -endl -done -v +

#@gmic srgb2rgb : (+)
#@gmic : Convert selected images from sRGB to RGB colorbases.

#@gmic to_a
#@gmic : Force selected images to have an alpha channel.
to_a :
  -e[^-1] "Force image$? to have an alpha channel."
  -v - -repeat @# -l[$>]
    -if {s==1||s==3} -channels 0,{s} -sh[-1] {s-1},{s-1} -f[-1] 255 -rm[-1] -endif
  -endl -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.
#@gmic : Default value: 'mode=0'.
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
    s=1 -repeat @#
      -if {@{$>,s}>4} -error "Image ["$>"] is not a G,GA,RGB or RGBA image."
      -else s={max($s,@{$>,s})}
      -endif
    -done -to_colormode $s
  -endif

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

#@gmic to_pseudogray : _max_step>=1,_is_perceptual_constraint={ 0 | 1 }
#@gmic : Convert selected scalar images ([0-255]-valued) to pseudo-gray color images.
#@gmic : Default parameters : 'max_step=2' and 'is_perceptual_constraint=0'.
#@gmic : The original pseudo-gray technique has been introduced by Rich Franzen [http://r0k.us/graphics/pseudoGrey.html].
#@gmic : Extension of this technique to arbitrary increments for more tones, has been done by David Tschumperle.
to_pseudogray : -check "isint(${1=1}) && $1>0" -skip ${2=0}
  -e[^-1] "Convert scalar image$? to pseudo-gray color images, with steps $1."
  -v - -channels 0 -srgb2rgb

  # Generate pseudogrey colormap.
  256,1,1,3,'x'
  {$1+1},{$1+1},{$1+1},1,'x' --f[-1] 'y' --f[-1] 'z' -a[-3--1] c -r[-1] {w*h*d},1,1,3,-1
  -f[-1] 'R=i(x,0,0,0);G=i(x,0,0,1);B=i(x,0,0,2);if(min(R,G,B),-1,i)'
  -permute[-1] cxyz -discard[-1] -1 -r[-1] 3,{h/3},1,1,-1 -permute[-1] yzcx
  -r[-2] {w*100}% -r[-1] [-2],0,2 -+[-2,-1]
  -f[-1] 'R=i(x,0,0,0);G=i(x,0,0,1);B=i(x,0,0,2);if(max(R,G,B)>255,-1,i)'
  -permute[-1] cxyz -discard[-1] -1 -r[-1] 3,{h/3},1,1,-1 -permute[-1] yzcx
  --srgb2rgb[-1] -rgb2lab[-1] -channels[-1] 0 -rv[-2,-1] -a[-2,-1] y -sort[-1] +,x -rows[-1] 1

  # Optimize colormap with respect to a perceptual constraint.
  -if $2 -repeat 100
    w={w}
    --srgb2rgb[-1] -rgb2lab[-1] --shift[-1] 1,0,0,0,0 --[-2,-1] -norm[-1]                # Compute dE between successive colors.
    -ge[-1] 2.3                                                                          # Get entries that do not respect the dE constraint.
    -a[-2,-1] c -f[-1] 'R=i(x,0,0,0);G=i(x,0,0,1);B=i(x,0,0,2);if(c==3&&R==G&&G==B,0,i)' # Force pure gray colors to be kept.
    -s[-1] c,-3
    --erode[-1] 2 --[-2,-1]                                                              # Determine entries to remove from colormap.
    -a[-2,-1] c -f[-1] 'if(i(x,0,0,3),-1,i)'                                             # Remove entries from colormap.
    -channels[-1] 0,2 -permute[-1] cxyz -discard[-1] -1 -r[-1] 3,{h/3},1,1,-1 -permute[-1] yzcx
    -if {w==$w} -break -endif
  -done -endif

  # Compute colormap with 65336 entries, to have match corresponding lightness.
  --srgb2rgb[-1] -rgb2lab[-1] -channels[-1] 0 -*[-1] {65535/100} -round[-1] -rows[-1] 0,2
  -rv[-2,-1] -permute[-1] xcyz -+[-1] 1 -a[-2,-1] y
  -pointcloud[-1] 0
  --norm[-1] -neq[-1] 0 -distance[-1] 1 -*[-1] -1 -watershed[-2] [-1] -rm[-1] --[-1] 1

  # Map colormap to images, with lightness preservation.
  -repeat {@#-1}
    -to_rgb[$>] -rgb2lab[$>] -channels[$>] 0 -*[$>] {65535/100} -round[$>] -c[$>] 0,65535
    -map[$>] [-1]
  -done -rm[-1] -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 @# -l[$>]
     -if {s>4} -error[] "Image ["@{<,-1}"] is not a G,GA,RGB or RGBA image."
     -elif {s==4} -channels 0,2
     -elif {s==2} -channels 0,0 -r 100%,100%,100%,3
     -elif {s==1} -r 100%,100%,100%,3
     -endif
   -endl -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 @# -l[$>]
     -if {s>4} -error[] "Image ["@{<,-1}"] is not a G,GA,RGB or RGBA image."
     -elif {s==3} -channels 0,3 -sh[-1] 3,3 -f[-1] 255 -rm[-1]
     -elif {s==2} -r 100%,100%,100%,4 -sh[-1] 2,2 -f[-1] [-2] -rm[-1]
     -elif {s==1} -r 100%,100%,100%,4 -sh[-1] 3,3 -f[-1] 255 -rm[-1]
     -endif
   -endl -done -v +

#@gmic transfer_colors : _transfer_brightness={ 0 | 1 }
#@gmic : Transfer colors of the first selected image to the other ones.
#@gmic : Default value: 'transfer_brightness=0'.
#@gmic : $ image.jpg --rand 0,255 -reverse --transfer_colors 1
transfer_colors : -skip ${1=0}
  -e[^-1] "Transfer colors of image [0] to image$?."
  -if {@#<2} -return -endif
  -v - -to_rgb[0] -to_colormode[^0] {max(3,@{-max_s})} -c 0,255      # Convert all images to RGB[A]
  -repeat @# -l[$>] -split_opacity -rgb2ycbcr[0] -a c -endl -done    # Perform RGB[A] to YCbCr[A] conversion.
  -l[0] -s c -histogram_cumul 256,1,0,255 -a c -* 255 -endl          # Compute channel-by-channel cumulative histogram of target image.
  -repeat {@#-1} -l[0,-1]
    -if $1 -repeat 3 -sh[0,1] $>,$> -equalize[-1] 256,0,255 -index[-1] [-2],0,0 -rm[-2,-1] -done         # Transfer brightness + colors.
    -else -repeat 2 -sh[0,1] {$>+1},{$>+1} -equalize[-1] 256,0,255 -index[-1] [-2],0,0 -rm[-2,-1] -done  # Transfer colors only.
    -endif
  -endl -mv[-1] 1 -done -rm[0]
  -repeat @# -l[$>] -split_opacity -ycbcr2rgb[0] -a c -endl -done    # Perform YCbCr[A] to RGB[A] conversion.
  -v +

_transfer_colors :  # Check transfer_colors performance.
  -repeat @# -l[$>] -rgb2ycbcr -s c -histogram 256,0,255 -a c -dg 300,200 -endl -done

#@gmic xyz2rgb
#@gmic : Convert selected images from XYZ to RGB colorbases.
xyz2rgb :
  -e[^-1] "Convert image$? from XYZ to RGB color bases."
  -v - -* 255 -mix_channels (3.240479,-1.537150,-0.498535;\
                             -0.969256,1.875992,0.041556;\
                             0.055648,-0.204043,1.057311) -c 0,255 -v +

#@gmic xyz82rgb
#@gmic : Convert selected images from XYZ8 to RGB color bases.
xyz82rgb :
  -e[^-1] "Convert image$? from XYZ8 to RGB color bases."
  -v - -repeat @#
    -sh[$>] 0,0 -/[-1] 255 -rm[-1]
    -sh[$>] 1,1 -/[-1] 255 -rm[-1]
    -sh[$>] 2,2 -/[-1] 231.8182 -rm[-1]
  -done -xyz2rgb -v +

#@gmic ycbcr2rgb
#@gmic : Convert selected images from YCbCr to RGB colorbases.
ycbcr2rgb :
  -e[^-1] "Convert image$? from YCbCr to RGB color bases."
  -v - -repeat @# -l[$>] -sh 0,0 --[-1] 16 -rm[-1] -sh 1,2 --[-1] 128 -rm[-1] -endl -done
  -mix_channels (298,0,409;298,-100,-208;298,516,0) -+ 128 -/ 256 -c 0,255
  -v +

#@gmic yuv2rgb
#@gmic : Convert selected images from YUV to RGB colorbases.
yuv2rgb :
  -e[^-1] "Convert image$? from YUV to RGB color bases."
  -v - -mix_channels (1,0,1.13983;\
                      1,-0.39465,-0.5806;\
                      1,2.03211,0) -* 255 -v +

#@gmic yuv82rgb
#@gmic : Convert selected images from YUV8 to RGB color bases.
yuv82rgb :
  -e[^-1] "Convert image$? from YUV8 to RGB color bases."
  -v - -repeat @#
    -sh[$>] 0,0 -/[-1] 255 -rm[-1]
    -sh[$>] 1,1 -/[-1] 289.773 --[-1] 0.44 -rm[-1]
    -sh[$>] 2,2 -/[-1] 205.645 --[-1] 0.62 -rm[-1]
  -done -yuv2rgb -v +

#---------------------------------
#
#@gmic :: Geometry manipulation
#
#---------------------------------

#@gmic a : eq. to '-append' : (*)

#@gmic append : [image],axis,_alignment : axis,_alignment : (*)
#@gmic : Append specified image to selected images, or all selected images together, along specified axis.
#@gmic : (eq. to '-a').
#@gmic : 'axis' can be { x | y | z | c }.
#@gmic : Usual 'alignment' values are { 0=left-justified | 0.5=centered | 1=right-justified }.
#@gmic : Default value: 'alignment=0'.
#@gmic : $ image.jpg -split y,10 -reverse -append y
#@gmic : $ image.jpg -repeat 5 --rows[0] 0,{10+18*$>}% -done -rm[0] -append x,0.5
#@gmic : $ image.jpg -append[0] [0],y

#@gmic append_tiles : M>=0,_N>=0,0<=_x_alignment<=1,0<=_y_alignment<=1
#@gmic : Append MxN selected tiles as new images.
#@gmic : If 'N' is set to 0, number of rows is determined automatically.
#@gmic : If 'M' is set to 0, number of columns is determined automatically.
#@gmic : If 'M' and 'N' are both set to '0', auto-mode is used.
#@gmic : If 'M' or 'N' is set to 0, only a single image is produced.
#@gmic : 'x_alignment' and 'y_aligment' tells about the alignment of tiles when they have different sizes.
#@gmic : Default values: 'M=0', 'N=0', 'x_alignment=y_alignment=0.5'.
#@gmic : $ image.jpg -split xy,4 -append_tiles ,
append_tiles : -check "isint(${1=0}) && isint(${2=0}) && ${3=0.5}>=0 && $3<=1 && ${4=$3}>=0 && $4<=1"
  -if {!$1&&!$2} # auto-mode
    -v - N={int(sqrt(@#))} M={round(@#/$N,1,1)}
    -v + -e[0--3] "Append image$? as a "${M}x${N}"-tiled image (auto-mode)." -v -
    MN={$M*$N} -if {@#%$MN} {$MN-(@#%$MN)} -s[-1] x -endif
  -elif {!$2} # auto-rows
    -v - M=$1 N={round(@#/$1,1,1)}
    -v + -e[0--3] "Append image$? as a "${M}x${N}"-tiled image." -v -
    -if {$M>@#} -v + -warn[0--3] "Missing images for having one row in a "${M}x${N}"-tiled image." -return -endif
    -if {@#%$M} {$M-(@#%$M)} -s[-1] x -endif
  -elif {!$1} # auto-columns
    -v - M={round(@#/$2,1,1)} N=$2
    -v + -e[0--3] "Append image$? as a "${M}x${N}"-tiled image." -v -
    -if {$N>@#} -v + -warn[0--3] "Missing images for having one column in a "${M}x${N}"-tiled image." -return -endif
    -if {@#%$M} {$M-(@#%$M)} -s[-1] x -endif
  -else
    -e[0--3] "Append image$?, as $1x$2-tiled images." -v -
    M=$1 N=$2
  -endif
  -if {!@#} -v + -return -endif

  MN={$M*$N}
  -repeat {int(@#/$MN)} -l[$>-{$>+$MN-1}]

    # Resize to best match for each column and row.
    $MN,1,1,2 -repeat $MN -point[-1] $>,0,0,1,@{$>,w},@{$>,h} -done -r[-1] $M,$N,1,2,-1
    -s[-1] c -l[-2] -s y -max -endl -l[-1] -s x -max -endl
    i=0 -repeat $N y=$> -repeat $M -r[$i] @{-2,$>},@{-1,$y},100%,100%,0,0,$3,$4 i={$i+1} -done -done
    -rm[-2,-1]

    # Append images together.
    -repeat {int(@#/$M)} -a[$>-{$>+$M-1}] x -done
    -repeat {int(@#/$N)} -a[$>-{$>+$N-1}] y -done
  -endl -done
  -v +

#@gmic autocrop : value1,value2,.. : (no args) : (*)
#@gmic : Autocrop selected images by specified vector-valued intensity.
#@gmic : If no arguments are provided, cropping value is guessed.
#@gmic : $ 400,400,1,3 -fill_color 64,128,255 -ellipse 50%,50%,120,120,0,1,255 --autocrop

#@gmic autocrop_seq : value1,value2,... | auto
#@gmic : Autocrop selected images using the crop geometry of the last one by specified vector-valued intensity,
#@gmic : or by automatic guessing the cropping value.
#@gmic : Default value: auto mode.
#@gmic : $ image.jpg --f[-1] 0 -ellipse[-1] 50%,50%,30%,20%,0,1,1 -autocrop_seq 0
autocrop_seq : -skip ${1=auto}
  -e[^-1] "Auto-crop image$? using crop geometry of last image by vector '$*'."
  -if {!@#} -return -endif
  -v -
  is_auto={$1'=='auto}
  -if {@#==1} -_autocrop_seq$is_auto ${1--1} -v + -return -endif
  w={w} h={h} d={d}
  value={i(w-1,h-1,d-1)} --=[-1] {1+$value},100%,100%,100% -_autocrop_seq$is_auto[-1] ${1--1} -=[-1] $value,100%,100%,100%
  x0={$w-w} y0={$h-h} z0={$d-d} -rm[-1]
  -_autocrop_seq$is_auto[-1] ${1--1}
  x1={$x0+w-1} y1={$y0+h-1} z1={$z0+d-1}
  -if {$x0>$x1" || "$y0>$y1" || "$z0>$z1} -i[0--3] 0 -rm[1--2:2]
  -else -crop[^-1] $x0,$y0,$z0,$x1,$y1,$z1
  -endif
  -v +

_autocrop_seq0 : -autocrop $*
_autocrop_seq1 : -skip $* -autocrop

#@gmic channels : { [image0] | c0[%] },_{ [image1] | c1[%] } : (*)
#@gmic : Keep only specified channels of selected images.
#@gmic : Dirichlet boundary is used when specified channels are out of range.
#@gmic : $ image.jpg -channels 0,1
#@gmic : $ image.jpg -luminance -channels 0,2

#@gmic columns : { [image0] | x0[%] },_{ [image1] | x1[%] } : (*)
#@gmic : Keep only specified columns of selected images.
#@gmic : Dirichlet boundary is used when specified columns are out of range.
#@gmic : $ image.jpg -columns -25%,50%

#@gmic z : eq. to '-crop'. : (*)

#@gmic crop : x0[%],x1[%],_boundary : x0[%],y0[%],x1[%],y1[%],_boundary : x0[%],y0[%],z0[%],x1[%],y1[%],z1[%],_boundary : x0[%],y0[%],z0[%],c0[%],x1[%],y1[%],z1[%],c1[%],_boundary : (noargs) : (*)
#@gmic : Crop selected images with specified region coordinates.
#@gmic : (eq. to '-z').
#@gmic : 'boundary' can be { 0=dirichlet | 1=neumann }.
#@gmic : (noargs) runs interactive mode (uses the instant window [0] if opened).
#@gmic : Default value: 'boundary=0'.
#@gmic : $ image.jpg --crop -230,-230,280,280,1 -crop[0] -230,-230,280,280,0
#@gmic : $ image.jpg -crop 25%,25%,75%,75%

#@gmic diagonal
#@gmic : Transform selected vectors as diagonal matrices.
#@gmic : $ 1,10,1,1,'y' --diagonal
diagonal :
  -e[^-1] "Transform vector$? as diagonal matrix."
  -v - -y y -repeat @# -r[$>] @{$>,h+1},100%,1,1,0 -r[$>] @{$>,h},100%,1,1,-1 -done -v +

#@gmic elevate : _depth,_is_plain,_is_colored
#@gmic : Elevate selected 2d images into 3d volumes.
#@gmic : Default values: 'depth=64', 'is_plain=1' and 'is_colored=1'.
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[$>] nm=@{0,n}
    --norm 100%,100%,$1,{if($3,@{0,s},1)}
    m=@{-2,m} d={@{-2,M}-$m}
    -repeat $1
      -if $2 --ge[1] {$m+$d*($>+1)/$1}
      -else --t2[1] {$m+$d*$>/$1},{$m+$d*($>+1)/$1}
      -endif
      -r[-1] 100%,100%,1,[-2] -if $3 -*[-1] [0] -endif
      -j[-2] [-1],0,0,$> -rm[-1]
    -done
  -rm[0,1] -nm $nm,1 -endl -done -v +

#@gmic expand_x : size_x>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the X-axis.
#@gmic : Default value: 'border=1'.
#@gmic : $ image.jpg -expand_x 30,0
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[$>] @{$>,w+2*$1},100%,100%,100%,0,$2,0.5,0.5,0.5 -done -v +

#@gmic expand_xy : size>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the XY-axes.
#@gmic : Default value: 'border=1'.
#@gmic : $ image.jpg -expand_xy 30,0
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[$>] @{$>,w+2*$1},@{$>,h+2*$1},100%,100%,0,$2,0.5,0.5,0.5 -done -v +

#@gmic expand_xyz : size>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the XYZ-axes.
#@gmic : Default value: 'border=1'.
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[$>] @{$>,w+2*$1},@{$>,h+2*$1},@{$>,d+2*$1},100%,0,$2,0.5,0.5,0.5 -done -v +

#@gmic expand_y : size_y>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the Y-axis.
#@gmic : Default value: 'border=1'.
#@gmic : $ image.jpg -expand_y 30,0
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[$>] 100%,@{$>,h+2*$1},100%,100%,0,$2,0.5,0.5,0.5 -done -v +

#@gmic expand_z : size_z>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Expand selected images along the Z-axis.
#@gmic : Default value: 'border=1'.
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[$>] 100%,100%,@{$>,d+2*$1},100%,0,$2,0.5,0.5,0.5 -done -v +

#@gmic mirror : { x | y | z }..{ x | y | z } : (*)
#@gmic : Mirror selected images along specified axes.
#@gmic : $ image.jpg --mirror y --mirror[0] c
#@gmic : $ image.jpg --mirror x --mirror y -append_tiles 2,2

#@gmic permute : permutation_string : (*)
#@gmic : Permute selected image axes by specified permutation.
#@gmic : 'permutation' is a combination of the character set {x|y|z|c},
#@gmic : e.g. 'xycz', 'cxyz', ..
#@gmic : $ image.jpg -permute yxzc

#@gmic r : eq. to '-resize'. : (*)

#@gmic resize : [image],_interpolation,_boundary,_ax,_ay,_az,_ac : {[image_w] | width>0[%]},_{[image_h] | height>0[%]},_{[image_d] | depth>0[%]},_{[image_s] | spectrum>0[%]},_interpolation,_boundary,_ax,_ay,_az,_ac : (noargs) : (*)
#@gmic : Resize selected images with specified geometry.
#@gmic : (eq. to '-r').
#@gmic : 'interpolation' can be { -1=none (memory content) | 0=none | 1=nearest | 2=average | 3=linear | 4=grid | 5=bicubic | 6=lanczos }.
#@gmic : 'boundary' has different meanings, according to the chosen 'interpolation' mode :
#@gmic : . When 'interpolation=={ -1 | 1 | 2 | 4 }', 'boundary' is meaningless.
#@gmic : . When 'interpolation==0', 'boundary' can be { 0=dirichlet | 1=neumann | 2=cyclic }.
#@gmic : . When 'interpolation=={ 3 | 5 | 6 }', 'boundary' can be { 0=none | 1=neumann }.
#@gmic : 'ax,ay,az,ac' set the alignment mode along each axis when 'interpolation=0 or 4'
#@gmic : (set to '0' by default, must be defined in range [0,1]).
#@gmic : (noargs) runs interactive mode (uses the instant window [0] if opened).
#@gmic : Default values: 'interpolation=1', 'boundary=0' and 'ax=ay=az=ac=0'.
#@gmic : $ image.jpg (0,1;0,1^0,0;1,1^1,1;1,1) -resize[-1] [-2],3 -mul[-2] [-1]
#@gmic : $ image.jpg --resize[-1] 256,128,1,3,2 --resize[-1] 120%,120%,1,3,0,1,0.5,0.5 --resize[-1] 120%,120%,1,3,0,0,0.2,0.2 --resize[-1] [0],[0],1,3,4

#@gmic resize_pow2 : _interpolation,_boundary,_ax,_ay,_az,_ac
#@gmic : Resize selected images so that each dimension is a power of 2.
#@gmic : 'interpolation' can be { -1=none (memory content) | 0=none | 1=nearest | 2=average | 3=linear | 4=grid | 5=bicubic | 6=lanczos }.
#@gmic : 'boundary' has different meanings, according to the chosen 'interpolation' mode :
#@gmic : . When 'interpolation=={ -1 | 1 | 2 | 4 }', 'boundary' is meaningless.
#@gmic : . When 'interpolation==0', 'boundary' can be { 0=dirichlet | 1=neumann | 2=cyclic }.
#@gmic : . When 'interpolation=={ 3 | 5 | 6 }', 'boundary' can be { 0=none | 1=neumann }.
#@gmic : 'ax,ay,az,ac' set the alignment mode along each axis when 'interpolation=0'
#@gmic : (set to '0' by default, must be defined in range [0,1]).
#@gmic : Default values: 'interpolation=0', 'boundary=0' and 'ax=ay=az=ac=0'.
#@gmic : $ image.jpg --resize_pow2[-1] 0
resize_pow2 : -check "isint(${1=0}) && $1>=-1 && $1<=6" -skip ${2=0},${3=0},${4=0},${5=0},${6=0}
  -e[^-1] "Resize image$? so that each dimension is a power of 2."
  -v - -repeat @#
    -r[$>] @{$>,2^(round(log2(w),1,1))},@{$>,2^(round(log2(h),1,1))},@{$>,2^(round(log2(d),1,1))},100%,${1-6}
  -done -v +

#@gmic resize2x : (*)
#@gmic : Resize selected images using the Scale2x algorithm.
#@gmic : $ image.jpg -threshold 50% -resize 50%,50% --resize2x

#@gmic resize3x : (*)
#@gmic : Resize selected images using the Scale3x algorithm.
#@gmic : $ image.jpg -threshold 50% -resize 33%,33% --resize3x

#@gmic rr2d : eq. to '-resize_ratio2d'.
rr2d :
  -_resize_ratio2d $*

#@gmic resize_ratio2d : width>0,height>0,_mode={ 0=inside | 1=outside | 2=padded },0=<_interpolation<=6
#@gmic : Resize selected images while preserving their aspect ratio.
#@gmic : (eq. to '-rr2d').
#@gmic : Default values: 'mode=0' and 'interpolation=6'.
resize_ratio2d :
  -_resize_ratio2d $*

_resize_ratio2d : -check "$1>0 && $2>0 && ${3=0}>=0 && $3<=2 && ${4=6}>=0 && $4<=6"
  -e[0--3] "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 @#
    ratio=@{$>,if($3==1,max($1/w,$2/h),min($1/w,$2/h))}
    -r[$>] @{$>,w*$ratio},@{$>,h*$ratio},100%,100%,$4
  -done
  -if {$3==2} -r $1,$2,100%,100%,0,0,0.5,0.5 -endif
  -v +

#@gmic r2dx : eq. to '-resize2dx'.
r2dx :
  -_resize2dx $*

#@gmic resize2dx : width>0,_interpolation,_boundary,_ax,_ay,_az,_ac
#@gmic : Resize selected images along the X-axis, preserving 2d ratio.
#@gmic : (eq. to '-r2dx').
#@gmic : 'interpolation' can be { -1=none (memory content) | 0=none | 1=nearest | 2=average | 3=linear | 4=grid | 5=bicubic | 6=lanczos }.
#@gmic : 'boundary' has different meanings, according to the chosen 'interpolation' mode :
#@gmic : . When 'interpolation=={ -1 | 1 | 2 | 4 }', 'boundary' is meaningless.
#@gmic : . When 'interpolation==0', 'boundary' can be { 0=dirichlet | 1=neumann | 2=cyclic }.
#@gmic : . When 'interpolation=={ 3 | 5 | 6 }', 'boundary' can be { 0=none | 1=neumann }.
#@gmic : 'ax,ay,az,ac' set the alignment mode along each axis when 'interpolation=0'
#@gmic : (set to '0' by default, must be defined in range [0,1]).
#@gmic : Default values: 'interpolation=2', 'boundary=0' and 'ax=ay=az=ac=0'.
#@gmic : $ image.jpg --resize2dx 100,2 -append x
resize2dx :
  -_resize2dx $*

_resize2dx : -check "$1>0 && ${2=2}>=0 && $2<=6 && ${3=0}>=0 && $3<=2 && ${4=0}>=0 && $4<=1 && ${5=0}>=0 && $5<=1 && ${6=0}>=0 && $6<=1 && ${7=0}>=0 && $7<=1"
  -e[0--3] "Resize 2d image$? to $1 pixels along the X-axis, preserving 2d ratio."
  -v - -repeat @# -r[$>] $1,@{$>,max(1,h*$1/w)},100%,100%,${2-7} -done -v +

#@gmic r2dy : eq. to '-resize2dy'.
r2dy :
  -_resize2dy $*

#@gmic resize2dy : height>0,_interpolation,_boundary,_ax,_ay,_az,_ac
#@gmic : Resize selected images along the Y-axis, preserving 2d ratio.
#@gmic : (eq. to '-r2dy').
#@gmic : 'interpolation' can be { -1=none (memory content) | 0=none | 1=nearest | 2=average | 3=linear | 4=grid | 5=bicubic | 6=lanczos }.
#@gmic : 'boundary' has different meanings, according to the chosen 'interpolation' mode :
#@gmic : . When 'interpolation=={ -1 | 1 | 2 | 4 }', 'boundary' is meaningless.
#@gmic : . When 'interpolation==0', 'boundary' can be { 0=dirichlet | 1=neumann | 2=cyclic }.
#@gmic : . When 'interpolation=={ 3 | 5 | 6 }', 'boundary' can be { 0=none | 1=neumann }.
#@gmic : 'ax,ay,az,ac' set the alignment mode along each axis when 'interpolation=0'
#@gmic : (set to '0' by default, must be defined in range [0,1]).
#@gmic : Default values: 'interpolation=2', 'boundary=0' and 'ax=ay=az=ac=0'.
#@gmic : $ image.jpg --resize2dy 100,2 -append x
resize2dy :
  -_resize2dy $*

_resize2dy : -check "$1>0 && ${2=2}>=0 && $2<=6 && ${3=0}>=0 && $3<=2 && ${4=0}>=0 && $4<=1 && ${5=0}>=0 && $5<=1 && ${6=0}>=0 && $6<=1 && ${7=0}>=0 && $7<=1"
  -e[0--3] "Resize 2d image$? to $1 pixels along the Y-axis, preserving 2d ratio."
  -v - -repeat @# -r[$>] @{$>,max(1,w*$1/h)},$1,100%,100%,${2-7} -done -v +

#@gmic r3dx : eq. to '-resize3dx'.
r3dx :
  -_resize3dx $*

#@gmic resize3dx : width>0,_interpolation,_boundary,_ax,_ay,_az,_ac
#@gmic : Resize selected images along the X-axis, preserving 3d ratio.
#@gmic : (eq. to '-r3dx').
#@gmic : 'interpolation' can be { -1=none (memory content) | 0=none | 1=nearest | 2=average | 3=linear | 4=grid | 5=bicubic | 6=lanczos }.
#@gmic : 'boundary' has different meanings, according to the chosen 'interpolation' mode :
#@gmic : . When 'interpolation=={ -1 | 1 | 2 | 4 }', 'boundary' is meaningless.
#@gmic : . When 'interpolation==0', 'boundary' can be { 0=dirichlet | 1=neumann | 2=cyclic }.
#@gmic : . When 'interpolation=={ 3 | 5 | 6 }', 'boundary' can be { 0=none | 1=neumann }.
#@gmic : 'ax,ay,az,ac' set the alignment mode along each axis when 'interpolation=0'
#@gmic : (set to '0' by default, must be defined in range [0,1]).
#@gmic : Default values: 'interpolation=2', 'boundary=0' and 'ax=ay=az=ac=0'.
resize3dx :
  -_resize3dx $*

_resize3dx : -check "$1>0 && ${2=2}>=0 && $2<=6 && ${3=0}>=0 && $3<=2 && ${4=0}>=0 && $4<=1 && ${5=0}>=0 && $5<=1 && ${6=0}>=0 && $6<=1 && ${7=0}>=0 && $7<=1"
  -e[0--3] "Resize 3d image$? to $1 pixels along the X-axis, preserving 3d ratio."
  -v - -repeat @# -r[$>] $1,@{$>,max(1,h*$1/w)},@{$>,max(1,d*$1/w)},100%,${2-7} -done -v +

#@gmic r3dy : eq. to '-resize3dy'.
r3dy :
  -_resize3dy $*

#@gmic resize3dy : height>0,_interpolation,_boundary,_ax,_ay,_az,_ac
#@gmic : Resize selected images along the Y-axis, preserving 3d ratio.
#@gmic : (eq. to '-r3dy').
#@gmic : 'interpolation' can be { -1=none (memory content) | 0=none | 1=nearest | 2=average | 3=linear | 4=grid | 5=bicubic | 6=lanczos }.
#@gmic : 'boundary' has different meanings, according to the chosen 'interpolation' mode :
#@gmic : . When 'interpolation=={ -1 | 1 | 2 | 4 }', 'boundary' is meaningless.
#@gmic : . When 'interpolation==0', 'boundary' can be { 0=dirichlet | 1=neumann | 2=cyclic }.
#@gmic : . When 'interpolation=={ 3 | 5 | 6 }', 'boundary' can be { 0=none | 1=neumann }.
#@gmic : 'ax,ay,az,ac' set the alignment mode along each axis when 'interpolation=0'
#@gmic : (set to '0' by default, must be defined in range [0,1]).
#@gmic : Default values: 'interpolation=2', 'boundary=0' and 'ax=ay=az=ac=0'.
resize3dy :
  -_resize3dy $*

_resize3dy : -check "$1>0 && ${2=2}>=0 && $2<=6 && ${3=0}>=0 && $3<=2 && ${4=0}>=0 && $4<=1 && ${5=0}>=0 && $5<=1 && ${6=0}>=0 && $6<=1 && ${7=0}>=0 && $7<=1"
  -e[0--3] "Resize 3d image$? to $1 pixels along the Y-axis, preserving 3d ratio."
  -v - -repeat @# -r[$>] @{$>,max(1,w*$1/h)},$1,@{$>,max(1,d*$1/h)},100%,${2-7} -done -v +

#@gmic r3dz : eq. to '-resize3dz'.
r3dz :
  -_resize3dz $*

#@gmic resize3dz : depth>0,_interpolation,_boundary,_ax,_ay,_az,_ac
#@gmic : Resize selected images along the Z-axis, preserving 3d ratio.
#@gmic : (eq. to '-r3dz').
#@gmic : 'interpolation' can be { -1=none (memory content) | 0=none | 1=nearest | 2=average | 3=linear | 4=grid | 5=bicubic | 6=lanczos }.
#@gmic : 'boundary' has different meanings, according to the chosen 'interpolation' mode :
#@gmic : . When 'interpolation=={ -1 | 1 | 2 | 4 }', 'boundary' is meaningless.
#@gmic : . When 'interpolation==0', 'boundary' can be { 0=dirichlet | 1=neumann | 2=cyclic }.
#@gmic : . When 'interpolation=={ 3 | 5 | 6 }', 'boundary' can be { 0=none | 1=neumann }.
#@gmic : 'ax,ay,az,ac' set the alignment mode along each axis when 'interpolation=0'
#@gmic : (set to '0' by default, must be defined in range [0,1]).
#@gmic : Default values: 'interpolation=2', 'boundary=0' and 'ax=ay=az=ac=0'.
resize3dz :
  -_resize3dz $*

_resize3dz : -check "$1>0 && ${2=2}>=0 && $2<=6 && ${3=0}>=0 && $3<=2 && ${4=0}>=0 && $4<=1 && ${5=0}>=0 && $5<=1 && ${6=0}>=0 && $6<=1 && ${7=0}>=0 && $7<=1"
  -e[0--3] "Resize 3d image$? to $1 pixels along the Z-axis, preserving 3d ratio."
  -v - -repeat @# -r[$>] @{$>,max(1,w*$1/d)},@{$>,max(1,h*$1/d)},$1,100%,${2-7} -done -v +

#@gmic rotate : angle,_boundary,_interpolation,_cx[%],_cy[%],_zoom : (*)
#@gmic : Rotate selected images with specified angle (in deg.).
#@gmic : 'boundary' can be { 0=dirichlet | 1=neumann | 2=cyclic }.
#@gmic : 'interpolation' can be { 0=none | 1=linear | 2=bicubic }.
#@gmic : When rotation center ('cx','cy') is specified, the size of the image is preserved.
#@gmic : Default values: 'boundary=0', 'interpolation=1', 'cx=cy=(undefined)' and 'zoom=1'.
#@gmic : $ image.jpg --rotate -25,2,1,50%,50%,0.6  -rotate[0] 25

#@gmic rotate_tileable : angle,_max_size_factor>=0
#@gmic : Rotate selected images by specified angle and make them tileable.
#@gmic : If resulting size of an image is too big, the image is replaced by a 1x1 image.
#@gmic : Default values: 'max_size_factor=8'.
rotate_tileable : -check ${2=8}>=0
  -e[^-1] "Rotate image$? with angle $1° and make them tileable."
  -v -

  # Reduce angle to known fraction.
  angle={$1%360}
  -if {$angle>=270} -rotate 270 angle={$angle-270}
  -elif {$angle>=180} -rotate 180 angle={$angle-180}
  -elif {$angle>=90} -rotate 90 angle={$angle-90}
  -endif
  (0,1;1,8;1,7;1,6;1,5;1,4;1,5;1,3;2,5;1,2;2,5;3,5;2,3;3,4;4,5;1,1;5,4;7,5;3,2;8,5;9,5;2,1;3,1;4,1;5,1;6,1;7,1;8,1) # List of known fractions.
  -s[-1] x,2 --/[-2,-1] -atan[-1] -*[-1] {180/pi}         # Compute corresponding angles.
  ($angle) -index[-1] [-2] -rm[-2]
  p=@{-3,@-1} q=@{-2,@-1} -rm[-3--1]                      # Find nearest fraction p/q to atan(angle).
  -if {!$p||!$q} -return -endif

  -repeat @# -l[$>]
    # Compute width and height of tile.
    theta={atan2($p,$q)}
    gcd=@{-gcd" "{h*$q},{w*$p}}
    pw={h*$q/$gcd}
    nw={round($pw*w/cos($theta))}
    gcd=@{-gcd" "{h*$p},{w*$q}}
    qh={w*$q/$gcd}
    nh={round($qh*h/cos($theta))}

    # Rotate and make tileable (may result in very large images!).
    -if {!$2" || "($nw<$2*w" && "$nh<$2*h)}
      -r {1.5*$nw},{1.5*$nh},1,100%,0,2
      -rotate {$theta*180/pi},2,1,50%,50%
      -r $nw,$nh,1,100%,0,2,0.5,0.5
    -else -rm 1
    -endif
  -endl -done -v +

#@gmic rows : { [image0] | y0[%] },_{ [image1] | y1[%] } : (*)
#@gmic : Keep only specified rows of selected images.
#@gmic : Dirichlet boundary is used when specified rows are out of range.
#@gmic : $ image.jpg -rows -25%,50%

#@gmic shift : vx[%],_vy[%],_vz[%],_vc[%],_boundary : (*)
#@gmic : Shift selected images by specified displacement vector.
#@gmic : 'boundary' can be { 0=dirichlet | 1=neumann | 2=cyclic }.
#@gmic : Default value: 'boundary=0'.
#@gmic : $ image.jpg --shift[0] 50%,50%,0,0,0 --shift[0] 50%,50%,0,0,1 --shift[0] 50%,50%,0,0,2

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

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

#@gmic shrink_y : size_y>=0
#@gmic : Shrink selected images along the Y-axis.
#@gmic : $ image.jpg -shrink_y 30
shrink_y : -check "$1>=0"
  -e[^-1] "Shrink image$? along the Y-axis with size $1."
  -v - -repeat @# -z[$>] 0,$1,100%,@{$>,h-$1-1} -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 @# -z[$>] 0,0,$1,100%,100%,@{$>,d-$1-1} -done -v +

#@gmic slices : { [image0] | z0[%] },_{ [image1] | z1[%] } : (*)
#@gmic : Keep only specified slices of selected images.
#@gmic : Dirichlet boundary is used when specified slices are out of range.

#@gmic sort : _ordering={ + | - },_axis={ x | y | z | c } : (+)
#@gmic : Sort pixel values of selected images.
#@gmic : If 'axis' is specified, the sorting is done according to the data of the first column/row/slice/channel
#@gmic : of selected images.
#@gmic : Default values: 'ordering=+' and 'axis=(undefined)'.
#@gmic : $ 64 -rand 0,100 --sort -display_graph 400,300,3

#@gmic s : eq. to '-split'. : (*)

#@gmic split : { x | y | z | c }..{ x | y | z | c },_nb_parts : keep_splitting_values={ + | - },value1,value2,... : (*)
#@gmic : Split selected images along specified axis, or sequence of scalar values.
#@gmic : (eq. to '-s').
#@gmic : 'nb_parts' can be { 0=maximum split | >0=split in N parts | <0=split in parts of size -N }.
#@gmic : 'boundary' can be { 0=dirichlet | 1=neumann }.
#@gmic : Default value: 'nb_parts=0'.
#@gmic : $ image.jpg -split c
#@gmic : $ image.jpg -split y,3
#@gmic : $ image.jpg -split x,-128

#@gmic split_tiles : M!=0,_N!=0,_is_homogeneous={ 0 | 1 }
#@gmic : Split selected images as a MxN array of tiles.
#@gmic : Default values: 'N=M' and 'is_homogeneous=0'.
#@gmic : $ image.jpg --local -split_tiles 5,4 -blur 3,0 -sharpen 700 -append_tiles 4,5 -endlocal
split_tiles : -skip ${2=$1},${3=0}
  -if $3 -e[^-1] "Split image$? as a $1x$2 array of homogeneous tiles."
  -else -e[^-1] "Split image$? as a $1x$2 array of tiles."
  -endif
  -v - -repeat @# -l[$<] -s y,$2 -s x,$1 -if $3 -r [0],[0],100%,100%,0 -endif -endl -done -v +

#@gmic y : eq. to '-unroll'. : (*)

#@gmic unroll : axis={ x | y | z | c } : (*)
#@gmic : Unroll selected images along specified axis.
#@gmic : (eq. to '-y').
#@gmic : $ (1,2,3;4,5,6;7,8,9) --unroll y

#@gmic upscale_smart : width,_height,_depth,_smoothness>=0,_anisotropy=[0,1],sharpening>=0
#@gmic : Upscale selected images with an edge-preserving algorithm.
#@gmic : Default values: 'height=100%', 'depth=100%', 'smoothness=2', 'anisotropy=0.4' and 'sharpening=10'.
#@gmic : $ image.jpg -resize2dy 100 --upscale_smart 500%,500% -append x
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 @# -l[$>]
    w={w} h={h}
    --r[-1] $1,$2,$3,1,0 # Compute desired dimensions.
    -if {w<$w" && "h<$h} # Test for downscaling
      -rm[-1] -r[-1] $1,$2,$3,100%,2
    -else
      -rm[-1] --diffusiontensors 0,$5,1.2,1.2
      -r[-2,-1] $1,$2,$3,100%,5
      -smooth[-2] [-1],$4 -rm[-1]
      -apply_channels "-sharpen[-1] $6,10",3,0
    -endif
  -endl -done -v +

#@gmic warp : [warping_field],_is_relative={ 0 | 1 },_interpolation={ 0 | 1 },_boundary,_nb_frames>0 : (+)
#@gmic : Warp selected image with specified displacement field.
#@gmic : 'boundary' can be { 0=dirichlet | 1=neumann | 2=cyclic }.
#@gmic : Default values: 'is_relative=0', 'interpolation=1', 'boundary=1' and 'nb_frames=1'.
#@gmic : $ image.jpg 100%,100%,1,2,'X=x/w-0.5;Y=y/h-0.5;R=(X*X+Y*Y)^0.5;A=atan2(Y,X);130*R*if(c==0,cos(4*A),sin(8*A))' -warp[-2] [-1],1,1,0 -quiver[-1] [-1],10,0.2,1,1,100

#---------------------------------
#
#@gmic :: Filtering
#
#---------------------------------

#@gmic bandpass : _min_freq[%],_max_freq[%]
#@gmic : Apply bandpass filter to selected images.
#@gmic : Default values: 'min_freq=0' and 'max_freq=20%'.
#@gmic : $ image.jpg -bandpass 1%,3%
bandpass : -skip ${1=0},${2=20%}
  -e[^-1] "Apply bandpass filter [$1,$2] to image$?."
  -v - -repeat @# -l[$>]
    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] {int(w/2)},{int(h/2)},50%,0,2
    -fft[-2] -*[-3] [-1] -*[-2,-1] -ifft -rm[-1]
  -endl -done -v +

#@gmic bilateral : std_variation_s>0[%],std_variation_r>0 : (+)
#@gmic : Blur selected images by anisotropic bilateral filtering.
#@gmic : $ image.jpg [0] -repeat 5 -bilateral[-1] 10,10 -done

#@gmic b : eq. to '-blur'. : (+)

#@gmic blur : std_variation>=0[%],_boundary : (+)
#@gmic : Blur selected images by a quasi-gaussian recursive filter.
#@gmic : (eq. to '-b').
#@gmic : 'boundary' can be { 0=dirichlet | 1=neumann }.
#@gmic : Default value: 'boundary=1'.
#@gmic : $ image.jpg --blur 5,0 --blur[0] 5,1

#@gmic blur_angular : amplitude[%],_cx,_cy
#@gmic : Apply angular blur on selected images.
#@gmic : Default values: 'cx=cy=0.5'.
#@gmic : $ image.jpg --blur_angular 2%
blur_angular : -skip ${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_linear : amplitude1[%],_amplitude2[%],_angle,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Apply linear blur on selected images, with specified angle and amplitudes.
#@gmic : Default values: 'amplitude2=0', 'angle=0' and 'boundary=1'.
#@gmic : $ image.jpg --blur_linear 10,0,45
blur_linear : -skip ${2=0},${3=0},${4=1}
  -e[^-1] "Apply linear blur on image$?, with angle $3° and amplitudes ($1,$2)."
  -v -
  -if {isval($1)} std1=$1 -else std1={(${1}10000)*max(w,h)/100} -endif
  -if {isval($2)} std2=$2 -else std2={(${2}10000)*max(w,h)/100} -endif
  stdM={round(1.25*max($std1,$std2))}
  -if {$stdM<=0} -return -endif
  -repeat @# -l[$>]
    -expand_xy $stdM,{$4!=0}
    {2*$stdM},{2*$stdM} -gaussian[-1] $1,$2,$3 -normalize_sum[-1]
    -convolve_fft -shrink_xy $stdM
  -endl -done -v +

#@gmic blur_radial : amplitude[%],_cx,_cy
#@gmic : Apply radial blur on selected images.
#@gmic : Default values: 'cx=cy=0.5'.
#@gmic : $ image.jpg --blur_radial 2%
blur_radial : -skip ${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_selective : sigma>=0,_edges>0,_nb_scales>0
#@gmic : Blur selected images using selective gaussian scales.
#@gmic : Default values: 'sigma=5', 'edges=0.5' and 'nb_scales=5'.
#@gmic : $ image.jpg -noise 20 -cut 0,255 --l[-1] -repeat 4 -blur_selective , -done -endl
blur_selective : -check "${1=5}>=0 && ${2=0.5}>=0 && isint(${3=5}) && $3>0"
  -e[^-1] "Blur image$? using $3 selective gaussian scales, with sigma $1 and edges $2."
  -v - -repeat @# -l[$>] nm=@{0,n}
    --gradient_norm -+[-1] 1 -^[-1] {-max(0.01,$2)} -quantize[-1] {$3+1},0 -min[-1] {$3-1} -r[-1] [-2] -/[-1] 100
    -repeat $3 --==[-1] {$>/100} -*[-1] [-3] -+[-2,-1] -b[-2] {$1/($3+1)} -done
  -rm[-2] -nm $nm,1 -endl -done -v +

#@gmic blur_x : amplitude[%]>=0,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Blur selected images along the X-axis.
#@gmic : Default value: 'boundary=1'.
#@gmic : $ image.jpg --blur_x 6
blur_x : -skip ${2=1}
  -e[^-1] "Blur image$? along the x-axis, with sigma $1 and "@{"s0=dirichlet s1=neumann -u ${s{$2!=0}}"}" boundary conditions."
  -v - -deriche $1,0,x,$2 -v +

#@gmic blur_xy : amplitude_x[%],amplitude_y[%],_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Blur selected images along the X and Y axes.
#@gmic : Default value: 'boundary=1'.
#@gmic : $ image.jpg --blur_xy 6
blur_xy : -skip ${2=$1},${3=1}
  -e[^-1] "Blur image$? along the xy-axes, with sigma $1 and "@{"s0=dirichlet s1=neumann -u ${s{$2!=0}}"}" boundary conditions."
  -v - -deriche $1,0,x,$3 -deriche $2,0,y,$3 -v +

#@gmic blur_xyz : amplitude_x[%],amplitude_y[%],amplitude_z,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Blur selected images along the X, Y and Z axes.
#@gmic : Default value: 'boundary=1'.
blur_xyz : -skip ${4=1}
  -e[^-1] "Blur image$? along the xyz-axes, with sigma $1 and "@{"s0=dirichlet s1=neumann -u ${s{$2!=0}}"}" boundary conditions."
  -v - -deriche $1,0,x,$4 -deriche $2,0,y,$4 -deriche $3,0,z,$4 -v +

#@gmic blur_y : amplitude[%]>=0,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Blur selected images along the Y-axis.
#@gmic : Default value: 'boundary=1'.
#@gmic : $ image.jpg --blur_y 6
blur_y : -skip ${2=1}
  -e[^-1] "Blur image$? along the y-axis, with sigma $1 and "@{"s0=dirichlet s1=neumann -u ${s{$2!=0}}"}" boundary conditions."
  -v - -deriche $1,0,y,$2 -v +

#@gmic blur_z : amplitude[%]>=0,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Blur selected images along the Z-axis.
#@gmic : Default value: 'boundary=1'.
blur_z : -skip ${2=1}
  -e[^-1] "Blur image$? along the z-axis, with sigma $1 and "@{"s0=dirichlet s1=neumann -u ${s{$2!=0}}"}" boundary conditions."
  -v - -deriche $1,0,z,$2 -v +

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

#@gmic convolve : [mask],_boundary,_is_normalized={ 0 | 1 } : (+)
#@gmic : Convolve selected images by specified mask.
#@gmic : 'boundary' can be { 0=dirichlet | 1=neumann }.
#@gmic : Default values: 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg (0,1,0;1,-4,1;0,1,0) -convolve[-2] [-1] -keep[-2]
#@gmic : $ image.jpg (0,1,0) -resize[-1] 130,1,1,1,3 --convolve[0] [1]

#@gmic convolve_fft
#@gmic : Convolve selected images two-by-two through fourier transforms.
#@gmic : $ image.jpg 100%,100% -gaussian[-1] 20,1,45 --convolve_fft
convolve_fft :
  -e[^-1] "Convolve image$? two-by-two through fourier transforms."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    w2={int(@{0,w}/2)} h2={int(@{0,h}/2)} d2={int(@{0,d}/2)}
    -r[1] [0],[0],[0],1,0,0,0.5,0.5,0.5,0.5 -shift[1] -$w2,-$h2,-$d2,0,2
    -fft[0] -fft[2]
    --*[-4] [-1] --*[-4] [-3] -+[-2,-1]
    -*[-5,-3] -*[-3,-2] --[-3,-2]
    -ifft -rm[-1]
  -endl -done -v +

#@gmic correlate : [mask],_boundary,_is_normalized={ 0 | 1 } : (+)
#@gmic : Correlate selected images by specified mask.
#@gmic : 'boundary' can be { 0=dirichlet | 1=neumann }.
#@gmic : Default values: 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg (0,1,0;1,-4,1;0,1,0) -correlate[-2] [-1] -keep[-2]
#@gmic : $ image.jpg --crop 40%,40%,60%,60% --correlate[0] [-1],0,1

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

#@gmic curvature
#@gmic : Compute isophote curvatures on selected images.
#@gmic : $ image.jpg -blur 10 -curvature
curvature :
  -e[^-1] "Compute isophote curvatures on image$?."
  -v - -repeat @# -l[$>]
    -if {d==1}
      --g 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 -^[-1] 1.5 -/                      # (iy^2ixx+2ixiyixy+ix^2iyy)/(ix^2+iy^2)
    -else
      --inn --gradient_norm[-2] -laplacian[-3]                # inn+iee inn in
      --[-3,-2] -+[-1] 0.1 -/[-2,-1]                          # iee in
      --inn[-1] -laplacian[-2] --                             # iee/in
    -endif
  -endl -done -v +

#@gmic deinterlace : _method={ 0 | 1 }
#@gmic : Deinterlace selected images ('method' can be { 0=standard or 1=motion-compensated }).
#@gmic : Default value: 'method=0'.
#@gmic : $ image.jpg --rotate 3,1,1,50%,50% -resize 100%,50% -resize 100%,200%,1,3,4 -shift[-1] 0,1 -add --deinterlace 1
deinterlace : -skip ${1=0}
  -e[^-1] "Deinterlace image$? with "@{"s0=standard s1=motion-compensated -u ${s{$1!=0}}"}" method."
  -v - -repeat @# -l[$>]
    wh={w},{h}
    -s y -a[0--1:2] y -a[^0] y -r[-2] [-1],0 -r 100%,200%,1,100%,5
    -if {$1!=0} --displacement[-1] [-2],0.05 -warp[-3] [-1],1,1,1 -rm[-1] -endif
    -+ -/ 2 -c 0,255 -r $wh
  -endl -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)} -l[$>,{$>+1}]
    w2={int(@{0,w}/2)} h2={int(@{0,h}/2)} d2={int(@{0,d}/2)}
    -r[1] [0],[0],[0],1,0,0,0.5,0.5,0.5,0.5 -shift[1] -$w2,-$h2,-$d2,0,2
    -fft[0] -fft[1]                            # a b a' b'
    --sqr[-2] --sqr[-2] -+[-2,-1] -+[-1] 1e-5  # a b a' b' (a'^2+b'^2)
    --*[-4] [-3]                               # a b a' b' (a'^2+b'^2) ba'
    --*[-6] [-3]                               # a b a' b' (a'^2+b'^2) ba' ab'
    --[-2,-1]                                  # a b a' b' (a'^2+b'^2) ba'-ab'
    -*[-6,-4]                                  # aa' b b' (a'^2+b'^2) ba'-ab'
    -*[-4,-3]                                  # aa' bb' (a'^2+b'^2) ba'-ab'
    -+[-4,-3]                                  # aa'+bb' (a'^2+b'^2) ba'-ab'
    -/[-1] [-2] -/[-3,-2]                      # divide (aa'+bb') and (ba'-ab') by (a'^2+b'^2)
    -ifft -rm[-1]
  -endl -done -v +

#@gmic denoise : std_variation_s>=0,_std_variation_p>=0,_patch_size>=0,_lookup_size>=0,_smoothness,_fast_approx={ 0 | 1 } : (+)
#@gmic : Denoise selected images by non-local patch averaging.
#@gmic : Default values: 'std_variation_p=10', 'patch_size=5', 'lookup_size=6' and 'smoothness=1'.
#@gmic : $ image.jpg --denoise 5,5,8

#@gmic denoise_haar : _threshold>=0,_nb_scales>=0,_cycle_spinning>0
#@gmic : Denoise selected image using haar-wavelet thresholding with cycle spinning.
#@gmic : Set 'nb_scales==0' to automatically determine the optimal number of scales.
#@gmic : Default values: 'threshold=1.4', 'nb_scale=0' and 'cycle_spinning=10'.
#@gmic : $ image.jpg -noise 20 -c 0,255 --denoise_haar[-1] 0.8
denoise_haar : -check "${1=1.4}>=0 && isint(${2=0}) && $2>=0 && isint(${3=10}) && $3>0"
  -e[^-1] "Denoise image$? using haar-wavelet thresholding, with threshold $1, "\
          @{"-if $2 -u $2 -else -u auto -endif"}" scales and $3 spinning cycles."
  -v - -repeat @# -l[$>] nm=@{0,n}
    nb_scales={min(if($2,$2,32),int(log2(min(w,h))-1))}
    w={w} h={h} d={d} sigma=@{-variance_noise}
    -r {round(w,2^($nb_scales+1),1)},{round(h,2^($nb_scales+1),1)},{if(d==1,1,round(d,2^($nb_scales+1),1))},100%,0,0
    --f 0
    -repeat $3
      dx={round(?(0,{4*$nb_scales}))}
      dy={round(?(0,{4*$nb_scales}))}
      dz={if($d==1,0,round(?(0,{4*$nb_scales})))}
      --shift[0] $dx,$dy,$dz,0,2
      -haar[-1] $nb_scales
      -threshold[-1] {$1*$sigma},1
      -ihaar[-1] $nb_scales
      -shift[-1] {-$dx},{-$dy},{-$dz},0,2
      -+[-2,-1]
    -done
    -rm[0] -/ $3 -r $w,$h,$d,100%,0
  -nm $nm,1 -endl -done -v +

#@gmic deriche : std_variation>=0[%],order={ 0 | 1 | 2 },axis={ x | y | z | c },_boundary : (+)
#@gmic : Apply Deriche recursive filter with specified standard deviation, order, axis and border
#@gmic : conditions on selected images.
#@gmic : 'boundary' can be { 0=dirichlet | 1=neumann }.
#@gmic : Default value: 'boundary=1'.
#@gmic : $ image.jpg --deriche 3,1,x
#@gmic : $ image.jpg --deriche 30,0,x -deriche[-2] 30,0,y -add

#@gmic dilate : size>=0 : size_x>=0,size_y>=0,size_z>=0 : [mask],_boundary,_is_normalized={ 0 | 1 } : (+)
#@gmic : Dilate selected images by a rectangular or the specified structuring element.
#@gmic : 'boundary' can be { 0=dirichlet | 1=neumann }.
#@gmic : Default values: 'size_z=1', 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg --dilate 10

#@gmic dilate_circ : _size>=0,_boundary,_is_normalized={ 0 | 1 }
#@gmic : Apply circular dilation of selected image by specified size.
#@gmic : Default values: 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg --dilate_circ 7
dilate_circ : -check $1>=0 -skip ${2=1},${3=0}
  -e[^-1] "Apply circular dilation of image$? by size $1, boundary $2 and is_normalized $3."
  -v -
  -if {$1<2} -return -endif
  -_jf_circle[] $1 -dilate[^-1] [-1],$2,$3 -rm[-1] -v +

#@gmic dilate_oct : _size>=0,_boundary,_is_normalized={ 0 | 1 }
#@gmic : Apply octagonal dilation of selected image by specified size.
#@gmic : Default values: 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg --dilate_oct 7
dilate_oct : -check $1>=0 -skip ${2=1},${3=0}
  -e[^-1] "Apply octagonal dilation of image$? by size $1, boundary $2 and is_normalized $3."
  -v -
  -if {$1<2} -return -endif
  -if {$1&1} ss={$1} -else ss={$1+1} -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}
    r={round(($ss-1)*sqrt(2)/(1+sqrt(2))/2)}
    q={round(($ss-1)/(1+sqrt(2))/2)}
    -if {$r>0} -repeat $r -dilate[-1] [0],$2,$3 -done -endif
    -if {$q>0} -repeat $q -dilate[-1] [1],$2,$3 -done -endif
  -mv[-1] 2 -done -rm[0,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}

_jf_circle :
  {round($1)},{round($1)}
  center={0.5*(w-1)}
  -f[-1] 'sqrt((x-$center)^2+(y-$center)^2)'
  -if {!(w%2)}
    -round[-1] 0.0001,-1
    t1={sqrt(((round($1)-1)/2)^2+0.25)}
    t2={sqrt(((round($1)+1)/2)^2+0.25)}
    k={$1-round($1)+0.5}
    t={$t1+($t2-$t1)*$k}
    -t2[-1] 0,$t
  -else -t2[-1] 0,{$1/2-0.25}
  -endif

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

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

#@gmic diffusiontensors : _sharpness>=0,0<=_anisotropy<=1,_alpha[%],_sigma[%],is_sqrt={ 0 | 1 }
#@gmic : Compute the diffusion tensors of selected images for edge-preserving smoothing algorithms.
#@gmic : Default values: 'sharpness=0.7', 'anisotropy=0.3', 'alpha=0.6', 'sigma=1.1' and 'is_sqrt=0'.
#@gmic : $ image.jpg -diffusiontensors 0.8 -abs -pow 0.2
diffusiontensors : -check "${1=0.7}>=0 && ${2=0.3}>=0 && $2<=1" -skip ${3=0.6},${4=1.1},${5=0}
  -e[^-1] "Compute diffusion tensors for image$?, with sharpness $1, anisotropy $2, alpha $3 and sigma $4."
  -v -
  p1={if($5,0.5,1)*max($1,1e-5)}
  p2={$p1/(1e-7+1-$2)}
  -b $3 -n 0,255 -structuretensors 2 -b $4
  -repeat @# -l[$>]
    -eigen -max[-2] 0
    -if {s==2} -s[-2] c -+[-3,-2] -+[-2] 1 --^[-2] -$p1 -^[-3] -$p2 -a[-3,-1] c                     # 2d
    -else -s[-2] c -+[-4--2] -+[-2] 1 --^[-2] -$p1 -r[-1] 100%,100%,100%,2 -^[-3] -$p2 -a[-3,-1] c  # 3d
    -endif
    -eigen2tensor
  -endl -done -v +

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

#@gmic eikonal : nb_iterations>=0,_band_size>=0 : (+)
#@gmic : Compute iterations of the eikonal equation (signed distance function) on selected images.
#@gmic : When 'band_size==0', the algorithm performs on all image pixels.
#@gmic : Default value: 'band_size=0'.
#@gmic : $ image.jpg -blur 3 -threshold 50% -eikonal 40

#@gmic erode : size>=0 : size_x>=0,size_y>=0,_size_z>=0 : [mask],_boundary,_is_normalized={ 0 | 1 } : (+)
#@gmic : Erode selected images by a rectangular or the specified structuring element.
#@gmic : boundary' can be { 0=dirichlet | 1=neumann }.
#@gmic : Default values: 'size_z=1', 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg --erode 10

#@gmic erode_circ : _size>=0,_boundary,_is_normalized={ 0 | 1 }
#@gmic : Apply circular erosion of selected images by specified size.
#@gmic : Default values: 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg --erode_circ 7
erode_circ : -check $1>=0 -skip ${2=1},${3=0}
  -e[^-1] "Apply circular erosion of image$? by size $1, boundary $2 and is_normalized $3."
  -v -
  -if {$1<2} -return -endif
  -_jf_circle[] $1 -erode[^-1] [-1],$2,$3 -rm[-1] -v +

#@gmic erode_oct : _size>=0,_boundary,_is_normalized={ 0 | 1 }
#@gmic : Apply octagonal erosion of selected images by specified size.
#@gmic : Default values: 'boundary=1' and 'is_normalized=0'.
#@gmic : $ image.jpg --erode_oct 7
erode_oct : -check $1>=0 -skip ${2=1},${3=0}
  -e[^-1] "Apply octagonal erosion of image$? by size $1, boundary $2 and is_normalized $3."
  -v -
  -if {$1<2} -return -endif
  -if {$1&1} ss={$1} -else ss={$1+1} -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}
    r={round(($ss-1)*sqrt(2)/(1+sqrt(2))/2)}
    q={round(($ss-1)/(1+sqrt(2))/2)}
    -if {$r>0} -repeat $r -erode[-1] [0],$2,$3 -done -endif
    -if {$q>0} -repeat $q -erode[-1] [1],$2,$3 -done -endif
  -mv[-1] 2 -done -rm[0,1] -v +

#@gmic fft : (+)
#@gmic : Compute the direct fourier transform (real and imaginary parts) of selected images.
#@gmic : $ image.jpg -luminance --fft -append[-2,-1] c -norm[-1] -log[-1] -shift[-1] 50%,50%,0,0,2
#@gmic : $ image.jpg -fft -shift 50%,50%,0,0,2 -ellipse 50%,50%,30,30,0,1,0 -shift -50%,-50%,0,0,2 -ifft -remove[-1]

#@gmic g : eq. to '-gradient'. : (+)

#@gmic gradient : { x | y | z }..{ x | y | z },_scheme : (no args) : (+)
#@gmic : Compute the gradient components (first derivatives) of selected images.
#@gmic : (eq. to '-g').
#@gmic : 'scheme' can be { -1=backward | 0=centered | 1=forward | 2=sobel | 3=rotation-invariant (default) | 4=recursive }.
#@gmic : (no args) compute all significant 2d/3d components.
#@gmic : Default value: 'scheme=3'.
#@gmic : $ image.jpg -gradient

#@gmic gradient_orientation : _dimension={1,2,3}
#@gmic : Compute N-d gradient orientation of selected images.
#@gmic : Default value: 'dimension=3'.
#@gmic : $ image.jpg --gradient_orientation 2
gradient_orientation : -check "${1=3}==1 || $1==2 || $1==3"
  -e[^-1] "Compute $1-d gradient orientation of image$?."
  -v - -repeat @# -l[$<]
    -if {$1==1} -g x --abs[-1] -+[-1] 1e-8 -/
    -elif {$1==2} -g xy --sqr -+[-2,-1] -+[-1] 1e-8 -sqrt[-1] -/[-3] [-1] -/[-2,-1]
    -else -g xyz --sqr -+[-3--1] -+[-1] 1e-8 -sqrt[-1] -/[-4,-3] [-1] -/[-2,-1]
    -endif
  -endl -done -v +

#@gmic gradient_norm
#@gmic : Compute gradient norm of selected images.
#@gmic : $ image.jpg --gradient_norm -equalize[-1] 256
gradient_norm :
  -e[^-1] "Compute gradient norm of image$?."
  -v - -repeat @# -l[$>]
    --g x -sqr[-1]
    --g[-2] y -sqr[-1] -+[-2,-1]
    -g[-2] z -sqr[-2] -+[-2,-1]
    s={s} -s[-1] c -+[-$s--1] -sqrt[-1]
  -endl -done -v +

#@gmic haar : scale>0 : (+)
#@gmic : Compute the direct haar multiscale wavelet transform of selected images.

#@gmic heat_flow : _nb_iter>=0,_dt,_keep_sequence={ 0 | 1 }
#@gmic : Apply iterations of the heat flow on selected images.
#@gmic : Default values: 'nb_iter=10', 'dt=30' and 'keep_sequence=0'.
#@gmic : $ image.jpg --heat_flow 20
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 hessian : { xx | xy | xz | yy | yz | zz }..{ xx | xy | xz | yy | yz | zz } : (no args) : (+)
#@gmic : Compute the hessian components (second derivatives) of selected images.
#@gmic : (no args) compute all significant components.
#@gmic : $ image.jpg -hessian

#@gmic iee
#@gmic : Compute gradient-orthogonal-directed 2nd derivative of image(s).
#@gmic : $ image.jpg -iee
iee :
  -e[^-1] "Compute gradient-orthogonal-directed 2nd derivative of image$?."
  -v - -repeat @# -l[$>]
    -if {d==1}
      --g 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 -/             # (iy^2ixx+2ixiyixy+ix^2iyy)/(ix^2+iy^2)
    -else
      --inn -laplacian[-2] --
    -endif
  -endl -done -v +

#@gmic ifft : (+)
#@gmic : Compute the inverse fourier transform (real and imaginary parts) of selected images.

#@gmic ihaar : scale>0 : (+)
#@gmic : Compute the inverse haar multiscale wavelet transform of selected images.

#@gmic inn
#@gmic : Compute gradient-directed 2nd derivative of image(s).
#@gmic : $ image.jpg -inn
inn :
  -e[^-1] "Compute gradient-directed 2nd derivative of image$?."
  -v - -repeat @# -l[$>]
    -if {d==1}
      --g 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 -/             # (ix^2ixx+2ixiyixy+iy^2iyy)/(ix^2+iy^2)
    -else
      --g 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 -/                                # (ix^2ixx+2ixiyixy+2ixizixy+iy^2iyy+2iyiziyz+iz^2izz)/(ix^2+iy^2+iz^2)
    -endif
  -endl -done -v +

#@gmic inpaint : [mask] : (+)
#@gmic : Inpaint selected images by specified mask.
#@gmic : $ image.jpg 100%,100% -ellipse 50%,50%,30,30,0,1,255 -ellipse 20%,20%,30,10,0,1,255 --inpaint[-2] [-1] -remove[-2]

#@gmic inpaint_flow : _nb_iter1>=0,_nb_iter2>=0,_dt>=0,_alpha,_sigma
#@gmic : Apply iteration of the inpainting flow on selected images.
#@gmic : Default values: 'nb_iter1=4', 'nb_iter2=15', 'dt=15', 'alpha=1' and 'sigma=3'.
#@gmic : $ image.jpg 100%,100% -ellipse[-1] 30%,30%,40,30,0,1,255 -reverse -inpaint_flow ,
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 --diffusiontensors[1] 0,1,$4,$5,0 -*[2] [0] -smooth[1] [2],$2,$3,0 -rm[2] -done
  -endl -endif -done -v +

#@gmic kuwahara : size>0
#@gmic : Apply Kuwahara filter of specified size on selected images.
#@gmic : $ image.jpg --kuwahara 5
kuwahara : -check $1>0
  -e[^-1] "Apply Kuwahara filter of size $1 on image$?."
  -v - -repeat @# -l[$>]
    s={s}
    --dilate $1 -compose_channels[-1] min
    --erode[0] $1 -compose_channels[-1] max
    --[-2,-1]
    $1,1,1,1,{1/$1} -convolve[0] [-1] -transpose[-1] -convolve[0] [-1] -rm[-1]
    p={int($1/2)}
    -a[-2,-1] c
    -f "v1=i(x-"$p",y-"$p",0,"$s",0,1); \
        v2=i(x+"$p",y-"$p",0,"$s",0,1); \
        v3=i(x-"$p",y+"$p",0,"$s",0,1); \
        v4=i(x+"$p",y+"$p",0,"$s",0,1); \
        vm=min(v1,v2,v3,v4); \
        if(c>="$s",i, \
          if(vm==v1,i(x-"$p",y-"$p",0,c,0,1),
            if(vm==v2,i(x+"$p",y-"$p",0,c,0,1),
              if(vm==v3,i(x-"$p",y+"$p",0,c,0,1),
                i(x+"$p",y+"$p",0,c,0,1)))))"
    -channels 0,{s-2}
  -endl -done -v +

#@gmic laplacian
#@gmic : Compute Laplacian of selected images.
#@gmic : $ image.jpg -laplacian
laplacian :
  -e[^-1] "Compute Laplacian of image $?."
  -v - -repeat @# -l[$>]
    -hessian @{"-if {d==1} -u xxyy -else -u xxyyzz -endif"} -+
  -endl -done -v +

#@gmic lic : _amplitude>0,_channels>0
#@gmic : Render LIC representation of selected vector fields.
#@gmic : Default values: 'amplitude=30' and 'channels=1'.
#@gmic : $ 400,400,1,2,'if(c==0,x-w/2,y-h/2)' --lic 200,3 -quiver[-2] [-2],10,-13,1,1,255
lic : -skip ${1=30},${2=1}
  -e[^-1] "Render LIC representation of 2d vector field$?, with amplitude $1 and $2 channel(s)."
  -v - -repeat @# -l[$>] nm=@{0,n}
     -channels 0,1 -/ {max(abs(@{-1,m}),abs(@{-1,M}))} -vector2tensor
     100%,100%,100%,$2 -rand[-1] 0,255 -smooth[-1] [-2],$1 -rm[-2]
     -equalize 256
  -nm $nm,1 -endl -done -v +

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

    # Estimate target divergence for each channel.
    --l -s c -repeat @# -l[$>]
      -g xy,1 -a c --norm -orientation[-2]
      m={im} M={iM} -b[-1] $3 -n[-1] $m,$M
      -*[-1] 'alpha=$1*iM;(alpha/(1e-10+i))*(i/(1e-10+alpha))^$2'
      -* -s c -g[-2] x,-1 -g[-1] y,-1 -+
    -endl -done -a c -* 0.25 -endl

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

  -endl -done  -v +

#@gmic map_tones_fast : _radius[%]>=0,_power>=0
#@gmic : Apply fast tone mapping operator on selected images.
#@gmic : Default values: 'radius=3%' and 'power=0.3'.
#@gmic : $ image.jpg --map_tones_fast ,
map_tones_fast : -check "${1=3%}>=0 && ${2=0.3}>=0"
  -e[^-1] "Apply fast tone mapping operator on image$?, with radius $1 and power $2."
  -v - -repeat @# -l[$>]
    --luminance -b[-1] $1 -n 0,1
    --*[-1] 2 --[-1] 1 -abs[-1] -*[-1] {$2*log(10)} -exp[-1]
    -le[-2] 0.5 -r[-1] [-3]
    --*[-3] -1 -+[-1] 1 -^[-1] [-2] -*[-1] -1 -+[-1] 1 -*[-1] [-3]
    -^[-4,-2] -eq[-2] 0 -*[-3,-2] -+
  -endl -done -n 0,255 -v +

#@gmic meancurvature_flow : _nb_iter>=0,_dt,_sequence_flag={ 0 | 1 }
#@gmic : Apply iterations of the mean curvature flow on selected images.
#@gmic : Default values: 'nb_iter=10', 'dt=30' and 'keep_sequence=0'.
#@gmic : $ image.jpg --meancurvature_flow 20
meancurvature_flow : -skip ${1=10},${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 median : radius>=0 : (+)
#@gmic : Apply median filter of specified radius on selected images.
#@gmic : $ image.jpg --median 5

#@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.
#@gmic : Default values: 'amplitude=3', 'radius=16', 'n_smooth=4%', 'a_smooth=2%', 'is_cut=1', 'min=0' and 'max=255'.
#@gmic : $ image.jpg --normalize_local 8,10
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[$>]
    --l -erode {2*$2+1} -s c -min -endl
    --l[-2] -dilate {2*$2+1} -s c -max -endl
    --b[-3] $4 -b[-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] -+
    -if $5 -c $6,$7 -endif
  -endl -done -v +

#@gmic normalized_cross_correlation
#@gmic : Compute normalized cross-correlation using two-by-two selected images.
#@gmic : $ image.jpg --shift -30,-20 -normalized_cross_correlation
normalized_cross_correlation :
  -e[^-1] "Compute normalized cross-correlation using two-by-two image$?."
  -v - -norm -repeat {int(@#/2)} -l[$>,{$>+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 -rm[-1]
  -endl -done -v +

#@gmic phase_correlation
#@gmic : Estimate translation vector using two-by-two selected images.
#@gmic : $ image.jpg --shift -30,-20 --phase_correlation -unroll[-1] y
phase_correlation :
  -e[^-1] "Estimate translation vector using two-by-two image$?."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -normalized_cross_correlation
    (@{-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 -rm[-2] -/ 2 -* -1
    -nm [phase\ correlation]
  -endl -done -v +

#@gmic pde_flow : _nb_iter>=0,_dt,_velocity_command,_keep_sequence={ 0 | 1 }
#@gmic : Apply iterations of a generic PDE flow on selected images.
#@gmic : Default values: 'nb_iter=10', 'dt=30', 'velocity_command=laplacian' and 'keep_sequence=0'.
#@gmic : $ image.jpg --pde_flow 20
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[$<]
    -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 -done
  -if $4 -s x,$1 -endif -v +

#@gmic red_eye : 0<=_threshold<=100,_smoothness>=0,0<=attenuation<=1
#@gmic : Attenuate red-eye effect in selected images.
#@gmic : Default values: 'threshold=75', 'smoothness=3.5' and 'attenuation=0.1'.
#@gmic : $ image.jpg --red_eye ,
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 @# -l[$>]
    -s c --[-1] 128 --ge[-1] $1% -b[-1] $2 -sqrt[-1] -*[-1] -1 -+[-1] 1
    -n[-1] $3,1 -*[-2,-1] -+[-1] 128 -a c -ycbcr2rgb
  -endl -done -v +

#@gmic remove_hotpixels : _mask_size>0, _threshold[%]>0
#@gmic : Remove hot pixels in selected images.
#@gmic : Default values: 'mask_size=3' and 'threshold=10%'.
#@gmic : $ image.jpg -noise 10,2 --remove_hotpixels ,
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 @# -l[$>]
    --median $1 --- -abs[-1] -ge[-1] $2
    -*[-2] [-1] -==[-1] 0 -*[-3,-1] -+
  -endl -done -v +

#@gmic remove_pixels : density>=0,_pixel_sum>=0
#@gmic : Remove (i.e. set to 0) specified density (in percent) of non-zero pixels to 0.
#@gmic : Specified density is regarded against 'pixel_sum' except if it is set to '0'
#@gmic : (in this case, 'pixel_sum' has default value 'width*height').
#@gmic : Default value: 'density=10', 'pixel_sum=0'.
#@gmic : $ image.jpg --remove_pixels 50
remove_pixels : -check "${1=10}>=0 && ${2=0}>=0"
  -e[^-1] "Remove $1% of non-zero pixels of image$?."
  -v - -repeat @# -l[$>]
    --norm -gt[-1] 0
    -if $2 rate={$1*$2/max(1e-8,@{-1,+})}
    -else rate={$1*w*h/max(1e-8,@{-1,+})}
    -endif
    -rm[-1]
    100%,100% -rand[-1] 0,1 -ge[-1] $rate% -*
  -endl -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.
#@gmic : Default values: 'nb_iter=10', 'dt=20', 'regul=0.7' and 'regul_type=1'.
#@gmic : $ image.jpg -blur 3 --richardson_lucy 3,40,20,0.01
richardson_lucy : -check "${2=10}>=0 && ${3=20}>=0 && ${4=0.7}>=0" -skip ${5=1}
  -e[^-1] "Deconvolve image$? with the Richardson-Lucy algorithm, with sigma $1, $2 iterations, time step $3 and regularization $4."
  -v - -repeat @# -l[$>] nm=@{0,n}
    [0]
    -repeat $2
      -if {$5>=2} --curvature[-1]                         # TV regularization.
      -elif {$5>=1} --iee[-1]                             # Meancurv. regularization.
      -else --laplacian[-1]                               # Tikhonov regularization.
      -endif
      -*[-1] $4
      --b[-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]
  -nm $nm,1 -endl -done -v +

#@gmic sharpen : amplitude>=0 : amplitude>=0,edge>=0,_alpha,_sigma : (+)
#@gmic : Sharpen selected images by inverse diffusion or shock filters methods.
#@gmic : 'edge' must be specified to enable shock-filter method.
#@gmic : Default values: 'alpha=0' and 'sigma=0'.
#@gmic : $ image.jpg --sharpen 300
#@gmic : $ image.jpg -blur 5 --sharpen[-1] 300,1

#@gmic smooth : amplitude>=0,_sharpness>=0,_anisotropy,_alpha,_sigma,_dl>0,_da>0,_precision>0,interpolation,_fast_approx={ 0 | 1 } : nb_iterations>=0,_sharpness>=0,_anisotropy,_alpha,_sigma,_dt>0,0 : [tensor_field],_amplitude>=0,_dl>0,_da>0,_precision>0,_interpolation,_fast_approx={ 0 | 1 } : [tensor_field],_nb_iters>=0,_dt>0,0 : (+)
#@gmic : Smooth selected images anisotropically using diffusion PDE's, with specified field of
#@gmic : diffusion tensors.
#@gmic : 'anisotropy' must be in [0,1].
#@gmic : 'interpolation' can be { 0=nearest | 1=linear | 2=runge-kutta }.
#@gmic : Default values: 'sharpness=0.7', 'anisotropy=0.3', 'alpha=0.6', 'sigma=1.1', 'dl=0.8', 'da=30', 'precision=2', 'interpolation=0' and 'fast_approx=1'.
#@gmic : $ image.jpg [0] -repeat 3 -smooth[-1] 20 -done
#@gmic : $ image.jpg 100%,100%,1,2 -rand[-1] -100,100 -repeat 2 -smooth[-1] 100,0.2,1,4,4 -done --warp[0] [-1],1,1

#@gmic split_freq : smoothness>0[%]
#@gmic : Split selected images into low and high frequency parts.
#@gmic : $ image.jpg -split_freq 2%
split_freq :
  -e[^-1] "Split image$? into low and high frequency parts, with smoothness $1."
  -v - -repeat @# -l[$>] --b $1 --[0] [1] -rv -endl -done -v +

#@gmic solidify
#@gmic : Replace transparent regions of a RGBA image by morphologically interpolated color.
#@gmic : $ image.jpg --luminance -ge[-1] 120 -*[-1] 255 -append c --solidify -display_rgba
solidify :
  -e[^-1] "Replace transparent regions of RGBA image$? by morphologically interpolated colors."
  -v - -repeat @# -l[$>] nm=@{0,n} -to_a
    [-1] -split_opacity[-2] -ge[-2] 50% -*[-1] [-2]
    -replace_color[-1] 0,0,0,0,0,0,-1,-1,-1,-1 -to_rgb[-1]
    -do
      --dilate[-1] 3
      -replace_color[-2] 0,0,-1,-1,-1,1000,1000,1000
      -erode[-2] 3
      -replace_color[-2] 0,0,1000,1000,1000,-1,-1,-1
      -+[-2,-1] -/[-1] 2
      -j[-1] [-3],0,0,0,0,1,[-2]
    -while {im<0}
    -k[-1]
  -nm $nm,1 -endl -done -v +

#@gmic solidify_linear : _sigma>=1,_dsigma>=1,0<=_precision<=1
#@gmic : Replace transparent regions of a RGBA image by linearly interpolated color.
#@gmic : Default values: 'sigma=1.5', 'dsigma=1' and 'precision=0.5'.
#@gmic : $ image.jpg --luminance -ge[-1] 120 -*[-1] 255 -append c --solidify_linear , -display_rgba
solidify_linear : -check "${1=1.5}>=1 && ${2=1}>=1 && ${3=0.5}>=0 && $3<=1"
  -e[^-1] "Replace transparent regions of RGBA image$? by linearly interpolated colors, with sigma $1, dsigma $2 and precision $3."
  -v - -repeat @# -l[$>]
    -split_opacity
    -if {@#>1}
      -ge[-1] 50% -*[-2] [-1]
      sigma=$1 -do
        N={v=round(3*$sigma);min(33,max(3,v+1-(v%2)))}
        $N,$N -=[-1] 1,50%,50% -distance[-1] 1 -*[-1] {-1/$sigma^2} -exp[-1] -normalize_sum[-1]
        --convolve[-3,-2] [-1] -rm[-3]
        -max[-1] 1e-5 -/[-2,-1]
        --dilate[-2] {v=round((1/3-$N/6)*$3+$N/2);max(3,v+1-(v%2))}
        --[-3] [-1] -*[-2] [-3] -rm[-3]
        --[-3,-2]
        sigma={$sigma*$2}
      -while {!im}
     -rm[-1]
   -endif
 -endl -done -v +

#@gmic structuretensors : _scheme : (+)
#@gmic : Compute the structure tensor field of selected images.
#@gmic : 'scheme' can be { 0=centered | 1=forward-backward1 | 2=forward-backward2 }.
#@gmic : Default value: 'scheme=2'.
#@gmic : $ image.jpg -structuretensors -abs -pow 0.2

#@gmic tv_flow : _nb_iter>=0,_dt,_sequence_flag={ 0 | 1 }
#@gmic : Apply iterations of the total variation flow on selected images.
#@gmic : Default values: 'nb_iter=10', 'dt=30' and 'keep_sequence=0'.
#@gmic : $ image.jpg --tv_flow 40
tv_flow : -skip ${1=10},${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 unsharp : radius[%]>=0,_amount>=0,_threshold[%]>=0
#@gmic : Apply unsharp mask on selected images.
#@gmic : Default values: 'amount=2' and 'threshold=0'.
#@gmic : $ image.jpg -blur 3 --unsharp 1.5,15 -cut 0,255
unsharp : -check "${2=2}>=0" -skip ${3=0}
  -e[^-1] "Apply unsharp mask on image$?, with radius $1, amount $2 and threshold $3."
  -v - -repeat @#
    --b[$>] $1 --[-1] [$>]
    -if $3 --norm[-1] -ge[-1] $3 -*[-2,-1] -endif
    -*[-1] $2 --[$>,-1]
  -done -v +

#@gmic unsharp_octave : _nb_scales>0,_radius[%]>=0,_amount>=0,threshold[%]>=0
#@gmic : Apply octave sharpening on selected images.
#@gmic : Default values: 'nb_scales=4', 'radius=1', 'amount=2' and 'threshold=0'.
#@gmic : $ image.jpg -blur 3 --unsharp_octave 4,5,15 -cut 0,255
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[$>] nm=@{0,n}
    --f 0 weight=0 -repeat $1
      --unsharp[0] {$2*2^-@{<,-1}},$3,$4 -*[-1] {2^-$>} weight={$weight+2^-$>} -+[1,-1]
    -done -rm[0] -/ $weight
  -nm $nm,1 -endl -done -v +

#@gmic watermark_fourier : text,_size>0
#@gmic : Add a textual watermark in the frequency domain of selected images.
#@gmic : Default value: 'size=32'.
#@gmic : $ image.jpg --watermark_fourier "Watermarked!" --display_fft -remove[-3,-1] -normalize 0,255 -append[-4,-2] y -append[-2,-1] y
watermark_fourier : -check ${2=32}>0
  -e[^-1] "Add textual watermark '$1' with size $2 in the frequency domain of image$?."
  -v - -i[0] 0 -t[0] "$1",0,0,$2,1,1 -ge[0] 0.5 -autocrop[0] 0
  -repeat {@#-1} w2={int(w/2)} h2={int(h/2)}
    -fft[-1]
    -shift[-2,-1] $w2,$h2,0,0,2
    [0],[0],1,{s}
    -j[-3,-2] [-1],3,3,0,0,1,[0]
    -mirror[0] x
    -j[-3,-2] [-1],{@{-2,w}-2-@{0,w}},3,0,0,1,[0]
    -mirror[0] y
    -j[-3,-2] [-1],{@{-2,w}-2-@{0,w}},{@{-2,h}-2-@{0,h}},0,0,1,[0]
    -mirror[0] x
    -j[-3,-2] [-1],3,{@{-2,h}-2-@{0,h}},0,0,1,[0]
    -mirror[0] y
    -rm[-1]
    -shift[-2,-1] -$w2,-$h2,0,0,2
    -ifft[-2,-1] -rm[-1]
  -mv[-1] 1 -done
  -rm[0] -v +

#@gmic watershed : [priority_image],_fill_lines={ 0 | 1 } : (+)
#@gmic : Compute the watershed transform of selected images.
#@gmic : Default value: 'fill_lines=1'.
#@gmic : $ 400,400 -noise 0.2,2 --distance 1 -mul[-1] -1 -label[-2] 0 -watershed[-2] [-1] -mod[-2] 256 -map[-2] 0 -reverse

#---------------------------------
#
#@gmic :: Features extraction
#
#---------------------------------

#@gmic area : tolerance>=0,is_high_connectivity={ 0 | 1 }
#@gmic : Compute area of connected components in selected images.
#@gmic : Default values: 'is_high_connectivity=0'.
#@gmic : $ image.jpg -luminance -stencil[-1] 1 --area 0
area : -check "$1>=0" -skip ${2=0}
  -e[^-1] "Compute area of connected components in image$?, with tolerance $1 and "@{"-if $2 -u high -else -u low -endif"}" connectivity."
  -v - -repeat @# -l[$>] -s c
    -repeat @# -label[$>] $1,$2 nb=@{$>,1+iM} --histogram[$>] $nb,0,{$nb-1} -map[$>] [-1] -rm[-1] -done
  -a c -endl -done -v +

#@gmic area_fg : tolerance>=0,is_high_connectivity={ 0 | 1 }
#@gmic : Compute area of connected components for non-zero values in selected images.
#@gmic : Similar to '-area' except that 0-valued pixels are not considered.
#@gmic : Default values: 'is_high_connectivity=0'.
#@gmic : $ image.jpg -luminance -stencil[-1] 1 --area_fg 0
area_fg : -check "$1>=0" -skip ${2=0}
  -e[^-1] "Compute area of foreground connected components in image$?, with tolerance $1 and "@{"-if $2 -u high -else -u low -endif"}" connectivity."
  -v - -repeat @# -l[$>] -s c
    -repeat @# -label_fg[$>] $1,$2 nb=@{$>,1+iM} --histogram[$>] $nb,0,{$nb-1} -=[-1] 0 -map[$>] [-1] -rm[-1] -done
  -a c -endl -done -v +

#@gmic barycenter
#@gmic : Compute the barycenter vector of pixel values.
#@gmic : $ 256,256 -ellipse 50%,50%,20%,20%,0,1,1 -deform 20 --barycenter --ellipse[-2] @{-1,0,1},5,5,0,10
barycenter :
  -e[^-1] "Compute the barycenter vector of pixel values of image$?."
  -v - -norm -repeat @# -l[$>] nm=@{0,b}
    sum=@{-1,+}
    -if {$sum>0}
      -if {d>1} --* 'z' z=@{-1,+} -rm[-1] -else z=0 -endif
      -if {h>1} --* 'y' y=@{-1,+} -rm[-1] -else y=0 -endif
      -* 'x' x=@{-1,+} -rm[-1]
      ({$x/$sum};{$y/$sum};{$z/$sum})
    -else ({w/2},{h/2},{d/2}) -rm[-2]
    -endif
  -nm "[barycenter of '"$nm"']" -endl -done -v +

#@gmic displacement : [source_image],_smoothness,_precision>=0,_nb_scales>=0,iteration_max>=0,is_backward={ 0 | 1 } : (+)
#@gmic : Estimate displacement field between specified source and selected images.
#@gmic : If 'smoothness>=0', regularization type is set to isotropic, else to anisotropic.
#@gmic : If 'nbscales==0', the number of needed scales is estimated from the image size.
#@gmic : Default values: 'smoothness=0.1', 'precision=5', 'nb_scales=0', 'iteration_max=10000' and 'is_backward=1'.
#@gmic : $ image.jpg --rotate 3,0,1,50%,50%,0.9 --displacement[-1] [-2] -quiver[-1] [-1],15,-20,1,1,{1.5*iM}

#@gmic distance : isovalue[%],_metric : isovalue[%],[custom_metric] : x[%]>=0,y[%]>=0,z[%]>=0 : (+)
#@gmic : Compute the unsigned distance function to specified isovalue or coordinates.
#@gmic : 'metric' can be { 0=chebyshev | 1=manhattan | 2=euclidean | 3=squared-euclidean }.
#@gmic : A custom metric for chamfer distances can be specified as a 2d or 3d image.
#@gmic : If arguments 'x','y','z' are provided, the image stands for a potential map used to
#@ŋmic : determine the distance map to specified point (x,y,z).
#@gmic : Default value: 'metric=2'.
#@gmic : $ image.jpg -threshold 20% -distance 0 -pow 0.3
#@gmic : $ 400,400 -set 1,50%,50% --distance[0] 1,2 --distance[0] 1,1 -distance[0] 1,0 -mod 32 -threshold 16 -append c
#@gmic : $ image.jpg -luminance -distance 50%,50%,50%

#@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 @# -l[$>]
    -fftpolar -+[-2] 1 -log[-2] -float2int8[-2,-1] -a y
  -endl -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 @# -l[$>]
    -s y,2 -int82float -exp[-2] --[-2] 1 -ifftpolar
  -endl -done -v +

#@gmic fftpolar
#@gmic : Compute fourier transform of selected images, as centered magnitude/phase images.
#@gmic : $ image.jpg -fftpolar -ellipse 50%,50%,10,10,0,1,0 -ifftpolar
fftpolar :
  -e[^-1] "Compute fourier transform of image$?, as centered magnitude/phase images."
  -v - -repeat @# -l[$<]
    -fft -complex2polar -shift {-int(w/2)},{-int(h/2)},{-int(d/2)},0,2
  -endl -done -v +

#@gmic histogram : nb_levels>0[%],_value0[%],_value1[%] : (+)
#@gmic : Compute the histogram of selected images.
#@gmic : If value range is set, the histogram is estimated only for pixels in the specified
#@gmic : value range. Argument 'value1' must be specified if 'value0' is set.
#@gmic : Default values: 'value0=0%' and 'value1=100%'.
#@gmic : $ image.jpg --histogram 64 -display_graph[-1] 400,300,3

#@gmic histogram_cumul : _nb_levels>0,_is_normalized={ 0 | 1 },_val0[%],_val1[%]
#@gmic : Compute cumulative histogram of selected images.
#@gmic : Default values: 'nb_levels=256', 'is_normalized=0' and 'val0=val1=0'.
#@gmic : $ image.jpg --histogram_cumul 256 -histogram[0] 256 -display_graph 400,300,3
histogram_cumul : -check ${1=256}>0 -skip ${2=0} -skip ${3=0},${4=0}
  -e[^-1] "Compute "@{"s0=\"\" s1=\"normalized \" -u ${s{$2!=0}}"}"cumulative histogram of image$?, using $1 levels."
  -v - -histogram $1,$3,$4 -cumul -if $2 -repeat @# -/[$>] @{$>,M} -done -endif -v +

#@gmic histogram_pointwise : nb_levels>0[%],_value0[%],_value1[%]
#@gmic : Compute the histogram of each vector-valued point of selected images.
#@gmic : If value range is set, the histogram is estimated only for values in the specified
#@gmic : value range.
#@gmic : Default values: 'value0=0%' and 'value1=100%'.
histogram_pointwise : -skip ${2=0%},${3=100%}
  -e[^-1] "Compute the pointwise histogram of vector-valued points in image$?, with $1 levels."
  -v - -repeat @# -l[$>] nm=@{0,n}
    nb_levels={round(if(@{"-is_percent $1"},(iM-im)*$1,$1))}
    value0={if(@{"-is_percent $2"},im+(iM-im)*$2,$2)}
    value1={if(@{"-is_percent $3"},im+(iM-im)*$3,$3)}
    -- $value0 -* {$nb_levels/max(1,abs($value1-$value0))} -c 0,{$nb_levels-1} -round
    w={w} h={h} d={d} -r {w*h*d},{s},1,1,-1
    -i[-2] (0,{w-1}) -r[-2] [-1],[-1],1,1,3 -round[-2]
    -r[-2,-1] 300%,100%,1,1,4 -shift[-1] 1 -+[-2,-1] -y[-1] y
    -i[-2] ({'CImg3d'},{h/3},{h/3})
    (1,0;1,{h/3-1}) -r[-1] 2,@{-2,h/3},1,1,3 -round[-1]
    3,100%,1,1,1 1,100%,1,1,-1 -y[-5,-3,-2] y -a[-5--1] y
    {$w*$h*$d},$nb_levels -object3d[-1] [-2],0,0,0,1,0,0,0 -rm[-2]
    -r $w,$h,$d,$nb_levels,-1
  -nm $nm,1 -endl -done -v +

#@gmic hough : _width>0,_height>0,gradient_norm_voting={ 0 | 1 }
#@gmic : Compute hough transform (theta,rho) of selected images.
#@gmic : Default values: 'width=512', 'height=width' and 'gradient_norm_voting=1'.
#@gmic : $ image.jpg --blur[-1] 1.5 -hough[-1] 400,400 -blur[-1] 0.5 -+[-1] 1 -log[-1]
hough : -check "${1=512}>0 && ${2=$1}>0" -skip ${3=1}
  -e[^-1] "Compute $1x$2 hough transform of image$?, "@{"-if $3 -u with -else -u without -endif"}" gradient norm voting."
  -v - -slices 50% -luminance -repeat @# -l[$>] nm=@{0,n}
    rhomax={sqrt(w^2+h^2)/2}
    -g (0,{w-1}) (0;{@{-2,h}-1}) -r[-2,-1] @{-3,w},@{-3,h},1,1,3 --[-2] {w/2} --[-1] {h/2}
    -complex2polar[-4--1] --[-1] [-3] -polar2complex[-2,-1] -rm[-1]
    --lt[-1] 0 -*[-1] {pi} -+[-3,-1] -abs[-1] -%[-2] {2*pi}
    -*[-1] {$2/$rhomax} -*[-2] {0.5*$1/pi}
    -y[-3--1] x {w} -mv[-4] @# -if {!$3} -f[-1] 1 -endif
    -a y -pointcloud 1 -r $1,$2,1,1,0
  -nm $nm,1 -endl -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)} -l[$>,{$>+1}]
    -shift {int(w/2)},{int(h/2)},{int(d/2)},0,2 -polar2complex -ifft -rm[-1]
  -endl -done -v +

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

#@gmic label : tolerance>=0,is_high_connectivity={ 0 | 1 } : (+)
#@gmic : Label connected components in selected images.
#@gmic : Default values: 'tolerance=0' and 'is_high_connectivity=0'.
#@gmic : $ image.jpg -luminance -threshold 60% -label 0 -normalize 0,255 -map 0
#@gmic : $ 400,400 -set 1,50%,50% -distance 1 -mod 16 -threshold 8 -label 0 -mod 255 -map 2

#@gmic label_fg : tolerance>=0,is_high_connectivity={ 0 | 1 }
#@gmic : Label connected components for non-zero values (foreground) in selected images.
#@gmic : Similar to '-label' except that 0-valued pixels are not labeled.
#@gmic : Default value: 'is_high_connectivity=0'.
label_fg : -check "$1>=0" -skip ${2=0}
  -e[^-1] "Label foreground connected components on image [1], with tolerance $1 and "@{"-if $2 -u high -else -u low -endif"}" connectivity."
  -v - -repeat @# -l[$>]
    -if {d>1} --z -1,-1,-1,{w-1},{h-1},{d-1} -label[-1] $1,$2 -z[-1] 1,1,1,{w-1},{h-1},{d-1}
    -else --z -1,-1,{w-1},{h-1} -label[-1] $1,$2 -z[-1] 1,1,{w-1},{h-1}
    -endif
    -neq[-2] 0 -*
    --histogram {1+iM} -neq[-1] 0 -*[-1] 'x' -rows[-1] -1,0 -label[-1] 0 -rows[-1] 1,1
    -map[-2] [-1] -rm[-1]
  -endl -done -v +

#@gmic max_patch : _patch_size>=1
#@gmic : Return locations of maximal values in local patch-based neighborhood of given size for selected images.
#@gmic : Default value: 'patch_size=16'.
#@gmic : $ image.jpg -norm --max_patch 16
max_patch : -check "isint(${1=16}) && $1>=1"
  -e[^-1] "Return locations of maximal values in local patch neighborhood of size $1, in image$?."
  -v - -repeat @# --dilate[$>] $1 -==[$>,-1] -done -v +

#@gmic min_patch : _patch_size>=1
#@gmic : Return locations of minimal values in local patch-based neighborhood of given size for selected images.
#@gmic : Default value: 'patch_size=16'.
#@gmic : $ image.jpg -norm --min_patch 16
min_patch : -check "isint(${1=16}) && $1>=1"
  -e[^-1] "Return locations of minimal values in local patch neighborhood of size $1, in image$?."
  -v - -repeat @# --erode[$>] $1 -==[$>,-1] -done -v +

#@gmic minimal_path : x0[%]>=0,y0[%]>=0,z0[%]>=0,x1[%]>=0,y1[%]>=0,z1[%]>=0
#@gmic : Compute minimal path between two points on selected potential maps.
#@gmic : $ image.jpg --gradient_norm -f[-1] 1/(1+i) -minimal_path[-1] 0,0,0,100%,100%,0 -pointcloud[-1] 0 -*[-1] 280 -to_rgb[-1] -resize[-1] [-2],0 -or
minimal_path : -check "$1>=0 && $2>=0 && $3>=0"
  -e[^-1] "Compute minimal path between points ($1,$2,$3) and ($4,$5,$6) for potential map$?."
  -v - -repeat @# -l[$>] nm=@{0,n}
    -distance ${4-6}
    x={round(if(@{"-is_percent $1"},$1*(w-1),$1))}
    y={round(if(@{"-is_percent $2"},$2*(h-1),$2))}
    z={round(if(@{"-is_percent $3"},$3*(d-1),$3))}
    ($x;$y;$z)
    -do
      p=@{0,($x,$y,$z,1)}
      -if {$p==1}   x={$x-1}
      -elif {$p==2} x={$x+1}
      -elif {$p==3} y={$y-1}
      -elif {$p==4} y={$y+1}
      -elif {$p==5} z={$z-1}
      -elif {$p==6} z={$z+1}
      -endif
      ($x;$y;$z)
    -while $p
    -rm[0,-1] -a x
  -nm $nm,1 -endl -done -v +

#@gmic plot2value
#@gmic : Retrieve values from selected 2d graph plots.
#@gmic : $ 400,300,1,1,'if(y>300*abs(cos(x/10+2*?)),1,0)' --plot2value --display_graph[-1] 400,300
plot2value :
  -e[^-1] "Retrieve values from 2d graph plot$?."
  -v - -repeat @# -l[$>]
    -s c -ge 50%
    -repeat @# -l[$>] (1,{w}) -r[1] [0],3 -* -histogram {w},1,{w} -endl -done
    -a c
  -endl -done -v +

#@gmic pointcloud : _type = { -X=-X-opacity | 0=binary | 1=cumulative | 2=label }
#@gmic : Convert a Nx1, Nx2, Nx3 or NxM image as a point cloud in a 1d/2d or 3d binary image.
#@gmic : If 'M'>3, the 3-to-M lines sets the (M-3)-dimensional color at each point.
#@gmic : Default value: 'type=0'.
#@gmic : $ 3000,2 -rand 0,400 --pointcloud 0
#@gmic : $ 3000,2 -rand 0,400 {w} {w},3 -rand[-1] 0,255 -append y --pointcloud 0
pointcloud : -skip ${1=0}
  -e[^-1] "Convert image$? to point clouds, in "\
          @{"-if {$1<0} -u \""{-$1}"-opacity\" -elif {$1==0} -u \"binary\" -elif {$1==1} -u \"cumulative\" -else -u \"labeling\" -endif"}\
          " mode."
  -v - -repeat @# -l[$>] nm=@{0,n}
    -if {"d>1 || s>1"} -error "Invalid input image "{w}x{h}x{d}x{s}". Should be NxMx1x1." -endif

    # Retrieve coordinates and color infos.
    -rows 0,{max(2,h-1)}
    -sh[-1] 0,0,0,0 -round[-1] dx={iM+1}
    -sh[-2] 1,1,0,0 -round[-1] dy={iM+1}
    -sh[-3] 2,2,0,0 -round[-1] dz={iM+1}
    -*[-1] $dy -+[-2] [-1] -f[-1] 0 -rm[-3--1]

    # Create corresponding 3d object (manage large point clouds).
    -s x,-1000000
    -repeat @# -l[$>]
      nbp={w}
      -if {h>3} --rows 3,100% -rows[-2] 0,2 -else 100%,1,1,1,1 -if {$1==2} -f[-1] 1+x -endif -endif
      spectrum={h} -i[-2] (-128;1;1;{h}) -r[-2] {w} -a[-2,-1] y
      -i[-3] ({'CImg3d'}) -transpose[-3--1] -i[-3] ($nbp;$nbp) # Header
      -i[-2] 1,$nbp,1,1,1 -i[-2] 1,$nbp,1,1,y -a[-3,-2] x      # Vertices and primitives.
      1,$nbp,1,1,{if($1<0,-$1,if($1==1,-1,1))}                 # Opacities.
      -y[-4--2] y -a y                                         # Merge object attributes.
    -endl -done
    -+3d

    # Draw corresponding point cloud.
    $dx,{$dy*$dz},1,$spectrum -object3d[-1] [-2],0,0,0,1,0,0,0 -rm[-2] -r[-1] $dx,$dy,$dz,100%,-1
  -nm $nm,1 -endl -done -v +

#@gmic psnr : _max_value : (+)
#@gmic : Compute PSNR (Peak Signal-to-Noise Ratio) matrix between selected images.
#@gmic : Default value: 'max_value=255'.
#@gmic : $ image.jpg --noise 30 --noise[0] 35 --noise[0] 38 -cut[-1] 0,255 -psnr 255 -replace_inf 0
psnr : -skip ${1=255}
  -e[^-1] "Compute the "@#x@#" matrix of PSNR values, from image$? with maximum value $1."
  -v - -mse -log10 -- {log10($1*$1)} -* -10 -v +

#@gmic segment_watershed : _threshold>=0,_keep_watershed={ 0 | 1 }
#@gmic : Apply watershed segmentation on selected images.
#@gmic : Default values: 'threshold=2' and 'keep_watershed=1'.
#@gmic : $ image.jpg --segment_watershed 2,0
segment_watershed : -check "${1=2}>=0" -skip ${2=1}
  -e[^-1] "Apply watershed segmentation on image$?, with edge threshold $1."
  -v - -repeat @# -l[$>]
    -+ {1+@{-1,m}} --gradient_norm
    -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],$2 -rm[-1]
  -endl -done -v +

#@gmic skeleton : _smoothness[%]>=0
#@gmic : Compute skeleton of binary shapes using distance transform.
#@gmic : Default value: 'smoothness=0'.
#@gmic : $ image.jpg -threshold 50% --skeleton 0
skeleton : -check ${1=0}>=0
  -e[^-1] "Compute skeleton of binary image$?."
  -v - -ge 50% -distance 0 -b $1 -sharpen 1e10 -ge 100%
  -repeat @# --erode[$>] 2 --[$>,-1] -done -v +

#@gmic ssd_patch : _use_fourier={ 0 | 1 },_boundary_conditions={ 0=dirichlet | 1=neumann }
#@gmic : Compute field of SSD between an image and a patch, taken as consecutive selected images.
#@gmic : Argument 'boundary_conditions' is valid only when 'use_fourier=0'.
#@gmic : Default value: 'use_fourier=0' and 'boundary_conditions=0'.
#@gmic : $ image.jpg --crop 20%,20%,35%,35% --ssd_patch 0,0
ssd_patch : -skip ${1=0},${2=0}
  -e[^-1] "Compute field of SSD between images and patchs using "@{"-if $1 -u fourier -else -u spatial -endif"}" mode, in image$?."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -r 100%,100%,100%,@{-max_s} -s c
    -repeat {@#/2} -l[$>,{-1-$<}]
      --sqr[1] val=@{-1,+} -rm[-1]        # Sum J(p,q)^2
      --sqr[0] --f[1] 1
      -if $1
        -convolve_fft[-2,-1]               # Sum I(x+p,y+q)^2
        -mirror[1] xyz -convolve_fft[0,1]  # Sum I(x+p,y+q).J(p,q)
      -else
        -correlate[-2] [-1],$2 -rm[-1]    # Sum I(x+p,y+q)^2
        -correlate[0] [1],$2 -rm[1]       # Sum I(x+p,y+q).J(p,q)
      -endif
      -*[0] -2 -+[0,1] -+ $val
    -endl -done -+
  -endl -done -v +

#@gmic thinning
#@gmic : Compute skeleton of binary shapes using morphological thinning
#@gmic : (This is a quite slow iterative proces)
#@gmic : $ image.jpg -threshold 50% --thinning
thinning :
  -e[^-1] "Compute skeleton of binary image$?, using morphological thinning."
  -v - -ge 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 @#  # Start skeleton refinement.
    bavg=@{-9,+}
    -repeat 99999
      --correlate[-9] [-8] -ge[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-7] -ge[-1] 6 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-6] -ge[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-5] -ge[-1] 6 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-4] -ge[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-3] -ge[-1] 6 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-2] -ge[-1] 7 -*[-1] 2 --[-10,-1]
      --correlate[-9] [-1] -ge[-1] 6 -*[-1] 2 --[-10,-1]
      aavg=@{-9,+} -if {$aavg==$bavg} -break -endif bavg=$aavg
    -done
  -mv[-9] 0 -done -rm[-8--1] -+ 1 -/ 2 -v +

#@gmic tones : N>0
#@gmic : Get N tones masks from selected images.
#@gmic : $ image.jpg --tones 3
tones : -check $1>0
  -e[^-1] "Get $1 tones masks from image$?."
  -v - -norm -repeat @# -l[$<]
    -norm -n 0,$1 -repeat {$1-1} --gt[0] {1+$>} --le[0] {$>+2} -and[-2,-1] -done -le[0] 1
  -endl -done -v +

#@gmic topographic_map : _nb_levels>0,_smoothness
#@gmic : Render selected images as topographic maps.
#@gmic : Default values: 'nb_levels=16' and 'smoothness=2'.
#@gmic : $ image.jpg --topographic_map 10
topographic_map : -check "isint(${1=16}) && $1>0" -skip ${2=2}
  -e[^-1] "Render topographic maps from image$?, with $1 levels and smoothness $2."
  -v - -repeat @# -l[$>]
    --b $2 -isophotes[-1] $1 -compose_channels[-1] + -==[-1] 0 -compose_shapeaverage
  -endl -done -v +

#---------------------------------
#
#@gmic :: Image drawing
#
#---------------------------------

#@gmic axes : x0,x1,y0,y1,_font_height>=0,_opacity,_pattern,_color1,.. : (+)
#@gmic : Draw xy-axes on selected images.
#@gmic : 'pattern' is an hexadecimal number starting with '0x' which can be omitted
#@gmic : even if a color is specified.
#@gmic : To draw only one X-axis at row Y, set both 'y0' and 'y1' to Y.
#@gmic : To draw only one Y-axis at column X, set both 'x0' and 'x1' to X.
#@gmic : Default values: 'font_height=13', 'opacity=1', 'pattern=(undefined)' and 'color1=0'.
#@gmic : $ 400,400,1,3,255 -axes -1,1,1,-1

#@gmic ball : _R,_G,_B
#@gmic : Draw a colored RGBA ball sprite on selected images.
#@gmic : Default values: 'R=255', 'G=R' and 'B=R'.
#@gmic : $ 32,32 64,64 200,200 256,256 -ball 255,164,100
ball : -skip ${1=255},${2=$1},${3=$2}
  -e[^-1] "Draw ball sprite on image$?, with color ($1,$2,$3)."
  -v - -to_rgba
  -repeat @# -l[$>]
    mwh={min(w,h)}
    -sh 3,3 -f[-1] 0 -rm[-1]
    -ellipse {0.5*$mwh},{0.5*$mwh},{0.5*$mwh-4},{0.5*$mwh-4},0,1,$1,$2,$3,1
    -sh 0,2 -*[-1] '($mwh+y-x)/(2*w)' -rm[-1]
    -ellipse {$mwh*0.7},{$mwh*0.3},{min(30,$mwh*$mwh/512)},{min(30,$mwh*$mwh/512)},0,{min($mwh/64,1)},255,255,255,1
    -sh 0,2 -b[-1] {0.02*$mwh} -rm[-1]
    -sh 3,3 -*[-2] [-1] -dilate[-1] 3 -rm[-1]
    -sh 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]
  -endl -done -v +

#@gmic chessboard : size1>0,_size2>0,_offset1,_offset2,_angle,_opacity,_color1,..,_color2,..
#@gmic : Draw chessboard on selected images.
#@gmic : Default values: 'size2=size1', 'offset1=offset2=0', 'angle=0', 'opacity=1', 'color1=0' and 'color2=255'.
#@gmic : $ image.jpg -chessboard 32,32,0,0,25,0.3,255,128,0,0,128,255
chessboard : -check "$1>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°, opacity $6 and colors (${7--1})."
  -v - -i[0] (${7--1}) -r[0] {@{0,w}/2},1,1,2,-1 -permute[0] cyzx
  -repeat {@#-1}
    w={w} h={h} theta={$5*pi/180}
    ($3,{$3+$w-1};$3,{$3+$w-1}^$4,$4;{$4+$h-1},{$4+$h-1}) -r[-1] $w,$h,1,2,3
    -r[-1] {$w*$h},2,1,1,-1
    -i[-2] ({cos($theta)},{-sin($theta)};{sin($theta)},{cos($theta)}) -**[-2,-1]
    -r[-1] $w,$h,1,2,-1
    -%[-1] {$1+$2} ->=[-1] $1 -s[-1] c -xor[-2,-1] -map[-1] [0] -r[-1] 100%,100%,1,[-2]
    -j[-2] [-1],0,0,0,0,$6 -rm[-1]
  -mv[-1] 1 -done -rm[0] -v +

#@gmic cie1931
#@gmic : Draw CIE-1931 chromaticity diagram on selected images.
#@gmic : $ 500,400,1,3 -cie1931
cie1931 :
  -e[^-1] "Draw CIE-1931 chromaticity diagram on image$?."
  -v -

  # Generate convex hull of visible colors, as a 3d object.
  (67.5;73.5;109.5;103.5;51.5;100.5;37;36)  # Header
  (280,420,0;171,829,0;158,820,0;153,816,0;147,811,0;140,804,0;132,794,0;121,776,0;106,747,0;88,701,0;\  # Vertices.
  65,633,0;42,539,0;20,421,0;5,295,0;0,179,0;4,115,0;10,83,0;16,61,0;25,38,0;35,21,0;47,10,0;58,3,0;\
  71,0,0;92,1,0;111,7,0;151,28,0;189,52,0;226,79,0;262,109,0;298,141,0;334,175,0;370,209,0;405,244,0;\
  441,279,0;475,313,0;509,347,0;731,568,0)
  xM=731 yM=829
  2,{h-1},1,1,3,0 1,{h},1,1,'y' --+[-1] 1 -%[-1] {h} -+[-2,-1] 1 -a[-3--1] x  # Primitives.
  3,{h},1,1,160 1,{h},1,1,1  # Colors + opacities.
  -y[-4--2] y -a[-5--1] y -mv[-1] 0

  # Generate RGB triangle of displayable colors.
  xR=636 yR=504 xG=297 yG=234 xB=147 yB=774
  512,512,1,3 -triangle_shade[-1] 0,0,{w-1},0,0,{h-1},""255,0,0,""0,255,0,""0,0,255 -rgb2srgb[-1]
  --compose_channels[-1] max -+[-1] 1e-8 -/[-2,-1] -*[-1] 255
  -i[-2] (67.5;73.5;109.5;103.5;51.5;100.5;3;1;$xR;$yR;-0.01;$xG;$yG;-0.01;$xB;$yB;-0.01;9;0;1;2;0;0;511;0;0;511;-128;512;512;3)
  -y[-1] y (1) -a[-3--1] y -mv[-1] 1

  # Draw chroma diagram.
  -repeat {@#-2}
    -to_rgb[-1] -fc[-1] 255,255,255 -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,1,0
    100%,100%,1,3
    --*3d[0,1] {(w-8)/$xM},{(h-32)/$yM}
    -object3d[-3] [-1],2,30,0,1,2
    --neq[-3] 0 -distance[-1] 1 -*[-1] -1 -watershed[-4] [-1] -rm[-1] -/[-3] 1.5
    -object3d[-3] [-1],2,30,0,1,2
    -p3d[-1] 1 -p3d[-1] 2 -col3d[-1] 128 -object3d[-3] [-1],2,30,0,1,1 -rm[-1]
    @{-2,w},@{-2,h} -object3d[-1] [-2],2,30,0,1,2 -rm[-2]
    --erode[-1] 4 --[-1] [-2] -eq[-1] 0 -*[-3,-1]
    -a[-2,-1] c -compose_alpha[-2,-1]
    100%,100%,1,1,255 -axes[-1] 0,0.75,0.85,0,13,1 --erode[-1] 3 -negative[-1] -to_rgb[-2]
    -j[-3] [-2],0,0,0,0,1,[-1],400 -rm[-2,-1]
  -mv[-1] 2 -done -rm[0,1] -v +

#@gmic circle : x[%],y[%],R[%],_opacity,_pattern,_color1,..
#@gmic : Draw specified colored circle on selected images.
#@gmic : A radius of '100%' stands for 'sqrt(width^2+height^2)'.
#@gmic : 'pattern' is an hexadecimal number starting with '0x' which can be omitted
#@gmic : even if a color is specified. If a pattern is specified, the circle is
#@gmic : drawn outlined instead of filled.
#@gmic : Default values: 'opacity=1', 'pattern=(undefined)' and 'color1=0'.
#@gmic : $ image.jpg -repeat 300 -circle {?(100)}%,{?(100)}%,{?(30)},0.3,@{-RGB} -done -circle 50%,50%,100,0.7,255
circle : -skip ${4=1},${5=0}
  -v - ({'"$5"'}) is_pattern={@{-1,0-1}'=='{'0x'}} -rm[-1] -v +
  -if $is_pattern
    -e[0--3] "Draw outlined circle at ($1,$2) with radius $3 on image$?, with opacity $4 and color (${6--1})."
  -else
    -e[0--3] "Draw filled circle at ($1,$2) with radius $3 on image$?, with opacity $4 and color (${5--1})."
  -endif
  -v - -ellipse $1,$2,$3,$3,0,${4--1} -v +

#@gmic ellipse : x[%],y[%],R[%],r[%],_angle,_opacity,_pattern,_color1,.. : (+)
#@gmic : Draw specified colored ellipse on selected images.
#@gmic : A radius of '100%' stands for 'sqrt(width^2+height^2)'.
#@gmic : 'pattern' is an hexadecimal number starting with '0x' which can be omitted
#@gmic : even if a color is specified. If a pattern is specified, the ellipse is
#@gmic : drawn outlined instead of filled.
#@gmic : Default values: 'opacity=1', 'pattern=(undefined)' and 'color1=0'.
#@gmic : $ image.jpg -repeat 300 -ellipse {?(100)}%,{?(100)}%,{?(30)},{?(30)},{?(180)},0.3,@{-RGB} -done -ellipse 50%,50%,100,100,0,0.7,255

#@gmic flood : x[%],_y[%],_z[%],_tolerance>=0,_is_high_connectivity={ 0 | 1 },_opacity,_color1,.. : (+)
#@gmic : Flood-fill selected images using specified value and tolerance.
#@gmic : Default values: 'y=z=0', 'tolerance=0', 'is_high_connectivity=0', 'opacity=1' and 'color1=0'.
#@gmic : $ image.jpg -repeat 1000 -flood {?(100)}%,{?(100)}%,0,20,0,1,@{-RGB} -done

#@gmic gaussian : _sigma1[%],_sigma2[%],_angle
#@gmic : Draw a centered gaussian on selected images, with specified standard deviations and orientation.
#@gmic : Default values: 'sigma1=3', 'sigma2=sigma1' and 'angle=0'.
#@gmic : $ 400,400 -gaussian 100,30,45
gaussian : -skip ${1=3},${2=$1},${3=0}
  -e[^-1] "Draw centered gaussian on image$? with standard deviations ($1,$2) and angle $3°."
  -v -
  u={cos($3*pi/180)}
  v={sin($3*pi/180)}
  dmax={max(w,h)}
  -if {isval($1)} l1=$1 -else l1={${1}10000*$dmax/100} -endif
  -if {isval($2)} l2=$2 -else l2={${2}10000*$dmax/100} -endif
  l1={1/(2*max(1/3,$l1)^2)}
  l2={1/(2*max(1/3,$l2)^2)}
  A={$l1*$u*$u+$l2*$v*$v}
  B={($l1-$l2)*$u*$v}
  C={$l1*$v*$v+$l2*$u*$u}
  -repeat @# -l[$>] nm=@{0,n}
    w={w} h={h} ds={d},{s} -rm
    ({-$w/2},{$w/2}) -r $w,$h,1,1,3
    -f[-1] "Y=y-"{$h/2};$A"*i*i+2*"$B"*i*Y+"$C*"Y*Y"
    -* -1 -exp -r $w,$h,$ds
  -nm $nm,1 -endl -done -v +

#@gmic graph : [function_image],_plot_type,_vertex_type,_ymin,_ymax,_opacity,_pattern,_color1,.. : 'formula',_resolution>=0,_plot_type,_vertex_type,_xmin,xmax,_ymin,_ymax,_opacity,_pattern,_color1,.. : (+)
#@gmic : Draw specified function graph on selected images.
#@gmic : 'plot_type' can be { 0=none | 1=lines | 2=splines | 3=bar }.
#@gmic : 'vertex_type' can be { 0=none | 1=points | 2,3=crosses | 4,5=circles | 6,7=squares }.
#@gmic : 'pattern' is an hexadecimal number starting with '0x' which can be omitted
#@gmic : even if a color is specified.
#@gmic : Default values: 'plot_type=1', 'vertex_type=1', 'ymin=ymax=0 (auto)', 'opacity=1', 'pattern=(undefined)'
#@gmic : and 'color1=0'.
#@gmic : $ image.jpg --rows 50% -blur[-1] 3 -s[-1] c -div[0] 1.5 -graph[0] [1],2,0,0,0,1,255,0,0 -graph[0] [2],2,0,0,0,1,0,255,0 -graph[0] [3],2,0,0,0,1,0,0,255 -keep[0]

#@gmic grid : size_x[%]>=0,size_y[%]>=0,_offset_x[%],_offset_y[%],_opacity,_pattern,_color1,..
#@gmic : Draw xy-grid on selected images.
#@gmic : 'pattern' is an hexadecimal number starting with '0x' which can be omitted
#@gmic : even if a color is specified.
#@gmic : Default values: 'offset_x=offset_y=0', 'opacity=1', 'pattern=(undefined)' and 'color1=0'.
#@gmic : $ image.jpg -grid 10%,10%,0,0,0.5,255
#@gmic : $ 400,400,1,3,255 -grid 10%,10%,0,0,0.3,0xCCCCCCCC,128,32,16
grid : -skip ${3=0},${4=0},${5=1},${6=0}
  -v - ({'"$6"'}) is_pattern={@{-1,0-1}'=='{'0x'}} -rm[-1] -v +
  -if $is_pattern
    -e[0--3] "Draw xy-grid on image$?, with sizes ($1,$2), offsets ($3,$4), opacity $5, pattern $6 and color (${7--1})."
    -v - pattern=$6 color=${7--1}
  -else
    -e[0--3] "Draw xy-grid on image$?, with sizes ($1,$2), offsets ($3,$4), opacity $5, and color (${6--1})."
    -v - pattern=0xFFFFFFFF color=${6--1}
  -endif
  is_percentsx=@{"-is_percent $1"} is_percentsy=@{"-is_percent $2"}
  is_percentox=@{"-is_percent $3"} is_percentoy=@{"-is_percent $4"}

  -repeat @# -l[$>]
    sizex={if($is_percentsx,w*$1,$1)}
    sizey={if($is_percentsy,h*$2,$2)}
    offsetx={if($is_percentox,$sizex*$3,$3)}
    offsety={if($is_percentoy,$sizey*$4,$4)}

    w={w} h={h} s={s}
    ({'CImg3d'}) -+[-1] 0.5

    1,{1+int($w/$sizex)},1,1,'y' -*[-1] $sizex -+[-1] {$offsetx%$sizex}
    1,{h},1,1,{$h/2} -a[-2,-1] x n1={h}

    1,{1+int($h/$sizey)},1,1,'y' -*[-1] $sizey -+[-1] {$offsety%$sizey}
    -i[-2] 1,{h},1,1,{$w/2} -a[-2,-1] x n2={h} n={$n1+$n2}
    -a[-2,-1] y -z[-1] 0,2 -i[-2] ($n;$n)

    (1,0;1,{$n-1}) -r[-1] 2,$n,1,1,3 -round[-1] # Primitives.

    (-128;1;$h;$s) 1,$h,1,$s -line[-1] 0,0,0,100%,1,$pattern,$color # Colors.
    1,{4*($n1-1)},1,1,-128,0,0,0
    (-128;$w;1;$s) $w,1,1,$s -line[-1] 0,0,100%,0,1,$pattern,$color
    1,{4*($n2-1)},1,1,-128,$n1,0,0

    (-128;1;$h;1) 1,$h,1,1 -line[-1] 0,0,0,100%,1,$pattern,1 # Opacities.
    1,{4*($n1-1)},1,1,-128,0,0,0
    (-128;$w;1;1) $w,1,1,1 -line[-1] 0,0,100%,0,1,$pattern,1
    1,{4*($n2-1)},1,1,-128,$n1,0,0

    -y[^0] y -a[^0] y -object3d[-2] [-1],0,0,0,$5,0,0,0 -rm[-1]  # Merge as a 3d object and draw.
  -endl -done -v +

#@gmic j : eq. to '-image'. : (+)

#@gmic image : [sprite],_x[%],_y[%],_z[%],_c[%],_opacity,_[sprite_mask],_max_opacity_mask : (+)
#@gmic : Draw specified sprite image on selected images.
#@gmic : (eq. to '-j').
#@gmic : Default values: 'x=y=z=c=0', 'opacity=1', 'sprite_mask=(undefined)' and 'max_opacity_mask=1'.
#@gmic : $ image.jpg --crop 40%,40%,60%,60% -resize[-1] 200%,200%,1,3,5 -frame[-1] 2,2,0 -image[0] [-1],30%,30% -keep[0]

#@gmic line : x0[%],y0[%],x1[%],y1[%],_opacity,_pattern,_color1,.. : (+)
#@gmic : Draw specified colored line on selected images.
#@gmic : 'pattern' is an hexadecimal number starting with '0x' which can be omitted
#@gmic : even if a color is specified.
#@gmic : Default values: 'opacity=1', 'pattern=(undefined)' and 'color1=0'.
#@gmic : $ image.jpg -repeat 500 -line 50%,50%,{?(w)},{?(h)},0.5,@{-RGB} -done -line 0,0,100%,100%,1,0xCCCCCCCC,255 -line 100%,0,0,100%,1,0xCCCCCCCC,255

#@gmic mandelbrot : z0r,z0i,z1r,z1i,_iteration_max>=0,_is_julia={ 0 | 1 },_c0r,_c0i,_opacity : (+)
#@gmic : Draw mandelbrot/julia fractal on selected images.
#@gmic : Default values: 'iteration_max=100', 'is_julia=0', 'c0r=c0i=0' and 'opacity=1'.
#@gmic : $ 400,400 -mandelbrot -2.5,-2,2,2,1024 -map 0 --blur 2 -elevation3d[-1] -0.2

#@gmic marble : _image_weight,_pattern_weight,_angle,_amplitude,_sharpness>=0,_anisotropy>=0,_alpha,_sigma,_cut_low>=0,_cut_high>=0
#@gmic : Render marble like pattern on selected images.
#@gmic : Default values: 'image_weight=0.2', 'pattern_weight=0.1', 'angle=45', 'amplitude=0', 'sharpness=0.4', 'anisotropy=0.8',
#@gmic : 'alpha=0.6', 'sigma=1.1' and 'cut_low=cut_high=0'.
#@gmic : $ image.jpg --marble ,
marble : -skip ${1=0.2},${2=0.1},${3=45},${4=0},${5=0.4},${6=0.8},${7=0.6},${8=1.1},${9=0%},${10=100%}
  -e[^-1] "Render marble like pattern on image$?, with image weight $1, pattern weight $2, angle $3°, amplitude $4, "\
          "sharpness $5, anisotropy $6, alpha $7, sigma $8, and cut ($9,$10)."
  -v - sx={$2*sin($3*pi/180)} sy={$2*cos($3*pi/180)} -f sin(x*$sx+y*$sy+i*$1)
  -if {$4} -smooth $4,$5,$6,$7,$8 -endif
  -c $9,$10 -n 0,255
  -v +

#@gmic maze : _width>0,_height>0,_cell_size>0
#@gmic : Input maze with specified size.
#@gmic : $ -maze 30,20 -negative -n 0,255
maze : -check "isint(${1=15}) && $1>0 && isint(${2=$1}) && $2>0 && isint(${3=24}) && $3>0"
  -e[^-1] "Input $1x$2 maze."
  -v -
  ({round(?($1-1))},{round(?($2-1))})  # Starting cell.
  $1,$2,1,1,15 --f[-1] 0 -a[-2,-1] c   # Starting maze data.
  -_generate_maze $1,$2
  -_render_maze[-1] $3 -nm[-1] [maze]
  -v +

_generate_maze :

  # Start opening walls.
  -do
    x=@{-2,-2} y=@{-2,-1}  # Coords of the current cell.
    -=[-1] 1,$x,$y,0,1     # Mark current cell as visited.

    # Check for neighboring cells that are candidate for opening wall, and select one random.
    is_candidate=0
    up=-1 -if {i($x,$y)&8" && "$y>0" && "!i($x,$y-1,0,1)} up=$x,{$y-1},8 is_candidate=1 -endif          # Up.
    down=-1 -if {i($x,$y)&4" && "$y<$2-1" && "!i($x,$y+1,0,1)} down=$x,{$y+1},4 is_candidate=1 -endif   # Down.
    left=-1 -if {i($x,$y)&2" && "$x>0" && "!i($x-1,$y,0,1)} left={$x-1},$y,2 is_candidate=1 -endif      # Left.
    right=-1 -if {i($x,$y)&1" && "$x<$1-1" && "!i($x+1,$y,0,1)} right={$x+1},$y,1 is_candidate=1 -endif # Right.
    -if $is_candidate
      ($up,$down,$left,$right) -discard[-1] -1 -r[-1] 3,{h/3},1,1,-1 -shift[-1] 0,{?(4)},0,0,2 -rows[-1] 0,0 -mv[-1] -2
    -endif

    # Remove wall between the current and chosen neighboring cells.
    -if $is_candidate
      -if {@{-2,-1}==8}   -=[-1] {i($x,$y)&7},$x,$y -=[-1] {i($x,$y-1)&11},$x,{$y-1}   # Remove up wall.
      -elif {@{-2,-1}==4} -=[-1] {i($x,$y)&11},$x,$y -=[-1] {i($x,$y+1)&7},$x,{$y+1}   # Remove down wall.
      -elif {@{-2,-1}==2} -=[-1] {i($x,$y)&13},$x,$y -=[-1] {i($x-1,$y)&14},{$x-1},$y  # Remove left wall.
      -else               -=[-1] {i($x,$y)&14},$x,$y -=[-1] {i($x+1,$y)&13},{$x+1},$y  # Remove right wall.
      -endif
      -z[-2] 0,1 -a[-3,-2] y  # Add neighboring cell to stack of cells to explore.
    -else # No candidate : remove current cell from cells to explore.
      -if {@{-2,h}==1} -break -endif
      -rows[-2] 0,{@{-2,h}-2}
    -endif
  -while 1
  -rm[-2] -channels[-1] 0

_render_maze :
  # Create the 16 configurations of walls.
  -i[0] $1,$1 -i[1] [0]x15
  -line[8-15] 0,0,100%,0,1,1
  -line[4-7,12-15] 0,100%,100%,100%,1,1
  -line[2-3,6-7,10-11,14-15] 0,0,0,100%,1,1
  -line[1-15:2] 100%,0,100%,100%,1,1
  # Map the wall data with them.
  -a[0-15] x -r[-1] {w*$1},{h*$1} -*[-1] $1 -channels[-1] 0,1
  $1,$1,1,1,x $1,$1,1,1,y -a[-2,-1] c -r[-1] [-2],[-2],1,2,0,2 -+[-2,-1]
  -warp[-2] [-1],0,0,0 -rm[-1]

#@gmic maze_mask : _cellsize>0
#@gmic : Input maze according to size and shape of selected mask images.
#@gmic : Mask may contain disconnected shapes.
#@gmic : $ 0 -text "G'MIC",0,0,57,1,1 -dilate 3 -autocrop 0 -frame 1,1,0 -maze_mask 8 -dilate 3 -negative -* 255
maze_mask : -check "isint(${1=24}) && $1>0"
  -e[^-1] "Input masked maze from image$? with cell size $1."
  -v - -norm -ge 50% -repeat @# -l[$>]
    -do
      --rand[0] 0,1 -*[-1] [0] ({xM},{yM}) -rm[-2]  # Select one starting point in the mask.
      --flood[0] @-1,0,0,0,1,2 -ge[-1] 2 --negative[-1] -*[-2] 15 -a[-2,-1] c
      -flood[0] @-2,0,0,0,1,0
      -_generate_maze {w},{h}
    -while @{0,M}
    -rm[0] -+ -_render_maze[-1] $1 -nm[-1] [maze]
  -endl -done -v +

#@gmic object3d : [object3d],_x[%],_y[%],_z,_opacity,_rendering_mode,_is_double3d={ 0 | 1 },_is_zbuffer={ 0 | 1 },_focale,_light_x,_light_y,_light_z,_specular_lightness,_specular_shininess : (+)
#@gmic : Draw specified 3d object on selected images.
#@gmic : 'rendering_mode' can be { 0=dots | 1=wireframe | 2=flat | 3=flat-shaded | 4=gouraud-shaded | 5=phong-shaded }.
#@gmic : Default values: 'x=y=z=0', 'opacity=1' and 'is_zbuffer=1'. All other arguments take their default values from the 3d environment variables.
#@gmic : $ image.jpg -torus3d 100,10 -cone3d 30,-120 -add3d[-2,-1] -rotate3d[-1] 1,1,0,60 -object3d[0] [-1],50%,50% -keep[0]

#@gmic piechart : label_height>=0,label_R,label_G,label_B,"label1",value1,R1,G1,B1,...,"labelN",valueN,RN,GN,BN
#@gmic : Draw pie chart on selected (RGB) images.
#@gmic : $ image.jpg -piechart 25,0,0,0,"Red",55,255,0,0,"Green",40,0,255,0,"Blue",30,128,128,255,"Other",5,128,128,128
piechart : -check $1>=0
  -e[^-1] "Draw pie chart on image$?, with label height $1 and color ($2,$3,$4)."
  -v - -repeat @# -l[$>]
    -ellipse 50%,50%,{w/2-1},{h/2-1},0,1,1
    -ellipse 50%,50%,{w/2-1},{h/2-1},0,1,0xFFFFFFFF
    (${6--1:5}) -normalize_sum[-1]
    theta=0
    -repeat {w}
      xe={0.5*@{-2,w}*(1+cos($theta))}
      ye={0.5*@{-2,h}*(1+sin($theta))}
      -line[-2] 50%,50%,$xe,$ye
      theta={$theta-2*pi*i($>)}
    -done
    theta=0
    -repeat {w} -if {i($>)}
      ntheta={$theta-2*pi*i($>)}
      xc={0.5*@{-2,w}*(1+0.5*cos(0.5*($ntheta+$theta)))}
      yc={0.5*@{-2,h}*(1+0.5*sin(0.5*($ntheta+$theta)))}
      xf={0.5*@{-2,w}*(1+0.8*cos(0.5*($ntheta+$theta)))}
      yf={0.5*@{-2,h}*(1+0.8*sin(0.5*($ntheta+$theta)))}
      -flood[-2] $xf,$yf,0,0,0,1,@{-arg\ {7+5*$>}-{9+5*$>},"$*"}
      -if {abs($ntheta-$theta)>0.1}
        0 -t[-1] @{-arg\ {5+5*$>},"$*"},0,0,$1,1,1
        ($2^$3^$4) -r[-1] [-2],[-2],1,3 -*[-1] [-2]
        -j[-4] [-1],{$xc-w/2},{$yc-h/2},0,0,1,[-2]
        -rm[-2,-1]
      -endif
      theta=$ntheta
    -endif -done
    -rm[-1]
  -endl -done -v +

#@gmic plasma : alpha,_beta,_scale>=0 : (+)
#@gmic : Draw a random colored plasma on selected images.
#@gmic : Default values: 'beta=1' and 'scale=8'.
#@gmic : $ 400,400,1,3 -plasma 1

#@gmic point : x[%],y[%],_z[%],_opacity,_color1,.. : (+)
#@gmic : Set specified colored pixel on selected images.
#@gmic : Default values: 'z=0', 'opacity=1' and 'color1=0'.
#@gmic : $ image.jpg -repeat 10000 -point {?(100)}%,{?(100)}%,0,1,@{-RGB} -done

#@gmic polka_dots : diameter>=0,_density,_offset1,_offset2,_angle,_aliasing,_shading,_opacity,_color,...
#@gmic : Draw dots pattern on selected images.
#@gmic : Default values: 'density=20', 'offset1=offset2=50', 'angle=0', 'aliasing=10', 'shading=1', 'opacity=1' and 'color=255'.
#@gmic : $ image.jpg -polka_dots 10,15,0,0,20,10,1,0.5,0,128,255
polka_dots : -check $1>=0 -skip ${2=20},${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}) -y[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}) -y[-1] c -r[-1] [-2],[-2],[-2]
    -j[-3] [-1],0,0,0,0,1,[-2] -rm[-2,-1]
  -mv[-1] 1 -done -rm[0] -v +

#@gmic polygon : N,x1[%],y1[%],..,xN[%],yN[%],_opacity,_pattern,_color1,.. : (+)
#@gmic : Draw specified colored N-vertices polygon on selected images.
#@gmic : 'pattern' is an hexadecimal number starting with '0x' which can be omitted
#@gmic : even if a color is specified. If a pattern is specified, the polygon is
#@gmic : drawn outlined instead of filled.
#@gmic : Default values: 'opacity=1', 'pattern=(undefined)' and 'color1=0'.
#@gmic : $ image.jpg -polygon 4,20%,20%,80%,30%,80%,70%,20%,80%,0.3,0,255,0 -polygon 4,20%,20%,80%,30%,80%,70%,20%,80%,1,0xCCCCCCCC,255
#@gmic : $ image.jpg 2,16,1,1,'?(if(x,@{-1,h},@{-1,w}))' -polygon[-2] {h},@-1,0.6,255,0,255 -remove[-1]

#@gmic quiver : [function_image],_sampling>0,_factor,_is_arrow={ 0 | 1 },_opacity,_pattern,_color1,.. : (+)
#@gmic : Draw specified 2d vector/orientation field on selected images.
#@gmic : 'pattern' is an hexadecimal number starting with '0x' which can be omitted
#@gmic : even if a color is specified.
#@gmic : Default values: 'sampling=25', 'factor=-20', 'is_arrow=1', 'opacity=1', 'pattern=(undefined)'
#@gmic : and 'color1=0'.
#@gmic : $ 100,100,1,2,'if(c==0,x-w/2,y-h/2)' 500,500,1,3,255 -quiver[-1] [-2],10
#@gmic : $ image.jpg --resize2dy 600 -luminance[0] -gradient[0] -mul[1] -1 -reverse[0,1] -append[0,1] c -blur[0] 8 -orientation[0] -quiver[1] [0],10,10,1,0.8,255

#@gmic rectangle : x0[%],y0[%],x1[%],y1[%],_opacity,_pattern,_color1,..
#@gmic : Draw specified colored rectangle on selected images.
#@gmic : 'pattern' is an hexadecimal number starting with '0x' which can be omitted
#@gmic : even if a color is specified. If a pattern is specified, the rectangle is
#@gmic : drawn outlined instead of filled.
#@gmic : Default values: 'opacity=1', 'pattern=(undefined)' and 'color1=0'.
#@gmic : $ image.jpg -repeat 30 -rectangle {?(100)}%,{?(100)}%,{?(100)}%,{?(100)}%,0.3,@{-RGB} -done
rectangle : -skip ${5=1},${6=0}
  -v - ({'"$5"'}) is_pattern={@{-1,0-1}'=='{'0x'}} -rm[-1] -v +
  -if $is_pattern
    -e[0--3] "Draw outlined rectangle from ($1,$2) to ($3,$4) on image$?, with opacity $5 and color (${7--1})."
  -else
    -e[0--3] "Draw filled rectangle from ($1,$2) to ($3,$4) on image$?, with opacity $5 and color (${6--1})."
  -endif
  -v - -polygon 4,$1,$2,$3,$2,$3,$4,$1,$4,${5--1} -v +

#@gmic rorschach : 'smoothness[%]>=0','mirroring={ 0=none | 1=x | 2=y | 3=xy }
#@gmic : Render rorschach-like inkblots on selected images.
#@gmic : Default values: 'smoothness=5%' and 'mirroring=1'.
#@gmic : $ 400,400 -rorschach 3%
rorschach : -check ${1=5%}>=0 -skip ${2=1}
  -e[^-1] "Render rorschach-like inkblots on image$?, with smoothness $1 and "\
          @{"-if {$2==1} -u X -elif {$2==2} -u Y -elif {$2==3} -u XY -else -u no -endif"}\
          "-mirroring."
  -v -
  -if {$2==0} # No mirroring.
   -rand -1,1 -b $1 -ge 0
  -elif {$2==1} # X-mirroring.
    -repeat @# -l[$>]
      w={w}
      -columns 0,{w/2-1} -rand -1,1 -b $1 -ge 0
      --mirror x -if {$w%2} -columns[-1] 1,100% -endif -a x
    -endl -done
  -elif {$2==2} # Y-mirroring.
    -repeat @# -l[$>]
      h={h}
      -rows 0,{h/2-1} -rand -1,1 -b $1 -ge 0
      --mirror y -if {$h%2} -rows[-1] 1,100% -endif -a y
    -endl -done
  -elif {$2==3} # XY-mirroring.
    -repeat @# -l[$>]
      w={w} h={h}
      -z 0,0,{w/2-1},{h/2-1} -rand -1,1 -b $1 -ge 0
      --mirror x -if {$w%2} -columns[-1] 1,100% -endif -a x
      --mirror y -if {$h%2} -rows[-1] 1,100% -endif -a y
    -endl -done
  -endif
  -v +

#@gmic sierpinski : recursion_level>=0
#@gmic : Draw Sierpinski triangle on selected images.
#@gmic : Default value: 'recursion_level=7'.
#@gmic : $ image.jpg -sierpinski 7
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 snowflake : _recursion>=0,_x0,_y0,_x1,_y1,_x2,_y2,_opacity,_col1,..._colN
#@gmic : Draw a Koch snowflake on selected images.
#@gmic : Default values: 'recursion=4', 'x0=20', 'y0=70', 'x1=80', 'y1=70', 'x2=50', 'y2=10', 'opacity=1' and 'col1=255'.
#@gmic : $ image.jpg -snowflake 4
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 spiralbw
#@gmic : Draw (squared) spiral on selected images.
#@gmic : $ 16,16 -spiralbw
spiralbw :
  -e[^-1] "Draw (squared) black and white spiral on image$?."
  -v - -channels 0
  -f "r=min(x,y,w-1-x,h-1-y); 2*r*(w+h-2*r-1) + if(min(x,h-1-y)>=min(w-1-x,y),x+y,2*(w+h-2-2*r)-x-y)"
  -v +

#@gmic spline : x0[%],y0[%],u0[%],v0[%],x1[%],y1[%],u1[%],v1[%],_opacity,_pattern,_color1,.. : (+)
#@gmic : Draw specified colored spline curve on selected images.
#@gmic : 'pattern' is an hexadecimal number starting with '0x' which can be omitted
#@gmic : even if a color is specified.
#@gmic : Default values: 'opacity=1', 'pattern=(undefined)' and 'color1=0'.
#@gmic : $ image.jpg -repeat 30 -spline {?(100)}%,{?(100)}%,{?(-600,600)},{?(-600,600)},{?(100)}%,{?(100)}%,{?(-600,600)},{?(-600,600)},0.3,255 -done

#@gmic t : eq. to '-text'. : (+)

#@gmic text : text,_x[%],_y[%],_font_height>=0,_opacity,_color1,.. : (+)
#@gmic : Draw specified colored text string on selected images.
#@gmic : (eq. to '-t').
#@gmic : Exact pre-defined sizes are '13','24','32' and '57'. Any other size is interpolated.
#@gmic : Specifying an empty target image resizes it to new dimensions such that the image contains
#@gmic : the entire text string.
#@gmic : Default values: 'opacity=1' and 'color1=0'.
#@gmic : $ image.jpg -resize2dy 600 y=0 -repeat 30 -text {2*$>}" : This is a nice text, isn't it ?",10,$y,{2*$>},0.9,255 y={$y+2*$>} -done
#@gmic : $ 0 -text \"G'MIC\",0,0,24,1,255

#@gmic text_outline : text,_x[%],_y[%],_font_height>0,_outline>=0,_opacity,_color1,..
#@gmic : Draw specified colored and outlined text string on selected images.
#@gmic : Default values: 'x=y=2', 'font_height=13', 'outline=2', 'opacity=1' and 'color1=255'.
#@gmic : $ image.jpg -text_outline "Hi there!",10,10,52,3
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
    0 -t[-1] "$1",0,0,$4,1,1 -expand_xy[-1] {1+$5},0 --dilate[-1] {2*$5+1}
    (${7--1}) -y[-1] c -r[-1] 2,1,1,100%,0,0,1 -map[-3] [-1] -rm[-1]
    -repeat {@#-2} -if @{$>,w} -j[$>] [-2],$2,$3,0,0,$6,[-1] -else -rm[$>] -i[$>] [-2] -endif -done -rm[-2,-1]
  -else
    -t "$1",${2-4},${6--1}
  -endif
  -v +

#@gmic triangle_shade : x0,y0,x1,y0,x2,y2,R0,G0,B0,...,R1,G1,B1,...,R2,G2,B2,....
#@gmic : Draw triangle with interpolated colors on selected images.
#@gmic : $ image.jpg -triangle_shade 20,20,400,100,120,200,255,0,0,0,255,0,0,0,255
triangle_shade :
  -e[^-1] "Draw triangle ($1,$2)-($3,$4)-($5,$6) with interpolated colors on image$?."
  -v -
  # Find mapping coefficients for each color.
  -l[] ($1,$2,1;$3,$4,1;$5,$6,1) (${7--1}) -r[-1] {w/3},3,1,1,-1 -s[-1] x -solve[^0] [0] -rm[0] -a c -endl
  -polygon[^-1] 3,${1-6},1,-65535 # Mask images with triangle.
  -repeat {@#-1} -l[$>,-1] -repeat @{0,s}
    a={i(0,0,0,$>)} b={i(0,1,0,$>)} c={i(0,2,0,$>)}
    -sh[0] $>,$> -f[-1] 'if(i==-65535,$a*x+$b*y+$c,i)' -rm[-1]
  -done -endl -done
  -rm[-1] -v +

#@gmic truchet : _scale>0,_radius>=0,_pattern_type={ 0=straight | 1=curved }
#@gmic : Fill selected images with random truchet patterns.
#@gmic : Default values: 'scale=32', 'radius=5' and 'pattern_type=1'.
#@gmic : $ 400,300 -truchet ,
truchet : -check "isint(${1=32}) && $1>0 && ${2=3}>=0" -skip ${3=1}
  -e[^-1] "Render "@{"-if $3 -u curved -else -u straight -endif"}" truchet patterns in image$?, with scale $1 and radius $2."
  -v - -repeat @# -l[$>] nm=@{0,n}
    w={w} h={h} s={s} -rm
    $1,$1 -= 1,0,0 -= 1,100%,100% -distance 1,{1+$3} M={int(iM/2)} # Generate truchet pattern and its mirrored version.
    -t2 {$M-$2/2-($1%2)},{$M+$2/2} --mirror y -a x
    {round($w/$1,1,1)},{round($h/$1,1,1)} -rand[-1] 0,1 -ge[-1] 50% -r[-1] {w*$1},{h*$1} -*[-1] $1
    -channels[-1] 0,1 (0,{$1-1}) -r[-1] $1,$1,1,1,3 --transpose[-1] -a[-2,-1] c -r[-1] [-2],0,2 -+[-2,-1]
    -warp[-2] [-1] -rm[-1] -ge 50% -r $w,$h,1,1,0 -r 100%,100%,1,$s
  -nm $nm,1 -endl -done -v +

#@gmic turbulence : _radius>0,_octaves={1,2,3...,12},_alpha>0,_difference={-10,10},_mode={0,1,2,3}
#@gmic : Render fractal noise or turbulence on selected image$?.
#@gmic : Default values: 'radius=32', 'octaves=6', 'alpha=3', 'difference=0' and 'mode=0'.
#@gmic : $ 400,400,1,3 -turbulence 16
turbulence : -check "${1=32}>0 && ${2=6}>0" -skip ${3=3},${4=0},${5=0}
  -e[^-1] "Render fractal noise or turbulence on image$?, with radius $1, octaves $2, damping per octave $3, difference $4 and mode $5."
  -v - -repeat @# -l[$>] nm=@{0,n}
    -if {$4} [-1] -endif
    -f[-1] 0 --noise[-1] 10,0 -b[-1] $1,0
    -if {$5==0||$5==1} --[-1] @{-1,a} -abs[-1]
    -elif {$5==3||$5==4} -^[-1] 2
    -elif {$5==5} -^[-1] 3
    -endif
    -repeat {$2-1}
      --noise[-2] 10,0 -b[-1] {$1/2^$>},0
      -if {$5==0} --[-1] @{-1,a} -abs[-1]
      -elif {$5==4} -^[-1] 2
      -elif {$5==5} -^[-1] 3
      -endif
      -*[-2] $3 -+[-2--1]
    -done
    -n[-1] 0,255
    -rm[-2]
    -if {$4} -*[-1] $4 -mv[-2] 2 -- -n[-1] 0,255 -endif
  -nm $nm,1 -endl -done -v +

#@gmic yinyang
#@gmic : Draw a yin-yang symbol on selected images.
#@gmic : $ 400,400 -yinyang
yinyang :
  -e[^-1] "Draw yin-yang symbol on image$?."
  -v - -f 0 -repeat @# -l[$>]
    s={s} -channels 0
    r={round(0.95*min(w,h)/4)}
    --line 50%,0,50%,50%,1,2 -ellipse[-1] 50%,{h/2-$r},$r,$r,0,1,2
    -line[-1] 50%,50%,50%,100%,1,1 -ellipse[-1] 50%,{h/2+$r},$r,$r,0,1,1
    -flood[-1] {w/2-$r},50%,0,0,0,1,2
    -flood[-1] {w/2+$r},50%,0,0,0,1,1
    -ellipse[-2] 50%,50%,{2*$r},{2*$r},0,1,1
    -*
    -ellipse[-1] 50%,{h/2-$r},{$r/3},{$r/3},0,1,1
    -ellipse[-1] 50%,{h/2+$r},{$r/3},{$r/3},0,1,2
    -r 100%,100%,1,$s
  -endl -done -v +

#---------------------------------
#
#@gmic :: Matrix computation
#
#---------------------------------

#@gmic dijkstra : starting_node>=0,ending_node>=0 : (+)
#@gmic : Compute minimal distances and pathes from specified adjacency matrices by the Dijkstra algorithm.

#@gmic eigen : (+)
#@gmic : Compute the eigenvalues and eigenvectors of selected symmetric matrices or matrix fields.
#@gmic : If one selected image has 3 or 6 channels, it is regarded as a field of 2x2 or 3x3 symmetric matrices,
#@gmic : whose eigen elements are computed at each point of the field.
#@gmic : $ (1,0,0;0,2,0;0,0,3) --eigen
#@gmic : $ image.jpg -structuretensors -blur 2 -eigen -split[0] c

#@gmic invert : (+)
#@gmic : Compute the inverse of the selected matrices.
#@gmic : $ (0,1,0;0,0,1;1,0,0) --invert

#@gmic solve : [image] : (+)
#@gmic : Solve linear system AX = B for selected B-vectors and specified A-matrix.
#@gmic : If the system is under- or over-determined, least square solution is returned.
#@gmic : $ (0,1,0;1,0,0;0,0,1) (1;2;3) --solve[-1] [-2]

#@gmic svd : (+)
#@gmic : Compute SVD decomposition of selected matrices.
#@gmic : $ 10,10,1,1,'if(x==y,x+?(-0.2,0.2),0)' --svd

#@gmic transpose
#@gmic : Transpose selected matrices.
#@gmic : $ image.jpg --transpose
transpose :
  -e[^-1] "Transpose image$?."
  -v - -permute yxzc -v +

#@gmic trisolve : [image] : (+)
#@gmic : Solve tridiagonal system AX = B for selected B-vectors and specified tridiagonal A-matrix.
#@gmic : Tridiagonal matrix must be stored as a 3 column vector, where 2nd column contains the
#@gmic : diagonal coefficients, while 1st and 3rd columns contain the left and right coefficients.
#@gmic : $ (0,0,1;1,0,0;0,1,0) (1;2;3) --trisolve[-1] [-2]

#---------------------------------
#
#@gmic :: 3d rendering
#
#---------------------------------

#@gmic +3d : eq. to '-add3d'. : (+)

#@gmic add3d : tx,_ty,_tz : [object3d] : (noargs) : (+)
#@gmic : Shift selected 3d objects with specified displacement vector, or merge them with specified
#@gmic : 3d object, or merge all selected 3d objects together.
#@gmic : (eq. to '-+3d').
#@gmic : Default values: 'ty=tz=0'.
#@gmic : $ -sphere3d 10 -repeat 5 --add3d[-1] 10,{?(-10,10)},0 -color3d[-1] @{-RGB} -done -add3d
#@gmic : $ -repeat 20 -torus3d 15,2 -color3d[-1] @{-RGB} -mul3d[-1] 0.5,1 -if {$>%2} -rotate3d[-1] 0,1,0,90 -endif -add3d[-1] 70 -add3d -rotate3d[-1] 0,0,1,18 -done -double3d 0

#@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 @# --l[$>]
    -n3d -*3d {$6*min($1,$2)/1.5} -c3d
    ax=0 ay=0 az=0 frame=0
    -do
       --r3d 1,0,0,$ax -r3d[-1] 0,1,0,$ay -r3d[-1] 0,0,1,$az
       ax={$ax+$3} ay={$ay+$4} az={$az+$5}
       $1,$2,1,3,-1 -object3d[-1] [-2],50%,50%,0,1
       -if {narg("$7")}
         -to_rgba[-1] -replace_color[-1] 0,0,-1,-1,-1,255,64,64,64,0
         -o[-1] @{"-filename \"$7\","$>,$frame} frame={$frame+1}
       -else
         -replace[-1] -1,64
       -endif
       -w[-1] {w},{h},0,0,@{0,n} -wait 20 -k[0]
    -while {@!" && "!@{!,ESC}" && "!@{!,Q}} -rm -w 0
  -endl -done -v +

#@gmic apply_camera3d : pos_x,pos_y,pos_z,target_x,target_y,target_z,up_x,up_y,up_z
#@gmic : Apply 3d camera matrix to selected 3d objects.
#@gmic : Default values: 'target_x=0', 'target_y=0', 'target_z=0', 'up_x=0', 'up_y=-1' and 'up_z=0'.
apply_camera3d : -skip ${4=0},${5=0},${6=0},${7=0},${8=-1},${9=0}
  -e[^-1] "Apply 3d camera matrix to 3d object$?, with camera position ($1,$2,$3), target position ($4,$5,$6) and up-vector ($7,$8,$9)."
  -v -
  ({$4-$1}^{$5-$2}^{$6-$3})  # f.
  ($7^$8^$9)                 # up.
  -orientation[-2,-1]        # f/|f| and up/|up|.
  -_cross3d @-2,@-1          # s = f x up
  -_cross3d @-1,@-3          # u = s x f
  -rm[-3] -y[-3--1] x -mv[-2,-1] -3
  -a[-3--1] y -z[-1] 0,3  # Rotation matrix R.
  --3d[^-1] $1,$2,$3 -apply_pose3d[^-1] @-1 -rm[-1] --3d 0,0,800
  -v +

_cross3d :
  ({$2*$6-$3*$5};{$3*$4-$1*$6};{$1*$5-$2*$4})

#@gmic apply_pose3d : p1,..,p12
#@gmic : Apply 3d pose matrix to selected 3d objects.
#@gmic : $ -torus3d 100,20 -apply_pose3d 0.152437,1.20666,-0.546366,0,-0.535962,0.559129,1.08531,0,1.21132,0.0955431,0.548966,0,0,0,-206,1 -snapshot3d 400
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[$>] -if @{-is_3d}
    -s3d -r[2] 3,@{2,h/3},1,1,-1 -i[3] 1,@{2,h},1,1,1 -a[2,3] x
    -i[3] ($1,$5,$9;$2,$6,$10;$3,$7,$11;$4,$8,$12) -**[2,3]
    -r[2] 1,@{2,3*h},1,1,-1 -a y
  -else -error "Image ["{@#-$>-1}"] does not represent a 3d object."
  -endif -endl -done -v +

#@gmic axes3d : _size_x,_size_y,_size_z,_font_size>0,_label_x,_label_y,_label_z
#@gmic : Input 3d axes with specified sizes along the x,y and z orientations.
#@gmic : Default values: 'size_x=size_y=size_z=1', 'font_size=24', 'label_x=X', 'label_y=Y' and 'label_z=Z'.
#@gmic : $ -axes3d ,
axes3d : -check ${4=24}>0 -skip ${1=1},${2=$1},${3=$2},"${5=X},${6=Y},${7=Z}"
  -e[^-1] "Input 3d axes with sizes ($1,$2,$3)."
  -v - -l[]
  m={max(abs($1),abs($2),abs($3))/40} m2={2*$m} m3={1.2*$m2}
  -_axes3d "O",$4 --3d[-1] $m3,$m3,$m3
  -if $1
    -line3d 0,0,0,$1,0,0
    -cone3d $m,{2*$m},16 -r3d[-1] 0,1,0,-90 -+3d[-1] {$1-$m2},0,0
    -_axes3d "$5",$4 -+3d[-1] {$1+$m3},0,0
  -endif
  -if $2
    -line3d 0,0,0,0,$2,0
    -cone3d $m,{2*$m},16 -r3d[-1] 1,0,0,90 -+3d[-1] 0,{$2-$m2},0
    -_axes3d "$6",$4 -+3d[-1] 0,{$2+$m3},0
  -endif
  -if $3
    -line3d 0,0,0,0,0,$3
    -cone3d $m,{2*$m},16 -+3d[-1] 0,0,{$3-$m2}
    -_axes3d "$7",$4 -+3d[-1] 0,0,{$3+$m3}
  -endif
  -+3d -nm [3d\ axes]
  -endl -v +

_axes3d :
  0 -t[-1] "$1",2,0,$2,1,1 --dilate[-1] 3 -*[-2] 255 -r[-2] 100%,100%,1,3
  -i[-3] (67.5;73.5;109.5;103.5;51.5;100.5;1;1;0;0;0;1;0;-128;{w};{h};3)
  -i[-2] (-128;{w};{h};1) -y[-3,-1] y -a[-4--1] y

#@gmic b3d : eq. to '-background3d'. : (+)

#@gmic background3d : R,_G,_B : [image] : (no args) : (+)
#@gmic : Define background from specified color or existing image for interactive 3d viewer.
#@gmic : (eq. to '-b3d').
#@gmic : (no args) resets the background to default.

#@gmic box3d : _size_x,_size_y,_size_z
#@gmic : Input 3d box at (0,0,0), with specified geometry.
#@gmic : Default values: 'size_x=1' and 'size_z=size_y=size_x'.
#@gmic : $ -box3d 100,40,30 --primitives3d 1 -color3d[-2] @{-RGB}
box3d : -skip ${1=1},${2=$1},${3=$2}
  -e[^-1] "Input 3d box, with size ($1,$2,$3)."
  -v -
  1,86,1,1,\
  67.5,73.5,109.5,103.5,51.5,100.5,8,6,\
  0,0,0,$1,0,0,$1,$2,0,0,$2,0,\
  0,0,$3,$1,0,$3,$1,$2,$3,0,$2,$3,\
  4,0,3,2,1,4,4,5,6,7,4,0,1,5,4,4,3,7,6,2,4,0,4,7,3,4,1,2,6,5,\
  200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,\
  1,1,1,1,1,1
  -nm[-1] [3d\ box]
  -v +

#@gmic c3d : eq. to '-center3d'.
c3d :
  -_center3d

#@gmic center3d
#@gmic : Center selected 3d objects at (0,0,0).
#@gmic : (eq. to '-c3d').
#@gmic : $ -repeat 100 -circle3d {?(100)},{?(100)},{?(100)},2 -done -add3d -color3d[-1] 255,0,0 --center3d -color3d[-1] 0,255,0 -add3d
center3d :
  -_center3d

_center3d :
  -e[0--3] "Center 3d object$?."
  -v - -repeat @# -l[$>]
    n={i(0,6)}
    -if {$n>0}
      -sh 8,{7+3*$n},0,0 -r[-1] 3,{h/3},1,1,-1 -s[-1] x
      --[-3] @{-3,ia} --[-2] @{-2,ia} --[-1] {ia}
      -a[-3--1] x -y[-1] y -j[-2] [-1],0,8 -rm[-1]
    -endif
  -endl -done -v +

#@gmic circle3d : _x0,_y0,_z0,_radius>=0
#@gmic : Input 3d circle at specified coordinates.
#@gmic : Default values: 'x0=y0=z0=0' and 'radius=1'.
#@gmic : $ -repeat 500 a={$>*pi/250} -circle3d {cos(3*$a)},{sin(2*$a)},0,{$a/50} -color3d[-1] @{-RGB},0.4 -done -add3d
circle3d : -skip ${1=0},${2=0},${3=0},${4=1}
  -e[^-1] "Input 3d circle at position ($1,$2,$3) with radius $4."
  -v -
  r={$4/sqrt(3)}
  1,24,1,1,\
  67.5,73.5,109.5,103.5,51.5,100.5,2,1,\
  {$1-$r},{$2-$r},{$3-$r},\
  {$1+$r},{$2+$r},{$3+$r},\
  5,0,1,0,0,0,200,200,200,1
  -nm[-1] [3d\ circle]
  -v +

#@gmic circles3d : _radius>=0
#@gmic : Convert specified 3d objects to sets of 3d circles with specified radius.
#@gmic : $ image.jpg -luminance -resize2dy 40 -threshold 50% -* 255 -pointcloud3d -color3d[-1] 255,255,255 -circles3d 0.7
circles3d : -check ${1=1}>=0
  -e[^-1] "Convert 3d object$? to sets of 3d circles with radius $1."
  -v - -p3d 0 -repeat @# -l[$>]
    nbv=@{-1,6} nbp=@{-1,7}
    -if {$nbv&&$nbp}
      --3d {$1/2},0,0 --+3d $1,0,0 -+3d nbp2=@{-1,7}
      -s3d -=[1] $nbp,0,1
      -r[3] 2,$nbp2,1,1,-1 -columns[3] 1,1 -s[3] y,2 -i[3] 1,$nbp,1,1,5 -a[3-5] x -columns[3] 0,5 -y[3] y
      -rows[4] 0,{3*$nbp-1} -rows[5] 0,{$nbp-1} -a y
    -endif
  -endl -done -v +

#@gmic col3d : eq. to '-color3d'. : (+)

#@gmic color3d : R,_G,_B,_opacity : (+)
#@gmic : Set color and opacity of selected 3d objects.
#@gmic : (eq. to '-col3d').
#@gmic : Default value: 'opacity=(undefined)'.
#@gmic : $ -torus3d 100,10 -double3d 0 -repeat 7 --rotate3d[-1] 1,0,0,20 -color3d[-1] @{-RGB} -done -add3d

#@gmic colorcube3d
#@gmic : Input 3d color cube.
#@gmic : $ -colorcube3d -mode3d 2 --primitives3d 1
colorcube3d :
  -e[^-1] "Input 3d RGB-color cube."
  -v -
  (67.5;73.5;109.5;103.5;51.5;100.5;8;6)
  (0;0;0;\
   255;0;0;\
   255;255;0;\
   0;255;0;\
   0;0;255;\
   255;0;255;\
   255;255;255;\
   0;255;255)
  (12;0;3;2;1;0;0;0;63;63;63;63;0;\
   12;1;2;6;5;0;0;0;63;63;63;63;0;\
   12;0;4;7;3;0;0;63;0;63;63;0;63;\
   12;4;5;6;7;0;0;63;0;63;63;0;63;\
   12;0;1;5;4;0;0;63;0;63;63;0;63;\
   12;3;7;6;2;0;0;0;63;63;63;63;0)
  (0,255;0,255^0,0;255,255^0,0;0,0)
  (255,255;255,255^0,0;255,255^0,255;0,255)
  (0,0;0,0^0,0;255,255^0,255;0,255)
  (0,255;0,255^0,0;255,255^255,255;255,255)
  (0,255;0,255^0,0;0,0^0,0;255,255)
  (0,255;0,255^255,255;255,255^0,0;255,255)
  -r[-6--1] 64,64,1,3,3 -y[-6--1] y -i[-7--2] (-128;64;64;3)
  (1;1;1;1;1;1)
  -a[-16--1] y -nm[-1] [3d\ colorcube]
  -v +

#@gmic cone3d : _radius,_height,_nb_subdivisions>0
#@gmic : Input 3d cone at (0,0,0), with specified geometry.
#@gmic : Default value: 'radius=1','height=1' and 'nb_subdivisions=24'.
#@gmic : $ -cone3d 10,40 --primitives3d 1 -color3d[-2] @{-RGB}
cone3d : -check ${3=24}>0 -skip ${1=1},${2=1}
  -e[^-1] "Input 3d cone, with radius $1, height $2 and $3 subdivisions."
  -v -
  # Header.
  (67.5;73.5;109.5;103.5;51.5;100.5)
  ({$3+2};{2*$3})

  # Vertices.
  (0,0,0;0,0,$2)
  (0;{2*pi}) -r[-1] 1,{$3+1},1,1,3 -rows[-1] 0,{$3-1} --sin[-1] -cos[-2] -*[-2,-1] $1 -a[-2,-1] x -z[-1] 0,2 -a[-2,-1] y

  # Primitives.
  1,$3,1,1,'y' --shift[-1] 0,-1 -+[-2,-1] 2
  2,$3,1,1,3,0 [-2] [-4] -a[-3--1] x
  -i[-4] 2,$3,1,1,3,1 -a[-4--2] x
  -a[-2,-1] y

  # Colors / opacities.
  3,{h},1,1,200
  1,{h},1,1,1
  -y[-4--2] y -a[-6--1] y -nm[-1] [3d\ cone]
  -v +

#@gmic cup3d : _resolution>0
#@gmic : Input 3d cup object.
#@gmic : $ -cup3d ,
cup3d : -check ${1=128}>0
  -e[^-1] "Input 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 -b[-1] 0.1%
  -lathe3d[-1] $1,2 -nm[-1] [3d\ cup]
  -v +

#@gmic cylinder3d : _radius,_height,_nb_subdivisions>0
#@gmic : Input 3d cylinder at (0,0,0), with specified geometry.
#@gmic : Default value: 'radius=1','height=1' and 'nb_subdivisions=24'.
#@gmic : $ -cylinder3d 10,40 --primitives3d 1 -color3d[-2] @{-RGB}
cylinder3d : -check ${3=24}>0 -skip ${1=1},${2=1}
  -e[^-1] "Input 3d cylinder, with radius $1, height $2 and $3 subdivisions."
  -v -
  # Header.
  (67.5;73.5;109.5;103.5;51.5;100.5)
  ({2*$3+2};{3*$3})

  # Vertices.
  (0,0,0;0,0,$2)
  (0;{2*pi}) -r[-1] 1,{$3+1},1,1,3 -rows[-1] 0,{$3-1} --sin[-1] -cos[-2] -*[-2,-1] $1 -a[-2,-1] x
  --z[-1] 0,2 1,$3,1,1,$2 -a[-3,-1] x
  -a[-3--1] y

  # Primitives.
  1,$3,1,1,'y' --shift[-1] 0,-1 -+[-2,-1] 2
  2,$3,1,1,3,1 [-3] [-3] -a[-3--1] x
  2,$3,1,1,3,0 [-3] [-5] -+[-2,-1] $3 -a[-3--1] x
  --+[-4,-3] $3 -i[-7] 1,$3,1,1,4 -rv[-6,-5] -a[-7--5,-2,-1] x

  # Colors / opacities.
  3,{3*$3},1,1,200
  1,{h},1,1,1
  -y[-6--2] y -a[-8--1] y -nm[-1] [3d\ cylinder]
  -v +

#@gmic distribution3d
#@gmic : Get 3d color distribution of selected images.
#@gmic : $ image.jpg -distribution3d -colorcube3d -primitives3d[-1] 1 -add3d
distribution3d :
  -e[^-1] "Get 3d color distribution of image$?."
  -v - -to_rgb -permute "cxyz" -y y
  -repeat @# -l[$>]
    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 -y[-1] y     # Primitives.
    [-2]                                              # Colors.
    1,$nbp,1,1,1                                      # Opacities.
    -a y -nm[-1] [3d\ distribution]                   # Build 3d object.
  -endl -done -v +

#@gmic /3d : eq. to '-div3d'. : (+)

#@gmic div3d : factor : factor_x,factor_y,_factor_z : (+)
#@gmic : Scale selected 3d objects isotropically or anisotropically, with the inverse of specified
#@gmic : factors.
#@gmic : (eq. to '-/3d').
#@gmic : Default value: 'factor_z=0'.
#@gmic : $ -torus3d 5,2 -repeat 5 --add3d[-1] 12,0,0 -div3d[-1] 1.2 -color3d[-1] @{-RGB} -done -add3d

#@gmic db3d : eq. to '-double3d'. : (+)

#@gmic double3d : is_doubled={ 0 | 1 } : (+)
#@gmic : Enable/disable double-sided mode for 3d rendering.
#@gmic : (eq. to '-db3d').
#@gmic : $ -mode3d 1 -repeat 2 -torus3d 100,30 -rotate3d[-1] 1,1,0,60 -double3d $> -snapshot3d[-1] 400 -done

#@gmic elevation3d : z-factor : [elevation_map] : 'formula' : (no args) : (+)
#@gmic : Build 3d elevation of selected images, with a specified elevation map.
#@gmic : When invoked with (no args) or 'z-factor', the elevation map is computed as the pointwise L2 norm of the
#@gmic : pixel values. Otherwise, the elevation map is taken from the specified image or formula.
#@gmic : $ image.jpg -blur 5 -elevation3d 0.5
#@gmic : $ 128,128,1,3,?(255) -plasma 10,3 -blur 4 -sharpen 10000 -elevation3d[-1] 'X=(x-64)/6;Y=(y-64)/6;100*exp(-(X^2+Y^2)/30)*abs(cos(X)*sin(Y))'

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

#@gmic extrude3d : _depth>0,_resolution>0,_smoothness[%]>=0
#@gmic : Generate extruded 3d object from selected binary XY-profiles.
#@gmic : Default values: 'depth=16', 'resolution=1024' and 'smoothness=0.5%'.
#@gmic : $ image.jpg -threshold 50% -extrude3d 16
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 @# -l[$>] nm=@{0,n}
    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)}
    -b $3,0 -r $wr,$hr,1,1,2 -expand_xyz 1,0
    -isosurface3d 50% -*3d 1,1,$fact -rv3d
  -nm $nm,1 -endl -done -v +

#@gmic f3d : eq. to '-focale3d'. : (+)

#@gmic focale3d : focale : (+)
#@gmic : Set 3d focale.
#@gmic : (eq. to '-f3d').
#@gmic : Set 'focale' to 0 to enable parallel projection (instead of perspective).
#@gmic : Set negative 'focale' will disable 3d sprite zooming.
#@gmic : $ -repeat 5 -torus3d 100,30 -rotate3d[-1] 1,1,0,60 -focale3d {$<*90} -snapshot3d[-1] 400 -done -remove[0]

#@gmic gaussians3d : _size>0,_opacity
#@gmic : Convert selected 3d objects into set of 3d gaussian-shaped sprites.
#@gmic : $ image.jpg -r2dy 32 -distribution3d -gaussians3d 20 -colorcube3d -primitives3d[-1] 1 -+3d
gaussians3d : -check "${1=32}>0" -skip ${2=0.3}
  -e[^-1] "Convert 3d object$? into sets of gaussian-shaped 3d sprites, with size $1 and opacity $2."
  -v - -p3d 2 -p3d 0 -repeat @# -l[$>] nm=@{0,n} -s3d
    nbv={h} -rm[-1] (-128;$1;$1;1)
    $1,$1 -gaussian[-1] 35%,35%,0 -c[-1] 30%,100% -n[-1] 0,$2 -y[-1] y -a[-2,-1] y  # First opacity is generated.
    -if {$nbv>1} 4,{$nbv-1},1,1,-128,0,0,0 -y[-2,-1] y -a[-2,-1] y -endif           # Other ones are shared copies of the first one.
    -a y
  -nm $nm,1 -endl -done -v +

#@gmic gmic3d
#@gmic : Input a 3d G'MIC logo.
#@gmic : $ -gmic3d --primitives3d 1
gmic3d :
  -e[^-1] "Input 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 -col3d[-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
    -r3d[-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] -nm[-1] [3d\ gmic]
  -v +

#@gmic gyroid3d : _resolution>0,_zoom
#@gmic : Input 3d gyroid at (0,0,0), with specified resolution.
#@gmic : Default values: 'resolution=32' and 'zoom=5'.
#@gmic : $ -gyroid3d 48 --primitives3d 1
gyroid3d : -check ${1=32}>0 -skip ${2=5}
  -e[^-1] "Input 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] -nm[-1] [3d\ gyroid]
  -v +

#@gmic histogram3d
#@gmic : Get 3d color histogram of selected images.
#@gmic : $ image.jpg -histogram3d -colorcube3d -primitives3d[-1] 1 -add3d
histogram3d :
  -e[^-1] "Get 3d color histogram of image$?."
  -v - -to_rgb -repeat @#
    -r[-1] {w*h},3,1,1,-1 -pointcloud[-1] 1 -n[-1] 0,255 -map[-1] 3 -pointcloud3d[-1] -nm[-1] "[3d histogram]"
  -mv[-1] 0 -done -v +

#@gmic image6cube3d
#@gmic : Generate 3d mapped cubes from 6-sets of selected images.
#@gmic : $ image.jpg -animate flower,"30,0","30,5",6 -image6cube3d
image6cube3d :
  -e[^-1] "Generate 3d mapped cubes from image$?."
  -v - M={max(@{-max_wh})} -r $M,$M,1,3 -imageplane3d -n3d -c3d -repeat {int(@#/6)}
    -+3d[-6] 0,0,-0.5
    -r3d[-5] 1,0,0,180 -+3d[-5] 0,0,0.5
    -r3d[-4] 0,1,0,-90 -+3d[-4] -0.5,0,0
    -r3d[-3] 0,1,0,90 -+3d[-3] 0.5,0,0
    -r3d[-2] 1,0,0,90 -+3d[-2] 0,-0.5,0
    -r3d[-1] 1,0,0,-90 -+3d[-1] 0,0.5,0
    -+3d[-6--1] -nm[-1] "[3d image cube]"
  -mv[-1] 0 -done -v +

#@gmic imagecube3d
#@gmic : Generate 3d mapped cubes from selected images.
#@gmic : $ image.jpg -imagecube3d
imagecube3d :
  -e[^-1] "Generate 3d mapped cubes from image$?."
  -v - -slices 50% -to_rgb -repeat @# -l[$>] nm=@{0,n}
    w1={w-1} h1={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;$h1;$w1;$h1;$w1;0;\    # Primitives description.
            12;1;2;6;5;0;0;0;$h1;$w1;$h1;$w1;0;\
            12;5;6;7;4;0;0;0;$h1;$w1;$h1;$w1;0;\
            12;4;7;3;0;0;0;0;$h1;$w1;$h1;$w1;0;\
            12;4;0;1;5;0;0;0;$h1;$w1;$h1;$w1;0;\
            12;3;7;6;2;0;0;0;$h1;$w1;$h1;$w1;0;\
            -128;{w};{h};{s})       # Texture map for the first face.
    -y[-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 y
  -nm $nm,1 -endl -done -v +

#@gmic imageplane3d
#@gmic : Generate 3d mapped planes from selected images.
#@gmic : $ image.jpg -imageplane3d
imageplane3d :
  -e[^-1] "Generate 3d mapped planes from image$?."
  -v - -slices 50% -to_rgb -repeat @# -l[$>] nm=@{0,n}
    w1={w-1} h1={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;0;0;\                              # Vertex coordinates.
            {w};0;0;\
            {w};{h};0;\
            {0};{h};0;\
            12;0;3;2;1;0;0;0;$h1;$w1;$h1;$w1;0;\ # Primitives description.
            -128;{w};{h};{s})                    # Texture map.
    -y[-1] y
    (1)  # Opacity.
    -a y
  -nm $nm,1 -endl -done -v +

#@gmic imagepyramid3d
#@gmic : Generate 3d mapped pyramides from selected images.
#@gmic : $ image.jpg -imagepyramid3d
imagepyramid3d :
  -e[^-1] "Generate 3d mapped pyramids from image$?."
  -v - -repeat @# -l[$>] nm=@{0,n}
    w1={w-1} h1={h-1} w2={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;$h1;$w1;$h1;$w1;0;\    # Primitives description.
            9;0;4;3;0;$h1;$w2;0;$w1;$h1;\
            9;1;4;0;0;$h1;$w2;0;$w1;$h1;\
            9;2;4;1;0;$h1;$w2;0;$w1;$h1;\
            9;3;4;2;0;$h1;$w2;0;$w1;$h1;\
            -128;{w};{h};{s})                   # Texture map for the first face.
    -y[-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 y
  -nm $nm,1 -endl -done -v +

#@gmic imagerubik3d : _xy_tiles>=1,0<=xy_shift<=100,0<=z_shift<=100
#@gmic : Generate 3d mapped rubik's cubes from selected images.
#@gmic : Default values: 'xy_tiles=3', 'xy_shift=5' and 'z_shift=5'.
#@gmic : $ image.jpg -imagerubik3d ,
imagerubik3d : -check "${1=3}>=1 && ${2=5}>=0 && $2<=100 && ${3=5}>=0 && $3<=100"
  -e[^-1] "Generate 3d mapped rubik's cubes from image$? with $1 xy-tiles, xy-shift $2 and z-shift $3."
  -v - -repeat @# -l[$>] nm=@{0,n}
    # Generate primary 3d side.
    ({'CImg3d'}) -+[-1] 0.5
    (8,5)
    (0,0,0;\
     100,0,0;\
     100,100,0;\
     0,100,0;\
     $2,$2,{-$3};\
     {100-$2},$2,{-$3};\
     {100-$2},{100-$2},{-$3};\
     $2,{100-$2},{-$3})
    (4,4,7,6,5;\
     4,0,4,5,1;\
     4,3,2,6,7;\
     4,0,3,7,4;\
     4,1,5,6,2)
    3,5,1,1,200
    1,5,1,1,1
    -y[-6--1] y -a[-6--1] y
    -repeat {$1-1} --+3d[-1] 100 -done -+3d[-$1--1]   # Duplicate along X
    -repeat {$1-1} --+3d[-1] 0,100 -done -+3d[-$1--1] # Duplicate along Y
    -t3d[-1] [-2] -rm[-2]
    -/3d[-1] $1 --3d[-1] 50,50,50
    --r3d[-1] 0,1,0,-90 --r3d[-1] 0,1,0,-90 --r3d[-1] 0,1,0,-90  # Generate the 5 other sides.
    --r3d[-1] 0,0,1,-90 --r3d[-1] 0,0,1,180
    -+3d
  -nm $nm,1 -endl -done -v +

#@gmic imagesphere3d : _resolution1>=3,_resolution2>=3
#@gmic : Generate 3d mapped sphere from selected images.
#@gmic : Default values: 'resolution1=32' and 'resolutions2=16'.
#@gmic : $ image.jpg -imagesphere3d 32,16
imagesphere3d : -check "${1=32}>=3 && ${2=16}>=3"
  -e[^-1] "Generate 3d mapped sphere from image$?, with resolutions ($1,$2)."
  -v - -to_rgb -repeat @# -l[$>] nm=@{0,n}

    # Generate object header.
    tw={w-1} th={h-1}                    # Maximum texture xy-coordinates.
    nbv={2+$1*($2-2)}                    # Number of vertices.
    nbp={$1*($2-1)}                      # Number of primitives.
    (67.5;73.5;109.5;103.5;51.5;100.5;\  # Magick number for CImg3d.
     $nbv;$nbp)                          # Number of vertices and primitives.

    # Define sphere vertices.
    (0;0;1) (0;0;-1) (0,{2*pi};0,{2*pi}^0,0;{pi},{pi})
    -r[-1] {$1+1},$2,1,2,3 -z[-1] 0,1,{w-2},{h-2} -s[-1] c
    --sin[-1] --sin[-3] -*[-2,-1] --cos[-2] -sin[-3] -cos[-4] -*[-4,-3]
    -a[-3--1] c -permute[-1] cxyz -y[-1] y -a[-3--1] y

    # Define sphere primitives (triangles and quadrangles).
    -repeat $1
      tx0={$>*$tw/$1} tx1={($>+1)*$tw/$1} ty1={$th/($2-1)}
      (9;0;{2+$>};{2+($>+1)%$1};{$tw/2};0;$tx0;$ty1;$tx1;$ty1) # Textured triangle from 1st pole.
      -repeat {$2-3}
        ty0=$ty1 ty1={($>+2)*$th/($2-1)} i0={2+$>*$1+@{>,-2}} i1={2+$>*$1+(@{>,-2}+1)%$1}
        (12;$i0;{$i0+$1};{$i1+$1};$i1;$tx0;$ty0;$tx0;$ty1;$tx1;$ty1;$tx1;$ty0) # Textured quadrangle.
      -done
      (9;1;{2+$1*($2-3)+($>+1)%$1};{2+$1*($2-3)+$>};{$tw/2};$th;$tx1;$ty1;$tx0;$ty1) # Textured triangle from 2nd pole.
    -done
    -a[-$nbp--1] y

    # Define sphere textures, opacities and generate object.
    -mv[-4] @# -i[-2] (-128;{w};{h};3) -y[-1] y 1,{4*($nbp-1)},1,1,-128,0,0,0 1,$nbp,1,1,1 -a y
  -nm $nm,1 -endl -done -v +

#@gmic isoline3d : isovalue[%] : 'formula',value,_x0,_y0,_x1,_y1,_size_x>0[%],_size_y>0[%] : (+)
#@gmic : Extract 3d isolines with specified value from selected images or from specified formula.
#@gmic : Default values: 'x0=y0=-3', 'x1=y1=3' and 'size_x=size_y=256'.
#@gmic : $ image.jpg -blur 1 -isoline3d 50%
#@gmic : $ -isoline3d 'X=x-w/2;Y=y-h/2;(X^2+Y^2)%20',10,-10,-10,10,10

#@gmic isosurface3d : isovalue[%] : 'formula',value,_x0,_y0,_z0,_x1,_y1,_z1,_size_x>0[%],_size_y>0[%],_size_z>0[%] : (+)
#@gmic : Extract 3d isosurfaces with specified value from selected images or from specified formula.
#@gmic : Default values: 'x0=y0=z0=-3', 'x1=y1=z1=3' and 'size_x=size_y=size_z=32'.
#@gmic : $ image.jpg -resize2dy 128 -luminance -threshold 50% -expand_z 2,0 -blur 1 -isosurface3d 50% -mul3d 1,1,30
#@gmic : $ -isosurface3d 'x^2+y^2+abs(z)^abs(4*cos(x*y*z*3))',3

#@gmic label_points3d : _label_size>0,_opacity
#@gmic : Add a numbered label to all vertices of selected 3d objects.
#@gmic : Default values: 'label_size=13' and 'opacity=0.8'.
#@gmic : $ -torus3d 100,40,6,6 -label_points3d 24,1 -mode3d 1
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.
      0 -t[-1] $>,0,0,$1,1,255,255,255 -autocrop[-1] 0
      -i[-2] (-128;{w};{h};3) -y[-1] y
    -done
    -repeat $nbp                                                # Create texture masks as primitive opacities.
      0 -t[-1] $>,0,0,$1,1,$2 -autocrop[-1] 0
      -i[-2] (-128;{w};{h};1) -y[-1] y
    -done
    -a y  # Merge final object data.
    -endl
    -+3d[$>,-1]
  -done -v +

#@gmic lathe3d : _resolution>0,_smoothness[%]>=0,_max_angle>=0
#@gmic : Generate 3d object from selected binary XY-profiles.
#@gmic : Default values: 'resolution=128', 'smoothness=0.5%' and 'max_angle=361'.
#@gmic : $ 300,300 -rand -1,1 -blur 40 -sign -normalize 0,255 -lathe3d ,
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°."
  -v - tmax={($3-180)*pi/180} -norm -n 0,1 -autocrop 0 -repeat @# -l[$>]
    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)^2+($hr)^2)/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 10,0 -b $2 -isosurface3d 50% -rv3d
  -endl -done -v +

#@gmic l3d : eq. to '-light3d'. : (+)

#@gmic light3d : position_x,position_y,position_z : [texture] : (no args) : (+)
#@gmic : Set the light coordinates or the light texture for 3d rendering.
#@gmic : (eq. to '-l3d').
#@gmic : (noargs) resets the 3d light to default.
#@gmic : $ -torus3d 100,30 -double3d 0 -specs3d 1.2 -repeat 5 -light3d {$>*100},0,-300 --snapshot3d[0] 400 -done -remove[0]

#@gmic line3d : x0,y0,z0,x1,y1,z1
#@gmic : Input 3d line at specified coordinates.
#@gmic : $ -repeat 100 a={$>*pi/50} -line3d 0,0,0,{cos(3*$a)},{sin(2*$a)},0 -color3d[-1] @{-RGB} -done -add3d
line3d :
  -e[^-1] "Input 3d line (${1-3})-(${4-6})."
  -v - 1,21,1,1,67.5,73.5,109.5,103.5,51.5,100.5,2,1,${1-6},2,0,1,200,200,200,1 -nm[-1] [3d\ line] -v +

#@gmic lissajous3d : resolution>1,a,A,b,B,c,C
#@gmic : Input 3d lissajous curves (x(t)=sin(a*t+A*2*pi),y(t)=sin(b*t+B*2*pi),z(t)=sin(c*t+C*2*pi)).
#@gmic : Default values: 'resolution=1024', 'a=2', 'A=0', 'b=1', 'B=0', 'c=0' and 'C=0'.
#@gmic : $ -lissajous3d ,
lissajous3d : -check ${1=1024}>1 -skip ${2=2},${3=0},${4=1},${5=0},${6=0},${7=0}
  -e[^-1] "Input 3d lissajous curve, with resolution $1, (a,A)=($2,$3), (b,B)=($4,$5) and (c,C)=($6,$7)."
  -v -
  res={round($1)}

  # Define object header and vertices.
  (67.5;73.5;109.5;103.5;51.5;100.5;$res;{$res-1})
  (0,{2*pi}) -r[-1] $res,1,1,1,3 [-1]x2
  -*[-3] $2 -+[-3] {$3*2*pi} -*[-2] $4 -+[-2] {$5*2*pi} -*[-1] $6 -+[-1] {$7*2*pi}
  -a[-3--1] y -sin[-1] -transpose[-1] -r[-1] 1,{w*h},1,1,-1

  # Define object primitives, colors and opacities.
  1,{$res-1},1,1,2 (0;{$res-2}) -r[-1] 1,{$res-1},1,1,3 --+[-1] 1 -a[-3--1] x -round[-1] 1 -r[-1] 1,{w*h},1,1,-1
  1,{3*($res-1)},1,1,200 1,{$res-1},1,1,1 -a[-5--1] y -nm[-1] [3d\ lissajou]
  -v +

#@gmic m3d : eq. to '-mode3d'. : (+)

#@gmic mode3d : mode : (+)
#@gmic : Set static 3d rendering mode.
#@gmic : (eq. to '-m3d').
#@gmic : 'mode' can be { -1=bounding-box | 0=dots | 1=wireframe | 2=flat | 3=flat-shaded | 4=gouraud-shaded | 5=phong-shaded }.");
#@gmic : Bounding-box mode ('mode==1') is active only for the interactive 3d viewer.
#@gmic : $ (0,1,2,3,4,5) -double3d 0 -repeat {w} -torus3d 100,30 -rotate3d[-1] 1,1,0,60 -mode3d @{0,$>} -snapshot3d[-1] 300 -done -remove[0]

#@gmic md3d : eq. to '-moded3d'. : (+)

#@gmic moded3d : mode : (+)
#@gmic : Set dynamic 3d rendering mode for interactive 3d viewer.
#@gmic : (eq. to '-md3d').
#@gmic : 'mode' can be { -1=bounding-box | 0=dots | 1=wireframe | 2=flat | 3=flat-shaded | 4=gouraud-shaded | 5=phong-shaded }.

#@gmic *3d : eq. to '-mul3d'. : (+)

#@gmic mul3d : factor : factor_x,factor_y,_factor_z : (+)
#@gmic : Scale selected 3d objects isotropically or anisotropically, with specified factors.
#@gmic : (eq. to '-*3d').
#@gmic : Default value: 'factor_z=0'.
#@gmic : $ -torus3d 5,2 -repeat 5 --add3d[-1] 10,0,0 -mul3d[-1] 1.2 -color3d[-1] @{-RGB} -done -add3d

#@gmic n3d : eq. to '-normalize3d'.
n3d :
  -_normalize3d

#@gmic normalize3d
#@gmic : Normalize selected 3d objects to unit size.
#@gmic : (eq. to '-n3d').
#@gmic : $ -repeat 100 -circle3d {?(3)},{?(3)},{?(3)},0.1 -done -add3d -color3d[-1] 255,0,0 --normalize3d[-1] -color3d[-1] 0,255,0 -add3d
normalize3d :
  -_normalize3d

_normalize3d :
  -e[0--3] "Normalize size of 3d object$?."
  -v - -repeat @# -l[$>]
    n={i(0,6)}
    -if {$n>0}
      -sh 8,{7+3*$n},0,0 -r[-1] 3,{h/3},1,1,-1 -s[-1] x
      -sh[-4] 8,{7+3*$n},0,0 -/[-1] {val=max(@{-3,iM}-@{-3,im},@{-2,iM}-@{-2,im},iM-im);if(val,val,1)}
      -rm[-4--1]
    -endif
  -nm @{0,n},1 -endl -done -v +

#@gmic o3d : eq. to '-opacity3d'. : (+)

#@gmic opacity3d : opacity : (+)
#@gmic : Set opacity of selected 3d objects.
#@gmic : (eq. to '-o3d').
#@gmic : $ -torus3d 100,10 -double3d 0 -repeat 7 --rotate3d[-1] 1,0,0,20 -opacity3d[-1] {?} -done -add3d

#@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 : Input 3d object from specified parametric surface (x(a,b),y(a,b),z(a,b)).
#@gmic : Default values: 'x=(2+cos(b))*sin(a)', 'y=(2+cos(b))*cos(a)', 'c=sin(b)', 'amin=-pi', 'amax='pi', 'bmin=-pi', 'bmax='pi',
#@gmic : 'res_a=512', 'res_b=res_a', 'res_x=64', 'res_y=res_x', 'res_z=res_y', 'smoothness=2%' and 'isovalue=10%'.
#@gmic : $ -parametric3d ,
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] "Input 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] 1 -r[-1] $10,$11,$12,1,0 -b[-1] $13,0
  -isosurface3d[-1] $14
  -c3d[-1] -n3d[-1] -*3d[-1] {$xmax-$xmin},{$ymax-$ymin},{$zmax-$zmin} -nm[-1] [3d\ parametric]
  -v +

#@gmic pca_patch3d : _patch_size>0,_M>0,_N>0,_normalize_input={ 0 | 1 },_normalize_output={ 0 | 1 },_lambda_xy
#@gmic : Get 3d patch-pca representation of selected images.
#@gmic : The 3d patch-pca is estimated from M patches on the input image, and displayed as a cloud of N 3d points.
#@gmic : Default values: 'patch_size=7', 'M=1000', 'N=3000', 'normalize_input=1', 'normalize_output=0', and 'lambda_xy=0'.
#@gmic : $ image.jpg -pca_patch3d 7
pca_patch3d : -check "isint(${1=7}) && $1>0 && isint(${2=1000}) && $2>0 && isint(${3=3000}) && $3>0" -skip ${4=1},${5=0},${6=0}
  -e[^-1] "Get 3d patch-pca representation"@{"-if {@#>1} -u s -else -u \"\" -endif"}" of image$?, from $2 $1x$1 input patchs,
           with $3 output patchs, input normalization "@{"-if $4 -u enabled -else -u disabled -endif"}", output normalization
          "@{"-if $5 -u enabled -else -u disabled -endif"}" and lambda_xy $6."
  -v -
  P1={int($1/2)}       # Backward half-patch size.
  P2={$1-$P1-1}        # Forward half-patch size.

  -n 0,255 -round 1
  -repeat @# -l[$>] nm=@{0,n}
    s={s}

    # Pick set of M random located patchs.
    -repeat $2
      x={round(?(@{0,w}))}
      y={round(?(@{0,h}))}
      ({$6*$x};{$6*$y})
      --z[0] {$x-$P1},{$y-$P1},{$x+$P2},{$y+$P2},1
      -y[-1] y -a[-2,-1] y
    -done

    # Normalize patch coordinates by using average and standard deviation.
    --+[^0] -/[-1] $2 --[1--2] [-1] -rm[-1]
    -a[^0] x
    -if $4 -l[-1] -s y -/ 'sqrt(1e-8+iv)' -a y -endl -endif

    # Do PCA for dimension reduction.
    --transpose[-1] -**[-2,-1]
    -eigen[-1] -rows[-2] 0,2 -columns[-1] 0,2 -transpose[-1]
    -if $5 -sqrt[-2] -/[-2] @{-2,M} -r[-2] [-1] -/[-1] [-2] -endif
    -rm[-2]

    # Pick set of N random located patchs.
    -repeat $3
      x={round(?(@{0,w}))}
      y={round(?(@{0,h}))}
      ({$6*$x};{$6*$y})
      --z[0] {$x-$P1},{$y-$P1},{$x+$P2},{$y+$P2},1
      -y[-1] y -a[-2,-1] y
    -done

    # Generate 3d representation of the projected patch set.
    --a[2--1] x -**[1,-1] -transpose[1]                    # Vertex coordinates.
    -rows[2--1] 2,100%                                     # Colors
    -if {$s!=3}
      -r[2--1] $1,$1,1,{min(3,$s)},-1
      -r[2--1] $1,$1,1,3,{if($s!=1,0,1)}
      -y[2--1] y
    -endif
    -i[2--2] (-128;$1;$1;3) -a[2--1] y
    -rm[0]                                                 # Remove input image (now useless).
    -i[0] ({'CImg3d'})                                     # Header.
    -i[1] ($3;$3)                                          # Geometry.
    -i[3] 2,$3,1,1,if(x==0,1,y)                            # Primitives.
    1,$3,1,1,1                                             # Opacities.
    -y y -a[-6--1] y                                       # Merge as a 3d object.

  -nm $nm,1 -endl -done -v +

#@gmic plane3d : _size_x,_size_y,_nb_subdivisions_x>0,_nb_subdisivions_y>0
#@gmic : Input 3d plane at (0,0,0), with specified geometry.
#@gmic : Default values: 'size_x=1', 'size_y=size_x' and 'nb_subdivisions_x=nb_subdivisions_y=24'.
#@gmic : $ -plane3d 50,30 --primitives3d 1 -color3d[-2] @{-RGB}
plane3d : -check "${3=24}>0 && ${4=24}>0" -skip ${1=1},${2=$1}
  -e[^-1] "Input 3d plane, with size (${1,2}) and subdivisions (${3,4})."
  -v - {$3+1},{$4+1} -elevation3d[-1] 0 -*3d[-1] {$1/$3},{$2/$4} -col3d[-1] 200 -nm[-1] [3d\ plane] -v +

#@gmic point3d : x0,y0,z0
#@gmic : Input 3d point at specified coordinates.
#@gmic : $ -repeat 1000 a={$>*pi/500} -point3d {cos(3*$a)},{sin(2*$a)},0 -color3d[-1] @{-RGB} -done -add3d
point3d :
  -e[^-1] "Input 3d point ($1,$2,$3)."
  -v - 1,17,1,1,67.5,73.5,109.5,103.5,51.5,100.5,1,1,${1-3},1,0,200,200,200,1 -nm[-1] [3d\ point] -v +

#@gmic pointcloud3d
#@gmic : Convert selected planar or volumetric images to 3d point clouds.
#@gmic : $ image.jpg -luminance -resize2dy 100 -threshold 50% -* 255 -pointcloud3d -color3d[-1] 255,255,255
pointcloud3d :
  -e[^-1] "Convert image$? to 3d point clouds."
  -v - -repeat @# -l[$>] nm=@{0,n}
    -s z -repeat @# -l[$>]
      --norm -!=[-1] 0
      -i[-2] (1,{w};1,{w}^1,1;{h},{h}) -r[-2] [-1],[-1],1,2,3 -*[-2,-1] -round[-1] -permute[-1] cxyz
      -l[-1] -s -,0 -a y is_points=@# -endl
      -if $is_points
        --[-1] 1 -r[-1] 2,{h/2},1,1,-1 -permute[-1] cyzx --warp[-2] [-1],0,0 -rm[-3]
        -permute[-2] cyzx -i[-2] 1,{h},1,1,$> -a[-3,-2] x    # Coordinates.
        -i[-3] ({'CImg3d'}) -i[-3] ({h},{h})                 # Header and size.
        -i[-2] 1,{h},1,1,1 -i[-2] 1,{h},1,1,y -a[-3,-2] x    # Primitives.
        -permute[-1] cyzx                                    # Colors.
        -if {w==1} -r[-1] 3,{h},1,1
        -elif {w>3} -i[-2] 4,{h},1,1,-128,1,1,{w} -a[-2,-1] x
        -else -r[-1] 3,{h},1,1,0
        -endif
        1,{h},1,1,1                                          # Opacities.
        -y[-6--1] y -a[-6--1] y
      -else -rm -empty3d
      -endif
      -endl -done
    -+3d
  -nm $nm,1 -endl -done -v +

#@gmic pose3d : value1,..,value16 : (noargs) : (+)
#@gmic : Set the coefficients of the 3d pose matrix.
#@gmic : (noargs) resets the 3d pose matrix to default.

#@gmic p3d : eq. to '-primitives3d'. : (+)

#@gmic primitives3d : mode : (+)
#@gmic : Convert primitives of selected 3d objects.
#@gmic : (eq. to '-p3d').
#@gmic : 'mode' can be { 0=points | 1=segments | 2=non-textured }.
#@gmic : $ -sphere3d 30 -primitives3d 1 -torus3d 50,10 -color3d[-1] @{-RGB} -add3d

#@gmic projections3d : _x[%],_y[%],_z[%],_is_bounding_box={ 0 | 1 }
#@gmic : Generate 3d xy,xz,yz projection planes from specified volumetric images.
projections3d : -skip ${1=50%},${2=50%},${3=50%},${4=1}
  -e[^-1] "Generate 3d xy,xz,yz projection planes from image$?."
  -v - -n 0,255 -repeat @# -l[$>]
    w={w} h={h} d={d}
    x={if(@{"-is_percent $1"},$1*w,$1)}
    y={if(@{"-is_percent $2"},$2*h,$2)}
    z={if(@{"-is_percent $3"},$3*d,$3)}
    --rows $2,$2 -r[-1] {w},{d},1,100%,-1
    --columns[-2] $1,$1 -permute[-1] zyxc
    -slices[-3] $3,$3 -r[-3--1] 100%,100%,1,3
    -imageplane3d[-3--1]
    -r3d[-1] 0,1,0,90 -r3d[-2] 1,0,0,-90
    -+3d[-3] 0,0,$z -+3d[-2] 0,$y,0 -+3d[-1] $x,0,0
    -+3d[-3--1] -o3d[-1] 0.8
    -if $4 -box3d $w,$h,$d -p3d[-1] 1 -o3d[-1] 0.4 -+3d[-2,-1] -endif
  -endl -done -v +

#@gmic pyramid3d : width,height
#@gmic : Input 3d pyramid at (0,0,0), with specified geometry.
#@gmic : $ -pyramid3d 100,100 --primitives3d 1 -color3d[-2] @{-RGB}
pyramid3d :
  -e[^-1] "Input 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 -nm[-1] [3d\ pyramid]
  -v +

#@gmic quadrangle3d : x0,y0,z0,x1,y1,z1,x2,y2,z2,x3,y3,z3
#@gmic : Input 3d quadrangle at specified coordinates.
#@gmic : $ -quadrangle3d -10,-10,10,10,-10,10,10,10,10,-10,10,10 -repeat 10 --rotate3d[-1] 0,1,0,30 -color3d[-1] @{-RGB},0.6 -done -add3d -mode3d 2
quadrangle3d :
  -e[^-1] "Input 3d quadrangle ($1,$2,$3)-($4,$5,$6)-($7,$8,$9)-($10,$11,$12)."
  -v - 1,29,1,1,67.5,73.5,109.5,103.5,51.5,100.5,4,1,${1-12},4,0,1,2,3,200,200,200,1 -nm[-1] [3d\ quadrangle] -v +

#@gmic rv3d : eq. to '-reverse3d'. : (+)

#@gmic reverse3d : (+)
#@gmic : Reverse primitive orientations of selected 3d objects.
#@gmic : (eq. to '-rv3d').
#@gmic : $ -torus3d 100,40 -double3d 0 --reverse3d

#@gmic r3d : eq. to '-rotate3d'. : (+)

#@gmic rotate3d : u,v,w,angle : (+)
#@gmic : Rotate selected 3d objects around specified axis with specified angle (in deg.).
#@gmic : (eq. to '-r3d').
#@gmic : $ -torus3d 100,10 -double3d 0 -repeat 7 --rotate3d[-1] 1,0,0,20 -done -add3d

#@gmic rotation3d : u,v,w,angle
#@gmic : Input 3x3 rotation matrix with specified axis and angle (in deg).
#@gmic : $ -rotation3d 1,0,0,0 -rotation3d 1,0,0,90 -rotation3d 1,0,0,180
rotation3d :
  -e[^-1] "Input 3d rotation matrix around axis ($1,$2,$3) with angle $4°."
  -v -
  ($1^$2^$3^0) -orientation[-1] -y[-1] x -*[-1] {sin($4*pi/360)} -=[-1] {cos($4*pi/360)},3
  xx={i(0)*i(0)} xy={i(0)*i(1)} xz={i(0)*i(2)} xw={i(0)*i(3)}
  yy={i(1)*i(1)} yz={i(1)*i(2)} yw={i(1)*i(3)}
  zz={i(2)*i(2)} zw={i(2)*i(3)}
  -rm[-1]
  ({1-2*($yy+$zz)},{2*($xy+$zw)},{2*($xz-$yw)};\
   {2*($xy-$zw)},{1-2*($xx+$zz)},{2*($yz+$xw)};\
   {2*($xz+$yw)},{2*($yz-$xw)},{1-2*($xx+$yy)})
  -nm[-1] [3d\ rotation]
  -v +

#@gmic sierpinski3d : _recursion_level>=0,_width,_height
#@gmic : Input 3d Sierpinski pyramid.
#@gmic : $ -sierpinski3d 3 --primitives3d 1 -color3d[-2] @{-RGB}
sierpinski3d : -check ${1=4}>=0 -skip ${2=1},${3=1}
-e[^-1] "Input 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
  -nm[-1] [3d\ sierpinski] -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 snapshot3d : _size>0,_zoom>=0,_backgroundR,_backgroundG,_backgroundB
#@gmic : Take 2d snapshots of selected 3d objects.
#@gmic : Set 'zoom' to 0 to disable object auto-scaling.
#@gmic : Default values: 'size=512', 'zoom=1' and 'backgroundR=backgroundG=backgroundB=(undefined)'.
#@gmic : $ -torus3d 100,20 -snapshot3d 400,1.2,128,64,32
snapshot3d : -check "${1=512}>0 && ${2=1}>=0" -skip ${3=""}
  -if {narg($3)}
    -e[0--3] "Take $1x$1 snapshot$? of 3d object$?, with zoom factor $2 and background color ${3--1}."
  -else
    -e[0--3] "Take $1x$1 snapshot$? of 3d object$?, with zoom factor $2."
  -endif
  -v - -repeat @# -l[$>]
    -if {$2!=0} -c3d -n3d -*3d {3*$1*$2/4} -endif
    -if {narg($3)} (${3--1}) -y[-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 -nm[-1] @{-2,n},1 -rm[-2]
  -endl -done -v +

#@gmic sl3d : eq. to '-specl3d'. : (+)

#@gmic specl3d : value>=0 : (+)
#@gmic : Set lightness of 3d specular light.
#@gmic : (eq. to '-sl3d').
#@gmic : $ (0,0.3,0.6,0.9,1.2) -repeat {w} -torus3d 100,30 -rotate3d[-1] 1,1,0,60 -color3d[-1] 255,0,0 -specl3d @{0,$>} -snapshot3d[-1] 400 -done -remove[0]

#@gmic ss3d : eq. to '-specs3d'. : (+)

#@gmic specs3d : value>=0 : (+)
#@gmic : Set shininess of 3d specular light.
#@gmic : (eq. to '-ss3d').
#@gmic : $ (0,0.3,0.6,0.9,1.2) -repeat {w} -torus3d 100,30 -rotate3d[-1] 1,1,0,60 -color3d[-1] 255,0,0 -specs3d @{0,$>} -snapshot3d[-1] 400 -done -remove[0]

#@gmic sphere3d : radius,_nb_recursions>=0 : (+)
#@gmic : Input 3d sphere at (0,0,0), with specified geometry.
#@gmic : Default value: 'nb_recursions=3'.
#@gmic : $ -sphere3d 100 --primitives3d 1  -color3d[-2] @{-RGB}

#@gmic spherical3d : _nb_azimuth>=3,_nb_zenith>=3,_radius_function(phi,theta)
#@gmic : Input 3d spherical object at (0,0,0), with specified geometry.
#@gmic : Default values: 'nb_zenith=nb_azimut=64' and 'radius_function="abs(1+0.5*cos(3*phi)*sin(4*theta))"'.
#@gmic : $ -spherical3d 64 --primitives3d 1
spherical3d : -check "${1=64}>=3 && ${2=$1}>=3" -skip "${3=abs(1+0.5*cos(3*phi)*sin(4*theta))}"
  -e[^-1] "Input 3d spherical object, with subdivisions ($1,$2) and height function '$3'."
  -v -
  ({'CImg3d'}) -y[-1] y # Magic number.
  n1={round($1)} n2={round($2)}

  # Define 3d vertices.
  $n1,{$n2-1},1,3,"phi=2*pi*(x+0.5)/w;\
                   theta=-pi/2+pi*(y+0.5)/h;\
                   cp=cos(phi);\
                   sp=sin(phi);\
                   ct=cos(theta);\
                   ($3)*if(c==0,ct*cp,if(c==1,ct*sp,sin(theta)))"
  -r[-1] {w*h},3,1,1,-1 -permute[-1] yxzc
  -i[-2] (0,0,{phi=0;theta=-pi/2;-$3};0,0,{phi=0;theta=pi/2;$3}) -a[-2,-1] y  # Add the two poles.
  nbv={h} -y[-1] y

  # Define 3d primitives.
  $n1,{$n2-2},1,4,"nx=(x+1)%w;ny=(y+1);2+if(c==0,x+y*"$n1",if(c==1,nx+y*"$n1",if(c==2,nx+ny*"$n1",x+ny*"$n1")))"
  -r[-1] {w*h},4,1,1,-1 -permute[-1] yxzc -i[-2] 1,{h},1,1,4 -a[-2,-1] x
  2,$n1,1,1,3,0 1,$n1,1,1,'y' --+[-1] 1 -%[-1] {h} 2,$n1,1,1,3,1 [-3,-2]  # Connect the two poles.
  -+[-5,-4] 2 -rv[-5,-4] -+[-2,-1] {$nbv-$n1} -a[-3--1] x -a[-4--2] x
  nbp={h+@{-2,h}+@{-3,h}}
  -y[-3--1] y -a[-3--1] y

  # Define other object informations (properties, colors and opacities).
  -i[-3] ($nbv;$nbp)
  1,{3*$nbp},1,1,200 1,$nbp,1,1,1 -a[-2,-1] y

  # Append as a 3d object.
  -a[-5--1] y -nm[-1] "[3d spherical surface '$3']"
  -v +

#@gmic s3d : eq. to '-split3d'. : (+)

#@gmic split3d : (+)
#@gmic : Split selected 3d objects into 6 feature vectors :
#@gmic : { header, sizes, vertices, primitives, colors, opacities }.
#@gmic : (eq. to '-s3d').
#@gmic : To recreate the 3d object, append these 6 images along the y-axis.
#@gmic : $ -box3d 100 --split3d

#@gmic sprite3d
#@gmic : Convert selected images as 3d sprites.
#@gmic : $ image.jpg -sprite3d
sprite3d :
  -e[^-1] "Convert image$? as 3d sprites."
  -v - -repeat @# -l[$>] nm=@{0,n}
    -i[-2] (67.5;73.5;109.5;103.5;51.5;100.5;1;1;0;0;0;1;0;-128;{w};{h};{s})
    -y[-1] y (1) -a y
  -nm $nm,1 -endl -done -v +

#@gmic sprites3d
#@gmic : Convert selected 3d objects as sprites clouds, where the specified 2d sprite is the last selected image.
#@gmic : If the selected sprite has a 4th channel, it stands for the sprite alpha-channel (in [0,255]).
#@gmic : $ -torus3d 100,20 image.jpg -resize2dy[-1] 64 100%,100% -gaussian[-1] 30%,30% -*[-1] 255 -append[-2,-1] c --sprites3d -drgba[-2]
sprites3d :
  -e[^-1] "Convert image$? as 3d sprites clouds."
  -v - -repeat {@#-1} [-1] -l[$>,-1]
    -s3d[0] N=@{1,0} -=[1] $N,0,1
    -rm[3-5] -i[3] (1,0;1,{$N-1}) -r[3] 2,$N,1,1,3 -round[3]
    -if {s==4}
      -s[-1] c,-3 -/[-1] 255
      -i[-3] (-128;{w};{h};3)
      -if {$N>1} -i[-2] 1,{4*($N-1)},1,1,-128,0,0,0 -endif
      -i[-2] (-128;{w};{h};1)
      -if {$N>1} 1,{4*($N-1)},1,1,-128,0,0,0 -endif
      -y[-7,-5,-2] y
    -else
      -i[-2] (-128;{w};{h};{s}) -y[-3,-1] y
      -if {$N>1} 1,{4*($N-1)},1,1,-128,0,0,0 -endif
      1,$N,1,1,1
    -endif
    -a y
  -endl -done -rm[-1] -v +

#@gmic star3d : nb_branches>0,0<=thickness<=1
#@gmic : Input 3d star at (0,0,0), with specified geometry.
#@gmic : Default values: 'nb_branches=5' and 'thickness=0.38'.
#@gmic : $ -star3d , --primitives3d 1 -color3d[-2] @{-RGB}
star3d : -check "${1=5}>0 && ${2=0.38}>=0 && $2<=1"
  -e[^-1] "Input 3d star, with $1 branches and thickness $2."
  -v -
  N={2*$1} ({'CImg3d'}) -+[-1] 0.5 ({$N+1};$N)
  ({-pi/2};{3*pi/2}) -r[-1] 1,{$N+1},1,1,3 -rows[-1] 0,{h-2} --sin[-1] -cos[-2] -a[-2,-1] x
  (1,1;$2,$2) -*[-2,-1] -z[-1] 0,2 -r[-1] 3,{h+1},1,1,0
  (3,$N,1,0;3,$N,$N,{$N-1}) -r[-1] 4,$N,1,1,3 -=[-1] 0,2,100%
  3,$N,1,1,200 1,$N,1,1,1 -y[-6,-4--2] y -a[-6--1] y -nm[-1] [3d\ star]
  -v +

#@gmic streamline3d : x[%],y[%],z[%],_L>=0,_dl>0,_interpolation,_is_backward={ 0 | 1 },_is_oriented={ 0 | 1 } : 'formula',x,y,z,_L>=0,_dl>0,_interpolation,_is_backward={ 0 | 1 },_is_oriented={ 0 | 1 } : (+)
#@gmic : Extract 3d streamlines from selected vector fields or from specified formula.
#@gmic : 'interpolation' can be { 0=nearest integer | 1=1st-order | 2=2nd-order | 3=4th-order }.
#@gmic : Default values: 'dl=0.1', 'interpolation=2', 'is_backward=0' and 'is_oriented=0'.
#@gmic : $ 100,100,100,3 -rand -10,10 -blur 3 -repeat 300 --streamline3d[0] {?(100)},{?(100)},{?(100)},1000,1,1 -color3d[-1] @{-RGB} -done -rm[0] -box3d 100 -primitives3d[-1] 1 -add3d

#@gmic -3d : eq. to '-sub3d'. : (+)

#@gmic sub3d : tx,_ty,_tz : (+)
#@gmic : Shift selected 3d objects with the opposite of specified displacement vector.
#@gmic : (eq. to '--3d').
#@gmic : Default values: 'ty=tz=0'.
#@gmic : $ -sphere3d 10 -repeat 5 --sub3d[-1] 10,{?(-10,10)},0 -color3d[-1] @{-RGB} -done -add3d

#@gmic superformula3d : resolution>1,m>=1,n1,n2,n3
#@gmic : Input 2d superformula curve as a 3d object.
#@gmic : Default values: 'resolution=1024', 'm=8', 'n1=1', 'n2=5' and 'n3=8'.
#@gmic : $ -superformula3d ,
superformula3d : -check "${1=1024}>1 && ${2=8}>=1" -skip ${3=1},${4=5},${5=8}
  -e[^-1] "Input 2d superformula curve, with resolution $1, m=$2 and (n1,n2,n3)=($3,$4,$5)."
  -v -
  res={round($1)}

  # Define object header and vertices.
  (67.5;73.5;109.5;103.5;51.5;100.5;$res;{$res-1})
  (0,{2*pi}) -r[-1] $res,1,1,1,3 [-1]

  -*[-1] {$2/4} --sin[-1] -cos[-2] -abs[-2,-1]
  -^[-2] $4 -^[-1] $5 -+[-2,-1] -^[-1] {-1/$3}
  --sin[-2] -cos[-3] -*[-1] [-2] -*[-3,-2] -n[-2,-1] -1,1
  -a[-2,-1] y -rows[-1] 0,2 -transpose[-1] -r[-1] 1,{w*h},1,1,-1

  # Define object primitives, colors and opacities.
  1,{$res-1},1,1,2 (0;{$res-2}) -r[-1] 1,{$res-1},1,1,3 --+[-1] 1 -a[-3--1] x -round[-1] 1 -r[-1] 1,{w*h},1,1,-1
  1,{3*($res-1)},1,1,200 1,{$res-1},1,1,1 -a[-5--1] y -nm[-1] [3d\ superformula]
  -v +

#@gmic text_pointcloud3d : _"text1",_"text2",_smoothness
#@gmic : Input 3d text pointcloud from the two specified strings.
#@gmic : Default values: 'text1="text1"', 'text2="text2"' and 'smoothness=1'.
#@gmic : $ -text_pointcloud3d "G'MIC","Rocks!"
text_pointcloud3d : -skip ${1="text1"},${2="text2"},${3=1}
  -e[^-1] "Input 3d pointcloud text object from strings '$1' and '$2', with smoothness $3."
  -v -
  0 -t[-1] "$1",0,0,57,1,1
  0 -t[-1] "$2",0,0,57,1,1 -mirror[-1] y
  -expand_xy[-2,-1] 2,0 -dilate[-2,-1] 2
  -permute[-1] zyxc -r[-2,-1] @{-max_whd} -and[-2,-1]

  100%,100% -rand[-1] 0,{@{-2,d}-1} -round[-1] -r[-1] [-2] -f[-1] 'if(z==i,1,0)'
  -distance[-1] 1 -+[-1] 1 --f[-1] 1 -rv[-2,-1] -/[-2,-1] -*[-1] [-2]
  --dilate[-1] 0,0,{d} -==[-2,-1] -*[-1] [-2]

  1,100%,100% -rand[-1] 0,{@{-2,w}-1} -round[-1] -r[-1] [-2] -f[-1] 'if(x==i,1,0)'
  -distance[-1] 1 -+[-1] 1 --f[-1] 1 -rv[-2,-1] -/[-2,-1] -*[-1] [-3]
  --dilate[-1] 0,0,{d} -==[-2,-1] -*[-3,-1]

  -or[-2,-1]

  -b[-1] $3 -isosurface3d[-1] 25%
  -c3d[-1] -n3d[-1] -nm[-1] "[3d text pointcloud]" -v +

#@gmic text3d : text,_font_height>0,_depth>0,_smoothness
#@gmic : Input a 3d text object from specified text.
#@gmic : Default values: 'font_height=57', 'depth=10' and 'smoothness=1.5'.
#@gmic : $ -text3d "G'MIC as a\n3D logo!"
text3d : -skip ${2=57},${3=10},${4=1.5}
  -e[^-1] "Input 3d text object '$1' with size $2, depth $3 and smoothness $4."
  -v - 0 -t[-1] "$1",0,0,$2,1,1 -autocrop[-1] 0 -r[-1] 100%,100%,$3 -expand_xyz[-1] 10,0
  -b[-1] $4 -isosurface3d[-1] 40% -rv3d[-1] -nm[-1] "[3d text '$1']" -v +

#@gmic t3d : eq. to '-texturize3d'. : (+)

#@gmic texturize3d : [ind_texture],_[ind_coords] : (+)
#@gmic : Texturize selected 3d objects with specified texture and coordinates.
#@gmic : (eq. to '-t3d').
#@gmic : When '[ind_coords]' is omitted, default XY texture projection is performed.
#@gmic : Default value: 'ind_coords=(undefined)'.
#@gmic : $ image.jpg -torus3d 100,30 -texturize3d[-1] [-2] -keep[-1]

#@gmic torus3d : _radius1,_radius2,_nb_subdivisions1>2,_nb_subdivisions2>2
#@gmic : Input 3d torus at (0,0,0), with specified geometry.
#@gmic : Default values: 'radius1=1', 'radius2=0.3', 'nb_subdivisions1=24' and 'nb_subdivisions2=12'.
#@gmic : $ -torus3d 10,3 --primitives3d 1 -color3d[-2] @{-RGB}
torus3d : -check "${3=24}>2 && ${4=12}>2" -skip ${1=1},${2=0.3}
  -e[^-1] "Input 3d torus, with radii ($1,$2) and subdivisions ($3,$4)."
  -v -
  # Header.
  nbp={$3*$4}
  1,8,1,1,67.5,73.5,109.5,103.5,51.5,100.5,$nbp,{$4*$3}

  # Vertices.
  (0;{2*pi}) --y[-1] x
  -r[-2] 1,{$3+1},1,1,3 -z[-2] 0,0,0,{$3-1}
  -r[-1] {$4+1},1,1,1,3 -z[-1] 0,{$4-1}
  --sin[-2,-1] -cos[-4,-3] -r[-4--1] $4,$3
  -*[-3] $2 -+[-3] $1 -*[-1] $2 -*[-4] [-3] -*[-3,-2]
  -y[-3--1] y -a[-3--1] x

  # Primitives.
  1,$3,1,1,'y' -*[-1] $4 --shift[-1] 0,-1 $4,1,1,1,'x' --shift[-1] -1 -r[-4--1] $4,$3
  --+[-4,-1] -+[-2] [-4] -+[-5] [-3] -+[-4,-3] -y[-4--1] y -i[-5] 1,{h},1,1,4 -a[-5--1] x

  # Colors / opacities.
  3,{h},1,1,200 1,{h},1,1,1 -y[-4--2] y -a[-5--1] y
  -nm[-1] [3d\ torus]
  -v +

#@gmic triangle3d : x0,y0,z0,x1,y1,z1,x2,y2,z2
#@gmic : Input 3d triangle at specified coordinates.
#@gmic : $ -repeat 100 a={$>*pi/50} -triangle3d 0,0,0,0,0,3,{cos(3*$a)},{sin(2*$a)},0 -color3d[-1] @{-RGB} -done -add3d
triangle3d :
  -e[^-1] "Input 3d triangle ($1,$2,$3)-($4,$5,$6)-($7,$8,$9)."
  -v - 1,25,1,1,67.5,73.5,109.5,103.5,51.5,100.5,3,1,${1-9},3,0,1,2,200,200,200,1 -nm[-1] [3d\ triangle] -v +

#@gmic weird3d : _resolution>0
#@gmic : Input 3d weird object at (0,0,0), with specified resolution.
#@gmic : Default value: 'resolution=32'.
#@gmic : $ -weird3d 48 --primitives3d 1 -color3d[-2] @{-RGB}
weird3d : -skip ${1=32}
  -e[^-1] "Input 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] -nm[-1] [3d\ weird]
  -v +

#-------------------------------
#
#@gmic :: Program controls
#
#-------------------------------

#@gmic check : expression : (*)
#@gmic : Evaluate specified expression and display an error message if evaluated to false.
#@gmic : If 'expression' is not evaluable, it is regarded as a filename and checked if it exists.

#@gmic continue : (*)
#@gmic : Continue to next iteration of current 'repeat..done', 'do..while' or 'local..endlocal' block.
#@gmic : $ image.jpg -repeat 10 -blur 1 -if {1==1} -continue -endif -deform 10 -done

#@gmic break : (*)
#@gmic : Break current 'repeat..done', 'do..while' or 'local..endlocal' block.
#@gmic : $ image.jpg -repeat 10 -blur 1 -if {1==1} -break -endif -deform 10 -done

#@gmic do : (*)
#@gmic : Start a 'do..while' block.
#@gmic : $ image.jpg -luminance -do -set 255,{?(100)}%,{?(100)}% -while {ia<128}

#@gmic done : (*)
#@gmic : End a 'repeat..done' block, and go to associated '-repeat' position, if iterations remain.

#@gmic elif : boolean : filename : (*)
#@gmic : Start a 'elif..[else]..endif' block if previous '-if' was not verified
#@gmic : and test if specified boolean is true, or if specified filename exists.
#@gmic : 'boolean' can be a float number standing for { 0=false | other=true }.

#@gmic else : (*)
#@gmic : Execute following commands if previous '-if' or '-elif' conditions failed.

#@gmic endif : (*)
#@gmic : End a 'if..[elif]..[else]..endif' block.

#@gmic endl : eq. to '-endlocal'. : (*)

#@gmic endlocal : (*)
#@gmic : End a 'local..endlocal' block.
#@gmic : (eq. to '-endl').

#@gmic error : message : (*)
#@gmic : Print specified error message on the standard output and exit interpreter, except
#@gmic : if error is caught by a '-onfail' command.
#@gmic : Command subset (if any) stands for displayed scope indices instead of image indices.

#@gmic x : eq. to '-exec'. : (*)

#@gmic exec : command : (*)
#@gmic : Execute external command using a system call.
#@gmic : The status value is then set to the error code returned by the system call.
#@gmic : (eq. to '-x').

#@gmic if : boolean : filename : (*)
#@gmic : Start a 'if..[elif]..[else]..endif' block and test if specified boolean is true,
#@gmic : or if specified filename exists.
#@gmic : 'boolean' can be a float number standing for { 0=false | other=true }.
#@gmic : $ image.jpg -if {ia<64} -add 50% -elif {ia<128} -add 25% -elif {ia<192} -sub 25% -else -sub 50% -endif -cut 0,255

#@gmic l : eq. to '-local'. : (*)

#@gmic local : (*)
#@gmic : Start a 'local..[onfail]..endlocal' block, with selected images.
#@gmic : (eq. to '-l').
#@gmic : $ image.jpg -local[] 300,300,1,3 -rand[0] 0,255 -blur 4 -sharpen 1000 -endlocal
#@gmic : $ image.jpg --local -repeat 3 -deform 20 -done -endlocal

#@gmic onfail : (*)
#@gmic : Execute following commands when an error is encountered in the body of the 'local..endlocal' block.
#@gmic : The status value is set with the corresponding error message.
#@gmic : $ image.jpg --local -blur -3 -onfail -mirror x -endlocal

#@gmic progress : 0<=value<=100 : -1 : (*)
#@gmic : Set the progress indice of the current processing pipeline.
#@gmic : This command is useful only when G'MIC is used by an embedding application.

#@gmic q : eq. to '-quit'. : (*)

#@gmic quit : (*)
#@gmic : Quit interpreter.
#@gmic : (eq. to '-q').

#@gmic repeat : nb_iterations : (*)
#@gmic : Start iterations of a 'repeat..done' block.
#@gmic : $ image.jpg -split y -repeat @# -shift[$>] $<,0,0,0,2 -done -append y
#@gmic : $ image.jpg -mode3d 2 -repeat 4 -imagecube3d -rotate3d 1,1,0,40 -snapshot3d 400,1.4 -done

#@gmic return : (*)
#@gmic : Return from current custom command.

#@gmic skip : item : (*)
#@gmic : Do nothing but skip specified item.

#@gmic u : eq. to '-status'. : (*)

#@gmic status : value : (*)
#@gmic : Set current status value. Used to define a returning value in a function.
#@gmic : (eq. to '-u').
#@gmic : $ image.jpg -command "foo : u0=Dark u1=Bright -status ${u{ia>=128}}" -text_outline @{-foo},2,2,24,2,1,255

#@gmic while : boolean : filename : (*)
#@gmic : End a 'do..while' block and go back to associated '-do'
#@gmic : if specified boolean is true or if specified filename exists.
#@gmic : 'boolean' can be a float number standing for { 0=false | other=true }.

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

#@gmic array : M>0,_N>0,_expand_type={0=min | 1=max | 2=all}
#@gmic : Create MxN array from selected images.
#@gmic : Default values: 'N=M' and 'expand_type=0'.
#@gmic : $ image.jpg -array 3,2,2
array : -check "isint($1) && $1>0 && isint(${2=$1}) && $2>0" -skip ${3=0}
  -e[^-1] "Create $1x$2 array from image$?, with expand type $3."
  -v - r0={100/max($1,$2)} r1={100/min($1,$2)} r2=100
  -r ${r$3}%,${r$3}%,1,100%,2 -r {$1*100}%,{$2*100}%,1,100%,0,2 -v +

#@gmic array_fade : M>0,_N>0,0<=_fade_start<=100,0<=_fade_end<=100,_expand_type={0=min | 1=max | 2=all}
#@gmic : Create MxN array from selected images.
#@gmic : Default values: 'N=M', 'fade_start=60', 'fade_end=90' and 'expand_type=1'.
#@gmic : $ image.jpg -array_fade 3,2
array_fade : -skip ${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 @# -l[$>] [-1] -shift[-2] 50%,50%,1,1,2 -fade_diamond $3,$4 -endl -done
  -array $1,$2,$5
  -v +

#@gmic array_mirror : N>=0,_dir={ 0=x | 1=y | 2=xy | 3=tri-xy },_expand_type={ 0 | 1 }
#@gmic : Create 2^Nx2^N array from selected images.
#@gmic : Default values: 'dir=2' and 'expand_type=0'.
#@gmic : $ image.jpg -array_mirror 2
array_mirror : -skip ${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}
      -if {$2>=3} -r 33%,33%,100%,100%,2
      -else -r 50%,50%,100%,100%,2
      -endif
    -endif
    -repeat @# -l[$>]
      -if {$2==0} --mirror x -a x
      -elif {$2==1} --mirror y -a y
      -else --mirror x -a x --mirror y -a y -if {$2==3} -r 150%,150%,1,100%,0,2,1,1 -endif
      -endif
    -endl -done
  -done -v +

#@gmic array_pattern : M>0,_N>0,_density>=0,_angle>=0,_zoom>=0,_opacity,_expand_type={0=min | 1=max | 2=all}
#@gmic : Create random MxN array from selected images.
#@gmic : Default values: 'N=M', 'density=80', 'angle=180', 'zoom=30', 'opacity=1' and 'expand_type=0'.
#@gmic : $ image.jpg -array_pattern 10
array_pattern : -skip ${2=$1},${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 - r0={100/max($1,$2)} r1={100/min($1,$2)} r2=100 -to_rgb
  -repeat @# -l[$>] nm=@{0,n}
    -r ${r$7}%,${r$7}%,1,100%,2 -= 0,0,0,0,3
    --z 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 -ge[-1] 0 -y[-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]
        -j[-5] [-3],@{-1},0,0,$6,[-2] -rm[-3--1]
      -endif
    -shift[-1] 0,-1 -done -done -k[1]
  -nm $nm,1 -endl -done -v +

#@gmic array_random : Ms>0,_Ns>0,_Md>0,_Nd>0
#@gmic : Create MdxNd array of tiles from selected MsxNs source arrays.
#@gmic : Default values: 'Ns=Ms', 'Md=Ms' and 'Nd=Ns'.
#@gmic : $ image.jpg --array_random 8,8,15,10
array_random : -skip ${2=$1},${3=$1},${4=$2}
  -e[^-1] "Create $3x$4 array of tiles from $1x$2 array$?."
  -v - -repeat @# -l[$>] nm=@{0,n}
    -split_tiles $1,$2
    -repeat $3 -repeat $4 [{?($1*$2-1)}] -done -done
    -rm[0-{$1*$2-1}] -append_tiles $3,$4
  -nm $nm,1 -endl -done -v +

#@gmic frame : size_x[%]>=0,_size_y[%]>=0,_col1,...,_colN
#@gmic : Insert RGBA-colored frame in selected images.
#@gmic : Default values: 'size_y=size_x' and 'col1=255'.
#@gmic : $ image.jpg -frame 2,2,255 -frame 10,10,128,0,255
frame : -skip ${2=$1},${3=255},${4=$3},${5=$4}
  -e[^-1] "Insert $1x$2 outer frame in image$?, with color (${3--1})."
  -v - -repeat @# -l[$>]
    -if {$1} -i[0] $1,[0],[0],[0] -fc[0] ${3--1} -nm[0] @{-1,n} [0] -a x -endif
    -if {$2} -i[0] [0],$2,[0],[0] -fc[0] ${3--1} -nm[0] @{-1,n} [0] -a y -endif
  -endl -done -v +

#@gmic frame_blur : _sharpness>0,_size>=0,_smoothness,_shading,_blur
#@gmic : Draw RGBA-colored round frame in selected images.
#@gmic : Default values: 'sharpness=10', 'size=30', 'smoothness=0', 'shade=1' and 'blur=3%'.
#@gmic : $ image.jpg -frame_blur 3,30,8,10%
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 @# -l[$>] nm=@{0,n}
    100%,100%,1,1,"-(abs(x/w-0.5)^$1 + abs(y/h-0.5)^$1)^(1/$1)" -ge[-1] $2%
    -if $4 -distance[-1] 1 -n[-1] 0,1 -*[-1] -1 -+[-1] 1 -^[-1] {1/$4} -endif
    -b[-1] $3 --b[-2] $5 -mv[-1] -3 -compose_fade
  -nm $nm,1 -endl -done -v +

#@gmic frame_cube : _depth>=0,_x_center,_y_center,_left_side={0=normal | 1=mirror-x | 2=mirror-y | 3=mirror-xy},_right_side,_lower_side,_upper_side
#@gmic : Insert 3d frames in selected images.
#@gmic : Default values: 'depth=1', 'x_center=y_center=0' and 'left_side=right_side,lower_side=upper_side=0'.
#@gmic : $ image.jpg -frame_cube ,
frame_cube : -check "${1=1}>=0" -skip ${2=0},${3=0},${4=0},${5=0},${6=0},${7=0}
  -e[^-1] "Insert 3d frame in image$?, with depth $1, center ($2,$3) and orientations (${4--1})."
  -v - -repeat @# -l[$>] nm=@{0,n} -split_opacity
    -if {@#==2} -frame_cube ${1--1} -a c  # Manage image with alpha-channel.
    -else
      m={max(w,h)} w={w} h={h} s={s}
      -imageplane3d -c3d -/3d[-1] $w,$h,1
      --_frame_cube[0] $4 -r3d[-1] 0,1,0,90 -+3d[-1] -0.5,0,-0.5  # Left side.
      --_frame_cube[0] $5 -r3d[-1] 0,1,0,-90 -+3d[-1] 0.5,0,-0.5  # Right side.
      --_frame_cube[0] $6 -r3d[-1] 1,0,0,90 -+3d[-1] 0,0.5,-0.5   # Lower side.
      --_frame_cube[0] $7 -r3d[-1] 1,0,0,-90 -+3d[-1] 0,-0.5,-0.5 # Upper side.
      -+3d 0,0,1 -+3d -*3d $w,$h,$m  # Append sides together.
      f=1000
      cx=$2*$w/2*($f+$m*$1)/$f
      cy=$3*$h/2*($f+$m*$1)/$f
      -s3d -r[2] 3,{@{2,h}/3},1,1,-1
      -f[2] "if(i(2,y)<0.5,i,i+if(x==0,"$cx",if(x==1,"$cy",($1-1)*"$m")))"
      -y[2] y -a y
      -*3d 2 {2*$w},{2*$h},1,$s -f3d {2*$f}
      -object3d[-1] [-2],50%,50%,0,1,2,0,0 -rm[-2]
      -r $w,$h,1,100%,2
    -endif
  -nm $nm,1 -endl -done
  -v +

_frame_cube :
  -if {$1==1} -r3d[-1] 0,1,0,180 -rv3d[-1]
  -elif {$1==2} -r3d[-1] 1,0,0,180 -rv3d[-1]
  -elif {$1==3} -r3d[-1] 0,0,1,180
  -endif

#@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.
#@gmic : Default values: 'size_y=size_x', 'fuzzyness=5', 'smoothness=1' and 'R=G=B=A=255'.
#@gmic : $ image.jpg -frame_fuzzy 20
frame_fuzzy : -skip ${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 @# -l[$>] nm=@{0,n}
    -i[0] ($1;$2) -*[0] 2 ($5^$6^$7^$8) -r[-1] [-2] 100%,100%
    -rectangle[-1] 0,0,100%,@{0,1},1,1
    -rectangle[-1] 0,0,@{0,0},100%,1,1
    -rm[0] -shift[-1] -$1,-$2,0,0,2 -spread[-1] $3 -b[-1] $4 -_fade 50,80
  -nm $nm,1 -endl -done -v +

#@gmic frame_painting : _size[%]>=0,0<=_contrast<=1,_profile_smoothness[%]>=0,_R,_G,_B,_vignette_size[%]>=0,_vignette_contrast>=0,_defects_contrast>=0,0<=_defects_density<=100,_defects_size>=0,_defects_smoothness[%]>=0,_serial_number
#@gmic : Add a painting frame to selected images.
#@gmic : Default values: 'size=10%', 'contrast=0.4', 'profile_smoothness=6%', 'R=225', 'G=200', 'B=120', 'vignette_size=2%', 'vignette_contrast=400', 'defects_contrast=50', 'defects_density=10', 'defects_size=1', 'defects_smoothness=0.5%' and 'serial_number=123456789'.
#@gmic : $ image.jpg -frame_painting ,
frame_painting :
  -check "${1=10%}>=0 && ${2=0.4}>=0 && $2<=1 && ${3=6%}>=0 && ${7=2%}>=0 && ${8=400}>=0 && ${9=50}>=0 && ${10=10}>=0 && $10<=100 && ${11=1}>=0 && ${12=0.5%}>=0"
  -skip ${4=225},${5=200},${6=120},${13=123456789}
  -e[^-1] "Add painting frame to image$?, with size $1, contrast $2, profile smoothness $3, color (${4-6}), vignette size $7, "\
          "vignette strength $8, defects contrast $9, defects density $10, defects size $11, defects smoothness $12 and serial number $13."
  -v - -repeat @# -l[$>]
    -if {!$1} -return -endif
    $1,$1 s={max(w,h)} -rm[-1]                                # Determine size of the frame.
    ({'@{"-dec2bin $13"}'}) --[-1] {'0'} -r[-1] $s            # Generate frame profile from serial number.
    -transpose[-1] -b[-1] $3 -n[-1] {1-$2},{1+$2}
    --r[-1] {@{-2,w}+2*$s},100%,1,1                           # Upper frame.
    --mirror[-1] y                                            # Lower frame.
    -mv[-3] @# -transpose[-1] -r[-1] 100%,{@{-4,h}+2*$s},1,1  # Left frame.
    --mirror[-1] x                                            # Right frame.
    [-3],[-3],1,1,1 -polygon[-1] 3,0,0,{$s-1},{$s-1},0,{$s-1},1,0 -polygon[-1] 3,100%,0,{w-$s},100%,100%,100%,1,0 # Upper/lower mask.
    [-2],[-2],1,1,1 -polygon[-1] 3,1,0,100%,{$s-2},100%,0 -polygon[-1] 3,1,100%,100%,{h-$s+1},100%,100%,1,0 # Left/right mask.
    -_frame_painting[-6--3] ${4-6},${9-12}                    # Add colors + defects.

    # Build full frame picture.
    {@{-7,w}+2*$s},{@{-7,h}+2*$s},1,3
    -j[-1] [-7],0,0,0,0,1,[-3],1 -rm[-7] -mirror[-3] y
    -j[-1] [-6],0,{h-$s},0,0,1,[-3],1 -rm[-6,-3]
    -j[-1] [-4],0,0,0,0,1,[-2],1 -rm[-4] -mirror[-2] x
    -j[-1] [-3],{w-$s},0,0,0,1,[-2],1 -rm[-3,-2]
    [-2],[-2],1,1,-255 -r[-1] [-2],[-2],1,1,0,0,0.5,0.5 -+[-1] 255 --b[-1] $7 -n[-1] 0,$8 -max[-2,-1] -c[-1] 0,255 # Frame opacity.
    -a[-2--1] c
    -r[-2] [-1],[-1],1,100%,0,0,0.5,0.5 -compose_alpha # Insert initial image into frame picture.
  -endl -done -v +

_frame_painting : # Add color + texture to each frame part.
  -repeat @# -l[$>]
    --*[-1] $2 --*[-2] $3 -*[-3] $1 -a[-3--1] c
    100%,100%
    i=0 -do -rand[-1] 0,1 -remove_pixels[-1] {100-$5} -b[-1] $6 -ge[-1] 50% i={$i+1} -while {"m=$5/200;(ia<m-0.2 || ia>m+0.2) && "$i"<10"}
    -b[-1] $7 -g[-1] -+[-2,-1] -n[-1] -$4,$4
    -+[-2,-1] -c[-1] 0,255
  -endl -done

#@gmic frame_pattern : M>=3,_pattern = { 0=first image | 1=self },_constrain_size = { 0 | 1 }
#@gmic : Insert selected pattern frame in selected images.
#@gmic : Default values: 'pattern=0' and 'constrain_size=0'.
#@gmic : $ image.jpg -frame_pattern 8
frame_pattern : -check $1>=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 @# -l[$>]
      wh={w},{h}
      --r {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 -j[-3] [-1],0,0 -j[-3] [-1],0,{@{-3,h}-1-h} -rm[-1]
      [-1]x{$1+1} -a[{-$1-2}--1] y -j[-2] [-1],0,0 -j[-2] [-1],{@{-2,w}-1-w} -rm[-1]
      -if $3 -r $wh,1,100%,2 -endif
    -endl -done
  -else # Frame from image[0]
    -v + -e[^-1] "Insert $1x$1 pattern frame on image$?, using first image." -v -
    -repeat {@#-1}
      wh={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 -j[-3] [-1],0,0 -j[-3] [-1],0,{@{-3,h}-1-h} -rm[-1]
      [-1]x{$1+1} -a[{-$1-2}--1] y -j[-2] [-1],0,0 -j[-2] [-1],{@{-2,w}-1-w} -rm[-1]
      -if $3 -r[-1] $wh,1,100%,2 -endif
    -mv[-1] 1 -done -rm[0]
  -endif
  -v +

#@gmic frame_round : _sharpness>0,_size>=0,_smoothness,_shading,_R,_G,_B,_A
#@gmic : Draw RGBA-colored round frame in selected images.
#@gmic : Default values: 'sharpness=10', 'size=10', 'smoothness=0', 'shade=0' and 'R=G=B=A=255'.
#@gmic : $ image.jpg -frame_round 10
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 @# -l[$>] nm=@{0,n}
    100%,100%,1,1,"-(abs(x/w-0.5)^$1 + abs(y/h-0.5)^$1)^(1/$1)" -ge[-1] $2%
    -if $4 -distance[-1] 1 -n[-1] 0,1 -*[-1] -1 -+[-1] 1 -^[-1] {1/$4} -endif
    -b[-1] $3 -i[-3] 100%,100%,1,4 -fc[-3] $5,$6,$7,$8 -compose_fade
  -nm $nm,1 -endl -done -v +

#@gmic imagegrid : M>0,_N>0
#@gmic : Create MxN image grid from selected images.
#@gmic : Default value: 'N=M'.
#@gmic : $ image.jpg -imagegrid 16
imagegrid : -skip ${2=$1}
  -e[^-1] "Create $1x$2 image grid from image$?."
  -v - -repeat @# -l[$>]
    ({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 -*
  -endl -done -v +

#@gmic linearize_tiles : M>0,_N>0
#@gmic : Linearize MxN tiles on selected images.
#@gmic : Default value: 'N=M'.
#@gmic : $ image.jpg --linearize_tiles 16
linearize_tiles : -check "$1>0 && ${2=$1}>0"
  -e[^-1] "Linearize $1x$2 tiles on image$?."
  -v - -repeat @# -l[$>] nm=@{0,n}
    s={s} -split_tiles $1,$2 -s c # Split as tiles for all channels.
    -repeat @# -l[$>]
      wh={w},{h}
      --f x --f[-1] y --f[-1] 1 -y y -a[^0] x -solve[-2] [-1] -rm[-1]
      $wh,1,1,@{-1,0}"*x + "@{-1,1}"*y + "@{-1,2} -rm[-2]
    -endl -done
    -repeat {int(@#/$s)} -a[-$s--1] c -mv[-1] 0 -done -append_tiles $1,$2
  -nm $nm,1 -endl -done -v +

#@gmic quadratize_tiles : M>0,_N>0
#@gmic : Quadratize MxN tiles on selected images.
#@gmic : Default value: 'N=M'.
#@gmic : $ image.jpg --quadratize_tiles 16
quadratize_tiles : -check "$1>0 && ${2=$1}>0"
  -e[^-1] "Quadratize $1x$2 tiles on image$?."
  -v - -repeat @# -l[$>] nm=@{0,n}
    s={s} -split_tiles $1,$2 -s c # Split as tiles for all channels.
    -repeat @# -l[$>]
      wh={w},{h}
      --f x^2 --f[-1] y^2 --f[-1] x*y --f[-1] x --f[-1] y --f[-1] 1 -y y -a[^0] x -solve[-2] [-1] -rm[-1]
      $wh,1,1,@{-1,0}"*x^2 + "@{-1,1}"*y^2 + "@{-1,2}"*x*y +"@{-1,3}"*x + "@{-1,4}"*y + "@{-1,5} -rm[-2]
    -endl -done
    -repeat {int(@#/$s)} -a[-$s--1] c -mv[-1] 0 -done -append_tiles $1,$2
  -nm $nm,1 -endl -done -v +

#@gmic rotate_tiles : angle,_M>0,N>0
#@gmic : Apply MxN tiled-rotation effect on selected images.
#@gmic : Default values: 'M=8' and 'N=M'.
#@gmic : $ image.jpg -to_rgba -rotate_tiles 10,8 -drop_shadow 10,10 -display_rgba
rotate_tiles : -skip ${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.
#@gmic : Default values: 'N=M' and 'amplitude=20'.
#@gmic : $ image.jpg --shift_tiles 8,8,10
shift_tiles : -check "${2=$1}>=0" -skip ${3=20}
  -e[^-1] "Apply $1x$2 tiled-shift effect on image$?, with amplitude $3."
  -v - -repeat @# -l[$>]
    $1,$2,1,2 -noise[-1] $3 -r[-1] [-2],[-2],1,2 -warp[-2] [-1],1,1,0 -rm[-1]
  -endl -done -v +

#@gmic taquin : M>0,_N>0
#@gmic : Create MxN taquin puzzle from selected images.
#@gmic : Default value: 'N=M'.
#@gmic : $ image.jpg --taquin 8
taquin : -skip ${2=$1}
 -e[^-1] "Create $1x$2 taquin puzzle from image $?."
 -v - -repeat @# -l[$>] nm=@{0,n}
   -split_tiles $1,$2,1 -repeat {$1*$2} -mv[$>] {?(@#)} -done -append_tiles $1,$2
 -nm $nm,1 -endl -done -v +

#@gmic tunnel : _level>=0,_factor>0,_cx,_cy,_opacity.
#@gmic : Apply tunnel effect on selected images.
#@gmic : Default values: 'level=9', 'factor=80%', 'cx=cy=0.5' and 'opacity=1'.
#@gmic : $ image.jpg --tunnel 20
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 @# -l[$>]
    -repeat $1 --r[-1] $2,$2,1,100%,5 -j[-2] [-1],{(@{-2,w}-w)*$3},{(@{-2,h}-h)*$4},0,0,$5 -rm[-1] -done
  -endl -done -c 0,255 -v +

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

#@gmic cartoon : _smoothness,_sharpening,_threshold>=0,_thickness>=0,_color>=0,quantization>0
#@gmic : Apply cartoon effect on selected images.
#@gmic : Default values: 'smoothness=3', 'sharpening=80', 'threshold=20', 'thickness=0.25', 'color=1.5' and 'quantization=8'.
#@gmic : $ image.jpg --cartoon 3,80,15
cartoon : -skip ${1=3},${2=80},${3=20},${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 - -repeat @# -l[$>] -split_opacity -l[0] -to_rgb
    -b $1 -sharpen $2,1 -c 0,255 -n 0,255
    --edges $3 -b[-1] $4 -ge[-1] 0.9
    -rgb2lab[-2] -s[-2] c -*[-3,-2] $5 -a[-4--2] c -lab2rgb[-2] -quantize[-2] $6 -n[-2] 0,255 -*
  -endl -a c -endl -done -v +

#@gmic circlism : _radius_min>0,_radius_max>0,_smoothness[%]>=0,_radius_linearity>=0,_location_linearity>=0,_shape={0=squares | 1=diamonds | 2=circle }
#@gmic : Apply circlism effect on selected images (effect inspired by Ben Heine).
#@gmic : Default values: 'radius_min=2', 'radius_max=20', 'smoothness=1', 'radius_linearity=0.4', 'location_linearity=3' and 'shape=1'.
#@gmic : $ image.jpg --circlism ,
circlism : -check "${1=2}>0 && ${2=20}>0 && ${3=1}>=0 && ${4=0.4}>0 && ${5=3}>=0" -skip ${6=2}
  -e[^-1] "Apply circlism effect on image$?, with radii ($1,$2), smoothness $3, radius linearity $4 and location linearity $5.\n"
  -v - -repeat @# -l[$>]
    --gradient_norm -b[-1] $3 -n[-1] 0,1 --^[-1] $5 -^[-2] $4 sumg0=@{-1,+} 100%,100%
    it=0 failed=0 noedges=0 svg="-1,-1"
    -do
      --distance[-1] 1,3
      -if $noedges xyzc=@{-1,C} -else --*[-3,-1] xyzc=@{-1,C} -rm[-1] -endif
      n=@{-4,($xyzc)}
      x={arg(1,$xyzc)}
      y={arg(2,$xyzc)}
      r={min(max($1,$2*(1-$n)),sqrt(@{-1,($xyzc)})-2)}
      -rm[-1]
      -if {$r>=$1}
        -if {$6==2}  # Fill with circles.
          -ellipse[-1] $x,$y,$r,$r,0,1,1 -ellipse[-2] $x,$y,{$r+$1},{$r+$1},0,1,-1
        -elif {$6==1} # Fill with squares.
          x0={$x-$r/2} y0={$y-$r/2} x1={$x+$r/2} y1={$y+$r/2}
          -rectangle[-1] $x0,$y0,$x1,$y1,1,1
          x0={$x-($r+$1)/2} y0={$y-($r+$1)/2} x1={$x+($r+$1)/2} y1={$y+($r+$1)/2}
          -rectangle[-2] $x0,$y0,$x1,$y1,1,-1
        -else # Fill with diamonds.
          x0={round($x-$r/2)} y0={round($y-$r/2)} x1={round($x+$r/2)} y1={round($y+$r/2)}
          -polygon[-1] 4,$x0,$y,$x,$y0,$x1,$y,$x,$y1,1,1
          x0={round($x-($r+$1)/2)} y0={round($y-($r+$1)/2)} x1={round($x+($r+$1)/2)} y1={round($y+($r+$1)/2)}
          -polygon[-2] 4,$x0,$y,$x,$y0,$x1,$y,$x,$y1,1,-1
        -endif
        failed=0
      -else
        -=[-2] -1,$x,$y
        failed={$failed+1}
        -if {$failed==100} failed=0 -if $noedges n=-1 -else noedges=1 -endif -endif
      -endif
      it={$it+1}
      -if {!($it%50)}
        p={round(100*(($sumg0-@{-2,+})/@{-2,wh})^3)}
        -progress $p -v + -e[] "\r  "$p% -v -
      -endif
    -while {$n>=0}
    -rm[-3,-2] -progress -1
    -compose_shapeaverage
  -endl -done -v +

#@gmic color_ellipses : _count>0,_radius>=0,_opacity>=0
#@gmic : Add random color ellipses to selected images.
#@gmic : Default values: 'count=400', 'radius=5' and 'opacity=0.1'.
#@gmic : $ image.jpg --color_ellipses ,,0.15
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 $1 -ellipse {?(0,100)}%,{?(0,100)}%,{?(0,$2)}%,{?(0,$2)}%,{?(0,360)},$3,{?(60,255)},{?(60,255)},{?(60,255)},255 -done -v +

#@gmic cubism : _nb_iter>=0,_bloc_size>0,_max_angle,_opacity,_smoothness>=0
#@gmic : Apply cubism effect on selected images.
#@gmic : Default values: 'nb_iter=160', 'bloc_size=10', 'max_angle=75', 'opacity=0.7' and 'smoothness=0'.
#@gmic : $ image.jpg --cubism ,
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 @# -l[$>]
    M={$2*max(w,h)/200}
    -repeat $1
      ({?(0,w)},{?(0,h)})
      --z[-2] {@{-1,0}-$M},{@{-1,1}-$M},{@{-1,0}+$M},{@{-1,1}+$M},1
      -b[-1] $5 --f[-1] 1 -rotate[-2,-1] {?(-$3,$3)},0,0
      -j[-4] [-2],{@{-3,0}-$M},{@{-3,1}-$M},0,0,$4,[-1] -k[0]
    -done
  -endl -done -v +

#@gmic dotsbw : _nb_scales>=0,_resolution>0,_radius>=0
#@gmic : Apply B&W dots effect on selected images.
#@gmic : Default values: 'nb_scales=4', 'resolution=10' and 'radius=3'.
#@gmic : $ image.jpg --dotsbw 10,10,5
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 @# -l[$>] nm=@{0,n}
    wh={round(w*100/$2,1,1)},{round(h*100/$2,1,1)} $wh,1,100%
    -repeat $1
      --ge[-2] {100*($>+1)/($1+1)}%
      -r[-1] $wh,1,100%,4,0,0.5,0.5
      -b[-1] {$3*($>+1)/($1+1)},0
      -ge[-1] 20%
      -or[-2,-1]
    -done -rm[-2]
  -nm $nm,1 -endl -done -v +

#@gmic draw_whirl : _amplitude>=0
#@gmic : Apply whirl drawing effect on selected images.
#@gmic : Default value: 'amplitude=100'.
#@gmic : $ image.jpg --draw_whirl ,
draw_whirl : -skip ${1=100}
  -e[^-1] "Apply whirl drawing effect on image$? with amplitude $1."
  -v - -repeat @# -l[$>]
    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
  -endl -done -v +

#@gmic drawing : _amplitude>=0
#@gmic : Apply drawing effect on selected images.
#@gmic : Default value: 'amplitude=200'.
#@gmic : $ image.jpg --drawing ,
drawing : -skip ${1=200}
  -e[^-1] "Apply drawing effect on image$? with amplitude $1."
  -v - -repeat @# -l[$>] -split_opacity -l[0] -to_rgb
    -smooth $1,0.2,1,3,3 -b 2 -sharpen 1000 [0]
    -r[0] 20,20,1,3,2 -equalize[0] 256 -index[1] [0],1,1
    -nm[1] @{0,n},1 -rm[0]
  -endl -a c -endl -done -v +

#@gmic drop_shadow : _offset_x[%],_offset_y[%],_smoothness[%],_keep_same_size={ 0 | 1 }
#@gmic : Drop shadow behind selected images.
#@gmic : Default values: 'offset_x=20', 'offset_y=offset_x', 'smoothness=5' and 'keep_same_size=0'.
#@gmic : $ image.jpg -drop_shadow 10,20 -expand_xy 20,0 -display_rgba
drop_shadow : -skip ${1=20},${2=$1},${3=5},${4=0}
  -e[^-1] "Drop shadow behind image$?, with offsets ($1,$2) and smoothness $3."
  -v - -to_rgba -repeat @# -l[$>]
    -if {!$4} -r 150%,150%,1,100%,0,0,0.5,0.5 -endif
    -s c --b[-1] $3 -shift[-1] $1,$2 -or[-2,-1] -a c
    -if {!$4} -autocrop 0,0,0,0 -endif
  -endl -done -v +

#@gmic ellipsionism : _R>0[%],_r>0[%],_smoothness>=0[%],_opacity,_outline>0,_density>0
#@gmic : Apply ellipsionism filter to selected images.
#@gmic : Default values: 'R=10', 'r=3', 'smoothness=1%', 'opacity=0.7', 'outlise=8' and 'density=0.6'.
#@gmic : $ image.jpg --ellipsionism ,
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 @# -l[$>]

    # Compute contour angle.
    --luminance -g[-1] xy -a[-2,-1] c -b[-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)}
      xy={?(w)},{?(h)}
      -ellipse[-1] $xy,$1,$2,@{-2,($xy)},$4,\
                   @{-3,($xy,0,0)},@{-3,($xy,0,1)},@{-3,($xy,0,2)},@{-3,($xy,0,3)}
      -ellipse[-1] $xy,$1,$2,@{-2,($xy)},$4,0x1,\
                   {@{-3,($xy,0,0)}/$5},{@{-3,($xy,0,1)}/$5},{@{-3,($xy,0,2)}/$5},{@{-3,($xy,0,3)}/$5}
    -done -rm[-2]

    # Renormalize and prepare next image.
    -n[-1] [-2] -compose_alpha[-2,-1]
  -endl -done -v +

#@gmic fire_edges : _edges>=0,0<=_attenuation<=1,_smoothness>=0,_threshold>=0,_nb_frames>0,_starting_frame>=0,frame_skip>=0
#@gmic : Generate fire effect from edges of selected images.
#@gmic : Default values: 'edges=0.7', 'attenuation=0.25', 'smoothness=0.5', 'threshold=25', 'nb_frames=1', 'starting_frame=20' and 'frame_skip=0'.
#@gmic : $ image.jpg -fire_edges ,
fire_edges : -check "${1=0.7}>=0 && ${2=0.25}>=0 && $2<=1 && ${3=0.5}>=0 && ${4=25}>=0 && ${5=1}>0 && ${6=20}>=0 && ${7=0}>=0"
  -e[^-1] "Generate fire effect from edges of image$?, with edges $1, attenuation $2, smoothness $3, threshold $4, "\
          "$5 frames, starting frame $6 and frame skip $7."
  -v - -repeat @# -l[$>] nm=@{0,n}
    -norm --gradient_norm -n[-1] 0,1 -roundify[-1] $1 -f[0] 0
    (0,0,0;0,0,0;1,1,1;0,1,0) -*[-1] {(1-$2^4)/4}
    -repeat {$5*(1+$7)+$6}
      @{0,w},@{0,h} -rand[-1] 0,255 -*[-1] [1]
      -b[-1] $3
      -if $4 -ge[-1] $4% -else -equalize[-1] 256 -endif
      -n[-1] 0,255
      -j[0] [-1],0,0,0,0,1,[1],1 -rm[-1]
      -correlate[0] [2]
      -if {$>>=$6" && "($>-$6)%($7+1)==0} [0] -endif
    -done -rm[0-2]
  -nm $nm,1 -endl -done
  (0,255,255,255,255^0,0,255,255,255^0,0,0,128,255) -r[-1] 256,1,1,3,3
  -map[^-1] [-1] -rm[-1] -v +

#@gmic glow : _amplitude>=0
#@gmic : Add soft glow on selected images.
#@gmic : Default value: 'amplitude=1%'.
#@gmic : $ image.jpg --glow ,
glow : -skip ${1=1%}
  -e[^-1] "Add soft glow on image$?, with amplitude $1."
  -v - -repeat @# -l[$>] -split_opacity --b[0] $1 -n[-1] [0] -compose_edges[0,-1] 1 -a c -endl -done -v +

#@gmic hardsketchbw : _amplitude>=0,_density>=0,_opacity,0<=_edge_threshold<=100,_is_fast={ 0 | 1 }
#@gmic : Apply hard B&W sketch effect on selected images.
#@gmic : Default values: 'amplitude=1000', 'sampling=3', 'opacity=0.1', 'edge_threshold=20' and 'is_fast=0'.
#@gmic : $ image.jpg --hardsketchbw 200,70,0.1,10 -median[-1] 2 --local -reverse -blur[-1] 3 -compose_overlay -endl
hardsketchbw : -skip ${1=300},${2=50},${3=0.1},${4=20},${5=0}
  -e[^-1] "Apply hard B&W sketch effect on image$?, with amplitude $1, density $2, opacity $3 and edge threshold $4."
  -if {!$2} -channels 0 -f 255 -return -endif
  -v - -luminance -n 0,1

  -if $5 # Fast version.
    -repeat @# -l[$>] nm=@{0,n}
      -g xy -rv -*[-2] -1 -a c
      -if $4 --norm -ge[-1] $4% -* -endif
      100%,100%,1,1,255 -quiver[-1] [-2],{max(1,10-$2/6)},$1,0,$3 -rm[-2]
    -nm $nm,1 -endl -done

  -else # Slower version.
    -repeat @# -l[$>] nm=@{0,n}

      # Isolate starting points and tangents.
      w={w} h={h} -g xy -rv -*[-2] -1 -a c -* $1
      --norm -ge[-1] $4% 100%,100% -noise[-1] $2,2 -*[-2,-1]

      # Retrieve points coordinates and corresponding tangents.
      -pointcloud3d[-1] -s3d[-1] -rm[-6--5,-3--1] -r[-1] 3,{h/3},1,1,-1 -s[-1] x -rm[-1] -a[-2,-1] c
      -warp[-2] [-1],0,0 ---[-1] [-2] -+[-3,-2] -s[-2,-1] c

      # Convert as a 3d object and render on white background.
      -i[-3] 1,{h} 1,{h} -a[-6--1] x
      -i[-2] ({'CImg3d'}) -i[-2] ({2*h},{h})
      1,{h},1,1,2 1,{h},1,1,2*y --+[-1] 1 -a[-3--1] x
      3,{h} 1,{h},1,1,$3 -y[-6--1] y -a[-6--1] y
      $w,$h,1,1,255 -object3d[-1] [-2],0,0,0,1,1,0,0 -rm[-2]
    -nm $nm,1 -endl -done
  -endif -v +

#@gmic hearts : _density>=0
#@gmic : Apply heart effect on selected images.
#@gmic : Default value: 'density=10'.
#@gmic : $ image.jpg --hearts ,
hearts : -skip ${1=10}
  -e[^-1] "Apply heart filter on image$?, with density $1."
  -v - -repeat @# -l[$>]
    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]
  -endl -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 houghsketchbw : _density>=0,_radius>0,0<=_threshold<=100,0<=_opacity<=1,_votesize[%]>0
#@gmic : Apply hough B&W sketch effect on selected images.
#@gmic : Default values: 'density=8', 'radius=5', 'threshold=80', 'opacity=0.1' and 'votesize=100%'.
#@gmic : $ image.jpg --houghsketchbw ,
houghsketchbw : -check "${1=8}>=0 && ${2=5}>=0 && ${3=80}>=0 && $3<=100 && ${4=0.1}>=0 && $4<=1 && ${5=100%}>0"
  -e[^-1] "Apply hough B&W sketch effect on image$?, with density $1, radius $2, threshold $3, opacity $4 and votesize $5."
  -v - -repeat @# -l[$>] nm=@{0,n}

    # Compute normalized Hough transform.
    res={round(if(@{"-is_percent $5"},$5*max(w,h),$5))} w={w} h={h} rhomax={sqrt(w^2+h^2)/2}
    -hough $res,$res -n 0,255

    # Retrieve coordinates of maximas in hough space.
    -normalize_local[-1] $1,$2 -ge[-1] $3% -pointcloud3d[-1]
    -s3d[-1] -rm[-6--5,-3--1] -r[-1] 3,{h/3},1,1,-1 -columns[-1] 0,1

    # Convert to (x0,y0)-(x1,y1) line coordinates.
    -s[-1] x,2
    -*[-2] {2*pi/$res}                   # theta
    -*[-1] {$rhomax/$res}                # rho
    --cos[-2] -*[-1] [-2] -+[-1] {$w/2}  # x
    --sin[-3] -*[-1] [-3] -+[-1] {$h/2}  # y
    -rm[-3]                              # Remove rho
    -i[-3] [-3]
    -cos[-4] -sin[-3] -*[-4,-3] 10000    # cos(t) sin(t)
    --+[-2] [-3]                         # x + sin(t)
    ---[-2] [-5]                         # y - cos(t)
    --[-4] [-5]                          # x - sin(t)
    -+[-3] [-6]                          # y + cos(t)
    -rm[-6,-5]

    # Transform as a 3d object.
    -i[-3] 1,{h} 1,{h} -a[-6--1] x                  # Vertices
    -i[-2] ({'CImg3d'}) -i[-2] ({2*h},{h})          # Header and size.
    1,{h},1,1,2 1,{h},1,1,2*y --+[-1] 1 -a[-3--1] x # Primitives.
    3,{h},1,1,0 1,{h},1,1,$4                        # Colors and opacities
    -y[-6--1] y -a[-6--1] y

    # Render on a white image.
    $w,$h,1,1,255 -object3d[-1] [-2],0,0,0,1,1,0,0 -rm[-2]
  -nm $nm,1 -endl -done -v +

#@gmic lightrays : 100<=_density<=0,_cx,_cy,_ray_length>=0,_ray_attenuation>=0
#@gmic : Generate ray lights from the edges of selected images.
#@gmic : Defaults values : 'density=50%', 'cx=0.5', 'cy=0.5', 'ray_length=0.9' and 'ray_attenuation=0.5'.
#@gmic : $ image.jpg --lightrays , -+ -c 0,255
lightrays : -check "${1=50}>=0 && $1<=100 && ${4=1} && ${5=1}>=0" -skip ${2=0.5},${3=0.5}
  -e[^-1] "Generate ray lights from image$?, with density $1, center ($2,$3), ray length $4 and attenuation $5."
  -v - -repeat @# -l[$>]
    -gradient_norm -* -1 -lt $1% -euclidean2polar $2,$3
    -repeat {log2(w)} --shift[-1] {2^$>} -+[-2,-1] -done
    -function1d 0.5,0,1,{$4*w},1,{1+($4+1-$5)*w},0 -r[-1] @{-2,w},1,1,1,0
    (1,{w}) -r[-1] @{-2,w},1,1,1,3 -/[-2,-1]
    -r[-1] [-2] -*[-2,-1] -polar2euclidean $2,$3 -n 0,255
  -endl -done -v +

#@gmic light_relief : _ambient_light,_specular_lightness,_specular_size,_light_smoothness,_darkness,_xl,_yl,_zl,_zscale,_opacity_bumpmap={ 0 | 1 }
#@gmic : Apply relief light to selected images.
#@gmic : Default values(s) : 'ambient_light=0.3', 'specular_lightness=0.5', 'specular_size=0.2', 'darkness=0', 'xl=0.2', 'yl=zl=0.5',
#@gmic : 'zscale=1', 'opacity=1' and 'opacity_bumpmap=0'.
#@gmic : $ image.jpg --blur 2 -light_relief[-1] 0.3,4,0.1,0
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 @# -l[$>]
    ({-$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
    -b[-1] $5% -g[-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[^-1]                                                         # Add light property to non-opaque part of the image.
    -+ -c 0,255
    -rv -a c -endl
  -endl -done -v +

#@gmic mosaic : _density>=0,_edges={ 0 | 1 }
#@gmic : Create random mosaic from selected images.
#@gmic : Default values: 'density=0.8' and 'edges=1'.
#@gmic : $ image.jpg --mosaic ,
mosaic : -skip ${1=0.8},${2=1}
  -e[^-1] "Apply mosaic effect on image$?, with density $1."
  -v - -repeat @# -l[$>]
    label0={1+im} -+ $label0
    100%,100% -noise[-1] {$1*2},2 -*[-2] [-1] -distance[-1] 1 -*[-1] -1 -watershed[-2] [-1],{if($2,0,1)} -rm[-1]
    -if $2 --l[-1] -gt 0 -s c -and -endl --[-2] $label0 -*[-2,-1] -else --[-1] $label0 -endif
  -endl -done -v +

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

#@gmic patternbw : nb_levels>=2,_size_dark>=2,_size_bright>=2,_shape={ 0=square | 1=diamond | 2=circle | 3=inv-square | 4=inv-diamond | 5=inv-circle },_smoothness[%]>=0
#@gmic : Apply B&W pattern dithering to selected images.
#@gmic : Default values: 'nb_levels=5', 'size_dark=8', 'size_bright=8', 'shape=5' and 'smoothnesss=0.5'.
#@gmic : $ image.jpg --patternbw ,
patternbw : -check "${1=5}>=2 && ${2=8}>=2 && ${3=8}>=2 && ${5=0.5}>=0" -skip ${4=5}
  -v - s0="square" s1="diamond" s2="circle" s3="inv-square" s4="inv-diamond" s5="inv-circle" -v +
  -e[^-1] "Apply B&W pattern dithering to image$?, with $1 levels, dark size $3, bright size $4, "${s$4}" shape and smoothness $5."
  -v - -luminance -repeat @# -l[$>]
    (0,255) -a y -quantize $1,0 -rows 0,{h-2}
    -repeat $1
      s={round(($2*$<+$3*$>)/($1-1))}
      $s,$s -=[-1] 1,50%,50% -distance[-1] 1,{$4%3} --shift[-1] 50%,50%,0,0,2 -min[-2,-1]
      -if {$4>=3} -lt[-1] {100*$</($1-1.1)}% -*[-1] {-255} -+[-1] {255-$>}
      -else -lt[-1] {100*$>/($1-1.1)}% -*[-1] 255 --[-1] $>
      -endif
      -r[-1] [-2],0,2 -b[-1] $5 --eq[-2] $> -*[-2,-1] -+[-2,-1]
    -done
  -endl -done -v +

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

#@gmic polaroid : _size1>=0,_size2>=0
#@gmic : Create polaroid effect in selected images.
#@gmic : Default values: 'size1=10' and 'size2=20'.
#@gmic : $ image.jpg -to_rgba -polaroid 5,30 -rotate 20 -drop_shadow , -display_rgba
polaroid : -check "${1=10}>=0 && ${2=20}>=0"
  -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 puzzle : _scale>=0
#@gmic : Apply puzzle effect on selected images.
#@gmic : Default value: 'scale=5'.
#@gmic : $ image.jpg --puzzle ,
puzzle : -skip ${1=5}
  -e[^-1] "Apply puzzle effect on image$?, with scale $1%."
  -v - -repeat @# -l[$>] nm=@{0,n}
    --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] -gt[-1] 0 -*[-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]
  -nm $nm,1 -endl -done -v +

#@gmic rodilius : 0<=_amplitude<=100,_0<=thickness<=100,_sharpness>=0,_nb_orientations>0,_offset,_color_mode={ 0=darker | 1=brighter }
#@gmic : Apply rodilius (fractalius-like) filter on selected images.
#@gmic : Default values: 'amplitude=10', 'thickness=10', 'sharpness=400', 'nb_orientations=7', 'offset=0' and 'color_mode=1'.
#@gmic : $ image.jpg --rodilius 12,10,300,10 -normalize_local[-1] 10,6
rodilius : -check "${1=10}>=0 && $1<=200 && ${2=10}>=0 && $2<=100 && ${3=400}>=0 && ${4=7}>0" -skip ${5=0},${6=1}
  -e[^-1] "Apply rodilius filter on image$? with amplitude $1, thickness $2, sharpness $3, $4 orientations, offset $5 and "\
    @{"s0=darker s1=brighter -u ${s{$6!=0}}"}" color mode."
  -v - -repeat @# -l[$>] -split_opacity -rv
    -if {!$6} -negative[-1] -endif
    --f[-1] 0 -nm[-1] @{-2,n}
    -repeat {round($4)}
      angle={$5+$>*180/round($4)}
      --blur_linear[-2] $1%,{$1*$2/100}%,$angle,1 -b[-1] 0.7 -sharpen[-1] $3 -max[-2,-1]
    -done -rm[-2]
    -if {!$6} -negative[-1] -endif
  -rv -a c -endl -done -v +

#@gmic stained_glass : _edges[%]>=0, shading>=0, is_thin_separators={ 0 | 1 }
#@gmic : Generate stained glass from selected images.
#@gmic : Default values: 'edges=40%', 'shading=0.2' and 'is_precise=0'.
#@gmic : $ image.jpg --stained_glass ,
stained_glass : -check "${1=40%}>=0 && ${2=0.2}>=0" -skip ${3=0}
  -e[^-1] "Apply stained glass effect on image$?, with edges $1, shading $2 and thin-separators "@{"-if $3 -u enabled -else -u disabled -endif"}"."
  -v - -repeat @# -l[$>]
    im={1+im} -+ $im  # Ensure positiveness of image labels.
    --gradient_norm -ge[-1] $1 -*[-2] [-1]
    -distance[-1] 1 -sharpen[-1] 1e10 -neq[-1] 0
    -if $3 -skeleton[-1] 0 -endif
    -distance[-1] 1 -watershed[-2] [-1] --[-2] $im
    -n[-1] 0,1  -^[-1] $2 -*
  -endl -done -v +

#@gmic stars : _density[%]>=0,_depth>=0,_size>0,_nb_branches>=1,0<=_thickness<=1,_smoothness[%]>=0,_R,_G,_B,_opacity
#@gmic : Add random stars to selected images.
#@gmic : Default values: 'density=10%', 'depth=1', 'size=32', 'nb_branches=5', 'thickness=0.38', 'smoothness=0.5', 'R=G=B=200' and 'opacity=1'.
#@gmic : $ image.jpg -stars ,
stars : -check "${1=10%}>=0 && ${2=1}>=0 && ${3=32}>0 && ${4=5}>=1 && ${5=0.38}>=0 && $5<=1 && ${6=0.5}>=0" -skip ${7=200},${8=$7},${9=$8},${10=1}
  -e[^-1] "Add $1 random stars to image$?, with depth $2, size $3, $4 branches, thickness $5, smoothness $6, color ($7,$8,$9) and opacity $10."
  -v -

  # Generate star sprites.
  -star3d $4,$5 -col3d[-1] 255 -*3d[-1] $3
  -l[-1] -repeat 4 {round(2*$3)},{round(2*$3)} -object3d[-1] [0],50%,50%,0,1,2,0,0 -r3d[0] 0,0,1,90 -done -rm[0] -endl
  -autocrop[-4--1] 0 -r2dy[-4--1] $3 -b[-4--1] $6,0 -r[-4--1] 100%,100%,1,4
  -repeat 4 -sh[{-1-$>}] 0,2 -fc[-1] $7,$8,$9 -rm[-1] -done

  # Draw stars on selected images.
  -repeat {@#-1} [-4--1] -l[$>,-4--1]
    N={round(if(@{"-is_percent $1"},w*h*$1,$1)/4,1,1)}
    -repeat 4
      2,$N -rand[-1] -1,1 1,$N -rand[-1] 0,1 -a[-2,-1] x
      -i[-2] ({'CImg3d'}) -+[-2] 0.5 -i[-2] ($N;$N)
      (1,0;1,{$N-1}) -r[-1] 2,$N,1,1,3 -round[-1] 4,$N,1,1,1 -y[-5,-3--1] y -a[-5--1] y
      -rv[-2,-1] -sprites3d[-2,-1] -*3d[-1] {0.75*@{0,w}},{0.75*@{0,h}},{1000*$2}
      -object3d[0] [-1],50%,50%,0,$10,0,0,0 -rm[-1]
    -done
  -endl -done
  -rm[-4--1] -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.
#@gmic : Default values: 'nb_orients=2', 'start_angle=45', 'angle_range=180', 'length=30', 'threshold=1', 'opacity=0.03',
#@gmic : 'bgfactor=0', 'density=0.6', 'sharpness=0.1', 'anisotropy=0.6', 'smoothness=0.25', 'coherence=1', 'is_boost=0' and 'is_curved=1'.
#@gmic : $ image.jpg --sketchbw 1 --local -reverse -blur[-1] 3 -compose_overlay -endl
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 - -diffusiontensors $9,$10,$11,$12
  w=1 h=1 -i[0] 1 -m3d 0

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

    -if {$w!=w||$h!=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
      w={w} h={h}
    -endif

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

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

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

#@gmic sponge : _size>0
#@gmic : Apply sponge effect on selected images.
#@gmic : Default value: 'size=13'.
#@gmic : $ image.jpg --sponge ,
sponge : -skip ${1=13}
  -e[^-1] "Apply sponge filter on image$?, with brush size $1."
  -v - -repeat @# -l[$>]
    100%,100%,1,1 -noise[-1] 20,2 -r[-1] [-2] -n[-1] 0,1 -*[-1,-2]
    -_circle $1 -dilate[-2] [-1] -rm[-1]
  -endl -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 stencil : _radius[%]>=0,_smoothness>=0,_iterations>=0
#@gmic : Apply stencil filter on selected images.
#@gmic : Default values: 'radius=3', 'smoothness=1' and 'iterations=8'.
#@gmic : $ image.jpg --stencil 1,10,3
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 -b $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.
#@gmic : Default values: 'edges=15' and 'smoothness=10'.
#@gmic : $ image.jpg --stencilbw 40,4
stencilbw : -skip ${1=15},${2=10}
  -e[^-1] "Apply B&W stencil effect on image$?, with edges $1 and smoothness $2."
  -v - -repeat @# -l[$>]
    -r 100%,100%,1,100% --edges $1 -quantize[-2] 3 -b[-2] $2
    -sharpen[-2] 1000000 -norm[-2] -n[-2] 0,1 -* -n 0,255
  -endl -done -v +

#@gmic tetris : _scale>0
#@gmic : Apply tetris effect on selected images.
#@gmic : Default value: 'scale=10'.
#@gmic : $ image.jpg --tetris 10
tetris : -skip ${1=10}
  -e[^-1] "Apply tetris effect on image$?, with scale $1."
  -v - -repeat @# -l[$>]
    wh={w},{h},1,{s} -r $1%,$1%,$1%,100%,2 -n 0,255 -quantize 10 -r $wh -b 2 -sharpen 300,1
  -endl -done -v +

#@gmic warhol : _M>0,_N>0,_smoothness>=0,_color>=0
#@gmic : Create MxN Andy Warhol-like artwork from selected images.
#@gmic : Default values: 'M=3', 'N=M', 'smoothness=2' and 'color=20'.
#@gmic : $ image.jpg --warhol 5,3,3,40
warhol : -skip ${1=3},${2=$1},${3=2},${4=20}
  -e[^-1] "Create $1x$2 Andy Warhol-like artwork from image$?."
  -v - r0={100/max($1,$2)}
  -repeat @# -l[$>]
    -norm -b $3 -r $r0%,$r0%,1,100%,2 -quantize 6 -n 0,5 -round 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[^0] $1,$2 -nm[1] @{0,n},1 -rm[0]
  -endl -done -v +

#@gmic whirls : _texture>=0,_smoothness>=0,_darkness>=0,_lightness>=0
#@gmic : Add random whirl texture to selected images.
#@gmic : Default values: 'texture=3', 'smoothness=6', 'darkness=0.5' and 'lightness=1.8'.
#@gmic : $ image.jpg --whirls ,
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 @# -l[$>]
    100%,100% -noise[-1] 0.3,2 -repeat $1 -b[-1] $2 -gradient_norm[-1] -^[-1] 0.2 -done
    -n[-1] $3,$4 -r[-1] [-2] -* -c 0,255
  -endl -done -v +

#------------------------------------
#
#@gmic :: Warpings
#
#------------------------------------

#@gmic euclidean2polar : _cx,_cy,_n>0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply euclidean to polar transform on selected images.
#@gmic : Default values: 'cx=cy=0.5', 'n=1' and 'boundary=1'.
#@gmic : $ image.jpg --euclidean2polar ,
euclidean2polar : -skip ${1=0.5},${2=0.5},${3=1},${4=1}
  -e[^-1] "Apply euclidean to polar transform on image$?."
  -v - -repeat @# -l[$>]
    ({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]
  -endl -done -v +

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

#@gmic fisheye : _x,_y,0<=_radius<=100,_amplitude>=0
#@gmic : Apply fish-eye deformation on selected images.
#@gmic : Default values: 'x=y=50', 'radius=50' and 'amplitude=1.2'.
#@gmic : $ image.jpg --fisheye ,
fisheye : -skip ${1=50},${2=50},${3=50},${4=1.2}
  -e[^-1] "Apply Fish-eye effect on image$?, centered at ($1%,$2%) with radius $3% and amplitude $4."
  -if {$4==0} -return -endif
  -v - -repeat @# -l[$>]
    100%,100%,1,1 -=[-1] 1,$1%,$2% -distance[-1] 1 -c[-1] 0,$3% -*[-1] -1 -n[-1] 0,1 -^[-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]
  -endl -done -v +

#@gmic flower : _amplitude,_frequency,_offset_r[%],_angle,_cx,_cy,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply flower deformation on selected images.
#@gmic : Default values: 'amplitude=30', 'frequency=6', 'offset_r=0', 'angle=0', 'cx=cy=0.5' and 'boundary=2'.
#@gmic : $ image.jpg -flower ,
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 @# -l[$>]
    -euclidean2polar $5,$6,1,$7 -shift $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 $5,$6,1,1
  -endl -done -v +

#@gmic kaleidoscope : _cx,_cy,_radius,_angle,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Create kaleidoscope effect from selected images.
#@gmic : Default values: 'cx=cy=0.5', 'radius=100', 'angle=30' and 'boundary=1'.
#@gmic : $ image.jpg --kaleidoscope ,
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 @# -l[$>]
    --columns 0,$3% -rows[-1] 0,$4% -r[-1] [-2],0,2 -nm[1] @{0,n} -rm[0]
  -endl -done -polar2euclidean $1,$2,1,$5 -v +

#@gmic map_sphere : _width>0,_height>0,_radius,_dilation>0,_fading>=0,_fading_power>=0
#@gmic : Map selected images on a sphere.
#@gmic : Default values: 'width=height=512', 'radius=100', 'dilation=0.5', 'fading=0' and 'fading_power=0.5'.
#@gmic : $ image.jpg --map_sphere ,
map_sphere : -check "${1=512}>0 && ${2=512}>0 && ${5=0}>=0 && ${6=0.5}>=0" -skip ${3=100},${4=0.5}
   -e[^-1] "Map image$? on spheres in $1x$2 images, with radius $3, dilation $4 and fading $5."
   -v - r2={($3*min($1,$2)/200)^2} # Compute squared radius.
   -repeat @# -l[$>]
     -i[-2] 100%,1,1,100%,0 -nm[0] @{1,n} -a 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,3 -/[-1] $r2 -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} -^[-1] $4 -*[-1] {@{-3,h}-1} -*[-1] -1 -+[-1] {@{-3,h}-1} # Normalize phi to Y-coordinates
     -if $5 --ge[-1] 1 -distance[-1] 1 -c[-1] 0,$5% -n[-1] 0,1 -^[-1] $6 -c[-2] 1,100% --[-2,-1] -endif
     -a[-2,-1] c -warp[-2] [-1],0,1,1 -rm[-1] # Apply image warping
   -endl -done -v +

#@gmic polar2euclidean : _cx,_cy,_n>0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply polar to euclidean transform on selected images.
#@gmic : Default values: 'cx=cy=0.5', 'n=1' and 'boundary=1'.
#@gmic : $ image.jpg --euclidean2polar , -mirror[-1] x -polar2euclidean[-1] ,
polar2euclidean : -skip ${1=0.5},${2=0.5},${3=1},${4=1}
  -e[^-1] "Apply polar to euclidean transform on image$?."
  -v - -repeat @# -l[$>]
    ({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]
  -endl -done -v +

#@gmic ripple : _amplitude,_frequency,_shape={ 0=bloc | 1=triangle | 2=sine | 3=sine+ | 4=random },_angle,_offset
#@gmic : Apply ripple deformation on selected images.
#@gmic : Default values: 'amplitude=10', 'frequency=10', 'shape=2', 'angle=0' and 'offset=0'.
#@gmic : $ image.jpg --ripple ,
ripple : -skip ${1=10},${2=20},${3=2},${4=0},${5=0}
  -e[^-1] "Apply ripple deformation on image$?, with amplitude $1, frequency $2, shape $3, angle $4° and offset $5."
  -v -
  theta={$4*pi/180} C={cos($theta)} S={-sin($theta)}
  -repeat @# -l[$>]
    100%,100%,1,1,"x" --[-1] {w/2} 100%,100%,1,1,'y'
    --[-1] {h/2-$5} -*[-2] $S -*[-1] $C -+[-2,-1]      # Generate rotated Y.
    -_ripple$3[-1] $1,$2                               # Generate warp field.
    --*[-1] {-$S} -*[-2] $C -a[-2,-1] c                # Rotate warp field.
    -warp[-2] [-1],1 -rm[-1]
  -endl -done -v +

_ripple0 : -f {$1/2}*"(1-2*(i%"{2*$2}"<$2))"
_ripple1 : -f "I=(i%$2)/$2;$1*(2*if(I<0.5,I,1-I)-0.5)"
_ripple2 : -f {-$1/2}*"cos(i*"{2*pi/$2}")"
_ripple3 : -f {-$1/2}*"abs(cos(i*"{2*pi/$2}"))"
_ripple4 : -skip $* -n 0,{h-1} 1,{h} -rand[-1] {-$1/2},{$1/2} m={im} M={iM} -b[-1] {$2/10} -n[-1] $m,$M -map[-2] [-1] -rm[-1]

#@gmic rotoidoscope : _cx,_cy,_tiles>0,_smoothness[%]>=0,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic}
#@gmic : Create rotational kaleidoscope effect from selected images.
#@gmic : Default values: 'cx=cy=50%', 'tiles=10', 'smoothness=1' and 'boundary=1'.
#@gmic : $ image.jpg --rotoidoscope ,
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[$>]
    -repeat $3 --rotate[0] {360/$3},$5,1,$1,$2 -compose_edges $4 -done
  -endl -done -v +

#@gmic transform_polar : "expr_radius",_"expr_angle",_x_center,_y_center,_boundary={ 0=dirichlet | 1=neumann }
#@gmic : Apply user-defined transform on polar representation of selected images.
#@gmic : Default values: 'expr_radius=R-r', 'expr_rangle=a', 'x_center=y_center=50' and 'boundary=1'.
#@gmic : $ image.jpg --transform_polar[0] R*(r/R)^2,a --transform_polar[0] r,2*a
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 @# -l[$>]
    R={"sqrt((max($3,100-$3)*w/100)^2 + (max($4,100-$4)*h/100)^2)"}
    w={"$3*w/100"}
    h={"$4*h/100"}
    -f "R ="$R";
        r = sqrt((x-"$w")^2 + (y-"$h")^2);
        a = atan2(y-"$h",x-"$w");
        nr = $1;
        na = $2;
        i("$w" + nr*cos(na), "$h" + nr*sin(na), z, c, 1,$5)"
  -endl -done -v +

#@gmic twirl : _amplitude,_cx,_cy,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply twirl deformation on selected images.
#@gmic : Default values: 'amplitude=1', 'cx=cy=0.5' and 'boundary=1'.
#@gmic : $ image.jpg --twirl 0.6
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 - -euclidean2polar $2,$3,1,$4 -repeat @#
    [$>],[$>],1,1,$1*x -channels[-1] -1,0 -warp[$>] [-1],1,1,2 -rm[-1]
  -done -polar2euclidean $2,$3,1,1 -v +

#@gmic warp_perspective : _x-angle,_y-angle,_zoom>0,_x-center,_y-center,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Warp selected images with perspective deformation.
#@gmic : Default values: 'x-angle=1.5', 'y-angle=0', 'zoom=1', 'x-center=y-center=50' and 'boundary=2'.
#@gmic : $ image.jpg --warp_perspective ,
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 @# -l[$>]
    (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]
  -endl -done -v +

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

#@gmic wave : _amplitude>=0,_frequency>=0,_center_x,_center_y
#@gmic : Apply wave deformation on selected images.
#@gmic : Default values: 'amplitude=4', 'frequency=0.4' and 'center_x=center_y=50'.
#@gmic : $ image.jpg --wave ,
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 @# -l[$>]
    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]
  -endl -done -v +

#@gmic wind : _amplitude>=0,_angle,0<=_attenuation<=1,_threshold
#@gmic : Apply wind effect on selected images.
#@gmic : Default values: 'amplitude=20', 'angle=0', 'attenuation=0.7' and 'threshold=20'.
#@gmic : $ image.jpg --wind ,
wind : -check "isint(${1=20}) && $1>=0 && ${3=0.7}>=0 && $3<=1" -skip "${2=0},${4=20}"
  -e[^-1] "Apply wind effect on image$?, with amplitude $1, angle "{round($2/45)*45}" deg., attenuation $3 and threshold $4."
  -v -
  -if {!$1} -return -endif
  dxdy=@{-_wind{round($2/45)%8}}
  fact={(1-$3)^(1/$1)}
  -repeat @# -l[$>]
    --gradient_norm -ge[-1] $4%
    sum=@{-1,+} -r[-1] 100%,100%,1,[-2] -*[-1] [-2]
    -repeat $1
      -shift[-1] $dxdy,0,0,0 -max[-2] [-1] -*[-1] $fact
      -remove_pixels[-1] {100/$1},$sum
    -done -rm[-1]
  -endl -done -v +

_wind0 : -u 1,0
_wind1 : -u 1,1
_wind2 : -u 0,1
_wind3 : -u -1,1
_wind4 : -u -1,0
_wind5 : -u -1,-1
_wind6 : -u 0,-1
_wind7 : -u 1,-1

#@gmic zoom : _factor,_cx,_cy,_cz,_boundary={ 0=dirichlet | 1=neumann | 2=cyclic }
#@gmic : Apply zoom factor to selected images.
#@gmic : Default values: 'factor=1', 'cx=cy=cz=0.5' and 'boundary=0'.
#@gmic : $ image.jpg --zoom[0] 0.6 --zoom[0] 1.5
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 @# -l[$>]
    -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]
  -endl -done -v +

#-----------------------------
#
#@gmic :: Degradations
#
#-----------------------------

#@gmic cracks : _density>=0,_amplitude,_relief={ 0 | 1 }
#@gmic : Add random cracks to selected images.
#@gmic : Default values: 'density=0.2', 'amplitude=40' and 'relief=0'.
#@gmic : $ image.jpg --cracks 0.2,60,1
cracks : -skip ${1=0.2},${2=40},${3=0}
  -e[^-1] "Add random cracks to image$?, with density $1."
  -v - -repeat @# -l[$>]
    ({im},{iM}) [-2],[-2],1,1 -noise[-1] $1,2 -distance[-1] 1 -sharpen[-1] 10000
    -if $3 -g[-1] xy -+[-2,-1] -n[-1] -1,1 -else -n[-1] 0,1 -endif
    -*[-1] $2 -+[-3,-1] -c[-2] @-1 -rm[-1]
  -endl -done -v +

#@gmic light_patch : _density>0,_darkness>=0,_lightness>=0
#@gmic : Add light patches to selected images.
#@gmic : Default values: 'density=10', 'darkness=0.9' and 'lightness=1.7'.
#@gmic : $ image.jpg --light_patch 20,0.9,4
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 @# -l[$>]
    -n 0,255 $1,$1 -noise[-1] 40 -r[-1] [-2],5 -c[-1] 0,255
    -n[-1] $2,$3 -* -c 0,255
  -endl -done -v +

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

#@gmic pixelize : _scale_x>0,_scale_y>0,_scale_z>0
#@gmic : Pixelize selected images with specified scales.
#@gmic : Default values: 'scale_x=20' and 'scale_y=scale_z=scale_x'.
#@gmic : $ image.jpg --pixelize ,
pixelize : -skip ${1=20},${2=$1},${3=$1}
  -e[^-1] "Pixelize image$? with scales ($1%,$2%,$3%)."
  -v - -repeat @# -l[$>] whd={w},{h},{d} -r $1%,$2%,$3%,100%,2 -r $whd -endl -done -v +

#@gmic shade_stripes : _frequency>=0,_direction={ 0=horizontal | 1=vertical },_darkness>=0,_lightness>=0
#@gmic : Add shade stripes to selected images.
#@gmic : Default values: 'frequency=5', 'direction=1', 'darkness=0.8' and 'lightness=2'.
#@gmic : $ image.jpg --shade_stripes 30
shade_stripes : -skip ${1=5},${2=1},${3=0.8},${4=2}
  -e[^-1] "Add "@{"s0=horizontal s1=vertical -u ${s{$2!=0}}"}" shaded stripes to image$?, with frequency $1, darkness $3 and lightness $4."
  -v - -n 0,255 -repeat @# -l[$>]
    {max(1,w*($2!=0))},{max(1,h*($2==0))} -noise[-1] $1,2 -distance[-1] 1 -r[-1] [-2] -n[-1] $3,$4 -* -c 0,255
  -endl -done -v +

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

#@gmic spread : _dx>=0,_dy>=0,_dz>=0
#@gmic : Spread pixel values of selected images randomly along x,y and z.
#@gmic : Default values: 'dx=3', 'dy=dx' and 'dz=0'.
#@gmic : $ image.jpg --spread 3
spread : -skip ${1=3},${2=$1},${3=0}
  -e[^-1] "Spread pixel of image$? randomly, with amplitudes ($1,$2,$3)."
  -v - -repeat @# -l[$>]
    100%,100%,100%,3
    -sh[-1] 0,0 -rand[-1] {-$1},$1 -rm[-1]
    -sh[-1] 1,1 -rand[-1] {-$2},$2 -rm[-1]
    -sh[-1] 2,2 -rand[-1] {-$3},$3 -rm[-1]
    -warp[-2] [-1],1 -rm[-1]
  -endl -done -v +

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

#@gmic texturize_canvas : _amplitude>=0,_fibrousness>=0,_emboss_level>=0
#@gmic : Add paint canvas texture to selected images.
#@gmic : Default values: 'amplitude=20', 'fibrousness=3' and 'emboss_level=0.6'.
#@gmic : $ image.jpg --texturize_canvas ,
texturize_canvas : -check "${1=20}>=0 && ${2=3}>=0 && ${3=0.6}>=0 && ${4=80}"
  -e[^-1] "Add canvas texture to image$?, with amplitude $1, fibrousness $2 and emboss level $3."
  -repeat @# -l[$>]
    {w},{h} -rand[-1] 0,255 --blur_x[-1] $2 -blur_y[-2] $2 -+[-2,-1] -g[-1] -a[-2,-1] c
    --compose_channels[-1] + -orientation[-2] -compose_channels[-2] + -n[-2] $3,1 -n[-1] 0,255
    -sharpen[-1] 80 -*[-2,-1] -n[-1] -$1,$1 -+ -c 0,255
  -endl -done -v +

#@gmic texturize_paper
#@gmic : Add paper texture to selected images.
#@gmic : $ image.jpg --texturize_paper
texturize_paper :
  -e[^-1] "Add paper texture to image$?."
  -v - -repeat @# -l[$>]
    [-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]
  -endl -done -v +

#@gmic vignette : _strength>=0,0<=_radius_min<=100,0<=_radius_max<=100
#@gmic : Add vignette effect to selected images.
#@gmic : $ image.jpg --vignette ,
vignette : -check "${1=100}>=0 && ${2=70}>=0 && $2<=100 && ${3=90}>=0 && $3<=100"
  -e[^-1] "Add vignette effect to image$?, with strength $1 and size $2."
  -v - -repeat @# -l[$>]
    mM={im},{iM} d={max(w,h)}
    $d,$d -=[-1] 1,50%,50% -distance[-1] 1 -r[-1] [-2],2
    -c[-1] $2%,$3% -n[-1] 0,$1 -- -c $mM
  -endl -done -v +

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

#--------------------------------------
#
#@gmic :: Blending and fading
#
#--------------------------------------

#@gmic compose_alpha
#@gmic : Compose selected images two-by-two, using alpha blending.
#@gmic : $ image.jpg --drop_shadow , -resize2dy[-1] 200 -rotate[-1] 20 --compose_alpha
compose_alpha :
  -e[^-1] "Compose image$? two-by-two, using alpha blending."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -r[-1] [-2],[-2],[-2],100%,0,0,0.5,0.5
    -to_colormode[-2] {a1=!(@{-2,s}%2);a2=!(s%2);max(@{-2,s}-a1,s-a2)+a1}
    -to_colormode[-1] {a=max(@{-2,s},s);a+(a%2)}
    -if {@{-2,s}==2||@{-2,s}==4} # Background has alpha.
      -_compose_alpha[-2] -_compose_alpha[-1]
      -sh[-1] {s-1},{s-1} --*[-3,-1] -rm[-2] -+[-3,-2] --[-2,-1]
      -sh[-1] 0,{s-2} -sh[-2] {@{-2,s}-1},{@{-2,s}-1}
      -max[-1] 1e-10 -/[-2] [-1] -*[-1] 255 -rm[-2,-1]
    -else                        # Background has no alpha.
      -sh[-1] 0,{s-2} -sh[-2] {@{-2,s}-1},{@{-2,s}-1} --[-2] [-4] -*[-2,-1] -/[-1] 255 -rm[-1] -+[-2,-1]
    -endif
  -endl -done -c 0,255 -v +

_compose_alpha :
  -sh[-1] 0,{s-2} -sh[-2] {@{-2,s}-1},{@{-2,s}-1} -max[-1] 1e-10 -/[-1] 255 -*[-2,-1] -rm[-1]

#@gmic compose_average
#@gmic : Compose selected images two-by-two, using average mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_average
compose_average :
  -e[^-1] "Compose image$? two-by-two, using average mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 -+
  -endl -done -/ 2 -v +

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

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

#@gmic compose_darken
#@gmic : Compose selected images two-by-two, using darken mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_darken
compose_darken :
  -e[^-1] "Compose image$? two-by-two, using darken mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 -min
  -endl -done -v +

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

#@gmic compose_divide
#@gmic : Compose selected images two-by-two, using divide mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_divide
compose_divide :
  -e[^-1] "Compose image$? two-by-two, using divide mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 -*[-2] 256 -+[-1] 1 -/
  -endl -done -c 0,255 -v +

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

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

#@gmic compose_exclusion
#@gmic : Compose selected images two-by-two, using exclusion mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_exclusion
compose_exclusion :
  -e[^-1] "Compose image$? two-by-two, using exclusion mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 --*[-2] [-1] -/[-1] -128 -+
  -endl -done -v +

#@gmic compose_fade
#@gmic : Compose selected images togethers using a given fading pattern (defined as the latest image).
#@gmic : $ image.jpg -testimage2d {w},{h} 100%,100%,1,1,'cos(y/10)' -normalize[-1] 0,1 --compose_fade
compose_fade :
  -e[^-1] "Compose image$? using fading mode."
  -v - -r[^0] @{-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_freeze
#@gmic : Compose selected images two-by-two, using freeze mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_freeze
compose_freeze :
  -e[^-1] "Compose image$? two-by-two, using freeze mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 --[-2] 255 -sqr[-2] -+[-1] 0.1 -/
  -endl -done -- 255 -* -1 -c 0,255 -v +

#@gmic compose_grainextract
#@gmic : Compose selected images two-by-two, using grain extract mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_grainextract
compose_grainextract :
  -e[^-1] "Compose image$? two-by-two, using grain extract mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 --
  -endl -done -+ 128 -c 0,255 -v +

#@gmic compose_grainmerge
#@gmic : Compose selected images two-by-two, using grain merge mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_grainmerge
compose_grainmerge :
  -e[^-1] "Compose image$? two-by-two, using grain merge mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 -+
  -endl -done -- 128 -c 0,255 -v +

#@gmic compose_hardlight
#@gmic : Compose selected images two-by-two, using hard light mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_hardlight
compose_hardlight :
  -e[^-1] "Compose image$? two-by-two, using hard light mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5
    --ge[-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] -+
  -endl -done -v +

#@gmic compose_hue
#@gmic : Compose selected images two-by-two, using hue mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_hue
compose_hue :
  -e[^-1] "Compose image$? two-by-two, using hue mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 -to_rgba -sh 0,2
    -rgb2hsv[-2,-1] -sh[-2] 0,0 -j[-2] [-1] -rm[-5,-3,-1] -hsv2rgb[-1] -rm[-1]
  -endl -done -v +

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

#@gmic compose_lighten
#@gmic : Compose selected images two-by-two, using lighten mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_lighten
compose_lighten :
  -e[^-1] "Compose image$? two-by-two, using lighten mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 -max
  -endl -done -v +

#@gmic compose_lightness
#@gmic : Compose selected images two-by-two, using lightness mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_lightness
compose_lightness :
  -e[^-1] "Compose image$? two-by-two, using lightness mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 -to_rgba -sh 0,2
    -rgb2lab[-2,-1] -sh[-2] 0,0 -j[-2] [-1],0,0,0,0 -rm[-5,-3,-1] -lab2rgb[-1] -rm[-1]
  -endl -done -v +

#@gmic compose_luminance
#@gmic : Compose selected images two-by-two, using luminance mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_luminance
compose_luminance :
  -e[^-1] "Compose image$? two-by-two, using luminance mode."
  -v - -repeat {int(@#/2)}
    -to_colormode[-2,-1] 0 -r[-1] [-2],0,0,0.5,0.5 -to_rgba[-2,-1] -sh[-2,-1] 0,2
    -rgb2ycbcr[-2,-1] -sh[-2] 0,0 -j[-2] [-1],0,0,0,0 -rm[-5,-3,-1] -ycbcr2rgb[-1] -rm[-1]
  -mv[-1] 0 -done -v +

#@gmic compose_median
#@gmic : Compose selected images together using median mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --mirror[0] y --compose_median
compose_median :
  -e[^-1] "Compose image$? using median mode."
  -if {@#==1} -return -endif
  -v - -r[^0] [0],0,0,0.5,0.5 -a z -permute zxyc -s y,-64
  -repeat @# -l[$>]
    -r 100%,{w*100}%
    -s z -median {w} w={w} -columns {int(w/2)} -r 1,{h/$w} -a z
  -endl -done -a y -permute yzxc -v +

#@gmic compose_multiply
#@gmic : Compose selected images two-by-two, using multiply mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_multiply
compose_multiply :
  -e[^-1] "Compose image$? two-by-two, using multiply mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 -*
  -endl -done -/ 255 -v +

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

#@gmic compose_overlay
#@gmic : Compose selected images two-by-two, using overlay mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_overlay
compose_overlay :
  -e[^-1] "Compose image$? two-by-two, using overlay mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5
    --ge[-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] -+
  -endl -done -v +

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

#@gmic compose_rgba
#@gmic : Compose selected images two-by-two, as RGBA images over RGB backgrounds.
compose_rgba :
  -e[^-1] "Compose image$? two-by-two, using alpha blending."
  -v - -to_rgb[0--1:2] -compose_alpha -v +

#@gmic compose_saturation
#@gmic : Compose selected images two-by-two, using saturation mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_saturation
compose_saturation :
  -e[^-1] "Compose image$? two-by-two, using saturation mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 -to_rgba -sh 0,2
    -rgb2hsv[-2,-1] -sh[-2] 1,1 -j[-2] [-1],0,0,0,1 -rm[-5,-3,-1] -hsv2rgb[-1] -rm[-1]
  -endl -done -v +

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

#@gmic compose_shapeaverage
#@gmic : Compose selected images two-by-two, using shape average mode.
#@gmic : $ image.jpg --luminance -stencil[-1] 1 --compose_shapeaverage
compose_shapeaverage :
  -e[^-1] "Compose image$? two-by-two, using shape average mode."
  -v - -repeat {int(@#/2)} -l[-2,-1] nm=@{0,n}
    -channels[-1] 0 -ge[-1] 50% -label_fg[-1] 0 nb={iM+1} -*[-1] 256
    -rv[-2,-1] m={im} M={iM} -n[-1] 0,255 -s[-1] c -+[^0] [0]
    -repeat {@#-1}
      -histogram[-1] {$nb*256},0,{$nb*256-1}
      -i[-2] 256,1,1,1,'x' -r[-2] {w},1,1,1,0,2 -*[-2] [-1] -r[-2,-1] $nb,1,1,1,2 -/[-2,-1]
    -mv[-1] 1 -done
    -/[0] 256 -a[^0] c -*[-1] {($M-$m)/256} -+[-1] $m -point[-1] 0,0,0,1,0 -map[0] [-1] -rm[-1]
  -nm $nm,1 -endl -mv[-1] 0 -done -v +

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

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

#@gmic compose_value
#@gmic : Compose selected images two-by-two, using value mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_value
compose_value :
  -e[^-1] "Compose image$? two-by-two, using value mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 -to_rgba -sh 0,2
    -rgb2hsv[-2,-1] -sh[-2] 2,2 -j[-2] [-1],0,0,0,2 -rm[-5,-3,-1] -hsv2rgb[-1] -rm[-1]
  -endl -done -v +

#@gmic compose_xor
#@gmic : Compose selected images two-by-two, using xor mode.
#@gmic : $ image.jpg -testimage2d {w},{h} --compose_xor
compose_xor :
  -e[^-1] "Compose image$? two-by-two, using xor mode."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    -to_colormode 0 -r[-1] [-2],0,0,0.5,0.5 -xor
  -endl -done -v +

_fade :
  -r[-2] [-3],5 -r[-1] [-2],3 -c[-1] $1%,$2% -n[-1] 0,1 -j[-3] [-2],0,0,0,0,1,[-1] -rm[-2,-1]

#@gmic fade_diamond : 0<=_start<=100,0<=_end<=100
#@gmic : Create diamond fading from selected images.
#@gmic : Default values: 'start=80' and 'end=90'.
#@gmic : $ image.jpg -testimage2d {w},{h} --fade_diamond 80,85
fade_diamond : -skip ${1=70},${2=90}
  -e[^-1] "Create ($1%,$2%) diamond-shaped fading from image$?."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    (0,1,0;1,1,1;0,1,0) -_fade $1,$2
  -endl -done -v +

#@gmic fade_linear : _angle,0<=_start<=100,0<=_end<=100
#@gmic : Create linear fading from selected images.
#@gmic : Default values: 'angle=45', 'start=30' and 'end=70'.
#@gmic : $ image.jpg -testimage2d {w},{h} --fade_linear 45,48,52
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)} -l[$>,{$>+1}]
     64,64,1,1,"x*cos($1*pi/180) + y*sin($1*pi/180)" -_fade $2,$3
  -endl -done -v +

#@gmic fade_radial : 0<=_start<=100,0<=_end<=100
#@gmic : Create radial fading from selected images.
#@gmic : Default values: 'start=30' and 'end=70'.
#@gmic : $ image.jpg -testimage2d {w},{h} --fade_radial 30,70
fade_radial : -skip ${1=30},${2=70}
  -e[^-1] "Create ($1%,$2%) radial fading from image$?."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}]
    100%,100% -=[-1] 1,50%,50% -distance[-1] 1 -_fade $1,$2
  -endl -done -v +

#@gmic fade_x : 0<=_start<=100,0<=_end<=100
#@gmic : Create horizontal fading from selected images.
#@gmic : Default values: 'start=30' and 'end=70'.
#@gmic : $ image.jpg -testimage2d {w},{h} --fade_x 30,70
fade_x : -skip ${1=30},${2=70}
  -e[^-1] "Create ($1%,$2%) horizontal fading from image$?."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}] (0,1) -_fade $1,$2 -endl -done -v +

#@gmic fade_y : 0<=_start<=100,0<=_end<=100
#@gmic : Create vertical fading from selected images.
#@gmic : Default values: 'start=30' and 'end=70'.
#@gmic : $ image.jpg -testimage2d {w},{h} --fade_y 30,70
fade_y : -skip ${1=30},${2=70}
  -e[^-1] "Create ($1%,$2%) vertical fading from image$?."
  -v - -repeat {int(@#/2)} -l[$>,{$>+1}] (0;1) -_fade $1,$2 -endl -done -v +

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

#---------------------------------------------
#
#@gmic :: Image sequences
#
#---------------------------------------------

#@gmic animate : filter_name,"param1_start,..,paramN_start","param1_end,..,paramN_end",nb_frames>=0,_output_frames={ 0 | 1 },_output_filename : delay>0
#@gmic : Animate filter from starting parameters to ending parameters or animate selected images
#@gmic : in a display window.
#@gmic : Default value: 'delay=30'.
#@gmic : $ image.jpg -animate flower,"0,3","20,8",9
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 -
    speed=$1    # Animation speed
    pause=-1    # Pause mode.
    direction=1 # Animation direction.
    frame=0     # Current frame.
    -do
      -w[$frame] -1,-1,1,0,@{$frame,b}.@{$frame,x}
      frame={$frame+$direction}
      -if $2
        -if {$frame==-1} frame=0 direction=1
        -elif {$frame==@#} frame={@#-1} direction=-1
        -endif
      -else frame={$frame%@#}
      -endif
      -wait $speed
      -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} speed={min(500,max(10,$speed-10*@{!,o}))} -wait -1 -endif
      -if @{!,SPACE}
        -if {$pause>=0} direction=$pause pause=-1
        -else pause=$direction direction=0 -endif
        -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) -y[-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 morph : nb_frames>0,_smoothness>=0,_precision>0
#@gmic : Create morphing sequence between selected images.
#@gmic : Default values: 'smoothness=0.1' and 'precision=5'.
#@gmic : $ image.jpg --rotate 20,1,1,50%,50% -morph 9
morph : -skip ${2=0.1},${3=5}
  -e[^-1] "Create morphing sequence between image$?, with $1 intra-frames, smoothness $2 and precision $3.\n"
  -v - -r[^0] [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[-1] [-2],$2,$3 --warp[-5] [-1],1,1,1,$1 -a[-$1--1] z -rm[-2]
    --displacement[-3] [-2],$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.
#@gmic : Default values: 'smoothness=0.2', 'precision=6' and 'nb_scale=0(auto)'.
#@gmic : $ image.jpg --rotate 20,1,1,50%,50% --register_nonrigid , -remove[-2]
register_nonrigid : -skip ${1=0.2},${2=5},${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 -rm[-2]
    -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.
#@gmic : Default value: 'smoothness=1'.
#@gmic : $ image.jpg --shift 30,20 --register_rigid , -remove[-2]
register_rigid : -skip ${1=1}
  -e[^-1] "Register image$? with rigid warp and smoothness $1."
  -v - --equalize[0] 256 -b[-1] $1 -n[-1] 0,255 -mv[-1] 1
  -repeat @# -if {$>>1}
    --equalize[-1] 256 -b[-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 transition3d : _nb_frames>=2,_nb_xtiles>0,_nb_ytiles>0,_axis_x,_axis_y,_axis_z,_is_antialias
#@gmic : Create 3d transition sequence between selected consecutive images.
#@gmic : 'axis_x', 'axis_y' and 'axis_z' can be set as mathematical expressions, depending on 'x' and 'y'.
#@gmic : Default values: 'nb_frames=10', 'nb_xtiles=nb_ytiles=3', 'axis_x=1', 'axis_y=1', 'axis_z=0' and 'is_antialias=1'.
#@gmic : $ image.jpg --blur 5 -transition3d 9 -drgba
transition3d : -check "isint(${1=10}) && $1>=2 && isint(${2=3}) && $2>0 && isint(${3=$2}) && $3>0" -skip ${4=1},${5=1},${6=0},${7=1}
  -e[^-1] "Create 3d transition sequence between image$?, with $1 frames, $2x$3 tiles and rotation axis ($4,$5,$6).\n"
  -v -
  -if {@#<2} -return -endif
  -slices 0 -to_rgb -r @{-max_whds},3
  off=0 -repeat {@#-1} -l[{$>+$off},{$>+$off+1}]
    -v + -e[] "\r > Generate transition from image "$>" to image "{$>+1}".    " -v -

    # Create 3d rotation vectors.
    $2,$3,1,1,'$4'
    $2,$3,1,1,'$5'
    $2,$3,1,1,'$6'
    -a[-3--1] z
    -permute[-1] zxyc -r[-1] 3,{$2*$3},1,1,-1
    -repeat {h} rot$>=@{-1,0-2} -shift[-1] 0,-1,0,0 -done
    -rm[-1]

    # Create 3d tiles.
    --split_tiles[-2,-1] $2,$3 -mv[0,1] @#
    N={$2*$3} i=0 y=0
    -repeat $3
      x=0
      -repeat $2
        lw=@{$i,w} lh=@{$i,h}
        -imageplane3d[$i] -imageplane3d[$N] -r3d[$N] ${rot$i},-180 -c3d[$i,$N] -+3d[$i,$N]
        x$i=$x y$i=$y x={$x+$lw} i={$i+1}
      -done
      y={$y+$lh}
    -done

    # Generate intermediate animation frames.
    -repeat {$1-2}
      -repeat $N -r3d[$>] ${rot$>},{180/($1-1)} --+3d[$>] ${x$>},${y$>},0 -done
      -+3d[-$N--1] -c3d[-1]

      -if $7  # Antialiased rendering.
        -i[-3] {2*@{-2,w}},{2*@{-2,h}},1,3,-1
        -*3d[-1] 2 -object3d[-3] [-1],50%,50%,0,1,2,0,0 -rm[-1]
        -to_rgba[-2] -replace_color[-2] 0,0,-1,-1,-1,255,0,0,0,0
        -r[-2] [-1],[-1],1,100%,2
      -else  # Standard rendering.
        -i[-3] @{-2,w},@{-2,h},1,3,-1 -object3d[-3] [-1],50%,50%,0,1,2,0,0 -rm[-1]
        -to_rgba[-2] -replace_color[-2] 0,0,-1,-1,-1,255,0,0,0,0
      -endif

    -done
    -rm[0-{$N-1}]
    -nm[1--2] @{0,n}
    off={$off+$1-2}
  -endl -done
  -v +

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

#@gmic x_blobs
#@gmic : Launch the blobs editor.
x_blobs :
  -e[] "\n
------ Blobs editor --------------------------\n
----\n
---- Mouse to insert/move/delete blobs.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------------------"
  -v -

  # Create background image [0].
  -rm (0;0^0;128^0;255) -r[-1] 350,350,1,3,3 -flower[-1] 30,8,0,0,0.5,0.5,1 -water[-1] 20
  -w {w},{h},0,0,"[G'MIC] Blobs editor"

  # Start event loop.
  moving=-1
  -do
    x=@{!,x} y=@{!,y} b=@{!,b} nearest=-1

    # Render image of blobs and find nearest blob to mouse pointer.
    -if {@#>1}
      @{!,w},@{!,h},1,2
      -repeat @{1,h}
        r={@{1,2}*(1+@{1,3}*cos(@{1,4}+@{1,5}*@|*1000))}
        -ellipse[-1] @{1,0,1},$r,$r,0,1,@{1,6-7}
        d={sqrt(($x-@{1,0})^2+($y-@{1,1})^2)}
        -if {$d<$r} nearest=$> -endif
      -shift[1] 0,-1,0,0,2 -done
      -b[-1] 15
      --norm[-1] --ge[-1] 50 -le[-2] 40 -*[-3,-1]
      --*[0,-1] -rm[-2] -rv[-2,-1] -*[-1] 1.6 -c[-1] 0,255 -+[-2,-1]
      -w[-1] {w},{h} -rm[-1]
    -else
      --text_outline[0] "G'MIC Blobs Editor",65,40,24,3,1,200,128,255
      -t[-1] "* Left mouse button : Create and move blobs.\n\n\
              * Right mouse button : Remove blob.\n\n\
              * Middle mouse button : Remove all blobs.\n\n\
              * Key 'ESC' or 'Q' : Quit.\n\n\
              * Colors and sizes of appearing blobs are\n   chosen randomly",\
             60,120,13,1,255
      -w[-1] {w},{h} -rm[-1]
    -endif
    -wait 20

    # Manage blob insertion, removal or move.
    -if {$x<0||$y<0} -continue -endif
    -if {$b&1}
      -if {$nearest>=0" || "$moving>=0} # Move existing blob.
        -if {$moving<0} moving=$nearest -endif
        -=[1] $x,0,$moving -=[1] $y,1,$moving
        -else # Insert new blob.
          (@{!,x},@{!,y},{?(20,50)},{?(-0.3,0.3)},{?(0,pi/2)},{?(0,0.009)},{?(64,255)},{?(64,255)}) -a[^0] y
          moving={h-1}
        -endif
    -elif {$b&2} # Remove existing blob.
      -if {$nearest>=0} -l[1] -s y -rm[$nearest] -a y -endl nearest=-1 -endif
    -elif {$b&4} # Remove all blobs.
      -k[0]
    -else
      moving=-1
    -endif

  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm -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,"[G'MIC] 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.21
  -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 -b[-1] 10
  -sharpen[-1] 1000 -shrink_xy[-1] 1 -n[-1] 0,255 -to_rgb[-1] -light3d [-1] -rm[-1]

  # Start animation loop.
  angle=0
  -do
    -correlate[0] [2]                                                # Apply fire effect.
    @{0,w},1 -rand[-1] 128,256 -j[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
    --r3d[3] 0,1,0,$angle -object3d[-2] [-1],50%,50%,0,1,5,0,0       # Draw 3d object.
    -*3d[-1] 0.25,0.16,1 -object3d[0] [-1],50%,50%,0,1,3,0,0
    -rm[-1]
    angle={$angle+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_fireworks
#@gmic : Launch the fireworks demo.
x_fireworks :
  -e[] "\n
------ Fireworks demo -------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v - -l[]
  time=0
  (0;64^0;32^128;0) -r 256,128,1,3,3          # [-2] = Background (color gradient).
  [-1]                                        # [-1] = Rendered image.
  -w[-1] 512,256,0,0,"[G'MIC] Fireworks demo" # Display window.
  -do                                         # Start animation loop.
    time={$time-1}
    -if {@#==2\ ||\ $time<0} # Insert new rocket.
      -i[0] ({?(w)},\        # X-position
             {h},\           # Y-position
             {?(-3,3)},\     # X-velocity
             {?(2)-5},\      # Y-velocity
             {30+?(20)},\    # Time of explosion
             1.5,\           # Radius
             255,255,255)    # Color
      time={?(40)}           # Elapsed time until next rocket.
    -endif
    -*[-1] 0.99               # Create fading effect with previous frames.
    -j[-1] [-2],0,0,0,0,0.2   # Add background.
    i=0
    -repeat {@#-2}
      to_be_removed=0
      radius={if(@{$i,4}>0,@{$i,5}/3,@{$i,5}*(1+2*(@{$i,4}+2)/120))}
      -ellipse[-1] @{$i,0},@{$i,1},@{$i,5},{max(0.5,$radius)},{atan2(@{$i,3},@{$i,2})*180/pi},0.6,@{$i,6-8}  # Draw rocket.
      (@{$i,2},@{$i,3},0,0.09,-1,0,0,0,0) -+[$i,-1] # Compute new position of the rocket.
      -if {@{$i,0}<0\ ||\ @{$i,0}>=w\ ||\ @{$i,1}>=h\ ||\ $radius<0} to_be_removed=1 -endif # Discard if rocket disappear.
      -if {@{$i,4}<0\ &&\ @{$i,4}>=-1} # In case of explosion -> Split current rocket into several colorful rockets.
        color={min(255,80+?(200))},{min(255,80+?(200))},{min(255,80+?(200))}
        radius={?(10)}
        N={5+?(10)}
        -repeat $N
          angle={$>*2*pi/$N}
          -i[-3] (@{$i,0,1},{2*cos($angle)+@{$i,2}/1.5},{2*sin($angle)+@{$i,3}/1.5},-2,$radius,$color)
        -done
        to_be_removed=1
      -endif
      -if $to_be_removed -rm[$i] -else i={$i+1} -endif  # If processed rocket has to be removed.
    -done
    -w[-1] -wait 20  # Display rendered frame.
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -endl -k[-1] -w[] 0 -v +

#@gmic x_fisheye
#@gmic : Launch fish-eye demo.
x_fisheye :
  -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
  -t "  G'MIC\nFISH-EYE\n  DEMO",15,13,24,1,255 -resize2x -b 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)} --r3d[-1] 1,0,0,90
  -col3d[-1] {?(30,255)},{?(30,255)},{?(30,255)} -+3d[-1] 15 -+3d[-2,-1] -db3d 0 -c3d[-1]
  R=30
  -w[-2] {2*@{-2,w}},{2*@{-2,h}},0,0,"[G'MIC] Fish-Eye Demo"
  -do
    -wait 40
    -if {@{!,b}==1} R={min(80,$R+8)} -endif
    -if {@{!,b}==2} R={max(3,$R-8)} -endif
    --object3d[-2] [-1],{50+30*cos(@|*2.5)}%,{50+30*sin(@|*1.6)}%,{50+330*sin(@|*2.6)},0.7,3,0,0 -r3d[-2] 1,0.2,0.6,3
    -if {@{!,x}>=0}
    -fisheye[-1] {@{!,x}*100/@{!,w}},{@{!,y}*100/@{!,h}},$R
    -endif
    -w[-1] -rm[-1]
    -if {@!==0" || "@{!,ESC}" || "@{!,Q}} -rm[-2,-1] -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
  -while 1

#@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
-----------------------------------------------------------------"
  -v -
  -if {!@#} -testimage2d 256 -endif
  -repeat @# -l[$>]

    # Init variables.
    need_update=1  # need_update (boolean)
    freqmin=0      # min freq. (in %)
    freqmax=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] -nm[-2] real -nm[-1] imag

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

    # Enter user event-loop.
    -do

      -if $need_update # If image must be updated.

        # Generated filtering mask.
        -i[mask] 100%,100%
        r={sqrt(w^2+h^2)*$freqmax/200} -ellipse[mask] 50%,50%,$r,$r,0,1,1
        r={max(0,sqrt(w^2+h^2)*$freqmin/200-1)} -if $r -ellipse[mask] 50%,50%,$r,$r,0,1,0 -endif

        # Compute filtered log-magnitude.
        --*[logmag] [mask] -+[-1] [mask] -/[-1] 2 -n[-1] 0,255

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

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

        # Display filtered image.
        -rv[-2,-1]
        -if @! -r[-2,-1] {@{!,w}/2},@{!,h} -endif
        -t[-1] "Freq. Min/Max = "{int($freqmin)}"% / "{int($freqmax)}"%",5,5,13,1,255
        -w[-2,-1] -1,-1,0,0,"[G'MIC] Fourier Filtering Demo"
        -rm[-2,-1]
        need_update=0

      -endif

      -wait

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

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

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

#@gmic x_histogram
#@gmic : Launch histogram demo.
x_histogram :
  -e[] "\n
------ Histogram demo -------------------------------\n
----\n
---- Mouse to set parameters.\n
---- Right button or key 'SPACE' to reset.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------------------"
  -v -
  -if {!@#} -testimage2d 300,300 -else -k[0] -to_rgb -r2dy 300 -if {w>800} -r 800,100%,1,3,2 -endif -n 0,255 -endif

  # Prepare image layout.
  --frame[-1] 1,1,0
  300,{h},1,3,220
  -t[-1] "Gamma :",5,0,16,1,0
  -t[-1] "Contrast :",5,50,16,1,0
  -t[-1] "Brightness :",5,100,16,1,0
  -t[-1] "Smoothness :",5,150,16,1,0
  -t[-1] "Sharpness :",5,200,16,1,0
  -t[-1] "Clusters :",5,250,16,1,0
  -a[-2,-1] x
  {w},200,1,3,255
  -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,0
  -rectangle[-1] 0,0,100%,100%,1,0xFFFFFFFF,0
  -axes[-1] 0,255,1,0,13,1,0
  -frame[-2,-1] 5,5,220
  -a[-2,-1] y

  # Initialize variables.
  clusters=64 sharpness=0 smoothness=0 contrast=1 brightness=0 gamma=1

  # Start event loop.
  -do

    # Render corrected image and insert it in canvas.
    [0]
    ia={ia}
    -if $gamma -/[-1] 255 -^[-1] {1/$gamma} -*[-1] 255 -endif
    --[-1] $ia -*[-1] $contrast -+[-1] $brightness -+[-1] $ia
    -b[-1] $smoothness
    -sharpen[-1] $sharpness
    -c[-1] 0,255
    --j[-2] [-1],6,6

    # Render parameter sliders.
    sx={@{0,w}+12}
    -_x_histogram[-1] {$gamma*100/4} -j[-2] [-1],$sx,25 -rm[-1]
    -_x_histogram[-1] {$contrast*100/4} -j[-2] [-1],$sx,75 -rm[-1]
    -_x_histogram[-1] {($brightness+128)*100/256} -j[-2] [-1],$sx,125 -rm[-1]
    -_x_histogram[-1] {$smoothness*100/10} -j[-2] [-1],$sx,175 -rm[-1]
    -_x_histogram[-1] {$sharpness*100/2000} -j[-2] [-1],$sx,225 -rm[-1]
    -_x_histogram[-1] {$clusters*100/256} -j[-2] [-1],$sx,275 -rm[-1]

    # Render corresponding histogram.
    --s[-2] c -histogram[-3--1] $clusters,0,255 -/[-3--1] {3*@{0,wh}/$clusters} -rm[-5]
    --z[-4] 5,317,{@{-4,w}-5},{@{-4,h}-6}
    -graph[-1] [-4],3,0,1,0,0.2,255,0,0
    -graph[-1] [-3],3,0,1,0,0.2,0,255,0
    -graph[-1] [-2],3,0,1,0,0.2,0,0,255
    -rm[-4--2]
    -j[-2] [-1],5,317 -rm[-1]

    # Display rendering.
    -w[-1] {w},{h},0,0,"[G'MIC] Histogram demo" -rm[-1]
    -wait

    # Manage user interactions.
    -if {@{!,b}&1\ &&\ @{!,x}>=@{0,w}-10}
      -if {@{!,y}>=25\ &&\ @{!,y}<=42}
        gamma={max(0,min(4,(@{!,x}-$sx)*4/280))}
      -elif {@{!,y}>=75\ &&\ @{!,y}<=92}
        contrast={max(0,min(4,(@{!,x}-$sx)*4/280))}
      -elif {@{!,y}>=125\ &&\ @{!,y}<=142}
        brightness={max(-128,min(128,(@{!,x}-$sx)*256/280-128))}
      -elif {@{!,y}>=175\ &&\ @{!,y}<=192}
        smoothness={max(0,min(10,(@{!,x}-$sx)*10/280))}
      -elif {@{!,y}>=225\ &&\ @{!,y}<=242}
        sharpness={max(0,min(2000,(@{!,x}-$sx)*2000/280))}
      -elif {@{!,y}>=275\ &&\ @{!,y}<=292}
        clusters={max(2,min(256,(@{!,x}-$sx)*256/280))}
      -endif
    -endif
    -if {@{!,b}&2\ ||\ @{!,SPACE}} clusters=64 sharpness=0 smoothness=0 contrast=1 brightness=0 gamma=1 -endif
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -w 0 -rm -v +

_x_histogram :
  val={max(0,min(100,$1))}
  280,2,1,3,255 -line[-1] 0,0,$val%,0,1,0,255,0 -line[-1] 0,1,$val%,1,1,240,255,62 -r[-1] 100%,16,1,3,3
  0 -t[-1] {round($val)}%,0,0,20,1,1 --*[-1] -255 -+[-1] 255 -r[-1] 100%,100%,1,3
  -j[-3] [-1],{(280-w)/2},{(16-h)/2},0,0,1,[-2] -rm[-2,-1]
  -r[-1] {w+2},{h+2},1,3,0,0,0.5,0.5

#@gmic x_hough
#@gmic : Launch hough transform demo.
x_hough :
  -e[] "\n
------ Hough-transform demo -----------------------------------\n
----\n
---- Mouse buttons on the vote image to draw corresponding line.\n
---- Mouse buttons on the image to vote for all lines crossing.\n
---- the clicked point.\n
---- Key 'SPACE' to reset the hough window.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------------------------------"
  -v -
  -if {!@#} -testimage2d 400 -endif
  -n 0,255 -repeat @# -l[$>]
    -r[-1] @{-fitscreen\ {w},{h}},1,100%,3  # Resize to fit screen if necessary.

    rhomax={sqrt(w^2+h^2)/2}
    --b[-1] 1.5 -hough[-1] 512,400 -b[-1] 0.5 -+[-1] 1 -log[-1] -n[-1] 0,255
    -w[-2] -1,-1,0,0,"[G'MIC] Image" -w1[-1] -1,-1,0,0,"[G'MIC] Hough Transform"

    -do
      -wait

      -if @{!,b} # When clicking on the image.
        x0={@{!,x}-@{!,w}/2}
        y0={@{!,y}-@{!,h}/2}
        rho0={sqrt(($x0)^2+($y0)^2)}
        theta0={atan2($y0,$x0)}
        (0,{2*pi}) ($theta0,{$theta0-2*pi})
        -r[-2,-1] @{-3,w},1,1,1,3
        -cos[-1] -*[-1] $rho0 --lt[-1] 0 -abs[-2]
        -*[-1] {pi} -+[-3,-1] -%[-2] {2*pi}
        -*[-2] {0.5*@{-3,w}/pi} -*[-1] {@{-3,h}/$rhomax}
        -a[-2,-1] y
        -repeat {w} -point[-2] @{-1,($>,0)},@{-1,($>,1)},0,0.3,255 -done
        -rm[-1] -w1[-1]

      -elif {@{!1,x}>=0" && "@{!1,b}} # When clicking on the vote window.
        theta={@{!1,x}*2*pi/@{!1,w}}
        rho={@{!1,y}*$rhomax/@{!1,h}}
        x={@{-2,w}/2+$rho*cos($theta)}
        y={@{-2,h}/2+$rho*sin($theta)}
        x0={$x+1000*sin($theta)}
        y0={$y-1000*cos($theta)}
        x1={$x-1000*sin($theta)}
        y1={$y+1000*cos($theta)}
        [-2]
        -line[-1] $x0,$y0,$x1,$y1,1,0x0F0F0F0F,255
        -line[-1] {$x0+1},$y0,$x1,$y1,1,0x0F0F0F0F,255
        -line[-1] $x0,{$y0+1},$x1,$y1,1,0x0F0F0F0F,255
        -line[-1] $x0,$y0,$x1,$y1,1,0xF0F0F0F0,0
        -line[-1] {$x0+1},$y0,$x1,$y1,1,0xF0F0F0F0,0
        -line[-1] $x0,{$y0+1},$x1,$y1,1,0xF0F0F0F0,0
        -w[-1] -rm[-1]

      -elif {@{!,SPACE}" || "@{!1,SPACE}}
        -rm[-1] --b[-1] 1.5 -hough[-1] 512,400 -b[-1] 0.5 -+[-1] 1 -log[-1] -n[-1] 0,255
        -w1[-1] -1,-1,0,0,"Hough Transform"

      -elif @{!,r} -w[-2]
      -elif @{!1,r} -w1[-1]
      -endif

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

    -rm[-1] -endl
    -if {!@!" || "!@{!1}} -break -endif
    -w0 0
  -done -rm -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} --ge[board] 0 -*[-1] 0.9 -r[-2,-1] [balls] [balls] -a[-3--1] c -hsv2rgb[-1]
      --compose_channels[-1] + -gt[-1] 0 -dilate[-1] 3
      -j[visu] [back] -j[visu] [-2],0,0,0,0,1,[-1] -rm[-2,-1]
      -if {!$shapescorey} -w[visu] @{back,w},@{back,h},0,0,"[G'MIC] Jawbreaker (score : "$score")" -endif
      render_board=0
    -endif

    # Add shape score sprite if necessary.
    -if $shapescorey
      --t[visu] "+"$shapescore,@{!,x},{@{!,y}-64+$shapescorey},32,{($shapescorey-1)/31},255
      shapescorey={max(0,$shapescorey-1)}
      -w[-1] @{back,w},@{back,h},0,0,"[G'MIC] 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)==i || i(x+1,y)==i || i(x,y+1)==i || i(x,y-1)==i,0)"
    -if {!@{-1,+}} -rm[-1] -break -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] -j[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,0,1,-@{board,($x,$y)}
        --ge[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,0,1,-1 -==[-1] -1
        -if {@{-1,+}>1} # If selected ball is connected to at least one ball.

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

          # Manage board shifts (vertical and horizontal).
          -flood[board] $x,$y,0,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
            -j[board] [-1],$> -rm[-1]
          -done
          -rows[board] -1,100% -f[board] "if(y==0,if(i(x,h-1),x,w),i)" -sort[board] +,x -rows[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
    -endif

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

  # Game over.
  -if {@!" && "!@{!,ESC}}
    -w[] @{visu,w},@{visu,h},0,0,"[G'MIC] Jawbreaker (final score : "$score")"
    -i[gameover] 230,85 -t[-1] "Game Over!",3,0,57,1,1 -t[-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)}%
      --j[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_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).
  iteration=0                                                   # Iteration counter.
  score=0                                                       # Current score.
  bestscore=0                                                   # Best score.
  stock=500                                                     # Remaining cells.
  -w[0] 400,400,0,0,"[G'MIC] 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" && "$stock>0}                 # Add random cells to the game if user presses mouse button.
      nb={?*7}
      -repeat $nb
        x={@{!,x}/@{!,w}*@{0,w}+?(-4,4)}
        y={@{!,y}/@{!,h}*@{0,h}+?(-3,3)}
        -=[0] 1,$x,$y
        -=[1] $iteration,$x,$y
        -point[2] {$x*@{2,w}/@{0,w}},{$y*@{2,h}/@{0,h}},0,0.8,255
      -done
      stock={round(max(0,$stock-$nb))}
    -endif

    --[-1] [0] -*[-1] -1                                        # Compute difference between consecutive states.
    stock={$stock-2*(min(0,int(@{-1,+}/16*$score/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 iteration=0 score=0 bestscore=0 stock=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 -b[-1] {1+$score*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.
      opac={0.7*min(1,$stock/500)} r={min(500,$stock)*cos($iteration)/100}
      -ellipse[-1] @{!,x},@{!,y},{15+$r},{15+$r},0,$opac,0,196,0
      -ellipse[-1] @{!,x},@{!,y},{10+$r},{10+$r},0,$opac,32,64,16
      -ellipse[-1] @{!,x},@{!,y},{5+$r},{5+$r},0,$opac,255,230,0
    -endif
    -t[-1] "Living cells : "$score"\n"\                      # Add score description.
           "Stock : "$stock"\n"\
           "Score : "$bestscore,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 {!($iteration%10)} score=@{0,+} bestscore={max($score,$bestscore)} -endif  # Re-compute current and best scores, every 10th iterations.
    -wait 60
    iteration={$iteration+1}
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}

  # End game and quit 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.
  0 -t[-1] "   G'MIC\nLight Demo",0,0,57,1,255 -expand_xy[-1] 15,0 -b[-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 -b[-1] 3 -n[-1] -60,60
  -+[-2,-1] -g[-1] xy -a[-2,-1] c -n[-1] -150,150
  -w[] {2*@{-2,w}},{2*@{-2,h}},0,0,"[G'MIC] 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.
    --z[-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_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
    siz={min(@{!,w},@{!,h})}                                                                      # Desired window dimension.
    $siz,$siz -mandelbrot[-1] @0,256,$1,{if($1,$2,0)},{if($1,$3,0)} -map[-1] [1]                  # Render fractal.
    -if $1 -w[-1] $siz,$siz,0,0,"[G'MIC] Julia set c=("@{0,0}","@{0,1}")-("@{0,2}","@{0,3}"), c0=($2,$3)" # Display on window.
    -else -w[-1] $siz,$siz,0,0,"[G'MIC] Mandelbrot set c=("@{0,0}","@{0,1}")-("@{0,2}","@{0,3}")" -endif
    w={w} h={h} -select[-1] 2                                                                     # Get the user selection.

    -if {@{-1,0}>0}                                                                               # If valid selection found.
      M={max(@{-1,3}-@{-1,0},@{-1,4}-@{-1,1})}                                                    # Compute max dimension of selected rectangle.
      -if {$M<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})/$w};\                                                # Else compute new fractal coordinates.
             {@{0,1}+@{-1,1}*(@{0,3}-@{0,1})/$h};\
             {@{0,0}+(@{-1,0}+$M)*(@{0,2}-@{0,0})/$w};\
             {@{0,1}+(@{-1,1}+$M)*(@{0,3}-@{0,1})/$h})
      -endif
      -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
    -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_minesweeper : 8<=_width=<20,8<=_height<=20
#@gmic : Launch the Minesweeper game.
x_minesweeper : -check "${1=20}>=8 && $1<=30 && ${2=20}>=8 && $2<=30"
  -e[] "\n
------ Minesweeper -------------------------------------------\n
----\n
---- The goal is to clear the minefield without detonating a\n
---- mine.\n
----\n
---- Left mouse button to try clearing one square.\n
---- Right mouse button to flag or unflag a square.\n
---- Middle mouse button to reset mine field.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------------------"
  -v -
  # Generate random mine field and player board.
  # Labels : 0=mine, 1=empty, 2='1-near', 3='2-near', ..., 9='8-near', 10=still unknown.
  $1,$2 -noise[-1] 30,2 nb_mines=@{-1,+} (1,1,1;1,0,1;1,1,1) --convolve[-2] [-1],0 -rm[-2] -+[-1] 1 -==[-2] 0 -*[-2,-1] -nm[-1] field
  --f[field] 11 -nm[-1] board

  # Generate sprite graphics.
  24,24,1,3,200 -fc[-1] 255,180,130
  -ellipse[-1] 12,12,4,4 -line[-1] 6,12,18,12 -line[-1] 12,6,12,18 -line[-1] 13,10,14,10,1,255 -line[-1] 13,11,14,11,1,255
  -z[-1] 1,1,{w-2},{h-2} -frame[-1] 1,1,0
  --fc[-1] 230,250,255
  --t[-1] "1",10,5,13,1,0,196,0 --t[-2] "2",9,5,13,1,0,128,0 --t[-3] "3",9,5,13,1,0,0,255
  --t[-4] "4",9,5,13,1,255,0,0 --t[-5] "5",9,5,13,1,200,0,0 --t[-6] "6",9,5,13,1,150,0,0
  --t[-7] "7",9,5,13,1,128,0,0 --t[-8] "8",9,5,13,1,64,0,0 -erode[-8--1] 2
  --f[-1] 'if(x<=1||y<=1||x>=w-2||y>=h-2,if(x<y,128,255),160+2*(y+x))'
  --polygon[-1] 4,13,15,11,15,6,18,17,18,1,0 -line[-1] 12,15,12,6,1,255,0,0 -polygon[-1] 3,12,6,6,9,12,12,1,220,0,0
  -rv[-2,-1] -a[-12--1] x -nm[-1] sprites

  # Pre-calculate offsets and canvas for faster board rendering.
  (0,23;0,23^0,0;23,23) -r[-1] 24,24,1,2,3 -r[-1] {@{board,w}*24},{@{board,h}*24},1,2,0,2 -nm[-1] offsets
  [-1],[-1],1,3,255 -frame[-1] 1,1,0 -frame[-1] 23,23,255
  0 -t[-1] "Number of mines : "$nb_mines,0,0,18,1,100,200,255 -negative[-1] -j[-2] [-1],{(@{-2,w}-w)/2},{@{-2,h}-h-2} -rm[-1]
  -nm[-1] canvas

  # Start user interaction loop.
  failed=0 succeeded=0 tic=@| nb_flags=0
  -do

    # Render board.
    --*[board] 24 -r[-1] [offsets],[offsets] -channels[-1] 0,1 -+[-1] [offsets] --warp[sprites] [-1],0,0 -rm[-2]
    -j[canvas] [-1],24,24 -rm[-1]

    # Wait for user's selection.
    -wait -1
    -if $failed
      0 -t[-1] "Game\nOver!",3,3,38,1,255 -r[-1] 100%,100%,1,4 -sh[-1] 3,3 -dilate[-1] 5 -/[-1] 2 -rm[-1]
      -drop_shadow[-1] 5,5,1 -compose_alpha[canvas,-1]
      0 -t[-1] "Boom! You failed!",0,0,18,1,100,255,255 -r[-1] @{canvas,w},100%,1,3,0,0,0.5,0.5 -negative[-1] -j[canvas] [-1],0,3 -rm[-1]
      -do -w[canvas] {w},{h} -wait -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
    -elif $succeeded
      0 -t[-1] "Success!",3,3,38,1,255 -r[-1] 100%,100%,1,4 -sh[-1] 3,3 -dilate[-1] 5 -/[-1] 2 -rm[-1]
      -drop_shadow[-1] 5,5,1 -compose_alpha[canvas,-1]
      0 -t[-1] "Congratulations! ("{round(@|-$tic)}" s)",0,0,18,1,255,100,255 -r[-1] @{canvas,w},100%,1,3,0,0,0.5,0.5
      -negative[-1] -j[canvas] [-1],0,3 -rm[-1]
      -do -w[canvas] {w},{h} -wait -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
    -else
      -do
        0 -t[-1] "Elapsed time : "{round(@|-$tic)}" s / Flags : "$nb_flags,0,0,18,1,255,200,0 -r[-1] @{canvas,w},100%,1,3,0,0,0.5,0.5
        -negative[-1] -j[canvas] [-1],0,3 -rm[-1]
        -wait 50
        x={int((@{!,x}-24)/24)} y={int((@{!,y}-24)/24)} b=@{!,b}
        -w[canvas] {w},{h},0,0,"[G'MIC] Minesweeper"
      -while {@!" && "!@{!,ESC}" && "!@{!,Q}" && "!$b}
    -endif

    # Manage selected square.
    -if {$x>=0\ &&\ $y>=0\ &&\ $x<@{board,w}\ &&\ $y<@{board,h}}
      -if {$b&1}  # Try to clean square.
        val=@{field,($x,$y)}
        -if {$val==0} --==[field] 0 -j[board] [field],0,0,0,0,1,[-1] -rm[-1] failed=1  # Found a mine -> boom!
        -elif {$val==1} --flood[field] $x,$y,0,0,1,1,-1 -==[-1] -1 -dilate[-1] 3 -j[board] [field],0,0,0,0,1,[-1] -rm[-1] # Found an empty area.
        -else -=[board] $val,$x,$y # Close to one or several mines.
        -endif
      -elif {$b&2} -=[board] {if(@{board,($x,$y)}==11,10,11)},$x,$y nb_flags={$nb_flags+if(@{board,($x,$y)}==11,-1,1)} # Flag or unflag a square.
      -elif {$b&4} -f[board] 10  # Reset minefield.
      -endif
    -endif

    -if {$nb_mines==$nb_flags\ &&\ @{board,M}!=11} succeeded=1 -endif  # Check if board is cleared.
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -w 0 -v +

#@gmic x_minimal_path
#@gmic : Launch the minimal path demo.
x_minimal_path :
  -e[] "\n
------ Minimal path demo -------------------------------------\n
----\n
---- Click on two points to compute and display the minimal\n
---- path between those points. The ending point is then\n
---- chosen as the next starting point for another path.\n
---- Key 'S' to save snapshot of the current view.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------------------"
  -v -
  -if {!@#} -testimage2d 400 -endif
  -n 0,200 -repeat @# -l[$>]
    -w[0] -1,-1,0,0,"[G'MIC] Select starting point P0"
    --gradient_norm -b[-1] 1 -f[-1] exp(-i/10)
    -to_rgb[0] --select[0] 0 P0=@-1
    -ellipse[0] @{-1,0,1},3,3,0,1,255,0,255
    -ellipse[0] @{-1,0,1},3,3,0,1,0xFFFFFFFF,255,255,255
    -rm[-1]
    -if {min($P0)>=0}
      p=1
      -do
        -w[0] -1,-1,0,0,"[G'MIC] Select ending point P"$p
        --select[0] 0
        -if {@{!,S}}
          -rm[-1]
          --text_outline[0] "Saving snapshot...",5,5,13,1,1,255,255,255 -w[-1] -rm[-1]
          -o[0] gmic_minimal_path.png
          -wait -1
        -else
          P1=@-1
          -ellipse[0] @{-1,0,1},3,3,0,1,255,0,255
          -ellipse[0] @{-1,0,1},3,3,0,1,0xFFFFFFFF,255,255,255
          -rm[-1]
          -if {min($P1)>=0}
            --text_outline[0] "Processing...",5,5,13,1,1,255,255,255 -w[-1] -rm[-1]
            --minimal_path[1] $P0,$P1
            -pointcloud[-1] 0 -*[-1] 255 -r[-1] 100%,100%,1,[0],0,0,0,0,0,0.5 -r[-1] [0],0 -or[0,-1]
            P0=$P1 p={$p+1}
          -endif
        -endif
      -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
    -endif
    -rm[1]
  -endl -done -w 0 -v +

#@gmic x_pacman
#@gmic : Launch pacman game.
x_pacman :
  -e[] "\n
------ Pacman -----------------------------------------------\n
----\n
---- This is a G'MIC implementation of the pacman game.\n
----\n
---- Move the pacman to eat all pacdots on the different levels.\n
---- Eating a pacgum makes pacman invincible for 10 seconds,\n
---- which mean pacman can eat ghosts during this time.\n
---- Eating a ghost earns 100 pts.\n
---- Eating a cherry earns 10 pts.\n
---- Eating a strawberry earns 100 pts.\n
---- Eating an orange earns 1000 pts.\n
---- Eating a banana earns 5000 pts.\n
----\n
---- Arrow keys to control pacman.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------------------"
  -v - -rm

  # Initialize characters gfx.
  -m "_pacman_ghost_base_gfx : 31,19 -circle[-1] 15,15,15,1,1 31,12,1,1,'y<4+8*abs(cos(x*0.3+0.25*pi*$""1))' -a[-2,-1] y"
  -repeat 4
    -_pacman_ghost_standard_gfx 255,0,0,$> -nm[-1] ghost0_$>
    -_pacman_ghost_standard_gfx 0,255,222,$> -nm[-1] ghost1_$>
    -_pacman_ghost_standard_gfx 255,184,222,$> -nm[-1] ghost2_$>
    -_pacman_ghost_standard_gfx 255,184,71,$> -nm[-1] ghost3_$>
    -_pacman_ghost_afraid_gfx $> -nm[-1] ghosta_$>
    -_pacman_ghost_base_gfx $> -r[-1] 16,16,1,1,2 -nm[-1] ghostm_$>
    -_pacman_ghost_standard_gfx 0,0,0,$> -nm[-1] ghostd_$>
    -_pacman_pacman_gfx $> -nm[-2] pacman_$> -nm[-1] pacmanm_$>
  -done
  --channels[ghostd_0] 0 -!=[-1] 0 -nm[-1] ghostdm
  -_pacman_cherry_gfx -nm[-1] fruit0 -_pacman_strawberry_gfx -nm[-1] fruit1
  -_pacman_orange_gfx -nm[-1] fruit2 -_pacman_banana_gfx -nm[-1] fruit3
  20,2,1,3,200 -nm[-1] gate
  score0="10" score1="100" score2="1000" score3="5000" score4="Argh!"
  -repeat 5
    0 -t[-1] ${score$>},0,0,13,1,255,255,255 -autocrop[-1] 0 -expand_xy[-1] 1,0 --dilate[-1] 3
    -nm[-1] scorem$> -nm[-2] score$>
  -done
  time4=255,255,255 time3=255,255,32 time2=255,128,32 time1=255,32,32
  -repeat 11 0 -t[-1] $<" s",0,0,23,1,${time{min(4,round(($<+1)/2))}} -nm[-1] time$< -done
  0 -t[-1] "Get Ready!",0,0,32,1,255 -autocrop[-1] 0 -expand_xy[-1] 4,0 --dilate[-1] 8 -r[-2] 100%,100%,1,3
  -nm[-2] get_ready -nm[-1] get_readym
  0 -t[-1] "Game\nOver!",0,0,57,1,255 -autocrop[-1] 0 -expand_xy[-1] 4,0 --dilate[-1] 8 -r[-2] 100%,100%,1,3
  -nm[-2] game_over -nm[-1] game_overm

  # Start game.
  score=0 level=-1 lives=3 is_quit=0
  -do

    # Build new level if necessary.
    -if {$level<0}
      _rlevel=33 _glevel=33 _blevel=255
      -_pacman_map_level{((-$level-1)%6)+1} mw={w} mh={h} mw2={int(w/2)} mh2={int(h/2)}
      -if {$level<-6} -replace[-1] 3,2 -endif
      -nm[-1] map0 -i[map] [-1]

      # Precompute valid directions on each map point, and shortest path to the ghost's home.
      --shift[map] -1,0 --shift[map] 0,-1 --shift[map] 1,0 --shift[map] 0,1 -a[-4--1] z -!=[-1] 1 -nm[-1] can_go
      --==[map] 1 -distance[-1] $mw2,$mh2,0 -channels[-1] 1 -f[-1] 'if(i==2,0,if(i==4,1,if(i==1,2,i)))' -nm[-1] path
      --==[map] 2 pacdots=@{-1,+} -rm[-1]
      level={-$level}
    -endif

    # Render board gfx.
    -f[map] 'if(i>=4,0,i)' --==[map] 1 -expand_xy[-1] 1,0 -r[-1] 1600%,1600% -erode[-1] 9 -b[-1] 2
    -g[-1] xy -abs[-2,-1] -+[-2,-1] -ge[-1] 80% -b[-1] 2 -n[-1] 0,1 -shrink_xy[-1] 16
    --*[-1] $_glevel --*[-2] $_blevel -*[-3] $_rlevel -a[-3--1] c
    16,16,1,1,'x' ---[map] 1 -max[-1] 0 -*[-1] 16 -r[-1] 1600%,1600%
    16,16,1,1,'y' -r[-3,-1] [-2],0,2 -+[-2,-1] -a[-2,-1] c
    16,16,1,3 -_pacman_pacdots_gfx -_pacman_pacgum_gfx -a[-3--1] y
    -warp[-1] [-2],0,0 -rm[-2] -or[-2,-1] -r[-1] 100%,{h+24},1,3,0,0,0,1
    -t[-1] "Lives :",10,0,23,1,255 -t[-1] "Score :",{w-140},0,23,1,255
    -if $lives --r[pacman_2] 12,12,1,4,2 -r[-1] {100*$lives}%,100%,1,4,0,2 -j[-2] [-1],90,7 -rm[-1] -endif
    -nm[-1] visu
    -w[visu] -1,-1,0,0,"[G'MIC] Pacman"
    0 -t[-1] "Level "$level,0,0,57,1,1 -autocrop[-1] 0 -expand_xy[-1] 4,0 (0,255^0,255^0,0) --map[-2] [-1] -rm[-2] -dilate[-2] 8
    -nm[-1] level_N -nm[-2] levelm_N

    -repeat 4 xg$>={16*$mw2} yg$>={16*$mh2+4*$>} dg$>=3 mg$>=0 -done
    xp={16*10} yp={16*21} dp=-1 pacgum_timer=-1 fruit_timer=@| dying_pacman=0 is_get_ready=1
    xscore=0 yscore=0 nscore=0 oscore=0

    # Start game interaction.
    -do

      # Display board graphics.
      t={int(6*@|)%4} left={if($pacgum_timer>=0,10-@|+$pacgum_timer,-1)}
      [visu]
      -repeat 4
        mg=${mg$>} xg=${xg$>} yg={${yg$>}+24}
        -if {$mg==0} -j[-1] [ghost$>_$t],$xg,$yg,0,0,1,[ghostm_$t]
        -elif {$mg==1} t2={if($left>7,$t,if($left>3,int(12*@|)%4,int(24*@|)%4))} -j[-1] [ghosta_$t2],$xg,$yg,0,0,1,[ghostm_$t]
        -elif {$mg==2} -j[-1] [ghostd_$t],$xg,$yg,0,0,0.8,[ghostdm]
        -else -j[-1] [ghost$>_$t],$xg,$yg,0,0,{$mg-2},[ghostm_$t] -j[-1] [ghostd_$t],$xg,$yg,0,0,1,[ghostdm]
        -endif
      -done
      -if $dying_pacman
        -_pacman_pacman_gfx {$dying_pacman/2} -rotate[-2,-1] {90*(abs($dp)-1)} -j[-3] [-2],$xp,{24+$yp},0,0,1,[-1],255 -rm[-2,-1]
        dying_pacman={$dying_pacman+1}
        -if {$dying_pacman>64}
          -if {$lives!=1} -rm[-1] -break -endif
          -j[-1] [game_over],{(w-@{game_over,w})/2},{12+(h-@{game_over,h})/2},0,0,{min(1,($dying_pacman-64)/50)},[game_overm],255
          -rectangle[-1] 90,7,101,18,1,0
        -endif
      -else
        --rotate[pacman_$t,pacmanm_$t] {90*(abs($dp)-1)} -j[-3] [-2],$xp,{24+$yp},0,0,1,[-1],255 -rm[-2,-1]
        -if {$left>=0" && "($left>=5" || "$t<=2)} -j[-1] [time{round($left)}],{(w-@{time0,w})/2},1 -endif
      -endif
      -t[-1] $score,{w-65},1,22,1,255
      -if {$is_get_ready}
        -j[-1] [level_N],{(w-@{level_N,w})/2},{12+(h-1.5*@{level_N,h})/2},0,0,1,[levelm_N]
        -if {int(@|*4)%2} -j[-1] [get_ready],{(w-@{get_ready,w})/2},{24+(h+@{get_ready,h})/2},0,0,1,[get_readym],255 -endif
      -endif
      -if {$oscore>0} -j[-1] [score$nscore],$xscore,$yscore,0,0,$oscore,[scorem$nscore],255 oscore={$oscore-0.04} yscore={$yscore-1} -endif
      -j[-1] [gate],158,223,0,0,0.6
      -w[-1] -rm[-1]

      # Manage ghosts displacements and collisions.
      -repeat 4
        xg=${xg$>} yg=${yg$>} dg=${dg$>} mg=${mg$>}

        -if {max(abs($xg-$xp),abs($yg-$yp))<=8}            # Test collision between ghost and pacman.
          -if {$mg==0" && "!$dying_pacman} dying_pacman=1  # Was in normal mode -> dying pacman.
            xscore=$xp yscore={$yp+12} oscore=1 nscore=4
          -elif {$mg==1} mg=2 mg$>=$mg score={$score+100}  # Was in invicibility mode -> dying ghost.
            xscore=$xp yscore={$yp+12} oscore=1 nscore=1
          -endif
        -endif
        -if {$mg>=2" && "($xg>>4)==$mw2" && "($yg>>4)==$mh2} # Check if dying ghost has returned to home.
          mg={$mg+0.01}
          -if {$mg>=3} mg=0 xg={$xg&-2} yg={$yg&-2} -endif
          mg$>=$mg
        -endif

        -if {!($xg&15)" && "!($yg&15)} # Check if ghost can take a new direction.
          ({?},{?},{?},{?};0,1,2,3)
          -if {$mg<2}
            -=[-1] {?(0.6,1)},{if($mg==0,dX0=$xp-$xg;dY0=$yp-$yg;if(abs(dX0)>abs(dY0),if(dX0>0,0,2),if(dY0>0,1,3)),\ # Try to chase pacman.
                                         dX1=$xp-$xg;dY1=$yp-$yg;if(abs(dX1)<abs(dY1),if(dX1>0,2,0),if(dY1>0,3,1)))} # Try to escape pacman.
            -=[-1] 0,{($dg+2)%4}
            -if $is_get_ready -=[-1] 0.8,@{path,({$xg>>4},{$yg>>4})} -endif
          -else -=[-1] 1,@{path,({$xg>>4},{$yg>>4})} # If dying ghost, follow the best path to home.
          -endif
          -sort[-1] -,x -repeat 4 d={i($>,1)} -if @{can_go,({$xg>>4},{$yg>>4},$d)} dg=$d -break -endif -done -rm[-1] # Try directions until it matches.
          dg$>=$d
        -endif
        u={D=${dg$>};(D==0)-(D==2)}
        v={D=${dg$>};(D==1)-(D==3)}
        xg$>={($xg+$u*(1+($mg==0)))%(16*$mw)}
        yg$>={($yg+$v*(1+($mg==0)))%(16*$mh)}
      -done

      -wait 22

      # Manage pacman displacement.
      -if {!$dying_pacman}
        d={if(@{!,ARROWRIGHT},1,if(@{!,ARROWDOWN},2,if(@{!,ARROWLEFT},3,if(@{!,ARROWUP},4,$dp))))}
        -if {!($xp&15)" && "!($yp&15)}
          i=@{map,({$xp>>4},{$yp>>4})}
          -if {$i==2} score={$score+10} pacdots={$pacdots-1} # Pacdot eaten.
          -elif {$i==3} pacgum_timer=@| -repeat 4 -if {!${mg$>}} mg$>=1 dg$>={(${dg$>}+2)%4} -endif -done  # Pacgum eaten.
          -elif {$i>=4} score={$score+${score{$i-4}}} xscore=$xp yscore={$yp+12} oscore=1 nscore={$i-4} # Fruit eaten.
          -endif
          -=[map] 0,{$xp>>4},{$yp>>4}
          16,16,1,3 -j[visu] [-1],$xp,{24+$yp} -rm[-1]
          d={if(@{can_go,({$xp>>4},{$yp>>4},{abs($d)-1})},$d,$dp)}
          d={if(@{can_go,({$xp>>4},{$yp>>4},{abs($d)-1})},$d,-abs($dp))}
          dp=$d
        -else dp={if(abs($d-$dp)==2,$d,$dp)}  # Allow to turn back on non-integer locations.
        -endif
        is_get_ready={if($dp>0,0,$is_get_ready)}
        u={($dp==1)-($dp==3)}
        v={($dp==2)-($dp==4)}
        xp={($xp+2*$u)%(16*$mw)}
        yp={($yp+2*$v)%(16*$mh)}

        -if {$pacgum_timer>=0" && "@|>$pacgum_timer+10} # Check if pacgum still has some effect.
          -repeat 4 xg$>={${xg$>}&-2} yg$>={${yg$>}&-2} mg$>={if(${mg$>}==1,0,${mg$>})} -done
          pacgum_timer=-1
        -endif

        -if {!$is_get_ready" && "(@|-$fruit_timer)>=10}
          x={round(?(0,@{map0,w}))}
          y={round(?(0,@{map0,h}))}
          -if {!@{map,($x,$y)}" && "@{map0,($x,$y)}==2}
            n={min(3,int(abs(g*1.7)))} -=[map] {4+$n},$x,$y -j[visu] [fruit$n],{16*$x},{16*$y+24} fruit_timer=@|
          -endif
        -endif

      -endif
      -if {!@!" || "@{!,Q}" || "@{!,ESC}} is_quit=1 -endif
    -while {!$is_quit" && "$pacdots}

    -if $is_quit -break         # Player asked to quit.
    -elif $pacdots              # Player lost a life.
      lives={$lives-1}
    -else                       # Player achieved level.
      level={-$level-1} -wait[0] -1
      -rm[map0,map,can_go,path]
    -endif
    -rm[visu,level_N,levelm_N]
  -while $lives
  -rm -w 0 -v +

# The functions below create the various sprite gfx.
_pacman_ghost_standard_gfx :
  -_pacman_ghost_base_gfx $4 (0,$1^0,$2^0,$3) -map[-2] [-1] -rm[-1]
  -ellipse[-1] 10,11,3,4,0,1,255 -ellipse[-1] 20,11,3,4,0,1,255
  -r[-1] 16,16,1,3,2 -point[-1] 5,{7-($4>=2)},0,1,1 -point[-1] 10,{7-($4>=2)},0,1,1

_pacman_ghost_afraid_gfx :
  -_pacman_ghost_base_gfx $1
  -if {$1<2} col=255,255,255 (0,0^0,0^0,208) -else col=255,0,0 (0,248^0,248^0,248) -endif
  -map[-2] [-1] -rm[-1] -r[-1] 16,16,1,3,2
  -line[-1] 4,4,6,6,1,$col,255 -line[-1] 4,6,6,4,1,$col,255
  -line[-1] 9,4,11,6,1,$col,255 -line[-1] 9,6,11,4,1,$col,255
  -f[-1] 'if(y>=9&&y<=10&&x>=2&&x<=13&&((int((x+1)/2)+y)%2),arg(c+1,$col),i)'

_pacman_pacman_gfx :
  32,32,1,1,'X=x-15;Y=y-15;A=atan2(Y,X);R=sqrt(X^2+Y^2);R<15.5&&abs(A)>0.8*0.33*$1'
  (0,255^0,255^0,0^0,255) -map[-2] [-1] -rm[-1] -r[-1] 16,16,1,4,2 -s[-1] c,-3

_pacman_pacdots_gfx :
  (255^184^151) -r[-1] 4,4,1,3 -r[-1] 16,16,1,3,0,0,0.5,0.5

_pacman_pacgum_gfx :
  16,16,1,3 -circle[-1] 7,7,7,1,255,128,64

_pacman_cherry_gfx :
  (0,0,0,0,0,0,0,0,0,0,1,1;0,0,0,0,0,0,0,0,1,1,1,1;0,0,0,0,0,0,1,1,0,1,0,0;0,0,0,0,0,1,0,0,0,1,0,0;\
   0,2,2,2,2,0,0,0,1,0,0,0;2,2,2,2,2,2,0,1,0,0,0,0;2,2,2,2,2,0,2,2,2,2,0,0;2,3,2,2,0,2,2,2,2,2,2,0;\
   2,2,3,2,0,2,2,2,2,2,2,0;0,2,2,2,0,2,3,2,2,2,2,0;0,0,0,0,0,2,2,3,2,2,2,0;0,0,0,0,0,0,2,2,2,2,0,0)
  (0,0,255,255^0,173,0,255^0,0,0,255) -map[-2] [-1] -rm[-1] -r2dy[-1] 14,3 -r[-1] 16,16,1,3,0,0,0.5,0.5

_pacman_strawberry_gfx :
  (0,0,0,0,0,3,0,0,0,0,0;0,0,1,1,1,3,1,1,1,0,0;0,2,2,1,1,1,1,1,2,2,0;2,2,2,2,1,1,1,2,2,3,2;\
   2,3,2,2,2,2,2,3,2,2,2;2,2,2,3,2,3,2,2,2,2,2;2,2,2,2,2,2,2,2,3,2,2;0,2,3,2,2,3,2,2,2,2,0;\
   0,2,2,2,2,2,2,2,2,2,0;0,0,2,2,3,2,2,3,0,0,0;0,0,0,2,2,2,2,2,0,0,0;0,0,0,0,0,2,0,0,0,0,0)
  (0,0,255,255^0,173,0,255^0,0,0,255) -map[-2] [-1] -rm[-1] -r2dy[-1] 14,3 -r[-1] 16,16,1,3,0,0,0.5,0.5

_pacman_orange_gfx :
  (0,0,0,0,0,1,0,1,1,0,0,0;0,0,0,0,0,1,1,1,1,1,1,0;0,0,0,0,0,1,3,1,1,1,0,0;0,0,2,2,2,1,2,2,2,2,0,0;\
   0,2,2,2,2,2,2,2,2,2,2,0;2,2,2,2,2,2,2,2,2,2,2,2;2,2,2,2,2,2,2,2,2,2,2,2;2,2,2,2,2,2,2,2,2,2,2,2;\
   2,2,2,2,2,2,2,2,2,2,2,2;2,2,2,2,2,2,2,2,2,2,2,2;0,2,2,2,2,2,2,2,2,2,2,0;0,2,2,2,2,2,2,2,2,2,2,0;\
   0,0,0,2,2,2,2,2,2,0,0,0)
  (0,0,255,255^0,173,173,255^0,0,0,255) -map[-2] [-1] -rm[-1] -r2dy[-1] 14,3 -r[-1] 16,16,1,3,0,0,0.5,0.5

_pacman_banana_gfx :
  (0,0,0,0,0,0,0,1,0;0,0,0,0,0,0,1,1,0;0,0,0,0,0,0,1,1,1;0,0,0,0,0,1,0,1,1;0,0,0,0,0,1,0,1,1;\
   0,0,0,0,1,0,1,1,1;0,0,0,0,1,0,1,1,1;0,0,0,1,0,1,2,1,0;0,0,1,0,1,2,1,1,0;0,1,0,1,2,1,1,0,0;\
   1,1,1,1,1,1,0,0,0;1,1,1,1,0,0,0,0,0)
  (0,255,255^0,173,255^0,0,255) -map[-2] [-1] -rm[-1] -r2dy[-1] 14,3 -r[-1] 16,16,1,3,0,0,0.5,0.5

_pacman_map_level1 :
  (1,1,1,1,1,1,1,1,1,1,1;1,2,2,2,2,2,1,2,2,2,2;1,3,1,1,1,2,1,2,1,1,1;1,2,1,1,1,2,1,2,1,1,1;\
   1,2,2,2,2,2,2,2,2,2,2;1,1,1,2,1,2,1,1,1,2,1;0,0,1,2,1,2,1,1,1,2,1;1,1,1,2,1,2,1,1,1,2,1;\
   0,0,0,2,1,2,2,2,2,2,1;1,1,1,2,1,1,1,0,1,1,1;0,0,1,2,1,1,1,0,1,1,1;0,0,1,2,0,0,0,0,0,0,0;\
   0,0,1,2,1,1,1,0,1,1,0;0,0,1,2,1,0,0,0,1,0,0;0,0,1,2,1,0,1,0,1,0,0;1,1,1,2,1,0,1,0,1,1,1;\
   0,0,0,2,0,0,1,0,0,0,0;1,1,1,2,1,1,1,1,1,0,1;0,0,1,2,2,2,2,2,0,0,1;0,0,1,2,1,1,1,2,1,1,1;\
   1,1,1,2,1,1,1,2,1,1,1;1,2,2,2,2,2,2,2,2,2,0;1,2,1,1,1,2,1,1,1,2,1;1,2,1,1,1,2,1,2,2,2,1;\
   1,3,1,1,1,2,1,2,1,1,1;1,2,1,1,1,2,1,2,1,1,1;1,2,2,2,2,2,2,2,2,2,2;1,1,1,1,1,1,1,1,1,1,1)
  --mirror[-1] x -crop[-1] 1,100% -a[-2,-1] x
  _rlevel=33 _glevel=33 _blevel=255

_pacman_map_level2 :
  (1,1,1,1,1,1,1,1,1,1,1;1,2,2,2,2,2,2,2,2,2,2;1,3,1,2,1,1,1,2,1,1,1;1,2,1,2,1,1,1,2,1,2,2;\
   1,2,1,2,2,2,2,2,1,2,1;1,2,1,1,1,2,1,2,1,2,1;1,2,1,1,1,2,1,2,1,2,1;1,2,2,2,2,2,1,2,2,2,1;\
   1,1,1,2,1,1,1,1,1,0,1;0,0,1,2,1,1,1,1,1,0,1;0,0,1,2,1,1,1,1,1,0,1;0,0,1,2,2,2,1,0,0,0,0;\
   1,1,1,0,1,2,1,0,1,1,0;0,0,0,0,1,2,1,0,1,0,0;1,1,1,1,1,2,0,0,1,0,0;1,1,1,1,1,2,1,0,1,1,1;\
   0,0,0,0,1,2,1,0,0,0,0;1,1,1,2,2,2,1,1,1,0,1;0,0,1,2,1,2,2,2,0,0,1;0,0,1,2,1,1,1,2,1,0,1;\
   1,1,1,2,1,1,1,2,1,0,1;1,2,2,2,2,2,2,2,1,0,0;1,2,1,1,1,2,1,2,1,1,1;1,2,1,2,2,2,1,2,2,2,2;\
   1,3,1,2,1,1,1,1,1,2,1;1,2,1,2,1,1,1,1,1,2,1;1,2,2,2,2,2,2,2,2,2,1;1,1,1,1,1,1,1,1,1,1,1)
  --mirror[-1] x -crop[-1] 1,100% -a[-2,-1] x
  _rlevel=200 _glevel=33 _blevel=33

_pacman_map_level3 :
  (1,1,1,1,1,1,1,1,1,1,1;0,0,0,0,0,0,1,2,2,2,2;1,1,1,1,1,0,1,2,1,1,1;1,1,1,1,1,0,1,2,1,1,1;\
   1,3,2,2,2,2,2,2,2,2,1;1,2,1,1,1,1,1,2,1,2,1;1,2,1,1,1,1,1,2,1,2,1;1,2,1,2,2,2,2,2,1,2,1;\
   1,2,1,2,1,1,1,0,1,2,1;1,2,2,2,2,2,1,0,1,2,2;1,1,1,1,1,2,1,0,1,1,1;1,2,2,2,2,2,1,0,0,0,0;\
   1,2,1,1,1,2,1,0,1,1,0;1,2,1,1,1,2,1,0,1,0,0;1,2,2,2,1,2,0,0,1,0,0;1,1,1,2,1,2,1,0,1,1,1;\
   0,0,1,2,1,2,1,0,0,0,0;0,0,1,2,1,2,1,1,0,1,1;0,0,1,2,1,2,1,1,0,1,1;0,0,1,2,2,2,2,2,2,1,1;\
   1,1,1,2,1,1,1,1,2,1,1;0,0,0,2,2,2,1,2,2,2,0;1,1,1,2,1,2,1,2,1,1,1;1,3,2,2,1,2,2,2,2,2,1;\
   1,2,1,1,1,2,1,1,1,2,1;1,2,1,1,1,2,1,1,1,2,1;1,2,2,2,2,2,2,2,2,2,2;1,1,1,1,1,1,1,1,1,1,1)
  --mirror[-1] x -crop[-1] 1,100% -a[-2,-1] x
  _rlevel=33 _glevel=200 _blevel=255

_pacman_map_level4 :
  (1,1,1,1,1,1,1,1,1,0,0;1,2,2,2,2,2,2,2,1,0,0;1,2,1,1,2,1,1,2,1,0,0;1,2,1,1,2,1,1,2,1,0,0;\
   1,2,2,2,3,2,2,2,1,1,1;1,2,1,1,2,1,1,2,2,2,2;1,2,1,1,2,1,1,2,1,1,2;1,2,2,2,2,2,2,2,1,1,2;\
   1,2,1,1,2,1,1,2,2,2,2;1,2,1,1,2,1,1,2,1,1,2;1,2,2,2,2,2,2,2,1,1,2;1,1,1,0,0,0,0,0,0,0,0;\
   0,0,1,0,0,0,0,0,1,1,0;1,1,1,0,0,0,0,0,1,0,0;0,0,0,0,0,0,0,0,1,0,0;1,1,1,0,0,0,0,0,1,1,1;\
   1,1,1,0,0,0,0,0,0,0,0;1,2,0,0,0,0,0,0,0,0,0;1,2,1,1,2,1,1,2,1,1,2;1,2,1,1,2,1,1,2,1,1,2;\
   1,2,2,2,2,2,2,2,2,2,2;1,2,1,1,2,1,1,2,0,0,0;1,2,1,1,2,1,1,2,0,1,1;1,2,2,2,3,2,2,2,2,1,0;\
   1,2,1,1,2,1,1,2,1,1,0;1,2,1,1,2,1,1,2,1,0,0;1,2,2,2,2,2,2,2,1,0,0;1,1,1,1,1,1,1,1,1,0,0)
  --mirror[-1] x -crop[-1] 1,100% -a[-2,-1] x
  _rlevel=200 _glevel=200 _blevel=33

_pacman_map_level5 :
  (1,1,1,1,1,1,1,1,1,1,1;1,2,2,2,2,2,2,2,1,2,2;1,3,1,1,1,1,1,2,1,2,1;1,2,1,1,1,1,1,2,1,2,1;\
   1,2,1,2,2,2,2,2,2,2,1;1,2,2,2,1,2,1,1,1,2,1;1,1,1,2,1,2,1,0,1,2,1;1,1,1,2,1,2,1,1,1,2,1;\
   0,0,0,0,1,2,2,2,2,2,2;1,2,1,0,1,1,1,0,1,1,1;1,2,1,0,1,1,1,0,1,1,1;1,2,1,0,0,0,0,0,0,0,0;\
   1,2,1,1,1,0,1,0,1,1,0;1,2,1,1,1,0,1,0,1,0,0;1,2,0,0,0,0,1,0,1,0,0;1,2,1,0,1,1,1,0,1,1,1;\
   1,2,1,0,0,0,0,0,0,0,0;1,2,1,1,1,0,1,1,1,0,1;1,2,2,2,2,2,1,2,2,2,1;1,1,1,2,1,2,1,2,1,1,1;\
   1,1,1,2,1,2,1,2,1,1,1;1,3,2,2,1,2,2,2,2,2,0;1,2,1,1,1,2,1,1,1,2,1;1,2,2,2,2,2,1,2,2,2,1;\
   1,2,1,1,1,2,1,2,1,1,1;1,2,1,1,1,2,1,2,1,1,1;1,2,2,2,2,2,1,2,2,2,2;1,1,1,1,1,1,1,1,1,1,1)
  --mirror[-1] x -crop[-1] 1,100% -a[-2,-1] x
  _rlevel=200 _glevel=255 _blevel=33

_pacman_map_level6 :
  (1,1,1,1,1,1,1,1,1,1,1;1,2,2,2,2,2,2,2,2,2,2;1,2,1,1,2,1,1,1,1,1,1;1,3,2,2,2,2,2,2,2,2,2;\
   1,1,1,1,1,2,1,1,1,1,1;1,2,2,2,2,2,2,2,2,2,2;1,2,1,1,1,1,0,1,1,1,1;1,2,1,0,0,0,0,0,0,0,0;\
   1,2,1,0,1,1,1,0,1,1,1;0,2,1,0,1,2,2,2,2,2,2;1,2,0,0,1,2,1,1,0,1,1;1,2,1,0,0,2,1,0,0,0,0;\
   1,2,1,0,1,2,0,0,1,1,0;1,2,1,0,1,2,1,0,1,0,0;1,2,1,0,1,2,1,0,1,0,0;1,2,1,0,1,2,0,0,1,1,1;\
   1,2,1,0,0,2,1,0,0,0,0;1,2,0,0,1,2,1,1,0,1,1;0,2,1,0,1,2,2,2,2,2,2;1,2,1,0,1,1,1,0,1,1,1;\
   1,2,1,0,0,0,0,0,0,0,0;1,2,1,1,1,1,0,1,1,1,0;1,2,2,2,2,2,2,2,2,2,2;1,1,1,1,1,2,1,1,1,1,1;\
   1,3,2,2,2,2,2,2,2,2,2;1,2,1,1,2,1,1,1,1,1,1;1,2,2,2,2,2,2,2,2,2,2;1,1,1,1,1,1,1,1,1,1,1)
  --mirror[-1] x -crop[-1] 1,100% -a[-2,-1] x
  _rlevel=255 _glevel=130 _blevel=233

#@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 -nm[0] "New image" -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 -t[-1] "Selected color",4,2,13,1,255
      -rectangle[-1] 80,3,100,13,1,$color
      -rectangle[-1] 80,3,100,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
      -rectangle[-1] {$brushsize*48},{$brushopacity*48},\
                     {$brushsize*48+47},{$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}
      -rectangle[-1] {$bx-16},20%,{$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)}
      -rectangle[-1] 20%,{$by-16},80%,{$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,0,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} brushangle={$x3*180/(w-16)}   # Bottom slider -> select brush angle.
      -elif {$x3>=384" && "$y3<192} brushthickness={$y3/(h-16)} # Right slider -> select brush thickness.
      -elif {$x3<384" && "$y3<192} brushsize={int($x3*8/(w-16))} brushopacity={int($y3*4/(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 +

#@gmic x_plasma
#@gmic : Launch the plasma demo.
x_plasma :
  -e[] "\n
------ Plasma demo ----------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v - -l[]

  # Init plasma backgrounds.
  N=8
  -repeat $N
    256,150,1,3 -rand[-1] 0,255 -plasma[-1] 1,0,7 -n[-1] 0,255
    amp={?(-40,40)} freq={round(?(2,6))} dir$>={if(?<0.5,-1,1)*round(?(1,2))}
    100%,100%,1,1,'$amp*cos(y*2*pi*$freq/h)'
  -done

  {w+2},100%,1,1,'x' 100%,100%,1,1,'Y=(y-60+5*cos(x/30)+10*sin(x/15));if(Y<0||Y>=32,-1,Y)' -a[-2,-1] c
  0 -t[-1] "** Welcome to G'MIC, a powerful image processing framework **",0,0,32,1,255
  -b[-1] 0.6 -n[-1] 0,255
  M={w}

  # Start animation loop.
  -w[] {2*@{0,w}},{2*@{0,h}},0,0,"[G'MIC] Plasma demo"
  t=0 tt={-1.5*@{0,w}}
  -do
    tic=@|

    # Render interpolated background between two successive plasmas.
    a={int($t)}   a2={2*$a} a21={$a2+1}
    b={($a+1)%$N} b2={2*$b} b21={$b2+1}
    --warp[$a2] [$a21],1,0,2
    --warp[$b2] [$b21],1,0,2
    -j[-2] [-1],0,0,0,0,{$t-$a} -rm[-1]

    -shift[$a21] 0,${dir$a},0,0,2  # Animate plasma background.
    -shift[$b21] 0,${dir$b},0,0,2
    -if {int($t+0.005)>int($t)} dir$a={if(?<0.5,-1,1)*round(?(1,3))} -endif
    t={($t+(@|-$tic))%$N}

    # Render text scrolling.
    --z[-2] $tt,{$tt+w-1+2}
    -warp[-1] [-4],0,0,0
    -r[-1] 100%,100%,1,3
    --*[-1] -1 -+[-1] 255
    -j[-3] [-1],0,0,0,0,1,[-2],255 -rm[-1]
    -j[-2] [-1],-2,-2,0,0,1,[-1],255 -rm[-1]

    tt={$tt+(@|-$tic)*100} # Animate scrolling.
    -if {$tt>=$M} tt={-1.5*@{0,w}} -endif

    # Display rendered frame.
    -w[-1] -rm[-1]
    -wait 20
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm[{-2*$N-2}--1] -w[] 0 -endl -v +

#@gmic x_reflection3d
#@gmic : Launch the 3d reflection demo.
x_reflection3d :
  -e[] "\n
------ 3d reflection demo ---------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v -

  # Render background.
  128,256,1,3 -rand[-1] 0,255 -plasma[-1] 1,100 -blur_xy[-1] 30,2
  -sh[-1] 0,0 -n[-1] 0,90 -rm[-1] -sh[-1] 1,1 -n[-1] 0,60 -rm[-1] -sh[-1] 2,2 -n[-1] 0,180 -rm[-1]
  --mirror[-1] x [-2,-1] -a[-4--1] x
  --luminance[-1] -mirror[-1] x -b[-1] 2 -n[-1] 0,255

  # Create 3d objects.
  -torus3d 30,10 -col3d[-1] 255,200,0
  -spherical3d 47,34,"80+20*abs(cos(2*theta))" -s3d[-1] -rm[-2] -i[-2] 3,{h},1,1,150,220,255,200,255,255 -y[-2] y -a[-6--1] y
  -spherical3d 47,34,"100*abs(1+0.6*cos(3*phi)*sin(4*theta))"
  -r3d[-2,-1] 0,1,0,90 -db3d 0

  # Start animation loop.
  xb=0 xl=0 anim=0
  -w[] 400,400,0,0,"[G'MIC] 3d reflection demo"
  -do

    tic=@|
    # Recreate 3d interpolated background object.
    --rows[-1] 8,{8+3*i(0,6)-1} --j[-3] [-1],0,8,0,0,{if($anim<250,0,0.5-0.5*cos(($anim-250)/100))} -rm[-2]

    # Render 3d background object (with flat colors).
    --z[-6] $xb,0,{$xb+255},255 -object3d[-1] [-2],75%,50%,0,1,3,0,0

    # Render light reflection map.
    --z[-6] $xl,0,{$xl+255},255
    xf={min(30,$anim-70)+20*cos(1.8*@|)}
    yf={50+20*sin(2.7*@|)}
    -object3d[-1] [-6],{20+$xf}%,$yf%,0,1,4,0,0

    # Add light reflection to 3d background object.
    -l3d [-1] -rm[-1] --object3d[-1] [-2],75%,50%,0,1,5,0,0 -j[-2] [-1],0,0,0,0,0.6 -rm[-3,-1]

    # Add 3d foreground object.
    -object3d[-1] [-4],$xf%,$yf%,0,1,4,0,0

    # Display frame and update animation variables.
    -w[-1] -rm[-1]
    xb={($xb+6)&255}
    xl={($xl-6)&255}
    anim={$anim+1}
    -r3d[-2,-1] {sin(0.5*@|)},{cos(@|)},1,{(@|-$tic)*33}
    -r3d[-3] -1,0.3,0.8,{(@|-$tic)*100}
    -wait 20
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm[-5--1] -w[] 0 -v +

#@gmic x_rubber3d
#@gmic : Launch the 3d rubber demo.
x_rubber3d :
  -e[] "\n
------ 3d rubber demo -------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-----------------------------------------"
  -v - -rm
  -sphere3d 150,0 -torus3d 70,15 -cylinder3d 20,40
  -col3d[-3] 200,200,200,0.3 -col3d[-2] 128,200,76 -col3d[-1] 200,128,76
  -c3d[-3--1] -r3d[-1] 1,0,0,70 -+3d[-3--1] -+3d[-1] 10,-8,20
  256,256,64,3
  {w},{h},1,3,'if(c==0,x,if(c==1,y,y*@{1,d}/h))'
  {w},{h},1,3
  frame=0
  -do
    {w},{h},1,3 -fc[-1] 16,32,32 -object3d[-1] [0],50%,50%,0,1,3,0,0 -j[1] [-1],0,0,$frame -rm[-1]
    -r3d[0] 0.1,1,0.6,{3*cos(@|*1.25)} -r3d[0] 1,0.2,0.6,-1
    --warp[1] [2],0,0 -*[3] 0.8 -*[-1] 0.2 -+[3,-1]
    -w[-1] {1.2*w},{1.2*h},0,0,"Rubber 3d" -wait 20
    -sh[2] 2,2 --[-1] 1 -and[-1] {@{1,d}-1} -rm[-1]
    frame={($frame-1)%@{1,d}}
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm -w 0 -v +

#@gmic x_shadebobs
#@gmic : Launch the shade bobs demo.
x_shadebobs :
  -e[] "\n
------ Shade bobs demo --------------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
-------------------------------------------------"
  -v - -rm t=100 -w 512,512,0,0,"[G'MIC] Shade bobs"

  # Start animation loop.
  -do
    t={$t+0.015}
    -if {$t>4*pi" || "@{!,b}} # Reset motions variables if necessary.
      rx={?(-1,1)} ry={?(-1,1)} rz={?(-1,1)} rt={?(-1,1)} rcx={?(-0.6*0.6)} t=0
      N={20+round(?(80))} R={(2+round(?(40)))*min(@{!,w},@{!,h})/300}
      -if $obj3d -rm[colormap,img,obj3d] -endif
      {4+round(?(12))},1,1,3 -noise[0] 255,2 -r[0] 256,1,1,3,3 -*[0] 255 -shift[0] 1 -nm[-1] colormap
      (67.5;73.5;109.5;103.5;51.5;100.5;{2*$N};$N) 3,{2*$N},1,1,0
      1,$N,1,1,5 2,$N,1,1,'y+x*$N' -a[-2--1] x -z[-1] 0,5
      4,$N,1,1,1 -y[-3--1] y -a[-4--1] y -nm[-1] obj3d
      @{!,w},@{!,h} -nm[-1] img
      -wait -1
    -endif

    # Compute bobs coordinates.
    r={$ry+$rx*cos(6*$rz*$t)+(1-$rx)*sin(6*$rt*$t)}
    (0;{30*$ry*($N-1)}) ($t;{2*pi*($N-1)/$N+$t}) -r[-2,-1] 1,$N,1,1,3
    -+[-2] {360*sin($rz*$t)} -*[-2] {pi/180}
    --sin[-2,-1] -cos[-4,-3] -*[-4,-2] $r -*[-3,-1] $rcx -+[-4,-3] -+[-2,-1]
    -*[-2] {@{!,w}/2} -*[-1] {@{!,h}/2} -a[-2,-1] x
    --+[-1] $R --[-2] $R -a[-2,-1] y -z[-1] 0,2 -y[-1] y -j[obj3d] [-1],0,8 -rm[-1]

    # Draw bobs, map colors and display.
    -object3d[img] [obj3d],50%,50%,0,-1,2,0,0
    -and[img] 255 --map[img] [colormap] -w[-1] -rm[-1] -wait 20
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm -w 0 -v +

#@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] "[G'MIC] 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
  roundness=0.5  # Curve roundness
  visuflags=23   # Visualisation flags
  nearest=-1     # Nearest point
  active=-1      # Active point

  # Start event loop.
  -do

    # Init coordinates [1] if necessary.
    -if {@{1,#}==1}
      -rm[1] roundness=0.5 nearest=-1 active=-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] $roundness # 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 {$visuflags&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 {$visuflags&1} -spline[-1] @{2,0-1},@{3,0-1},@{2,2-3},@{3,2-3},1,255 -endif
      -if {$visuflags&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 {$visuflags&16} -t[-1] $>,{@{2,0}-3},{@{2,1}-18},13,1,255,255,0 -endif
      -if {$visuflags&32} -t[-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 {$visuflags"&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} visuflags={$visuflags+if($visuflags&1,-1,1)} -wait -1 -endif  # Show/hide spline.
    -if @{!,P} visuflags={$visuflags+if($visuflags&2,-2,2)} -wait -1 -endif      # Show/hide points.
    -if @{!,ENTER} visuflags={$visuflags+if($visuflags&4,-4,4)} -wait -1 -endif  # Show/hide polygon.
    -if @{!,T} visuflags={$visuflags+if($visuflags&8,-8,8)} -wait -1 -endif      # Show/hide tangents.
    -if @{!,I} visuflags={$visuflags+if($visuflags&16,-16,16)} -wait -1 -endif   # Show/hide indices.
    -if {@{!,C}" && "!@{!,CTRLLEFT}" && "!@{!,CTRLRIGHT}} visuflags={$visuflags+if($visuflags&32,-32,32)} -wait -1 -endif # Show/hide coordinates.
    -if {@{!,PADADD}" && "$roundness<1} roundness={$roundness*1.1} -wait -1 -endif    # Increase roundness.
    -if {@{!,PADSUB}" && "$roundness>0.1} roundness={$roundness*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} active=-1                                   # Unset active point if mouse button is released.
    -elif {@{!,x}>=0" && "@{!,b}" && "$active==-1}              # Find new active point.
      [2] (@{!,x},@{!,y}) --[-2,-1] -sqr[-1] -s[-1] x -+[-2,-1] # Compute distance vector to points.
      (@{-1,c}) nearest=@{-1,1} -rm[-1]                         # Set nearest point.
      -if {@{-1,m}<64} active=$nearest -endif                   # Set it as active point, if near enough.
      -rm[-1]
    -endif
    -rm[2]

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

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

    # Insert new active point.
    -elif {@{!,b}&1" && "@{!,x}>=0}
      xy=({@{!,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.
      $xy --[-2,-1] -sqr[-1] -s[-1] x -+[-2,-1]                       # Compute distance vector to segments.
      (@{-1,c}) ns=@{-1,1} -rm[-2,-1]                                 # Get nearest segment.
      -l[1] -s y -i[{$ns+1}] $xy -a y -endl                           # Insert new point at right position.
      active={$ns+1}                                                  # 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] $roundness
  [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,0,1,0

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

#@gmic x_tetris
#@gmic : Launch tetris game.
x_tetris :
  -e[] "\n
------ Tetris --------------------------------------------\n
----\n
---- This is a G'MIC implementation of the Tetris game.\n
----\n
---- Arrow keys to move/rotate the triominos.\n
---- Key 'SPACE' to make the current triomino falling.\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------------------"
  -v - -rm

  # Init board and triominos shapes.
  -i[m0] 4,1,1,1,1,1,1,1
  -i[m4] 3,2,1,1,1,0,0,1,1,1
  -i[m8] 3,2,1,1,0,0,1,1,1,1
  -i[m12] 2,2,1,1,1,1,1,1
  -i[m16] 3,2,1,1,0,1,1,1,1,0
  -i[m20] 3,2,1,1,0,1,0,1,1,1
  -i[m24] 3,2,1,1,1,1,0,0,1,1
  -if {?<0.25}  # Enable extended set.
    -i[m28] 2,1,1,1,1,1
    -i[m32] 2,2,1,1,1,1,0,1
    -i[m36] 3,1,1,1,1,1,1
    -i[m40] 1,1,1,1,1
    -i[m44] 3,2,1,1,1,1,1,1,0,1
    -i[m48] 3,3,1,1,1,1,1,1,0,1,1,1,1
  -endif
  -repeat @# i={4*$>} -l[m$i] -repeat 3 --rotate[0] {90*($>+1)} -nm[-1] m{$i+$>+1} -done -endl -done
  N=@#

  # Render triomino colored sprites.
  -i[colors] 3,$N,1,1,'?(16,224)' -r[-1] 3,400% -i[mask] (0,-1,0;1,0,-1;0,1,0) -*[-1] 120
  -repeat $N
    --r[m$>] 500%,500%,1,3 --correlate[-1] [mask],0 -r[-1] 200%,200%,1,1,3 -r[-2] [-1] -*[-2,-1] -c[-1] 30%,100%
    --r[m$>] [-1],[-1],1,3 --replace_color[-1] 0,0,1,1,1,@{colors,{3*$>}-{3*$>+2}} -rv[-3,-1] -+[-3,-1] -c[-2] 0,255
    -channels[-1] 0 -*[-1] 255 -a[-2,-1] c -nm[-1] s$>
  -done
  -rm[colors,mask]
  fact={@{s0,w}/@{m0,w}}

  # Generate board and background.
  W=12 H=20
  -i[board] $W,$H -i[curr_board] [board]
  -i[render] {$fact*$W},{$fact*$H},1,3 -i[curr_render] [render] --channels[-1] 0 -nm[-1] curr_render_mask
  --rows[render] 0,50% -plasma[-1] 1,2 -noise[-1] 20 -blur_y[-1] 40%,1 --mirror[-1] y -a[-2,-1] y -r[-1] [render]
  -n[-1] 0,64 -blur_x[-1] 1 100%,100% -noise[-1] 0.5,2 -b[-1] 1 -*[-1] 300 -+[-2,-1] -c[-1] 0,255 -nm[-1] background

  # Start game.
  time=@| score=0 fall_mode=0 gameover=0 n=-1 nn={round(?(0,$N-1))}
  -do
    -wait {if($fall_mode,-1,-20)}

    # In case of game over.
    -if $gameover
      --j[background] [curr_render],0,0,0,0,0.7,[curr_render_mask],255
      -text_outline[-1] "Game\nOver!",30,30%,32,2,1,255 -w[-1] -rm[-1]
      -continue
    -endif

    # Check for completed lines and select new random triomino.
    -if {$n<0}
      -l[board] -s y i=-1 -repeat @# -if @{$<,m} i=$<,$i -endif -done
      0 -rm[$i] -a y score={$score+2^(narg($i)-1)-1} -r $W,$H,1,1,0,0,0,1 -nm board -endl
      -if {narg($i)>1} -l[render] -s y,$H 0 -rm[$i] -a y -r {$fact*$W},{$fact*$H},1,3,0,0,0,1 -nm render -endl -endif
      n=$nn nn={round(?(0,$N-1))} x={$W/2} y=0 do_render=1 fall_mode=0
    -endif

    # Render board at current time.
    -if $do_render
      -rm[curr_board,curr_render,curr_render_mask]
      -i[curr_board] [board] -j[curr_board] [m$n],{$x-int(@{m$n,w}/2)},$y,0,0,1,[m$n]
      -i[curr_render] [render] --sh[s$n] 3,3 -j[curr_render] [s$n],{$fact*($x-int(@{m$n,w}/2))},{$fact*$y},0,0,1,[-1],255 -rm[-1]
      --*[curr_board] 255 -r[-1] [curr_render],[curr_render] -nm[-1] curr_render_mask
      0 -t[-1] "Score : "$score"    Next :",4,0,32,1,164 -r[-1] 40%,40%,1,3,2 --neq[-1] 0 -*[-1] 255
      -j[curr_render] [-2],0,0,0,0,1,[-1],255 -j[curr_render_mask] [-1],0,0,0,0,1,[-1],255 -rm[-2,-1]
      --*[m$nn] 196 -r[-1] 300%,300%,1,3 -j[curr_render,curr_render_mask] [-1],{@{curr_render,w}-w-4},3,0,0,1,[-1],196 -rm[-1]
      do_render=0
    -endif

    --shift[background] 0,{-13*@|*1.04^$score},0,0,2
    -j[-1] [curr_render],0,0,0,0,1,[curr_render_mask],255
    -w[-1] {2*w},{2*h},0,0,"[G'MIC] Tetris" -rm[-1]

    # Manage user interactions.
    -if @{!,SPACE} fall_mode=1 -endif
    -if {@{!,ARROWUP}" || "@{!,ARROWLEFT}" || "@{!,ARROWRIGHT}}
      an={if(@{!,ARROWUP},n=$n+1;if(n%4,n,n-4),$n)}
      nx={w2=int(@{m$an,w}/2);max(w2,min($x-@{!,ARROWLEFT}+@{!,ARROWRIGHT},$W-(@{m$an,w}%2)-w2))}
      --j[board] [m$an],{$nx-int(@{m$an,w}/2)},$y,0,0,-1,[m$an]
      -if {@{-1,M}==1} x=$nx n=$an -endif
      -rm[-1]
      do_render=1
    -endif

    -if {@{!,ARROWDOWN}" || "@|-$time>0.9^int($score/2)" || "$fall_mode}   # Piece goes down.
      y={$y+1}
      --j[board] [m$n],{$x-int(@{m$n,w}/2)},$y,0,0,-1,[m$n]
      -if {@{-1,M}>1" || "$y+@{m$n,h}>$H}
        -if {$y<=1} gameover=1 -endif  # Game over!
        -j[board] [curr_board] -j[render] [curr_render] n=-1
      -endif
      -rm[-1]
      time=@| do_render=1
    -endif

  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm -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.
  message=0                       # [-7] : State message.
  counter=0                       # [-6] : Turn counter (0 to 8).
  player=0                        # [-5] : Current player (0 or 1).
  state=0                         # [-4] : Board state.
  tmp3=0                          # [-3] : Temporary variable 3.
  tmp2=0                          # [-2] : Temporary variable 2.
  tmp1=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 $player message="Tic-Tac-Toe (O to play)"
    -else message="Tic-Tac-Toe (X to play)"
    -endif

    # Select position by the user.
    -do                                                                       # Enter event loop.
      -w[] {w},{h},0,0,"[G'MIC] "$message -wait                               # Wait for events and force window size if necessary.
      -if {!@!} -w[] 0 -rm -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.
        tmp3={int((@{!,x}-15)/130)}                                                # Get x-coord of the selected position (0,1 or 2).
        tmp2={int((@{!,y}-15)/130)}                                                # Get y-coord of the selected position (0,1 or 2).
        tmp1={4^($tmp2*3+$tmp3)}                                                   # Get state code of the selected position.
        -if {int($state/$tmp1)%4} tmp1=-1 -endif                                   # Check availability of the selected position.
      -else tmp1=-1 -endif                                                    # If no mouse button, do nothing but loop.
    -while {$tmp1<0}                                                          # Go on until a valid position has been selected.

    # Draw symbol on selected position and update board state.
    -_x_tictactoe{$player%2}                                                  # Generate the symbol sprite and his mask.
    -j[-3] [-2],{"130*"$tmp3" + 15+?(-5,5)"},\                                # Draw symbol at its position (with some fuzzyness).
                {"130*"$tmp2" + 15+?(-5,5)"},0,0,1,[-1]
    -rm[-2--1]                                                                # Delete the sprite and the mask (not needed anymore).
    -w[-1]                                                                    # Update display window.
    state={$state+(1+$player)*$tmp1}                                          # 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.
      tmp1=@{-1,$>}                                                           # Save the current configuration code (used several times).
      -if {($state&$tmp1)==$tmp1||($state&(2*$tmp1))==2*$tmp1}                # If a winner has been found.
        -_x_tictactoe@{-1,($>,3)}                                               # Generate the stroke symbol and his mask.
        -j[-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 {($state&$tmp1)==$tmp1} -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 -w[] 0 -v + -return                                                 # And return properly.
      -endif
    -done                                                                     # Go on until all configurations have been checked.
    -rm[-1]                                                                   # Delete winning configuration data.

    player={($player+1)%2}                                                  # Select next player.
    counter={$counter+1}                                                    # Increment turn counter.
  -while {$counter<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.
  -w[] 0 -rm -v +                                                           # Return properly.

# Generate Tic-Tac-Toe graphics.
_x_tictactoe : # Apply a hand-drawing effect.
  -spread[-1] 4 -b[-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 -b[-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_whirl : _opacity>=0
#@gmic : Launch fractal whirl demo.
#@gmic : Default values: 'opacity=0.2'.
x_whirl : -check ${1=0.2}>=0
  -e[] "\n
------ Fractal whirl demo ------------------------\n
----\n
---- Keys 'ESC' or 'Q' to exit.\n
----\n
--------------------------------------------------"

  -v -
  5,5,1,3 256,256,1,3 [-1] -w[-1] 512,512,0,0,"[G'MIC] Fractal whirl demo"
  tangle=0 tzoom=0 xc={(w-@{-3,w})/2} yc={(h-@{-3,h})/2}
  -do
    -rand[-3] 0,255 -j[-2] [-3],$xc,$yc,0,0
    -rotate[-2] {8*sin($tangle)},0,0,{w/2+?(-2,2)},{h/2},{1.03+0.02*sin($tzoom)}
    tangle={$tangle+0.001} tzoom={$tzoom+0.02}
    -j[-1] [-2],0,0,0,0,$1 -w[-1] -wait 20
  -while {@!" && "!@{!,ESC}" && "!@{!,Q}}
  -rm[-3,-2] -w[] 0 -v +

#------------------------------------
#
#@gmic :: PINK-library operators
#
#------------------------------------

_wrbytepnk :
  -output_pink3d ${1}.pnk

_xpink :
  filename=@{-file_rand}
  -if {!@{-is_windows}}
    -x "which $1 >/dev/null 2>&1"
    -if {@{}!=0} -error "executable "$1" not found in PATH, status = "@{}"!! Returning!!\n" -return -endif
    -output_pink3d ${filename}.pnk -x "$1 "${filename}".pnk $2 "${filename}"_o.pnk >/dev/null 2>&1"
  -else
    -output_pink3d ${filename}.pnk -x "$1 "${filename}".pnk $2 "${filename}"_o.pnk"
  -endif
  status=@{}
  -file_rm ${filename}.pnk
  -if {$status!=0\ &&\ {$1'!='seuilauto} -error "exec Status is "${status}"." -return
  -elif ${filename}_o.pnk -i ${filename}_o.pnk -file_rm ${filename}_o.pnk -k[-1]
  -else -error "exec Error!!" -endif

_xpinks :
  s=@{-1,s} -if {$s>1} -s[-1] c -endif
  -repeat @# -l[@{>,-1}]  -_xpink $1,"$2" -k[-1] -endl -done
  -if {$s>1} -a[-$s--1] c -endif

_xframe :
  -line 0%,0%,100%,0% -line 0%,100%,100%,100% -line 0%,0%,0%,100% -line 100%,0%,100%,100%

#@gmic output_pink3d : filename
#@gmic : Save selected images as P5-coded PPM files (PINK extension for 3d volumetric images).
output_pink3d :
  -e[^-1] "Output image$? as file '$1' (in 3d pink extension of P5-coded PPM format)."
  -v - -if {@#==1} filename0="$1"
  -else -repeat @# filename$>=@{-filename\ "\"$1\"",$>} -done
  -endif
  -repeat @# -l[$>]
    -if {d==1} -o[-1] ppm:${filename$>}  # 2d image, save as regular PPM format.
    -else                                # 3d image, save as PINK PPM extension.
      ({'P5\n{w}\ {h}\ {d}\n255\n'})
      --channels[-2] 0 -y[-1] x -a[-2,-1] x
      -o[-1] raw:${filename$>},uchar
      -rm[-1]
    -endif
  -endl -done -v +

#@gmic pink
#@gmic : Pink wrapper name,p1, .. ,pn (requires the PINK library to be installed).
#@gmic : (http://pinkhq.com/)
#@gmic : prepares input, calls external "name input p1 ... pn output" and reads output (/tmp)
#@gmic : $ image.jpg --pink asfr,5 -pink[0] asf,5
#@gmic : $ image.jpg --blur 2 -pink maxima,4
pink : -v -
  -if {$#>1} ({"'${2--1}'"}) -replace[-1] {','},{"' '"} p=@{-1,t} -rm[-1] -else p=" " -endif
  -v + -e[^-1] "Call pink package with cmd: \"$1$? "$p"$?\"." -v -
  -repeat @# -l[@{>,-1}] -_xpinks $1,$p -endl -done -v +

#@gmic pink_grayskel : _connectivity={ 4 | 8 | 6 | 26 }, _lambda=0
#@gmic : (http://pinkhq.com/grayskel_8c.html)
#@gmic : Grayscale homotopic skeleton (requires the PINK library to be installed).
#@gmic : Default values: 'connectivity=4' and 'lambda=0'.
#@gmic : $ image.jpg --pink_grayskel , --pink_grayskel[0] ,10 --pink_grayskel[0] ,100 -append_tiles 2
pink_grayskel : -skip ${1=4},${2=0}
  -check "${1=4}==4 || $1==8 || $1==6 || $1==26"
  -repeat @# -l[@{>,-1}] -_xpinks "grayskel","null $1 $2" -endl -done

#@gmic pink_heightmaxima : _connectivity={ 4 | 8 | 6 | 26 },_height=1
#@gmic : (http://pinkhq.com/heightmaxima_8c.html)
#@gmic : Heightmaxima filtering (requires the PINK library to be installed).
#@gmic : Default values: 'connectivity=4' and 'height=1'.
#@gmic : $ image.jpg --blur 2 --pink_heightminima ,15 --pink_heightmaxima[0,1] ,15 --[-3,-1] --[-3,-1] -k[-1,-2]
pink_heightmaxima : -check "${1=4}==4 || $1==8 || $1==6 || $1==26" -skip ${2=1}
  -e[^-1] "Filter by heightmaxima exec with connectivity $1 height $2."
  -v - -repeat @# -l[@{>,-1}]
    s=@{-1,s} -if {$s>1} -s[-1] c -endif
    -repeat @# -l[@{>,-1}] -_xpink "heightmaxima","$1 $2" -k[-1] -endl -done
    -if {$s>1} -a[-$s--1] c -endif
  -endl -done -v +

#@gmic pink_heightminima : _connectivity={ 4 | 8 | 6 | 26 },_height=1
#@gmic : (http://pinkhq.com/heightminima_8c.html)
#@gmic : Heightminima filtering (requires the PINK library to be installed).
#@gmic : Default values: 'connectivity=4' and 'height=1'.
#@gmic : $ image.jpg --blur 2 --pink_heightminima ,15 --pink_heightmaxima[0,1] ,15 --[-3,-1] --[-3,-1] -k[-1,-2]
pink_heightminima : -check "${1=4}==4 || $1==8 || $1==6 || $1==26" -skip ${2=1}
  -e[^-1] "Apply filter by heightminima exec with connectivity $1 height $2."
  -v - -repeat @# -l[@{>,-1}]
    s=@{-1,s} -if {$s>1} -s[-1] c -endif
    -repeat @# -l[@{>,-1}] -_xpink "heightminima","$1 $2" -k[-1] -endl -done
    -if {$s>1} -a[-$s--1] c -endif
  -endl -done -v +

#@gmic pink_htkern : _connectivity={ 4 | 8 | 6 | 26 }, _type={""|u}
#@gmic : (http://pinkhq.com/htkern_8c.html)
#@gmic : (http://pinkhq.com/htkernu_8c.html)
#@gmic : Grayscale ultimate homotopic thinning/thickening without condition (requires the PINK library to be installed).
#@gmic : Default values: 'connectivity=4' and 'type=""'.
#@gmic : $ image.jpg --pink_htkern ,u --pink_htkern[0] , ---[-1,-2] -rm[0]
pink_htkern : -skip ${1=4},${2=""}
  -repeat @# -l[@{>,-1}] -_xpinks htkern$2,"null $1" -endl -done

#@gmic pink_lvkern : _connectivity={ 4 | 8 | 6 | 26 }, _type={""|u}
#@gmic : (http://pinkhq.com/lvkern_8c.html)
#@gmic : (http://pinkhq.com/lvkernu_8c.html)
#@gmic : Grayscale ultimate leveling thinning/thickening without condition (requires the PINK library to be installed).
#@gmic : Default values: 'connectivity=4' and 'type=""'.
#@gmic : $ image.jpg -pink_lvkern ,u
pink_lvkern : -skip ${1=4},${2=""}
  -check "${1=4}==4 || $1==8 || $1==6 || $1==26"
  -repeat @# -l[@{>,-1}] -_xpinks lvkern${2},"null $1" -endl -done

#@gmic pink_reg_minima : _connectivity={ 4 | 8 | 6 | 26 }
#@gmic : (http://pinkhq.com/minima_8c.html)
#@gmic : Regional minima (requires the PINK library to be installed).
#@gmic : Default values: 'connectivity=4'.
#@gmic : $ image.jpg --blur 2 -pink_reg_minima ,
pink_reg_minima : -check "${1=4}==4 || $1==8 || $1==6 || $1==26"
  -e[^-1] "Compute regional minima exec with connectivity $1."
  -v - -repeat @# -l[@{>,-1}]
    s=@{-1,s} -if {$s>1} -s[-1] c -endif
    -repeat @# -l[@{>,-1}]  -_xpink "minima","$1" -k[-1] -endl -done
    -if {$s>1} -a[-$s--1] c -endif
  -endl -done -v +

#@gmic pink_skelcurv : _prio={0|1|2|3|4|8|6|26},_connectivity={ 4 | 8 | 6 | 26 },_inhibit={""}
#@gmic : (http://pinkhq.com/skelcurv_8c.html)
#@gmic : Curvilinear binary skeleton guided by a priority function or image (requires the PINK library to be installed).
#@gmic : Default values: 'prio=0', 'connectivity=4' and 'inhibit=""'.
#@gmic : $ image.jpg -threshold 50% {w},{h} -fill[-1] 'if(x>w/2,255,0)' tp=@{-path_tmp} -output[-1] ${tp}/inhibit.pgm -remove[-1] --pink_skelcurv[0] , --pink_skelcurv[0] ,,${tp}/inhibit.pgm -exec "rm "${tp}"/inhibit.pgm"
#@gmic : $ image.jpg -threshold 50% --pink_skelcurv , --pink_skelcurv[-2] ,8
pink_skelcurv : -skip ${1=0},${2=4},${3=""}
  -e[^-1] "Curvilinear binary skeleton guided by a priority function or image from image$?, prio=$1, connectivity=$2, inhibit=$3."
  -repeat @# -l[@{>,-1}] -_xpinks "skelcurv","$1 $2 $3" -endl -done

#@gmic pink_skelend : _connectivity={ 4 | 8 | 6 | 26 },_n=0
#@gmic : (http://pinkhq.com/skelend_8c.html)
#@gmic : Homotopic skeleton of a 2d or 3d binary image with dynamic detection of end points (requires the PINK library to be installed).
#@gmic : Default values: 'connectivity=4' and 'n=0'.
#@gmic : $ image.jpg -threshold 50% --pink_skelend , --pink_skelend[-2] ,-1
pink_skelend : -skip ${1=4},${2=0}
  -repeat @# -l[@{>,-1}] -_xpinks "skelend","$1 $2" -endl -done

#@gmic pink_skeleton : _prio={0|1|2|3|4|8|6|26},_connectivity={ 4 | 8 | 6 | 26 },_inhibit={""}
#@gmic : (http://pinkhq.com/skeleton_8c.html)
#@gmic : Ultimate binary skeleton guided by a priority image (requires the PINK library to be installed).
#@gmic : Default values: 'prio=0', 'connectivity=4' and 'inhibit=""'.
#@gmic : $ image.jpg -threshold 50% --pink_skeleton[-1] ,
 pink_skeleton : -skip ${1=0},${2=4},${3=""}
  -repeat @# -l[@{>,-1}] -_xpinks "skeleton","$1 $2 $3" -endl -done

#@gmic pink_skelpar : _algorithm={0..29},_nsteps=_1,_inhibit=""
#@gmic : (http://pinkhq.com/skelpar_8c.html)
#@gmic : Parallel binary skeleton (requires the PINK library to be installed).
#@gmic : Default values: 'algorithm=4', 'nsteps=-1' and 'inhibit=""'.
#@gmic : $ image.jpg -threshold 50% --pink_skelpar[-1] 0 --pink_skelpar[-1] 2
pink_skelpar : -skip ${1=4},${2=-1},${3=""}
  -repeat @# -l[@{>,-1}] -_xframe -_xpinks "skelpar","$1 $2 $3" -endl -done

#@gmic pink_wshed : _connectivity={ 4 | 8 | 6 | 26 },_inverse={ 0 | 1 },_height=0
#@gmic : (http://pinkhq.com/wshedtopo_8c.html)
#@gmic : Watershed (requires the PINK library to be installed).
#@gmic : Default values: 'connectivity=4', 'inverse=0' and 'height=0'.
#@gmic : $ image.jpg --pink_wshed ,1,5 -pink_wshed[0] ,,5
pink_wshed : -check "${1=4}==4 || $1==8 || $1==6 || $1==26" -skip ${2=0},${3=0}
  -e[^-1] "Compute wshedtopo exec with connectivity $1 inversion $2 height $3."
  -v - -repeat @# -l[@{>,-1}]
    s=@{-1,s} -if {$s>1} -s[-1] c -endif
    -if {d==1}
      -check "${1=4}==4 || $1==8"
      -repeat @# -l[@{>,-1}]
        -if {$2!=0} -negative -endif
        -fill max(min(i,255),0)
        -if {$3>=0} -pink heightminima,$1,$3 -endif
        -pink wshedtopo,$1
        -if {$2!=0} -negative -endif
      -endl -done
    -else
      -check "$1==6 || $1==26"
      -repeat @# -l[@{>,-1}]
        -if {$2!=0} -negative -endif
        -fill max(min(i,255),0)
#        -output_pink3d ${filename}.pnk
        -if {$3>=0}
          -pink heightminima,$1,$3
        -endif
        -pink wshedtopo,$1
#        -i ${filename}_.pnk
        -if {$2!=0} -negative -endif
#        -x "rm "${filename}"*" -k[-1]
      -endl -done
    -endif
    -if {$s>1} -a[-$s--1] c -endif
  -endl -done -v +

#------------------------------
#
#@gmic :: Convenience functions
#
#------------------------------

#@gmic arg : n,_arg1,...,_argN
#@gmic : Return the n-th argument of the specified argument list.
#@gmic : 'n' can be also a pattern, as '1--1' for instance.
arg :
  -m "__arg : -u ${"$1"}" -__arg ${2--1} -uncommand __arg

#@gmic at : _x,_y,_z
#@gmic : Return a specified vector-valued point (x,y,z) from the latest of the selected images.
at : -skip ${1=0},${2=0},${3=0}
  --z[-1] ${1-3},${1-3} -u @-1 -rm[-1]

#@gmic average_color
#@gmic : Return the average color of the latest of the selected images.
average_color :
  res=""
  -repeat {s-1} -sh[-1] {1+$>},{1+$>} res=$res,{ia} -rm[-1] -done
  -sh[-1] 0,0 -u {ia}$res -rm[-1]

#@gmic basename : file_path,_variable_name_for_folder
#@gmic : Return the basename of a file path, and opt. its folder location.
#@gmic : When specified 'variable_name_for_folder' must starts by an underscore
#@gmic : (global variable accessible from calling function).
basename : -skip ${2=unused}
  -l[] ({"'$1'"}) -replace 92,47 -s +,47
  -if {i==47} -a y $2=@{-1,t} -u ""
  -elif {@#==1} -u @{-1,t} $2=""
  -else -a[^-1] y -u @{-1,t} $2=@{-2,t}
  -endif
  -rm -endl

#@gmic bin : binary_int1,...
#@gmic : Print specified binary integers into their octal, decimal, hexadecimal and string representations.
bin :
  -v - dec=@{-bin2dec\ ${^0}} -v +
  -e[^-1] "Convert binary integer"@{"-if {$#>1} -u s -else -u \"\" -endif"}" '${^0}' to octal '"@{-dec2oct\ $dec}"',
           decimal '"$dec"', hexadecimal '"@{-dec2hex\ $dec}"' and string '"@{-dec2str\ $dec}"'."

#@gmic bin2dec : binary_int1,...
#@gmic : Convert specified binary integers into their decimal representations.
bin2dec :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_bin2dec :
  ({'@{-struncase\ $1}'})
  is_negative=0
  -if {@{-1,0}==45} -z[-1] 1,100% is_negative=1 -endif
  -f[-1] "if(i>=48 && i<=49,(i-48)*2^(w-1-x),nan)"
  -u {if($is_negative,-1,1)*@{-1,+}}
  -rm[-1]

# compress_gmic
# Compress .gmic custom command files for the 'gmic' command line tool,
# by removing empty lines, and useless comments (non starting with '#@gmic').
compress_gmic :
  head_std={'"#@gmic"'}
  -s -,10
  -repeat @#
    -if {i=={'#'}}
      head=@{-1,0-{min(5,h-1)}}
      -if {{$head'!='$head_std}" || "(i(0,6)!={'" "'}" && "i(0,6)!={':'})} -rm[-1] -continue
      -endif
    -else
      -l[-1] -split +,32,35 -if {@#>2} -k[0] -endif -a y -endl
      -autocrop[-1] 32 -if {!w} -rm[-1] -continue -endif
    -endif
  -mv[-1] 0 -done
  -i[1--2] (10) -a y

# compress_gmic_gimp
# Compress .gmic custom command files for the GIMP plug-in,
# by removing empty lines, and useless comments (non starting with '#@gimp').
compress_gmic_gimp :
  head_std={'"#@gimp"'}
  -s -,10
  -repeat @#
    -if {i=={'#'}}
      head=@{-1,0-{min(5,h-1)}}
      -if {$head'!='$head_std} -rm[-1] -continue
      -endif
    -else
      -l[-1] -split +,32,35 -if {@#>2} -k[0] -endif -a y -endl
      -autocrop[-1] 32 -if {!w} -rm[-1] -continue -endif
    -endif
  -mv[-1] 0 -done
  -i[1--2] (10) -a y

#@gmic dec : decimal_int1,...
#@gmic : Print specified decimal integers into their binary, octal, hexadecimal and string representations.
dec :
  -e[^-1] "Convert decimal integer"@{"-if {$#>1} -u s -else -u \"\" -endif"}" '${^0}' to binary '"@{-dec2bin\ ${^0}}"',
           octal '"@{-dec2oct\ ${^0}}"', hexadecimal '"@{-dec2hex\ ${^0}}"' and string '"@{-dec2str\ ${^0}}"'."

#@gmic dec2str : decimal_int1,...
#@gmic : Convert specifial decimal integers into its string representation.
dec2str :
  -u {`${^0}`}

#@gmic dec2bin : decimal_int1,...
#@gmic : Convert specified decimal integers into their binary representations.
dec2bin :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_dec2bin : -check isint($1)
  res="" r={abs($1)}
  -do res={$r%2}$res r={int($r/2)} -while $r
  -u @{"-if {$1>=0} -u \"\" -else -u - -endif"}$res

#@gmic dec2hex : decimal_int1,...
#@gmic : Convert specified decimal integers into their hexadecimal representations.
dec2hex :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_dec2hex : -check isint($1)
  res="" r={abs($1)}
  -do res=@{-_dec2hex_{$r%16}}$res r={int($r/16)} -while $r
  -u @{"-if {$1>=0} -u \"\" -else -u - -endif"}$res

_dec2hex_0 : -u 0
_dec2hex_1 : -u 1
_dec2hex_2 : -u 2
_dec2hex_3 : -u 3
_dec2hex_4 : -u 4
_dec2hex_5 : -u 5
_dec2hex_6 : -u 6
_dec2hex_7 : -u 7
_dec2hex_8 : -u 8
_dec2hex_9 : -u 9
_dec2hex_10 : -u a
_dec2hex_11 : -u b
_dec2hex_12 : -u c
_dec2hex_13 : -u d
_dec2hex_14 : -u e
_dec2hex_15 : -u f

#@gmic dec2oct : decimal_int1,...
#@gmic : Convert specified decimal integers into their octal representations.
dec2oct :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_dec2oct : -check isint($1)
  res="" r={abs($1)}
  -do res={$r%8}$res r={int($r/8)} -while $r
  -u @{"-if {$1>=0} -u \"\" -else -u - -endif"}$res

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

#@gmic file_mv : filename_src,filename_dest
#@gmic : Rename or move a file from a location $1 to another location $2.
file_mv :
  -if @{-is_windows} -x "move "$1" "$2 -else -x "mv "$1" "$2 -endif

#@gmic file_rand
#@gmic : Return a random filename for storing temporary data.
file_rand :
  -do filename=@{-path_tmp}@{-file_slash}gmic@%{round(?(0,9))}{round(?(0,9))}{round(?(0,9))}{round(?(0,9))}{round(?(0,9))}{round(?(0,9))}
  -while $filename
  -u $filename

#@gmic file_rm : filename
#@gmic : Delete a file.
file_rm :
  -if @{-is_windows}
    1 -nm[-1] "$1" dir=@{-1,f} base=@{-1,b} ext=@{-1,x} -rm[-1] com=""
    -if {narg($dir)} com="cd \""$dir"\\\" && " -endif
    -if {narg($ext)} com=${com}"del \""$base.$ext"\"" -else com=${com}"del \""$base"\"" -endif
    -x $com
  -else
    -x "rm -f \"$1\""
  -endif

#@gmic file_slash
#@gmic : Return '/' or '\' as a path separator for filenames.
file_slash :
  -if @{-is_windows} -u "\\" -else -u "/" -endif

#@gmic filename : filename,_number1,_number2,...,_numberN
#@gmic : 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

#@gmic fitratio_wh : min_width,min_height,ratio_wh
#@gmic : Return a 2d size '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

#@gmic fitscreen : width,height,_depth
#@gmic : Return the 'ideal' size WxH for a window intended to display an image of specified size on screen.
fitscreen : -check "$1>0 && $2>0 && ${3=1}>0"
  w={if($3>1,$1+$3,$1)}
  h={if($3>1,$2+$3,$2)}
  Mw={int(0.85*@{!,u})}
  Mh={int(0.85*@{!,v})}
  -if {$w<128} h={int($h*128/$w)} w=128 -endif
  -if {$h<128} w={int($w*128/$h)} h=128 -endif
  -if {$w>$Mw} h={max(1,int($h*$Mw/$w))} w=$Mw -endif
  -if {$h>$Mh} w={max(1,int($w*$Mh/$h))} h=$Mw -endif
  w={max($w,128)}
  h={max($h,128)}
  -u $w,$h

#@gmic gcd : a,b
#@gmic : Return the GCD (greatest common divisor) between a and b.
gcd : -check "isint($1) && isint($2) && $1*$2!=0"
  -_gcd {max(abs($1),abs($2))},{min(abs($1),abs($2))}

_gcd :
  r={$1%$2} -if $r -u @{"-_gcd "$2,$r} -else -u $2 -endif

#@gmic hex : hexadecimal_int1,...
#@gmic : Print specified hexadecimal integers into their binary, octal, decimal and string representations.
hex :
  -v - dec=@{-hex2dec\ ${^0}} -v +
  -e[^-1] "Convert hexadecimal integer"@{"-if {$#>1} -u s -else -u \"\" -endif"}" '${^0}' to binary '"@{-dec2bin\ $dec}"',
           octal '"@{-dec2oct\ $dec}"', decimal '"$dec"' and string '"@{-dec2str\ $dec}"'."

#@gmic hex2dec : hexadecimal_int1,...
#@gmic : Convert specified hexadecimal integers into their decimal representations.
hex2dec :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_hex2dec :
  ({'@{-struncase\ $1}'})
  is_negative=0
  -if {@{-1,0}==45} -z[-1] 1,100% is_negative=1 -endif
  -f[-1] "if(i>=48 && i<=57,i-48,if(i>=97 && i<=102,i-87,nan))*16^(w-1-x)"
  -u {if($is_negative,-1,1)*@{-1,+}}
  -rm[-1]

#@gmic hex2str : hexadecimal_string
#@gmic : Convert specified hexadecimal string into a string.
hex2str : -skip ${1=""}
  -if {!narg("$1")} -return -endif
  ({'$*'})
  -if {w<2} -rm[-1] -u "" -return -endif
  -r[-1] 2,{w/2},1,1,-1 -f[-1] 'if(i>=97,i-87,i-48)' -f[-1] 'if(x==0,i*16+i(x+1),0)' -columns[-1] 0
  -u @{-1,t} -rm[-1]

#@gmic img2str
#@gmic : Return the content of the latest of the selected image as a special G'MIC input string.
img2str :
  -u "("
  -repeat {s} c=$>
    -repeat {d} z=$>
      -repeat {h} y=$>
        --crop[-1] 0,$y,$z,$c,100%,$y,$z,$c
        -u @{}@-1
        -rm[-1]
        -if {$y!=h-1} -u @{}; -endif
        -e @{}
      -done
      -if {$z!=d-1} -u @{}/ -endif
    -done
    -if {$c!=s-1} -u @{}^ -endif
  -done
  -u @{}")"

#@gmic img2text : _line_separator
#@gmic : Return text contained in a multi-line image.
#@gmic : Default value: 'line_separator= '.
img2text : -skip "${1= }"
  -v - --l -s y -s -,0 -y x -if {@#>1} -i[1--2] ({'"$1"'}) -endif -a x -u @{0,t} -rm -endl -v +

#@gmic img82hex
#@gmic : Convert selected 8bits-valued vectors into their hexadecimal representations (ascii-encoded).
img82hex :
  -e[^-1] "Convert 8bits-valued vector$? into hexadecimal representations (ascii-encoded)."
  -v - -mod 256 -y y
  -repeat @#
    --f[$>] 'v=int(i)&15;v+if(v<10,48,87)'  # lower digit.
    -f[$>] 'v=int(i)>>4;v+if(v<10,48,87)'   # higher digit.
    -a[$>,-1] x
  -done -v +

#@gmic hex2img8
#@gmic : Convert selected hexadecimal representations (ascii-encoded) into 8bits-valued vectors.
hex2img8 :
  -e[^-1] "Convert hexadecimal representation$? (ascii-encoded) into 8bits-valued vectors."
  -v - -repeat @#
    -s[-1] x,2 -f[-2,-1] 'if(i>=97,i-87,i-48)' -*[-2] 16 -+[-2,-1]
  -mv[-1] 0 -done -v +

#@gmic is_3d
#@gmic : Return 1 if all of the selected image are 3d objects, 0 otherwise.
is_3d :
  res=0
  -if @# res=1 -repeat @# -l[$>] -+3d 0 -onfail res=0 -endl -done -endif
  -u $res

#@gmic is_percent : string
#@gmic : Return 1 if specified string ends with a '%', 0 otherwise.
is_percent :
  -u {arg(-1,{'"$1"'})==37}

#@gmic is_windows
#@gmic : Return 1 if current computer OS is Windows, 0 otherwise.
is_windows :
  -if {narg($OS)==1" && "narg($WINDIR)==1} -u 1 -else -u 0 -endif

#@gmic mad
#@gmic : Return the MAD (Maximum Absolute Deviation) of the last selected image.
#@gmic : The MAD is defined as MAD = med_i|x_i-med_j(x_j)|
mad :
  ---[-1] @{-med[-1]} -abs[-1] -med[-1] -u {1.4826*@{}} -rm[-1]

#@gmic max_w
#@gmic : Return the maximal width between selected images.
max_w :
  -u {arg(1,@{"-_max_whds 4"})}

#@gmic max_h
#@gmic : Return the maximal height between selected images.
max_h :
  -u {arg(2,@{"-_max_whds 4"})}

#@gmic max_d
#@gmic : Return the maximal depth between selected images.
max_d :
  -u {arg(3,@{"-_max_whds 4"})}

#@gmic max_s
#@gmic : Return the maximal spectrum between selected images.
max_s :
  -u {arg(4,@{"-_max_whds 4"})}

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

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

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

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

#@gmic med
#@gmic : Return the median value of the last selected image.
med :
  --sort[-1] -u @{-1,{w*h*d*s/2}} -rm[-1]

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

_min_s :
  -u $4

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

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

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

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

#@gmic oct : octal_int1,...
#@gmic : Print specified octal integers into their binary, decimal, hexadecimal and string representations.
oct :
  -v - dec=@{-oct2dec\ ${^0}} -v +
  -e[^-1] "Convert octal integer"@{"-if {$#>1} -u s -else -u \"\" -endif"}" '${^0}' to binary '"@{-dec2bin\ $dec}"', decimal '"$dec"',
           hexadecimal '"@{-dec2hex\ $dec}"' and string '"@{-dec2str\ $dec}"'."

#@gmic oct2dec : octal_int1,...
#@gmic : Convert specified octal integers into their decimal representations.
oct2dec :
  res=@{-_$0\ $1} -repeat {$#-1} res=$res,@{-_$0\ @{-arg\ {$>+2},${^0}}} -done -u $res

_oct2dec :
  ({'@{-struncase\ $1}'})
  is_negative=0
  -if {@{-1,0}==45} -z[-1] 1,100% is_negative=1 -endif
  -f[-1] "if(i>=48 && i<=55,(i-48)*8^(w-1-x),nan)"
  -u {if($is_negative,-1,1)*@{-1,+}}
  -rm[-1]

#@gmic padint : number,_size>0
#@gmic : Return a integer with 'size' digits (eventually left-padded with '0').
padint : -skip ${2=4}
  -u "" -repeat $2 -u @{}{int($1/10^$<)%10} -done

#@gmic path_tmp
#@gmic : Return a path to store temporary files (whose value is 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"
  -else -u ""
  -endif

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

#@gmic quote : string
#@gmic : Return a "quotified" version of the string.
quote :
  -u "$*"

#@gmic region_feature : region_label,feature,_default_value
#@gmic : Return feature for a specified region.
#@gmic : This function requires two images [img,region_label] in the selection.
#@gmic : Argument 'feature' is a string that corresponds to the way the feature would
#@gmic : be asked for the entire image.
#@gmic : Default value: 'default_value=0'.
#@gmic : $ image.jpg --luminance -quantize[-1] 2 -label[-1] 0,1 mean=@{"-region_feature[0,1] 10,\"{ia}\""} sum=@{"-region_feature[0,1] 10,\"@{-1,+}\""}
region_feature : -skip "${3=0}"
  s=@{-2,s} --channels[-1] 0 -==[-1] $1 -^[-1] -1 --[-1] 1 -r[-1] [-3] -+[-1] [-3]
  -l[-1]
    -s[-1] -,inf -a y                            # Keep only pixel values inside the selected region.
    -if @# -r[-1] 1,{h/$s},1,$s,-1 -u $2 -rm[-1] # If region is not empty, compute the feature.
    -else -u $3                                  # Otherwise set a default return value.
    -endif
  -endl

#@gmic reset
#@gmic : Reset global parameters of the interpreter environment.
reset :
  -e[^-1] "Reset global parameters of the interpreter environment."
  -v - -db3d 1 -b3d -m3d 4 -md3d -1 -f3d 800 -l3d -sl3d 0.15 -ss3d 0.8 -v +

#@gmic RGB
#@gmic : Return a random int-valued RGB color.
RGB :
  -u {round(?(255))},{round(?(255))},{round(?(255))}

#@gmic RGBA
#@gmic : Return a random int-valued RGBA color.
RGBA :
  -u {round(?(255))},{round(?(255))},{round(?(255))},{round(?(255))}

#@gmic str : string
#@gmic : Print specified string into its binary, octal, decimal and hexadecimal representations.
str : -skip $1
  -v - dec={'$*'} -v +
  -e[^-1] "Convert string '$*' to binary '"@{-dec2bin\ $dec}"', octal '"@{-dec2oct\ $dec}"', decimal '"$dec"' and
           hexadecimal '"@{-dec2hex\ $dec}"'."

#@gmic str2hex : string
#@gmic : Convert specified string into a sequence of hexadecimal values.
str2hex :
  ({'"$*"'}) -rows[-1] 0,1 -f[-1] 'if(y==0,int(i/16),i(x,y-1)%16)' -f[-1] 'if(i<=9,48+i,87+i)' -transpose[-1] -u @{-1,t} -rm[-1]

#@gmic stresc : val1,...,valN
#@gmic : Return escaped string from specified ascii codes.
stresc :
  ($*) -c[-1] 32,255 -y[-1] y [-1]
  -f[-2] 'if(i==32||i==34||i==36||i==44||i==64||i==92||i==123||i==125,92,-1)' -a[-2,-1] x
  -discard[-1] -1 -u @{-1,t} -rm[-1]

#@gmic strcat : string1,string2,...
#@gmic : Return the concatenation of all strings passed as arguments.
strcat :
  $=s res="$1" -repeat {$#-1} res=$res${s{$>+2}} -done
  -u $res

#@gmic strcmp : string1,string2
#@gmic : Return 1 if the two strings are equal, 0 otherwise.
strcmp :
  (0,{'"$1"'}) ({w},{'"$2"'}) -=[-2] {w} --[-2,-1] -abs[-1] -u {!@{-1,+}} -rm[-1]

#@gmic strlen : string1
#@gmic : Return the length of specified string argument.
strlen :
  ({'"$1"'}) -u {w} -rm[-1]

#@gmic strreplace : string,search,replace
#@gmic : Search and replace substrings in an input string.
strreplace :
  ls=@{"-strlen \"$2\""}
  lr={@{"-strlen \"$3\""}-1}
  -l[] ({'"$1"'}) -s +,{'"$2"'} -s y,-$ls
  -repeat @# -if {@{$>,t}'=='"$2"} -rows[$>] 0,$lr -f[$>] {'"$3"'} -endif -done
  -a y -u @{-1,t} -rm -endl

#@gmic struncase : string
#@gmic : Return a lower-case version of the specified string.
struncase :
  ({'"$*"'}) -+[-1] 'if(i>=65&&i<=90,32,0)' -u @{-1,t} -rm[-1]

#@gmic strver
#@gmic : Return the current version number of the G'MIC interpreter, as a string.
strver :
  ({'@.'}) -r[-1] 7 -f[-1] 'if(x%2,{'.'},i)' -u @{-1,t} -rm[-1]

#@gmic tic
#@gmic : Initialize tic-toc timer.
#@gmic : Use it in conjunction with '-toc'.
tic :
  -e "Initialize timer."
  -v - __tic=@| -v +

#@gmic toc
#@gmic : Display elapsed time of the tic-toc timer since the last call to '-tic'.
#@gmic : Use it in conjunction with '-tic'.
toc :
  -e "Elapsed time : "{@|-$__tic}" s".

#@gmic variance_noise
#@gmic : Return the estimated noise variance of the last selected image.
variance_noise :
  --laplacian[-1] -u {@{-mad[-1]}/sqrt(if(d==1,20,42))} -rm[-1]

#-----------------------------
#
#@gmic :: Others
#
#-----------------------------

#@gmic gpt : _scorefile,_number_of_sessions>=0
#@gmic : Generate score board for the GPT championship (GREYC Poker Tour).
#@gmic : $ -gpt ,
gpt : -skip "${1=http://www.greyc.ensicaen.fr/~dtschump/gpt.raw}" -skip ${2=0},${3=0}
  -e[^-1] "Generate score board for GPT-like championship (GREYC Poker Tour), from file '$1'."
  -v -

  # Load score file and generate score field.
  #------------------------------------------
  -rm -i raw:$1,uchar -s[-1] -,10 -transpose                           # Split score file into lines.
  -repeat @# -if {i=={'#'}} -rm[-1] -else -mv[-1] 0 -endif -done       # Remove comment lines.
  -repeat @# -l[$>]
    -s -,{'\ '}
    -if @#
      -if {@#!=4} -error[0--4] "Invalid score file (line "{$>+1}" defines "@#" items instead of 4)." -endif
      player$>_name=@{0,t}
      player$>_url=@{1,t}
      player$>_file=@{2,t}
      (@{3,t}) -rm[0-3]
    -endif
  -endl -done
  -+ 1 -a y,1 -- 1
  -if {$2>0} -z[-1] {max(0,w-$2)},100%          # Keep only last Nth sessions.
  -elif {$2<0} -z[-1] {w-1-((w-1)%-$2)},100%    # Keep only sessions of the last Nth-session tournament.
  -endif

  # Remove non-players in 'alternate' score boards.
  #------------------------------------------------
  -if $2 -s y -repeat @# -if {@{$<,M}<0}
    i=$< -repeat {@#-$i}
      player{$i+$>}_name=${player{$i+$>+1}_name}
      player{$i+$>}_url=${player{$i+$>+1}_url}
      player{$i+$>}_file=${player{$i+$>+1}_file}
    -done
    -rm[$<] -endif -done -a y
  -endif
  -nm[-1] scores

  # Set global variables.
  #-----------------------
  row_height={if($2,24,48)}

  # Compute session winners and losers
  # (must be done before rounding scores to integers!).
  #----------------------------------------------------
  --l[scores] -s y -max -endl --==[scores,-1] -rm[-2]
  -nm[-1] winners
  --l[scores] -replace[-1] -1,1e8 -s y -min -endl --==[scores,-1] -rm[-2]
  -nm[-1] losers
  --l[winners] -s y -+ -endl
  -nm[-1] nb_winners
  --l[losers] -s y -+ -endl
  -nm[-1] nb_losers

  # Compute players ranks for each session.
  # (must be done before rounding scores to integers!).
  #----------------------------------------
  --l[scores] -s x -r 2,100%,1,1,0 -f 'if(x,y,i)' -sort -,y
  -r 3,100%,1,1,0,0,1,0 -f 'if(x,i,y+1)'
  -repeat {h} -f 'if(!x,if(i(1,y)==i(1,y-1),i(0,y-1),i),i)' -done            # Manage ax-aequo ranks.
  -mirror x -sort +,y -z 1,2 -f 'if(i(0,y)==-1,-1,i)'
  -z 1,1 -a x -endl
  -nm[-1] ranks

  # Round scores to nearest integer.
  #---------------------------------
  -round[scores]

  # Compute number of players per session.
  #---------------------------------------
  --l[scores] -s x -discard -1 -f h -rows 0 -a x -endl
  -nm[-1] nb_players

  # Compute min and max scores per session.
  #----------------------------------------
  --l[scores] -s y -max -endl
  -nm[-1] max_scores
  --l[scores] -replace[-1] -1,1e8 -s y -min -endl
  -nm[-1] min_scores

  # Compute number of games per player.
  #-------------------------------------
  --l[scores] -ge 0 -s x -+ -endl
  -nm[-1] nb_games

  # Compute index of first games.
  #-------------------------------
  --l[scores] -neq -1 -s y -* 'w-x' -f xM -a y -z 0,0 -endl
  -nm[-1] first_game

  # Compute absences malus.
  #-------------------------
  --lt[scores] 0
  --l[-1] -s x -+ -endl --[-1] [first_game] # nb_absences since first played game.
  -l[-2] -f 'if(i,i,-x)' -s y -label 0 -repeat @# n={@{$>,M}} -if $n -histogram[$>] $n,1,$n -else -f[$>] 0 -endif -done
  -r 1,1,1,1,2 -a y -- 1 -max 0 -round -endl -*[-2,-1] -round[-1]
  -nm[-1] abs_malus

  # Compute player scores and corresponding ranks.
  #------------------------------------------------
  --l[scores] -f 'if(i==-1,0,i-100)' -s x -+ -endl --[-1] [abs_malus]
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,'y+1' -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -nm[-1] rank
  --shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] score
  sum_score=@{score,+}

  # Compute player best scores and corresponding ranks.
  #----------------------------------------------------
  --l[scores] -s x -max -- 100 -endl
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,'y+1' -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] best_score

  # Compute previous player scores and corresponding ranks.
  #--------------------------------------------------------
  --l[scores] -columns 0,{w-2} -f 'if(i==-1,0,i-100)' -s x -+ -endl --[-1] [abs_malus]
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,'y+1' -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] previous_score

  # Compute player chips.
  #----------------------
  --l[scores] -f 'if(i==-1,0,i-100)' -s x -+ -endl
  -nm[-1] chips
  sum_chips=@{chips,+}
  -v +
  -e "Sum of chips : "$sum_chips
  -e "Sum of scores : "$sum_score
  -v -

  # Compute player ranking trends.
  #-------------------------------
  ---[previous_score,score] -columns[-1] 1
  -nm[-1] trend

  # Compute player highest chips count.
  #------------------------------------
  --l[scores] -s y -discard -1 -unroll x -- 100 -cumul -f iM -a y -z 0,0 -endl
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,'y+1' -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] highest_chips

  # Compute player lowest chips count.
  #------------------------------------
  --l[scores] -s y -discard -1 -unroll x -- 100 -cumul -f im -a y -z 0,0 -endl
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,'y+1' -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] lowest_chips

  # Compute player performances and corresponding ranks.
  #-----------------------------------------------------
  ---[scores] [min_scores] [max_scores] --[-1] [min_scores] -/[-2,-1] -*[-1] 100
  -l[-1] -f 'if(i<0,-1,i)' -s y -discard -1 -f 'if(ia<0,0,ia)' -rows 0 -a y -round 1 -endl
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,y+1 -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] performance

  # Compute player average scores and corresponding ranks.
  #--------------------------------------------------------
  --l[scores] -s y -discard -1 -- 100 -r 1,1,1,1,2 -a y -endl
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,y+1 -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] average

  # Compute player coffee balances and corresponding ranks.
  #--------------------------------------------------------
  --!=[scores] -1                            # Coffee won.
  --*[losers,nb_players] -/[-1] [nb_losers]  # Coffee paid.
  --[-2,-1] -l[-1] -s x -+ -endl -round[-1] -*[-1] 0.4
  --f[-1] y -a[-2,-1] x -sort[-1] -,y
  1,100%,1,1,y+1 -a[-2,-1] x -mirror[-1] x
  -repeat {h} -f[-1] 'if(!x,if(i(2,y)==i(2,y-1),i(0,y-1),i),i)' -done        # Manage ax-aequo ranks.
  -shift[-1] -1,0,0,0,2 -sort[-1] +,y -columns[-1] 1,100%
  -nm[-1] coffee_balance

  # Compute arrow sprites for trends.
  #----------------------------------
  -cone3d 1.5,2 -r3d[-1] 0,1,0,90 -box3d 4,1,0 -+3d[-1] 0,-0.5 -+3d[-2,-1] -r3d[-1] 0,1,0,180
  -c3d[-1] -*3d[-1] 17 -col3d[-1] 1
  128,128 -object3d[-1] [-2],50%,50%,0,1,2 -nm[-1] arrow_eq_mask
  --*[-1] 200 --*[-2] 200 --*[-3] 200 -a[-3--1] c -nm[-1] arrow_eq
  -r3d[-3] 0,0,1,35
  128,128 -object3d[-1] [-4],50%,50%,0,1,2 -nm[-1] arrow_up_mask
  --*[-1] 64 --*[-2] 255 --*[-3] 64 -a[-3--1] c -nm[-1] arrow_up
  -r3d[-5] 0,0,1,-70
  128,128 -object3d[-1] [-6],50%,50%,0,1,2 -nm[-1] arrow_down_mask
  --*[-1] 255 --*[-2] 64 --*[-3] 32 -a[-3--1] c -nm[-1] arrow_down
  -dilate[arrow_eq_mask,arrow_up_mask,arrow_down_mask] 3
  -rm[-7]

  # Render score board.
  #--------------------
  board=@#

  # Row of labels.
  i=@#
  -_gpt_field "Rank",48,$row_height,16,1,6
  -_gpt_field " ",$row_height,$row_height,16,1,6
  -_gpt_field "Name",150,$row_height,16,1,6
  -_gpt_field "Score",80,$row_height,16,1,6
  -_gpt_field "Chips\n[malus]",80,$row_height,24,1,6
  -_gpt_field "Played",48,$row_height,12,1,6
  -_gpt_field "Won/\nLost",48,$row_height,24,1,6
  -if $2 -_gpt_field "Trd",$row_height,$row_height,12,1,6
  -else -_gpt_field "Trend",$row_height,$row_height,12,1,6
  -endif
  -if $2 -_gpt_field "Stats",{2*$row_height},$row_height,12,1,6
  -else -_gpt_field "Statistics",{4*$row_height+2},$row_height,12,1,6
  -endif
  -_gpt_field "Last\n(rank)",64,$row_height,24,1,6
  -_gpt_field "Best\n(rank)",64,$row_height,24,1,6
  -_gpt_field "Highest\nchips (rank)",64,$row_height,24,1,6
  -_gpt_field "Lowest\nchips (rank)",64,$row_height,24,1,6
  -_gpt_field "Performance\n   (rank)",64,$row_height,24,1,6
  -_gpt_field "Average\n[std] (rank)",100,$row_height,24,1,6
  -_gpt_field "Coffee balance\n     (rank)",80,$row_height,24,1,6
  -a[$i--1] x

  # Retrieve maximum ranks for every field.
  max_players=@{nb_players,M}
  --z[rank] 0,0 max_rank={iM} -rm[-1]
  --z[performance] 1,1 max_performance_rank={iM-1} -rm[-1]
  --z[best_score] 1,1 max_best_score_rank={iM-1} -rm[-1]
  --z[average] 1,1 max_average_rank={iM-1} -rm[-1]
  --z[coffee_balance] 1,1 max_coffee_balance_rank={iM} -rm[-1]

  # Loop on each player row.
  -repeat @{rank,h}
    p=@{rank,(1,$>)}
    n=@{nb_games,(0,$p)}
    c={if(@{nb_games,(0,$p)}==0,0,v=@{score,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_rank-1,4,if(v==$max_rank,5,0))))}
    i=@#

    # Rank.
    t_rank=@{score,(1,$p)}
    -_gpt_field $t_rank,48,$row_height,16,1,$c

    # Avatar.
    -if @{-path_tmp}/${player${p}_file} @{-path_tmp}/${player${p}_file}
    -else ${player${p}_url}${player${p}_file} -o[-1] @{-path_tmp}/${player${p}_file}
    -endif
    -to_rgb[-1] --[-1] 255 -rr2d[-1] {$row_height-2},{$row_height-2},2,2 -+[-1] 255 -frame[-1] 1,1,0

    # Name.
    t_name=@{-_gpt_rm_underscore\ ${player${p}_name}}

    0 -t[-1] $t_name,0,0,32,1,255,255,255
    -r[-1] 100%,100%,1,4
    -sh[-1] 0,2 -*[-1] '(2-c)*0.9*y/h' -rm[-1]
    -drop_shadow[-1] 1,1,1
    -_gpt_field " ",225,{1.5*$row_height},20,1,$c -mv[-1] -2
    -compose_alpha[-2,-1]
    -r2dy[-1] $row_height
    -z[-1] 1,1,{w-2},{h-2} -frame[-1] 1,1,0

    # Score.
    t_score=@{score,(0,$p)}
    -if {$t_score>0} t_score=+$t_score -endif
    -_gpt_field $t_score,80,$row_height,20,$n,$c

    # Chips [malus]
    t_chips=@{chips,(0,$p)}
    t_malus={-@{abs_malus,(0,$p)}}
    -if {$t_chips>0} t_chips=+$t_chips -endif
    -_gpt_field $t_chips\ [$t_malus],80,$row_height,16,$n,$c

    # Played
    t_nb_games=@{nb_games,(0,$p)}
    -_gpt_field $t_nb_games,48,$row_height,16,$n,$c

    # Won/lost.
    --rows[winners] $p
    t_won=@{-1,+}
    --rows[losers] $p
    t_lost=@{-1,+}
    -rm[-2,-1]
    -_gpt_field $t_won/$t_lost,48,$row_height,16,$n,$c

    # Trend.
    -if {!$n} {$row_height-2},{$row_height-2},1,3,255 -frame[-1] 1,1,0
    -else
      t_trend={-@{trend,(0,$p)}}
      -_gpt_field " ",128,128,16,$n,$c
      -if {$t_trend>0} t_trend=+$t_trend -j[-1] [arrow_up],0,0,0,0,1,[arrow_up_mask]
      -elif {$t_trend<0} -j[-1] [arrow_down],0,0,0,0,1,[arrow_down_mask]
      -else -j[-1] [arrow_eq],0,0,0,0,1,[arrow_eq_mask]
      -endif
      -r2dy[-1] $row_height

      -if $2
        -z[-1] 1,1,{w-2},{h-2} -frame[-1] 1,1,0
      -else
        -if {$t_trend>0} -_gpt_field "\n\n    "$t_trend,$row_height,$row_height,48,$n,0
        -elif {$t_trend<0} -_gpt_field "\n\n"$t_trend"     ",$row_height,$row_height,48,$n,0
        -else -_gpt_field " ",$row_height,$row_height,48,$n,0
        -endif
        -/[-1] 255 -*[-2,-1]
      -endif

    -endif

    # Statistics.
    -if {!$n} {if($2,2*$row_height,4*$row_height+2)},{$row_height},1,3,255
    -else
      {3*$row_height},{1.5*$row_height},1,3,255

      # Histogram of session ranks.
      --rows[ranks] $p,$p -histogram[-1] $max_players,1,$max_players
      -graph[-2] [-1],3,0,0,0,0.2,0,64,255
      -rm[-1]

      # Plot of results.
      --rows[scores] $p
      -discard[-1] -1 --[-1] 100 -cumul[-1] sa={ia} sm={im} sM={iM}
      -grid[-2] {max(20,100/max(1,h-1))}%,10,0,0,0.6,0xCCCCCCCC,0
      (0,0) -graph[-3] [-1],1,0,{$sM+10},{$sm-10},1,0 -rm[-1]
      ($sa,$sa) -graph[-3] [-1],1,0,{$sM+10},{$sm-10},1,0x55555555,0,150,0 -rm[-1]
      -graph[-2] [-1],2,0,{$sM+10},{$sm-10},1,255,32,48 -rm[-1]
      -r2dy[-1] {$row_height}

      # Pie-chart of sessions ranks.
      -if {!$2}
        1,$row_height,1,3,0        # Separator
        --rows[ranks] $p -histogram[-1] $max_players,1,$max_players -y[-1] y
        ip=@#
        (1,10,255,242,153)
        (2,10,222,222,222)
        (3,10,232,209,196)
        ({$max_players-1},10,255,204,204)
        ($max_players,10,255,153,153)
        -if {$max_players==1} -rm[-4--1]
        -elif {$max_players==2} -rm[-3--1]
        -elif {$max_players==3} -rm[-2--1]
        -elif {$max_players==4} -rm[-2]
        -elif {$max_players>5} -a[-3,-2] y -r[-2] 100%,{$max_players-3},1,1,3 -round[-2]
        -endif
        -a[$ip--1] y
        -j[-1] [-2],1,0 -rm[-2]

        256,256,1,3,255 -piechart[-1] 57,0,0,0,@-2,"abs.",{@{scores,w}-@{nb_games,(0,$p)}},255,255,255 -frame[-1] 10,10,255
        1,$row_height,1,3,0
        256,256,1,3,255 -piechart[-1] 57,0,0,0,@-4 -frame[-1] 10,10,255
        -rm[-4] -r2dy[-3,-1] $row_height
        -a[-5--1] x
      -endif

    -endif
    -z[-1] 1,1,{w-2},{h-2} -frame[-1] 1,1,0

    # Last score.
    t_last_score=@{scores,(100%,$p)}
    -if {$t_last_score==-1} t_last=abs.
    -else
      t_last_score={$t_last_score-100}
      -if {$t_last_score>0} t_last_score=+$t_last_score -endif
      t_last_rank=@{ranks,(100%,$p)}
      t_last=$t_last_score\ ($t_last_rank)
    -endif
    c={v=@{ranks,(100%,$p)};if(v>=1&&v<=3,v,if(v==@{nb_players,-1}-1,4,if(v==@{nb_players,-1},5,0)))}
    -_gpt_field $t_last,64,$row_height,16,$n,$c

    # Best score.
    t_best_score={v=@{best_score,(0,$p)};if(v==-1,-1,v)}
    t_best_rank=@{best_score,(1,$p)}
    -if {$t_best_score>0} t_best_score=+$t_best_score
    -elif {$t_best_score==-1} t_best_score=abs.
    -endif
    c={v=@{best_score,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_best_score_rank-1,4,if(v==$max_best_score_rank,5,0)))}
    -_gpt_field $t_best_score\ ($t_best_rank),64,$row_height,16,$n,$c

    # Highest chips.
    t_highest_chips={v=@{highest_chips,(0,$p)};if(v==-1,-1,v)}
    t_highest_rank=@{highest_chips,(1,$p)}
    -if {$t_highest_chips>0} t_highest_chips=+$t_highest_chips
    -elif {$t_highest_chips==-1} t_highest_chips=abs.
    -endif
    c={v=@{highest_chips,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_best_score_rank-1,4,if(v==$max_best_score_rank,5,0)))}
    -_gpt_field $t_highest_chips\ ($t_highest_rank),64,$row_height,16,$n,$c

    # Lowest chips.
    t_lowest_chips={v=@{lowest_chips,(0,$p)};if(v==-1,-1,v)}
    t_lowest_rank=@{lowest_chips,(1,$p)}
    -if {$t_lowest_chips>0} t_lowest_chips=+$t_lowest_chips
    -elif {$t_lowest_chips==-1} t_lowest_chips=abs.
    -endif
    c={v=@{lowest_chips,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_performance_rank,4,if(v==$max_performance_rank+1,5,0)))}
    -_gpt_field $t_lowest_chips\ ($t_lowest_rank),64,$row_height,16,$n,$c

    # Performance.
    t_performance=@{performance,(0,$p)}
    t_performance_rank=@{performance,(1,$p)}
    c={v=@{performance,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_performance_rank-1,4,if(v==$max_performance_rank,5,0)))}
    -_gpt_field $t_performance%\ ($t_performance_rank),64,$row_height,16,$n,$c

    # Average [std].
    --rows[scores] $p -discard[-1] -1
    t_average={if(i==-1,0,round(ia-100))}
    -if {$t_average>0} t_average=+$t_average -endif
    t_average_std={if(i==-1,0,round(sqrt(iv)))}
    -rm[-1]
    t_average_rank=@{average,(1,$p)}
    c={v=@{average,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_average_rank-1,4,if(v==$max_average_rank,5,0)))}
    -_gpt_field $t_average\ [$t_average_std]\ ($t_average_rank),100,$row_height,16,$n,$c

    # Coffee balance.
    t_coffee_balance={_@{coffee_balance,(0,$p)}}
    -if {$t_coffee_balance>0} t_coffee_balance=+$t_coffee_balance -endif
    t_coffee_rank=@{coffee_balance,(1,$p)}
    c={v=@{coffee_balance,(1,$p)};if(v>=1&&v<=3,v,if(v==$max_coffee_balance_rank-1,4,if(v==$max_coffee_balance_rank,5,0)))}
    -_gpt_field $t_coffee_balance\$\ ($t_coffee_rank),80,$row_height,16,$n,$c

    # Append all fields into a single row.
    -if {!$n} -f[$i,{$i+2}--1] "i*(0.7+0.3*(((x+y)%8)!=0))" -endif  # Add hatches for absent player.
    -a[$i--1] x

  -done

  # Title.
  avg_nb_players={round(@{nb_players,a},0.5)}
  -if {$2==0} t_title="** GREYC Poker Tour ** Session \#"@{scores,w}"   (avg. \#player = "$avg_nb_players")"
  -elif {$2>0} t_title="** GREYC Poker Tour ** Last "@{scores,w}" sessions  (avg. \#player = "$avg_nb_players")"
  -else t_title="** GREYC Poker Tour ** Session \#"@{scores,w}"/"{-$2}" (avg. \#player = "$avg_nb_players")"
  -endif
  0 -t[-1] $t_title,0,0,57,1,255 -r[-1] 100%,100%,1,4 -drop_shadow[-1] 5,5,2
  -r2dy[-1] 24 -r[-1] {@{$board,w}-2},{1.5*$row_height-2},1,4,0,0,0.5,{if($2,0.9,0.6)}
  -i[-2] 1,3,1,3,32,0,64,32,64,128,64,200,256 -r[-2] [-1],[-1],1,3,3 -compose_rgba[-2,-1]
  -if {$2>0} -shift[-1] 0,0,0,1,2 -elif {$2<0} -mirror[-1] c -endif
  -frame[-1] 1,1,0
  -mv[-1] $board

  # Session winner(s).
  -if {!$2}
    --columns[scores] 100% --f[-1] y -a[-2,-1] x -sort[-1] -,y
    -f[-1] 'if(i(0,y)==i(0,0),i,-1)' -autocrop[-1] -1 -nm[-1] session_winners # Keep only winners.
    nb_session_winners={h}
    t_session_winners=""
    -repeat $nb_session_winners
      i=@{session_winners,(1,$>)}
      t_session_winners=${player${i}_name}"__"${t_session_winners}
      @{-path_tmp}/${player{@{session_winners,(1,$>)}}_file} --[-1] 255 -rr2d[-1] 56,56,2,2 -+[-1] 255 -frame[-1] 1,1,0
    -done
    t_session_winners=@{-_gpt_rm_underscore\ $t_session_winners}
    0 -t[-1] "Session winner"@{-if\ {$nb_session_winners==1}\ -u\ \"\"\ -else\ -u\ s\ -endif}" : "$t_session_winners,0,0,57,1,255
    -r[-1] 100%,100%,1,4 -drop_shadow[-1] 5,5,2
    -r2dy[-1] 24 -r[-1] {@{$board,w}-2},{1.5*$row_height-2},1,4,0,0,0.1,0.5
    -i[-2] 1,2,1,3,0,128,128,255,64,128 -r[-2] [-1],[-1],1,3,3 -compose_rgba[-2,-1]
    -if {$2>0} -shift[-1] 0,0,0,1,2 -elif {$2<0} -mirror[-1] c -endif
    -repeat $nb_session_winners -j[-1] [{-2-$<}],{w-64-$>*64},7 -done
    -frame[-1] 1,1,0
    -mv[-1] {$board+1}
    -rm[-{$nb_session_winners+1}--1]
  -endif

  # Session loser(s).
  -if {!$2}
    --columns[losers] 100% --f[-1] y -a[-2,-1] x -sort[-1] -,y
    -f[-1] 'if(i(0,y),i,-1)' -autocrop[-1] -1 -nm[-1] session_losers # Keep only losers.
    nb_session_losers={h}
    t_session_losers=""
    -repeat $nb_session_losers
      i=@{session_losers,(1,$>)}
      t_session_losers=${player${i}_name}"__"${t_session_losers}
      @{-path_tmp}/${player{@{session_losers,(1,$>)}}_file} --[-1] 255 -rr2d[-1] 56,56,2,2 -+[-1] 255 -frame[-1] 1,1,0
    -done
    t_session_losers=@{-_gpt_rm_underscore\ $t_session_losers}
    0 -t[-1] "Session loser"@{-if\ {$nb_session_losers==1}\ -u\ \"\"\ -else\ -u\ s\ -endif}" : "$t_session_losers,0,0,57,1,255
    -r[-1] 100%,100%,1,4 -drop_shadow[-1] 5,5,2
    -r2dy[-1] 24 -r[-1] {@{$board,w}-2},{1.5*$row_height-2},1,4,0,0,0.1,0.5
    -i[-2] 1,2,1,3,128,255,0,128,64,128 -r[-2] [-1],[-1],1,3,3 -compose_rgba[-2,-1]
    -if {$2>0} -shift[-1] 0,0,0,1,2 -elif {$2<0} -mirror[-1] c -endif
    -repeat $nb_session_losers -j[-1] [{-2-$<}],{w-64-$>*64},7 -done
    -frame[-1] 1,1,0
    -rm[-{$nb_session_losers+2}--2]
  -endif

  # Append rows together.
  -a[$board--1] y

  # Add final shadow.
  100%,100%,1,1,255 -a[-2,-1] c -drop_shadow[-1] 6,6,4 -i[-2] {w},{h},1,3,255 -compose_alpha[-2,-1]

  # Quit properly.
  -k[$board] -v +

_gpt_rm_underscore :
  ({'"$1"'}) -replace[-1] {'_'},{'\ '} -u @{-1,t} -rm[-1]

# $1 : Text - $2 : Width - $3 : Height - $4 : Font size - $5 : Text - $6 : Color code.
_gpt_field :
  -if {!$5} {$2-2},{$3-2},1,3,255 -frame[-1] 1,1,0 -return -endif
  0 -t[-1] "$1",0,0,57,1,1 -*[-1] -1 -+[-1] 1
  -r2dy[-1] $4 --[-1] 1 -r[-1] {$2-2},{$3-2},1,1,0,0,0.5,0.5 -+[-1] 1
  -frame[-1] 1,1,0
  [-1]x2
  -if {$6==1} -*[-3] 255 -*[-2] 242 -*[-1] 153
  -elif {$6==2} -*[-3] 222 -*[-2] 222 -*[-1] 222
  -elif {$6==3} -*[-3] 232 -*[-2] 209 -*[-1] 196
  -elif {$6==4} -*[-3] 255 -*[-2] 204 -*[-1] 204
  -elif {$6==5} -*[-3] 255 -*[-2] 153 -*[-1] 153
  -elif {$6==6} -*[-3] 240 -*[-2] 240 -*[-1] 240
  -else -*[-3--1] 255
  -endif
  -a[-3--1] c

#-------------------------------------
#
# Define menu entries for
# the G'MIC plug-in for GIMP
#
#-------------------------------------

# Update function called each time the G'MIC plug-in for GIMP has refreshed his filters
# (by function 'update_filter(const bool)' in gmic_gimp.cpp.
# Parameter $1 can be equal to { 0=no_network_update | 1=network_update }.
# This function is always called with $1==0 when the plug-in is launched.
gimp_update_filters : -skip $*
  gmic_path=$GMIC_GIMP_PATH
  -if {!narg($gmic_path)} gmic_path=@{-path_user}/ -endif
  -if {!@{-is_windows}} gmic_path=${gmic_path}. -endif
  gmic_path=${gmic_path}gmic_sources.cimgz
  ({'http://mpkaro.helmholtz-muenchen.de/~karo/karos.gmic'},0)
  ({'http://www.greyc.ensicaen.fr/~dtschump/ronounours.gmic'},0)
  ({'http://www.tkfilter.bplaced.net/tomkeil.gmic'},0)
  ({'http://s406833247.websitehome.co.uk/gmic/photocomix.gmic'},0)
  ({'http://gentlemanbeggar.bplaced.net/gentlemanbeggar_gmic.gmic'},0)
  ({'http://www.saunalahti.fi/naggobot/naggobot.gmic'},0)
  ({'http://www.iain.bplaced.net/iain_fergusson.gmic'},0)
  ({'http://s406833247.websitehome.co.uk/gmic/garagecoder.gmic'},0)
  ({'http://www.aljacom.com/~gmic/samj.gmic'},0)
  -o $gmic_path
  -rm

# 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 -t[-1] "Before",1,-1,13,1,1
_after :
  26,11 -t[-1] "After",1,-1,13,1,1

gimp_split_preview :
  -repeat @#
    -if {$2==0} -e[] "$1" -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.
    -j[-5] [-4],1,1,0,0,0.8,[-2] -j[-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 :
  -_gimp_no_preview "No preview\navailable","$*"

_gimp_no_preview :
  -if {@#>0} -k[0] -else 256,256,1,1,128 -endif
  118,50 -t[-1] "$1",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 "$*"


# 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 : url = link{"Download G'MIC plug-in for Windows (64 bits)","http://downloads.sourceforge.net/gmic/gmic_gimp_win64.zip"}
# #@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://tschumperle.users.greyc.fr/")
#@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 : -skip "${1=Plug-in for GIMP}"
  -if @# -k[0] -endif
  -to_rgb 0 -t[-1] "G'MIC",0,0,57,1,1 -label[-1] 0
  6,1,1,3 -rand[-1] 150,255 -point[-1] 0 -map[-2] [-1] -rm[-1]
  -expand_xy[-1] 10,0 -b[-1] 2 -r[-1] 200%,200%,1,3,6 -sqr[-1] -c[-1] 0,60% -n[-1] 0,255
  -warp_perspective[-1] 0.5,0,1,50,50,0 -shift[-1] 0,-10
  100%,100% -noise[-1] 0.8,2 -*[-1] 180 --blur_linear[-1] 20,0,45,0 -*[-1] 20 -max[-3--1]
  -sh[-1] 2,2 (0;128) -r[-1] [-2],3 -+[-2,-1] -min[-1] 255 -rm[-1]
  -text_outline[-1] "$1",32%,75%,13,3,1,255 -frame[-1] 1,1,128 -mv[-1] 0
  -if {@#>1} -*[^0] 0.45 -repeat {@#-1} -j[-1] [0],{(w-@{0,w})/2},{(h-@{0,h})/2} -mv[-1] 1 -done -rm[0] -endif

gimp_logo_old :
  -if @# ratio={w/h} -else ratio=1 -endif
  -rm 118,44,1,1 -t "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 -b 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 -sl3d 0.2 -ss3d 1.3 -r3d[-1] 1,0,0,30 -f3d 120 -*3d[-1] 1.5
  230,120,1,3 -object3d[-1] [-2],50%,30%,0,1,4 -rm[-2] -t "$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,"$ratio},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_alpha

gimp_logo_en :
  -gimp_logo "Plug-in for GIMP\n     "[@{-strver}]

#@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 in your <i>Home</i> folder (or <i>Applications Data/</i> on Windows, without the first dot).
#@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 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/")

#---------------------
# 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://tschumperle.users.greyc.fr/")
#@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\n     "[@{-strver}]

#@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 : dans votre dossier <i>Home</i> (ou <i>Applications Data/</i> sous Windows, sans le premier point).
#@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")

#----------------------
# 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://tschumperle.users.greyc.fr/")
#@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\n     "[@{-strver}]

#@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")

#----------------------
# 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 : - <b>2010/12/17</b> : version <i>1.4.7</i>.\n
#@gimp : - <b>2011/03/15</b> : version <i>1.4.8.3</i>.\n
#@gimp : - <b>2011/04/01</b> : version <i>1.4.9</i>.\n
#@gimp : - <b>2011/06/08</b> : version <i>1.4.9.5</i>.\n
#@gimp : - <b>2011/07/07</b> : version <i>1.5.0.0</i>.\n
#@gimp : - <b>2012/03/01</b> : version <i>1.5.1.0</i>.\n
#@gimp : - <span foreground="purple"><b>2012/10/15</b> : version <i>1.5.2.0</i> (Current stable).</span>\n
#@gimp : "}
#@gimp : link = link("View latest changelog","http://www.flickr.com/groups/gmic/discuss/72157631333001102/")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/15</i>.</small>")

#@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>Sylvie Alexandre</i> <small>(packaging, testing &amp; filters)</small>
#@gimp : <b> -</b> <i>Partha Bagchi</i> <small>(packaging)</small>
#@gimp : <b> -</b> <i>S&#233;bastien Bougleux</i> <small>(debugging)</small>
#@gimp : <b> -</b> <i>J&#233;rome Boulanger</i> <small>(testing &amp; code)</small>
#@gimp : <b> -</b> <i>Claude Bulin</i> <small>(packaging)</small>
#@gimp : <b> -</b> <i>Aur&#233;lien Ceyden</i> <small>(packaging)</small>
#@gimp : <b> -</b> <i>Fran&#231;ois Collard</i> <small>(testing)</small>
#@gimp : <b> -</b> <i>Iain Fergusson</i> <small>(filters)</small>
#@gimp : <b> -</b> <i>Roberto Ferramosca</i> <small>(packaging)</small>
#@gimp : <b> -</b> <i>J&#233;rome Ferrari</i> <small>(testing, code &amp; tutorials)</small>
#@gimp : <b> -</b> <i>S&#233;bastien Fourey</i> <small>(ZArt code &amp; G'MIC online)</small>
#@gimp : <b> -</b> <i>Gentlemanbeggar</i> <small>(filters)</small>
#@gimp : <b> -</b> <i>Claes Holmerson</i> <small>(tutorials)</small>
#@gimp : <b> -</b> <i>Arto Huotari</i> <small>(filters)</small>
#@gimp : <b> -</b> <i>Tom Keil</i> <small>(testing, filters &amp; tutorials)</small>
#@gimp : <b> -</b> <i>Andy Kelday</i> <small>(testing &amp; filters)</small>
#@gimp : <b> -</b> <i>Angelo Lama</i> <small>(testing &amp; EKD integration)</small>
#@gimp : <b> -</b> <i>St&#233;phane de la Linuxerie</i> <small>(design)</small>
#@gimp : <b> -</b> <i>Mark</i> <small>(translation)</small>
#@gimp : <b> -</b> <i>PhotoComiX</i> <small>(testing, translation &amp; filters)</small>
#@gimp : <b> -</b> <i>MareroQ</i> <small>(translation)</small>
#@gimp : <b> -</b> <i>Mahvin</i> <small>(testing &amp; design)</small>
#@gimp : <b> -</b> <i>Mauro Quercia</i> <small>(translation)</small>
#@gimp : <b> -</b> <i>Guilherme Razgriz</i> <small>(translation)</small>
#@gimp : <b> -</b> <i>Karsten Rodenacker</i> <small>(packaging &amp; code)</small>
#@gimp : <b> -</b> <i>Dani Sard&#224;</i> <small>(translation)</small>
#@gimp : <b> -</b> <i>Yuri Shemanin</i> <small>(debugging)</small>
#@gimp : <b> -</b> <i>Stepanekos</i> <small>(translation)</small>
#@gimp : <b> -</b> <i>Bernd Zeimetz</i> <small>(packaging)</small>
#@gimp : <b> -</b>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/03/30</i>.</small>")

#@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>5</b> donations from <b>G'MIC</b> mega-enthusiasts so far.
#@gimp :               You could be the 6th donator :)"}
#@gimp : note = note{" <b>-</b> A big hug goes to these folks (recently received first) :"}
#@gimp : link = link(0,"[1] Matt Jones","https://plus.google.com/116658221461047313647")
#@gimp : link = link(0,"[2] Eddy Vervest","http://www.flickr.com/people/twekkel/")
#@gimp : link = link(0,"[3] Steven Shupe","http://www.flickr.com/photos/ssshupe/")
#@gimp : link = link(0,"[4] Flavio Casadei Della Chiesa","http://www.flaviocdc.net/wiki/")
#@gimp : link = link(0,"[5] 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>15</b> postcards from <b>G'MIC</b> enthusiasts so far.
#@gimp :               You could be the 16th sender :)"}
#@gimp : note = note{" <b>-</b> A big hug goes to these folks (recently received first) :"}
#@gimp : link = link(0,"[1] Mauro Mitrino - Mantova/Italy","http://cimg.sourceforge.net/img/postcard39.jpg")
#@gimp : link = link(0,"[2] Werner Meier - Mettlach/Germany","http://cimg.sourceforge.net/img/postcard37.jpg")
#@gimp : link = link(0,"[3] Arto Huotari - Helsinki/Finland","http://cimg.sourceforge.net/img/postcard36.jpg")
#@gimp : link = link(0,"[4] Benoit Gauzere - California/USA","http://cimg.sourceforge.net/img/postcard33.jpg")
#@gimp : link = link(0,"[5] Arkadi Gelfond - Foster City - California/USA","http://cimg.sourceforge.net/img/postcard30.jpg")
#@gimp : link = link(0,"[6] Corinne Masimann - Neuchatel/Switzerland","http://cimg.sourceforge.net/img/postcard29.jpg")
#@gimp : link = link(0,"[7] Mahvin - Portland/USA","http://cimg.sourceforge.net/img/postcard27.jpg")
#@gimp : link = link(0,"[8] Vincent Roullier - Caen/France","http://cimg.sourceforge.net/img/postcard26.jpg")
#@gimp : link = link(0,"[9] M???? - Munich/Germany","http://cimg.sourceforge.net/img/postcard24.jpg")
#@gimp : link = link(0,"[10] F. Albior - Jaca/Spain","http://cimg.sourceforge.net/img/postcard23.jpg")
#@gimp : link = link(0,"[11] PhotoComIX - Frascati/Italy","http://cimg.sourceforge.net/img/postcard22.jpg")
#@gimp : link = link(0,"[12] Guy Poizat - Cabestany/France","http://cimg.sourceforge.net/img/postcard21.jpg")
#@gimp : link = link(0,"[13] Institut for Biomathematik und Biometrie - Neuherberg/Germany","http://cimg.sourceforge.net/img/postcard20.jpg")
#@gimp : link = link(0,"[14] Jaime - Barcelona/Spain","http://cimg.sourceforge.net/img/postcard14.jpg")
#@gimp : link = link(0,"[15] 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/03/30</i>.</small>")
gimp_friends :
  -if @# ratio={w/h} -else ratio=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 "{w},{h},$ratio},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_alpha
  135,67,1,1,0 -t[-1] "Greetings to\n  all G'MIC\n  friends!",2,-2,24,1,1
  --dilate[-1] 3 -*[-2] 255 -to_rgb[-2] -j[-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 Gmicky / Roddy : gimp_gmicky, gimp_gmicky_preview
#@gimp : Mascot image = choice("Gmicky","Gmicky & Wilber","Roddy")
#@gimp : sep = separator()
#@gimp : note = note{"<b><i>Gmicky</i></b> is the name of the <b>G'MIC</b> mascot. He is a small and cute tiger who knows how to do magic.
#@gimp : <b><i>Gmicky</i></b> is a tiger, i.e. fast, agile and elegant, just as the <b>G'MIC</b> code is :).
#@gimp : As many magicians, <b><i>Gmicky</i></b> knows lot of gimmicks (<b>G'MIC</b>), and he is a direct and friendly competitor of
#@gimp : the ImageMagick's wizard, or the GraphicMagick's frog."}
#@gimp : note = note{"<b><i>Roddy</i></b> is another mascot designed specifically for the <i>Artistic / Rodilius</i> filter of <b>G'MIC</b>."}
#@gimp : note = note{"<b><i>Gmicky</i></b> and <b><i>Roddy</i></b> have been designed by "}
#@gimp : link = link("Mahvelous Mahvin","http://www.mahvin.com/")
#@gimp : sep = separator(), note = note("<small>Authors : <i>David Tschumperl&#233;, Mahvin</i>.      Latest update: <i>2011/05/27</i>.</small>")
gimp_gmicky :
  -rm
  -if {$1==0} -gmicky
  -elif {$1==1} -gmicky_wilber
  -else -roddy
  -endif

gimp_gmicky_preview :
  w={w} h={h} -rm
  -if {$1==0}
    filename=@{-path_tmp}/gmicky_small.cimgz
    url=http://gmic.sourceforge.net/img/gmicky_small.cimgz
  -elif {$1==1}
    filename=@{-path_tmp}/gmicky_wilber_small.cimgz
    url=http://gmic.sourceforge.net/img/gmicky_wilber_small.cimgz
  -else
    filename=@{-path_tmp}/roddy_small.cimgz
    url=http://gmic.sourceforge.net/img/roddy_small.cimgz
  -endif
  -if $filename $filename -else -i $url -o $filename -endif
  -r2dy $h,3 -- 255 -r $w,$h,1,3,0,0,0.5,0.5 -+ 255


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


#@gimp Array [regular] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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_array_preview :
  -gimp_array $1,$2,$3,$4,$5,0

#@gimp Array [faded] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Array [mirrored] : 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","2XY-axes")
#@gimp : Initialization = choice("Original","Mirror X","Mirror Y","Rotate 90 deg.","Rotate 180 deg.","Rotate 270 deg.")
#@gimp : Expand size = _bool(false)
#@gimp : Crop = int(0,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_array_mirror : -skip ${7=0}
  -if {$5==1} -mirror x
  -elif {$5==2} -mirror y
  -elif {$5==3} -rotate 90
  -elif {$5==4} -rotate 180
  -elif {$5==5} -rotate 270
  -endif
  -if $7
    -if {$4==0} -columns 0,{100-$7}%
    -elif {$4==1} -rows 0,{100-$7}%
    -elif {$4==2} -z 0,0,{100-$7}%,{100-$7}%
    -elif {$4==3} -z {$7/2}%,{$7/2}%,{100-$7/2}%,{100-$7/2}%
    -endif
  -endif
  -shift -$2%,-$3%,0,0,2
  -array_mirror $1,$4,$6

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

#@gimp Array [random] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@gimp Array [random colors] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Droste : gimp_droste, gimp_droste_preview(1)
#@gimp : note = note("<span color=\"red\">Upper-left coordinates :</span>")
#@gimp : X0 = float(20,0,100)
#@gimp : Y0 = float(20,0,100)
#@gimp : sep = separator(), note = note("<span color=\"magenta\">Upper-right coordinates :</span>")
#@gimp : X1 = float(80,0,100)
#@gimp : Y1 = float(20,0,100)
#@gimp : sep = separator(), note = note("<span color=\"blue\">Lower-right coordinates :</span>")
#@gimp : X2 = float(80,0,100)
#@gimp : Y2 = float(80,0,100)
#@gimp : sep = separator(), note = note("<span color=\"cyan\">Lower-left coordinates :</span>")
#@gimp : X3 = float(20,0,100)
#@gimp : Y3 = float(80,0,100)
#@gimp : sep = separator()
#@gimp : Iterations = int(1,1,10)
#@gimp : X-shift = float(0,-100,100)
#@gimp : Y-shift = float(0,-100,100)
#@gimp : Angle = float(0,0,360)
#@gimp : Zoom = float(1,0.1,5)
#@gimp : Mirror = choice("None","X-axis","Y-axis","XY-axes")
#@gimp : Borders = choice(1,"Black","Nearest","Repeat")
#@gimp : Drawing mode = choice{"Replace","Replace (sharpest)","Behind","Below"}
#@gimp : View outlines only = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/06/11</i>.</small>")
gimp_droste :
  -repeat @#
    -if {$16==1} 100%,100%,1,1,'x' 100%,100%,1,1,'y' -a[-2,-1] c -endif
    -repeat $9
      x0={round($1*w/100)} y0={round($2*h/100)} x1={round($3*w/100)} y1={round($4*h/100)}
      x2={round($5*w/100)} y2={round($6*h/100)} x3={round($7*w/100)} y3={round($8*h/100)}
      100%,100%,1,2,-32767 -polygon[-1] 4,$x0,$y0,$x1,$y1,$x2,$y2,$x3,$y3,1,-65535
      -sh[-1] 0,0 -f[-1] 'if(i==-65535,x03=$x0+(y-$y0)/($y3-$y0)*($x3-$x0);x12=$x1+(y-$y1)/($y2-$y1)*($x2-$x1);(x-x03)/(x12-x03)*(w-1),i)' -rm[-1]
      -sh[-1] 1,1 -f[-1] 'if(i==-65535,y01=$y0+(x-$x0)/($x1-$x0)*($y1-$y0);y32=$y3+(x-$x3)/($x2-$x3)*($y2-$y3);(y-y01)/(y32-y01)*(h-1),i)' -rm[-1]
      xshift={w*$10/100} yshift={h*$11/100} alpha={-$12*pi/180} ca={cos($alpha)/$13} sa={sin($alpha)/$13} w2={w/2} h2={h/2}
      -f[-1] 'if(i==-32767,i,X=i(x,y,0,0)-$w2;Y=i(x,y,0,1)-$h2;if(c==0,$w2-$xshift+X*$ca-Y*$sa,$h2-$yshift+X*$sa+Y*$ca))'
      -if {$14==0} -sh[-1] 0,0 -f[-1] 'if(i==-32767,x,i)' -rm[-1] -sh[-1] 1,1 -f[-1] 'if(i==-32767,y,i)' -rm[-1]
      -elif {$14==1} -sh[-1] 0,0 -f[-1] 'if(i==-32767,x,w-1-i)' -rm[-1] -sh[-1] 1,1 -f[-1] 'if(i==-32767,y,i)' -rm[-1]
      -elif {$14==2} -sh[-1] 0,0 -f[-1] 'if(i==-32767,x,i)' -rm[-1] -sh[-1] 1,1 -f[-1] 'if(i==-32767,y,h-1-i)' -rm[-1]
      -else -sh[-1] 0,0 -f[-1] 'if(i==-32767,x,w-1-i)' -rm[-1] -sh[-1] 1,1 -f[-1] 'if(i==-32767,y,h-1-i)' -rm[-1]
      -endif
      -if {$16<2} -warp[-2] [-1],0,{$16==0},$15 -rm[-1]
      -else
        --warp[-2] [-1],0,1,$15 -rm[-2]
        -if {$16==3} -rv[-2,-1] -endif
        -compose_alpha[-2,-1]
      -endif
    -done
    -if {$16==1} -warp[-2] [-1],0,1,1 -rm[-1] -endif
    -mv[-1] 0 -done

gimp_droste_preview :
  -if {!$17} -gimp_droste $* -else -polygon 4,$1%,$2%,$3%,$4%,$5%,$6%,$7%,$8%,0.3,0,0,0,255 -endif
  -polygon 4,$1%,$2%,$3%,$4%,$5%,$6%,$7%,$8%,1,0xFFFFFFFF,0,0,0,255
  -ellipse $1%,$2%,3,3,0,1,255,0,0,255 -ellipse $1%,$2%,3,3,0,1,0xFFFFFFFF,0,0,0,255
  -ellipse $3%,$4%,3,3,0,1,255,0,255,255 -ellipse $3%,$4%,3,3,0,1,0xFFFFFFFF,0,0,0,255
  -ellipse $5%,$6%,3,3,0,1,0,0,255,255 -ellipse $5%,$6%,3,3,0,1,0xFFFFFFFF,0,0,0,255
  -ellipse $7%,$8%,3,3,0,1,0,255,255,255 -ellipse $7%,$8%,3,3,0,1,0xFFFFFFFF,0,0,0,255

#@gimp Frame [cube] : frame_cube, frame_cube(1)
#@gimp : Depth = float(1,0,100)
#@gimp : X-center = float(0,-2,2)
#@gimp : Y-center = float(0,-2,2)
#@gimp : Left side orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gimp : Right side orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gimp : Upper side orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gimp : Lower sider orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;, Angelo Lama</i>.      Latest update: <i>2012/01/29</i>.</small>")

#@gimp Frame [fuzzy] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Frame [painting] : gimp_frame_painting, gimp_frame_painting_preview(1)
#@gimp : Size = float(10,0,100)
#@gimp : Contrast = float(0.4,0,1)
#@gimp : Smoothness = float(6,0,30)
#@gimp : Color = color(225,200,120)
#@gimp : sep = separator()
#@gimp : Vignette size = float(2,0,50)
#@gimp : Vignette contrast = float(400,0,1000)
#@gimp : sep = separator()
#@gimp : Defects contrast = float(50,0,512)
#@gimp : Defects density = float(10,0,100)
#@gimp : Defects size = float(1,0,10)
#@gimp : Defects smoothness = float(0.5,0,20)
#@gimp : sep = separator()
#@gimp : Serial number = int(123456,0,1000000)
#@gimp : Frame as a new layer = _bool(false)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/06/07</i>.</small>")
gimp_frame_painting :
  -if $14
    -repeat @# 100%,100%,1,4 -frame_painting[-1] $1%,$2,$3%,${4-6},$7%,${8-13}
    -rv[-2,-1] -to_a[-1] -r[-1] [-2],[-2],1,4,0,0,0.5,0.5 -mv[-2,-1] 0 -done
  -else -frame_painting $1%,$2,$3%,${4-6},$7%,${8-13}
  -endif

gimp_frame_painting_preview :
  -frame_painting $1%,$2,$3%,${4-6},$7%,${8-13}

#@gimp Frame [pattern] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_frame_pattern :
  -repeat $3 -frame_pattern $1,$2,$4 -done

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

#@gimp Frame [regular] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_frame :
 -to_rgba -repeat @#
   -z[-1] $1%,$3%,$2%,$4%
   -frame[-1] $11,$11,${12-15}
   -frame[-1] $5%,$6%,${7-10}
 -mv[-1] 0 -done

#@gimp Frame [round] : 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,0,0,255)
#@gimp : Blur frame = float(0,0,100)
#@gimp : Blur shade = float(0.1,0,1)
#@gimp : Blur amplitude = float(3,0,10)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_frame_round :
  -frame_round ${1-8}
  -if $9 -frame_blur $1,{min(99,$1+$9)},$3,$10,$11% -endif

#@gimp Grid : gimp_imagegrid, gimp_imagegrid(0)
#@gimp : X-size = int(10,2,100)
#@gimp : Y-size = int(10,2,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_imagegrid :
  -imagegrid $1,$2

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Taquin : taquin, taquin(1)
#@gimp : X-tiles = int(7,1,20)
#@gimp : Y-tiles = int(7,1,20)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@gimp Tileable rotation : gimp_rotate_tileable, gimp_rotate_tileable(1)
#@gimp : Angle = float(45,0,360)
#@gimp : Maximum size factor = int(8,0,20)
#@gimp : Array mode = choice(0,"None","X-axis","Y-axis","XY-axes","2XY-axes")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/05/26</i>.</small>")
gimp_rotate_tileable :
  -if $3 -array_mirror 1,{$3-1},1 -endif
  -rotate_tileable $1,{if($3==0,$2,$2/2)}
  -repeat @#
    -if {@{$>,w}==1" && "@{$>,h}==1} -rm -_gimp_no_preview "  Invalid\nimage size" -return -endif
  -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 : X-shadow = float(3,-20,20)
#@gimp : Y-shadow = float(3,-20,20)
#@gimp : Smoothness = float(1.8,0,5)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_rotate_tiles :
  -to_rgba -rotate_tiles $3,$1,$2 -drop_shadow $4%,$5%,$6%

#@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 : 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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
_gimp_normalize_tiles :
  -repeat @# -l[-1] -split_tiles $1,$2 -n $3,$4 -append_tiles $1,$2 -endl -mv[-1] 0 -done

gimp_normalize_tiles :
  -apply_channels "-_gimp_normalize_tiles ${1-4}",$-1

#@gimp Tiled random shifts : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_parameterize_tiles :
  -if $3
    -quadratize_tiles $1,$2
  -else
    -linearize_tiles $1,$2
  -endif
  -c 0,255

#@gimp Tiled isolation : gimp_isolate_tiles, gimp_isolate_tiles(0)
#@gimp : X-size = float(10,0,100)
#@gimp : Y-size = float(10,0,100)
#@gimp : X-border = float(5,0,100)
#@gimp : Y-border = float(5,0,100)
#@gimp : Keep tiles square = bool(1)
#@gimp : Keep borders square = bool(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/04/13</i>.</small>")
gimp_isolate_tiles :
  -repeat @# -l[$>] -to_rgba
    -if $5 sx={round(min(w,h)*max($1,$2)/100)} sy=$sx -else sx={round(w*$1/100)} sy={round(h*$2/100)} -endif
    -if $6 bx={max($3,$4)} by=$bx -else bx=$3 by=$4 -endif
    -s x,-$sx
    -repeat @# -l[$>] -s y,-$sy -r 100%,{100+$by}%,1,100%,0,0,0.5,0.5 -a y -endl -done
    -r {100+$bx}%,100%,1,100%,0,0,0.5,0.5 -a x
  -endl -done

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_tunnel :
  -tunnel $1,$2%,$3,$4,$5


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

#@gimp Cartoon : cartoon, gimp_cartoon_preview(0)
#@gimp : Smoothness = float(3,0,10)
#@gimp : Sharpening = float(80,0,400)
#@gimp : Edge threshold = float(20,1,30)
#@gimp : Edge thickness = float(0.25,0,1)
#@gimp : Color strength = float(1.5,0,3)
#@gimp : Color quantization = int(8,2,256)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_cartoon_preview :
  -gimp_split_preview "-cartoon ${1--2}",$-1

#@gimp Circlism : gimp_circlism, gimp_no_preview
#@gimp : Min radius = int(2,1,100)
#@gimp : Max radius = int(10,1,100)
#@gimp : Smoothness = float(1,0,10)
#@gimp : Edge linearity = float(0.4,0.01,5)
#@gimp : Location linearity = float(3,0.01,5)
#@gimp : Shape = choice(2,"Diamonds","Squares","Circles")
#@gimp : Transparency = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/10/16</i>.</small>")
gimp_circlism :
  -to_rgb -circlism ${1-6}
  -if $7 -to_rgba -replace_color 0,0,0,0,0,255,0,0,0,0 -endif

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_ellipsionism :
  -ellipsionism ${^0}

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

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_kaleidoscope :
  -shift $3%,$4%,0,0,2 -kaleidoscope $1,$2,$5,$6,$7

#@gimp Kuwahara : gimp_kuwahara, gimp_kuwahara_preview(0)
#@gimp : Iterations = int(2,1,20)
#@gimp : Radius = int(5,1,30)
#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/05/31</i>.</small>")
gimp_kuwahara :
  -apply_channels "-repeat $1 -kuwahara $2 -done",$3,0

gimp_kuwahara_preview :
  -gimp_split_preview "-gimp_kuwahara ${1--2}",$-1

#@gimp Lylejk's painting : gimp_lylejk_painting, gimp_lylejk_painting_preview(0)
#@gimp : Iterations = int(2,1,20)
#@gimp : Radius = int(4,1,30)
#@gimp : Canvas = float(10,0,100)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Lyle Kroll, David Tschumperl&#233;</i>.      Latest update: <i>2011/09/21</i>.</small>")
#@gimp : note = link("Filter Explained here","http://www.gimpchat.com/viewtopic.php?f=10&t=2624")
gimp_lylejk_painting :
  -repeat @#
    --gimp_lylejk_stencil[-1] 10,10.49,0.75,0
    -smooth[-1] 300,0.26,1,0,7 -sharpen[-1] $3
    [-1] -rv[-3--1]
    -gimp_compose_lighten[-2,-1] 0.5
    -gimp_compose_grainmerge[-2,-1] 1
    -gimp_kuwahara[-1] $1,$2,0
    -texturize_canvas[-1] $3,4
  -mv[-1] 0 -done

gimp_lylejk_painting_preview :
  -gimp_split_preview "-gimp_lylejk_painting ${1--2}",$-1

#@gimp Old photograph : old_photo, old_photo(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@gimp Painting : gimp_painting, gimp_painting_preview(0)
#@gimp : Abstraction = int(5,1,10)
#@gimp : Details scale = float(2.5,0,5)
#@gimp : Color = float(1.5,0,4)
#@gimp : Smoothness = float(50,0,1000)
#@gimp : Sharpen shades = bool(1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Lyle Kroll, Angelo Lama, David Tschumperl&#233;</i>.\nLatest update: <i>2011/02/28</i>.</small>")
gimp_painting : -skip ${4=0},${5=0}
  -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
    -if $5 -gimp_segment_watershed[-1] 10,1,0 -endif
    -smooth[-1] $4,0,1,1,1
    -rv -a c
  -endl -done

gimp_painting_preview :
  -gimp_split_preview "-gimp_painting ${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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_pen_drawing :
  -drawing $1

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

#@gimp Polaroid : gimp_polaroid, gimp_polaroid(1)
#@gimp : Frame size = int(10,0,400)
#@gimp : Bottom size = int(20,0,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,-180,180)
#@gimp : Vignette strength = float(50,0,255)
#@gimp : Vignette min radius = float(70,0,100)
#@gimp : Vignette max radius = float(95,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_polaroid :
  -vignette ${7-9} -polaroid $1,$2 -drop_shadow $3%,$4%,$5% -rotate $6,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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_color_ellipses :
  -color_ellipses $1,$2,$3

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_reflect :
  -repeat @#
    -to_rgba[-1] --rows[-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 Rodilius : gimp_rodilius, gimp_rodilius_preview(1)
#@gimp : Amplitude = float(10,0,30)
#@gimp : Thickness = float(10,0,100)
#@gimp : Sharpness = float(300,0,1000)
#@gimp : Orientations = int(5,2,36)
#@gimp : Offset = float(30,0,180)
#@gimp : Color mode = choice(1,"Darker","Lighter")
#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Rod/GimpChat, David Tschumperl&#233;</i>.      Latest update: <i>2011/09/28</i>.</small>")
gimp_rodilius :
  -apply_channels "-rodilius ${1-6}",$7,0

gimp_rodilius_preview :
  -gimp_split_preview "-rodilius ${1--2}",$-1

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_rotoidoscope :
  -rotoidoscope {$1*100}%,{$2*100}%,$3,$4%,$5

#@gimp Soft glow : gimp_glow, gimp_glow_preview(0)
#@gimp : Amplitude = float(6,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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_tetris :
  -tetris $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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_draw_whirl_preview :
  -gimp_split_preview "-draw_whirl ${1--2}",$-1


#@gimp _<b>Black &amp; white</b>
#--------------------------------

#@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()
#@gimp : Pseudo-gray dithering = int(0,0,20)
#@gimp : Use maximum tones = bool(false)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_blackandwhite :
  -repeat @#
    -l[-1] -split_opacity -rv -to_rgb[-1] -s[-1] c          # Isolate opacity
    -*[-3] $1 -b[-3] $2%                                    # Red contrast + smoothness
    -*[-2] $3 -b[-2] $4%                                    # Green contrast + smoothness
    -*[-1] $5 -b[-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 -b[-3] $16% -n[-3] -$12,$12          # Scaled grain on shadows.
    -noise[-2] 100,$17 -b[-2] $16% -n[-2] -$13,$13          # Scaled grain on midtones.
    -noise[-1] 100,$17 -b[-1] $16% -n[-1] -$14,$14          # Scaled grain on highlights.

    --tones[-4] 3 -b[-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.
  -if $18 -normalize_local $18,$19,$20,2%,1,0,255 -endif
  -if $22 -n 0,255 -endif
  -if $21 -to_pseudogray {1+($21-1)} -endif

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

#@gimp Charcoal : gimp_charcoal, gimp_charcoal_preview(0)
#@gimp : Granularity = int(65,0,800)
#@gimp : Lowlights crossover point = int(70,0,255)
#@gimp : Highlights crossover point = int(170,0,255)
#@gimp : Boost contrast = bool(0)
#@gimp : Resize image for optimum effect = bool(1)
#@gimp : Add chalk highlights = bool(0)
#@gimp : Minimal highlights = int(50,0,255)
#@gimp : Maximal highlights = int(70,0,255)
#@gimp : Background color = color(255,255,255)
#@gimp : Foreground color = color(0,0,0)
#@gimp : Invert background/foreground = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/03/17</i>.</small>")
#@gimp : note = note("<small>Inspired from the Charcoal script by <i>micomicon</i> :</small>")
#@gimp : link = link("http://registry.gimp.org/node/25078")
gimp_charcoal :
  -repeat @# -l[$>] -split_opacity -l[0]
    -compose_channels max
    w={w} h={h}
    -if $5 -resize[-1] 150%,150%,1,1,6 -endif
    -if $4 -equalize[-1] 256 -n[-1] 0,255 -endif
    -sharpen {$1*3} -cut 0,255
    -if $6 --t2 $7,$8 -endif  # Add highlights layer if required.
    -t2[0] $2,$3
    -if {!$15} -eq[0] 0 -endif
    -or
    --*[0] $10 --*[0] $11 -*[0] $9
    -append[-3--1] c -replace_color 0,0,0,0,0,$12,$13,$14
    -r $w,$h,1,100%,2
  -endl -a c -endl -done

gimp_charcoal_preview :
  -gimp_split_preview "-gimp_charcoal ${1--2}",$-1

#@gimp 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_ditheredbw :
  -apply_gamma $1 -- 128 -* $2 -+ 128 -+ $3 -b $4 -c 0,255 -ditheredbw

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

#@gimp Hard sketch : gimp_hardsketchbw, gimp_hardsketchbw_preview(0)
#@gimp : Amplitude = float(300,0,4000)
#@gimp : Density = float(50,0,100)
#@gimp : Smoothness = float(1,0,10)
#@gimp : Opacity = float(0.1,0,1)
#@gimp : Edge = float(20,0,100)
#@gimp : Fast approximation = bool(0)
#@gimp : Negative = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_hardsketchbw :
  -b $3 -hardsketchbw $1,$2,$4,$5,$6
  -if $7 -negative -endif

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

#@gimp Hough sketch : gimp_houghsketchbw, gimp_houghsketchbw_preview(0)
#@gimp : Smoothness = float(1.25,0,10)
#@gimp : Density = float(10,0,70)
#@gimp : Radius = int(5,0,30)
#@gimp : Threshold = float(80,0,100)
#@gimp : Opacity = float(0.1,0,1)
#@gimp : Negative = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/05/18</i>.</small>")
gimp_houghsketchbw :
  -b $1 -n 0,255 -houghsketchbw ${2-5}
  -if $6 -negative -endif

gimp_houghsketchbw_preview :
  -gimp_split_preview "-gimp_houghsketchbw ${1--2}",$-1

#@gimp Ink wash : gimp_ink_wash, gimp_ink_wash(0)
#@gimp : note = note("Ink wash controls")
#@gimp : Size = float(0.14,0,4)
#@gimp : Amplitude = float(23,0,200)
#@gimp : sep = separator()
#@gimp : note = note("Check if you wish visual control on this step")
#@gimp : SKIP all other steps = bool(false)
#@gimp : note = note ("UNcheck to reactivate the other controls")
#@gimp : sep = separator()
#@gimp : Smoother Sharpness = float(0.5,0,2)
#@gimp : Smoother Edge Protection = float(0.54,0,1)
#@gimp : Smoother Softness = float(2.25,0,10)
#@gimp : sep = separator()
#@gimp : Stretch Contrast = choice("None","Automatic","Automatic & Contrast Mask","Manual Controls")
#@gimp : note = note ("To activate the sliders below chose 'Manual Controls'")
#@gimp :sep = separator ()
#@gimp : LN Amplititude = float(2,0,60)
#@gimp : LN Size = float(6,0,64)
#@gimp : LN Neightborhood-Smoothness = float(5,0,40)
#@gimp : LN Average-Smoothness = float(20,0,40)
#@gimp : sep = separator(), note = note("<small>Author : <i>PhotoComiX</i>.      Latest update: <i>2011/4/5</i>.</small>")
#@gimp : note = link(0,"Forum thread about the filter discussion","http://gimpchat.com/viewtopic.php?f=10&t=914")
gimp_ink_wash :
  -repeat @# -l[$>] -split_opacity -l[0]
    -gimp_pencilbw[-1] $1,$2,0,0,0
    -if {$3==1} -continue
    -elif {$3==0} -gimp_anisotropic_smoothing[-1] 60,$4,$5,$6,1.1,0.8,30,2,0,1,1,0,1,0
    -endif
    -if {$7==1} -normalize_local[-1] 2,6,5,24,1,0,255
	-elif {$7==2}  -normalize_local[-1] 2,6,5,24,1,0,255 -gimp_contrast_swm 2,0,0.512
    -elif {$7==3} -gimp_normalize_local[-1] $8,$9,$10,$11,1,3,0
    -endif
  -endl -a c -endl -done

#@gimp 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Stamp : gimp_stamp, gimp_stamp_preview(0)
#@gimp : Auto-threshold = bool(1)
#@gimp : Threshold = int(50,0,100)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Sharpening = float(0,0,30)
#@gimp : Grain = float(0,0,100)
#@gimp : Invert colors = bool(false)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Antaron, Mahvin, David Tschumperl&#233;</i>.             Latest update: 2012/10/08.</small>")
gimp_stamp :
  -repeat @# -l[$>] -split_opacity
    -norm -noise $5
    -if $1 -otsu 256 -else -ge $2% -endif
    -b $3,0 -sharpen $4 -n 0,255
    -apply_curve 1,0,0,101,33,170,229,255,255
    -if $6 -negative -endif
  -a c -endl -done

gimp_stamp_preview :
  -gimp_split_preview "-gimp_stamp ${1--2}",$-1

#@gimp 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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>Colors</b>
#---------------------

#@gimp Abstraction : gimp_color_abstraction, gimp_color_abstraction_preview(0)
#@gimp : Smoothness = float(1,0,10)
#@gimp : Levels = int(10,2,255)
#@gimp : Contrast = float(0.2,0.01,1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/10/19</i>.</small>")
gimp_color_abstraction :
  -to_rgb -b $1 -quantize $2 -area 0 -^ $3 -n 0,255

gimp_color_abstraction_preview :
  -gimp_split_preview "-gimp_color_abstraction ${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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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}
    s=@{$>,s}
    -luminance[$>] -apply_gamma[$>] $1 --[$>] 128 -*[$>] $2 -+[$>] {$3+128} -c[$>] 0,255
    -map[$>] [-1] -to_colormode[$>] $s
  -done
  -rm[-1]

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

#@gimp Boost / Fade : gimp_boost_fade, gimp_boost_fade_preview
#@gimp : Amplitude = float(5,0,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/10/12</i>.</small>")
gimp_boost_fade :
  -i[0] 640,480,1,3 -rand[0] 0,1 -b[0] {10-$1} -n[0] 0,255 -transfer_colors -rm[0]

gimp_boost_fade_preview :
  -gimp_split_preview "-gimp_boost_fade ${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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
_gimp_channel_processing :
  -apply_gamma[-1] $1
  -if {$2!=1} --[-1] 128 -*[-1] $2 -+[-1] 128 -endif
  -+[-1] $3
  -b[-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 Color balance : gimp_balance_gamma, gimp_balance_gamma_preview
#@gimp : Neutral color = color(128,128,128)
#@gimp : Stretch colors = bool(1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/07/01</i>.</small>")
gimp_balance_gamma :
  -balance_gamma ${1-3}
  -if $4 -repeat @# -l[$>] -s c -n 0,255 -a c -endl -done -endif

gimp_balance_gamma_preview :
  -gimp_split_preview "-gimp_balance_gamma ${1--2}",$-1

#@gimp Colormap : gimp_colormap,gimp_colormap_preview
#@gimp : Colormap = choice[1,"Adaptive","Custom","Standard (256)","HSV (256)","Lines (256)","Hot (256)","Cool (256)","Jet (256)","Flag (256)","Cube (256)"]
#@gimp : Dithering = float(1,0,1)
#@gimp : sep = separator(), note = note("<small><i>For adaptive and custom colormaps only :</i></small>")
#@gimp : Number of tones = int(32,2,256)
#@gimp : sep = separator(), note = note("<small><i>For custom colormaps only :</i></small>")
#@gimp : Number of colors = int(8,2,8)
#@gimp : 1st color = color(0,0,0)
#@gimp : 2nd color = color(255,255,255)
#@gimp : 3rd color = color(255,0,0)
#@gimp : 4th color = color(0,255,0)
#@gimp : 5th color = color(0,0,255)
#@gimp : 6th color = color(255,255,0)
#@gimp : 7th color = color(255,0,255)
#@gimp : 8th color = color(0,255,255)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/12/27</i>.</small>")
gimp_colormap :
  -repeat @# -l[$>] -split_opacity -to_rgb[0]
    -if {$1>=2}                # Pre-defined colormap.
      -index[0] {$1-2},$2,1
    -elif {$1==1}              # Custom colormap.
      (${5-28}) -z[-1] 0,{3*$4-1}
      -r[-1] 3,{w/3},1,1,-1 -permute[-1] yzcx -r[-1] $3,1,1,3,3
      -index[0] [-1],$2,1 -rm[-1]
    -else                      # Adaptive colormap.
      -autoindex[0] $3,$2,{if($3<=32,1,0)}
    -endif
    -a c
  -endl -done

gimp_colormap_preview :
  -gimp_split_preview "-gimp_colormap ${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","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : Display histogram = float(0,0,1)
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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
    100%,100% -axes[-1] 0,255,255,0,13,1,255 --dilate[-1] 3 -r[-2] [-3] -j[-3] [-2],0,0,0,0,1,[-1],255 -rm[-2,-1]
    -grid[-1] 10%,10%,0,0,0.3,0xCCCCCCCC,255
    -line[-1] 0,100%,100%,0,0.3,0xCCCCCCCC,255
    -if $-2
      [-1],[-1] -to_gray[-3] -histogram[-3] 256,0,255 -graph[-1] [-3],3,0,0,0,1,1 -neq[-1] 0 -*[-1] 255 -rm[-3]
      --xor[-2,-1] -j[-3] [-1],0,0,0,0,$16,[-2],255 -rm[-2,-1]
     -else -rm[-2] -endif
     100%,100% -graph[-1] [0],1,0,255,0,1,255 --dilate[-1] 3 -r[-2] [-3] -j[-3] [-2],0,0,0,0,1,[-1],255 -rm[-2,-1]
     -_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
    -t[-1] $3,$x,{$y*h-20},13,1,255
  -endif

#@gimp Curves [RGB]
#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
#@gimp _
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[^-1] @-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[^-1] @-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[^-1] @-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}
    --gimp_split_preview[-1] "-gimp_apply_RGBcurve 0",$-1
    100%,100% -axes[-1] 0,255,255,0,13,1,255 --dilate[-1] 3 -r[-2] [-3] -j[-3] [-2],0,0,0,0,1,[-1],255 -rm[-2,-1]
    -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 Curves [YCbCr]
#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
#@gimp _
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[^-1] @-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[^-1] @-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[^-1] @-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,13,1,255
    100%,100% -axes[-1] 0,255,255,0,13,1,255 --dilate[-1] 3 -r[-2] [-3] -j[-3] [-2],0,0,0,0,1,[-1],255 -rm[-2,-1]
    -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 Curves [Lab]
#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
#@gimp _
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[^-1] @-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[^-1] @-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[^-1] @-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,13,1,255
    100%,100% -axes[-1] 0,255,255,0,13,1,255 --dilate[-1] 3 -r[-2] [-3] -j[-3] [-2],0,0,0,0,1,[-1],255 -rm[-2,-1]
    -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 Decompose channels : gimp_decompose_channels, gimp_decompose_channels_preview
#@gimp : Color basis = choice(7,"RGB","HSV","HSL","HSI","YUV","YCbCr","XYZ","Lab","Lch","CMY","CMYK")
#@gimp : Action = choice("Decompose","Recompose")
#@gimp : Use multiple layers = bool(0)
#@gimp : Include opacity layer = bool(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_decompose_channels :
  -if {!$2} # Decompose
    -if $4 -to_rgba -else -to_rgb -endif
    -repeat @# -l[-1]
      -split_opacity -_gimp_decompose_channels$1[0]
      -s[0] c -if {!$3} -a x -endif
      nb=@#
    -endl -mv[-$nb--1] 0 -done
  -else # Recompose
    -channels 0 nbc={3+($1==10)} nb={$nbc+$4}
    -if $3 -repeat {int(@#/$nb)} -l[0-{$nb-1}]
      -a[0-{$nbc-1}] c -_gimp_recompose_channels$1[0] -a c
    -endl -mv[-1] 0 -done
    -else -repeat @# -l[$>]
      -s x,$nb -a[0-{$nbc-1}] c -_gimp_recompose_channels$1[0] -a c
    -endl -mv[-1] 0 -done -endif
  -endif

gimp_decompose_channels_preview :
  -gimp_decompose_channels ${^0} -append_tiles ,

_gimp_decompose_channels0 :
_gimp_decompose_channels1 : -rgb2hsv8
_gimp_decompose_channels2 : -rgb2hsl8
_gimp_decompose_channels3 : -rgb2hsi8
_gimp_decompose_channels4 : -rgb2yuv8
_gimp_decompose_channels5 : -rgb2ycbcr
_gimp_decompose_channels6 : -rgb2xyz8
_gimp_decompose_channels7 : -rgb2lab8
_gimp_decompose_channels8 : -rgb2lch8
_gimp_decompose_channels9 : -rgb2cmy
_gimp_decompose_channels10 : -rgb2cmyk

_gimp_recompose_channels0 :
_gimp_recompose_channels1 : -hsv82rgb
_gimp_recompose_channels2 : -hsl82rgb
_gimp_recompose_channels3 : -hsi82rgb
_gimp_recompose_channels4 : -yuv82rgb
_gimp_recompose_channels5 : -ycbcr2rgb
_gimp_recompose_channels6 : -xyz82rgb
_gimp_recompose_channels7 : -lab82rgb
_gimp_recompose_channels8 : -lch82rgb
_gimp_recompose_channels9 : -cmy2rgb
_gimp_recompose_channels10 : -cmyk2rgb

#@gimp Discrete color square: gimp_colorsquare, gimp_colorsquare
#@gimp : a = color(0,0,0)
#@gimp : b = color(255,255,255)
#@gimp : c = color(128,255,192)
#@gimp : d = color(80,128,255)
#@gimp : Colorspace = choice("LCH","LAB","YCbCr","RGB")
#@gimp : sep = separator()
#@gimp : Quantization = int(256,2,256)
#@gimp : Disable quantization = bool(0)
#@gimp : Clip high end = bool(0)
#@gimp : Steps = int(5,3,32)
#@gimp : Scale = int(36,1,96)
#@gimp : sep = separator(), note = note("<small>Author : <i>Noun0ion9</i>.      Latest update: <i>2011/05/18</i>.</small>")
gimp_colorsquare:
  -rm
  ($1,$4;$7,$10^$2,$5;$8,$11^$3,$6;$9,$12)
  -to_rgb
  -srgb2rgb
  -if {$13==3}
     -resize $17,$17,1,3,3,0
  -elif {$13==0}
     -rgb2lch -resize $17,$17,1,3,3,0 -lch2rgb
  -elif {$13==1}
     -rgb2lab -resize $17,$17,1,3,3,0 -lab2rgb
  -elif {$13==2}
     -rgb2ycbcr -resize $17,$17,1,3,3,0 -ycbcr2rgb
  -endif
  -rgb2srgb
  -if {$14!=256}
     -if {$15==0}
       -if {$16==1}
         -quantize {$14+1},0
         -cut 0,{$14-1}
         -* {256/$14}
       -else
         -quantize $14,0
         -* {255/($14-1)}
       -endif
     -endif
  -endif
  -resize {$17*$18},{$17*$18},1,3,1,0,0,0,0,0

#@gimp Equalize HSV : gimp_hsv_equalizer, gimp_hsv_equalizer_preview
#@gimp : Preview bands = bool(false)
#@gimp : sep = separator()
#@gimp : Hue band = float(180,0,360)
#@gimp : Band width = float(40,1,360)
#@gimp : Hue shift = float(0,-180,180)
#@gimp : Saturation correction = float(0,-0.99,0.99)
#@gimp : Value correction = float(0,-0.99,0.99)
#@gimp : sep = separator()
#@gimp : Hue band = float(180,0,360)
#@gimp : Band width = float(40,1,360)
#@gimp : Hue shift = float(0,-180,180)
#@gimp : Saturation correction = float(0,-0.99,0.99)
#@gimp : Value correction = float(0,-0.99,0.99)
#@gimp : sep = separator()
#@gimp : Hue band = float(180,0,360)
#@gimp : Band width = float(40,1,360)
#@gimp : Hue shift = float(0,-180,180)
#@gimp : Saturation correction = float(0,-0.99,0.99)
#@gimp : Value correction = float(0,-0.99,0.99)
#@gimp : sep = separator()
#@gimp : note = note("<small>Author : <i>J&#233;rome Ferrari</i>.      Latest update: <i>2011/01/14</i>.</small>")
#@gimp : note = link("Filter explained here","http://www.flickr.com/groups/gmic/discuss/72157625798533482")
gimp_hsv_equalizer :
  -repeat @# -local[@{>,-1}]
  -to_rgb -rgb2hsv -split c
# From now on 0,1,2 are H,S,V
#3 masks:
  --fill[0] if(abs(i-$2)<$3/2|abs(i-$2-360)<$3/2|abs(i-$2+360)<$3/2,1,0)
  --fill[0] if(abs(i-$7)<$8/2|abs(i-$7-360)<$8/2|abs(i-$7+360)<$8/2,1,0)
  --fill[0] if(abs(i-$12)<$13/2|abs(i-$12-360)<$13/2|abs(i-$12+360)<$13/2,1,0)
# From now on 3,4,5 are Masks
  --threshold[1,2] 0.01 -*[-1,-2] [-1]x2 -*[-1,3] -*[-1,4] -*[-1,5]	#0 saturation and value not in mask
# Hue shift:
  --*[3] $4 --*[4] $9 --*[5] $14 -+[-1,-2,-3]
  -+[-1,0] -%[0] 360
# Saturation :
  -if {$5>=0} --*[3] -$5 -else --*[3] {1/(1+$5)-1} -endif -+[-1] 1
  -if {$10>=0} --*[4] -$10 -else --*[4] {1/(1+$10)-1} -endif -+[-1] 1
  -if {$15>=0} --*[5] -$15 -else --*[5] {1/(1+$15)-1} -endif -+[-1] 1
  -*[-1,-2,-3] -^[1,-1]
# Value :
  -if {$6>=0} --*[3] -$6 -else --*[3] {1/(1+$6)-1} -endif -+[-1] 1
  -if {$11>=0} --*[4] -$11 -else --*[4] {1/(1+$11)-1} -endif -+[-1] 1
  -if {$16>=0} --*[5] -$16 -else --*[5] {1/(1+$16)-1} -endif -+[-1] 1
  -*[-1,-2,-3] -^[2,-1]
#reconstruction
  -rm[3,4,5] -append[0,1,2] c -hsv2rgb
  -endlocal -done

gimp_hsv_equalizer_preview :
-local[-1]
  -if {$1==0} -gimp_hsv_equalizer $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16
  -else
    -to_rgb -rgb2hsv -split c
    (0,359) -resize[-1] [-2],{@{0,h}/10},1,1,3 [-1] -fill[-1] 1	#create lower band
    -j[0] [3],0,91% -j[1] [4],0,91% -j[2] [4],0,91% -rm[-1,-2] #paste lower band
    --fill[0] if(abs(i-$2)<$3/2|abs(i-$2-360)<$3/2|abs(i-$2+360)<$3/2,1,0)
    --fill[0] if(abs(i-$7)<$8/2|abs(i-$7-360)<$8/2|abs(i-$7+360)<$8/2,1,0)
    --fill[0] if(abs(i-$12)<$13/2|abs(i-$12-360)<$13/2|abs(i-$12+360)<$13/2,1,0) #masks
    -or[-3--1] -+[-1] 0.33 -/[-1] 1.33	#1 and 0.25
    -*[2,-1] -append c -hsv2rgb
  -endif
-endlocal

#@gimp Gradient [corners] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Gradient [linear] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Gradient [radial] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Lomo : gimp_lomo, gimp_lomo_preview
#@gimp : Vignette size = float(20,0,100)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>J&#233;rome Boulanger, David Tschumperl&#233;</i>.      Latest update: <i>2012/06/06</i>.</small>")
gimp_lomo :
  -repeat @# -l[$>]
    --gaussian {100-$1}%,{100-$1}% -normalize[-1] 0,1 -*
    -s c
    -f[0] '255*atan((i-128)/128)'
    -f[1] '255*tan((i-128)/128)'
    -f[2] '255*atan((i-128)/255)'
    -a c
    -sharpen 1
    -normalize 0,255
  -endl -done

gimp_lomo_preview :
  -gimp_split_preview "-gimp_lomo ${1--2}",$-1

#@gimp Mixer [RGB] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_start_mix :
  -if {$1==1} --tones[-1] 3 -+[-2,-1] -b[-2,-1] $2% -r[-2,-1] [-3] -*[-1] [-3] -mv[-3] @#
  -elif {$1==2} --tones[-1] 3 -+[-3,-1] -b[-2,-1] $2% -r[-2,-1] [-3] -*[-2] [-3] -mv[-3] @#
  -elif {$1==3} --tones[-1] 3 -+[-3,-2] -b[-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 -b[-3] $3%
    -*[-2] $4 -+[-2] $5 -b[-2] $6%
    -*[-1] $7 -+[-1] $8 -b[-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 Mixer [YCbCr] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 -b[-3] $3%
    -*[-2] $4 -+[-2] $5 -b[-2] $6%
    -*[-1] $7 -+[-1] $8 -b[-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 Mixer [HSV] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 -b[-3] $3%
    -*[-2] $4 -+[-2] $5 -b[-2] $6%
    -*[-1] $7 -+[-1] $8 -b[-1] $9%
    -%[-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 Mixer [Lab] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 -b[-3] $3%
    -*[-2] $4 -+[-2] $5 -b[-2] $6%
    -*[-1] $7 -+[-1] $8 -b[-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 Mixer [CMYK] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 -b[-4] $3%
    -*[-3] $4 -+[-3] $5 -b[-3] $6%
    -*[-2] $7 -+[-2] $8 -b[-2] $9%
    -*[-1] $10 -+[-1] $11 -b[-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 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_replace_color :
  -to_rgba -replace_color $1,$2%,${3--1} -c 0,255

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
_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 color=@-1 -rm[-1]
  -repeat @#
    -if {$8==0}                                  # Output selected colors.
      --_gimp_select_color[-1] $1
      -select_color[-1] $2%,$color
      -b[-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%,$color
      -b[-1] $3
      -if $9 -*[-1] -1 -+[-1] 1 -endif
      -*[-1] 255 -r[-1] 100%,100%,1,4
    -endif
  -mv[-1] 0 -done

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Tone mapping [fast] : gimp_map_tones_fast, gimp_map_tones_fast_preview(0)
#@gimp : Radius = float(3,0,20)
#@gimp : Power = float(0.5,0,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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Paul Nasca, David Tschumperl&#233;</i>.      Latest update: <i>2011/06/10</i>.</small>")
gimp_map_tones_fast :
  -apply_channels "-map_tones_fast $1,$2",$3,0

gimp_map_tones_fast_preview :
  -gimp_split_preview "-gimp_map_tones_fast ${^0}",$-1

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 _<b>Contours</b>
#----------------------

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_curvature :
  -b $1 -iee
  -if $4 -abs -endif
  -c $2%,$3%
  -if $5 -negative -endif
  -n 0,255

gimp_curvature_preview :
  -gimp_split_preview "-gimp_curvature ${^0}",$-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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_dog :
  -dog $1%,$2%
  -c $3%,{100-$3}%
  -if $4 -negative -endif
  -n 0,255

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

#@gimp Distance transform : gimp_distance, gimp_distance_preview(0)
#@gimp : Value = int(128,0,255)
#@gimp : Metric = choice(2,"Chebyshev","Manhattan","Euclidean","Squared-Euclidean")
#@gimp : Normalization = choice(2,"Cut","Normalize","Modulo")
#@gimp : Modulo value = int(32,1,255)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/04/07</i>.</small>")
gimp_distance :
  -distance $1,$2
  -if {$3==0} -c 0,255
  -elif {$3==1} -n 0,255
  -else -% $4 -n 0,255
  -endif

gimp_distance_preview :
  -gimp_split_preview "-gimp_distance ${^0}",$-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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_edges :
  -to_rgb -b $1% -edges $2%
  -if $3 -negative -endif
  -n 0,255

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

#@gimp Edges 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_edge_offsets :
  -repeat @#
    os={s}
    -b[-1] $1% -gradient_norm[-1] -ge[-1] $2% -skeleton[-1] 0 -distance[-1] 1 -round[-1] 1 -%[-1] $3 -ge[-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 ${^0}",$-1

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_gradient_norm :
  -b $1 -gradient_norm -^ $2
  -c $3%,$4%
  -if $5 -negative -endif
  -n 0,255

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

#@gimp Gradient RGB : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_gradient2rgb :
  -b $1 -gradient2rgb $4
  -c $2%,$3%
  -if $5 -negative -endif
  -n 0,255

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

#@gimp Isophotes : gimp_isophotes, gimp_isophotes_preview(0)
#@gimp : Levels = int(8,1,256)
#@gimp : Smoothness = float(0,0,5)
#@gimp : Filling = choice(1,"Transparent","Colors")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_isophotes :
  -if $3
    -topographic_map $1,$2
  -else
    -b $2 -isophotes $1
  -endif

gimp_isophotes_preview :
  -gimp_split_preview "-gimp_isophotes ${^0}",$-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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_laplacian :
  -b $1 -laplacian
  -if $4 -abs -endif
  -c $2%,$3%
  -if $5 -negative -endif
  -n 0,255

gimp_laplacian_preview :
  -gimp_split_preview "-gimp_laplacian ${^0}",$-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("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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
_gimp_local_orientation :
  -b $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 ${^0}",$-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","Red","Green","Blue","Alpha")
#@gimp : Scale = bool(true)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_morpho :
  -apply_channels "-__gimp_morpho ${^0}",$5,$6

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

__gimp_morpho :
  -if {$4==1} suf="_oct" -elif {$4==0} suf="" -else suf="_circ" -endif
  -if {$1==0} -erode$suf $2
  -elif {$1==1} -dilate$suf $2
  -elif {$1==2} -erode$suf $2 -dilate$suf $2
  -elif {$1==3} -dilate$suf $2 -erode$suf $2
  -elif {$1==4} -repeat @# --erode$suf $2 --[-2,-1] -mv[-1] 0 -done
  -elif {$1==5} -repeat @# --dilate$suf $2 -rv[-2,-1] --[-2,-1] -mv[-1] 0 -done
  -elif {$1==6} -repeat @# --erode$suf $2 -dilate$suf[-1] $2 --[-2,-1] -mv[-1] 0 -done
  -else -repeat @# --dilate$suf $2 -erode$suf[-1] $2 -rv[-2,-1] --[-2,-1] -mv[-1] 0 -done
  -endif
  -if $3 -repeat @# -l[$>] -split_opacity -negative[0] -a c -endl -done -endif

#@gimp Segmentation : gimp_segment_watershed, gimp_segment_watershed_preview(0)
#@gimp : Edge threshold = float(2,0,15)
#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_segment_watershed :
  -apply_channels "-b $2 -segment_watershed $1",$3,0

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

#@gimp Skeleton : gimp_skeleton, gimp_skeleton_preview(1)
#@gimp : Method = choice("Distance","Thinning")
#@gimp : Smoothness = float(0,0,10)
#@gimp : Curviness = float(0,0,10)
#@gimp : Multiple channels = bool(1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/04/07</i>.</small>")
gimp_skeleton :
  -if {!$4} -norm -endif
  -b $2%
  -if $1 -thinning -else -skeleton $3% -endif
  -* 255

gimp_skeleton_preview :
  -gimp_split_preview "-gimp_skeleton ${^0}",$-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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_thin_edges :
  -b $1% -gradient_norm -ge $2% -thinning
  -if {!$3} -negative -endif
  -n 0,255

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


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


#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_euclidean2polar :
  -if $5 -polar2euclidean $1,$2,$3,$4 -else -euclidean2polar $1,$2,$3,$4 -endif

#@gimp Fish-eye : fisheye, fisheye(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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_flower :
  -flower $1,$2,$3%,$4,$5,$6,$7

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_warp_perspective :
  -shift $6%,$7%,0,0,2 -warp_perspective $1,$2,$3,$4,$5,$8

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Random : deform, deform(0)
#@gimp : Amplitude = float(10,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@gimp Ripple : ripple, ripple(0)
#@gimp : Amplitude = float(10,0,100)
#@gimp : Size = float(20,1,300)
#@gimp : Shape = choice(2,"Bloc","Triangle","Sine","Sine+","Random")
#@gimp : Angle = float(0,0,360)
#@gimp : Offset = float(0,0,500)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/08/23</i>.</small>")

#@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 : Border smoothness = float(0,0,200)
#@gimp : Border width = float(20,0,100)
#@gimp : Orientation = choice("0 deg.","90 deg.","180 deg.","270 deg.")
#@gimp : Background = choice("Transparent","Mean color")
#@gimp : Fading = float(0,0,100)
#@gimp : Fading shape = float(0.5,0,3)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/11/07</i>.</small>")
gimp_map_sphere :
  -rotate {$8*90}
  -if $6
    -repeat @#
      -shift[-1] 50%,0,0,0,2 --columns[-1] {(1-$7/100)*w/2},{(1+$7/100)*w/2}
      100% -gaussian[-1] {0.1*w},{h},0 100% 100% -a[-3--1] c -r[-1] [-2],[-2],1,3
      -smooth[-2] [-1],$6,5,0 -rm[-1]
      -j[-2] [-1],{(1-$7/100)*@{-2,w}/2} -rm[-1] -shift[-1] -50%,0,0,0,2
    -mv[-1] 0 -done
  -endif
  -shift $5%,0,0,0,2 -to_rgba
  -if $9
    -repeat @#
      --rows[$>] 0 -r[-1] 1,1,1,4,2 RGBA$>=@-1
      -r[-1] [$>],[$>],1,4 --[$>,-1]
    -done
  -endif
  -map_sphere $1,$2,$3,$4,$10,$11
  -if $9
    -repeat @#
      (${RGBA$>}) -y[-1] c -r[-1] [$>],[$>],1,4 -+[$>,-1]
    -done
  -endif

gimp_map_sphere_preview :
  -gimp_map_sphere {w},{h},${3--1}

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@gimp Water : water, water(0)
#@gimp : Amplitude = float(30,0,300)
#@gimp : Smoothness = float(1.5,0,4)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@gimp Wind : gimp_wind, gimp_wind_preview(0)
#@gimp : Amplitude = int(20,0,500)
#@gimp : Angle = float(0,0,360)
#@gimp : Attenuation = float(0.7,0,1)
#@gimp : Threshold = float(20,0,100)
#@gimp : Mode = choice(1,"Darker","Brighter")
#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/07/13</i>.</small>")
gimp_wind :
  -if {!$5} -negative -endif
  -apply_channels "-wind ${1-4}",$-2
  -if {!$5} -negative -endif

gimp_wind_preview :
  -gimp_split_preview "-gimp_wind ${1--2}",$-1

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_zoom :
  -if {$1<1} -to_rgba -endif
  -zoom $1,$2,$3,0,$4


#@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","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_noise :
  -apply_channels "-noise $1,$2",$3,$4

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

#@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 : Sharpness = float(0,0,500)
#@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","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_blur_angular :
  -apply_channels "-blur_angular $1%,$2,$3 -sharpen $4",$5,$6

#@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","Red","Green","Blue","Alpha")
#@gimp : Value range = choice(1,"Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_bandpass :
  -apply_channels "-bandpass $1%,$2%",$3,$4

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

#@gimp Bayer filter : rgb2bayer, rgb2bayer(0)
#@gimp : Starting pattern = choice(0,"Red-Green","Blue-Green","Green-Red","Green-Blue")
#@gimp : Keep colors = bool(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
_gimp_gaussian_blur :
  -b $1,$4
  -if {$2>0} -repeat @# -l[-1] -s y -b $2,$4 -a y -endl -mv[-1] 0 -done -endif
  -if {$3>0} -repeat @# -l[-1] -s x -b $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 : Sharpness = float(0,0,500)
#@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","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_blur_linear :
  -apply_channels "-blur_linear $1,{$2*$1/100},$3,$5 -sharpen $4",$6,$7

gimp_blur_linear_preview :
  -gimp_split_preview "-gimp_blur_linear ${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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_stripes_y :
  -apply_channels "-stripes_y $1",$2,0

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

#@gimp Oldschool 8bits : gimp_8bits, gimp_8bits_preview(0)
#@gimp : Scale = float(25,1,100)
#@gimp : Dithering = float(800,0,10000)
#@gimp : Levels = int(16,2,256)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/11/02</i>.</small>")
gimp_8bits :
  -to_rgb
  -repeat @#
    w={w} h={h}
    -resize[-1] $1%,$1%,1,100%,2
    --luminance[-1] -sharpen[-1] $2 -otsu[-1] 256 -compose_shapeaverage[-2,-1] -quantize[-1] $3
    -resize[-1] $w,$h,1,100%,1
  -mv[-1] 0 -done

gimp_8bits_preview :
  -gimp_split_preview "-gimp_8bits ${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 : Sharpness = float(0,0,500)
#@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","Red","Green","Blue","Alpha")
#@gimp : Value range = choice("Cut","Normalize")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_blur_radial :
  -apply_channels "-blur_radial $1%,$2,$3 -sharpen $4",$5,$6

#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_spread :
  -apply_channels "-spread $1,$2",$3,0

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

#@gimp Visible watermark : 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 : Smoothness = float(0.5,0,5)
#@gimp : Lightness = choice(1,"Darker","Brighter")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_watermark_visible :
  -watermark_visible "$1",$2,$3,$4,$6,$5


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

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_deinterlace :
  -deinterlace 0 -skip ${^0}

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

#@gimp Inpaint region : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_inpaint :
  -if {@#==1} -return -endif
  -if $1 -inpaint_flow $2,$3,$4,$5%,$6% -c 0,255 -else -inpaint[^0] [0] -endif
  -to_rgba[0] -f[0] 0

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

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@gimp Remove hot pixels : 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 : sep = separator(), note = note("<small>Author : <i>J&#233;rome Boulanger</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_remove_hotpixels :
  -remove_hotpixels $1,$2

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

#@gimp Sharpen [deconvolve] : 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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Sharpen [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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_sharpen_inversediff :
  -apply_channels "-repeat $2 -sharpen $1 -c 0,255 -done",$3,0

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

#@gimp Sharpen [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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Sharpen [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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_sharpen_shock :
  -apply_channels "-repeat $5 -sharpen $1,$2,$3,$4 -c 0,255 -done",$6,0

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

#@gimp Sharpen [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","Red","Green","Blue","Alpha")
#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
_gimp_unsharp :
  -repeat @# -repeat $8
    -if {$1==0} --b[-1] $2 -else --bilateral[-1] $2,$3 -endif
    --[-1] [-2] -*[-1] -$4
    --norm[-1] -ge[-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 Smooth [anisotropic] : 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","Red","Green","Blue","Alpha")
#@gimp : Tiles = int(1,1,10)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Smooth [bilateral] : 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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_bilateral :
  -apply_channels "-repeat $3 -bilateral $1,$2 -done",$4,0

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

#@gimp Smooth [diffusion] : gimp_diffusion_smoothing, gimp_diffusion_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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_diffusion_smoothing :
  -apply_channels "-smooth $6,$1,$2,$3,$4,$5,0",$7,0 -c 0,255

gimp_diffusion_smoothing_preview :
  -gimp_split_preview "-gimp_diffusion_smoothing ${1--2}",$-1

#@gimp Smooth [mean-curvature] : gimp_meancurvature_smoothing, gimp_meancurvature_smoothing_preview(0)
#@gimp : Time step = float(30,5,50)
#@gimp : Iterations = int(4,1,30)
#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Smooth [median] : 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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_median :
  -apply_channels "-median $1",$2,0

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

#@gimp Smooth [patch-based] : 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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Smooth [selective gaussian] : gimp_selective_smoothing, gimp_selective_smoothing_preview(0)
#@gimp : Amplitude = float(5,0,20)
#@gimp : Edges = float(0.5,0,2)
#@gimp : Scales = int(5,1,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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/08/23</i>.</small>")
gimp_selective_smoothing :
  -apply_channels "-repeat $4 -blur_selective $1,$2,$3 -done",$5,0 -c 0,255

gimp_selective_smoothing_preview :
  -gimp_split_preview "-gimp_selective_smoothing ${1--2}",$-1

#@gimp Smooth [thin brush] : 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 : sep = separator(), note = note("<small>Author : <i>PhotoComiX</i>.      Latest update: <i>2010/12/26</i>.</small>")

#@gimp Smooth [total-variation] : 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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Smooth [wavelets] : gimp_haar_smoothing, gimp_haar_smoothing_preview(0)
#@gimp : Threshold = float(1,0,10)
#@gimp : Iterations = int(10,1,32)
#@gimp : Scales = int(10,2,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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>J&#233;rome Boulanger, David Tschumperl&#233;</i>.      Latest update: <i>2012/08/17</i>.</small>")
gimp_haar_smoothing :
  -apply_channels "-denoise_haar $1,$3,$2",$4,0 -c 0,255

gimp_haar_smoothing_preview :
  -gimp_split_preview "-gimp_haar_smoothing ${1--2}",$-1

#@gimp Solidify : gimp_solidify, gimp_solidify_preview(0)
#@gimp : Interpolation type = choice("Linear","Morphological")
#@gimp : sep = separator(), note = note("<small><b>For linear method only :</b></small>")
#@gimp : Smoothness = float(1.5,1,5)
#@gimp : Smoothness factor = float(1,1,1.2)
#@gimp : Precision = float(0.5,0,1)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small><b>Note :</b>
#@gimp : This filter replaces transparent regions by interpolated colors. It may take long to render!
#@gimp : </small>")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/12/01</i>.</small>")
gimp_solidify :
  -if $1 -solidify
  -else -solidify_linear $2,$3,$4
  -endif

gimp_solidify_preview :
  -gimp_split_preview "-gimp_solidify ${1--2}",$-1

#@gimp Upscale [diffusion] : 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(50,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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
      0 -t[-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
      -z[-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 Upscale [scale2x] : 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 : Colorbase = choice(1,"RGB","YCbCr","Lab")
#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_scalenx :
  -repeat @# -l[$>] -split_opacity
    -if {$2==1} -rgb2ycbcr[0] -round[0]
    -elif {$2==2} -rgb2lab8[0] -round[0]
    -endif

    -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

    -if {$2==1} -ycbcr2rgb[0]
    -elif {$2==2} -lab82rgb[0]
    -endif

  -a c -endl -done

gimp_scalenx_preview :
  -z 40%,40%,60%,60%
  -gimp_scalenx $1,$2


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

_gimp_compose :
  -repeat {int(@#/2)} --compose_$1[-2,-1] -rm[-3] -to_rgba[-1] -sh[-1] 3,3 -*[-1] $2 -rm[-1] -compose_alpha[-2,-1] -mv[-1] 0 -done

_gimp_revert_layers :
  -repeat {int(@#/2)} -rv[{2*$>},{2*$>+1}] -done

#@gimp Blend [alpha] : gimp_compose_alpha, gimp_compose_alpha
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>Arto Huotari, David Tschumperl&#233;</i>.      Latest update: <i>2011/10/26</i>.</small>")
gimp_compose_alpha :
  -if ${2=0} -_gimp_revert_layers -endif
  -repeat {int(@#/2)}
    -to_rgba[-1] -sh[-1] 3,3 -*[-1] $1 -rm[-1]
    -compose_alpha[-2,-1]
  -mv[-1] 0 -done

#@gimp Blend [average] : gimp_compose_average, gimp_compose_average
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_average :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose average,$1

#@gimp Blend [color burn] : gimp_compose_colorburn, gimp_compose_colorburn
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_colorburn :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose colorburn,$1

#@gimp Blend [darken] : gimp_compose_darken, gimp_compose_darken
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_darken :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose darken,$1

#@gimp Blend [difference] : gimp_compose_difference, gimp_compose_difference
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_difference :
  -if ${2=0} -_gimp_revert_layers -endif
  -to_rgb -_gimp_compose difference,$1

#@gimp Blend [divide] : gimp_compose_divide, gimp_compose_divide
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>Arto Huotari</i>.      Latest update: <i>2011/10/25</i>.</small>")
gimp_compose_divide :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose divide,$1

#@gimp Blend [dodge] : gimp_compose_dodge, gimp_compose_dodge
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_dodge :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose dodge,$1

#@gimp Blend [edges] : gimp_compose_edges, gimp_compose_edges(0)
#@gimp : Opacity = float(1,0,1)
#@gimp : Smoothness = float(0.8,0,5)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_edges :
  -if ${3=0} -_gimp_revert_layers -endif
  -repeat {int(@#/2)} --compose_edges[-2,-1] $2 -rm[-3] -to_rgba[-1] -sh[-1] 3,3 -*[-1] $1 -rm[-1] -compose_alpha[-2,-1] -mv[-1] 0 -done

#@gimp Blend [exclusion] : gimp_compose_exclusion, gimp_compose_exclusion
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_exclusion :
  -if ${2=0} -_gimp_revert_layers -endif
  -to_rgb -_gimp_compose exclusion,$1

#@gimp Blend [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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</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[^-1] -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 Blend [freeze] : gimp_compose_freeze, gimp_compose_freeze
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_freeze :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose freeze,$1

#@gimp Blend [grain extract] : gimp_compose_grainextract, gimp_compose_grainextract
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/01/13</i>.</small>")
gimp_compose_grainextract :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose grainextract,$1

#@gimp Blend [grain merge] : gimp_compose_grainmerge, gimp_compose_grainmerge
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/01/13</i>.</small>")
gimp_compose_grainmerge :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose grainmerge,$1

#@gimp Blend [hard light] : gimp_compose_hardlight, gimp_compose_hardlight
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_hardlight :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose hardlight,$1

#@gimp Blend [hue] : gimp_compose_hue, gimp_compose_hue
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_hue : -skip ${2=0}
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose hue,$1

#@gimp Blend [interpolation] : gimp_compose_interpolation, gimp_compose_interpolation
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_interpolation :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose interpolation,$1

#@gimp Blend [lighten] : gimp_compose_lighten, gimp_compose_lighten
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_lighten :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose lighten,$1

#@gimp Blend [lightness] : gimp_compose_lightness, gimp_compose_lightness
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/04/08</i>.</small>")
gimp_compose_lightness : -skip ${2=0}
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose lightness,$1

#@gimp Blend [luminance] : gimp_compose_luminance, gimp_compose_luminance
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/04/08</i>.</small>")
gimp_compose_luminance : -skip ${2=0}
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose luminance,$1

#@gimp Blend [median] : compose_median, compose_median(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/10/25</i>.</small>")

#@gimp Blend [multiply] : gimp_compose_multiply, gimp_compose_multiply
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_multiply :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose multiply,$1

#@gimp Blend [negation] : gimp_compose_negation, gimp_compose_negation
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_negation :
  -if ${2=0} -_gimp_revert_layers -endif
  -to_rgb -_gimp_compose negation,$1

#@gimp Blend [overlay] : gimp_compose_overlay, gimp_compose_overlay
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_overlay :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose overlay,$1

#@gimp Blend [reflect] : gimp_compose_reflect, gimp_compose_reflect
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_reflect :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose reflect,$1

#@gimp Blend [saturation] : gimp_compose_saturation, gimp_compose_saturation
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_saturation : -skip ${2=0}
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose saturation,$1

#@gimp Blend [screen] : gimp_compose_screen, gimp_compose_screen
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_screen :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose screen,$1

#@gimp Blend [shape average] : gimp_compose_shapeaverage, gimp_compose_shapeaverage(0)
#@gimp : Preserve shading = bool(1)
#@gimp : Transparency = bool(0)
#@gimp : Revert layers = 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/10/19</i>.</small>")
gimp_compose_shapeaverage :
  -if ${3=0} -_gimp_revert_layers -endif
  -to_rgb
  -repeat {int(@#/2)}
    -rv[-2,-1]
    -if $1 -i[0] [-1] -endif
    -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 Blend [soft light] : gimp_compose_softlight, gimp_compose_softlight
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_softlight :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose softlight,$1

#@gimp Blend [stamp] : gimp_compose_stamp, gimp_compose_stamp
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_stamp :
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose stamp,$1

#@gimp Blend [value] : gimp_compose_value, gimp_compose_value
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_value : -skip ${2=0}
  -if ${2=0} -_gimp_revert_layers -endif
  -_gimp_compose value,$1

#@gimp Blend [xor] : gimp_compose_xor, gimp_compose_xor
#@gimp : Opacity = float(1,0,1)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_compose_xor :
  -if ${2=0} -_gimp_revert_layers -endif
  -to_rgb -_gimp_compose xor,$1

#@gimp Align layers : 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 : Revert layers = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_align_layers :
  -if ${4=0} -_gimp_revert_layers -endif
  -remove_opacity
  -if $1 -register_nonrigid $2,0.1,$3
  -else ($2) -*[-1] 3 -register_rigid[^-1] @-1 -rm[-1]
  -endif

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

#@gimp Fade layers : gimp_fade_layers, gimp_fade_layers_preview
#@gimp : Inter-frames = _int(10,2,100)
#@gimp : sep = separator(), note = note{"<small><b>Note :</b>
#@gimp : This filter needs at least two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/08/04</i>.</small>")
gimp_fade_layers :
  -if {@#<2} -return -endif
  -a z -r 100%,100%,{(d-1)*$1+1},100%,3 -s z

gimp_fade_layers_preview :
  -if {@#<2} -return -endif
  -k[0,1] -+ -/ 2

#@gimp Morph layers : gimp_morph, gimp_no_preview
#@gimp : Inter-frames = _int(10,2,100)
#@gimp : Smoothness = _float(0.2,0,2)
#@gimp : Precision = _float(0.1,0,2)
#@gimp : Revert layers = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_morph :
  -if ${4=0} -_gimp_revert_layers -endif
  -to_rgb -morph $1,$2,$3

#@gimp Layers to tiles : append_tiles, gimp_append_tiles_preview(1)
#@gimp : X-tiles = int(3,0,256)
#@gimp : Y-tiles = int(3,0,256)
#@gimp : note = note("<small>For both parameters, <i>0</i> means <i>automatic</i>.</small>")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_append_tiles_preview :
  -frame 1,1,0,0,0,255 -append_tiles $1,$2

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_split_tiles :
  -split_tiles $1,$2,$3 -k[50%]

#@gimp Transfer colors : gimp_transfer_colors, gimp_transfer_colors
#@gimp : Transfer brighness = bool(0)
#@gimp : Revert layers = bool(0)
#@gimp : Note = note{"<small><b>Note : </b>
#@gimp : The top layer contains the target colors.\n
#@gimp : This filter needs at least two layers to work properly. Set the <i>Input layers</i> option to handle multiple input layers.
#@gimp : </small>"}
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_transfer_colors :
  -if ${2=0} -_gimp_revert_layers -endif
  -transfer_colors $1

#@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 : Revert layers = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_transparent_diff :
  -if ${5=0} -_gimp_revert_layers -endif
  -repeat {int(@#/2)}
    -if $3
      --[-2] [-1] -norm[-2] -b[-2] $2% -ge[-2] $1% -rv[-2,-1]
    -else
      --[-1] [-2] -norm[-1] -b[-1] $2% -ge[-1] $1%
    -endif
    -if {!$4} -negative[-1] -endif
    -to_rgba[-2] -*[-2,-1]
  -mv[-1] 0 -done

#@gimp Split tones : gimp_split_tones, gimp_split_tones_preview(0)
#@gimp : Number of tones = int(3,2,10)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 -append_tiles ,


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

#@gimp Contrast swiss mask : gimp_contrast_swm , gimp_contrast_swm(0)
#@gimp : sep = separator ()
#@gimp : Blur the mask = float(2,0.5,10)
#@gimp : sep = separator ()
#@gimp : note = note ("Contrast Mask need the negative of the mask")
#@gimp : SKIP to use the mask to boost = bool(false)
#@gimp : note = note ("Uncheck for Contrast Mask,Check for Contrast Boost")
#@gimp : sep = separator ()
#@gimp : note = note("Merge the Mask")
#@gimp : Intensity = float (1,0,1)
#@gimp : sep = separator(), note = note("<small>Author : <i>PhotoComiX</i>.      Latest update: <i>2011/1/1 </i>.</small>")
#@gimp : note = link("Filter explained here","http://www.gimpchat.com/viewtopic.php?f=9&t=864")
gimp_contrast_swm :
-repeat @# -l[$>] -split_opacity -l[0]
 --luminance -to_rgb
  -blur_xy[1] $1,$1
  -if {$2==0} -negative[1] -elif {$2==1} -gimp_do_nothing -endif
  -reverse[-2,-1] -gimp_compose_hardlight[-2,-1] $3
-endl -a c -endl -done

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_drop_shadow :
  -drop_shadow $1%,$2%,$3% -rotate $4,0

#@gimp Light glow : gimp_lightglow, gimp_lightglow_preview(0)
#@gimp : Density = float(30,0,100)
#@gimp : Amplitude = float(0.5,0,2)
#@gimp : Mode = choice(8,"Color burn","Dodge","Freeze","Grain merge","Hard light","Interpolation",
#@gimp :               "Lighten","Multiply","Overlay","Reflect","Soft light","Stamp","Value")
#@gimp : Opacity = float(0.8,0,1)
#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/02/21</i>.</small>")
_gimp_lightglow :
  -repeat @#
    --gradient_norm[-1] -ge[-1] {100-$1}% -distance[-1] 1 -^[-1] $2 -*[-1] -1 -n[-1] 0,255 -rv[-2,-1]
    -__gimp_lightglow$3[-2,-1] $4
  -mv[-1] 0 -done

__gimp_lightglow0 : -gimp_compose_colorburn $1
__gimp_lightglow1 : -gimp_compose_dodge $1
__gimp_lightglow2 : -gimp_compose_freeze $1
__gimp_lightglow3 : -gimp_compose_grainmerge $1
__gimp_lightglow4 : -gimp_compose_hardlight $1
__gimp_lightglow5 : -gimp_compose_interpolation $1
__gimp_lightglow6 : -gimp_compose_lighten $1
__gimp_lightglow7 : -gimp_compose_multiply $1
__gimp_lightglow8 : -gimp_compose_overlay $1
__gimp_lightglow9 : -gimp_compose_reflect $1
__gimp_lightglow10 : -gimp_compose_softlight $1
__gimp_lightglow11 : -gimp_compose_stamp $1
__gimp_lightglow12 : -gimp_compose_value $1

gimp_lightglow :
  -apply_channels "-_gimp_lightglow ${1-4}",$5,0

gimp_lightglow_preview :
  -gimp_split_preview "-gimp_lightglow ${1--2}",$-1

#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_light_patch :
  -apply_channels "-light_patch $1,$2,$3",$4,0

#@gimp Light rays : gimp_lightrays, gimp_lightrays(1)
#@gimp : Density = float(80,0,100)
#@gimp : X-center = float(0.5,0,1)
#@gimp : Y-center = float(0.5,0,1)
#@gimp : Length = float(1,0,1)
#@gimp : Attenuation = float(0.5,0,1)
#@gimp : Transparency = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/01/03</i>.</small>")
gimp_lightrays :
  -lightrays ${1-5}
  -if $6 -repeat @# -r[$>] 100%,100%,1,{@{$>,s}+(@{$>,s}%2)} -done -endif

#@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(1,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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_light_relief :
  -b $11% -light_relief ${1-10}

#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_shadow_patch :
  -apply_channels "-shadow_patch $1",$2,0


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


#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 Canvas texture : texturize_canvas, texturize_canvas(0)
#@gimp : Amplitude = float(20,0,256)
#@gimp : Fibrousness = float(3,0,20)
#@gimp : Emboss = float(0.6,0,1)

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_chessboard :
  -to_rgba -chessboard ${1-14}

gimp_chessboard_preview :
  -gimp_split_preview "-gimp_chessboard ${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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_cracks :
  -apply_channels "-cracks $1,$2,$3",$4,0

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

#@gimp Dices : gimp_dices, gimp_dices(0)
#@gimp : Resolution = float(2,1,10)
#@gimp : Size = int(24,8,64)
#@gimp : Color model = choice(1,"Black dices","White dices")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/12/13</i>.</small>")
gimp_dices :
    # Prepare input images.
    -luminance -r {100*$1/$2}%,{100*$1/$2}%,1,1,2 -quantize 6,0

    # Create dice patterns.
    -repeat 6 {2*$2},{2*$2} -_dice$> -done
    -if $3 -negative -endif
    -to_rgb[-1] -frame_round[-6--1] 10,10,0,0,128,128,128,0
    -r2dy[-6--1] $2 -a[-6--1] x

    # Convert input image to dices pattern.
    -repeat {@#-1}
      -*[-2] $2 -channels[-2] 0,1 -r[-2] {$2*100}%,{$2*100}%
      $2,$2,1,2,'if(c,y,x)' -r[-1] [-3],[-3],1,2,0,2 -+[-3,-1] --warp[-1] [-2],0,0 -rm[-3]
    -mv[-1] 0 -done
    -rm[-1]

_dice0 : -ellipse[-1] 50%,50%,5.2%,5.2%,0,1,255
_dice1 : -ellipse[-1] 25%,25%,5.2%,5.2%,0,1,255 -ellipse[-1] 75%,75%,5.2%,5.2%,0,1,255
_dice2 : -_dice1 -_dice0
_dice3 : -_dice1 -ellipse[-1] 25%,75%,5.2%,5.2%,0,1,255 -ellipse[-1] 75%,25%,5.2%,5.2%,0,1,255
_dice4 : -_dice3 -_dice0
_dice5 : -_dice3 -ellipse[-1] 25%,50%,5.2%,5.2%,0,1,255 -ellipse[-1] 75%,50%,5.2%,5.2%,0,1,255

#@gimp Dithering : gimp_dithering_pattern, gimp_dithering_pattern_preview(0)
#@gimp : note = note("<b><small>Image parameters :</small></b>")
#@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 : Color = float(1,0,1)
#@gimp : sep = separator(), note = note("<b><small>Pattern parameters :</small></b>")
#@gimp : Number of tones = int(5,2,32)
#@gimp : Size for dark tones = int(8,2,256)
#@gimp : Size for bright tones = int(8,2,256)
#@gimp : Shape = choice{5,"Square","Diamond","Circle","Square (inv.)","Diamond (inv.)","Circle (inv.)"}
#@gimp : Smoothness = float(0.1,0,32)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/07/23</i>.</small>")
gimp_dithering_pattern :
  -apply_gamma $1 -- 128 -* $2 -+ 128 -+ $3 -b $4 -c 0,255
  -repeat @# -l[$>] -split_opacity
    --patternbw[0] ${6-10}
    -if {$5" && "@{0,s}==3} -rgb2hsv[0] -sh[0] 1,1 -*[-1] $5 -rm[-1] -/[-1] 255 -j[0] [-1],0,0,0,2 -rm[-1] -hsv2rgb[0]
    -else -rm[0] -mv[-1] 0
    -endif
    -a c
  -endl -done

gimp_dithering_pattern_preview :
  -gimp_split_preview "-gimp_dithering_pattern ${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(2,"Black & White","RGB","Color")
#@gimp : Transparency = bool(0)
#@gimp : Negative = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_dots :
  -v -
  -if $6 -* -1 -+ 255 -endif
  -if {$4==0} -norm -dotsbw $1,$2,$3 -* 255
  -elif {$4==1} -dotsbw $1,$2,$3 -* 255
  -else -repeat @#
    --norm[-1] -dotsbw[-1] $1,$2,$3 -compose_shapeaverage[-2,-1]
  -mv[-1] 0 -done -endif
  -if $5 -to_rgba -replace_color 0,0,0,0,0,255,0,0,0,0 -endif
  -if $6 -* -1 -+ 255 -endif

gimp_dots_preview :
  -gimp_split_preview "-gimp_dots ${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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_hearts :
  -apply_channels "-hearts $1",$2,0

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

#@gimp Lissajous : gimp_lissajous, gimp_lissajous(1)
#@gimp : Resolution = int(4096,2,8192)
#@gimp : sep = separator()
#@gimp : X-size = float(0.9,0,2)
#@gimp : Y-size = float(0.9,0,2)
#@gimp : Z-size = float(3,1,10)
#@gimp : sep = separator()
#@gimp : X-multiplier = float(8,0,32)
#@gimp : Y-multiplier = float(7,0,32)
#@gimp : Z-multiplier = float(0,0,32)
#@gimp : sep = separator()
#@gimp : X-offset = float(0,0,1)
#@gimp : Y-offset = float(0,0,1)
#@gimp : Z-offset = float(0,0,1)
#@gimp : sep = separator()
#@gimp : X-angle = float(0,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : sep = separator()
#@gimp : Thickness = float(0,0,50)
#@gimp : Color = color(255,255,255,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/04/18</i>.</small>")
gimp_lissajous :
  -repeat @# -l[$>] -to_rgba
    {w},{h}
    -f3d {0.5*max(w,h)/tan($4*pi/360)}
    -lissajous3d $1,$5,$8,$6,$9,$7,$10
    -r3d[-1] 0,0,1,$13 -r3d[-1] 0,1,0,$12 -r3d[-1] 1,0,0,$11
    -*3d[-1] {0.5*$2*@{-2,w}},{0.5*$3*@{-2,h}},{0.5*$4*max(@{-2,w},@{-2,h})}
    -col3d[-1] 1 -object3d[-2] [-1],50%,50%,0,1,1,0,0 -rm[-1]
    -distance[-1] 1 -gt[-1] $14% -*[-2] [-1] -eq[-1] 0
    -r[-1] 100%,100%,1,4
    -sh[-1] 0,0 -*[-1] $15 -rm[-1]
    -sh[-1] 1,1 -*[-1] $16 -rm[-1]
    -sh[-1] 2,2 -*[-1] $17 -rm[-1]
    -sh[-1] 3,3 -*[-1] $18 -rm[-1]
    -+[-2,-1]
  -endl -done

#@gimp Marble : gimp_marble, gimp_marble
#@gimp : Image weight = float(.5,0,30)
#@gimp : Pattern weight = float(1,0,30)
#@gimp : Pattern angle = float(0,0,360)
#@gimp : Amplitude = float(0,0,1000)
#@gimp : Sharpness = float(.4,0,5)
#@gimp : Anisotropy = float(.6,0,1)
#@gimp : Alpha = float(.6,0,20)
#@gimp : Sigma = float(1.1,0,20)
#@gimp : Cut low = float(0,0,100)
#@gimp : Cut high = float(100,0,100)
#@gimp : sep = separator(), note = note("<small>Author : <i>Preben Soeberg</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_marble :
  -marble $1/10,$2/10,$3,$4,$5,$6,$7,$8,$9%,$10%

#@gimp Maze : gimp_maze, gimp_maze
#@gimp : Cell size = int(24,1,256)
#@gimp : Thickness = int(1,1,10)
#@gimp : Masking = choice("None","Render on dark areas","Render on white areas")
#@gimp : Preserve image dimension = bool(1)
#@gimp : Maze type = choice("Dark walls","White walls")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/09/02</i>.</small>")
gimp_maze :
  -repeat @#
    w={w} h={h}
    -r[-1] {100/$1}%,{100/$1}%,1,100%,2
    -if {$3==0} -f[-1] 1
    -elif {$3==1} -negative[-1]
    -endif
    -maze_mask[-1] $1 -dilate[-1] $2 -*[-1] 255
    -if {!$5} -negative[-1] -endif
    -if $4 -r[-1] $w,$h,100%,100% -endif
  -mv[-1] 0 -done

#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_mosaic :
  -apply_channels "-mosaic $1,$2",$3,0

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

#@gimp Paper texture : 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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_paper :
  -apply_channels "-texturize_paper",$1,0

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

#@gimp Plaid : gimp_plaid_texture,gimp_plaid_texture(1)
#@gimp : Line = float(50,0,100)
#@gimp : Number of angles = int(2,1,8)
#@gimp : Starting angle = float(0,0,360)
#@gimp : Angle range = float(90,0,360)
#@gimp : Smoothness = float(1,0,5)
#@gimp : Sharpen = float(300,0,1000)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/05/16</i>.</small>")
gimp_plaid_texture :
  -repeat @# -l[$>]
    w={w} h={h} s={s}
    -rows $1%
    -b $5% -sharpen $6
    -resize $w,$h,1,$s,2
    --rotate[0] $3,2,1,50%,50%
    -repeat {$2-1} --rotate[0] {$3+$4*($>+1)/($2-1)},2,1,50%,50% -+[-2,-1] -done -rm[0]
    -/ $2
  -endl -done

#@gimp Plasma : gimp_plasma, gimp_plasma(0)
#@gimp : Alpha = float(0.5,0,5)
#@gimp : Beta = float(0,0,100)
#@gimp : Scale = int(8,2,10)
#@gimp : Randomize = bool(0)
#@gimp : Transparency = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/03/20</i>.</small>")
gimp_plasma : -skip ${4=0},${5=0}
  -if $5 -to_rgba -else -to_rgb -endif
  -if $4 -rand 0,255 -endif
  -plasma $1,$2,$3 -n 0,255

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_polka_dots :
  -to_rgba -polka_dots {$1*$2/100},${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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_puzzle :
  -apply_channels "-puzzle $1",$2,0

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

#@gimp Rorschach : gimp_rorschach, gimp_rorschach
#@gimp : Scale = float(3,0,30)
#@gimp : Mirror = choice(1,"None","X-axis","Y-axis","XY-axes")
#@gimp : Colored = bool(false)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/03/12</i>.</small>")
gimp_rorschach :
  -repeat @#
    -if $3 -to_rgb[-1] -else -to_gray[-1] -endif
    -rorschach $1%,$2 -* 255
  -mv[-1] 0 -done

#@gimp Sierpinski triangle : gimp_sierpinski, gimp_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 : Color = color(128,128,128)
#@gimp : Opacity = float(1,0,1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_sierpinski :
  -repeat @# -l[$>]
    100%,100% -sierpinski[-1] ${1-7}
    --fc[-2] $8,$9,$10 -j[0] [-1],0,0,0,0,$11,[-2],255 -rm[-2,-1]
  -endl -done

#@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(128,128,128)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_sponge :
  -apply_channels "-sponge $1",$2,0

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

#@gimp Stained glass : gimp_stained_glass, gimp_stained_glass_preview(0)
#@gimp : Edges = float(20,0,100)
#@gimp : Shading = float(0.1,0,0.5)
#@gimp : Thin separators = bool(1)
#@gimp : sep = separator()
#@gimp : Equalize = bool(1)
#@gimp : Colors = float(1,0,3)
#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/03/18</i>.</small>")
gimp_stained_glass :
  -repeat @# -l[$>] -split_opacity -l[0]
    -stained_glass $1,$2,$3
    -n 0,255
    -if $4 -equalize[-1] 256 -endif
    -rgb2lab[-1] -sh[-1] 1,2 -*[-1] $5 -rm[-1] -lab2rgb[-1]
    -apply_gamma[-1] $6 --[-1] 128 -*[-1] $7 -+[-1] {128+$8}
    -c[-1] 0,255
  -endl -append c -endl -done

gimp_stained_glass_preview :
  -gimp_split_preview "-gimp_stained_glass ${1--2}",$-1

#@gimp Stars : gimp_stars, gimp_stars(0)
#@gimp : Density = float(10,0,200)
#@gimp : Depth = float(0,0,5)
#@gimp : Size = int(32,8,128)
#@gimp : Branches = int(5,2,16)
#@gimp : Thickness = float(0.38,0.1,1)
#@gimp : Smoothness = float(0,0,10)
#@gimp : Color = color(200,200,200,200)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/01</i>.</small>")
gimp_stars :
  -repeat @# -l[$>] -split_opacity -rv
    -stars $1%,$2,$3,$4,$5,$6%,${7-9},{$10/255}
  -rv -a c -endl -done

#@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(2,"Black & White","RGB","Color")
#@gimp : Transparency = bool(0)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_stencil :
  -v -
  -if {$5==0} -norm -stencil $1,$2,$3
  -elif {$5==1} -stencil $1,$2,$3
  -else -repeat @#
    --norm[-1] -stencil[-1] $1,$2,$3 -ge[-1] 50% -compose_shapeaverage[-2,-1]
  -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

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

#@gimp Superformula : gimp_superformula, gimp_superformula(1)
#@gimp : Resolution = int(4096,2,8192)
#@gimp : sep = separator()
#@gimp : X-size = float(0.9,0,2)
#@gimp : Y-size = float(0.9,0,2)
#@gimp : sep = separator()
#@gimp : m = int(8,1,32)
#@gimp : n1 = float(1,-32,32)
#@gimp : n2 = float(5,-32,32)
#@gimp : n3 = float(8,-32,32)
#@gimp : sep = separator()
#@gimp : X-angle = float(0,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : sep = separator()
#@gimp : Thickness = float(1,0,50)
#@gimp : Color = color(128,128,128,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/04/18</i>.</small>")
gimp_superformula :
  -repeat @# -l[$>] -to_rgba
    {w},{h}
    -f3d {0.5*max(w,h)/tan($4*pi/360)}
    -superformula3d $1,${4-7}
    -r3d[-1] 0,0,1,$10 -r3d[-1] 0,1,0,$9 -r3d[-1] 1,0,0,$8
    -*3d[-1] {0.5*$2*@{-2,w}},{0.5*$3*@{-2,h}}
    -col3d[-1] 1 -object3d[-2] [-1],50%,50%,0,1,1,0,0 -rm[-1]
    -distance[-1] 1 -gt[-1] $11% -*[-2] [-1] -eq[-1] 0
    -r[-1] 100%,100%,1,4
    -sh[-1] 0,0 -*[-1] $12 -rm[-1]
    -sh[-1] 1,1 -*[-1] $13 -rm[-1]
    -sh[-1] 2,2 -*[-1] $14 -rm[-1]
    -sh[-1] 3,3 -*[-1] $15 -rm[-1]
    -+[-2,-1]
  -endl -done

#@gimp Truchet : gimp_truchet, gimp_truchet(0)
#@gimp : Scale = int(32,1,256)
#@gimp : Radius = int(5,1,64)
#@gimp : Smoothness = float(1,0,10)
#@gimp : Type = choice(1,"Straight","Curved")
#@gimp : Colorize randomly = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/10/26</i>.</small>")
gimp_truchet :
  -truchet $1,$2,$4
  -if $5 -repeat @# -channels[-1] 0 -label[-1] 0,1 {iM+1},1,1,3 -rand[-1] 0,255 -map[-2] [-1] -rm[-1] -mv[-1] 0 -done -endif
  -b $3 -n 0,255

#@gimp Turbulence : gimp_turbulence, gimp_turbulence
#@gimp : Radius = float(128,1,1024)
#@gimp : Octaves = int(6,1,12)
#@gimp : Damping per octave = float(4,1,10)
#@gimp : Difference mixing = float(0,-10,10)
#@gimp : Mode = choice("Turbulence","Turbulence 2","Fractal Noise","Fractured Clouds","Stardust","Pea Soup")
#@gimp : sep = separator(), note = note("<small>Author : <i>Preben Soeberg</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_turbulence :
  -turbulence ${^0}

#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_whirls :
  -apply_channels "-whirls $1,$2,$3,$4",$5,0

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

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

#@gimp <i>Lylejk</i>
#@gimp Lylejk's 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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), note = note("<small>Authors : <i>Lyle Kroll, David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_lylejk_stencil :
  -apply_channels "-repeat $1 -b $3 -unsharp $3,$2 -c 0,255 -mv[-1] 0 -done",$4,0
#@gimp _


#@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 = Specular lightness
# $12 = Specular 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)} -r3d 0,0,1,$6 -r3d 0,1,0,$5 -r3d 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 colored object : gimp_coloredobject3d, gimp_coloredobject3d_preview(1)
#@gimp : Type = choice{1,"Plane","Box","Pyramid","Ellipsoid","Torus","Gyroid","Weird","Cup"}
#@gimp : Color = color(128,128,128,255)
#@gimp : sep = separator()
#@gimp : Size-1 = float(0.5,0,3)
#@gimp : Size-2 = float(0.5,0,3)
#@gimp : Size-3 = 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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular shininess = float(0.7,0,3)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/05/16</i>.</small>")
_gimp_coloredobject3d :
  -to_rgb -_gimp_coloredobject3d$1$2 ${6-8} -col3d[-1] ${3-5}
  -db3d 0

gimp_coloredobject3d :
  -_gimp_coloredobject3d "_",${1-4,6-8}
  -repeat {@#-1}
    --gimp_render3d[-1] @{$>,w},@{$>,h},$6,${9--1}
    -sh[-1] 3,3 -*[-1] {$5/255} -rm[-1]
    -compose_alpha[$>,-1]
  -done
  -rm[-1]

gimp_coloredobject3d_preview :
  -_gimp_coloredobject3d "_preview_",${1-4,6-8}
  -repeat {@#-1}
    --gimp_render3d[-1] @{$>,w},@{$>,h},$6,${9--1}
    -sh[-1] 3,3 -*[-1] {$5/255} -rm[-1]
    -compose_alpha[$>,-1]
  -done -rm[-1]

_gimp_coloredobject3d_0 : -plane3d 1 -*3d[-1] $1,$2,1
_gimp_coloredobject3d_1 : -box3d 1 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_2 : -pyramid3d 1,1 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_3 : -sphere3d 1 -*3d[-1] 1,{2*$2},{2*$3}
_gimp_coloredobject3d_4 : -torus3d $1,{$2/2} -*3d[-1] $3,0.5,0.5
_gimp_coloredobject3d_5 : -gyroid3d 24 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_6 : -weird3d 32 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_7 : -cup3d 128 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_preview_0 : -plane3d 1 -*3d[-1] $1,$2,1
_gimp_coloredobject3d_preview_1 : -box3d 1 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_preview_2 : -pyramid3d 1,1 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_preview_3 : -sphere3d 1 -*3d[-1] 1,{2*$2},{2*$3}
_gimp_coloredobject3d_preview_4 : -torus3d $1,{$2/2} -*3d[-1] $3,0.5,0.5
_gimp_coloredobject3d_preview_5 : -gyroid3d 8 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_preview_6 : -weird3d 12 -*3d[-1] $1,$2,$3
_gimp_coloredobject3d_preview_7 : -cup3d 64 -*3d[-1] $1,$2,$3

#@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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
_gimp_elevation3d :
  -repeat {@#/2} -l[$>,{min($>+1,@#-1)}]
    -if {@#==1} --norm -else -r[1] [0],3 -endif
    -n[1] 0,$1 -b[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 extrusion : gimp_extrude3d, gimp_extrude3d_preview(1)
#@gimp : Depth = float(10,1,1024)
#@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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</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 image object : gimp_imageobject3d, gimp_imageobject3d_preview(1)
#@gimp : Type = choice{1,"Plane","Cube","Pyramid","Sphere","Torus","Gyroid","Weird","Cup","Rubik"}
#@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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular shininess = float(0.7,0,3)
#@gimp : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
_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 64,32
_gimp_imageobject3d_4 : -torus3d 100,30 -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 128 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_8 : -imagerubik3d 5,5
_gimp_imageobject3d_preview_0 : -imageplane3d
_gimp_imageobject3d_preview_1 : -imagecube3d
_gimp_imageobject3d_preview_2 : -imagepyramid3d
_gimp_imageobject3d_preview_3 : -imagesphere3d 16,8
_gimp_imageobject3d_preview_4 : -torus3d 100,30 -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 64 -t3d[-1] [-2] -rm[-2]
_gimp_imageobject3d_preview_8 : -imagerubik3d 3,3,5,5

#@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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</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 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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular shininess = float(0.7,0,3)
#@gimp : Rendering = choice(3,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gimp : Opacity = float(1,0,1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_random3d :
  -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]
    -r3d[-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,$11,0,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 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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}
    wh={w},{h} -rm[-1] $wh
    -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 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_quick_copyright :
  -i[0] 0 -t[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] 0 -t[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} -j[-1] [0],$9,$9,0,0,{$6/255},[1]
  -elif {$8==1} -j[-1] [0],{w-1-@{0,w}-$9},$9,0,0,{$6/255},[1]
  -elif {$8==2} -j[-1] [0],$9,{h-1-@{0,h}-$9},0,0,{$6/255},[1]
  -else -j[-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 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_rainbow :
  -channels 0 -f 0
  -spline 0,$1%,100,{-$3}%,100%,$2%,100,$4%,1,1
  -flood 0,0,0,0,0,1,1 -flood {w-1},0,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[^-1] [-1] -rm[-1]
  -if {$6<100} -repeat @# -sh[$>] 3,3 -*[-1] {$6/100} -rm[-1] -done -endif

#@gimp Shade bobs : gimp_shadebobs, gimp_shadebobs
#@gimp : note = note("<small>Bobs parameters :</small>")
#@gimp : Density = int(50,1,200)
#@gimp : Radius = int(5,1,100)
#@gimp : Duration = int(200,1,500)
#@gimp : Velocity = float(1,0,10)
#@gimp : sep = separator()
#@gimp : note = note("<small>Curve parameters :</small>")
#@gimp : Rx = float(-1,-3,3)
#@gimp : Ry = float(2,-3,3)
#@gimp : Rz = float(1,-3,3)
#@gimp : Rt = float(0.8,-3,3)
#@gimp : Rcx = float(0,-3,3)
#@gimp : Colormap = choice(8,"Grayscale","Standard","HSV","Lines","Hot","Cool","Jet","Flag","Cube")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/04/18</i>.</small>")
gimp_shadebobs :
  -channels 0 -f 0
  -repeat @# -l[$>]
    t=0
    -repeat $3
      -repeat $1
        r={$6+$5*cos(6*$7*$t)+(1-$5)*sin(6*$8*$t)}
        a={(360*sin($7*$t)+30*$6*$>)*pi/180}
        ax={2*$>*pi/$1+$t}
        cx={(1+$9*cos($ax)+$r*cos($a))*w/2}
        cy={(1+$9*sin($ax)+$r*sin($a))*h/2}
        -ellipse[-1] $cx,$cy,$2%,$2%,0,-1,1
      -done
      t={$t+$4/100}
    -done
  -endl -done
  -and 255 -if $10 -map {$10-1} -endif

#@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 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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular 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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular shininess = float(0.7,0,3)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_animate_elevation3d :
  -if $3 filename="$4/gmic_elevation3d.png" -else filename="" -endif
  -_gimp_elevation3d ${5-6}
  -animate gimp_render3d,"${7-8},${10-19},$9",\
                         "${7-8},${20-29},$9",$1,$2,@{"-quote \""$filename"\""}

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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular 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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular shininess = float(0.7,0,3)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_animate_extrude3d :
  -if $3 filename="$4/gmic_extrude3d.png" -else filename="" -endif
  -_gimp_extrude3d ${5-7}
  -animate gimp_render3d,"${8-9},${11-20},$10",\
                         "${8-9},${21-30},$10",$1,$2,@{"-quote \""$filename"\""}

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 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","Rubik"}
#@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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular 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 : Specular lightness = float(0.5,0,1)
#@gimp : Specular shininess = float(0.7,0,3)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_animate_imageobject3d :
  -if $3 filename="$4/gmic_imageobject3d.png" -else filename="" -endif
  -_gimp_imageobject3d "_",$5
  -animate gimp_render3d,"${6-7},${9-18},$8",\
                         "${6-7},${19-28},$8",$1,$2,@{"-quote \""$filename"\""}

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 text pointcloud : gimp_text_pointcloud3d, gimp_text_pointcloud3d_preview
#@gimp : Frames = _int(64,1,256)
#@gimp : 1st text = text("G'MIC")
#@gimp : 2nd text = text("Rocks!")
#@gimp : Smoothness = float(1,0,5)
#@gimp : Color = color(200,220,255)
#@gimp : Background = color(255,255,255,255)
#@gimp : X-shadow= float(2,0,10)
#@gimp : Y-shadow= float(2,0,10)
#@gimp : Shadow smoothness = float(1,0,5)
#@gimp : Stationary frames = _int(19,1,32)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/09/01</i>.</small>")
gimp_text_pointcloud3d :
  W={w} H={h} M={round(1.5*max(w,h))} -rm
  -text_pointcloud3d "$2","$3",$4
  -col3d[-1] ${5-7} -*3d[-1] {0.7*$M}
  -f3d 4000 -db3d 0 -m3d 4
  -repeat $1
    -progress {60*$>/$1}
    angle={$>*360/$1}
    --r3d[0] 1,0,1,$angle
    $M,$M,1,3,-1 -object3d[-1] [-2],50%,50%,0,1 -rm[-2]
  -done
  -rm[0] -a z -autocrop -1 -to_rgba -s z -replace_color 0,0,-1,-1,-1,255,0,0,0,0
  -if $11 N=@# -repeat @# -l[$>] -progress {60+40*$>/$N}
    -i[0] 100%,100%,1,4 -fc[0] ${8-11} --channels[-1] 3,3 --negative[-1] -b[-2,-1] $14% -to_rgba[-1]
    -j[0] [-1],$12%,$13%,0,0,1,[-2],255 -rm[-2,-1] -compose_alpha
  -endl -done -endif
  -if {$W>$H} -r2dx $W -else -r2dy $H -endif
  -if {$15>1}
    -i[{int($1/2)}] [{int($1/2)}]x{$15-1}
    -i[0] [0]x{$15-1}
  -endif

gimp_text_pointcloud3d_preview :
  -gimp_text_pointcloud3d 4,"$2","$3",$4,${5-7},${8-11},${12-14},1 -drgba
  -frame 1,1,0 -append_tiles 2,2

#@gimp 3d tiles : gimp_transition3d, gimp_transition3d_preview
#@gimp : Inter-frames = _int(10,3,100)
#@gimp : X-tiles = int(8,1,64)
#@gimp : Y-tiles = int(8,1,64)
#@gimp : X-rotation = text("1")
#@gimp : Y-rotation = text("1")
#@gimp : Z-rotation = text("0")
#@gimp : Focale = float(800,100,2000)
#@gimp : Enable antialiasing = bool(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/08/13</i>.</small>")
gimp_transition3d :
  -f3d $7
  -transition3d $1,$2,$3,"$4","$5","$6",$8

gimp_transition3d_preview :
  -f3d $7
  -if {@#==1} -return -endif
  -k[0,1] -transition3d 4,$2,$3,"$4","$5","$6",$8
  -k[1,2]
  -r[0] 50%,100%,1,100%,0
  -r[1] 50%,100%,1,100%,0,0,1
  -a x
  -line 50%,0,50%,100%,1,0,0,0,255

#@gimp Smooth [anisotropic] : 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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_animate_anisotropic_smoothing :
  -if $3 filename="$4/gmic_anisotropic_smoothing.png" -else filename="" -endif
  -animate gimp_anisotropic_smoothing,"${13-17},${5-12}",\
                                      "${18-22},${5-12}",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_anisotropic_smoothing_preview :
  -gimp_animate_preview gimp_anisotropic_smoothing,"${13-17},${5-12}",\
                                                   "${18-22},${5-12}",0

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_animate_pencilbw :
  -if $3 filename="$4/gmic_pencilbw.png" -else filename="" -endif
  -animate pencilbw,"${5-6}",\
                    "${7-8}",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_pencilbw_preview :
  -gimp_animate_preview pencilbw,"${5-6}",\
                                 "${7-8}"

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_animate_stencilbw :
  -if $3 filename="$4/gmic_stencilbw.png" -else filename="" -endif
  -animate stencilbw,"${5-6}",\
                     "${7-8}",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_stencilbw_preview :
  -gimp_animate_preview stencilbw,"${5-6}",\
                                  "${7-8}"

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_animate_cartoon :
  -if $3 filename="$4/gmic_cartoon.png" -else filename="" -endif
  -animate cartoon,"${6-10},$5",\
                   "${11-15},$5",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_cartoon_preview :
  -gimp_animate_preview cartoon,"${6-10},$5",\
                                "${11-15},$5"

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_animate_edges :
  -if $3 filename="$4/gmic_edges.png" -else filename="" -endif
  -animate gimp_edges,"${6-7},$5",\
                      "${8-9},$5",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_edges_preview :
  -gimp_animate_preview gimp_edges,"${6-7},$5",\
                                   "${8-9},$5"

#@gimp Edges on fire : gimp_fire_edges, gimp_fire_edges_preview(0)
#@gimp : Edges = float(0.7,0,3)
#@gimp : Attenuation = float(0.25,0,1)
#@gimp : Smoothness = float(0.5,0,5)
#@gimp : Threshold = float(25,0,100)
#@gimp : sep = separator()
#@gimp : Number of frames = _int(20,1,999)
#@gimp : Starting frame = int(20,0,199)
#@gimp : Frame skip = _int(0,0,20)
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/07/06</i>.</small>")
gimp_fire_edges :
  -fire_edges ${1-7} -rv

gimp_fire_edges_preview :
  -gimp_split_preview "-fire_edges $1,$2,$3,$4,1,$6,0",$-1

#@gimp Lava lamp : gimp_lavalampbw, gimp_lavalampbw_preview(0)
#@gimp : Number of key-frames = _int(3,2,50)
#@gimp : Number of inter-frames = _int(30,2,100)
#@gimp : Smooth looping = _bool(1)
#@gimp : sep = separator()
#@gimp : Resolution = float(20,1,100)
#@gimp : Size = float(2,0,30)
#@gimp : Smoothness = _float(0.01,0,1)
#@gimp : Transparent background = bool(0)
gimp_lavalampbw :
  -if {!@#} (255;100^64;16^128;0) -r[-1] 512,512,1,3,3 -endif
  -repeat @# -l[$<]
    w={w} h={h}
    --r $4%,$4%,1,1,0 [-1]x{$1-1} -rand[^0] 0,1 -stencil[^0] $5,0
    -if $3 [1] -endif
    -morph[^0] $2,$6,0
    -stencil[^0] $5,0
    -r[^0] $w,$h,1,1,3 -b[^0] 10 -ge[^0] 50% -*[^0] 255
    -r[^0] 100%,100%,1,4 -j[^0] [0] -rm[0]
    -if $3 -rm[-1] -endif
  -endl -done
  -if {!$7} -repeat @# -l[$>] -split_opacity -n[-1] 0,1 -*[^-1] [-1] -rm[-1] -endl -done -endif

gimp_lavalampbw_preview :
  -gimp_lavalampbw 2,2,1,$4,$5,$6,$7 -k[0]

#@gimp Lissajous : gimp_animate_lissajous, gimp_animate_lissajous_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 : sep = separator()
#@gimp : note = note{"<b>Starting parameters :</b>"}
#@gimp : Resolution = int(4096,2,8192)
#@gimp : X-size = float(0.9,0,2)
#@gimp : Y-size = float(0.9,0,2)
#@gimp : Z-size = float(3,1,10)
#@gimp : X-multiplier = float(8,0,32)
#@gimp : Y-multiplier = float(7,0,32)
#@gimp : Z-multiplier = float(0,0,32)
#@gimp : X-offset = float(0,0,1)
#@gimp : Y-offset = float(0,0,1)
#@gimp : Z-offset = float(0,0,1)
#@gimp : X-angle = float(0,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : Thickness = float(0,0,50)
#@gimp : Color = color(255,255,255,255)
#@gimp : sep = separator()
#@gimp : note = note{"<b>Ending parameters :</b>"}
#@gimp : Resolution = int(4096,2,8192)
#@gimp : X-size = float(0.9,0,2)
#@gimp : Y-size = float(0.9,0,2)
#@gimp : Z-size = float(3,1,10)
#@gimp : X-multiplier = float(8,0,32)
#@gimp : Y-multiplier = float(7,0,32)
#@gimp : Z-multiplier = float(0,0,32)
#@gimp : X-offset = float(0,0,1)
#@gimp : Y-offset = float(0,0,1)
#@gimp : Z-offset = float(0,0,1)
#@gimp : X-angle = float(0,0,360)
#@gimp : Y-angle = float(0,0,360)
#@gimp : Z-angle = float(0,0,360)
#@gimp : Thickness = float(0,0,50)
#@gimp : Color = color(255,255,255,255)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/04/18</i>.</small>")
gimp_animate_lissajous :
  -if $3 filename="$4/gmic_lissajous.png" -else filename="" -endif
  -animate gimp_lissajous,"${5-22}",\
                          "${23-40}",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_lissajous_preview :
  -gimp_animate_preview gimp_lissajous,"${5-22}",\
                                       "${23-40}",0

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_animate_morpho :
  -if $3 filename="$4/gmic_morpho.png" -else filename="" -endif
  -animate gimp_morpho,"$5,$8,$6,$7,0,1",\
                       "$5,$9,$6,$7,0,1",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_morpho_preview :
  -gimp_animate_preview gimp_morpho,"$5,$8,$6,$7,0,1",\
                                    "$5,$9,$6,$7,0,1"

#@gimp Rodilius : gimp_animate_rodilius, gimp_animate_rodilius_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 : Color mode = choice(1,"Darker","Lighter")
#@gimp : note = note{"\n<b>Starting parameters :</b>"}
#@gimp : Amplitude = float(10,0,30)
#@gimp : Thickness = float(10,0,100)
#@gimp : Sharpness = float(300,0,1000)
#@gimp : Orientations = int(5,2,20)
#@gimp : Offset = float(0,0,180)
#@gimp : note = note{"\n<b>Ending parameters :</b>"}
#@gimp : Amplitude = float(10,0,30)
#@gimp : Thickness = float(10,0,100)
#@gimp : Sharpness = float(300,0,1000)
#@gimp : Orientations = int(5,2,20)
#@gimp : Offset = float(180,0,180)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_animate_rodilius :
  -if $3 filename="$4/gmic_rodilius.png" -else filename="" -endif
  -animate rodilius,"${6-10},$5",\
                    "${11-15},$5",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_rodilius_preview :
  -gimp_animate_preview rodilius,"${6-10},$5",\
                                 "${11-15},$5"

#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_animate_glow :
  -if $3 filename="$4/gmic_glow.png" -else filename="" -endif
  -animate glow,"$5",\
                "$6",$1,$2,@{"-quote \""$filename"\""}

gimp_animate_glow_preview :
  -gimp_animate_preview glow,"$5",\
                             "$6"

#@gimp _<b>Spectral handling</b>
#-------------------------------


#@gimp Fourier analysis : gimp_display_fft, gimp_display_fft(1)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_display_fft :
  -to_rgb -display_fft

#@gimp Fourier transform : gimp_fourier, gimp_fourier_preview(1)
#@gimp : Transform = choice(0,"Direct","Inverse")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_split_freq_preview :
  -gimp_split_freq $1 -k[0,1] -a x

gimp_split_freq :
  -repeat @#
    --b[-1] $1 --[-2] [-1] -/[-2] 2 -+[-2] 128 -rv[-2,-1]
  -mv[-2,-1] 0 -done


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

#@gimp Custom code (local) : gimp_custom_code, gimp_custom_code_preview(0)
#@gimp : Code = text(1,"-repeat @# -l[$>]\n\n  -to_rgb\n  --deform 20\n  -compose_edges 3\n\n-endl -done\n\n\n")
#@gimp : sep = separator()
#@gimp : Value range = choice("Cut","Normalize")
#@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","Red","Green","Blue","Alpha")
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator()
#@gimp : note = note{"<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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/06/14</i>.</small>")

#@gimp Custom code (global) : gimp_custom_code, gimp_custom_code_preview(1)
#@gimp : Code = text(1,"-repeat @# -l[$>]\n\n  -to_rgb\n  --deform 20\n  -compose_edges 3\n\n-endl -done\n\n\n")
#@gimp : sep = separator()
#@gimp : Value range = choice("Cut","Normalize")
#@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","Red","Green","Blue","Alpha")
#@gimp : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : sep = separator()
#@gimp : note = note{"<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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/06/14</i>.</small>")
gimp_custom_code : -skip "${1=-skip ,}"
  -m "_gimp_custom_code_start : $1"
  -if {$3>0}
    -apply_channels "-_gimp_custom_code_start",$3,$2
  -else
    -_gimp_custom_code
    -if $2 -n 0,255 -else -c 0,255 -endif
  -endif

gimp_custom_code_preview : -skip "${1=-skip ,}"
  _gcp_arg="$1"
  -gimp_split_preview "-gimp_custom_code $_gcp_arg,${2--2}",$-1

_gimp_custom_code :
  -_gimp_custom_code_start

#@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 conjunction with the input/output options of the G'MIC plug-in.")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_do_nothing :

#@gimp GREYC Poker Tour : gimp_gpt, gimp_no_preview
#@gimp : Score type = _choice(0,"All-times","Last 50 sessions","Last 25 sessions","Last 10 sessions","Last tournament 50","Last tournament 25","Last tournament 10")
#@gimp : sep = separator(), note = note{"<b>Note</b> : This filters renders and displays the current score board for the <b>GPT (GREYC Poker Tour)</b>,
#@gimp : a small and local poker tournament organized in our research lab."};
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/03/27</i>.</small>")
gimp_gpt :
  -gpt ,@{-_gimp_gpt$1}

_gimp_gpt0 : -u 0
_gimp_gpt1 : -u 50
_gimp_gpt2 : -u 25
_gimp_gpt3 : -u 10
_gimp_gpt4 : -u -50
_gimp_gpt5 : -u -25
_gimp_gpt6 : -u -10

#@gimp Histogram analysis : _none_, gimp_display_histogram(1)
#@gimp : Clusters = int(256,2,256)
#@gimp : Monochrome = bool(0)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_display_histogram :
  -to_rgb -if $2 -luminance -endif
  -repeat @#
    -display_histogram[-1] {w},{h},$1,0,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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_import_image :
  -rm -i "$1" -s z -if $2 -n 0,255 -else -c 0,255 -endif

#@gimp Solve maze : gimp_solve_maze, gimp_solve_maze_preview(1)
#@gimp : Starting X-coord = float(5,0,100)
#@gimp : Starting Y-coord = float(5,0,100)
#@gimp : Ending X-coord = float(95,0,100)
#@gimp : Endind Y-coord = float(95,0,100)
#@gimp : Smoothness = float(0.1,0,1)
#@gimp : Thickness = int(3,1,10)
#@gimp : Color = color(255,0,0)
#@gimp : Maze type = choice("Dark walls","White walls")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2011/09/01</i>.</small>")
gimp_solve_maze :
  -repeat @#
    --norm[-1] -ge[-1] 50%
    -if {!$10} -negative[-1] -endif
    -*[-1] 255 --b[-1] $5% -*[-2] 1e10 -+[-2,-1]
    -minimal_path[-1] $1%,$2%,0,$3%,$4%,0
    -pointcloud[-1] 0 -dilate[-1] $6 -r[-1] [-2],[-2],1,1,0
    -to_rgba[-1]
    -replace_color[-1] 0,0,1,1,1,255,${7-9},255
    -replace_color[-1] 0,0,0,0,0,255,0,0,0,0
    -ellipse[-1] $1%,$2%,5,5,0,1,${7-9},255
    -ellipse[-1] $3%,$4%,5,5,0,1,${7-9},255
    -rv[-2,-1]
  -mv[-2,-1] 0 -done

gimp_solve_maze_preview :
  -drgba
  -line $1%,$2%,$3%,$4%,1,0xCCCCCCCC,${7-9}
  -ellipse $1%,$2%,3,3,0,1,${7-9}
  -ellipse $1%,$2%,3,3,0,1,0x1,0
  -ellipse $3%,$4%,3,3,0,1,${7-9}
  -ellipse $3%,$4%,3,3,0,1,0x1,0


#@gimp <b>Experimental</b>
#--------------------------

#@gimp Adjust orientation : gimp_adjust_orientation, gimp_adjust_orientation(1)
#@gimp : Threshold = float(5,0,100)
gimp_adjust_orientation :
  -repeat @#
    M={max(w,h)}
    --gradient_norm[-1] -ge[-1] $1%                      # Compute binary contours.
    --*[-1] '1+y' -*[-2] '1+x' -a[-2,-1] c               # Extract contours points.
    -r[-1] {w*h},2,1,1,-1 -sort[-1] +,x -autocrop[-1] 0
    -/[-1] $M --r[-1] 1,2,1,1,2 -r[-1] [-2] --[-2,-1]    # Estimate main axis.
    --transpose[-1] -**[-2,-1]
    -eigen[-1] -rm[-2] -z[-1] 0,0
    -if {i<0} -*[-1] -1 -endif
    theta={180*atan2(i(0,1),i)/pi}
    -rm[-1]
    -if {w>h} -rotate[-1] {-$theta},0,1,50%,50%
    -else -rotate[-1] {-$theta+90},0,1,50%,50%
    -endif
  -mv[-1] 0 -done

#@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","Red","Green","Blue","Alpha")
#@gimp : Tiles = int(1,1,10)
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 -z[-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)} -k[-1] -/ 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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
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 -z[-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)} -k[-1] -/ 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","Red","Green","Blue","Alpha")
#@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 : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2010/12/29</i>.</small>")
gimp_unsharp16 :
  -rm -i $1 -/ 256
  -gimp_unsharp ${3--1}
  -* 256 -if {narg($2)} -o $2 -endif -/ 256

gimp_unsharp16_preview :
  -i $1 -z[-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)} -k[-1] -/ 256
  -gimp_unsharp ${3--1}

#@gimp Pink operator : gimp_pink, gimp_pink_preview(1)
#@gimp : Pink operator = choice("wshedtopo","wshedtopo inv","minima","maxima","heightminima","heightmaxima","grayskel","htkern","htkernu","lvkern","lvkernu","asf","asflin","asfr","asft","asftmed","asftndg","dilatballnum","erosballnum","lintophat")
#@gimp : Connectivity / Dir = choice("Four/x","Eight/y")
#@gimp : Smoothness = float(0,0,5)
#@gimp : Height/Rep = int(5,0,25)
#@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","Red","Green","Blue","Alpha")
#@gimp : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gimp : note = link("http://pinkhq.com/")
gimp_pink :
  -if   {$1==0}  -apply_channels "-b $3 -pink heightminima,{($2+1)*4},$4 -pink wshedtopo,{($2+1)*4}",$5,0
  -elif {$1==1}  -apply_channels "-b $3 -pink heightmaxima,{($2+1)*4},$4 -pink wshedtopo,{($2+1)*4},i",$5,0
  -elif {$1==2}  -apply_channels "-b $3 -pink minima,{($2+1)*4}",$5,0
  -elif {$1==3}  -apply_channels "-b $3 -pink maxima,{($2+1)*4}",$5,0
  -elif {$1==4}  -apply_channels "-b $3 -pink heightminima,{($2+1)*4},$4",$5,0
  -elif {$1==5}  -apply_channels "-b $3 -pink heightmaxima,{($2+1)*4},$4",$5,0
  -elif {$1==6}  -apply_channels "-b $3 -pink grayskel,null,4,$4",$5,0
  -elif {$1==7}  -apply_channels "-b $3 -pink htkern,null,{($2+1)*4}",$5,0
  -elif {$1==8}  -apply_channels "-b $3 -pink htkernu,null,{($2+1)*4}",$5,0
  -elif {$1==9}  -apply_channels "-b $3 -pink lvkern,null,{($2+1)*4}",$5,0
  -elif {$1==10} -apply_channels "-b $3 -pink lvkernu,null,{($2+1)*4}",$5,0
  -elif {$1==11} -apply_channels "-b $3 -pink asf,$4",$5,0
  -elif {$1==12}
     -if {$2==0} -apply_channels "-b $3 [0]x2 -a z -pink asflin,x,$4 -s z -k[-1]",$5,0
           -else -apply_channels "-b $3 [0]x2 -a z -pink asflin,y,$4 -s z -k[-1]",$5,0 -endif
  -elif {$1==13} -apply_channels "-b $3 -pink asfr,$4",$5,0
  -elif {$1==14} -apply_channels "-b $3 -pink asft,null,null,{($2+1)*4},$4",$5,0
  -elif {$1==15} -apply_channels "-b $3 -pink asftmed,{($2+1)*4},$4",$5,0
  -elif {$1==16} -apply_channels "-b $3 -pink asftndg,null,null,{($2+1)*4},$4",$5,0
  -elif {$1==17} -apply_channels "-b $3 -pink dilatballnum,$4",$5,0
  -elif {$1==18} -apply_channels "-b $3 -pink erosballnum,$4",$5,0
  -elif {$1==19} -apply_channels "-b $3 -pink lintophat,$4",$5,0
  -else          -apply_channels "-b $3 -pink heightminima,{($2+1)*4},$4 -pink wshedtopo,{($2+1)*4}",$5,0
  -endif

gimp_pink_preview :
  -gimp_split_preview "-gimp_pink ${1-5}",$6

#-------------------------------------
#
# Define menu entries for
# the G'MIC online web service.
#
#-------------------------------------


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


#@gmicol G'MIC Online : _none_, gmicol_logo_en
#@gmicol : note = note{"
#@gmicol : <span foreground="purple">( <b>G</b>REYC's <b>M</b>agic <b>I</b>mage <b>C</b>onverter <b>O</b>n-<b>L</b>ine)</span>\n\nis proposed to you by"}
#@gmicol : note = link("S&#233;bastien Fourey","http://foureys.users.greyc.fr/")
#@gmicol : note = link("David Tschumperl&#233;","http://tschumperle.users.greyc.fr/")
#@gmicol : note = link{"( IMAGE Team / GREYC Laboratory - CNRS UMR 6072 )","http://www.greyc.ensicaen.fr/EquipeImage"}
#@gmicol : note = note{"
#@gmicol : This web-service is based on our software <b>G'MIC</b> available at:"}
#@gmicol : note = link("http://gmic.sourceforge.net/")
#@gmicol : note = note{"Colorpickers and sliders widgets are provided by the <b>DHTMLX</b> project:"}
#@gmicol : note = link("http://www.dhtmlx.com")
#@gmicol : sep = separator()
#@gmicol : note = note{"<b>G'MIC</b> is also available as a free plug-in for the image retouching software <b>GIMP</b>. Download it to get more filters
#@gmicol : and features than in the online version, at:"}
#@gmicol : note = link{"The G'MIC plug-in for GIMP","http://gmic.sourceforge.net/gimp.shtml"}
#@gmicol : sep = separator(), note = note("<small>Authors : <i>S&#233;bastien Fourey, David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")
gmicol_logo_en :
  -gimp_logo "    - Online -"

#@gmicol Contributors : _none_, _none_
#@gmicol : note = note{"
#@gmicol : We would like to thank all these people who contributed to <b>G'MIC</b> in one way or another.
#@gmicol : A big hug to : \n\n
#@gmicol : <b> -</b> <i>Sylvie Alexandre</i> <small>(packaging, testing &amp; filters)</small>
#@gmicol : <b> -</b> <i>Partha Bagchi</i> <small>(packaging)</small>
#@gmicol : <b> -</b> <i>J&#233;rome Boulanger</i> <small>(testing &amp; code)</small>
#@gmicol : <b> -</b> <i>Claude Bulin</i> <small>(packaging)</small>
#@gmicol : <b> -</b> <i>Aur&#233;lien Ceyden</i> <small>(packaging)</small>
#@gmicol : <b> -</b> <i>Fran&#231;ois Collard</i> <small>(testing)</small>
#@gmicol : <b> -</b> <i>Iain Fergusson</i> <small>(filters)</small>
#@gmicol : <b> -</b> <i>Roberto Ferramosca</i> <small>(packaging)</small>
#@gmicol : <b> -</b> <i>J&#233;rome Ferrari</i> <small>(testing, code &amp; tutorials)</small>
#@gmicol : <b> -</b> <i>S&#233;bastien Fourey</i> <small>(ZArt code &amp; G'MIC online)</small>
#@gmicol : <b> -</b> <i>Gentlemanbeggar</i> <small>(filters)</small>
#@gmicol : <b> -</b> <i>Claes Holmerson</i> <small>(tutorials)</small>
#@gmicol : <b> -</b> <i>Arto Huotari</i> <small>(filters)</small>
#@gmicol : <b> -</b> <i>Tom Keil</i> <small>(testing, filters &amp; tutorials)</small>
#@gmicol : <b> -</b> <i>Andy Kelday</i> <small>(testing &amp; filters)</small>
#@gmicol : <b> -</b> <i>Angelo Lama</i> <small>(testing &amp; EKD integration)</small>
#@gmicol : <b> -</b> <i>St&#233;phane de la Linuxerie</i> <small>(design)</small>
#@gmicol : <b> -</b> <i>Mark</i> <small>(translation)</small>
#@gmicol : <b> -</b> <i>PhotoComiX</i> <small>(testing, translation &amp; filters)</small>
#@gmicol : <b> -</b> <i>MareroQ</i> <small>(translation)</small>
#@gmicol : <b> -</b> <i>Mahvin</i> <small>(testing &amp; design)</small>
#@gmicol : <b> -</b> <i>Mauro Quercia</i> <small>(translation)</small>
#@gmicol : <b> -</b> <i>Guilherme Razgriz</i> <small>(translation)</small>
#@gmicol : <b> -</b> <i>Karsten Rodenacker</i> <small>(packaging &amp; code)</small>
#@gmicol : <b> -</b> <i>Dani Sard&#224;</i> <small>(translation)</small>
#@gmicol : <b> -</b> <i>Yuri Shemanin</i> <small>(debugging)</small>
#@gmicol : <b> -</b> <i>Stepanekos</i> <small>(translation)</small>
#@gmicol : <b> -</b> <i>Bernd Zeimetz</i> <small>(packaging)</small>
#@gmicol : <b> -</b>"}
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


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


#@gmicol Array [regular] : gimp_array, gimp_array_preview(1)
#@gmicol : X-tiles = int(2,1,10)
#@gmicol : Y-tiles = int(2,1,10)
#@gmicol : X-offset = float(0,0,100)
#@gmicol : Y-offset = float(0,0,100)
#@gmicol : Mirror = choice("None","X-axis","Y-axis","XY-axes")
#@gmicol : Size = _choice("Shrink", "Expand")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Array [faded] : gimp_array_fade, gimp_array_fade_preview(1)
#@gmicol : X-tiles = int(2,1,10)
#@gmicol : Y-tiles = int(2,1,10)
#@gmicol : X-offset = float(0,0,100)
#@gmicol : Y-offset = float(0,0,100)
#@gmicol : Fade start = float(80,1,100)
#@gmicol : Fade end = float(90,1,100)
#@gmicol : Mirror = choice("None","X-axis","Y-axis","XY-axes")
#@gmicol : Size = _choice("Shrink", "Expand")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Array [mirrored] : gimp_array_mirror, gimp_array_mirror_preview(1)
#@gmicol : Iterations = int(1,1,4)
#@gmicol : X-offset = float(0,0,100)
#@gmicol : Y-offset = float(0,0,100)
#@gmicol : Array mode = choice(2,"X-axis","Y-axis","XY-axes","2XY-axes")
#@gmicol : Initialization = choice("Original","Mirror X","Mirror Y","Rotate 90 deg.","Rotate 180 deg.","Rotate 270 deg.")
#@gmicol : Expand size = _bool(false)
#@gmicol : Crop = int(0,0,100)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Array [random] : array_random, array_random(1)
#@gmicol : Source X-tiles = int(5,1,20)
#@gmicol : Source Y-tiles = int(5,1,20)
#@gmicol : Destination X-tiles = int(7,1,20)
#@gmicol : Destination Y-tiles = int(7,1,20)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Array [random colors] : gimp_array_color, gimp_array_color(1)
#@gmicol : X-tiles = int(5,1,20)
#@gmicol : Y-tiles = int(5,1,20)
#@gmicol : Opacity = float(0.5,0,1)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Droste : gimp_droste, gimp_droste_preview(1)
#@gmicol : note = note("<span color=\"red\">Upper-left coordinates :</span>")
#@gmicol : X0 = float(20,0,100)
#@gmicol : Y0 = float(20,0,100)
#@gmicol : sep = separator(), note = note("<span color=\"magenta\">Upper-right coordinates :</span>")
#@gmicol : X1 = float(80,0,100)
#@gmicol : Y1 = float(20,0,100)
#@gmicol : sep = separator(), note = note("<span color=\"blue\">Lower-right coordinates :</span>")
#@gmicol : X2 = float(80,0,100)
#@gmicol : Y2 = float(80,0,100)
#@gmicol : sep = separator(), note = note("<span color=\"cyan\">Lower-left coordinates :</span>")
#@gmicol : X3 = float(20,0,100)
#@gmicol : Y3 = float(80,0,100)
#@gmicol : sep = separator()
#@gmicol : Iterations = int(1,1,4)
#@gmicol : X-shift = float(0,-100,100)
#@gmicol : Y-shift = float(0,-100,100)
#@gmicol : Angle = float(0,0,360)
#@gmicol : Zoom = float(1,0.1,5)
#@gmicol : Mirror = choice("None","X-axis","Y-axis","XY-axes")
#@gmicol : Borders = choice(1,"Black","Nearest","Repeat")
#@gmicol : Drawing mode = choice{"Replace","Replace (sharpest)","Behind","Below"}
#@gmicol : View outlines only = bool(0)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Frame [cube] : frame_cube, frame_cube(1)
#@gmicol : Depth = float(1,0,100)
#@gmicol : X-center = float(0,-2,2)
#@gmicol : Y-center = float(0,-2,2)
#@gmicol : Left side orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gmicol : Right side orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gmicol : Upper side orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gmicol : Lower sider orientation = choice("Normal","Mirror-X","Mirror-Y","Mirror-XY")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Frame [fuzzy] : gimp_frame_fuzzy, gimp_frame_fuzzy(0)
#@gmicol : Width = int(10,0,99)
#@gmicol : Height = int(10,0,99)
#@gmicol : Fuzzyness = float(10,0,40)
#@gmicol : Smoothness = float(1,0,5)
#@gmicol : Color = color(128,128,128,255)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Frame [painting] : gimp_frame_painting, gimp_frame_painting_preview(1)
#@gmicol : Size = float(10,0,100)
#@gmicol : Contrast = float(0.4,0,1)
#@gmicol : Smoothness = float(6,0,30)
#@gmicol : Color = color(225,200,120)
#@gmicol : sep = separator()
#@gmicol : Vignette size = float(2,0,50)
#@gmicol : Vignette contrast = float(400,0,1000)
#@gmicol : sep = separator()
#@gmicol : Defects contrast = float(50,0,512)
#@gmicol : Defects density = float(10,0,100)
#@gmicol : Defects size = float(1,0,10)
#@gmicol : Defects smoothness = float(0.5,0,20)
#@gmicol : sep = separator()
#@gmicol : Serial number = int(123456,0,1000000)
#@gmicol : Frame as a new layer = _bool(false)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Frame [pattern] : gmicol_frame_pattern, gmicol_frame_pattern_preview(1)
#@gmicol : Tiles = int(10,3,30)
#@gmicol : Iterations = int(1,1,4)
#@gmicol : Constrain image size = _bool(1)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")
gmicol_frame_pattern :
  -gimp_frame_pattern $1,1,${2--1}

gmicol_frame_pattern_preview :
  -gimp_frame_pattern_preview $1,1,${2--1}

#@gmicol Frame [regular] : gimp_frame, gimp_frame(1)
#@gmicol : note = note("<b>Crop parameters :</b>")
#@gmicol : X-start = int(0,0,100)
#@gmicol : X-end = int(100,0,100)
#@gmicol : Y-start = int(0,0,100)
#@gmicol : Y-end = int(100,0,100)
#@gmicol : sep = separator(), note = note("<b>Frame parameters :</b>")
#@gmicol : Width = int(10,0,100)
#@gmicol : Height = int(10,0,100)
#@gmicol : Color = color(0,0,0,255)
#@gmicol : Outline size = int(1,0,100)
#@gmicol : Outline color = color(255,255,255,255)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Frame [round] : gimp_frame_round, gimp_frame_round(1)
#@gmicol : Sharpness = float(6,0.1,40)
#@gmicol : Size = float(20,0,100)
#@gmicol : Smoothness = float(0.1,0,15)
#@gmicol : Shade = float(0,0,1)
#@gmicol : Color = color(128,128,128,255)
#@gmicol : Blur frame = float(0,0,100)
#@gmicol : Blur shade = float(0.1,0,1)
#@gmicol : Blur amplitude = float(3,0,10)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Grid : gimp_imagegrid, gimp_imagegrid(0)
#@gmicol : X-size = int(10,2,100)
#@gmicol : Y-size = int(10,2,100)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Random pattern : gimp_array_pattern, gimp_array_pattern_preview(1)
#@gmicol : X-tiles = int(10,1,30)
#@gmicol : Y-tiles = int(10,1,30)
#@gmicol : Density = float(80,0,100)
#@gmicol : Angle = float(180,0,180)
#@gmicol : Zoom = float(30,0,100)
#@gmicol : Opacity = float(1,0,1)
#@gmicol : Image size = _choice("Shrink", "Expand")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Taquin : taquin, taquin(1)
#@gmicol : X-tiles = int(7,1,20)
#@gmicol : Y-tiles = int(7,1,20)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Tileable rotation : gimp_rotate_tileable, gimp_rotate_tileable(1)
#@gmicol : Angle = float(45,0,360)
#@gmicol : Maximum size factor = int(8,0,20)
#@gmicol : Array mode = choice(0,"None","X-axis","Y-axis","XY-axes","2XY-axes")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Tiled rotation : gimp_rotate_tiles, gimp_rotate_tiles(1)
#@gmicol : X-tiles = int(5,1,80)
#@gmicol : Y-tiles = int(5,1,80)
#@gmicol : Angle = float(15,0,360)
#@gmicol : X-shadow = float(3,-20,20)
#@gmicol : Y-shadow = float(3,-20,20)
#@gmicol : Smoothness = float(1.8,0,5)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Tiled normalization : gimp_normalize_tiles, gimp_normalize_tiles(1)
#@gmicol : X-tiles = int(25,1,80)
#@gmicol : Y-tiles = int(25,1,80)
#@gmicol : Minimal value = float(0,0,255)
#@gmicol : Maximal value = float(255,0,255)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Tiled random shifts : gimp_shift_tiles, gimp_shift_tiles(1)
#@gmicol : X-tiles = int(10,1,30)
#@gmicol : Y-tiles = int(10,1,30)
#@gmicol : Amplitude = float(10,0,100)
#@gmicol : Opacity = float(1,0,1)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Tiled parameterization : gimp_parameterize_tiles, gimp_parameterize_tiles(1)
#@gmicol : X-tiles = int(10,1,30)
#@gmicol : Y-tiles = int(10,1,30)
#@gmicol : Fitting function = choice("Linear","Quadratic")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Tiled isolation : gimp_isolate_tiles, gimp_isolate_tiles(0)
#@gmicol : X-size = float(10,0,100)
#@gmicol : Y-size = float(10,0,100)
#@gmicol : X-border = float(5,0,100)
#@gmicol : Y-border = float(5,0,100)
#@gmicol : Keep tiles square = bool(1)
#@gmicol : Keep borders square = bool(1)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Tunnel : gimp_tunnel, gimp_tunnel(1)
#@gmicol : Depth = int(4,1,100)
#@gmicol : Factor = float(80,1,99)
#@gmicol : X-center = float(0.5,0,1)
#@gmicol : Y-center = float(0.5,0,1)
#@gmicol : Opacity = float(0.2,0,1)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


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


#@gmicol Cartoon : cartoon, gimp_cartoon_preview(0)
#@gmicol : Smoothness = float(3,0,10)
#@gmicol : Sharpening = float(80,0,400)
#@gmicol : Edge threshold = float(20,1,30)
#@gmicol : Edge thickness = float(0.25,0,1)
#@gmicol : Color strength = float(1.5,0,3)
#@gmicol : Color quantization = int(8,2,256)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Cubism : cubism, cubism(1)
#@gmicol : Iterations = int(300,1,1000)
#@gmicol : Bloc size = float(10,0,40)
#@gmicol : Angle = float(90,0,360)
#@gmicol : Opacity = float(0.7,0.01,1)
#@gmicol : Smoothness = float(0,0,5)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Ellipsionism : gimp_ellipsionism, gimp_ellipsionism_preview(0)
#@gmicol : Primary radius = float(20,1,100)
#@gmicol : Secondary radius = float(10,1,100)
#@gmicol : Smoothness = float(0.5,0,10)
#@gmicol : Opacity = float(0.7,0,1)
#@gmicol : Outline = float(8,1,3)
#@gmicol : Density = float(0.5,0.1,2)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Kaleidoscope : gimp_kaleidoscope, gimp_kaleidoscope(1)
#@gmicol : X-center = float(0.5,0,1)
#@gmicol : Y-center = float(0.5,0,1)
#@gmicol : X-offset = float(0,0,100)
#@gmicol : Y-offset = float(0,0,100)
#@gmicol : Radius cut = float(100,0,100)
#@gmicol : Angle cut = float(10,0,100)
#@gmicol : Borders = choice(2,"Black","Nearest","Repeat")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Kuwahara : gimp_kuwahara, gimp_kuwahara_preview(0)
#@gmicol : Iterations = int(2,1,8)
#@gmicol : Radius = int(5,1,30)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Lylejk's painting : gimp_lylejk_painting, gimp_lylejk_painting_preview(0)
#@gmicol : Iterations = int(2,1,8)
#@gmicol : Radius = int(4,1,30)
#@gmicol : Canvas = float(10,0,100)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Authors : <i>Lyle Kroll, David Tschumperl&#233;</i>.      Latest update: <i>2011/09/21</i>.</small>")
#@gmicol : note = link("Filter Explained here","http://www.gimpchat.com/viewtopic.php?f=10&t=2624")

#@gmicol Old photograph : old_photo, old_photo(1)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Painting : gimp_painting, gimp_painting_preview(0)
#@gmicol : Abstraction = int(5,1,10)
#@gmicol : Details scale = float(2.5,0,5)
#@gmicol : Color = float(1.5,0,4)
#@gmicol : Smoothness = float(50,0,1000)
#@gmicol : Sharpen shades = bool(1)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Authors : <i>Lyle Kroll, Angelo Lama, David Tschumperl&#233;</i>.\nLatest update: <i>2011/02/28</i>.</small>")

#@gmicol Pen drawing : gimp_pen_drawing, gimp_pen_drawing_preview(0)
#@gmicol : Amplitude = float(10,0,30)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Polaroid : gimp_polaroid, gimp_polaroid(1)
#@gmicol : Frame size = int(10,0,400)
#@gmicol : Bottom size = int(20,0,400)
#@gmicol : X-shadow = float(0,-20,20)
#@gmicol : Y-shadow = float(0,-20,20)
#@gmicol : Smoothness = float(3,0,5)
#@gmicol : Angle = float(20,-180,180)
#@gmicol : Vignette strength = float(50,0,255)
#@gmicol : Vignette min radius = float(70,0,100)
#@gmicol : Vignette max radius = float(95,0,100)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Random color ellipses : gimp_color_ellipses, gimp_color_ellipses(1)
#@gmicol : Density = int(400,0,3000)
#@gmicol : Radius = float(8,0,30)
#@gmicol : Opacity = float(0.1,0.01,0.5)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Reflection : gimp_reflect, gimp_reflect(1)
#@gmicol : Height = float(50,0,100)
#@gmicol : Attenuation = float(1,0.1,4)
#@gmicol : Color = color(110,160,190,64)
#@gmicol : Waves amplitude = float(0,0,100)
#@gmicol : Waves smoothness = float(1.5,0,4)
#@gmicol : X-angle = float(0,-10,10)
#@gmicol : Y-angle = float(-3.30,-10,10)
#@gmicol : Focale = float(7,0,10)
#@gmicol : Zoom = float(1.5,1,5)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Rodilius : gimp_rodilius, gimp_rodilius_preview(1)
#@gmicol : Amplitude = float(10,0,30)
#@gmicol : Thickness = float(10,0,100)
#@gmicol : Sharpness = float(300,0,1000)
#@gmicol : Orientations = int(5,2,36)
#@gmicol : Offset = float(30,0,180)
#@gmicol : Color mode = choice(1,"Darker","Lighter")
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Authors : <i>Rod/GimpChat, David Tschumperl&#233;</i>.      Latest update: <i>2011/09/28</i>.</small>")

#@gmicol Rotoidoscope : gimp_rotoidoscope, gimp_rotoidoscope(1)
#@gmicol : X-center = float(0.5,0,1)
#@gmicol : Y-center = float(0.5,0,1)
#@gmicol : Angular tiles = int(10,1,72)
#@gmicol : Smoothness = float(0.5,0,5)
#@gmicol : Borders = choice(2,"Black","Nearest","Repeat")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Soft glow : gimp_glow, gimp_glow_preview(0)
#@gmicol : Amplitude = float(6,0,20)
#@gmicol : note = note()
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Tetris effect : gimp_tetris, gimp_tetris(0)
#@gmicol : Scale = int(10,1,20)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Warhol : warhol, warhol(1)
#@gmicol : X-tiles = int(3,1,10)
#@gmicol : Y-tiles = int(3,1,10)
#@gmicol : Smoothness = float(2,0,10)
#@gmicol : Color = float(40,0,60)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Whirl drawing : draw_whirl, gimp_draw_whirl_preview(0)
#@gmicol : Amplitude = float(20,0,100)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


#@gmicol _<b>Black &amp; white</b>
#--------------------------------


#@gmicol Black &amp; White : gimp_blackandwhite, gimp_blackandwhite_preview(1)
#@gmicol : Red level = float(0.299,0,1)
#@gmicol : Red smoothness = float(0,0,10)
#@gmicol : Green level = float(0.587,0,1)
#@gmicol : Green smoothness = float(0,0,10)
#@gmicol : Blue level = float(0.114,0,1)
#@gmicol : Blue smoothness = float(0,0,10)
#@gmicol : sep = separator()
#@gmicol : Gamma = float(1,0.01,5)
#@gmicol : Contrast = float(1,0,4)
#@gmicol : Brightness = float(0,-255,255)
#@gmicol : Hue = float(0,0,360)
#@gmicol : Saturation = float(0,0,1)
#@gmicol : sep = separator()
#@gmicol : Grain (shadows) = float(0,0,200)
#@gmicol : Grain (midtones) = float(0,0,200)
#@gmicol : Grain (highlights) = float(0,0,200)
#@gmicol : Grain tone fading = float(2,0,10)
#@gmicol : Grain scale = float(0,0,3)
#@gmicol : Grain type = choice("Gaussian","Uniform","Salt and pepper","Poisson")
#@gmicol : sep = separator()
#@gmicol : Local contrast = float(0,0,60)
#@gmicol : Radius = int(16,1,512)
#@gmicol : Contrast smoothness = float(4,0,10)
#@gmicol : sep = separator()
#@gmicol : Pseudo-gray dithering = int(0,0,20)
#@gmicol : Use maximum tones = bool(false)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Charcoal : gimp_charcoal, gimp_charcoal_preview(0)
#@gmicol : Granularity = int(65,0,800)
#@gmicol : Lowlights crossover point = int(70,0,255)
#@gmicol : Highlights crossover point = int(170,0,255)
#@gmicol : Boost contrast = bool(0)
#@gmicol : Resize image for optimum effect = bool(1)
#@gmicol : Add chalk highlights = bool(0)
#@gmicol : Minimal highlights = int(50,0,255)
#@gmicol : Maximal highlights = int(70,0,255)
#@gmicol : Background color = color(255,255,255)
#@gmicol : Foreground color = color(0,0,0)
#@gmicol : Invert background/foreground = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")
#@gmicol : note = note("<small>Inspired from the Charcoal script by <i>micomicon</i> :</small>")
#@gmicol : link = link("http://registry.gimp.org/node/25078")

#@gmicol Dithering : gimp_ditheredbw, gimp_ditheredbw_preview(0)
#@gmicol : Gamma = float(1,0.01,5)
#@gmicol : Contrast = float(1,0,4)
#@gmicol : Brightness = float(0,-255,255)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Hard sketch : gimp_hardsketchbw, gimp_hardsketchbw_preview(0)
#@gmicol : Amplitude = float(300,0,4000)
#@gmicol : Density = float(50,0,100)
#@gmicol : Smoothness = float(1,0,10)
#@gmicol : Opacity = float(0.1,0,1)
#@gmicol : Edge = float(20,0,100)
#@gmicol : Fast approximation = bool(1)
#@gmicol : Negative = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Hough sketch : gimp_houghsketchbw, gimp_houghsketchbw_preview(0)
#@gmicol : Smoothness = float(1.25,0,10)
#@gmicol : Density = float(50,0,70)
#@gmicol : Radius = int(5,0,30)
#@gmicol : Threshold = float(80,0,100)
#@gmicol : Opacity = float(0.1,0,1)
#@gmicol : Negative = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Ink wash : gimp_ink_wash, gimp_ink_wash(0)
#@gmicol : note = note("Ink wash controls")
#@gmicol : Size = float(0.14,0,4)
#@gmicol : Amplitude = float(23,0,200)
#@gmicol : sep = separator()
#@gmicol : note = note("Check if you wish visual control on this step")
#@gmicol : SKIP all other steps = bool(false)
#@gmicol : note = note ("UNcheck to reactivate the other controls")
#@gmicol : sep = separator()
#@gmicol : Smoother Sharpness = float(0.5,0,2)
#@gmicol : Smoother Edge Protection = float(0.54,0,1)
#@gmicol : Smoother Softness = float(2.25,0,10)
#@gmicol : sep = separator()
#@gmicol : Stretch Contrast = choice("None","Automatic","Automatic & Contrast Mask","Manual Controls")
#@gmicol : note = note ("To activate the sliders below chose 'Manual Controls'")
#@gmicol :sep = separator ()
#@gmicol : LN Amplititude = float(2,0,60)
#@gmicol : LN Size = float(6,0,64)
#@gmicol : LN Neightborhood-Smoothness = float(5,0,40)
#@gmicol : LN Average-Smoothness = float(20,0,40)
#@gmicol : sep = separator(), note = note("<small>Author : <i>PhotoComiX</i>.      Latest update: <i>2011/4/5</i>.</small>")
#@gmicol : note = link(0,"Forum thread about the filter discussion","http://gimpchat.com/viewtopic.php?f=10&t=914")

#@gmicol Pencil : gimp_pencilbw, gimp_pencilbw_preview(0)
#@gmicol : Size = float(0.3,0,5)
#@gmicol : Amplitude = float(60,0,200)
#@gmicol : Hue = float(0,0,360)
#@gmicol : Saturation = float(0,0,1)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Sketch : gimp_sketchbw, gimp_sketchbw_preview(0)
#@gmicol : Number of orientations = int(2,1,16)
#@gmicol : Starting angle = float(45,0,180)
#@gmicol : Angle range = float(180,0,180)
#@gmicol : Stroke length = float(30,0,1000)
#@gmicol : Contour threshold = float(1,0,3)
#@gmicol : Opacity = float(0.03,0,0.3)
#@gmicol : Background intensity = float(0,0,2)
#@gmicol : Density = float(0.6,0,5)
#@gmicol : Sharpness = float(0.1,0,1.5)
#@gmicol : Anisotropy = float(0.6,0,1)
#@gmicol : Smoothness = float(0.25,0,10)
#@gmicol : Coherence = float(1,0,10)
#@gmicol : Boost stroke = bool(0)
#@gmicol : Curved stroke = bool(1)
#@gmicol : Color model = choice("Black on white","White on black","Black on transparent white","White on transparent black")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Stamp : gimp_stamp, gimp_stamp_preview(0)
#@gmicol : Auto-threshold = bool(1)
#@gmicol : Threshold = int(50,0,100)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Sharpening = float(0,0,30)
#@gmicol : Grain = float(0,0,100)
#@gmicol : Invert colors = bool(false)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Authors : <i>Antaron, Mahvin, David Tschumperl&#233;</i>.             Latest update: 2011/05/17.</small>")

#@gmicol Stencil : gimp_stencilbw, gimp_stencilbw_preview(0)
#@gmicol : Threshold = float(10,0,30)
#@gmicol : Smoothness = float(10,0,30)
#@gmicol : Hue = float(0,0,360)
#@gmicol : Saturation = float(0,0,1)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


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


#@gmicol Abstraction : gimp_color_abstraction, gimp_color_abstraction_preview(0)
#@gmicol : Smoothness = float(1,0,10)
#@gmicol : Levels = int(10,2,255)
#@gmicol : Contrast = float(0.2,0.01,1)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol B&amp;W recolorize : gimp_bwrecolorize, gimp_bwrecolorize_preview
#@gmicol : Gamma = float(1,0.01,5)
#@gmicol : Contrast = float(1,0,4)
#@gmicol : Brightness = float(0,-255,255)
#@gmicol : Normalize = bool(0)
#@gmicol : sep = separator()
#@gmicol : Gradient preset = choice("User-defined","Black to white","White to black","Sepia","Solarize")
#@gmicol : Interpolation type = choice(1,"Nearest","Linear","Cubic","Lanczos")
#@gmicol : Preserve initial brightness = bool(0)
#@gmicol : sep = separator(), note = note("<small><u>User-defined gradient :</u></small>")
#@gmicol : Number of tones = int(5,2,8)
#@gmicol : 1st tone = color(0,0,0,255)
#@gmicol : 2nd tone = color(43,25,55,255)
#@gmicol : 3rd tone = color(158,137,189,255)
#@gmicol : 4th tone = color(224,191,228,255)
#@gmicol : 5th tone = color(255,255,255,255)
#@gmicol : 6th tone = color(255,255,255,255)
#@gmicol : 7th tone = color(255,255,255,255)
#@gmicol : 8th tone = color(255,255,255,255)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Boost / Fade : gimp_boost_fade, gimp_boost_fade_preview
#@gmicol : Amplitude = float(5,0,10)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Channel processing : gimp_channel_processing, gimp_channel_processing_preview(1)
#@gmicol : Gamma = float(1,0.01,5)
#@gmicol : Contrast = float(1,0,4)
#@gmicol : Brightness = float(0,-255,255)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Value action = choice("None","Cut","Cut & Normalize","Normalize","Threshold")
#@gmicol : Low value = float(0,0,100)
#@gmicol : High value = float(100,0,100)
#@gmicol : Quantization = int(256,1,256)
#@gmicol : Equalization = bool()
#@gmicol : Negation = bool()
#@gmicol : note = note()
#@gmicol : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gmicol : Tones smoothness = float(2,0,10)
#@gmicol : note = note()
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Color balance : gimp_balance_gamma, gimp_balance_gamma_preview
#@gmicol : Neutral color = color(128,128,128)
#@gmicol : Stretch colors = bool(1)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Colormap : gimp_colormap,gimp_colormap_preview
#@gmicol : Colormap = choice[1,"Adaptive","Custom","Standard (256)","HSV (256)","Lines (256)","Hot (256)","Cool (256)","Jet (256)","Flag (256)","Cube (256)"]
#@gmicol : Dithering = float(1,0,1)
#@gmicol : sep = separator(), note = note("<small><i>For adaptive and custom colormaps only :</i></small>")
#@gmicol : Number of tones = int(32,2,256)
#@gmicol : sep = separator(), note = note("<small><i>For custom colormaps only :</i></small>")
#@gmicol : Number of colors = int(8,2,8)
#@gmicol : 1st color = color(0,0,0)
#@gmicol : 2nd color = color(255,255,255)
#@gmicol : 3rd color = color(255,0,0)
#@gmicol : 4th color = color(0,255,0)
#@gmicol : 5th color = color(0,0,255)
#@gmicol : 6th color = color(255,255,0)
#@gmicol : 7th color = color(255,0,255)
#@gmicol : 8th color = color(0,255,255)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Curves : gimp_apply_curve, gimp_apply_curve_preview
#@gmicol : Starting Y = int(0,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(1) = int(-1,-1,255)
#@gmicol : Y-coord(1) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(2) = int(-1,-1,255)
#@gmicol : Y-coord(2) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(3) = int(-1,-1,255)
#@gmicol : Y-coord(3) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(4) = int(-1,-1,255)
#@gmicol : Y-coord(4) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(5) = int(-1,-1,255)
#@gmicol : Y-coord(5) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : Ending Y = int(255,0,255)
#@gmicol : sep = separator()
#@gmicol : Curve smoothness = float(1,0,1)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : Value range = choice("Cut","Normalize")
#@gmicol : Display histogram = float(0,0,1)
#@gmicol : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Curves [RGB]
#@gmicol Red : gimp_apply_RGBcurve, gimp_apply_Rcurve_preview
#@gmicol : Starting Y = int(0,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(1) = int(-1,-1,255)
#@gmicol : Y-coord(1) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(2) = int(-1,-1,255)
#@gmicol : Y-coord(2) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(3) = int(-1,-1,255)
#@gmicol : Y-coord(3) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(4) = int(-1,-1,255)
#@gmicol : Y-coord(4) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(5) = int(-1,-1,255)
#@gmicol : Y-coord(5) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : Ending Y = int(255,0,255)
#@gmicol : sep = separator()
#@gmicol : Curve smoothness = float(1,0,1)
#@gmicol : Display histogram = float(0,0,100)
#@gmicol : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Green : gimp_apply_RGBcurve, gimp_apply_Gcurve_preview
#@gmicol : Starting Y = int(0,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(1) = int(-1,-1,255)
#@gmicol : Y-coord(1) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(2) = int(-1,-1,255)
#@gmicol : Y-coord(2) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(3) = int(-1,-1,255)
#@gmicol : Y-coord(3) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(4) = int(-1,-1,255)
#@gmicol : Y-coord(4) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(5) = int(-1,-1,255)
#@gmicol : Y-coord(5) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : Ending Y = int(255,0,255)
#@gmicol : sep = separator()
#@gmicol : Curve smoothness = float(1,0,1)
#@gmicol : Display histogram = float(0,0,100)
#@gmicol : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Blue : gimp_apply_RGBcurve, gimp_apply_Bcurve_preview
#@gmicol : Starting Y = int(0,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(1) = int(-1,-1,255)
#@gmicol : Y-coord(1) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(2) = int(-1,-1,255)
#@gmicol : Y-coord(2) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(3) = int(-1,-1,255)
#@gmicol : Y-coord(3) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(4) = int(-1,-1,255)
#@gmicol : Y-coord(4) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(5) = int(-1,-1,255)
#@gmicol : Y-coord(5) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : Ending Y = int(255,0,255)
#@gmicol : sep = separator()
#@gmicol : Curve smoothness = float(1,0,1)
#@gmicol : Display histogram = float(0,0,100)
#@gmicol : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")
#@gmicol _

#@gmicol Curves [YCbCr]
#@gmicol Luminance : gimp_apply_YCbCrcurve, gimp_apply_Ycurve_preview
#@gmicol : Starting Y = int(0,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(1) = int(-1,-1,255)
#@gmicol : Y-coord(1) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(2) = int(-1,-1,255)
#@gmicol : Y-coord(2) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(3) = int(-1,-1,255)
#@gmicol : Y-coord(3) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(4) = int(-1,-1,255)
#@gmicol : Y-coord(4) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(5) = int(-1,-1,255)
#@gmicol : Y-coord(5) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : Ending Y = int(255,0,255)
#@gmicol : sep = separator()
#@gmicol : Curve smoothness = float(1,0,1)
#@gmicol : Display histogram = float(0,0,100)
#@gmicol : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Blue chrominance : gimp_apply_YCbCrcurve, gimp_apply_Cbcurve_preview
#@gmicol : Starting Y = int(0,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(1) = int(-1,-1,255)
#@gmicol : Y-coord(1) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(2) = int(-1,-1,255)
#@gmicol : Y-coord(2) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(3) = int(-1,-1,255)
#@gmicol : Y-coord(3) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(4) = int(-1,-1,255)
#@gmicol : Y-coord(4) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(5) = int(-1,-1,255)
#@gmicol : Y-coord(5) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : Ending Y = int(255,0,255)
#@gmicol : sep = separator()
#@gmicol : Curve smoothness = float(1,0,1)
#@gmicol : Display histogram = float(0,0,100)
#@gmicol : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Red Chrominance : gimp_apply_YCbCrcurve, gimp_apply_Crcurve_preview
#@gmicol : Starting Y = int(0,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(1) = int(-1,-1,255)
#@gmicol : Y-coord(1) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(2) = int(-1,-1,255)
#@gmicol : Y-coord(2) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(3) = int(-1,-1,255)
#@gmicol : Y-coord(3) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(4) = int(-1,-1,255)
#@gmicol : Y-coord(4) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(5) = int(-1,-1,255)
#@gmicol : Y-coord(5) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : Ending Y = int(255,0,255)
#@gmicol : sep = separator()
#@gmicol : Curve smoothness = float(1,0,1)
#@gmicol : Display histogram = float(0,0,100)
#@gmicol : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")
#@gmicol _

#@gmicol Curves [Lab]
#@gmicol Lightness : gimp_apply_Labcurve, gimp_apply_Lcurve_preview
#@gmicol : Starting Y = int(0,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(1) = int(-1,-1,255)
#@gmicol : Y-coord(1) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(2) = int(-1,-1,255)
#@gmicol : Y-coord(2) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(3) = int(-1,-1,255)
#@gmicol : Y-coord(3) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(4) = int(-1,-1,255)
#@gmicol : Y-coord(4) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(5) = int(-1,-1,255)
#@gmicol : Y-coord(5) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : Ending Y = int(255,0,255)
#@gmicol : sep = separator()
#@gmicol : Curve smoothness = float(1,0,1)
#@gmicol : Display histogram = float(0,0,100)
#@gmicol : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol A-color : gimp_apply_Labcurve, gimp_apply_acurve_preview
#@gmicol : Starting Y = int(0,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(1) = int(-1,-1,255)
#@gmicol : Y-coord(1) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(2) = int(-1,-1,255)
#@gmicol : Y-coord(2) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(3) = int(-1,-1,255)
#@gmicol : Y-coord(3) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(4) = int(-1,-1,255)
#@gmicol : Y-coord(4) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(5) = int(-1,-1,255)
#@gmicol : Y-coord(5) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : Ending Y = int(255,0,255)
#@gmicol : sep = separator()
#@gmicol : Curve smoothness = float(1,0,1)
#@gmicol : Display histogram = float(0,0,100)
#@gmicol : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol B-color : gimp_apply_Labcurve, gimp_apply_bcurve_preview
#@gmicol : Starting Y = int(0,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(1) = int(-1,-1,255)
#@gmicol : Y-coord(1) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(2) = int(-1,-1,255)
#@gmicol : Y-coord(2) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(3) = int(-1,-1,255)
#@gmicol : Y-coord(3) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(4) = int(-1,-1,255)
#@gmicol : Y-coord(4) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : X-coord(5) = int(-1,-1,255)
#@gmicol : Y-coord(5) = int(128,0,255)
#@gmicol : sep = separator()
#@gmicol : Ending Y = int(255,0,255)
#@gmicol : sep = separator()
#@gmicol : Curve smoothness = float(1,0,1)
#@gmicol : Display histogram = float(0,0,100)
#@gmicol : Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")
#@gmicol _

#@gmicol Decompose channels : gimp_decompose_channels, gimp_decompose_channels_preview
#@gmicol : Color basis = choice(7,"RGB","HSV","HSL","HSI","YUV","YCbCr","XYZ","Lab","Lch","CMY","CMYK")
#@gmicol : Action = choice("Decompose","Recompose")
#@gmicol : Use multiple layers = bool(0)
#@gmicol : Include opacity layer = bool(1)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Discrete color square: gimp_colorsquare, gimp_colorsquare
#@gmicol : a = color(0,0,0)
#@gmicol : b = color(255,255,255)
#@gmicol : c = color(128,255,192)
#@gmicol : d = color(80,128,255)
#@gmicol : Colorspace = choice("LCH","LAB","YCbCr","RGB")
#@gmicol : sep = separator()
#@gmicol : Quantization = int(256,2,256)
#@gmicol : Disable quantization = bool(0)
#@gmicol : Clip high end = bool(0)
#@gmicol : Steps = int(5,3,32)
#@gmicol : Scale = int(36,1,96)
#@gmicol : sep = separator(), note = note("<small>Author : <i>Noun0ion9</i>.      Latest update: <i>2011/05/18</i>.</small>")

#@gmicol Equalize HSV : gimp_hsv_equalizer, gimp_hsv_equalizer_preview
#@gmicol : Preview bands = bool(false)
#@gmicol : sep = separator()
#@gmicol : Hue band = float(180,0,360)
#@gmicol : Band width = float(40,1,360)
#@gmicol : Hue shift = float(0,-180,180)
#@gmicol : Saturation correction = float(0,-0.99,0.99)
#@gmicol : Value correction = float(0,-0.99,0.99)
#@gmicol : sep = separator()
#@gmicol : Hue band = float(180,0,360)
#@gmicol : Band width = float(40,1,360)
#@gmicol : Hue shift = float(0,-180,180)
#@gmicol : Saturation correction = float(0,-0.99,0.99)
#@gmicol : Value correction = float(0,-0.99,0.99)
#@gmicol : sep = separator()
#@gmicol : Hue band = float(180,0,360)
#@gmicol : Band width = float(40,1,360)
#@gmicol : Hue shift = float(0,-180,180)
#@gmicol : Saturation correction = float(0,-0.99,0.99)
#@gmicol : Value correction = float(0,-0.99,0.99)
#@gmicol : sep = separator()
#@gmicol : note = note("<small>Author : <i>J&#233;rome Ferrari</i>.      Latest update: <i>2011/01/14</i>.</small>")
#@gmicol : note = link("Filter explained here","http://www.flickr.com/groups/gmic/discuss/72157625798533482")

#@gmicol Gradient [corners] : gimp_corner_gradient, gimp_corner_gradient
#@gmicol : Color 1 (up/left corner) = color(255,255,255,128)
#@gmicol : Color 2 (up/right corner) = color(255,0,0,255)
#@gmicol : Color 3 (bottom/left corner) = color(0,255,0,255)
#@gmicol : Color 4 (bottom/right corner) = color(0,0,255,255)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Gradient [linear] : gimp_linear_gradient, gimp_linear_gradient
#@gmicol : Starting color = color(0,0,0,255)
#@gmicol : Ending color = color(255,255,255,255)
#@gmicol : Swap colors = bool(0)
#@gmicol : Angle = float(45,0,360)
#@gmicol : Fade start = float(0,0,100)
#@gmicol : Fade end = float(100,0,100)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Gradient [radial] : gimp_radial_gradient, gimp_radial_gradient
#@gmicol : Starting color = color(0,0,0,255)
#@gmicol : Ending color = color(255,255,255,255)
#@gmicol : Swap colors = bool(0)
#@gmicol : Fade start = float(0,0,100)
#@gmicol : Fade end = float(100,0,100)
#@gmicol : X-center = float(50,0,100)
#@gmicol : Y-center = float(50,0,100)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Local normalization : gimp_normalize_local, gimp_normalize_local_preview(0)
#@gmicol : Amplitude = float(2,0,60)
#@gmicol : Radius = int(6,1,64)
#@gmicol : Neighborhood smoothness = float(5,0,40)
#@gmicol : Average smoothness = float(20,0,40)
#@gmicol : Constrain values = bool(1)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Lomo : gimp_lomo, gimp_lomo_preview
#@gmicol : Vignette size = float(20,0,100)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Authors : <i>J&#233;rome Boulanger, David Tschumperl&#233;</i>.      Latest update: <i>2012/06/06</i>.</small>")

#@gmicol Mixer [RGB] : gimp_mix_rgb, gimp_mix_rgb_preview(1)
#@gmicol : Red contrast = float(1,0,4)
#@gmicol : Red brightness = float(0,-255,255)
#@gmicol : Red smoothness = float(0,0,10)
#@gmicol : Green contrast = float(1,0,4)
#@gmicol : Green brightness = float(0,-255,255)
#@gmicol : Green smoothness = float(0,0,10)
#@gmicol : Blue contrast = float(1,0,4)
#@gmicol : Blue brightness = float(0,-255,255)
#@gmicol : Blue smoothness = float(0,0,10)
#@gmicol : note = note()
#@gmicol : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gmicol : Tones smoothness = float(2,0,10)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Mixer [YCbCr] : gimp_mix_ycbcr, gimp_mix_ycbcr_preview(1)
#@gmicol : Luminance contrast = float(1,0,4)
#@gmicol : Luminance brightness = float(0,-255,255)
#@gmicol : Luminance smoothness = float(0,0,10)
#@gmicol : Blue chroma contrast = float(1,0,4)
#@gmicol : Blue chroma brightness = float(0,-255,255)
#@gmicol : Blue chroma smoothness = float(0,0,10)
#@gmicol : Red chroma contrast = float(1,0,4)
#@gmicol : Red chroma brightness = float(0,-255,255)
#@gmicol : Red chroma smoothness = float(0,0,10)
#@gmicol : note = note()
#@gmicol : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gmicol : Tones smoothness = float(2,0,10)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Mixer [HSV] : gimp_mix_hsv, gimp_mix_hsv_preview(1)
#@gmicol : Hue contrast = float(1,0,4)
#@gmicol : Hue brightness = float(0,-180,180)
#@gmicol : Hue smoothness = float(0,0,10)
#@gmicol : Saturation contrast = float(1,0,4)
#@gmicol : Saturation brightness = float(0,-1,1)
#@gmicol : Saturation smoothness = float(0,0,10)
#@gmicol : Value contrast = float(1,0,4)
#@gmicol : Value brightness = float(0,-1,1)
#@gmicol : Value smoothness = float(0,0,10)
#@gmicol : note = note()
#@gmicol : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gmicol : Tones smoothness = float(2,0,10)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Mixer [Lab] : gimp_mix_lab, gimp_mix_lab_preview(1)
#@gmicol : Lightness contrast = float(1,0.5,1.5)
#@gmicol : Lightness brightness = float(0,-50,50)
#@gmicol : Lightness smoothness = float(0,0,10)
#@gmicol : A-color contrast = float(1,0,4)
#@gmicol : A-color brightness = float(0,-20,20)
#@gmicol : A-color smoothness = float(0,0,10)
#@gmicol : B-color contrast = float(1,0,4)
#@gmicol : B-color brightness = float(0,-20,20)
#@gmicol : B-color smoothness = float(0,0,10)
#@gmicol : note = note()
#@gmicol : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gmicol : Tones smoothness = float(2,0,10)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Mixer [CMYK] : gimp_mix_cmyk, gimp_mix_cmyk_preview(1)
#@gmicol : Cyan contrast = float(1,0,4)
#@gmicol : Cyan brightness = float(0,-255,255)
#@gmicol : Cyan smoothness = float(0,0,10)
#@gmicol : Magenta contrast = float(1,0,4)
#@gmicol : Magenta brightness = float(0,-255,255)
#@gmicol : Magenta smoothness = float(0,0,10)
#@gmicol : Yellow contrast = float(1,0,4)
#@gmicol : Yellow brightness = float(0,-255,255)
#@gmicol : Yellow smoothness = float(0,0,10)
#@gmicol : Key contrast = float(1,0,4)
#@gmicol : Key brightness = float(0,-255,255)
#@gmicol : Key smoothness = float(0,0,10)
#@gmicol : note = note()
#@gmicol : Tones range = choice("All tones","Shadows","Mid-tones","Highlights")
#@gmicol : Tones smoothness = float(2,0,10)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Replace color : gimp_replace_color, gimp_replace_color(0)
#@gmicol : Tolerance = float(100,1,450)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Selected color = color(255,255,255,255)
#@gmicol : Replaced color = color(0,0,0,0)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Select color : gimp_select_color, gimp_select_color(1)
#@gmicol : Similarity space = choice(0,"RGB[A]","RGB","YCbCr","Red","Green","Blue","Opacity","Luminance","Blue & Red chrominances","Hue","Saturation")
#@gmicol : Tolerance = float(20,0,100)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Selected color = color(255,255,255,255)
#@gmicol : Output as = choice(0,"Selected colors","Selected mask")
#@gmicol : Invert selection = bool(0)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Sepia : gimp_sepia, gimp_sepia_preview
#@gmicol : Gamma = float(1,0.01,5)
#@gmicol : Contrast = float(1,0,4)
#@gmicol : Brightness = float(0,-255,255)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Split tones : gimp_split_tones, gimp_split_tones_preview(0)
#@gmicol : Number of tones = int(3,2,10)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Tone mapping : gimp_map_tones, gimp_map_tones_preview(0)
#@gmicol : Threshold = float(0.5,0,1)
#@gmicol : Gamma = float(0.7,0,1)
#@gmicol : Smoothness = float(0.1,0,10)
#@gmicol : Iterations = int(30,0,50)
#@gmicol : 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")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Tone mapping [fast] : gimp_map_tones_fast, gimp_map_tones_fast_preview(0)
#@gmicol : Radius = float(3,0,20)
#@gmicol : Power = float(0.5,0,1)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Authors : <i>Paul Nasca, David Tschumperl&#233;</i>.      Latest update: <i>2011/06/10</i>.</small>")

#@gmicol User-defined : gimp_custom_transform, gimp_custom_transform
#@gmicol : Red - Green - Blue - Alpha = text{"i"}
#@gmicol : Red - Green - Blue = text{"i + 90*(x/w)*cos(i/10)"}
#@gmicol : Red = text{"i"}
#@gmicol : Green = text{"i"}
#@gmicol : Blue = text{"i"}
#@gmicol : Alpha = text{"i"}
#@gmicol : Value normalization = choice("None","RGB","RGBA")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


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


#@gmicol Curvature : gimp_curvature, gimp_curvature_preview(0)
#@gmicol : Smoothness = float(2,0,10)
#@gmicol : Min threshold = float(0,0,100)
#@gmicol : Max threshold = float(100,0,100)
#@gmicol : Absolute value = bool(0)
#@gmicol : Negative colors = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Difference of gaussians : gimp_dog, gimp_dog_preview(1)
#@gmicol : 1st Variance = float(1.4,0,5)
#@gmicol : 2nd Variance = float(1.5,0,5)
#@gmicol : Threshold = float(0,0,49)
#@gmicol : Negative colors = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Distance transform : gimp_distance, gimp_distance_preview(0)
#@gmicol : Value = int(128,0,255)
#@gmicol : Metric = choice(2,"Chebyshev","Manhattan","Euclidean","Squared-Euclidean")
#@gmicol : Normalization = choice(2,"Cut","Normalize","Modulo")
#@gmicol : Modulo value = int(32,1,255)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Edges : gimp_edges, gimp_edges_preview(0)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Threshold = float(15,0,50)
#@gmicol : Negative colors = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Edges offsets : gimp_edge_offsets, gimp_edge_offsets_preview(0)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Threshold = float(15,0,50)
#@gmicol : Scale = int(4,0,32)
#@gmicol : Thickness = int(1,0,16)
#@gmicol : Negative colors = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Gradient norm : gimp_gradient_norm, gimp_gradient_norm_preview(0)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Linearity = float(0.5,0,1.5)
#@gmicol : Min threshold = float(0,0,100)
#@gmicol : Max threshold = float(100,0,100)
#@gmicol : Negative colors = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Gradient RGB : gimp_gradient2rgb, gimp_gradient2rgb_preview(0)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Min threshold = float(0,0,100)
#@gmicol : Max threshold = float(100,0,100)
#@gmicol : Orientation only = bool(0)
#@gmicol : Negative colors = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Isophotes : gimp_isophotes, gimp_isophotes_preview(0)
#@gmicol : Levels = int(8,1,256)
#@gmicol : Smoothness = float(0,0,5)
#@gmicol : Filling = choice(1,"Transparent","Colors")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Laplacian : gimp_laplacian, gimp_laplacian_preview(0)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Min threshold = float(0,0,100)
#@gmicol : Max threshold = float(100,0,100)
#@gmicol : Absolute value = bool(0)
#@gmicol : Negative colors = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Local orientation : gimp_local_orientation, gimp_local_orientation_preview(1)
#@gmicol : Smoothness = float(0,0,5)
#@gmicol : Min threshold = float(0,0,100)
#@gmicol : Max threshold = float(100,0,100)
#@gmicol : Negative colors = bool(0)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Morphological filter : gimp_morpho, gimp_morpho_preview(0)
#@gmicol : Action = choice("Erosion","Dilation","Opening","Closing",
#@gmicol : "Original - Erosion","Dilation - Original","Original - Opening","Closing - Original")
#@gmicol : Size = int(5,2,60)
#@gmicol : Invert colors = bool(false)
#@gmicol : Shape = choice(0,"Square","Octagonal")
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : Scale = bool(true)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Segmentation : gimp_segment_watershed, gimp_segment_watershed_preview(0)
#@gmicol : Edge threshold = float(2,0,15)
#@gmicol : Smoothness = float(1,0,5)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Skeleton : gimp_skeleton, gimp_skeleton_preview(1)
#@gmicol : Method = choice("Distance","Thinning")
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Curviness = float(0,0,10)
#@gmicol : Multiple channels = bool(1)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Thin edges : gimp_thin_edges, gimp_thin_edges_preview(0)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Threshold = float(15,0,50)
#@gmicol : Negative colors = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


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


#@gmicol Cartesian transform : gimp_custom_deformation, gimp_custom_deformation(1)
#@gmicol : X-warping = text{"(w+h)/20 * cos(y*20/h)"}
#@gmicol : Y-warping = text{"(w+h)/20 * sin(x*20/w)"}
#@gmicol : Relative warping = bool(1)
#@gmicol : Interpolation = choice(1,"Nearest neighbor","Linear")
#@gmicol : Borders = choice(1,"Black","Nearest","Repeat")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Euclidean - Polar : gimp_euclidean2polar, gimp_euclidean2polar(1)
#@gmicol : X-center = float(0.5,0,1)
#@gmicol : Y-center = float(0.5,0,1)
#@gmicol : Dilation = float(1,0.1,10)
#@gmicol : Borders = choice(1,"Black","Nearest","Repeat")
#@gmicol : Inverse transform = bool(0)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Fish-eye : fisheye, fisheye(1)
#@gmicol : X-center = float(50,0,100)
#@gmicol : Y-center = float(50,0,100)
#@gmicol : Radius = float(70,0,100)
#@gmicol : Amplitude = float(1,0,2)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Flower : gimp_flower, gimp_flower(1)
#@gmicol : Amplitude = float(30,-100,100)
#@gmicol : Petals = int(6,0,20)
#@gmicol : Offset = float(0,0,100)
#@gmicol : Angle = float(0,0,360)
#@gmicol : X-center = float(0.5,0,1)
#@gmicol : Y-center = float(0.5,0,1)
#@gmicol : Borders = choice(1,"Black","Nearest","Repeat")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Perspective : gimp_warp_perspective, gimp_warp_perspective(1)
#@gmicol : X-angle = float(1.73,-4,4)
#@gmicol : Y-angle = float(0,-4,4)
#@gmicol : Zoom = float(1,0.1,4)
#@gmicol : X-center = float(50,0,100)
#@gmicol : Y-center = float(50,0,100)
#@gmicol : X-offset = float(0,0,100)
#@gmicol : Y-offset = float(0,0,100)
#@gmicol : Borders = choice(2,"Black","Nearest","Repeat")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Polar transform : gimp_transform_polar, gimp_transform_polar(1)
#@gmicol : Preset = choice("Custom transform","Inverse radius","Swap radius/angle")
#@gmicol : X-center = float(50,0,100)
#@gmicol : Y-center = float(50,0,100)
#@gmicol : Radius = text{"r + R/10*cos(a*5)"}
#@gmicol : Angle = text{"a"}
#@gmicol : Borders = choice(1,"Black","Nearest","Repeat")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Random : deform, deform(0)
#@gmicol : Amplitude = float(10,0,100)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Ripple : ripple, ripple(0)
#@gmicol : Amplitude = float(10,0,100)
#@gmicol : Size = float(20,1,300)
#@gmicol : Shape = choice(2,"Bloc","Triangle","Sine","Sine+","Random")
#@gmicol : Angle = float(0,0,360)
#@gmicol : Offset = float(0,0,500)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Sphere : gimp_map_sphere, gimp_map_sphere_preview(1)
#@gmicol : Width = _int(512,1,4096)
#@gmicol : Height = _int(512,1,4096)
#@gmicol : Radius = float(90,0,400)
#@gmicol : Dilation = float(0.5,0,1)
#@gmicol : Angle = float(0,-50,50)
#@gmicol : Border smoothness = float(0,0,200)
#@gmicol : Border width = float(20,0,100)
#@gmicol : Orientation = choice("0 deg.","90 deg.","180 deg.","270 deg.")
#@gmicol : Background = choice("Transparent","Mean color")
#@gmicol : Fading = float(0,0,100)
#@gmicol : Fading shape = float(0.5,0,3)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Twirl : twirl, twirl(1)
#@gmicol : Amplitude = float(1,-5,5)
#@gmicol : X-center = float(0.5,0,1)
#@gmicol : Y-center = float(0.5,0,1)
#@gmicol : Borders = choice(1,"Black","Nearest","Repeat")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Water : water, water(0)
#@gmicol : Amplitude = float(30,0,300)
#@gmicol : Smoothness = float(1.5,0,4)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Wave : wave, wave(1)
#@gmicol : Amplitude = float(10,0,30)
#@gmicol : Frequency = float(0.4,0,2)
#@gmicol : X-center = float(50,0,100)
#@gmicol : Y-center = float(50,0,100)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Wind : gimp_wind, gimp_wind_preview(0)
#@gmicol : Amplitude = int(20,0,500)
#@gmicol : Angle = float(0,0,360)
#@gmicol : Attenuation = float(0.7,0,1)
#@gmicol : Threshold = float(20,0,100)
#@gmicol : Mode = choice(1,"Darker","Brighter")
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Zoom : gimp_zoom, gimp_zoom(1)
#@gmicol : Factor = float(2,0.01,10)
#@gmicol : X-center = float(0.5,0,1)
#@gmicol : Y-center = float(0.5,0,1)
#@gmicol : Borders = choice(0,"Black","Nearest","Repeat")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


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


#@gmicol Additive noise : gimp_noise, gimp_noise_preview(0)
#@gmicol : Amplitude = float(10,0,200)
#@gmicol : Noise type = choice("Gaussian","Uniform","Salt and pepper","Poisson")
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : Value range = choice("Cut","Normalize")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Angular blur : gimp_blur_angular, gimp_blur_angular(1)
#@gmicol : Amplitude = float(2,0,10)
#@gmicol : X-center = float(0.5,0,1)
#@gmicol : Y-center = float(0.5,0,1)
#@gmicol : Sharpness = float(0,0,500)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : Value range = choice("Cut","Normalize")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Bandpass filter : gimp_bandpass, gimp_bandpass_preview(0)
#@gmicol : Low frequency = float(0,0,100)
#@gmicol : High frequency = float(100,0,100)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : Value range = choice(1,"Cut","Normalize")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Bayer filter : rgb2bayer, rgb2bayer(0)
#@gmicol : Starting pattern = choice(0,"Red-Green","Blue-Green","Green-Red","Green-Blue")
#@gmicol : Keep colors = bool(1)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Bayer reconstruction : bayer2rgb, gimp_no_preview
#@gmicol : G/M smoothness = _float(6,0,20)
#@gmicol : R/B smoothness (principal) = _float(6,0,20)
#@gmicol : R/B smoothness (secondary) = _float(4,0,20)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Gaussian blur : gimp_gaussian_blur, gimp_gaussian_blur_preview(0)
#@gmicol : XY-amplitude = float(3,0,20)
#@gmicol : X-amplitude = float(0,0,20)
#@gmicol : Y-amplitude = float(0,0,20)
#@gmicol : Border conditions = choice(1,"Black","Nearest")
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : Value range = choice("Cut","Normalize")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Linear blur : gimp_blur_linear, gimp_blur_linear_preview(1)
#@gmicol : Tangent radius = float(10,0,100)
#@gmicol : Orthogonal radius = float(0.5,0,100)
#@gmicol : Angle = float(0,0,180)
#@gmicol : Sharpness = float(0,0,500)
#@gmicol : Border conditions = choice(1,"Black","Nearest")
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : Value range = choice("Cut","Normalize")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Old-movie stripes : gimp_stripes_y, gimp_stripes_y_preview(1)
#@gmicol : Frequency = float(10,0,100)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Oldschool 8bits : gimp_8bits, gimp_8bits_preview(0)
#@gmicol : Scale = float(25,1,100)
#@gmicol : Dithering = float(800,0,10000)
#@gmicol : Levels = int(16,2,256)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Radial blur : gimp_blur_radial, gimp_blur_radial(1)
#@gmicol : Amplitude = float(3,0,20)
#@gmicol : X-center = float(0.5,0,1)
#@gmicol : Y-center = float(0.5,0,1)
#@gmicol : Sharpness = float(0,0,500)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : Value range = choice("Cut","Normalize")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Random shade stripes : gimp_shade_stripes, gimp_shade_stripes_preview(1)
#@gmicol : Frequency = float(30,1,100)
#@gmicol : Orientation = choice(1,"Horizontal","Vertical")
#@gmicol : Darkness = float(0.8,0,3)
#@gmicol : Lightness = float(1.3,0,3)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Spread noise : gimp_spread, gimp_spread_preview(0)
#@gmicol : X-variations = float(4,0,20)
#@gmicol : Y-variations = float(4,0,20)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Visible watermark : gimp_watermark_visible, gimp_watermark_visible(0)
#@gmicol : Text = text{"(C) G'MIC"}
#@gmicol : Opacity = float(0.4,0.1,0.9)
#@gmicol : Size = int(57,13,128)
#@gmicol : Angle = float(25,0,360)
#@gmicol : Smoothness = float(0.5,0,5)
#@gmicol : Lightness = choice(1,"Darker","Brighter")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


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


#@gmicol Deinterlace : deinterlace, gimp_deinterlace_preview(0)
#@gmicol : Algorithm = choice("Standard","Motion-compensated")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Red-Eye attenuation : red_eye, red_eye
#@gmicol : Threshold = float(75,0,100)
#@gmicol : Smoothness = float(3.5,0,20)
#@gmicol : Factor = float(0.1,0,1)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Remove hot pixels : gimp_remove_hotpixels, gimp_remove_hotpixels_preview(0)
#@gmicol : Mask size = int(3,3,20)
#@gmicol : Threshold = float(10,0,200)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>J&#233;rome Boulanger</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@gmicol Sharpen [deconvolve] : gimp_richardson_lucy, gimp_richardson_lucy_preview(0)
#@gmicol : Radius = float(2,0,20)
#@gmicol : Iterations = int(10,0,50)
#@gmicol : Time step = float(20,0,50)
#@gmicol : Smoothness = float(0.1,0,10)
#@gmicol : Regularization = choice(1,"Tikhonov","Mean curvature","Total variation")
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Sharpen [inverse diffusion] : gimp_sharpen_inversediff, gimp_sharpen_inversediff_preview(0)
#@gmicol : Amplitude = float(50,1,300)
#@gmicol : Iterations = int(2,1,10)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Sharpen [octave sharpening] : gimp_unsharp_octave, gimp_unsharp_octave_preview(0)
#@gmicol : Scales = int(4,1,10)
#@gmicol : Maximal radius = float(5,0,20)
#@gmicol : Amount = float(3,0,10)
#@gmicol : Threshold = float(0,0,255)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Sharpen [shock filters] : gimp_sharpen_shock, gimp_sharpen_shock_preview(0)
#@gmicol : Amplitude = float(150,1,400)
#@gmicol : Edge threshold = float(0.1,0,0.7)
#@gmicol : Gradient smoothness = float(0.8,0,10)
#@gmicol : Tensor smoothness = float(1.1,0,10)
#@gmicol : Iterations = int(1,1,10)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Sharpen [unsharp mask] : gimp_unsharp, gimp_unsharp_preview(0)
#@gmicol : Sharpening type = choice(0,"Gaussian","Bilateral")
#@gmicol : Spatial radius = float(1.25,0,20)
#@gmicol : Bilateral radius = float(30,0,60)
#@gmicol : Amount = float(3,0,10)
#@gmicol : Threshold = float(0,0,20)
#@gmicol : Darkness level = float(1,0,4)
#@gmicol : Lightness level = float(1,0,4)
#@gmicol : Iterations = int(1,1,10)
#@gmicol : Negative effect = bool(0)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : note = note{"\n\n<small><b>Note : </b>
#@gmicol : This filter is inspired by the original <i>Unsharp Mask</i> filter in GIMP, with additional parameters.
#@gmicol : </small>"}
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Smooth [anisotropic] : gimp_anisotropic_smoothing, gimp_anisotropic_smoothing_preview(0)
#@gmicol : Amplitude = float(60,0,1000)
#@gmicol : Sharpness = float(0.7,0,2)
#@gmicol : Anisotropy = float(0.3,0,1)
#@gmicol : Gradient smoothness = float(0.6,0,10)
#@gmicol : Tensor smoothness = float(1.1,0,10)
#@gmicol : Spatial precision = float(0.8,0.1,2)
#@gmicol : Angular precision = float(30,1,180)
#@gmicol : Value precision = float(2,0.1,5)
#@gmicol : Interpolation = choice(0,"Nearest neighbor","Linear","Runge-Kutta")
#@gmicol : Fast approximation = bool(1)
#@gmicol : Iterations = int(1,1,10)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : Tiles = int(1,1,10)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Smooth [bilateral] : gimp_bilateral, gimp_bilateral_preview(0)
#@gmicol : Spatial variance = float(10,0,100)
#@gmicol : Value variance = float(7,0,100)
#@gmicol : Iterations = int(2,1,10)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Smooth [diffusion] : gimp_diffusion_smoothing, gimp_diffusion_smoothing_preview(0)
#@gmicol : Sharpness = float(0.7,0,2)
#@gmicol : Anisotropy = float(0.3,0,1)
#@gmicol : Gradient smoothness = float(0.6,0,10)
#@gmicol : Tensor smoothness = float(1.1,0,10)
#@gmicol : Time step = float(15,5,50)
#@gmicol : Iterations = int(8,1,20)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Smooth [mean-curvature] : gmicol_meancurvature_smoothing, gmicol_meancurvature_smoothing_preview(0)
#@gmicol : Time step = float(30,5,50)
#@gmicol : Iterations = int(4,1,20)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")
gmicol_meancurvature_smoothing :
  -gimp_meancurvature_smoothing $1,$2,0,$3

gmicol_meancurvature_smoothing_preview :
  -gimp_meancurvature_smoothing_preview $1,$2,0,$3,$4

#@gmicol Smooth [median] : gimp_median, gimp_median_preview(0)
#@gmicol : Radius = int(3,1,20)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Smooth [patch-based] : gimp_patch_smoothing, gimp_patch_smoothing_preview(0)
#@gmicol : Spatial variance = float(10,0.1,200)
#@gmicol : Patch variance = float(10,0.1,200)
#@gmicol : Patch size = int(3,2,21)
#@gmicol : Lookup size = int(5,2,21)
#@gmicol : Patch smoothness = float(0,0,4)
#@gmicol : Fast approximation = bool(1)
#@gmicol : Iterations = int(1,1,10)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Smooth [selective gaussian] : gimp_selective_smoothing, gimp_selective_smoothing_preview(0)
#@gmicol : Amplitude = float(5,0,20)
#@gmicol : Edges = float(0.5,0,2)
#@gmicol : Scales = int(5,1,10)
#@gmicol : Iterations = int(1,1,10)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

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

#@gmicol Smooth [total-variation] : gmicol_tv_smoothing, gmicol_tv_smoothing_preview(0)
#@gmicol : Time step = float(30,5,100)
#@gmicol : Iterations = int(10,1,30)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")
gmicol_tv_smoothing :
  -gimp_tv_smoothing $1,$2,0,$3

gmicol_tv_smoothing_preview :
  -gimp_tv_smoothing_preview $1,$2,0,$3,$4

#@gmicol Smooth [wavelets] : gimp_haar_smoothing, gimp_haar_smoothing_preview(0)
#@gmicol : Threshold = float(1,0,10)
#@gmicol : Iterations = int(10,1,24)
#@gmicol : Scales = int(10,2,10)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>J&#233;rome Boulanger, David Tschumperl&#233;</i>.      Latest update: <i>2012/08/17</i>.</small>")

#@gmicol Solidify : gimp_solidify, gimp_solidify_preview(0)
#@gmicol : Interpolation type = choice("Linear","Morphological")
#@gmicol : sep = separator(), note = note("<small><b>For linear method only :</b></small>")
#@gmicol : Smoothness = float(1.5,1,5)
#@gmicol : Smoothness factor = float(1,1,1.2)
#@gmicol : Precision = float(0.5,0,1)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small><b>Note :</b>
#@gmicol : This filter replaces transparent regions by interpolated colors. It may take long to render!
#@gmicol : </small>")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Upscale [diffusion] : gimp_upscale_smart, gimp_upscale_smart_preview(0)
#@gmicol : Width = text("200%")
#@gmicol : Height = text("200%")
#@gmicol : Smoothness = float(2,0,20)
#@gmicol : Anisotropy = float(0.4,0,1)
#@gmicol : Sharpness = float(50,0,100)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Upscale [scale2x] : gimp_scalenx, gimp_scalenx_preview(0)
#@gmicol : Scaling factor = choice("x 2","x 3","x 4","x 6","x 8","x 9","x 12","x 16","x 18","x 27")
#@gmicol : Colorbase = choice(1,"RGB","YCbCr","Lab")
#@gmicol : note = note{"\n<small><b>Note : </b>
#@gmicol : This filter re-implements the scaling algorithm described at :
#@gmicol : </small>"}
#@gmicol : note = link("http://scale2x.sourceforge.net")
#@gmicol : note = note{"<small>
#@gmicol : This filter is useful for resizing images that have very few colors
#@gmicol : (e.g. indexed images). It is generally useless for true colors images.
#@gmicol : </small>"}
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


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


#@gmicol Drop shadow : gimp_drop_shadow, gimp_drop_shadow(1)
#@gmicol : X-shadow = float(3,-20,20)
#@gmicol : Y-shadow = float(3,-20,20)
#@gmicol : Smoothness = float(1.8,0,5)
#@gmicol : Angle = float(0,0,360)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Light glow : gimp_lightglow, gimp_lightglow_preview(0)
#@gmicol : Density = float(30,0,100)
#@gmicol : Amplitude = float(0.5,0,2)
#@gmicol : Mode = choice(8,"Color burn","Dodge","Freeze","Grain merge","Hard light","Interpolation",
#@gmicol :               "Lighten","Multiply","Overlay","Reflect","Soft light","Stamp","Value")
#@gmicol : Opacity = float(0.8,0,1)
#@gmicol : note = note()
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Light patch : gimp_light_patch, gimp_light_patch(0)
#@gmicol : Density = int(5,2,30)
#@gmicol : Darkness = float(0.7,0,1)
#@gmicol : Lightness = float(2.5,1,4)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Light rays : gimp_lightrays, gimp_lightrays(1)
#@gmicol : Density = float(80,0,100)
#@gmicol : X-center = float(0.5,0,1)
#@gmicol : Y-center = float(0.5,0,1)
#@gmicol : Length = float(1,0,1)
#@gmicol : Attenuation = float(0.5,0,1)
#@gmicol : Transparency = bool(0)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Relief light : gimp_light_relief, gimp_light_relief(1)
#@gmicol : Ambient lightness = float(0.3,0,5)
#@gmicol : Specular lightness = float(0.2,0,2)
#@gmicol : Specular size = float(0.2,0,1)
#@gmicol : Darkness = float(0,0,1)
#@gmicol : Light smoothness = float(1,0,5)
#@gmicol : X-light = float(0.5,0,1)
#@gmicol : Y-light = float(0.5,0,1)
#@gmicol : Z-light = float(5,0,20)
#@gmicol : Z-scale = float(0.5,0,3)
#@gmicol : Opacity as bumpmap = bool(0)
#@gmicol : Image smoothness = float(0,0,10)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Shadow patch : gimp_shadow_patch, gimp_shadow_patch(1)
#@gmicol : Opacity = float(0.7,0,1)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


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


#@gmicol Canvas : gimp_canvas, gimp_canvas_preview(0)
#@gmicol : note = note{"<b>First direction :</b>"}
#@gmicol : Amplitude = float(70,0,300)
#@gmicol : Angle = float(45,0,180)
#@gmicol : Sharpness = float(400,0,2000)
#@gmicol : note = note{"\n<b>Second direction : </b>"}
#@gmicol : Activate second direction = bool(true)
#@gmicol : Amplitude = float(70,0,300)
#@gmicol : Angle = float(135,0,180)
#@gmicol : Sharpness = float(400,0,2000)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Canvas texture : texturize_canvas, texturize_canvas(0)
#@gmicol : Amplitude = float(20,0,256)
#@gmicol : Fibrousness = float(3,0,20)
#@gmicol : Emboss = float(0.6,0,1)

#@gmicol Chessboard : gimp_chessboard, gimp_chessboard_preview(0)
#@gmicol : First size = int(64,1,512)
#@gmicol : Second size = int(64,1,512)
#@gmicol : First offset = int(0,0,512)
#@gmicol : Second offset = int(0,0,512)
#@gmicol : Angle = float(0,0,180)
#@gmicol : Opacity = float(0.5,0,1)
#@gmicol : First color = color(0,0,0,255)
#@gmicol : Second color = color(255,255,255,255)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Cracks : gimp_cracks, gimp_cracks_preview(0)
#@gmicol : Density = float(1,0.1,10)
#@gmicol : Amplitude = float(-80,-255,255)
#@gmicol : Relief = bool(true)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Dices : gimp_dices, gimp_dices(0)
#@gmicol : Resolution = float(2,1,10)
#@gmicol : Size = int(24,8,64)
#@gmicol : Color model = choice(1,"Black dices","White dices")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Dithering : gimp_dithering_pattern, gimp_dithering_pattern_preview(0)
#@gmicol : note = note("<b><small>Image parameters :</small></b>")
#@gmicol : Gamma = float(1,0.01,5)
#@gmicol : Contrast = float(1,0,4)
#@gmicol : Brightness = float(0,-255,255)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Color = float(1,0,1)
#@gmicol : sep = separator(), note = note("<b><small>Pattern parameters :</small></b>")
#@gmicol : Number of tones = int(5,2,32)
#@gmicol : Size for dark tones = int(8,2,256)
#@gmicol : Size for bright tones = int(8,2,256)
#@gmicol : Shape = choice{5,"Square","Diamond","Circle","Square (inv.)","Diamond (inv.)","Circle (inv.)"}
#@gmicol : Smoothness = float(0.1,0,32)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Dots : gimp_dots, gimp_dots_preview(0)
#@gmicol : Number of scales = int(10,1,20)
#@gmicol : Resolution = float(10,1,100)
#@gmicol : Radius = float(3,0.1,10)
#@gmicol : Stencil type = choice(2,"Black & White","RGB","Color")
#@gmicol : Transparency = bool(0)
#@gmicol : Negative = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Hearts : gimp_hearts, gimp_hearts_preview(0)
#@gmicol : Density = float(10,0,100)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Lissajous : gimp_lissajous, gimp_lissajous(1)
#@gmicol : Resolution = int(4096,2,8192)
#@gmicol : sep = separator()
#@gmicol : X-size = float(0.9,0,2)
#@gmicol : Y-size = float(0.9,0,2)
#@gmicol : Z-size = float(3,1,10)
#@gmicol : sep = separator()
#@gmicol : X-multiplier = float(8,0,32)
#@gmicol : Y-multiplier = float(7,0,32)
#@gmicol : Z-multiplier = float(0,0,32)
#@gmicol : sep = separator()
#@gmicol : X-offset = float(0,0,1)
#@gmicol : Y-offset = float(0,0,1)
#@gmicol : Z-offset = float(0,0,1)
#@gmicol : sep = separator()
#@gmicol : X-angle = float(0,0,360)
#@gmicol : Y-angle = float(0,0,360)
#@gmicol : Z-angle = float(0,0,360)
#@gmicol : sep = separator()
#@gmicol : Thickness = float(0,0,50)
#@gmicol : Color = color(128,128,128,255)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Marble : gimp_marble, gimp_marble
#@gmicol : Image weight = float(.5,0,30)
#@gmicol : Pattern weight = float(1,0,30)
#@gmicol : Pattern angle = float(0,0,360)
#@gmicol : Amplitude = float(0,0,1000)
#@gmicol : Sharpness = float(.4,0,5)
#@gmicol : Anisotropy = float(.6,0,1)
#@gmicol : Alpha = float(.6,0,20)
#@gmicol : Sigma = float(1.1,0,20)
#@gmicol : Cut low = float(0,0,100)
#@gmicol : Cut high = float(100,0,100)
#@gmicol : sep = separator(), note = note("<small>Author : <i>Preben Soeberg</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@gmicol Maze : gimp_maze, gimp_maze
#@gmicol : Cell size = int(24,5,256)
#@gmicol : Thickness = int(1,1,10)
#@gmicol : Masking = choice("None","Render on dark areas","Render on white areas")
#@gmicol : Preserve image dimension = bool(1)
#@gmicol : Maze type = choice("Dark walls","White walls")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Mosaic : gimp_mosaic, gimp_mosaic_preview(0)
#@gmicol : Density = float(1,0.1,10)
#@gmicol : Keep edges = bool(true)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Paper texture : gimp_paper, gimp_paper_preview(0)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Plaid : gimp_plaid_texture,gimp_plaid_texture(1)
#@gmicol : Line = float(50,0,100)
#@gmicol : Number of angles = int(2,1,8)
#@gmicol : Starting angle = float(0,0,360)
#@gmicol : Angle range = float(90,0,360)
#@gmicol : Smoothness = float(1,0,5)
#@gmicol : Sharpen = float(300,0,1000)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Plasma : gimp_plasma, gimp_plasma(0)
#@gmicol : Alpha = float(0.5,0,5)
#@gmicol : Beta = float(0,0,100)
#@gmicol : Scale = int(8,2,10)
#@gmicol : Randomize = bool(0)
#@gmicol : Transparency = bool(0)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Polka dots : gimp_polka_dots, gimp_polka_dots(1)
#@gmicol : Size = float(80,0,100)
#@gmicol : Density = float(20,0.1,100)
#@gmicol : First offset = float(50,0,100)
#@gmicol : Second offset = float(50,0,100)
#@gmicol : Angle = float(0,0,180)
#@gmicol : Aliasing = float(0.5,0.1,1)
#@gmicol : Shading = float(0.1,0.1,1)
#@gmicol : Opacity = float(1,0,1)
#@gmicol : Color = color(255,0,0,255)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Puzzle : gimp_puzzle, gimp_puzzle_preview(0)
#@gmicol : Scale = float(6,1,20)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Rorschach : gimp_rorschach, gimp_rorschach
#@gmicol : Scale = float(3,0,30)
#@gmicol : Mirror = choice(1,"None","X-axis","Y-axis","XY-axes")
#@gmicol : Colored = bool(false)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Sierpinski triangle : sierpinski, sierpinski(1)
#@gmicol : Recursions = int(6,0,7)
#@gmicol : 1st X-coord = float(50,0,100)
#@gmicol : 1st Y-coord = float(0,0,100)
#@gmicol : 2nd X-coord = float(0,0,100)
#@gmicol : 2nd Y-coord = float(100,0,100)
#@gmicol : 3rd X-coord = float(100,0,100)
#@gmicol : 3rd Y-coord = float(100,0,100)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Snowflake : snowflake, snowflake(1)
#@gmicol : Recursions = int(3,0,5)
#@gmicol : 1st X-coord = float(20,0,100)
#@gmicol : 1st Y-coord = float(70,0,100)
#@gmicol : 2nd X-coord = float(80,0,100)
#@gmicol : 2nd Y-coord = float(70,0,100)
#@gmicol : 3rd X-coord = float(50,0,100)
#@gmicol : 3rd Y-coord = float(10,0,100)
#@gmicol : Opacity = float(1,0,1)
#@gmicol : Color = color(128,128,128)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Sponge : gimp_sponge, gimp_sponge_preview(0)
#@gmicol : Size = int(13,3,21)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Stained glass : gimp_stained_glass, gimp_stained_glass_preview(0)
#@gmicol : Edges = float(20,0,100)
#@gmicol : Shading = float(0.1,0,0.5)
#@gmicol : Thin separators = bool(1)
#@gmicol : sep = separator()
#@gmicol : Equalize = bool(1)
#@gmicol : Colors = float(1,0,3)
#@gmicol : Gamma = float(1,0.01,5)
#@gmicol : Contrast = float(1,0,4)
#@gmicol : Brightness = float(0,-255,255)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Stars : gimp_stars, gimp_stars(0)
#@gmicol : Density = float(10,0,200)
#@gmicol : Depth = float(0,0,5)
#@gmicol : Size = int(32,8,64)
#@gmicol : Branches = int(5,2,16)
#@gmicol : Thickness = float(0.38,0.1,1)
#@gmicol : Smoothness = float(0,0,10)
#@gmicol : Color = color(200,200,200,200)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Stencil : gimp_stencil, gimp_stencil_preview(0)
#@gmicol : Radius = float(3,0,10)
#@gmicol : Smoothness = float(0,0,30)
#@gmicol : Iterations = int(8,1,16)
#@gmicol : Aliasing = float(0,0,5)
#@gmicol : Stencil type = choice(2,"Black & White","RGB","Color")
#@gmicol : Transparency = bool(0)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Superformula : gimp_superformula, gimp_superformula(1)
#@gmicol : Resolution = int(4096,2,8192)
#@gmicol : sep = separator()
#@gmicol : X-size = float(0.9,0,2)
#@gmicol : Y-size = float(0.9,0,2)
#@gmicol : sep = separator()
#@gmicol : m = int(8,1,32)
#@gmicol : n1 = float(1,-32,32)
#@gmicol : n2 = float(5,-32,32)
#@gmicol : n3 = float(8,-32,32)
#@gmicol : sep = separator()
#@gmicol : X-angle = float(0,0,360)
#@gmicol : Y-angle = float(0,0,360)
#@gmicol : Z-angle = float(0,0,360)
#@gmicol : sep = separator()
#@gmicol : Thickness = float(0,0,50)
#@gmicol : Color = color(128,128,128,255)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Truchet : gimp_truchet, gimp_truchet(0)
#@gmicol : Scale = int(32,1,256)
#@gmicol : Radius = int(5,1,64)
#@gmicol : Smoothness = float(1,0,10)
#@gmicol : Type = choice(1,"Straight","Curved")
#@gmicol : Colorize randomly = bool(0)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Turbulence : gimp_turbulence, gimp_turbulence
#@gmicol : Radius = float(128,1,1024)
#@gmicol : Octaves = int(6,1,12)
#@gmicol : Damping per octave = float(4,1,10)
#@gmicol : Difference mixing = float(0,-10,10)
#@gmicol : Mode = choice("Turbulence","Turbulence 2","Fractal Noise","Fractured Clouds","Stardust","Pea Soup")
#@gmicol : sep = separator(), note = note("<small>Author : <i>Preben Soeberg</i>.      Latest update: <i>2010/12/29</i>.</small>")

#@gmicol Whirls : gimp_whirls, gimp_whirls_preview(0)
#@gmicol : Density = int(7,3,20)
#@gmicol : Smoothness = float(2,0,10)
#@gmicol : Darkness = float(0.2,0,1)
#@gmicol : Lightness = float(1.8,1,3)
#@gmicol : 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","Red","Green","Blue","Alpha")
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


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


#@gmicol 3d colored object : gimp_coloredobject3d, gimp_coloredobject3d_preview(1)
#@gmicol : Type = choice{1,"Plane","Box","Pyramid","Ellipsoid","Torus","Gyroid","Weird","Cup"}
#@gmicol : Color = color(128,128,128,255)
#@gmicol : sep = separator()
#@gmicol : Size-1 = float(0.5,0,3)
#@gmicol : Size-2 = float(0.5,0,3)
#@gmicol : Size-3 = float(0.5,0,3)
#@gmicol : X-angle = float(57,0,360)
#@gmicol : Y-angle = float(41,0,360)
#@gmicol : Z-angle = float(21,0,360)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol 3d elevation : gimp_elevation3d, gimp_elevation3d_preview(1)
#@gmicol : Factor = float(100,-1000,1000)
#@gmicol : Smoothness = float(1,0,10)
#@gmicol : sep = separator()
#@gmicol : Width = _int(512,8,1024)
#@gmicol : Height = _int(512,8,1024)
#@gmicol : Size = float(0.8,0,3)
#@gmicol : X-angle = float(25,0,360)
#@gmicol : Y-angle = float(0,0,360)
#@gmicol : Z-angle = float(21,0,360)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : Rendering = choice(2,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gmicol : sep = separator(), note = note{"<small><b>Note :</b> Add a top layer to define object texture.</small>"}
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol 3d extrusion : gimp_extrude3d, gimp_extrude3d_preview(1)
#@gmicol : Depth = float(10,1,1024)
#@gmicol : Resolution = int(512,1,1024)
#@gmicol : Smoothness = float(0.6,0,3)
#@gmicol : sep = separator()
#@gmicol : Width = _int(512,1,1024)
#@gmicol : Height = _int(512,1,1024)
#@gmicol : Size = float(0.5,0,3)
#@gmicol : X-angle = float(57,0,360)
#@gmicol : Y-angle = float(41,0,360)
#@gmicol : Z-angle = float(21,0,360)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gmicol : sep = separator(), note = note{"<small><b>Note :</b> Add a top layer to define object texture.</small>"}
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol 3d image object : gimp_imageobject3d, gimp_imageobject3d_preview(1)
#@gmicol : Type = choice{1,"Plane","Cube","Pyramid","Sphere","Torus","Gyroid","Weird","Cup","Rubik"}
#@gmicol : sep = separator()
#@gmicol : Width = _int(512,1,1024)
#@gmicol : Height = _int(512,1,1024)
#@gmicol : Size = float(0.5,0,3)
#@gmicol : X-angle = float(57,0,360)
#@gmicol : Y-angle = float(41,0,360)
#@gmicol : Z-angle = float(21,0,360)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol 3d lathing : gimp_lathing3d, gimp_lathing3d_preview(1)
#@gmicol : Resolution = int(76,1,1024)
#@gmicol : Smoothness = float(0.6,0,3)
#@gmicol : Max angle = float(361,0,361)
#@gmicol : sep = separator()
#@gmicol : Width = _int(512,1,1024)
#@gmicol : Height = _int(512,1,1024)
#@gmicol : Size = float(0.5,0,3)
#@gmicol : X-angle = float(57,0,360)
#@gmicol : Y-angle = float(41,0,360)
#@gmicol : Z-angle = float(21,0,360)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gmicol : sep = separator(), note = note{"<small><b>Note :</b> Add a top layer to define object texture.</small>"}
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol 3d random objects : gimp_random3d, gimp_random3d(1)
#@gmicol : Type = choice("Cube","Cone","Cylinder","Sphere","Torus")
#@gmicol : Density = int(50,1,300)
#@gmicol : Size = float(3,1,20)
#@gmicol : Z-range = float(100,0,300)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : Rendering = choice(3,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gmicol : Opacity = float(1,0,1)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Equation plot : gimp_equation_plot, gimp_equation_plot
#@gmicol : Equation = text{"X*c+10*cos(X+c+?)"}
#@gmicol : X-min = float(-10,-100,100)
#@gmicol : X-max = float(10,-100,100)
#@gmicol : Resolution = int(100,2,1024)
#@gmicol : Channels = int(3,1,32)
#@gmicol : Plot type = choice(2,"None","Lines","Splines","Bars")
#@gmicol : Vertex type = choice(0,"None","Points","Crosses 1","Crosses 2","Circles 1","Circles 2","Square 1","Square 2")
#@gmicol : sep = separator()
#@gmicol : note = note("<b>Note</b> :
#@gmicol : Use variable 'X' instead of 'x' in the equation to take care of X-min/max settings.
#@gmicol : Variable 'c' refers to the current channel number. Reduce resolution to be able to view
#@gmicol : separate graph vertices.")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Mandelbrot / Julia sets : gimp_mandelbrot, gimp_mandelbrot_preview
#@gmicol : X-center = float(0,-2,2)
#@gmicol : Y-center = float(0,-2,2)
#@gmicol : Zoom = float(0,0,100)
#@gmicol : Iterations = int(128,1,256)
#@gmicol : Fractal set = choice(Mandelbrot, Julia)
#@gmicol : X-seed (Julia) = text("0.317")
#@gmicol : Y-seed (Julia) = text("0.03")
#@gmicol : Color 1 = color(0,0,255)
#@gmicol : Color 2 = color(0,255,0)
#@gmicol : Color 3 = color(255,0,0)
#@gmicol : Color 4 = color(255,0,255)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Quick copyright : gimp_quick_copyright, gimp_quick_copyright(0)
#@gmicol : Text = text{"(C) G'MIC Online"}
#@gmicol : Size = int(24,13,128)
#@gmicol : Color = color(255,255,255,128)
#@gmicol : Outline = int(1,0,4)
#@gmicol : Position = choice(3,"Up-left","Up-right","Bottom-left","Bottom-right")
#@gmicol : Offset = int(5,0,40)
#@gmicol : Orientation = choice(1,"-90 deg.","0 deg.","+90 deg.","+180 deg.")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Rainbow : gimp_rainbow, gimp_rainbow
#@gmicol : Left position = float(80,0,100)
#@gmicol : Right position = float(80,0,100)
#@gmicol : Left slope = float(175,0,400)
#@gmicol : Right slope = float(175,0,400)
#@gmicol : Thinness = float(3,0.1,8)
#@gmicol : Opacity = float(80,0,199)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Shade bobs : gimp_shadebobs, gimp_shadebobs
#@gmicol : note = note("<small>Bobs parameters :</small>")
#@gmicol : Density = int(50,1,200)
#@gmicol : Radius = int(5,1,100)
#@gmicol : Duration = int(200,1,500)
#@gmicol : Velocity = float(1,0,10)
#@gmicol : sep = separator()
#@gmicol : note = note("<small>Curve parameters :</small>")
#@gmicol : Rx = float(-1,-3,3)
#@gmicol : Ry = float(2,-3,3)
#@gmicol : Rz = float(1,-3,3)
#@gmicol : Rt = float(0.8,-3,3)
#@gmicol : Rcx = float(0,-3,3)
#@gmicol : Colormap = choice(8,"Grayscale","Standard","HSV","Lines","Hot","Cool","Jet","Flag","Cube")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


#@gmicol _<b>Sequences</b>
#-----------------------


#@gmicol 3d elevation : gmicol_animate_elevation3d, gmicol_animate_elevation3d_preview(1)
#@gmicol : Frames = _int(4,2,20)
#@gmicol : note = note{"\n<b>Global parameters :</b>"}
#@gmicol : Factor = float(100,-1000,1000)
#@gmicol : Smoothness = float(1,0,10)
#@gmicol : Width = _int(128,8,256)
#@gmicol : Height = _int(128,8,256)
#@gmicol : Rendering = choice(2,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gmicol : note = note{"\n<b>Starting parameters :</b>"}
#@gmicol : Size = float(0.8,0,3)
#@gmicol : X-angle = float(35,0,360)
#@gmicol : Y-angle = float(0,0,360)
#@gmicol : Z-angle = float(0,0,360)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : note = note{"\n<b>Ending parameters :</b>"}
#@gmicol : Size = float(0.8,0,3)
#@gmicol : X-angle = float(35,0,1440)
#@gmicol : Y-angle = float(0,0,1440)
#@gmicol : Z-angle = float(360,0,1440)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")
gmicol_animate_elevation3d :
  -gimp_animate_elevation3d $1,1,0,\"\",${2--1}

gmicol_animate_elevation3d_preview :
  -gimp_animate_elevation3d_preview $1,1,0,\"\",${2--1}

#@gmicol 3d extrusion : gmicol_animate_extrude3d, gmicol_animate_extrude3d_preview(1)
#@gmicol : Frames = _int(4,2,20)
#@gmicol : note = note{"\n<b>Global parameters :</b>"}
#@gmicol : Depth = float(10,1,256)
#@gmicol : Resolution = int(512,1,1024)
#@gmicol : Smoothness = float(0.6,0,3)
#@gmicol : Width = _int(128,8,256)
#@gmicol : Height = _int(128,8,256)
#@gmicol : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gmicol : note = note{"\n<b>Starting parameters :</b>"}
#@gmicol : Size = float(0.8,0,3)
#@gmicol : X-angle = float(35,0,360)
#@gmicol : Y-angle = float(0,0,360)
#@gmicol : Z-angle = float(0,0,360)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : note = note{"\n<b>Ending parameters :</b>"}
#@gmicol : Size = float(0.8,0,3)
#@gmicol : X-angle = float(35,0,1440)
#@gmicol : Y-angle = float(360,0,1440)
#@gmicol : Z-angle = float(0,0,1440)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")
gmicol_animate_extrude3d :
  -gimp_animate_extrude3d $1,1,0,\"\",${2--1}

gmicol_animate_extrude3d_preview :
  -gimp_animate_extrude3d_preview $1,1,0,\"\",${2--1}

#@gmicol 3d image object : gmicol_animate_imageobject3d, gmicol_animate_imageobject3d_preview(1)
#@gmicol : Frames = _int(4,2,20)
#@gmicol : note = note{"\n<b>Global parameters :</b>"}
#@gmicol : Type = choice{1,"Plane","Cube","Pyramid","Sphere","Torus","Gyroid","Weird","Cup","Rubik"}
#@gmicol : Width = _int(128,1,256)
#@gmicol : Height = _int(128,1,256)
#@gmicol : Rendering = choice(4,"Dots","Wireframe","Flat","Flat shaded","Gouraud","Phong")
#@gmicol : note = note{"\n<b>Starting parameters :</b>"}
#@gmicol : Size = float(0.5,0,3)
#@gmicol : X-angle = float(57,0,360)
#@gmicol : Y-angle = float(41,0,360)
#@gmicol : Z-angle = float(21,0,360)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : note = note{"\n<b>Ending parameters :</b>"}
#@gmicol : Size = float(0.5,0,3)
#@gmicol : X-angle = float(57,0,1440)
#@gmicol : Y-angle = float(401,0,1440)
#@gmicol : Z-angle = float(21,0,1440)
#@gmicol : FOV = float(45,1,90)
#@gmicol : X-light = float(0,-100,100)
#@gmicol : Y-light = float(0,-100,100)
#@gmicol : Z-light = float(-100,-100,0)
#@gmicol : Specular lightness = float(0.5,0,1)
#@gmicol : Specular shininess = float(0.7,0,3)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")
gmicol_animate_imageobject3d :
  -gimp_animate_imageobject3d $1,1,0,\"\",${2--1}

gmicol_animate_imageobject3d_preview :
  -gimp_animate_imageobject3d_preview $1,1,0,\"\",${2--1}

#@gmicol 3d text pointcloud : gimp_text_pointcloud3d, gimp_text_pointcloud3d_preview
#@gmicol : Frames = _int(9,1,20)
#@gmicol : 1st text = text("G'MIC")
#@gmicol : 2nd text = text("Rocks!")
#@gmicol : Smoothness = float(1,0,5)
#@gmicol : Color = color(200,220,255)
#@gmicol : Background = color(255,255,255,255)
#@gmicol : X-shadow= float(2,0,10)
#@gmicol : Y-shadow= float(2,0,10)
#@gmicol : Shadow smoothness = float(1,0,5)
#@gmicol : Stationary frames = _int(1,1,32)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Edges on fire : gimp_fire_edges, gimp_fire_edges_preview(0)
#@gmicol : Edges = float(0.7,0,3)
#@gmicol : Attenuation = float(0.25,0,1)
#@gmicol : Smoothness = float(0.5,0,5)
#@gmicol : Threshold = float(25,0,100)
#@gmicol : sep = separator()
#@gmicol : Number of frames = _int(9,2,20)
#@gmicol : Starting frame = int(5,0,199)
#@gmicol : Frame skip = _int(0,0,20)
#@gmicol : sep = separator(), Preview type = choice("Full","Forward horizontal","Forward vertical","Backward horizontal","Backward vertical")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Lava lamp : gimp_lavalampbw, gimp_lavalampbw_preview(0)
#@gmicol : Number of key-frames = _int(3,2,50)
#@gmicol : Number of inter-frames = _int(3,2,100)
#@gmicol : Smooth looping = _bool(1)
#@gmicol : sep = separator()
#@gmicol : Resolution = float(20,1,100)
#@gmicol : Size = float(2,0,30)
#@gmicol : Smoothness = _float(0.01,0,1)
#@gmicol : Transparent background = bool(0)


#@gmicol _<b>Spectral handling</b>
#-------------------------------


#@gmicol Fourier analysis : gimp_display_fft, gimp_display_fft(1)
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")

#@gmicol Fourier watermark : gimp_watermark_fourier, _none_
#@gmicol : Text = text{"(C) G'MIC"}
#@gmicol : Size = int(57,13,128)
#@gmicol : sep = separator()
#@gmicol : note = note("<small><b>Note : </b> To make the watermark visible afterwards, use the 'Fourier Analysis' filter. </small>")
#@gmicol : sep = separator(), note = note("<small>Author : <i>David Tschumperl&#233;</i>.      Latest update: <i>2012/10/11</i>.</small>")


# Local Variables:
# mode: sh
# End:
#
# (End of G'MIC custom commands)