Advertisement
danfalck

importWebGL.py

May 12th, 2013
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.33 KB | None | 0 0
  1. #***************************************************************************
  2. #*                                                                         *
  3. #*   Copyright (c) 2013                                                    *  
  4. #*   Yorik van Havre <yorik@uncreated.net>                                 *  
  5. #*                                                                         *
  6. #*   This program is free software; you can redistribute it and/or modify  *
  7. #*   it under the terms of the GNU Lesser General Public License (LGPL)    *
  8. #*   as published by the Free Software Foundation; either version 2 of     *
  9. #*   the License, or (at your option) any later version.                   *
  10. #*   for detail see the LICENCE text file.                                 *
  11. #*                                                                         *
  12. #*   This program is distributed in the hope that it will be useful,       *
  13. #*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
  14. #*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
  15. #*   GNU Library General Public License for more details.                  *
  16. #*                                                                         *
  17. #*   You should have received a copy of the GNU Library General Public     *
  18. #*   License along with this program; if not, write to the Free Software   *
  19. #*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
  20. #*   USA                                                                   *
  21. #*                                                                         *
  22. #***************************************************************************
  23.  
  24. "FreeCAD webgl exporter"
  25.  
  26. import FreeCAD,Draft,Part,DraftGeomUtils
  27. if FreeCAD.GuiUp:
  28.     from DraftTools import translate
  29.  
  30. if FreeCAD.GuiUp:
  31.     import FreeCADGui
  32. else:
  33.     FreeCADGui = None
  34.  
  35. tab = "                "
  36. addWireframe = False
  37.  
  38. if open.__module__ == '__builtin__':
  39.     pythonopen = open
  40.    
  41. def export(exportList,filename):
  42.     "exports the given objects to a .html file"
  43.  
  44.     html = getHTML(exportList)
  45.     outfile = pythonopen(filename,"wb")
  46.     outfile.write(html)
  47.     outfile.close()
  48.     FreeCAD.Console.PrintMessage(str(translate("Arch","successfully written "))+filename)
  49.    
  50. def getHTML(objectsList):
  51.     "returns the complete HTML code of a viewer for the given objects"
  52.    
  53.     # get objects data
  54.     objectsData = ''
  55.     for obj in objectsList:
  56.         objectsData += getObjectData(obj)
  57.     template = getTemplate()
  58.     template = template.replace("$CameraData",getCameraData())
  59.     template = template.replace("$ObjectsData",objectsData)
  60.     return template
  61.    
  62. def getCameraData():
  63.     "returns the position and direction of the camera as three.js snippet"
  64.    
  65.     result = ""
  66.     if FreeCADGui:
  67.         # getting camera position
  68.         pos = FreeCADGui.ActiveDocument.ActiveView.viewPosition().Base
  69.         result += "camera.position.set( "
  70.         result += str(pos.x) + ", "
  71.         result += str(pos.y) + ", "
  72.         result += str(pos.z) + " );\n"
  73.     else:
  74.         result += "camera.position.set(0,0,1000);\n"
  75.     result += tab+"camera.lookAt( scene.position );\n"+tab
  76.     # print result
  77.     return result
  78.    
  79. def getObjectData(obj,wireframeMode="faceloop"):
  80.     """returns the geometry data of an object as three.js snippet. wireframeMode
  81.    can be multimaterial, faceloop or None"""
  82.    
  83.     result = ""
  84.     wires = []
  85.  
  86.     if obj.isDerivedFrom("Part::Feature"):
  87.         fcmesh = obj.Shape.tessellate(0.1)
  88.         result = "var geom = new THREE.Geometry();\n"
  89.         # adding vertices data
  90.         for i in range(len(fcmesh[0])):
  91.             v = fcmesh[0][i]
  92.             result += tab+"var v"+str(i)+" = new THREE.Vector3("+str(v.x)+","+str(v.y)+","+str(v.z)+");\n"
  93.         result += tab+"console.log(geom.vertices)\n"
  94.         for i in range(len(fcmesh[0])):
  95.             result += tab+"geom.vertices.push(v"+str(i)+");\n"
  96.         # adding facets data
  97.         for f in fcmesh[1]:
  98.             result += tab+"geom.faces.push( new THREE.Face3"+str(f)+" );\n"
  99.         for f in obj.Shape.Faces:
  100.             for w in f.Wires:
  101.                 wo = Part.Wire(DraftGeomUtils.sortEdges(w.Edges))
  102.                 p = []
  103.                 for v in wo.Vertexes:
  104.                     p.append(v.Point)
  105.                 p.append(wo.Vertexes[0].Point)
  106.                 wires.append(p)
  107.  
  108.     elif obj.isDerivedFrom("Part::TopoShape") :
  109.         fcmesh = obj.tessellate(0.1)
  110.         result = "var geom = new THREE.Geometry();\n"
  111.         # adding vertices data
  112.         for i in range(len(fcmesh[0])):
  113.             v = fcmesh[0][i]
  114.             result += tab+"var v"+str(i)+" = new THREE.Vector3("+str(v.x)+","+str(v.y)+","+str(v.z)+");\n"
  115.         result += tab+"console.log(geom.vertices)\n"
  116.         for i in range(len(fcmesh[0])):
  117.             result += tab+"geom.vertices.push(v"+str(i)+");\n"
  118.         # adding facets data
  119.         for f in fcmesh[1]:
  120.             result += tab+"geom.faces.push( new THREE.Face3"+str(f)+" );\n"
  121.         for f in obj.Faces:
  122.             for w in f.Wires:
  123.                 wo = Part.Wire(DraftGeomUtils.sortEdges(w.Edges))
  124.                 p = []
  125.                 for v in wo.Vertexes:
  126.                     p.append(v.Point)
  127.                 p.append(wo.Vertexes[0].Point)
  128.                 wires.append(p)
  129.  
  130.  
  131.     elif obj.isDerivedFrom("Mesh::Feature"):
  132.         mesh = obj.Mesh
  133.         result = "var geom = new THREE.Geometry();\n"
  134.         # adding vertices data
  135.         for p in mesh.Points:
  136.             v = p.Vector
  137.             i = p.Index
  138.             result += tab+"var v"+str(i)+" = new THREE.Vector3("+str(v.x)+","+str(v.y)+","+str(v.z)+");\n"
  139.         result += tab+"console.log(geom.vertices)\n"
  140.         for p in mesh.Points:
  141.             result += tab+"geom.vertices.push(v"+str(p.Index)+");\n"
  142.         # adding facets data
  143.         for f in mesh.Facets:
  144.             result += tab+"geom.faces.push( new THREE.Face3"+str(f.PointIndices)+" );\n"
  145.            
  146.     if result:
  147.         # adding a base material
  148.         if FreeCADGui:
  149.             col = obj.ViewObject.ShapeColor
  150.             rgb = Draft.getrgb(col,testbw=False)
  151.         else:
  152.             rgb = "#888888" # test color
  153.         result += tab+"var basematerial = new THREE.MeshBasicMaterial( { color: 0x"+str(rgb)[1:]+" } );\n"
  154.         #result += tab+"var basematerial = new THREE.MeshLambertMaterial( { color: 0x"+str(rgb)[1:]+" } );\n"
  155.        
  156.         if wireframeMode == "faceloop":
  157.             # adding the mesh to the scene with a wireframe copy
  158.             result += tab+"var mesh = new THREE.Mesh( geom, basematerial );\n"
  159.             result += tab+"scene.add( mesh );\n"
  160.             result += tab+"var linematerial = new THREE.LineBasicMaterial({color: 0x000000,});\n"
  161.             for w in wires:
  162.                 result += tab+"var wire = new THREE.Geometry();\n"
  163.                 for p in w:
  164.                     result += tab+"wire.vertices.push(new THREE.Vector3("
  165.                     result += str(p.x)+", "+str(p.y)+", "+str(p.z)+"));\n"
  166.                 result += tab+"var line = new THREE.Line(wire, linematerial);\n"
  167.                 result += tab+"scene.add(line);\n"
  168.            
  169.         elif wireframeMode == "multimaterial":
  170.             # adding a wireframe material
  171.             result += tab+"var wireframe = new THREE.MeshBasicMaterial( { color: "
  172.             result += "0x000000, wireframe: true, transparent: true } );\n"
  173.             result += tab+"var material = [ basematerial, wireframe ];\n"
  174.             result += tab+"var mesh = new THREE.SceneUtils.createMultiMaterialObject( geom, material );\n"
  175.             result += tab+"scene.add( mesh );\n"+tab
  176.            
  177.         else:
  178.             # adding the mesh to the scene with simple material
  179.             result += tab+"var mesh = new THREE.Mesh( geom, basematerial );\n"
  180.             result += tab+"scene.add( mesh );\n"+tab
  181.        
  182.     return result
  183.  
  184. def getTemplate():
  185.     "returns a html template"
  186.    
  187.     result = """<!DOCTYPE html>
  188.        <html>
  189.        <head>
  190.            <title>FreeCAD model</title>
  191.            <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/three.js/r50/three.min.js"></script>
  192.            
  193.            <script>
  194.            
  195.            var camera, controls, scene, renderer;
  196.            
  197.            window.onload = function() {
  198.  
  199.                var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
  200.                var VIEW_ANGLE = 35, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
  201.  
  202.                renderer = new THREE.WebGLRenderer();
  203.                renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
  204.                document.body.appendChild( renderer.domElement );
  205.        
  206.                scene = new THREE.Scene();
  207.        
  208.                camera = new THREE.PerspectiveCamera(
  209.                    VIEW_ANGLE,      // Field of view
  210.                    ASPECT,          // Aspect ratio
  211.                    NEAR,            // Near plane
  212.                    FAR              // Far plane
  213.                );
  214.                $CameraData // placeholder for the FreeCAD camera
  215.                
  216.                controls = new THREE.TrackballControls( camera );
  217.                controls.rotateSpeed = 1.0;
  218.                controls.zoomSpeed = 1.2;
  219.                controls.panSpeed = 0.8;
  220.                controls.noZoom = false;
  221.                controls.noPan = false;
  222.                controls.staticMoving = true;
  223.                controls.dynamicDampingFactor = 0.3;
  224.                controls.keys = [ 65, 83, 68 ];
  225.        
  226.                $ObjectsData // placeholder for the FreeCAD objects
  227.        
  228.                var light = new THREE.PointLight( 0xFFFF00 );
  229.                light.position.set( -10000, -10000, 10000 );
  230.                scene.add( light );
  231.        
  232.                renderer.render( scene, camera );
  233.                
  234.                animate();
  235.            };
  236.            
  237.            function animate(){
  238.                requestAnimationFrame( animate );
  239.                render();
  240.            };
  241.            
  242.            function render(){
  243.                controls.update();
  244.                renderer.render( scene, camera );
  245.            };
  246.            </script>
  247.        </head>
  248.        <body></body>
  249.        </html>"""
  250.    
  251.     return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement