#!/usr/bin/env python

#   Sunflawer plugin
#   Copyright (C) 2008  Matteo Nastasi <nastasi@alternativeoutput.it>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

from gimpfu import *
from math import sqrt, pi, sin, cos
import time

def python_sunflower(img, layer, scale_ref, a, n):
    img.undo_group_start()

    w = layer.width
    h = layer.height
    b = 1.5 * 640 / sqrt(2 * n)
    radius = 0.75 * b

    gimp.progress_init("Sunflower tassellation ...")

    for i in xrange(n, 1, -1):
        r = b * sqrt(i - 0.5)
        a1 = a * i * pi / 180
        x = (w / 2) + r * cos(a1)
        y = (h / 2) + r * sin(a1)

        gimp.progress_update((i - n) / n)

        pen = pdb.gimp_edit_paste(layer,0)
        px = pen.offsets[0]
        py = pen.offsets[1]
        pw = pen.width
        ph = pen.height

        pxorig = px + (pw / 2)
        pyorig = py + (ph / 2)

        if pw > ph:
            mag = scale_ref / pw
        else:
            mag = scale_ref / ph
        
        pdb.gimp_drawable_transform_2d(pen, pxorig,pyorig, mag / 2.0,mag / 2.0, a1 - (pi / 2), x,y, 0, 2, 1, 3, 0)
        pdb.gimp_floating_sel_anchor(pen)

    img.undo_group_end()

register(
    "python_fu_sunflower",
    "Sunflower Tasselate",
    "Sunflower Tasselate",
    "Matteo Nastasi",
    "Matteo Nastasi",
    "2008",
    "<Image>/Python-Fu/Effects/sunflower",
    "RGB*, GRAY*",
    [
        (PF_FLOAT,  "scale_ref", "Scale Reference", 100.0),
        (PF_FLOAT,  "a", "Divergence angle", 137.50776),
        (PF_INT, "n", "Number of elements", 600),
    ],
    [],
    python_sunflower)

main()

