#!BPY
# -*- coding: iso8859-1 -*- 
"""
Name: 'Exporter infos scènes'
Blender: 240
Group: 'Export'
Tooltip: 'Exporte les informations sur les scènes'
"""

__author__ = "VVPix"
__url__ = ("www.vvpix.com/bld_Index.htm")
__version__ = "1.00"

__bpydoc__ = """\
Ce script exporte les informations sur les scènes.
"""

# ***** 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 *****

# V 1.00 : première version

import Blender
from Blender import Draw, BGL, Window, Scene, NMesh, Armature, Mathutils, sys, Object, Scene, Text
import BPyMesh
import BPyMessages
import platform
import os
import webbrowser


# v1.00 : première version


def writeSeparateur( file ):
	file.write( "-------------------------------------------------------\n" )

def writeTitre( file, strTitre ):
	writeSeparateur( file )
	file.write( "  %s\n"%(strTitre))
	writeSeparateur( file )


def afficherInfos( file, bAfficherInfosScenes, \
								 bAfficherInfosLayers, \
								 bAfficherInfosObjets, \
								 bAfficherInfosMaillages, \
								 bAfficherInfosMaterials, \
								 bAfficherInfosCurves, \
								 bAfficherInfosLamp, \
								 bAfficherInfosCamera ):
	
	# Affichage des informations sur les scènes
	if bAfficherInfosScenes == 1:
		writeTitre( file, "Scene" )
	lst_scenes = Scene.Get()
	nb_scenes = len( lst_scenes )
	lst_noms_obj_scenes=[]
	if bAfficherInfosScenes == 1:
		file.write ("Nb de scenes : %d\n"%( nb_scenes ) )
		sceneCourante = Scene.GetCurrent()
		for scene in lst_scenes:
			scene.update(1)
			if scene == sceneCourante:
				file.write ("\n- scene \"%s\" (scene courante)\n"%( scene.getName() ) )
			else:
				file.write ("\n- scene \"%s\"\n"%( scene.getName() ) )
			for obj in scene.objects:
				if not obj.getName() in lst_noms_obj_scenes:
					lst_noms_obj_scenes.append( obj.getName() )
				bAfficher = True
				if obj.getType() == "Lamp" and not bAfficherInfosLamp:
					bAfficher = False
				if obj.getType() == "Camera" and not bAfficherInfosCamera:
					bAfficher = False
				#
				if bAfficher:
					file.write("  - obj type=\"%s\", nom=\"%s\"\n"%(obj.getType(), obj.getName()) )
		file.write("\n")
	
	# Affichage des informations sur chacun des calques de chaque scène
	if bAfficherInfosLayers == 1:
		writeTitre( file, "Calques" )
	for scene in lst_scenes:
		lstCalques = scene.getLayers()
		nbCalques = len( lstCalques )
		if bAfficherInfosLayers == 1:
			file.write("Scene : \"%s\", %d calque(s)\n"%(scene.getName(), nbCalques ))
			if nbCalques > 0:
				for calque in lstCalques:
					file.write("%d "%( calque ))
				file.write("\n")
			file.write("\n")
	
	# Affichage des informations sur les maillages
	lst_mesh = Blender.Mesh.Get()
	lst_mesh_names = NMesh.GetNames()
	if bAfficherInfosMaillages == 1:
		writeTitre( file, "Maillages" )
	nbMesh = len(lst_mesh)
	if bAfficherInfosMaillages == 1:
		file.write("Nb de maillages = %d\n"%( nbMesh ))
		for nom_mesh in lst_mesh_names:
			file.write("- mesh \"%s\"\n"%( nom_mesh ))
		file.write("\n")
	
	# Affichage des informations sur les objets
	lst_obj = Blender.Object.Get()
	nbObj = len(lst_obj)
	if bAfficherInfosObjets == 1:
		writeTitre( file, "Objets" )
		file.write("Nb total d'objets : %d\n"%( nbObj ) )
		file.write("Objets lies à une scene : %d (voir rubrique scène)\n"%(len( lst_noms_obj_scenes) ))
		file.write("Objets non lies à une scene %d :\n"%( nbObj - len( lst_noms_obj_scenes) ) )
		for obj in lst_obj:
			# recherche de la scène correspondante pour cet objet (si elle existe)
			strNomScene = ""
			for scene in lst_scenes:
				if obj in scene.getChildren():
					strNomScene = scene.getName()
			if strNomScene == "":
				bAfficher = True
				if obj.getType() == "Lamp" and not bAfficherInfosLamp:
					bAfficher = False
				if obj.getType() == "Camera" and not bAfficherInfosCamera:
					bAfficher = False
				if bAfficher:
					file.write("- obj type=\"%s\", nom=\"%s\"\n"%(obj.getType(), obj.getName()) )
			
		file.write("\n")
	
	# Détail des materiaux des objets
	if bAfficherInfosMaterials == 1:
		writeTitre( file, "Info materials (pour les objets des scènes)" )
		for scene in lst_scenes:
			for obj in scene.objects:
				#print obj.getType()
				if obj.getType().lower() != "text":
					lst_mat = obj.getMaterials(1)
					nbMateriaux = len( lst_mat )
					if nbMateriaux > 0:
						file.write("- obj type=\"%s\", nom=\"%s\", nb materiaux=\"%d\"\n"%(obj.getType(), \
																												obj.getName(), \
																												nbMateriaux ) )
						mesh = obj.getData(mesh=1)
						mat = mesh.materials[0]
						file.write ("  - couleur materiau :")
						file.write (" r=\"%.2f\", v=\"%.2f\", b=\"%.2f\"\n"%( mat.rgbCol[0], \
																						mat.rgbCol[1], \
																						mat.rgbCol[2] ))
						file.write ("\n")
	
	# Détails sur les courbes
	if bAfficherInfosCurves == 1:
		writeTitre( file, "Info curves" )
		for obj in scene.objects:
			#print obj.getType()
			if obj.getType().lower() == "curve":
				file.write("- obj type=\"%s\", nom=\"%s\"\n"%(obj.getType(), obj.getName()) )
				loc = obj.getLocation()
				file.write( " - Position\n")
				file.write( " - ->> X = %f, Y = %f, Z = %f\n"%(loc[0], loc[1], loc[2] ))
				rot = obj.getEuler()
				file.write( " - Rotation\n")
				file.write( " - ->> X = %f, Y = %f, Z = %f\n"%(rot[0], rot[1], rot[2] ))
				curvedata = obj.getData()
				file.write("- - nb curvedata = %d \n"%( len(curvedata) ) )
				numCourbe = 1
				for curnurb in curvedata:
					file.write("- - courbe numero %d , type %d (0-Poly, 1-Bezier, 4-NURBS)\n"%( numCourbe, curnurb.getType() ) )
					file.write("- - nb points = %d \n"%( len( curnurb ) ) )
					if curnurb.getType() == 1:# Bezier
						nNumPt = 1
						for pt in curnurb:
							file.write( " - - Point %d\n"%(nNumPt))
							listePt = pt.getTriple()
							for t in listePt:
								file.write( " - ->> X = %f, Y = %f, Z = %f\n"%(t[0], t[1], t[2] ))
							nNumPt += 1
					else:
						file.write(" courbe inconnue")
					numCourbe += 1
				file.write ("\n")
		
	# Détail des armatures
	arms = Armature.Get()
	for arm in arms.values():
		print "Draw type" , arm.drawType
		for bone in arm.bones.values():
			print "Bone parent = ", bone.parent, "nom = " , bone.name


def fx():
	
	lst_obj = Blender.Object.Get()
	nbObj = len(lst_obj)
	print "Nb objets = %d"%(nbObj)
	obj = lst_obj[13]
	print "Objet type %s, nom : %s, type : %s"%( type(obj), obj.getName(), obj.getType())

	lst_mat = obj.getMaterials(1)
	nbMaterials = len(lst_mat)
	print "Nb materiaux : %d"%(nbMaterials)

	scene = Scene.GetCurrent()	
	lst_obj_scene = scene.getChildren() 
	print "Nb d'objets lies a cette scene : %d"%(len(lst_obj_scene))

	for obj in lst_obj:
		if obj in lst_obj_scene:
			print "Objet dans la scene : %s"%(obj.getName())
		else:
			print "Objet hors scene %s"%(obj.getName())
			



def draw_gui():
	INFOS_SCENES = Draw.Create(1)
	INFOS_LAYERS = Draw.Create(1)
	INFOS_OBJECTS = Draw.Create(1)
	INFOS_MESH = Draw.Create(1)
	INFOS_MATERIALS = Draw.Create(1)
	INFOS_CURVES = Draw.Create(1)
	INFOS_LAMPS = Draw.Create(0)
	INFOS_CAMERAS = Draw.Create(0)
	
	# Get USER Options
	pup_block= [\
	'Choix des informations à exporter :',\
	('Scenes', INFOS_SCENES, 'Affiche les informations des scènes'),\
	('Layers', INFOS_LAYERS, 'Affiche les informations des calques (layers)'),\
	('Objects', INFOS_OBJECTS, 'Affiche les informations sur les objets'),\
	('Mesh', INFOS_MESH, 'Affiche les informations sur les courbes'),\
	('Materials', INFOS_MATERIALS, 'Affiche les informations sur les materiaux'),\
	('Curves', INFOS_CURVES, 'Affiche les informations sur les courbes'),\
	('Lamps', INFOS_LAMPS, 'Affiche les informations sur les lampes'),\
	('Cameras', INFOS_CAMERAS, 'Affiche les informations sur les caméras'),\
	]
	
	if not Draw.PupBlock('Choix des informations à exporter', pup_block):
		return
		
	Window.WaitCursor(1)
	# Placement du répertoire courant dans le chemin des scripts utilisateur
	strScriptDir = Blender.Get('uscriptsdir')
	if os.getcwd() != strScriptDir:
		os.chdir( strScriptDir )
	print "Chemin courant : %s"%(os.getcwd())
	
	strFichierLog = "logBlenderInformation.txt"
	if not strScriptDir.endswith( os.sep ):
		strScriptDir += os.sep
	strFichierLog = strScriptDir + strFichierLog
	file = open( strFichierLog, "w")
	
	Blender.UpdateMenus()
	
	afficherInfos( file, \
						INFOS_SCENES.val, \
						INFOS_LAYERS.val, \
						INFOS_OBJECTS.val, \
						INFOS_MESH.val, \
						INFOS_MATERIALS.val, \
						INFOS_CURVES.val, \
						INFOS_LAMPS.val, \
						INFOS_CAMERAS.val )
	
	file.close()
	
	if ( platform.system().lower() == "windows" ):
		os.startfile( strFichierLog )
	elif ( platform.system().lower() == "linux" ):
		webbrowser.open( strFichierLog )
	else:
		print platform.system()
	strM = "Information%t|"
	strM += "Le résultat est dans le fichier \"%s\""%(strFichierLog)
	Draw.PupMenu( strM )
	Window.WaitCursor(0)


# Effacement du texte de la console
if ( platform.system() == "Windows" ):
	os.system('cls') # pour Windows
else:
	os.system('clear') # pour Linux
print "--- debut du script ---"
draw_gui()
print "--- fin du script ---"



