#!BPY
"""
Name: 'Ma_Self'
Blender: 248
Group: 'UV'
Tooltip: 'Generate UV colours depending on the angles of the edges.'
"""

__author__ = ["macouno"]
__url__ = ("http://www.alienhelpdesk.com")
__version__ = "0.1"
__bpydoc__ = """\

MaSelf

This script generates UV colours depending on the angles between vertex normals and the edges connected to them.
There are no settings and it's coded to run quick and clean.

Many thanks to Campbell J Barton for his valuable assistance/examples/instructions.

"""

# ***** BEGIN GPL LICENSE BLOCK *****
#
# Script copyright (C) macouno 2006
#
# 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.
#
# ***** END GPL LICENCE BLOCK *****
# --------------------------------------------------------------------------

from Blender import *
import BPyMesh


def MainScript(me):

	BPyMesh.meshCalcNormals(me)

	if not me.faceUV:
		me.faceUV= 1

	leng = len(me.verts)
	angles= [0.0] * leng
	totAngles= [0] * leng
	
	del leng
	
	Ang = Mathutils.AngleBetweenVecs

	for e in me.edges:

		iOne = e.v1.index
		iTwo = e.v2.index

		vOne = e.v1.co - e.v2.co
		vTwo = e.v2.co - e.v1.co

		try:
			angles[iOne] += Ang(vOne, e.v1.no)
			angles[iTwo] += Ang(vTwo, e.v2.no)
			
			totAngles[iOne] += 1
			totAngles[iTwo] += 1
		except:
			continue
		
	del Ang, iOne, iTwo, vOne, vTwo

	big_num = 1<<30
	max_tone = - big_num
	min_tone = big_num
	
	del big_num

	for i, a in enumerate(angles):

		if totAngles[i]:
		
			angle = a / totAngles[i]

			angles[i] = angle

			if max_tone < angle:
				max_tone = angle
			if min_tone > angle:
				min_tone = angle
			
	del i, a, angle, totAngles

	max_tone -= min_tone

	for f in me.faces:
		f_col = f.col
		for i, v in enumerate(f.v):
			f_col[i].r= f_col[i].g= f_col[i].b = 255 - int(((angles[v.index] - min_tone)/max_tone)*255)

	del i, v, f_col, min_tone, max_tone, angles

	me.update()
	del me

def MeshCheck():

	Window.WaitCursor(1)

	scn = Scene.GetCurrent()
	ob = scn.objects.active
	
	if not ob or ob.getType() != 'Mesh':
		Draw.PupMenu('Error, no active mesh object, aborting.')
		return
		
	me = ob.getData(mesh=1)
	del ob
	
	MainScript(me)
	
	scn.update()
	del scn

	Window.Redraw(Window.Types.VIEW3D)
	
	Window.WaitCursor(0)


MeshCheck()	