# -*- coding: latin-1 -*-
#!/usr/bin/env python
from gimpfu import *
from gimpenums import *

import sys
import os
import math


def draw_line( layer, x0, y0, x1, y1, couleur ):
	"""Fonction de tracé de lignes par l'algo de Bresenham récupérée sur \
	le site http://en.literateprograms.org/ """
	# steep
	steep = abs(y1 - y0) > abs(x1 - x0)
	if steep:
		x0, y0 = y0, x0  
		x1, y1 = y1, x1
	# endpoint swap
	if x0 > x1:
		x0, x1 = x1, x0
		y0, y1 = y1, y0
	# ystep
	if y0 < y1: 
		ystep = 1
	else:
		ystep = -1
	# init
	deltax = x1 - x0
	deltay = abs( y1 - y0 )
	error = -deltax / 2
	y = y0
	# Core loop
	for x in range(x0, x1 + 1):# correction "+1" pour atteindre l'extrémité (x1, y1) 
		if steep:
			layer.set_pixel( y, x, couleur )
		else:
			layer.set_pixel( x, y, couleur )
	
		error = error + deltay
		if error > 0:
			y = y + ystep
			error = error - deltax



def importer_ligne_brisee( inImage, strNomFichier ):
	"""Dessine la ligne brisée contenue dans le fichier strNomFichier sur l'image"""
	# Gestion des accents dans le nom du fichier
	strNomFichier = strNomFichier.decode('utf-8')
	
	# Sauvegarde des couleurs
	save_fg = gimp.get_foreground()
	save_bg = gimp.get_background()
	
	fd = open('out.txt', 'w')# ouverture d'un fichier de traces pour le débugage 
	# Sous Windows, ce fichier se crée par défaut dans le dossier "C:\Mes Images"
	fd.write('This is a test\n')
	fd.write( strNomFichier )
	fd.write( '\n' )
	fd.write( __name__ )
	fd.write( '\n' )
	fd.write( os.getcwd() )
	fd.write( '\n' )
	
	f = open( strNomFichier, 'r' )
	# Recherche des mini et maxi de la liste
	strL = f.readline()
	nCpt = 0
	xMin = xMax = yMin = yMax = 0
	while strL != "":
		lstStr = strL.split(';')
		if len( lstStr ) >= 2 :
			x = int( lstStr[0] )
			y = int( lstStr[1] )
		if nCpt == 0:# Premier point
			nCpt += 1
			xMin = xMax = x
			yMin = yMax = y
		else:# Mémorisation du mini et maxi
			if x < xMin:
				xMin = x
			if y < yMin:
				yMin = y
			if x > xMax:
				xMax = x
			if y > yMax:
				yMax = y
		# suivant
		strL = f.readline()
	
	# Redimensionnement de l'image pour accepter les points du fichier
	nLargeur = abs( xMax - xMin ) + 1
	nHauteur = abs( yMax - yMin ) + 1
	fd.write( 'xmin = %d, xmax = %d, ymin = %d, ymax = %d'%(xMin, xMax, yMin, yMax))
	lstLayers = inImage.layers
	layerImg_src = lstLayers[0]
	gimp.set_background( 255.0, 255.0, 255.0 )
	gimp.set_foreground( 0.0, 0.0, 0.0 )
	gimp.pdb.gimp_image_resize ( inImage, nLargeur, nHauteur, 0, 0 )  
	for layer in lstLayers:
		gimp.pdb.gimp_layer_resize_to_image_size( layer ) # redimensionnement des calques
	
	# Dessin des lignes
	couleur = (0, 0, 0)# noir
	f.seek( 0 )
	strL = f.readline()
	nCpt = 0
	vxOffset = -xMin
	vyOffset = -yMin
	while strL != "":
		lstStr = strL.split(';')
		if len( lstStr ) >= 3 :
			x = int( lstStr[ 0 ] ) + vxOffset
			y = ( nHauteur - 1 ) - ( int( lstStr[ 1 ] ) + vyOffset )
			nCl = 255 - int( lstStr[ 2 ] )# couleur 255 -> noir ; 0 -> blanc
			couleur = ( nCl, nCl, nCl ) # niveau de gris
			if nCpt == 0:
				nCpt += 1
				layerImg_src.set_pixel( x, y, couleur )
			else:
				draw_line( layer, x, y, xPrec, yPrec, couleur )
		# suivant
		strL = f.readline()
		xPrec = x
		yPrec = y
	
	fd.close()
	f.close()
	
	# Restauration des courleurs initiales
	gimp.set_background( save_bg )
	gimp.set_foreground( save_fg )
	
	strM = "Fin du traitement"
	print strNomFichier
	gimp.pdb.gimp_message( strM )


#-----------------------------------------
# Version 1.0 : 29/09/2008
#             : première version
#
#
#-----------------------------------------
register(
	"importer_ligne_brisee",# Nom de la fonction
	"Importe une ligne brisee depuis le fichier specifie",# pas d'accents ici
	"Importe une ligne brisee depuis le fichier specifie",# pas d'accents ici
	"Vincent Vansuyt",
	"LGPL License",
	"2008",
	"<Image>/Python-Fu/Importer ligne brisee",# pas d'accents ici
	"",
	[
	(PF_IMAGE, "inImage", "Input image", None),
	(PF_FILE, "strNomFichier", "Fichier ligne brisee a importer", "")
	],
	[],
	importer_ligne_brisee,
	menu="<Image>/Python-Fu/Importer ligne brisee",
	)

main() 
