use f.area where possible over python function and use len(mface) over len(mface.v)
[blender.git] / release / scripts / x3d_export.py
1 #!BPY
2 """ Registration info for Blender menus:
3 Name: 'X3D Extensible 3D (.x3d)...'
4 Blender: 235
5 Group: 'Export'
6 Submenu: 'All Objects...' all
7 Submenu: 'All Objects compressed...' comp
8 Submenu: 'Selected Objects...' selected
9 Tooltip: 'Export to Extensible 3D file (.x3d)'
10 """
11
12 __author__ = ("Bart")
13 __email__ = ["Bart, bart:neeneenee*de"]
14 __url__ = ["Author's (Bart) homepage, http://www.neeneenee.de/vrml"]
15 __version__ = "2006/01/17"
16 __bpydoc__ = """\
17 This script exports to X3D format.
18
19 Usage:
20
21 Run this script from "File->Export" menu.  A pop-up will ask whether you
22 want to export only selected or all relevant objects.
23
24 Known issues:<br>
25     Doesn't handle multiple materials (don't use material indices);<br>
26     Doesn't handle multiple UV textures on a single mesh (create a mesh
27 for each texture);<br>
28     Can't get the texture array associated with material * not the UV ones;
29 """
30
31
32 # $Id$
33 #
34 #------------------------------------------------------------------------
35 # X3D exporter for blender 2.36 or above
36 #
37 # ***** BEGIN GPL LICENSE BLOCK *****
38 #
39 # This program is free software; you can redistribute it and/or
40 # modify it under the terms of the GNU General Public License
41 # as published by the Free Software Foundation; either version 2
42 # of the License, or (at your option) any later version.
43 #
44 # This program is distributed in the hope that it will be useful,
45 # but WITHOUT ANY WARRANTY; without even the implied warranty of
46 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
47 # GNU General Public License for more details.
48 #
49 # You should have received a copy of the GNU General Public License
50 # along with this program; if not, write to the Free Software Foundation,
51 # Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
52 #
53 # ***** END GPL LICENCE BLOCK *****
54 #
55
56 ####################################
57 # Library dependancies
58 ####################################
59
60 import Blender
61 from Blender import Object, NMesh, Lamp, Draw, BGL, Image, Text, sys, Mathutils
62 from Blender.Scene import Render
63 try:
64     from os.path import exists, join
65     pytinst = 1
66 except:
67     print "No Python installed, for full features install Python (http://www.python.org/)."
68     pytinst = 0
69 import math
70
71 ####################################
72 # Global Variables
73 ####################################
74
75 scene = Blender.Scene.getCurrent()
76 world = Blender.World.Get() 
77 worldmat = Blender.Texture.Get()
78 filename = Blender.Get('filename')
79 _safeOverwrite = True
80 ARG=''
81 extension = ''
82
83 class DrawTypes:
84     """Object DrawTypes enum values
85     BOUNDS - draw only the bounding box of the object
86     WIRE - draw object as a wire frame
87     SOLID - draw object with flat shading
88     SHADED - draw object with OpenGL shading
89 """
90     BOUNDBOX  = 1
91     WIRE      = 2
92     SOLID     = 3
93     SHADED    = 4
94     TEXTURE   = 5
95
96 if not hasattr(Blender.Object,'DrawTypes'):
97     Blender.Object.DrawTypes = DrawTypes()
98
99 ##########################################################
100 # Functions for writing output file
101 ##########################################################
102
103 class VRML2Export:
104
105     def __init__(self, filename):
106         #--- public you can change these ---
107         self.writingcolor = 0
108         self.writingtexture = 0
109         self.writingcoords = 0
110         self.wire = 0
111         self.proto = 1
112         self.matonly = 0
113         self.share = 0
114         self.billnode = 0
115         self.halonode = 0
116         self.collnode = 0
117         self.tilenode = 0
118         self.verbose=2     # level of verbosity in console 0-none, 1-some, 2-most
119         self.cp=3          # decimals for material color values     0.000 - 1.000
120         self.vp=3          # decimals for vertex coordinate values  0.000 - n.000
121         self.tp=3          # decimals for texture coordinate values 0.000 - 1.000
122         self.it=3
123         
124         #--- class private don't touch ---
125         self.texNames={}   # dictionary of textureNames
126         self.matNames={}   # dictionary of materiaNames
127         self.meshNames={}   # dictionary of meshNames
128         self.indentLevel=0 # keeps track of current indenting
129         self.filename=filename
130         self.file = open(filename, "w")
131         self.bNav=0
132         self.nodeID=0
133         self.namesReserved=[ "Anchor","Appearance","Arc2D","ArcClose2D","AudioClip","Background","Billboard",
134                              "BooleanFilter","BooleanSequencer","BooleanToggle","BooleanTrigger","Box","Circle2D",
135                              "Collision","Color","ColorInterpolator","ColorRGBA","component","Cone","connect",
136                              "Contour2D","ContourPolyline2D","Coordinate","CoordinateDouble","CoordinateInterpolator",
137                              "CoordinateInterpolator2D","Cylinder","CylinderSensor","DirectionalLight","Disk2D",
138                              "ElevationGrid","EspduTransform","EXPORT","ExternProtoDeclare","Extrusion","field",
139                              "fieldValue","FillProperties","Fog","FontStyle","GeoCoordinate","GeoElevationGrid",
140                              "GeoLocation","GeoLOD","GeoMetadata","GeoOrigin","GeoPositionInterpolator",
141                              "GeoTouchSensor","GeoViewpoint","Group","HAnimDisplacer","HAnimHumanoid","HAnimJoint",
142                              "HAnimSegment","HAnimSite","head","ImageTexture","IMPORT","IndexedFaceSet",
143                              "IndexedLineSet","IndexedTriangleFanSet","IndexedTriangleSet","IndexedTriangleStripSet",
144                              "Inline","IntegerSequencer","IntegerTrigger","IS","KeySensor","LineProperties","LineSet",
145                              "LoadSensor","LOD","Material","meta","MetadataDouble","MetadataFloat","MetadataInteger",
146                              "MetadataSet","MetadataString","MovieTexture","MultiTexture","MultiTextureCoordinate",
147                              "MultiTextureTransform","NavigationInfo","Normal","NormalInterpolator","NurbsCurve",
148                              "NurbsCurve2D","NurbsOrientationInterpolator","NurbsPatchSurface",
149                              "NurbsPositionInterpolator","NurbsSet","NurbsSurfaceInterpolator","NurbsSweptSurface",
150                              "NurbsSwungSurface","NurbsTextureCoordinate","NurbsTrimmedSurface","OrientationInterpolator",
151                              "PixelTexture","PlaneSensor","PointLight","PointSet","Polyline2D","Polypoint2D",
152                              "PositionInterpolator","PositionInterpolator2D","ProtoBody","ProtoDeclare","ProtoInstance",
153                              "ProtoInterface","ProximitySensor","ReceiverPdu","Rectangle2D","ROUTE","ScalarInterpolator",
154                              "Scene","Script","Shape","SignalPdu","Sound","Sphere","SphereSensor","SpotLight","StaticGroup",
155                              "StringSensor","Switch","Text","TextureBackground","TextureCoordinate","TextureCoordinateGenerator",
156                              "TextureTransform","TimeSensor","TimeTrigger","TouchSensor","Transform","TransmitterPdu",
157                              "TriangleFanSet","TriangleSet","TriangleSet2D","TriangleStripSet","Viewpoint","VisibilitySensor",
158                              "WorldInfo","X3D","XvlShell","VertexShader","FragmentShader","MultiShaderAppearance","ShaderAppearance" ]
159         self.namesStandard=[ "Empty","Empty.000","Empty.001","Empty.002","Empty.003","Empty.004","Empty.005",
160                              "Empty.006","Empty.007","Empty.008","Empty.009","Empty.010","Empty.011","Empty.012",
161                              "Scene.001","Scene.002","Scene.003","Scene.004","Scene.005","Scene.06","Scene.013",
162                              "Scene.006","Scene.007","Scene.008","Scene.009","Scene.010","Scene.011","Scene.012",
163                              "World","World.000","World.001","World.002","World.003","World.004","World.005" ]
164         self.namesFog=[ "","LINEAR","EXPONENTIAL","" ]
165
166 ##########################################################
167 # Writing nodes routines
168 ##########################################################
169
170     def writeHeader(self):
171         bfile = sys.expandpath(Blender.Get('filename'))
172         self.file.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
173         self.file.write("<!DOCTYPE X3D PUBLIC \"ISO//Web3D//DTD X3D 3.0//EN\" \"http://www.web3d.org/specifications/x3d-3.0.dtd\">\n")
174         self.file.write("<X3D version=\"3.0\" profile=\"Immersive\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema-instance\" xsd:noNamespaceSchemaLocation=\"http://www.web3d.org/specifications/x3d-3.0.xsd\">\n")
175         self.file.write("<head>\n")
176         self.file.write("\t<meta name=\"filename\" content=\"%s\" />\n" % sys.basename(bfile))
177         self.file.write("\t<meta name=\"generator\" content=\"Blender %s\" />\n" % Blender.Get('version'))
178         self.file.write("\t<meta name=\"translator\" content=\"X3D exporter v1.55 (2006/01/17)\" />\n")
179         self.file.write("</head>\n")
180         self.file.write("<Scene>\n")
181
182     def writeInline(self):
183         inlines = Blender.Scene.Get()
184         allinlines = len(inlines)
185         if scene != inlines[0]:
186             return
187         else:
188             for i in range(allinlines):
189                 nameinline=inlines[i].getName()
190                 if (nameinline not in self.namesStandard) and (i > 0):
191                     self.file.write("<Inline DEF=\"%s\" " % (self.cleanStr(nameinline)))
192                     nameinline = nameinline+".x3d"
193                     self.file.write("url=\"%s\" />" % nameinline)
194                     self.file.write("\n\n")
195
196     def writeScript(self):
197         textEditor = Blender.Text.Get() 
198         alltext = len(textEditor)
199         for i in range(alltext):
200             nametext = textEditor[i].getName()
201             nlines = textEditor[i].getNLines()
202             if (self.proto == 1):
203                 if (nametext == "proto" or nametext == "proto.js" or nametext == "proto.txt") and (nlines != None):
204                     nalllines = len(textEditor[i].asLines())
205                     alllines = textEditor[i].asLines()
206                     for j in range(nalllines):
207                         self.writeIndented(alllines[j] + "\n")
208             elif (self.proto == 0):
209                 if (nametext == "route" or nametext == "route.js" or nametext == "route.txt") and (nlines != None):
210                     nalllines = len(textEditor[i].asLines())
211                     alllines = textEditor[i].asLines()
212                     for j in range(nalllines):
213                         self.writeIndented(alllines[j] + "\n")
214         self.writeIndented("\n")
215
216     def writeViewpoint(self, thisObj):
217         context = scene.getRenderingContext()
218         ratio = float(context.imageSizeY())/float(context.imageSizeX())
219         lens = (360* (math.atan(ratio *16 / thisObj.data.getLens()) / math.pi))*(math.pi/180)
220         lens = min(lens, math.pi) 
221         # get the camera location, subtract 90 degress from X to orient like X3D does
222         loc = self.rotatePointForVRML(thisObj.loc)
223         rot = [thisObj.RotX - 1.57, thisObj.RotY, thisObj.RotZ]
224         nRot = self.rotatePointForVRML(rot)
225         # convert to Quaternion and to Angle Axis
226         Q  = self.eulerToQuaternions(nRot[0], nRot[1], nRot[2])
227         Q1 = self.multiplyQuaternions(Q[0], Q[1])
228         Qf = self.multiplyQuaternions(Q1, Q[2])
229         angleAxis = self.quaternionToAngleAxis(Qf)
230         self.file.write("<Viewpoint DEF=\"%s\" " % (self.cleanStr(thisObj.name)))
231         self.file.write("description=\"%s\" " % (thisObj.name))
232         self.file.write("centerOfRotation=\"0 0 0\" ")
233         self.file.write("position=\"%3.2f %3.2f %3.2f\" " % (loc[0], loc[1], loc[2]))
234         self.file.write("orientation=\"%3.2f %3.2f %3.2f %3.2f\" " % (angleAxis[0], angleAxis[1], -angleAxis[2], angleAxis[3]))
235         self.file.write("fieldOfView=\"%.3f\" />\n\n" % (lens))
236
237     def writeFog(self):
238         if len(world) > 0:
239             mtype = world[0].getMistype()
240             mparam = world[0].getMist()
241             grd = world[0].getHor()
242             grd0, grd1, grd2 = grd[0], grd[1], grd[2]
243         else:
244             return
245         if (mtype == 1 or mtype == 2):
246             self.file.write("<Fog fogType=\"%s\" " % self.namesFog[mtype])                                              
247             self.file.write("color=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
248             self.file.write("visibilityRange=\"%s\" />\n\n" % round(mparam[2],self.cp))
249         else:
250             return
251
252     def writeNavigationInfo(self, scene):
253         allObj = []
254         allObj = scene.getChildren()
255         headlight = "TRUE"
256         vislimit = 0.0
257         for thisObj in allObj:
258             objType=thisObj.getType()
259             if objType == "Camera":
260                 vislimit = thisObj.data.getClipEnd()
261             elif objType == "Lamp":
262                 headlight = "FALSE"
263         self.file.write("<NavigationInfo headlight=\"%s\" " % headlight)
264         self.file.write("visibilityLimit=\"%s\" " % (round(vislimit,self.cp)))
265         self.file.write("type=\"EXAMINE, ANY\" avatarSize=\"0.25, 1.75, 0.75\" />\n\n")
266
267     def writeSpotLight(self, object, lamp):
268         safeName = self.cleanStr(object.name)
269         if len(world) > 0:
270             ambi = world[0].getAmb()
271             ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
272         else:
273             ambi = 0
274             ambientIntensity = 0
275
276         # compute cutoff and beamwidth
277         intensity=min(lamp.energy/1.75,1.0)
278         beamWidth=((lamp.spotSize*math.pi)/180.0)*.37;
279         cutOffAngle=beamWidth*1.3
280
281         (dx,dy,dz)=self.computeDirection(object)
282         # note -dx seems to equal om[3][0]
283         # note -dz seems to equal om[3][1]
284         # note  dy seems to equal om[3][2]
285         om = object.getMatrix()
286             
287         location=self.rotVertex(om, (0,0,0));
288         radius = lamp.dist*math.cos(beamWidth)
289         self.file.write("<SpotLight DEF=\"%s\" " % safeName)
290         self.file.write("radius=\"%s\" " % (round(radius,self.cp)))
291         self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
292         self.file.write("intensity=\"%s\" " % (round(intensity,self.cp)))
293         self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
294         self.file.write("beamWidth=\"%s\" " % (round(beamWidth,self.cp)))
295         self.file.write("cutOffAngle=\"%s\" " % (round(cutOffAngle,self.cp)))
296         self.file.write("direction=\"%s %s %s\" " % (round(dx,3),round(dy,3),round(dz,3)))
297         self.file.write("location=\"%s %s %s\" />\n\n" % (round(location[0],3), round(location[1],3), round(location[2],3)))
298         
299     def writeDirectionalLight(self, object, lamp):
300         safeName = self.cleanStr(object.name)
301         if len(world) > 0:
302             ambi = world[0].getAmb()
303             ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
304         else:
305             ambi = 0
306             ambientIntensity = 0
307
308         intensity=min(lamp.energy/1.75,1.0) 
309         (dx,dy,dz)=self.computeDirection(object)
310         self.file.write("<DirectionalLight DEF=\"%s\" " % safeName)
311         self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
312         self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
313         self.file.write("intensity=\"%s\" " % (round(intensity,self.cp)))
314         self.file.write("direction=\"%s %s %s\" />\n\n" % (round(dx,4),round(dy,4),round(dz,4)))
315
316     def writePointLight(self, object, lamp):
317         safeName = self.cleanStr(object.name)
318         if len(world) > 0:
319             ambi = world[0].getAmb()
320             ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
321         else:
322             ambi = 0
323             ambientIntensity = 0
324         om = object.getMatrix()
325         location=self.rotVertex(om, (0,0,0));
326         intensity=min(lamp.energy/1.75,1.0) 
327         radius = lamp.dist
328         self.file.write("<PointLight DEF=\"%s\" " % safeName)
329         self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
330         self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
331         self.file.write("intensity=\"%s\" " % (round(intensity,self.cp)))
332         self.file.write("radius=\"%s\" " % radius )
333         self.file.write("location=\"%s %s %s\" />\n\n" % (round(location[0],3), round(location[1],3), round(location[2],3)))
334
335     def writeNode(self, thisObj):
336         objectname=str(thisObj.getName())
337         if objectname in self.namesStandard:
338             return
339         else:
340             (dx,dy,dz)=self.computeDirection(thisObj)
341             om = thisObj.getMatrix()
342             location=self.rotVertex(om, (0,0,0));
343             self.writeIndented("<%s\n" % objectname,1)
344             self.writeIndented("# direction %s %s %s\n" % (round(dx,3),round(dy,3),round(dz,3)))
345             self.writeIndented("# location %s %s %s\n" % (round(location[0],3), round(location[1],3), round(location[2],3)))
346             self.writeIndented("/>\n",-1)
347             self.writeIndented("\n")
348
349     def secureName(self, name):
350         name = name + str(self.nodeID)
351         self.nodeID=self.nodeID+1
352         if len(name) <= 3:
353             newname = "_" + str(self.nodeID)
354             return "%s" % (newname)
355         else:
356             for bad in ['"','#',"'",',','.','[','\\',']','{','}']:
357                 name=name.replace(bad,'_')
358             if name in self.namesReserved:
359                 newname = name[0:3] + "_" + str(self.nodeID)
360                 return "%s" % (newname)
361             elif name[0].isdigit():
362                 newname = "_" + name + str(self.nodeID)
363                 return "%s" % (newname)
364             else:
365                 newname = name
366                 return "%s" % (newname)
367
368     def writeIndexedFaceSet(self, object, normals = 0):
369         imageMap={}   # set of used images
370         sided={}      # 'one':cnt , 'two':cnt
371         vColors={}    # 'multi':1
372         meshName = self.cleanStr(object.name)
373         mesh=object.getData()
374         meshME = self.cleanStr(mesh.name)
375         if len(mesh.faces) == 0:
376                                         return
377         for face in mesh.faces:
378             if face.mode & Blender.NMesh.FaceModes['HALO'] and self.halonode == 0:
379                 self.writeIndented("<Billboard axisOfRotation=\"0 0 0\">\n",1)
380                 self.halonode = 1
381             elif face.mode & Blender.NMesh.FaceModes['BILLBOARD'] and self.billnode == 0:
382                 self.writeIndented("<Billboard axisOfRotation=\"0 1 0\">\n",1)
383                 self.billnode = 1
384             elif face.mode & Blender.NMesh.FaceModes['OBCOL'] and self.matonly == 0:
385                 self.matonly = 1
386             elif face.mode & Blender.NMesh.FaceModes['SHAREDCOL'] and self.share == 0:
387                 self.share = 1
388             elif face.mode & Blender.NMesh.FaceModes['TILES'] and self.tilenode == 0:
389                 self.tilenode = 1
390             elif not face.mode & Blender.NMesh.FaceModes['DYNAMIC'] and self.collnode == 0:
391                 self.writeIndented("<Collision enabled=\"false\">\n",1)
392                 self.collnode = 1
393
394         nIFSCnt=self.countIFSSetsNeeded(mesh, imageMap, sided, vColors)
395         
396         if nIFSCnt > 1:
397             self.writeIndented("<Group DEF=\"%s%s\">\n" % ("G_", meshName),1)
398         
399         if sided.has_key('two') and sided['two'] > 0:
400             bTwoSided=1
401         else:
402             bTwoSided=0
403         om = object.getMatrix();
404         location=self.rotVertex(om, (0,0,0));
405         self.writeIndented("<Transform DEF=\"%s\" translation=\"%s %s %s\">\n" % (meshName, round(location[0],3), round(location[1],3), round(location[2],3)),1)
406         self.writeIndented("<Shape>\n",1)
407             
408         maters=mesh.materials
409         hasImageTexture=0
410         issmooth=0
411
412         if len(maters) > 0 or mesh.hasFaceUV():
413           self.writeIndented("<Appearance>\n", 1)
414           # right now this script can only handle a single material per mesh.
415           if len(maters) >= 1:
416             mat=Blender.Material.Get(maters[0].name)
417             matFlags = mat.getMode()
418             if not matFlags & Blender.Material.Modes['TEXFACE']:
419               self.writeMaterial(mat, self.cleanStr(maters[0].name,''))
420               if len(maters) > 1:
421                 print "Warning: mesh named %s has multiple materials" % meshName
422                 print "Warning: only one material per object handled"
423         
424             #-- textures
425             if mesh.hasFaceUV():
426                 for face in mesh.faces:
427                     if (hasImageTexture == 0) and (face.image):
428                         self.writeImageTexture(face.image.name)
429                         hasImageTexture=1  # keep track of face texture
430             if self.tilenode == 1:
431                 self.writeIndented("<TextureTransform   scale=\"%s %s\" />\n" % (face.image.xrep, face.image.yrep))
432                 self.tilenode = 0
433             self.writeIndented("</Appearance>\n", -1)
434
435         #-- IndexedFaceSet or IndexedLineSet
436
437         # check if object is wireframe only
438         if object.drawType == Blender.Object.DrawTypes.WIRE:
439             # user selected WIRE=2 on the Drawtype=Wire on (F9) Edit page
440             ifStyle="IndexedLineSet"
441             self.wire = 1
442         else:
443             # user selected BOUNDS=1, SOLID=3, SHARED=4, or TEXTURE=5
444             ifStyle="IndexedFaceSet"
445         # look up mesh name, use it if available
446         if self.meshNames.has_key(meshME):
447             self.writeIndented("<%s USE=\"ME_%s\">" % (ifStyle, meshME), 1)
448             self.meshNames[meshME]+=1
449         else:
450             if int(mesh.users) > 1:
451                 self.writeIndented("<%s DEF=\"ME_%s\" " % (ifStyle, meshME), 1)
452                 self.meshNames[meshME]=1
453             else:
454                 self.writeIndented("<%s " % ifStyle, 1)
455             if object.drawType != Blender.Object.DrawTypes.WIRE:
456                 if bTwoSided == 1:
457                     self.file.write("solid=\"false\" ")
458                 else:
459                     self.file.write("solid=\"true\" ")
460
461             for face in mesh.faces:
462                 if face.smooth:
463                      issmooth=1
464             if issmooth==1 and self.wire == 0:
465                 creaseAngle=(mesh.getMaxSmoothAngle())*(math.pi/180.0)
466                 self.file.write("creaseAngle=\"%s\" " % (round(creaseAngle,self.cp)))
467
468             #--- output vertexColors
469             if self.share == 1 and self.matonly == 0:
470                 self.writeVertexColors(mesh)
471             if object.drawType != Blender.Object.DrawTypes.WIRE:
472                 #--- output textureCoordinates if UV texture used
473                 if mesh.hasFaceUV():
474                     if self.matonly == 1 and self.share == 1:
475                         self.writeFaceColors(mesh)
476                     elif hasImageTexture == 1:
477                         self.writeTextureCoordinates(mesh)
478             #--- output coordinates
479             self.writeCoordinates(object, mesh, meshName)
480
481             self.writingcoords = 1
482             self.writingtexture = 1
483             self.writingcolor = 1
484             self.writeCoordinates(object, mesh, meshName)
485        
486             if object.drawType != Blender.Object.DrawTypes.WIRE:
487                 #--- output textureCoordinates if UV texture used
488                 if mesh.hasFaceUV():
489                     if hasImageTexture == 1:
490                         self.writeTextureCoordinates(mesh)
491                     elif self.matonly == 1 and self.share == 1:
492                         self.writeFaceColors(mesh)
493             #--- output vertexColors
494             if self.share == 1 and self.matonly == 0:
495                 self.writeVertexColors(mesh)
496         self.matonly = 0
497         self.share = 0
498         self.wire = 0
499         self.writingcoords = 0
500         self.writingtexture = 0
501         self.writingcolor = 0
502         #--- output closing braces
503         self.writeIndented("</%s>\n" % ifStyle, -1)
504         self.writeIndented("</Shape>\n", -1)
505         self.writeIndented("</Transform>\n", -1)
506
507         if self.halonode == 1:
508             self.writeIndented("</Billboard>\n", -1)
509             self.halonode = 0
510
511         if self.billnode == 1:
512             self.writeIndented("</Billboard>\n", -1)
513             self.billnode = 0
514
515         if self.collnode == 1:
516             self.writeIndented("</Collision>\n", -1)
517             self.collnode = 0
518
519         if nIFSCnt > 1:
520             self.writeIndented("</Group>\n", -1)
521
522         self.file.write("\n")
523
524     def writeCoordinates(self, object, mesh, meshName):
525         meshVertexList = mesh.verts
526
527         # create vertex list and pre rotate -90 degrees X for VRML
528         mm=object.getMatrix()
529         location=self.rotVertex(mm, (0,0,0));
530         if self.writingcoords == 0:
531             self.file.write("coordIndex=\"")
532             coordIndexList=[]  
533             for face in mesh.faces:
534                 cordStr=""
535                 for i in range(len(face)):
536                     indx=meshVertexList.index(face[i])
537                     cordStr = cordStr + "%s " % indx
538                 self.file.write(cordStr + "-1, ")
539             self.file.write("\">\n")
540         else:
541             #-- vertices
542             self.writeIndented("<Coordinate DEF=\"%s%s\" \n" % ("coord_",meshName), 1)
543             self.file.write("\t\t\t\tpoint=\"")
544             for vertex in meshVertexList:
545                 v=self.rotVertex(mm, vertex);
546                 self.file.write("%s %s %s, " % (round((v[0]-location[0]),self.vp), round((v[1]-location[1]),self.vp), round((v[2]-location[2]),self.vp)))
547             self.file.write("\" />")
548             self.writeIndented("\n", -1)
549
550     def writeTextureCoordinates(self, mesh):
551         texCoordList=[] 
552         texIndexList=[]
553         j=0
554
555         for face in mesh.faces:
556             for i in range(len(face)):
557                 texIndexList.append(j)
558                 texCoordList.append(face.uv[i])
559                 j=j+1
560             texIndexList.append(-1)
561         if self.writingtexture == 0:
562             self.file.write("\n\t\t\ttexCoordIndex=\"")
563             texIndxStr=""
564             for i in range(len(texIndexList)):
565                 texIndxStr = texIndxStr + "%d, " % texIndexList[i]
566                 if texIndexList[i]==-1:
567                     self.file.write(texIndxStr)
568                     texIndxStr=""
569             self.file.write("\"\n\t\t\t")
570         else:
571             self.writeIndented("<TextureCoordinate point=\"", 1)
572             for i in range(len(texCoordList)):
573                 self.file.write("%s %s, " % (round(texCoordList[i][0],self.tp), round(texCoordList[i][1],self.tp)))
574             self.file.write("\" />")
575             self.writeIndented("\n", -1)
576
577     def writeFaceColors(self, mesh):
578         if self.writingcolor == 0:
579             self.file.write("colorPerVertex=\"false\" ")
580         else:
581             self.writeIndented("<Color color=\"", 1)
582             for face in mesh.faces:
583                 if face.col:
584                     c=face.col[0]
585                     if self.verbose > 2:
586                         print "Debug: face.col r=%d g=%d b=%d" % (c.r, c.g, c.b)
587                     aColor = self.rgbToFS(c)
588                     self.file.write("%s, " % aColor)
589             self.file.write("\" />")
590             self.writeIndented("\n",-1)
591
592     def writeVertexColors(self, mesh):
593         if self.writingcolor == 0:
594             self.file.write("colorPerVertex=\"false\" ")
595         else:
596             self.writeIndented("<Color color=\"", 1)
597             for i in range(len(mesh.verts)):
598                 c=self.getVertexColorByIndx(mesh,i)
599                 if self.verbose > 2:
600                     print "Debug: vertex[%d].col r=%d g=%d b=%d" % (i, c.r, c.g, c.b)
601
602                 aColor = self.rgbToFS(c)
603                 self.file.write("%s, " % aColor)
604             self.file.write("\" />")
605             self.writeIndented("\n",-1)
606
607     def writeMaterial(self, mat, matName):
608         # look up material name, use it if available
609         if self.matNames.has_key(matName):
610             self.writeIndented("<Material USE=\"MA_%s\" />\n" % matName)
611             self.matNames[matName]+=1
612             return;
613
614         self.matNames[matName]=1
615
616         ambient = mat.amb/3
617         diffuseR, diffuseG, diffuseB = mat.rgbCol[0], mat.rgbCol[1],mat.rgbCol[2]
618         if len(world) > 0:
619             ambi = world[0].getAmb()
620             ambi0, ambi1, ambi2 = (ambi[0]*mat.amb)*2, (ambi[1]*mat.amb)*2, (ambi[2]*mat.amb)*2
621         else:
622             ambi0, ambi1, ambi2 = 0, 0, 0
623         emisR, emisG, emisB = (diffuseR*mat.emit+ambi0)/2, (diffuseG*mat.emit+ambi1)/2, (diffuseB*mat.emit+ambi2)/2
624
625         shininess = mat.hard/512.0
626         specR = (mat.specCol[0]+0.001)/(1.25/(mat.getSpec()+0.001))
627         specG = (mat.specCol[1]+0.001)/(1.25/(mat.getSpec()+0.001))
628         specB = (mat.specCol[2]+0.001)/(1.25/(mat.getSpec()+0.001))
629         transp = 1-mat.alpha
630         matFlags = mat.getMode()
631         if matFlags & Blender.Material.Modes['SHADELESS']:
632           ambient = 1
633           shine = 1
634           specR = emitR = diffuseR
635           specG = emitG = diffuseG
636           specB = emitB = diffuseB
637         self.writeIndented("<Material DEF=\"MA_%s\" " % matName, 1)
638         self.file.write("diffuseColor=\"%s %s %s\" " % (round(diffuseR,self.cp), round(diffuseG,self.cp), round(diffuseB,self.cp)))
639         self.file.write("specularColor=\"%s %s %s\" " % (round(specR,self.cp), round(specG,self.cp), round(specB,self.cp)))
640         self.file.write("emissiveColor=\"%s %s %s\" \n" % (round(emisR,self.cp), round(emisG,self.cp), round(emisB,self.cp)))
641         self.writeIndented("ambientIntensity=\"%s\" " % (round(ambient,self.cp)))
642         self.file.write("shininess=\"%s\" " % (round(shininess,self.cp)))
643         self.file.write("transparency=\"%s\" />" % (round(transp,self.cp)))
644         self.writeIndented("\n",-1)
645
646     def writeImageTexture(self, name):
647         if self.texNames.has_key(name):
648             self.writeIndented("<ImageTexture USE=\"%s\" />\n" % self.cleanStr(name))
649             self.texNames[name] += 1
650             return
651         else:
652             self.writeIndented("<ImageTexture DEF=\"%s\" " % self.cleanStr(name), 1)
653             self.file.write("url=\"%s\" />" % name)
654             self.writeIndented("\n",-1)
655             self.texNames[name] = 1
656
657     def writeBackground(self):
658         if len(world) > 0:
659             worldname = world[0].getName()
660         else:
661             return
662         blending = world[0].getSkytype()        
663         grd = world[0].getHor()
664         grd0, grd1, grd2 = grd[0], grd[1], grd[2]
665         sky = world[0].getZen()
666         sky0, sky1, sky2 = sky[0], sky[1], sky[2]
667         mix0, mix1, mix2 = grd[0]+sky[0], grd[1]+sky[1], grd[2]+sky[2]
668         mix0, mix1, mix2 = mix0/2, mix1/2, mix2/2
669         self.file.write("<Background ")
670         if worldname not in self.namesStandard:
671             self.file.write("DEF=\"%s\" " % self.secureName(worldname))
672         # No Skytype - just Hor color
673         if blending == 0:
674             self.file.write("groundColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
675             self.file.write("skyColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
676         # Blend Gradient
677         elif blending == 1:
678             self.file.write("groundColor=\"%s %s %s, " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
679             self.file.write("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
680             self.file.write("skyColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
681             self.file.write("%s %s %s\" skyAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
682         # Blend+Real Gradient Inverse
683         elif blending == 3:
684             self.file.write("groundColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
685             self.file.write("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
686             self.file.write("skyColor=\"%s %s %s, " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
687             self.file.write("%s %s %s\" skyAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
688         # Paper - just Zen Color
689         elif blending == 4:
690             self.file.write("groundColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
691             self.file.write("skyColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
692         # Blend+Real+Paper - komplex gradient
693         elif blending == 7:
694             self.writeIndented("groundColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
695             self.writeIndented("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
696             self.writeIndented("skyColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
697             self.writeIndented("%s %s %s\" skyAngle=\"1.57, 1.57\" " %(round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
698         # Any Other two colors
699         else:
700             self.file.write("groundColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
701             self.file.write("skyColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
702         alltexture = len(worldmat)
703         for i in range(alltexture):
704             namemat = worldmat[i].getName()
705             pic = worldmat[i].getImage()        
706             if (namemat == "back") and (pic != None):
707                 self.file.write("\n\tbackUrl=\"%s\" " % str(pic.getName()))
708             elif (namemat == "bottom") and (pic != None):
709                 self.writeIndented("bottomUrl=\"%s\" " % str(pic.getName()))
710             elif (namemat == "front") and (pic != None):
711                 self.writeIndented("frontUrl=\"%s\" " % str(pic.getName()))
712             elif (namemat == "left") and (pic != None):
713                 self.writeIndented("leftUrl=\"%s\" " % str(pic.getName()))
714             elif (namemat == "right") and (pic != None):
715                 self.writeIndented("rightUrl=\"%s\" " % str(pic.getName()))
716             elif (namemat == "top") and (pic != None):
717                 self.writeIndented("topUrl=\"%s\" " % str(pic.getName()))
718         self.writeIndented("/>\n\n")
719
720 ##########################################################
721 # export routine
722 ##########################################################
723
724     def export(self, scene, world, worldmat):
725         print "Info: starting X3D export to " + self.filename + "..."
726         self.writeHeader()
727         self.writeScript()
728         self.writeNavigationInfo(scene)
729         self.writeBackground()
730         self.writeFog()
731         self.proto = 0
732         allObj = []
733         if ARG == 'selected':
734             allObj = Blender.Object.GetSelected()
735         else:
736             allObj = scene.getChildren()
737             self.writeInline()
738         for thisObj in allObj:
739             try:
740                 objType=thisObj.getType()
741                 objName=thisObj.getName()
742                 self.matonly = 0
743                 if objType == "Camera":
744                     self.writeViewpoint(thisObj)
745                 elif objType == "Mesh":
746                     self.writeIndexedFaceSet(thisObj, normals = 0)
747                 elif objType == "Lamp":
748                     lmpName=Lamp.Get(thisObj.data.getName())
749                     lmpType=lmpName.getType()
750                     if lmpType == Lamp.Types.Lamp:
751                         self.writePointLight(thisObj, lmpName)
752                     elif lmpType == Lamp.Types.Spot:
753                         self.writeSpotLight(thisObj, lmpName)
754                     elif lmpType == Lamp.Types.Sun:
755                         self.writeDirectionalLight(thisObj, lmpName)
756                     else:
757                         self.writeDirectionalLight(thisObj, lmpName)
758                 elif objType == "Empty" and objName != "Empty":
759                     self.writeNode(thisObj)
760                 else:
761                     #print "Info: Ignoring [%s], object type [%s] not handle yet" % (object.name,object.getType())
762                     print ""
763             except AttributeError:
764                 print "Error: Unable to get type info for %s" % thisObj.getName()
765         if ARG != 'selected':
766             self.writeScript()
767         self.file.write("\n</Scene>\n</X3D>")
768         self.cleanup()
769         
770 ##########################################################
771 # Utility methods
772 ##########################################################
773
774     def cleanup(self):
775         self.file.close()
776         self.texNames={}
777         self.matNames={}
778         self.indentLevel=0
779         print "Info: finished X3D export to %s\n" % self.filename
780
781     def cleanStr(self, name, prefix='rsvd_'):
782         """cleanStr(name,prefix) - try to create a valid VRML DEF name from object name"""
783
784         newName=name[:]
785         if len(newName) == 0:
786             self.nNodeID+=1
787             return "%s%d" % (prefix, self.nNodeID)
788         
789         if newName in self.namesReserved:
790             newName='%s%s' % (prefix,newName)
791         
792         if newName[0].isdigit():
793             newName='%s%s' % ('_',newName)
794
795         for bad in [' ','"','#',"'",',','.','[','\\',']','{','}']:
796             newName=newName.replace(bad,'_')
797         return newName
798
799     def countIFSSetsNeeded(self, mesh, imageMap, sided, vColors):
800         """
801         countIFFSetsNeeded() - should look at a blender mesh to determine
802         how many VRML IndexFaceSets or IndexLineSets are needed.  A
803         new mesh created under the following conditions:
804         
805          o - split by UV Textures / one per mesh
806          o - split by face, one sided and two sided
807          o - split by smooth and flat faces
808          o - split when faces only have 2 vertices * needs to be an IndexLineSet
809         """
810         
811         imageNameMap={}
812         faceMap={}
813         nFaceIndx=0
814         
815         for face in mesh.faces:
816             sidename='';
817             if (face.mode & NMesh.FaceModes.TWOSIDE) == NMesh.FaceModes.TWOSIDE:
818                 sidename='two'
819             else:
820                 sidename='one'
821
822             if not vColors.has_key('multi'):
823                 for face in mesh.faces:
824                     if face.col:
825                         c=face.col[0]
826                         if c.r != 255 and c.g != 255 and c.b !=255:
827                             vColors['multi']=1
828
829             if sided.has_key(sidename):
830                 sided[sidename]+=1
831             else:
832                 sided[sidename]=1
833
834             if face.image:
835                 faceName="%s_%s" % (face.image.name, sidename);
836
837                 if imageMap.has_key(faceName):
838                     imageMap[faceName].append(face)
839                 else:
840                     imageMap[faceName]=[face.image.name,sidename,face]
841
842         if self.verbose > 2:
843             for faceName in imageMap.keys():
844                 ifs=imageMap[faceName]
845                 print "Debug: faceName=%s image=%s, solid=%s facecnt=%d" % \
846                       (faceName, ifs[0], ifs[1], len(ifs)-2)
847
848         return len(imageMap.keys())
849     
850     def faceToString(self,face):
851
852         print "Debug: face.flag=0x%x (bitflags)" % face.flag
853         if face.flag & NMesh.FaceFlags.SELECT == NMesh.FaceFlags.SELECT:
854             print "Debug: face.flag.SELECT=true"
855
856         print "Debug: face.mode=0x%x (bitflags)" % face.mode
857         if (face.mode & NMesh.FaceModes.TWOSIDE) == NMesh.FaceModes.TWOSIDE:
858             print "Debug: face.mode twosided"
859
860         print "Debug: face.transp=0x%x (enum)" % face.transp
861         if face.transp == NMesh.FaceTranspModes.SOLID:
862             print "Debug: face.transp.SOLID"
863
864         if face.image:
865             print "Debug: face.image=%s" % face.image.name
866         print "Debug: face.materialIndex=%d" % face.materialIndex 
867
868     def getVertexColorByIndx(self, mesh, indx):
869         for face in mesh.faces:
870             j=0
871             for vertex in face.v:
872                 if vertex.index == indx:
873                     c=face.col[j]
874                 j=j+1
875         return c
876
877     def meshToString(self,mesh):
878         print "Debug: mesh.hasVertexUV=%d" % mesh.hasVertexUV()
879         print "Debug: mesh.hasFaceUV=%d" % mesh.hasFaceUV()
880         print "Debug: mesh.hasVertexColours=%d" % mesh.hasVertexColours()
881         print "Debug: mesh.verts=%d" % len(mesh.verts)
882         print "Debug: mesh.faces=%d" % len(mesh.faces)
883         print "Debug: mesh.materials=%d" % len(mesh.materials)
884
885     def rgbToFS(self, c):
886         s="%s %s %s" % (
887             round(c.r/255.0,self.cp),
888             round(c.g/255.0,self.cp),
889             round(c.b/255.0,self.cp))
890         return s
891
892     def computeDirection(self, object):
893         x,y,z=(0,-1.0,0) # point down
894         ax,ay,az = (object.RotX,object.RotZ,object.RotY)
895
896         # rot X
897         x1=x
898         y1=y*math.cos(ax)-z*math.sin(ax)
899         z1=y*math.sin(ax)+z*math.cos(ax)
900
901         # rot Y
902         x2=x1*math.cos(ay)+z1*math.sin(ay)
903         y2=y1
904         z2=z1*math.cos(ay)-x1*math.sin(ay)
905
906         # rot Z
907         x3=x2*math.cos(az)-y2*math.sin(az)
908         y3=x2*math.sin(az)+y2*math.cos(az)
909         z3=z2
910
911         return [x3,y3,z3]
912         
913
914     # swap Y and Z to handle axis difference between Blender and VRML
915     #------------------------------------------------------------------------
916     def rotatePointForVRML(self, v):
917         x = v[0]
918         y = v[2]
919         z = -v[1]
920         
921         vrmlPoint=[x, y, z]
922         return vrmlPoint
923     
924     def rotVertex(self, mm, v):
925         lx,ly,lz=v[0],v[1],v[2]
926         gx=(mm[0][0]*lx + mm[1][0]*ly + mm[2][0]*lz) + mm[3][0]
927         gy=((mm[0][2]*lx + mm[1][2]*ly+ mm[2][2]*lz) + mm[3][2])
928         gz=-((mm[0][1]*lx + mm[1][1]*ly + mm[2][1]*lz) + mm[3][1])
929         rotatedv=[gx,gy,gz]
930         return rotatedv
931
932     # For writing well formed VRML code
933     #------------------------------------------------------------------------
934     def writeIndented(self, s, inc=0):
935         if inc < 1:
936             self.indentLevel = self.indentLevel + inc
937
938         spaces=""
939         for x in xrange(self.indentLevel):
940             spaces = spaces + "\t"
941         self.file.write(spaces + s)
942
943         if inc > 0:
944             self.indentLevel = self.indentLevel + inc
945
946     # Converts a Euler to three new Quaternions
947     # Angles of Euler are passed in as radians
948     #------------------------------------------------------------------------
949     def eulerToQuaternions(self, x, y, z):
950         Qx = [math.cos(x/2), math.sin(x/2), 0, 0]
951         Qy = [math.cos(y/2), 0, math.sin(y/2), 0]
952         Qz = [math.cos(z/2), 0, 0, math.sin(z/2)]
953         
954         quaternionVec=[Qx,Qy,Qz]
955         return quaternionVec
956     
957     # Multiply two Quaternions together to get a new Quaternion
958     #------------------------------------------------------------------------
959     def multiplyQuaternions(self, Q1, Q2):
960         result = [((Q1[0] * Q2[0]) - (Q1[1] * Q2[1]) - (Q1[2] * Q2[2]) - (Q1[3] * Q2[3])),
961                   ((Q1[0] * Q2[1]) + (Q1[1] * Q2[0]) + (Q1[2] * Q2[3]) - (Q1[3] * Q2[2])),
962                   ((Q1[0] * Q2[2]) + (Q1[2] * Q2[0]) + (Q1[3] * Q2[1]) - (Q1[1] * Q2[3])),
963                   ((Q1[0] * Q2[3]) + (Q1[3] * Q2[0]) + (Q1[1] * Q2[2]) - (Q1[2] * Q2[1]))]
964         
965         return result
966     
967     # Convert a Quaternion to an Angle Axis (ax, ay, az, angle)
968     # angle is in radians
969     #------------------------------------------------------------------------
970     def quaternionToAngleAxis(self, Qf):
971         scale = math.pow(Qf[1],2) + math.pow(Qf[2],2) + math.pow(Qf[3],2)
972         ax = Qf[1]
973         ay = Qf[2]
974         az = Qf[3]
975
976         if scale > .0001:
977             ax/=scale
978             ay/=scale
979             az/=scale
980         
981         angle = 2 * math.acos(Qf[0])
982         
983         result = [ax, ay, az, angle]
984         return result
985
986 ##########################################################
987 # Callbacks, needed before Main
988 ##########################################################
989
990 def select_file(filename):
991   if pytinst == 1:
992     if exists(filename) and _safeOverwrite:
993       result = Draw.PupMenu("File Already Exists, Overwrite?%t|Yes%x1|No%x0")
994       if(result != 1):
995         return
996
997   if not filename.endswith(extension):
998     filename += extension
999                 
1000   wrlexport=VRML2Export(filename)
1001   wrlexport.export(scene, world, worldmat)
1002
1003 def createWRLPath():
1004   filename = Blender.Get('filename')
1005   print filename
1006   
1007   if filename.find('.') != -1:
1008     filename = filename.split('.')[0]
1009     filename += extension
1010     print filename
1011
1012   return filename
1013
1014 #########################################################
1015 # main routine
1016 #########################################################
1017
1018 try:
1019     ARG = __script__['arg'] # user selected argument
1020 except:
1021     print "older version"
1022
1023 if Blender.Get('version') < 235:
1024   print "Warning: X3D export failed, wrong blender version!"
1025   print " You aren't running blender version 2.35 or greater"
1026   print " download a newer version from http://blender3d.org/"
1027 else:
1028   if ARG == 'comp':
1029     from gzip import *
1030     extension=".x3dz"
1031   else:
1032     extension=".x3d"
1033   Blender.Window.FileSelector(select_file,"Export X3D",createWRLPath())
1034