#!BPY
"""
Name: 'Check Integrity'
Blender: 248
Group: 'Object'
Tooltip: 'Highlights non-manifold edges in the active mesh'
"""
__author__ = ["Yorik van Havre"]
__url__ = ("http://wiki.blender.org/index.php/Extensions:Py/Scripts/Manual/Object/Check_Integrity", "http://yorik.orgfree.com")
__version__ = "0"
__bpydoc__ = """\
This script checks the active mesh for open or non-manifold edges.

If all edges have exactly 2 faces, this means we have a perfectly closed manifold mesh.

Otherwise, the 1-face or 3-face meshes are selected, so you can fix them easily...
"""

# ***** BEGIN GPL LICENSE BLOCK *****
#
# 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 *****

import Blender,BPyMessages
from Blender import Mesh,Scene,Window

def search(mymesh):
	culprits=[]
	for e in mymesh.edges:
		e.sel = 0
		shared=0
		for f in mymesh.faces:
			for vf1 in f.v:
				if vf1 == e.v1:
					for vf2 in f.v:
						if vf2 == e.v2:
							shared = shared+1
		if (shared > 2):
			# non-manifold
			culprits.append(e)
			e.sel=1
		if (shared < 2):
			# open
			culprits.append(e)
			e.sel=1
	return culprits

def main():

		# Gets the current scene, there can be many scenes in 1 blend file.
		sce = Scene.GetCurrent()

		# Get the active object, there can only ever be 1
		# and the active object is always the editmode object.
		ob_act = sce.objects.active

		if not ob_act or ob_act.type != 'Mesh':
				BPyMessages.Error_NoMeshActive()
				return 

		# Saves the editmode state and go's out of 
		# editmode if its enabled, we cant make
		# changes to the mesh data while in editmode.
		is_editmode = Window.EditMode()
		if is_editmode: Window.EditMode(1)

		Window.WaitCursor(1)

		mymesh = ob_act.getData(mesh=1)
		culprits = search(mymesh)

		if len(culprits) == 0:
			print "No problematic edge. This mesh is manifold."
		else:
			print "Found ",len(culprits)," problematic edges."

		Window.WaitCursor(0)
		Blender.Redraw()


# This lets you import the script without running it
if __name__ == '__main__':
		main()
