home *** CD-ROM | disk | FTP | other *** search
/ Hackers Magazine 57 / CdHackersMagazineNr57.iso / Software / Multimedia / k3d-setup-0.7.11.0.exe / lib / site-packages / cgkit / dddsimport.py < prev    next >
Encoding:
Python Source  |  2007-01-11  |  16.3 KB  |  375 lines

  1. # ***** BEGIN LICENSE BLOCK *****
  2. # Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3. #
  4. # The contents of this file are subject to the Mozilla Public License Version
  5. # 1.1 (the "License"); you may not use this file except in compliance with
  6. # the License. You may obtain a copy of the License at
  7. # http://www.mozilla.org/MPL/
  8. #
  9. # Software distributed under the License is distributed on an "AS IS" basis,
  10. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. # for the specific language governing rights and limitations under the
  12. # License.
  13. #
  14. # The Original Code is the Python Computer Graphics Kit.
  15. #
  16. # The Initial Developer of the Original Code is Matthias Baas.
  17. # Portions created by the Initial Developer are Copyright (C) 2004
  18. # the Initial Developer. All Rights Reserved.
  19. #
  20. # Contributor(s):
  21. #
  22. # Alternatively, the contents of this file may be used under the terms of
  23. # either the GNU General Public License Version 2 or later (the "GPL"), or
  24. # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  25. # in which case the provisions of the GPL or the LGPL are applicable instead
  26. # of those above. If you wish to allow use of your version of this file only
  27. # under the terms of either the GPL or the LGPL, and not to allow others to
  28. # use your version of this file under the terms of the MPL, indicate your
  29. # decision by deleting the provisions above and replace them with the notice
  30. # and other provisions required by the GPL or the LGPL. If you do not delete
  31. # the provisions above, a recipient may use your version of this file under
  32. # the terms of any one of the MPL, the GPL or the LGPL.
  33. #
  34. # ***** END LICENSE BLOCK *****
  35. # $Id: dddsimport.py,v 1.5 2005/06/07 07:43:03 mbaas Exp $
  36.  
  37. import os.path
  38. import _core
  39. from cgtypes import *
  40. from scene import getScene
  41. from worldobject import WorldObject
  42. from trimesh import TriMesh
  43. from trimeshgeom import TriMeshGeom
  44. from targetcamera import TargetCamera
  45. from glpointlight import GLPointLight
  46. from gltargetspotlight import GLTargetSpotLight
  47. from spotlight3ds import SpotLight3DS
  48. from glmaterial import GLMaterial
  49. from material3ds import Material3DS, TextureMap3DS
  50. import pluginmanager
  51. from sl import *
  52.  
  53. TYPE_UNKNOWN = 0
  54. TYPE_AMBIENT = 1
  55. TYPE_OBJECT = 2
  56. TYPE_CAMERA = 3
  57. TYPE_TARGET = 4
  58. TYPE_LIGHT = 5
  59. TYPE_SPOT = 6
  60.  
  61. GEOM_INIT_NORMALS   = 0x01
  62. GEOM_INIT_MATIDS    = 0x02
  63. GEOM_INIT_TEXELS    = 0x04
  64. GEOM_INIT_FLAGS     = 0x08
  65. GEOM_INIT_SMOOTHING = 0x10
  66. GEOM_INIT_ALL       = 0xff
  67.  
  68.  
  69. # DDDSImporter
  70. class DDDSImporter:
  71.  
  72.     _protocols = ["Import"]
  73.  
  74.     # extension
  75.     def extension():
  76.         """Return the file extensions for this format."""
  77.         return ["3ds"]
  78.     extension = staticmethod(extension)
  79.  
  80.     # description
  81.     def description(self):
  82.         """Return a short description for the file dialog."""
  83.         return "3D Studio"
  84.     description = staticmethod(description)
  85.  
  86.     # importFile
  87.     def importFile(self, filename, flags=GEOM_INIT_ALL, parent=None):
  88.         """Import a 3DS file."""
  89.  
  90.         self.filename = filename
  91.         self.ddds = _core.File3ds()
  92.         self.ddds.load(filename)
  93. #        f = self.ddds.current_frame
  94.         f = getScene().timer().frame
  95.         if f<self.ddds.segment_from:
  96.             f = self.ddds.segment_from
  97.         if f>self.ddds.segment_to:
  98.             f = self.ddds.segment_to
  99.         self.ddds.eval(f)
  100.  
  101.         # Create a dictionary containing all available meshes.
  102.         # Key is the mesh name. This is used to check if all meshes have
  103.         # been processed (i.e. if there were corresponding nodes).
  104.         self.meshes = {}
  105.         m = self.ddds.meshes()
  106.         while m!=None:
  107.             if self.meshes.has_key(m.name):
  108.                 print "Warning: Duplicate mesh names in 3ds file"
  109.             self.meshes[m.name] = m
  110.             m = m.next()
  111.  
  112.         # Create objects...
  113.         self.materials = {}
  114.         self.createObject(self.ddds.nodes(), parent=parent, flags=flags)
  115.         del self.materials
  116.  
  117.         # Create TriMeshes for all left over meshes...
  118.         for n in self.meshes:
  119.             mesh = self.meshes[n]
  120.             tm = TriMeshGeom()
  121.             mesh.initGeom(tm, flags)
  122.             worldobj = TriMesh(name = mesh.name, parent=parent)
  123.             worldobj.geom = tm
  124.  
  125.         self.ddds.free()
  126.  
  127.         
  128.     def createObject(self, node, parent=None, flags=GEOM_INIT_ALL):
  129.         """
  130.         \param node (\c Lib3dsNode) Current node
  131.         \param parent (\c WorldObject) Parent object or None
  132.         \param flags (\c int) Flags for mesh creation
  133.  
  134.         \todo worldtransform als Slot
  135.         \todo Pivot so setzen wie in 3DS
  136.         """
  137.         if node==None:
  138.             return
  139.  
  140.         worldobj = None
  141.         auto_insert = True
  142.         if parent!=None:
  143.             auto_insert = False
  144.  
  145.         # Object?
  146.         if node.type==TYPE_OBJECT:
  147.             if node.name!="$$$DUMMY" and node.name!="_Quader01":
  148.                 data = node.object_data
  149.                 mesh = self.ddds.meshByName(node.name)
  150.                 if self.meshes.has_key(mesh.name):
  151.                     del self.meshes[mesh.name]
  152. #                print "###",node.name,"###"
  153. #                print "Node matrix:"
  154. #                print node.matrix
  155. #                print "Pivot:",data.pivot
  156. #                print "Mesh matrix:"
  157. #                print mesh.matrix
  158.                 tm = TriMeshGeom()
  159.                 mesh.initGeom(tm, flags)
  160.  
  161.                 if parent==None:
  162.                     PT = mat4().translation(-data.pivot)
  163.                     m = node.matrix*PT*mesh.matrix.inverse()
  164.                 else:
  165.                     PT = mat4().translation(-data.pivot)
  166.                     m = node.matrix*PT*mesh.matrix.inverse()
  167.                     # worldtransform von Parent bestimmen...
  168.                     pworldtransform = parent.worldtransform
  169. #                    pworldtransform = parent.localTransform()
  170. #                    p = parent.parent
  171. #                    while p!=None:
  172. #                        pworldtransform = p.localTransform()*pworldtransform
  173. #                        p = p.parent
  174.                     m = pworldtransform.inverse()*m
  175.                 worldobj = TriMesh(name=node.name,
  176. #                                   pivot=data.pivot,
  177.                                    transform=m,
  178.                                    auto_insert=auto_insert)
  179.                 worldobj.geom = tm
  180.  
  181.                 # Set the materials
  182.                 matnames = mesh.materialNames()
  183.                 worldobj.setNumMaterials(len(matnames))
  184.                 for i in range(len(matnames)):
  185.                     if matnames[i]=="":
  186.                         material = GLMaterial()  
  187.                     # Was the material already instantiated?
  188.                     elif matnames[i] in self.materials:
  189.                         material = self.materials[matnames[i]]
  190.                     else:
  191.                         mat = self.ddds.materialByName(matnames[i])
  192. #                        print "Material:",matnames[i]
  193. #                        print "  self_illum:",mat.self_illum
  194. #                        print "  self_ilpct:",mat.self_ilpct
  195.                         material = Material3DS(name = matnames[i],
  196.                                                ambient = mat.ambient,
  197.                                                diffuse = mat.diffuse,
  198.                                                specular = mat.specular,
  199.                                                shininess = mat.shininess,
  200.                                                shin_strength = mat.shin_strength,
  201.                                                use_blur = mat.use_blur,
  202.                                                transparency = mat.transparency,
  203.                                                falloff = mat.falloff,
  204.                                                additive = mat.additive,
  205.                                                use_falloff = mat.use_falloff,
  206.                                                self_illum = mat.self_illum,
  207.                                                self_ilpct = getattr(mat, "self_ilpct", 0),
  208.                                                shading = mat.shading,
  209.                                                soften = mat.soften,
  210.                                                face_map = mat.face_map,
  211.                                                two_sided = mat.two_sided,
  212.                                                map_decal = mat.map_decal,
  213.                                                use_wire = mat.use_wire,
  214.                                                use_wire_abs = mat.use_wire_abs,
  215.                                                wire_size = mat.wire_size,
  216.                                                texture1_map = self._createTexMap(mat.texture1_map),
  217.                                                texture2_map = self._createTexMap(mat.texture2_map),
  218.                                                opacity_map = self._createTexMap(mat.opacity_map),
  219.                                                bump_map = self._createTexMap(mat.bump_map),
  220.                                                specular_map = self._createTexMap(mat.specular_map),
  221.                                                shininess_map = self._createTexMap(mat.shininess_map),
  222.                                                self_illum_map = self._createTexMap(mat.self_illum_map),
  223.                                                reflection_map = self._createTexMap(mat.reflection_map)
  224.                                                )
  225.                         self.materials[matnames[i]] = material
  226.                     worldobj.setMaterial(material, i)
  227.                 
  228.         # Camera?
  229.         elif node.type==TYPE_CAMERA:
  230.             cam = self.ddds.cameraByName(node.name)
  231. #            print "Camera:",node.name
  232. #            print "  Roll:",cam.roll
  233. #            print node.matrix
  234.             # Convert the FOV from horizontal to vertical direction
  235.             # (Todo: What aspect ratio to use?)
  236.             fov = degrees(atan(480/640.0*tan(radians(cam.fov/2.0))))*2.0
  237.             worldobj = TargetCamera(name = node.name,
  238.                                     pos = cam.position,
  239.                                     target = cam.target,
  240.                                     fov = fov,
  241.                                     auto_insert = auto_insert)
  242.         # Light?
  243.         elif node.type==TYPE_LIGHT:
  244.             lgt = self.ddds.lightByName(node.name)
  245.             worldobj = self._createLight(node, lgt, auto_insert)
  246.  
  247.         if worldobj!=None and parent!=None:
  248.             parent.addChild(worldobj)
  249.  
  250.         if worldobj!=None:
  251.             self.createObject(node.childs(), worldobj, flags=flags)
  252.         else:
  253.             self.createObject(node.childs(), parent, flags=flags)
  254.         self.createObject(node.next(), parent, flags=flags)
  255.         
  256.  
  257.     ## protected:
  258.  
  259.     def _createLight(self, node, lgt, auto_insert):
  260.         """Create a light source.
  261.  
  262.         Helper method for the createObject() method.
  263.         """
  264.         shadow_size = lgt.shadow_size
  265.         shadow_bias = lgt.shadow_bias
  266.         shadow_filter = lgt.shadow_filter
  267.         # Check if a shadow map is used but the parameters are all zero
  268.         # (this happens when the Use Global Settings checkbox in MAX
  269.         # is set). If it happens then use the same default values as MAX
  270.         if lgt.shadowed and shadow_size==0 and shadow_bias==0 and shadow_filter==0:
  271.             shadow_size = 256
  272.             shadow_bias = 3.0
  273.             shadow_filter = 5.0
  274.             
  275.         if lgt.spot_light:
  276.             worldobj = SpotLight3DS(name = node.name,
  277.                                     pos = lgt.position,
  278.                                     target = lgt.spot,
  279.                                     enabled = not lgt.off,
  280.                                     intensity = lgt.multiplier,
  281.                                     see_cone = lgt.see_cone,
  282.                                     roll = lgt.roll, 
  283.                                     outer_range = lgt.outer_range,
  284.                                     inner_range = lgt.inner_range,
  285.                                     attenuation = lgt.attenuation,
  286.                                     rectangular_spot = lgt.rectangular_spot,
  287.                                     shadowed = lgt.shadowed,
  288.                                     shadow_bias = shadow_bias,
  289.                                     shadow_filter = shadow_filter,
  290.                                     shadow_size = shadow_size,
  291.                                     spot_aspect = lgt.spot_aspect,
  292.                                     use_projector = lgt.use_projector,
  293.                                     projector = lgt.projector,
  294.                                     overshoot = lgt.spot_overshoot,
  295.                                     ray_shadows = lgt.ray_shadows,
  296.                                     ray_bias = lgt.ray_bias,
  297.                                     hotspot = lgt.hotspot,
  298.                                     falloff = lgt.falloff,
  299.                                     color = lgt.color,
  300.                                     auto_insert = auto_insert)
  301. #            worldobj = GLTargetSpotLight(name = node.name,
  302. #                                         pos = lgt.position,
  303. #                                         target = lgt.spot,
  304. #                                         cutoff = lgt.falloff/2,
  305. #                                         intensity = lgt.multiplier,
  306. #                                         diffuse = lgt.color,
  307. #                                         auto_insert = auto_insert)
  308. #            if lgt.shadowed:
  309. #                worldobj.shadowmap = (lgt.shadow_size, 1.0, 0.001)
  310.         else:
  311.             worldobj = SpotLight3DS(name = node.name,
  312.                                     pos = lgt.position,
  313.                                     target = lgt.spot,
  314.                                     enabled = not lgt.off,
  315.                                     intensity = lgt.multiplier,
  316.                                     see_cone = lgt.see_cone,
  317.                                     roll = lgt.roll, 
  318.                                     outer_range = lgt.outer_range,
  319.                                     inner_range = lgt.inner_range,
  320.                                     attenuation = lgt.attenuation,
  321.                                     rectangular_spot = lgt.rectangular_spot,
  322.                                     shadowed = False,
  323.                                     shadow_bias = shadow_bias,
  324.                                     shadow_filter = shadow_filter,
  325.                                     shadow_size = shadow_size,
  326.                                     spot_aspect = lgt.spot_aspect,
  327.                                     use_projector = lgt.use_projector,
  328.                                     projector = lgt.projector,
  329.                                     overshoot = True,
  330.                                     ray_shadows = lgt.ray_shadows,
  331.                                     ray_bias = lgt.ray_bias,
  332.                                     hotspot = lgt.hotspot,
  333.                                     falloff = lgt.falloff,
  334.                                     color = lgt.color,
  335.                                     auto_insert = auto_insert)
  336. #            worldobj = GLPointLight(name = node.name,
  337. #                                    pos = lgt.position,
  338. #                                    intensity = lgt.multiplier,
  339. #                                    diffuse = lgt.color,
  340. #                                    auto_insert = auto_insert)
  341.             
  342.         return worldobj
  343.         
  344.     def _createTexMap(self, texmap):
  345.         """Create a TextureMap3DS object (or None).
  346.  
  347.         \param texmap (\c Lib3dsTextureMap) Texture map
  348.         """
  349.         if texmap.name=="":
  350.             return None
  351.  
  352.         dir = os.path.dirname(self.filename)
  353.         dir = os.path.abspath(dir)
  354.         return TextureMap3DS(name=os.path.join(dir, texmap.name),
  355.                              flags = texmap.flags,
  356.                              percent = texmap.percent,
  357.                              blur = texmap.blur,
  358.                              scale = texmap.scale,
  359.                              offset = texmap.offset,
  360.                              rotation = texmap.rotation,
  361.                              tint1 = texmap.tint_1,
  362.                              tint2 = texmap.tint_2,
  363.                              tintr = texmap.tint_r,
  364.                              tintg = texmap.tint_g,
  365.                              tintb = texmap.tint_b)
  366.  
  367.         
  368.  
  369.  
  370. ######################################################################
  371.  
  372. # Register the Importer class as a plugin class
  373. if hasattr(_core, "File3ds"):
  374.     pluginmanager.register(DDDSImporter)
  375.