+ def open(self, startFrame=1, endFrame=1):
+ if startFrame != endFrame:
+ self.startFrame = startFrame
+ self.endFrame = endFrame
+ self.animation = True
+
+ self.file = open(self.outputFileName, "w")
+ print "Outputting to: ", self.outputFileName
+
+ return
+
+ def close(self):
+ self.file.close()
+ return
+
+ def printCanvas(self, scene, doPrintPolygons=True, doPrintEdges=False,
+ showHiddenEdges=False):
+ """This is the interface for the needed printing routine.
+ """
+ return
+
+
+## SVG Writer
+
+class SVGVectorWriter(VectorWriter):
+ """A concrete class for writing SVG output.
+ """
+
+ def __init__(self, fileName):
+ """Simply call the parent Contructor.
+ """
+ VectorWriter.__init__(self, fileName)
+
+
+ ##
+ # Public Methods
+ #
+
+ def open(self, startFrame=1, endFrame=1):
+ """Do some initialization operations.
+ """
+ VectorWriter.open(self, startFrame, endFrame)
+ self._printHeader()
+
+ def close(self):
+ """Do some finalization operation.
+ """
+ self._printFooter()
+
+ # remember to call the close method of the parent
+ VectorWriter.close(self)
+
+
+ def printCanvas(self, scene, doPrintPolygons=True, doPrintEdges=False,
+ showHiddenEdges=False):
+ """Convert the scene representation to SVG.
+ """
+
+ Objects = scene.getChildren()
+
+ context = scene.getRenderingContext()
+ framenumber = context.currentFrame()
+
+ if self.animation:
+ framestyle = "display:none"
+ else:
+ framestyle = "display:block"
+
+ # Assign an id to this group so we can set properties on it using DOM
+ self.file.write("<g id=\"frame%d\" style=\"%s\">\n" %
+ (framenumber, framestyle) )
+
+
+ for obj in Objects:
+
+ if(obj.getType() != 'Mesh'):
+ continue
+
+ self.file.write("<g id=\"%s\">\n" % obj.getName())
+
+ mesh = obj.getData(mesh=1)
+
+ if doPrintPolygons:
+ self._printPolygons(mesh)
+
+ if doPrintEdges:
+ self._printEdges(mesh, showHiddenEdges)
+
+ self.file.write("</g>\n")
+
+ self.file.write("</g>\n")
+
+
+ ##
+ # Private Methods
+ #
+
+ def _calcCanvasCoord(self, v):
+ """Convert vertex in scene coordinates to canvas coordinates.
+ """
+
+ pt = Vector([0, 0, 0])
+
+ mW = float(self.canvasSize[0])/2.0
+ mH = float(self.canvasSize[1])/2.0
+
+ # rescale to canvas size
+ pt[0] = v.co[0]*mW + mW
+ pt[1] = v.co[1]*mH + mH
+ pt[2] = v.co[2]
+
+ # For now we want (0,0) in the top-left corner of the canvas.
+ # Mirror and translate along y
+ pt[1] *= -1
+ pt[1] += self.canvasSize[1]
+
+ return pt
+
+ def _printHeader(self):
+ """Print SVG header."""
+
+ self.file.write("<?xml version=\"1.0\"?>\n")
+ self.file.write("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n")
+ self.file.write("\t\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n")
+ self.file.write("<svg version=\"1.1\"\n")
+ self.file.write("\txmlns=\"http://www.w3.org/2000/svg\"\n")
+ self.file.write("\twidth=\"%d\" height=\"%d\" streamable=\"true\">\n\n" %
+ self.canvasSize)
+
+ if self.animation:
+
+ self.file.write("""\n<script><![CDATA[
+ globalStartFrame=%d;
+ globalEndFrame=%d;
+
+ /* FIXME: Use 1000 as interval as lower values gives problems */
+ timerID = setInterval("NextFrame()", 1000);
+ globalFrameCounter=%d;
+
+ function NextFrame()
+ {
+ currentElement = document.getElementById('frame'+globalFrameCounter)
+ previousElement = document.getElementById('frame'+(globalFrameCounter-1))
+
+ if (!currentElement)
+ {
+ return;
+ }
+
+ if (globalFrameCounter > globalEndFrame)
+ {
+ clearInterval(timerID)
+ }
+ else
+ {
+ if(previousElement)
+ {
+ previousElement.style.display="none";
+ }
+ currentElement.style.display="block";
+ globalFrameCounter++;
+ }
+ }
+ \n]]></script>\n
+ \n""" % (self.startFrame, self.endFrame, self.startFrame) )
+
+ def _printFooter(self):
+ """Print the SVG footer."""
+
+ self.file.write("\n</svg>\n")
+
+ def _printPolygons(self, mesh):
+ """Print the selected (visible) polygons.
+ """
+
+ if len(mesh.faces) == 0:
+ return
+
+ self.file.write("<g>\n")
+
+ for face in mesh.faces:
+ if not face.sel:
+ continue
+
+ self.file.write("<path d=\"")
+
+ p = self._calcCanvasCoord(face.verts[0])
+ self.file.write("M %g,%g L " % (p[0], p[1]))
+
+ for v in face.verts[1:]:
+ p = self._calcCanvasCoord(v)
+ self.file.write("%g,%g " % (p[0], p[1]))
+
+ # get rid of the last blank space, just cosmetics here.
+ self.file.seek(-1, 1)
+ self.file.write("\"\n")
+
+ # take as face color the first vertex color
+ # TODO: the average of vetrex colors?
+ if face.col:
+ fcol = face.col[0]
+ color = [fcol.r, fcol.g, fcol.b, fcol.a]
+ else:
+ color = [255, 255, 255, 255]
+
+ # Convert the color to the #RRGGBB form
+ str_col = "#%02X%02X%02X" % (color[0], color[1], color[2])
+
+ # use the stroke property to alleviate the "adjacent edges" problem,
+ # we simulate polygon expansion using borders,
+ # see http://www.antigrain.com/svg/index.html for more info
+ stroke_width = 0.5
+
+ # Handle transparent polygons
+ opacity_string = ""
+ if color[3] != 255:
+ opacity = float(color[3])/255.0
+ opacity_string = " fill-opacity: %g; stroke-opacity: %g; opacity: 1;" % (opacity, opacity)
+
+ self.file.write("\tstyle=\"fill:" + str_col + ";")
+ self.file.write(opacity_string)
+ if config.polygons['EXPANSION_TRICK']:
+ self.file.write(" stroke-width:" + str(stroke_width) + ";\n")
+ self.file.write(" stroke-linecap:round;stroke-linejoin:round")
+ self.file.write("\"/>\n")
+
+ self.file.write("</g>\n")
+
+ def _printEdges(self, mesh, showHiddenEdges=False):
+ """Print the wireframe using mesh edges.
+ """
+
+ stroke_width = config.edges['WIDTH']
+ stroke_col = config.edges['COLOR']
+
+ self.file.write("<g>\n")
+
+ for e in mesh.edges:
+
+ hidden_stroke_style = ""
+
+ if e.sel == 0:
+ if showHiddenEdges == False:
+ continue
+ else:
+ hidden_stroke_style = ";\n stroke-dasharray:3, 3"
+
+ p1 = self._calcCanvasCoord(e.v1)
+ p2 = self._calcCanvasCoord(e.v2)
+
+ self.file.write("<line x1=\"%g\" y1=\"%g\" x2=\"%g\" y2=\"%g\"\n"
+ % ( p1[0], p1[1], p2[0], p2[1] ) )
+ self.file.write(" style=\"stroke:rgb("+str(stroke_col[0])+","+str(stroke_col[1])+","+str(stroke_col[2])+");")
+ self.file.write(" stroke-width:"+str(stroke_width)+";\n")
+ self.file.write(" stroke-linecap:round;stroke-linejoin:round")
+ self.file.write(hidden_stroke_style)
+ self.file.write("\"/>\n")
+
+ self.file.write("</g>\n")
+
+
+
+# ---------------------------------------------------------------------
+#
+## Rendering Classes
+#
+# ---------------------------------------------------------------------
+
+# A dictionary to collect different shading style methods
+shadingStyles = dict()
+shadingStyles['FLAT'] = None
+shadingStyles['TOON'] = None
+
+# A dictionary to collect different edge style methods
+edgeStyles = dict()
+edgeStyles['MESH'] = MeshUtils.isMeshEdge
+edgeStyles['SILHOUETTE'] = MeshUtils.isSilhouetteEdge
+
+# A dictionary to collect the supported output formats
+outputWriters = dict()
+outputWriters['SVG'] = SVGVectorWriter
+
+
+class Renderer:
+ """Render a scene viewed from a given camera.
+
+ This class is responsible of the rendering process, transformation and
+ projection of the objects in the scene are invoked by the renderer.
+
+ The rendering is done using the active camera for the current scene.
+ """
+
+ def __init__(self):
+ """Make the rendering process only for the current scene by default.
+
+ We will work on a copy of the scene, be sure that the current scene do
+ not get modified in any way.
+ """
+
+ # Render the current Scene, this should be a READ-ONLY property
+ self._SCENE = Scene.GetCurrent()
+
+ # Use the aspect ratio of the scene rendering context
+ context = self._SCENE.getRenderingContext()
+
+ aspect_ratio = float(context.imageSizeX())/float(context.imageSizeY())
+ self.canvasRatio = (float(context.aspectRatioX())*aspect_ratio,
+ float(context.aspectRatioY())
+ )
+
+ # Render from the currently active camera
+ self.cameraObj = self._SCENE.getCurrentCamera()
+
+ # Get a projector for this camera.
+ # NOTE: the projector wants object in world coordinates,
+ # so we should remember to apply modelview transformations
+ # _before_ we do projection transformations.
+ self.proj = Projector(self.cameraObj, self.canvasRatio)
+
+ # Get the list of lighting sources
+ obj_lst = self._SCENE.getChildren()
+ self.lights = [ o for o in obj_lst if o.getType() == 'Lamp']
+
+ # When there are no lights we use a default lighting source
+ # that have the same position of the camera
+ if len(self.lights) == 0:
+ l = Lamp.New('Lamp')
+ lobj = Object.New('Lamp')
+ lobj.loc = self.cameraObj.loc
+ lobj.link(l)
+ self.lights.append(lobj)
+
+
+ ##
+ # Public Methods
+ #
+
+ def doRendering(self, outputWriter, animation=False):
+ """Render picture or animation and write it out.
+
+ The parameters are:
+ - a Vector writer object that will be used to output the result.
+ - a flag to tell if we want to render an animation or only the
+ current frame.
+ """
+
+ context = self._SCENE.getRenderingContext()
+ origCurrentFrame = context.currentFrame()
+
+ # Handle the animation case
+ if not animation:
+ startFrame = origCurrentFrame
+ endFrame = startFrame
+ outputWriter.open()
+ else:
+ startFrame = context.startFrame()
+ endFrame = context.endFrame()
+ outputWriter.open(startFrame, endFrame)
+
+ # Do the rendering process frame by frame
+ print "Start Rendering!"
+ for f in range(startFrame, endFrame+1):
+ context.currentFrame(f)
+
+ # Use some temporary workspace, a full copy of the scene
+ inputScene = self._SCENE.copy(2)
+ # And Set our camera accordingly
+ self.cameraObj = inputScene.getCurrentCamera()
+
+ try:
+ renderedScene = self.doRenderScene(inputScene)
+ except :
+ print "There was an error! Aborting."
+ import traceback
+ print traceback.print_exc()
+
+ self._SCENE.makeCurrent()
+ Scene.unlink(inputScene)
+ del inputScene
+ return
+
+ outputWriter.printCanvas(renderedScene,
+ doPrintPolygons = config.polygons['SHOW'],
+ doPrintEdges = config.edges['SHOW'],
+ showHiddenEdges = config.edges['SHOW_HIDDEN'])
+
+ # clear the rendered scene
+ self._SCENE.makeCurrent()
+ #Scene.unlink(renderedScene)
+ #del renderedScene
+
+ outputWriter.close()
+ print "Done!"
+ context.currentFrame(origCurrentFrame)
+
+
+ def doRenderScene(self, workScene):
+ """Control the rendering process.
+
+ Here we control the entire rendering process invoking the operation
+ needed to transform and project the 3D scene in two dimensions.
+ """
+
+ # global processing of the scene
+
+ self._doSceneClipping(workScene)
+
+ self._doConvertGeometricObjToMesh(workScene)
+
+ if config.output['JOIN_OBJECTS']:
+ self._joinMeshObjectsInScene(workScene)
+
+ self._doSceneDepthSorting(workScene)
+
+ # Per object activities
+
+ Objects = workScene.getChildren()
+ for obj in Objects:
+
+ if obj.getType() != 'Mesh':
+ print "Only Mesh supported! - Skipping type:", obj.getType()
+ continue
+
+ print "Rendering: ", obj.getName()
+
+ mesh = obj.getData(mesh=1)