#!/usr/bin/python
# -*- coding:Utf-8 -*-
#############################################################
#  Convertisseur de fichier .dxf vers .elmt Qelectrotech    #
#   Nécessite le paquet libdime sous Debian                 #
#   apt-get install libdime                                 #
#   Copier ce fichier dans un répertoire contenant les      #
#   fichiers dxf, puis exécuter ce programme:               #
#   chmod a+x convert_dxf_elmt.py                           #
#   ./convert_dxf_elmt.py                                   #
#   Pas testé sous windows                                  #
# A utiliser tel que, sans aucune garantie de fonctionnement#
# Contact=> baNO_SPAMbouNO_SPAM2607NO_SPAMyahooNO_SPAMfr    #
#############################################################
#from __future__ import with_statement # This isn't required in Python 2.6
print "il faut installer le paquet libdime http://www.coin3d.org/lib/dime/"
print
import os
listefichier = os.listdir(os.getcwd())
dxfile = []
for i in range(0,len(listefichier)):
    if listefichier[i][-3:]=="dxf":
        dxfile.append(listefichier[i])
print "Liste des fichiers dxf dans ce dossier:\n",dxfile
print
nbdxf=dirx=diry=0
zoom=raw_input('Entrez la valeur de zoom defaut[3]')
if zoom=="": zoom="3"#facteur de zoom=>0.5pour/2  3 pour x3
zoom=eval(zoom)
while len(dxfile)>nbdxf:
    os.system('dxf2vrml '+dxfile[nbdxf]+' -o '+ dxfile[nbdxf][:-3]+'wrl -vrml2')
    print "Conversion fichier: "+dxfile[nbdxf]+" en fichier: "+ dxfile[nbdxf][:-3]+"elmt"
    print "Patientez..."
    maxiy=miniy=maxix=minix=dir_hotspot_x=dir_hotspot_y=0
    fichier_sauve = open(dxfile[nbdxf][:-3]+'elmt', 'w')
    fichier_sauve.write('<definition width="160" version="0.2" hotspot_x="160" hotspot_y="110" height="110" type="element" orientation="dyyy" >\n')
    fichier_sauve.write('    <names>\n')
    fichier_sauve.write('        <name lang="fr" >'+dxfile[nbdxf][:-4]+'</name>\n')
    fichier_sauve.write('        <name lang="en" >Name of element</name>\n')
    fichier_sauve.write('    </names>\n')
    fichier_sauve.write('    <description>\n')
    fichier = open(dxfile[nbdxf][:-3]+'wrl', 'rt') 
    #zoom=3 #facteur de zoom=>0.5pour/2  3 pour x3 
    ligne=fichier.readline()
    while ligne!="":#tant que pas à la fin du fichier
        if ligne.strip() == "point [":#si chaine point (strip enléve les espaces)
                ligne=fichier.readline()
                nb=0
                listepoint=[]
                while ligne.strip() != "]":#tant que pas la fin des points
                    chaine=ligne.strip()#efface les espaces
                    liste=chaine.split(" ")#découpe la chaine en liste
                    x=eval(liste[0])*zoom #texte x vers chiffre puis on zoom
                    y=eval(liste[1])*zoom #texte y vers chiffre puis on zoom
                    x=int(round(x,2))#arrondi en prenant 2 decimales puis integer puis string
                    y=int(round(y,2))#arrondi en prenant 2 decimales puis integer puis string
                    listepoint.append([x,y])
                    #print "point numero %d="%nb, "x=",listepoint[nb][0],"y=",listepoint[nb][1]
                    if listepoint[nb][1]>maxiy:maxiy=listepoint[nb][1]#memorise valeur maxi y
                    if listepoint[nb][1]<miniy:miniy=listepoint[nb][1]#memorise valeur mini y
                    if listepoint[nb][0]>maxix:maxix=listepoint[nb][0]#memorise valeur maxi x
                    if listepoint[nb][0]<minix:minix=listepoint[nb][0]#memorise valeur mini x
                    ligne=fichier.readline()
                    nb+=1#compteur de nombre de points uniquement pour déboguage
                nb=0
                ligne=fichier.readline()#on saute }
                ligne=fichier.readline()#on saute coordIndex [
                ligne=fichier.readline()#on lit la ligne qui vient 
                #print
                chainecoord=""
                while ligne.strip() != "]":#tant que pas la fin des coordIndex
                    chainecoord=chainecoord+ligne.strip()
                    ligne=fichier.readline()
                #print chainecoord
                listecoord=chainecoord.split(",")
                #print listecoord
                nbcoord=0
                while len(listecoord)>nbcoord:
                    #print listecoord[nbcoord]
                    if listecoord[nbcoord]=="-1":
                        nbcoord+=1
                    else:
                        y1=(-listepoint[eval(listecoord[nbcoord])][1])# -listepoint on recupere y1 du vrml, mais l'axe des y est inversé sur qelectro
                        x1=(listepoint[eval(listecoord[nbcoord])][0])# on recupere x1 du vrml
                        #x1,y1=-y1,x1 # pour pivoter la vue de 90° a droite
                        y2=(-listepoint[eval(listecoord[nbcoord+1])][1])# -listepoint on recupere y2 du vrml, mais l'axe des y est inversé sur qelectro
                        x2=(listepoint[eval(listecoord[nbcoord+1])][0])# on recupere x2 du vrml
                        #x2,y2=-y2,x2 # pour pivoter la vue de 90° a droite
                        if x1==0 and y1==0: dirx,diry=x2,y2                    
                        if x2==0 and y2==0: dirx,diry=x1,y1            
                        if x1==x2 or y1==y2: antialias="false"
                        else:
                            antialias="true"
                        nbcoord+=1
                        fichier_sauve.write('        <line length1="1,5" length2="1,5" antialias="'+antialias+'" end1="none" end2="none" style="line-style:normal;line-weight:normal;filling:none;color:black"')
                        fichier_sauve.write(' y1="'+str(y1)+'" x1="'+str(x1)+'"'),
                        fichier_sauve.write(' y2="'+str(y2)+'" x2="'+str(x2)+'"/>\n')
                        if listecoord[nbcoord+1]=="-1":
                            nbcoord+=1
                    #print nbcoord,len(listecoord)
        ligne=fichier.readline()
    fichier.close()
    if dirx==0:
        if diry>0: orientation="n"
        else: orientation="s"
    if diry==0:
        if dirx>0: orientation="w"
        else: orientation="e"
    fichier_sauve.write('<terminal x="0" y="0" orientation="'+orientation+'" />') #la borne
    fichier_sauve.write('    </description>\n')
    fichier_sauve.write('</definition>\n')
    fichier_sauve.seek(0,0)#on se deplace au début du fichier
    fichier_sauve.tell()#on valide le deplacement
    width=abs(minix)+abs(maxix)
    width=(-int(-width / 10) * 10) +20 #arrondi a la dizaine sup + 20 -Int(-valeur / pas) * pas
    hotspot_x=int((width-(abs(minix)+abs(maxix)))/2)+abs(minix) #on centre
    hotspot_x=(int(hotspot_x / 10) * 10) #Int(valeur / pas) * pas arrondi inferieur
    if hotspot_x<100: hotspot_x='0'+str(hotspot_x) #pour eviter d'ecraser le fichier et conserver la meme lg de chaine
    else:
        hotspot_x=str(hotspot_x) #transtypage de la même variable
    if width<100: width='0'+str(width)
    else:
        width=str(width)
    height=abs(miniy)+abs(maxiy)
    height=(-int(-height / 10) * 10) + 20 #arrondi a la dizaine sup + 20 -Int(-valeur / pas) * pas
    hotspot_y=int((height-(abs(miniy)+abs(maxiy)))/2)+abs(maxiy) #on centre
    hotspot_y=(int(hotspot_y / 10) * 10) #Int(valeur / pas) * pas arrondi inferieur
    if hotspot_y<100: hotspot_y='0'+str(hotspot_y)
    else:
        hotspot_y=str(hotspot_y)
    if height<100: height='0'+str(height)
    else:
        height=str(height)
    fichier_sauve.write('<definition width="'+width+'" version="0.2" hotspot_x="'+hotspot_x+'" hotspot_y="'+hotspot_y+'" height="'+height+'" type="element" orientation="dyyy" >\n')
    fichier_sauve.close()
    #print "Ok! dimension: xmini,xmaxi,ymini,ymaxi,dir_hotspot_x,dir_hotspot_y",minix,maxix,miniy,maxiy,dir_hotspot_x,dir_hotspot_y
    #print "Ok! dimension: hotspot_x,hotspot_y,width,height",hotspot_x,hotspot_y,width,height
    nbdxf+=1
os.system('rm *.wrl')
