#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  V1_Mdlbrt.py
#  
#  Copyright 2017 renaud <renaud@renaud-VirtualBox>
#  
#  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., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#  
#  
import Image
import math
def colormap(n):
    #Frequence d'ocilation des couleur
    frequency1=0.3
    frequency2=0.3
    frequency3=0.3
    #dephage des couleur
    phase1=0.0
    phase2=2.0
    phase3=4.0
    #Centre de l'ocilation de la couleur
    center=128.0
    #Amplitude de l'ocilation
    Width=127.0
    
    R=int(math.sin(frequency1*n+phase1)*Width+center)
    G=int(math.sin(frequency2*n+phase2)*Width+center)
    B=int(math.sin(frequency3*n+phase3)*Width+center)
    
    return (R,G,B)
    
def Mandelbrot(x,y,max_iter):
    z_x=x
    z_y=y
    for nb_iter in range(max_iter+1):
        z_tx=z_x
        
        z_x=(z_x*z_x)-(z_y*z_y)+x
        z_y=2*z_tx*z_y+y
        if (z_x*z_x+z_y*z_y)>4:
            break
    return nb_iter
# Definition de la taille de l'image
# Je multiplit par 4 la taille pour eviter l'effet de pixelisation
size_Image_X=192*4
size_Image_y=108*4
# Definition de Xmax et Xmin
Xmin=-2.05
Xmax=0.5
# Definition de pasX, la distance entre deux pixel
pasX=(Xmax-Xmin)/size_Image_X
# Definition de Ymin
Ymin=-1.3
Ymax=Ymin+(pasX*size_Image_y)
# Definition de pasY, la distance entre deux pixel
pasY=(Ymax-Ymin)/size_Image_y
# Creation de l'image
img = Image.new( 'RGB', (size_Image_X,size_Image_y), "black") # create a new black image
pixels = img.load() # create the pixel map
for i in range(img.size[0]):    # for every pixel:
    for j in range(img.size[1]):
        
        x=Xmin+i*pasX
        y=Ymax-(j*pasY)
        max_iter=500
        nb_iter=Mandelbrot(x,y,max_iter)
        
        if nb_iter>=max_iter:
            pixels[i,j] = (0,0,0)
        else:
            pixels[i,j] = colormap(nb_iter) # set the colour accordingly
img.show()
img.save("toto.bmp")
img.save("toto.png")