Browse Source

Fixing Export Selected another issues. (#9485)

In the previous commit there were still situations where export
selected would not work properly.

- Fixing Export Selected: Removed most of the calls to ls() which does
a physical select which would really mess up the attempts to Export
Selected. In place I am using listHistory followed by listConnections
which seems to work correctly.
- Updated references to "Diffuse" in maya to be "Color" which is what
was actually being used. Added comments about this to the README.
- Changed code reference of "diffuse" to "color" where it was
appropriate for clarity.
- Added code that keeps it from exporting bones/animations on Export
Selected because it currently doesn't work. Also added Note in the
export dialog to this effect.
- Fixed how opacity was exported. Previously was grabbing the A channel
of the RGB object, but Maya stores transparency in all three RGB
channels. Grabbing R channel for opacity value in JSON.
- Added comment regarding the JSON exporter hack at the bottom of the
file for clarity.
- Turned on Pretty Output by default. I saw no reason not to now that
I've cleaned up the output.
- Removed depreciated arguments from the frameLayout call in MEL. -bs
is no longer supported.
- Moved the bones checkbox and related textfield into the animation
section. Seemed logical.
Aaron Cloutier 9 years ago
parent
commit
24cfc7cf50

+ 17 - 1
utils/exporters/maya/README.md

@@ -8,7 +8,7 @@ Exports Maya models to Three.js' JSON format.  Currently supports exporting the
 - UV sets
 - Shaders/Materials
 - Per-Face material indices
-- Diffuse Maps
+- Color/Diffuse Maps
 - Specular Maps
 - Bump/Normal Maps
 - Bones
@@ -40,3 +40,19 @@ After that, you need to activate the plugin.  In Maya, open `Windows > Settings/
 ## Usage
 
 Use the regular Export menus within Maya, select `Three.js`.
+
+## Notes
+
+Export Selected will not export bones or animations. That is only supported in Export All.
+
+The Maya "Color" Maps are exported as the diffuseColor and mapDiffuse attributes in JSON. The Maya "Diffuse" Maps do NOT export. 
+
+It is recommended to do one character per scene if you are planning to export animations. All geometry will be merged together in the JSON during an export all.
+
+## Trouble Shooting
+
+If you are getting errors while exporting there are a couple things you can try that may help.
+
+- Triangulate all objects before exporting. I have encountered geometry that will not export until I do this. 
+
+- Freeze Transforms. If you've scaled your objects any amount before exporting you'll need to freeze transforms to ensure the normals are exported properly. 

+ 54 - 36
utils/exporters/maya/plug-ins/threeJsFileTranslator.py

@@ -21,7 +21,7 @@ FLOAT_PRECISION = 8
 class ThreeJsWriter(object):
     def __init__(self):
         self.componentKeys = ['vertices', 'normals', 'colors', 'uvs', 'faces',
-                'materials', 'diffuseMaps', 'specularMaps', 'bumpMaps', 'copyTextures',
+                'materials', 'colorMaps', 'specularMaps', 'bumpMaps', 'copyTextures',
                 'bones', 'skeletalAnim', 'bakeAnimations', 'prettyOutput']
 
     def write(self, path, optionString, accessMode):
@@ -43,25 +43,27 @@ class ThreeJsWriter(object):
         self.skinIndices = []
         self.skinWeights = []
 
-        if self.options["bakeAnimations"]:
-            print("exporting animations")
-            self._exportAnimations()
-            self._goToFrame(self.options["startFrame"])
+        print("exporting meshes")
+        self._exportMeshes()
         if self.options["materials"]:
             print("exporting materials")
             self._exportMaterials()
-        if self.options["bones"]:
-            print("exporting bones")
-            select(map(lambda m: m.getParent(), ls(type='mesh')))
-            runtime.GoToBindPose()
-            self._exportBones()
-            print("exporting skins")
-            self._exportSkins()
-        print("exporting meshes")
-        self._exportMeshes()
-        if self.options["skeletalAnim"]:
-            print("exporting keyframe animations")
-            self._exportKeyframeAnimations()
+        if not self.accessMode == MPxFileTranslator.kExportActiveAccessMode :
+			if self.options["bakeAnimations"]:
+				print("exporting animations")
+				self._exportAnimations()
+				self._goToFrame(self.options["startFrame"])
+			if self.options["bones"]:
+				print("exporting bones")
+				select(map(lambda m: m.getParent(), ls(type='mesh')))
+				runtime.GoToBindPose()
+				self._exportBones()
+				print("exporting skins")
+				self._exportSkins()
+			if self.options["skeletalAnim"]:
+				print("exporting keyframe animations")
+				self._exportKeyframeAnimations()
+        
 
         print("writing file")
         output = {
@@ -77,17 +79,18 @@ class ThreeJsWriter(object):
             'materials': self.materials,
         }
 
-        if self.options['bakeAnimations']:
-            output['morphTargets'] = self.morphTargets
+        if not self.accessMode == MPxFileTranslator.kExportActiveAccessMode :
+			if self.options['bakeAnimations']:
+				output['morphTargets'] = self.morphTargets
 
-        if self.options['bones']:
-            output['bones'] = self.bones
-            output['skinIndices'] = self.skinIndices
-            output['skinWeights'] = self.skinWeights
-            output['influencesPerVertex'] = self.options["influencesPerVertex"]
+			if self.options['bones']:
+				output['bones'] = self.bones
+				output['skinIndices'] = self.skinIndices
+				output['skinWeights'] = self.skinWeights
+				output['influencesPerVertex'] = self.options["influencesPerVertex"]
 
-        if self.options['skeletalAnim']:
-            output['animations'] = self.animations
+			if self.options['skeletalAnim']:
+				output['animations'] = self.animations
 
         with file(path, 'w') as f:
             if self.options['prettyOutput']:
@@ -101,7 +104,7 @@ class ThreeJsWriter(object):
             self.__allMeshes = filter(lambda m: len(m.listConnections()) > 0, ls(type='mesh'))
         else :
             print("### Exporting SELECTED ###")
-            self.__allMeshes = ls(sl=1)
+            self.__allMeshes = ls(selection=True)
         return self.__allMeshes
 
     def _parseOptions(self, optionsString):
@@ -230,7 +233,10 @@ class ThreeJsWriter(object):
         return bitmask
 
     def _exportMaterials(self):
-        for mat in ls(type='lambert'):
+    	hist = listHistory( self._allMeshes(), f=1 )
+    	mats = listConnections( hist, type='lambert' )
+        for mat in mats:
+            print("material: " + mat)
             self.materials.append(self._exportMaterial(mat))
 
     def _exportMaterial(self, mat):
@@ -241,8 +247,8 @@ class ThreeJsWriter(object):
             "depthTest": True,
             "depthWrite": True,
             "shading": mat.__class__.__name__,
-            "opacity": mat.getTransparency().a,
-            "transparent": mat.getTransparency().a != 1.0,
+            "opacity": mat.getTransparency().r,
+            "transparent": mat.getTransparency().r != 1.0,
             "vertexColors": False
         }
         if isinstance(mat, nodetypes.Phong):
@@ -253,8 +259,8 @@ class ThreeJsWriter(object):
                 self._exportSpecularMap(result, mat)
         if self.options["bumpMaps"]:
             self._exportBumpMap(result, mat)
-        if self.options["diffuseMaps"]:
-            self._exportDiffuseMap(result, mat)
+        if self.options["colorMaps"]:
+            self._exportColorMap(result, mat)
 
         return result
 
@@ -264,7 +270,7 @@ class ThreeJsWriter(object):
                 result["mapNormalFactor"] = 1
                 self._exportFile(result, f, "Normal")
 
-    def _exportDiffuseMap(self, result, mat):
+    def _exportColorMap(self, result, mat):
         for f in mat.attr('color').inputs():
             result["colorDiffuse"] = f.attr('defaultColor').get()
             self._exportFile(result, f, "Diffuse")
@@ -286,7 +292,9 @@ class ThreeJsWriter(object):
         result["map" + mapType + "Anisotropy"] = 4
 
     def _exportBones(self):
-        for joint in ls(type='joint'):
+    	hist = listHistory( self._allMeshes(), f=1 )
+    	joints = listConnections( hist, type="joint")
+        for joint in joints:
             if joint.getParent():
                 parentIndex = self._indexOfJoint(joint.getParent().name())
             else:
@@ -314,7 +322,9 @@ class ThreeJsWriter(object):
         hierarchy = []
         i = -1
         frameRate = FramesPerSecond(currentUnit(query=True, time=True)).value()
-        for joint in ls(type='joint'):
+        hist = listHistory( self._allMeshes(), f=1 )
+    	joints = listConnections( hist, type="joint")
+        for joint in joints:
             hierarchy.append({
                 "parent": i,
                 "keys": self._getKeyframes(joint, frameRate)
@@ -361,7 +371,8 @@ class ThreeJsWriter(object):
     def _exportSkins(self):
         for mesh in self._allMeshes():
             print("exporting skins for mesh: " + mesh.name())
-            skins = filter(lambda skin: mesh in skin.getOutputGeometry(), ls(type='skinCluster'))
+            hist = listHistory( mesh, f=1 )
+            skins = listConnections( hist, type='skinCluster')
             if len(skins) > 0:
                 print("mesh has " + str(len(skins)) + " skins")
                 skin = skins[0]
@@ -449,6 +460,13 @@ class FramesPerSecond(object):
         else:
             return int(filter(lambda c: c.isdigit(), self.fpsString))
 
+###################################################################
+## The code below was taken from the Blender 3JS Exporter 
+## It's purpose is to fix the JSON output so that it does not
+## put each array value on it's own line, which is ridiculous 
+## for this type of output.
+###################################################################
+
 ROUND = 6
 
 ## THREE override function

+ 16 - 15
utils/exporters/maya/scripts/ThreeJsExportScript.mel

@@ -9,35 +9,35 @@ global proc int ThreeJsExportScript(string $parent, string $action, string $sett
         setParent $parent;
         columnLayout -adj true;
 
-          frameLayout -cll true -cl false -bv true -bs "etchedIn" -l "General Export Options";
+          frameLayout -cll true -cl false -bv true -l "General Export Options";
             columnLayout -adj true;
               checkBox -v true -l "Vertices" vertsCb;
               checkBox -v true -l "Faces" facesCb;
               checkBox -v true -l "Normals" normalsCb;
               checkBox -v true -l "UVs" uvsCb;
               checkBox -v false -l "Colors" colorsCb;
-              checkBox
-                -v true
-                -l "Bones"
-                -onc "textField -e -en true maxInfluencesText;"
-                -ofc "textField -e -en false maxInfluencesText;"
-                bonesCb;
-              textFieldGrp -tx 4 -label "Max Influences Per Vertex" maxInfluencesText;
               setParent ..; // columnLayout
             setParent ..; // frameLayout
 
-          frameLayout -cll true -cl false -bv true -bs "etchedIn" -l "Skinning Options";
+          frameLayout -cll true -cl false -bv true -l "Skinning Options";
             columnLayout -adj true;
               checkBox -v true -l "Material Indices" materialsCb;
-              checkBox -v true -l "Diffuse Maps" diffuseMapsCb;
+              checkBox -v true -l "Color Maps" colorMapsCb;
               checkBox -v true -l "Specular Maps" specularMapsCb;
               checkBox -v true -l "Bump Maps" bumpMapsCb;
               checkBox -v true -l "Copy Texture Files to Target Directory" copyTexturesCb;
               setParent ..; // columnLayout
             setParent ..; // frameLayout
 
-          frameLayout -cll true -cl false -bv true -bs "etchedIn" -l "Animation Options";
+          frameLayout -cll true -cl false -bv true -l "Animation Options";
             columnLayout -adj true;
+              checkBox
+                -v true
+                -l "Bones"
+                -onc "textField -e -en true maxInfluencesText;"
+                -ofc "textField -e -en false maxInfluencesText;"
+            	bonesCb;
+              textFieldGrp -tx 4 -label "Max Influences Per Vertex" maxInfluencesText;
               checkBox -v true -l "Export Animations" animCb;
               checkBox
                 -v false
@@ -48,12 +48,13 @@ global proc int ThreeJsExportScript(string $parent, string $action, string $sett
               textField -en false -tx `playbackOptions -minTime true -q` -ann "Start" startText;
               textField -en false -tx `playbackOptions -maxTime true -q` -ann "End" endText;
               textField -en false -tx 1 -ann "Step" stepText;
+              text -label "NOTE: Animation data is only included in Export All.";
             setParent ..; // columnLayout
           setParent ..; // frameLayout
 
-          frameLayout -cll true -cl false -bv true -bs "etchedIn" -l "Debug Options";
+          frameLayout -cll true -cl false -bv true -l "Debug Options";
             columnLayout -adj true;
-              checkBox -v false -l "Pretty Output" prettyOutputCb;
+              checkBox -v true -l "Pretty Output" prettyOutputCb;
             setParent ..; // columnLayout
           setParent ..; // frameLayout
 
@@ -71,8 +72,8 @@ global proc int ThreeJsExportScript(string $parent, string $action, string $sett
             $option += "uvs ";
         if (`checkBox -q -v materialsCb`)
             $option += "materials ";
-        if (`checkBox -q -v diffuseMapsCb`)
-            $option += "diffuseMaps ";
+        if (`checkBox -q -v colorMapsCb`)
+            $option += "colorMaps ";
         if (`checkBox -q -v specularMapsCb`)
             $option += "specularMaps ";
         if (`checkBox -q -v bumpMapsCb`)