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