private void GetTransform(MFnTransform mFnTransform, ref float[] position, ref float[] rotationQuaternion, ref float[] rotation, ref BabylonVector3.EulerRotationOrder rotationOrder, ref float[] scaling) { var transformationMatrix = new MTransformationMatrix(mFnTransform.transformationMatrix); var mayaRotationOrder = 0; MGlobal.executeCommand($"getAttr {mFnTransform.fullPathName}.rotateOrder", out mayaRotationOrder); rotationOrder = Tools.ConvertMayaRotationOrder((MEulerRotation.RotationOrder)mayaRotationOrder); position = transformationMatrix.getTranslation(); rotationQuaternion = transformationMatrix.getRotationQuaternion(); rotation = transformationMatrix.getRotation(); scaling = transformationMatrix.getScale(); // Switch coordinate system at object level position[2] *= -1; rotationQuaternion[0] *= -1; rotationQuaternion[1] *= -1; rotation[0] *= -1; rotation[1] *= -1; rotationOrder = Tools.InvertRotationOrder(rotationOrder); // Apply unit conversion factor to meter position[0] *= scaleFactorToMeters; position[1] *= scaleFactorToMeters; position[2] *= scaleFactorToMeters; }
public ModelVisual3D MakeVisualModel(MDagPath path) { var mesh = new MFnMesh(path); var r = new ModelVisual3D(); r.Content = MakeModel(mesh); r.Transform = new Transform3DGroup(); Transform3DGroup transformGroup = r.Transform as Transform3DGroup; MTransformationMatrix matrix = new MTransformationMatrix(path.inclusiveMatrix); //MVector tr =matrix.getTranslation (MSpace.Space.kWorld) ; //TranslateTransform3D translation =new TranslateTransform3D (tr.x, tr.y, tr.z) ; //transformGroup.Children.Add (translation) ; //double x =0, y =0, z =0, w =0 ; //matrix.getRotationQuaternion (ref x, ref y, ref z, ref w, MSpace.Space.kWorld) ; //QuaternionRotation3D rotation =new QuaternionRotation3D (new Quaternion (x, y, z, w)) ; //transformGroup.Children.Add (new RotateTransform3D (rotation)) ; //double [] scales =new double [3] ; //matrix.getScale (scales, MSpace.Space.kWorld) ; //ScaleTransform3D scale =new ScaleTransform3D (scales [0], scales [1], scales [2]) ; //transformGroup.Children.Add (scale) ; MMatrix mat = matrix.asMatrixProperty; Matrix3D matrix3d = new Matrix3D(mat [0, 0], mat [0, 1], mat [0, 2], mat [0, 3], mat [1, 0], mat [1, 1], mat [1, 2], mat [1, 3], mat [2, 0], mat [2, 1], mat [2, 2], mat [2, 3], mat [3, 0], mat [3, 1], mat [3, 2], mat [3, 3]); MatrixTransform3D matrixTransform = new MatrixTransform3D(matrix3d); transformGroup.Children.Add(matrixTransform); return(r); }
private BabylonMatrix ConvertMayaToBabylonMatrix(MMatrix mMatrix) { var transformationMatrix = new MTransformationMatrix(mMatrix); // Retreive TRS vectors from matrix float[] position = transformationMatrix.getTranslation(); float[] rotationQuaternion = transformationMatrix.getRotationQuaternion(); float[] scaling = transformationMatrix.getScale(); // Switch coordinate system at object level position[2] *= -1; rotationQuaternion[0] *= -1; rotationQuaternion[1] *= -1; // Apply unit conversion factor to meter position[0] *= scaleFactorToMeters; position[1] *= scaleFactorToMeters; position[2] *= scaleFactorToMeters; // The composed matrix return(BabylonMatrix.Compose(new BabylonVector3(scaling[0], scaling[1], scaling[2]), // scaling new BabylonQuaternion(rotationQuaternion[0], rotationQuaternion[1], rotationQuaternion[2], rotationQuaternion[3]), // rotation new BabylonVector3(position[0], position[1], position[2]) // position )); }
/// <summary> /// Default space is transform /// </summary> /// <param name="mTransformationMatrix"></param> /// <returns></returns> public static float[] getRotationQuaternion(this MTransformationMatrix mTransformationMatrix) { double x = 0, y = 0, z = 0, w = 0; mTransformationMatrix.getRotationQuaternion(ref x, ref y, ref z, ref w); return(new float[] { (float)x, (float)y, (float)z, (float)w }); }
/// <summary> /// Default space is transform /// Default rotation order is YXZ /// </summary> /// <param name="mTransformationMatrix"></param> /// <returns></returns> public static float[] getRotation(this MTransformationMatrix mTransformationMatrix) { double[] rotation = new double[3]; int order = (int)MTransformationMatrix.RotationOrder.kYXZ; mTransformationMatrix.getRotation(rotation, out order); return(Array.ConvertAll(rotation, item => (float)item));; }
private void GetTransform(MFnTransform mFnTransform, ref float[] position) { var transformationMatrix = new MTransformationMatrix(mFnTransform.transformationMatrix); position = transformationMatrix.getTranslation(); // Switch coordinate system at object level position[2] *= -1; }
private void ComposeInverseGlobal(Vector3 translation, Vector3 scale, Quaternion rotation) { MTransformationMatrix transform = new MTransformationMatrix(); transform.setTranslation(new MVector(translation.X, translation.Y, translation.Z), MSpace.Space.kTransform); transform.setRotationQuaternion(rotation.X, rotation.Y, rotation.Z, rotation.W, MSpace.Space.kTransform); transform.setScale(new double[] { scale.X, scale.Y, scale.Z }, MSpace.Space.kTransform); this.InverseGlobal = transform; }
/// <summary> /// Default space is transform /// Default rotation order is YXZ /// </summary> /// <param name="mTransformationMatrix"></param> /// <returns></returns> public static float[] getRotation(this MTransformationMatrix mTransformationMatrix) { double x = 0, y = 0, z = 0, w = 0; mTransformationMatrix.getRotationQuaternion(ref x, ref y, ref z, ref w); // Maya conversion algorithm is bugged when reaching limits (angle like (-90,89,90)) // Convert quaternion to vector3 using Babylon conversion algorithm BabylonQuaternion babylonQuaternion = new BabylonQuaternion((float)x, (float)y, (float)z, (float)w); return(babylonQuaternion.toEulerAngles().ToArray()); }
public void Create() { MItDag jointIterator = new MItDag(MItDag.TraversalType.kDepthFirst, MFn.Type.kJoint); //Create Joints and collect their DAG Paths short jointID = 0; for (; !jointIterator.isDone; jointIterator.next()) { MFnIkJoint ikJoint = new MFnIkJoint(); MDagPath jointDagPath = new MDagPath(); jointIterator.getPath(jointDagPath); this.JointDagPaths.Add(jointDagPath); ikJoint.setObject(jointDagPath); MTransformationMatrix local = new MTransformationMatrix(ikJoint.transformationMatrix); MTransformationMatrix inverseGlobal = new MTransformationMatrix(jointDagPath.inclusiveMatrixInverse); this.Joints.Add(new SKLJoint(jointID, ikJoint.name, local, inverseGlobal)); this.JointIndices.Add(ELF.Hash(ikJoint.name), jointID); jointID++; } //Set Joint parents for (int i = 0; i < this.Joints.Count; i++) { MFnIkJoint ikJoint = new MFnIkJoint(this.JointDagPaths[i]); if (ikJoint.parentCount == 1 && ikJoint.parent(0).apiType == MFn.Type.kJoint) { MFnIkJoint parentJoint = new MFnIkJoint(ikJoint.parent(0)); MDagPath parentDagPath = new MDagPath(); parentJoint.getPath(parentDagPath); //Find index of parent for (int j = 0; j < this.JointDagPaths.Count; j++) { if (parentDagPath.equalEqual(this.JointDagPaths[j])) { this.Joints[i].ParentID = (short)j; } } } else { this.Joints[i].ParentID = -1; } } MGlobal.displayInfo("SKLFile:Create - Created SKL File"); }
public SKLJoint(short id, string name, MTransformationMatrix local, MTransformationMatrix inverseGlobal) { this.IsLegacy = false; this.Flags = 0; this.ID = id; this.Name = name; this.Hash = ELF.Hash(name); this.Local = local; this.InverseGlobal = inverseGlobal; PrintInfo(); }
void printTransformData(MDagPath dagPath, bool quiet) { MObject transformNode = null; try { transformNode = dagPath.transform; } catch (System.Exception) { // This node has no transform - i.e., it's the world node // return; } MFnDagNode transform = null; try { transform = new MFnDagNode(transformNode); } catch (System.Exception) { return; } MTransformationMatrix matrix = new MTransformationMatrix(transform.transformationMatrix); if (!quiet) { MGlobal.displayInfo(" translation: " + MVectorToString(matrix.translation(MSpace.Space.kWorld)) + Environment.NewLine); } double[] threeDoubles = new double[3]; int rOrder = 0; matrix.getRotation(threeDoubles, out rOrder, MSpace.Space.kWorld); if (!quiet) { MGlobal.displayInfo(string.Format(" rotation: [%f, %f, %f]\n", threeDoubles[0], threeDoubles[1], threeDoubles[2])); } matrix.getScale(threeDoubles, MSpace.Space.kWorld); if (!quiet) { MGlobal.displayInfo(string.Format(" scale: [%f, %f, %f]\n", threeDoubles[0], threeDoubles[1], threeDoubles[2])); } }
private void GetTransform(MFnTransform mFnTransform, ref float[] position, ref float[] rotationQuaternion, ref float[] rotation, ref float[] scaling) { var transformationMatrix = new MTransformationMatrix(mFnTransform.transformationMatrix); position = transformationMatrix.getTranslation(); rotationQuaternion = transformationMatrix.getRotationQuaternion(); rotation = transformationMatrix.getRotation(); scaling = transformationMatrix.getScale(); // Switch coordinate system at object level position[2] *= -1; rotationQuaternion[0] *= -1; rotationQuaternion[1] *= -1; rotation[0] *= -1; rotation[1] *= -1; }
public override MMatrix asMatrix() { // Get the current transform matrix MMatrix m = base.asMatrix(); // Initialize the new matrix we will calculate MTransformationMatrix tm = new MTransformationMatrix( m ); // Find the current rotation as a quaternion MQuaternion quat = rotation(); // Convert the rocking value in degrees to radians DegreeRadianConverter conv = new DegreeRadianConverter(); double newTheta = conv.degreesToRadians( getRockInX() ); quat.setToXAxis( newTheta ); // Apply the rocking rotation to the existing rotation tm.addRotationQuaternion( quat.x, quat.y, quat.z, quat.w, MSpace.Space.kTransform); // Let Maya know what the matrix should be return tm.asMatrixProperty; }
private void ExportTransform(BabylonAbstractMesh babylonAbstractMesh, MFnDagNode mFnDagNode) { // Position / rotation / scaling var transformationMatrix = new MTransformationMatrix(mFnDagNode.transformationMatrix); babylonAbstractMesh.position = transformationMatrix.getTranslation(); if (_exportQuaternionsInsteadOfEulers) { babylonAbstractMesh.rotationQuaternion = transformationMatrix.getRotationQuaternion(); } else { babylonAbstractMesh.rotation = transformationMatrix.getRotation(); } babylonAbstractMesh.scaling = transformationMatrix.getScale(); }
public override MMatrix asMatrix() { // Get the current transform matrix MMatrix m = base.asMatrix(); // Initialize the new matrix we will calculate MTransformationMatrix tm = new MTransformationMatrix(m); // Find the current rotation as a quaternion MQuaternion quat = rotation(); // Convert the rocking value in degrees to radians DegreeRadianConverter conv = new DegreeRadianConverter(); double newTheta = conv.degreesToRadians(getRockInX()); quat.setToXAxis(newTheta); // Apply the rocking rotation to the existing rotation tm.addRotationQuaternion(quat.x, quat.y, quat.z, quat.w, MSpace.Space.kTransform); // Let Maya know what the matrix should be return(tm.asMatrixProperty); }
public ModelVisual3D MakeVisualModel(MDagPath path) { var mesh =new MFnMesh (path) ; var r =new ModelVisual3D () ; r.Content =MakeModel (mesh) ; r.Transform =new Transform3DGroup () ; Transform3DGroup transformGroup =r.Transform as Transform3DGroup ; MTransformationMatrix matrix =new MTransformationMatrix (path.inclusiveMatrix) ; //MVector tr =matrix.getTranslation (MSpace.Space.kWorld) ; //TranslateTransform3D translation =new TranslateTransform3D (tr.x, tr.y, tr.z) ; //transformGroup.Children.Add (translation) ; //double x =0, y =0, z =0, w =0 ; //matrix.getRotationQuaternion (ref x, ref y, ref z, ref w, MSpace.Space.kWorld) ; //QuaternionRotation3D rotation =new QuaternionRotation3D (new Quaternion (x, y, z, w)) ; //transformGroup.Children.Add (new RotateTransform3D (rotation)) ; //double [] scales =new double [3] ; //matrix.getScale (scales, MSpace.Space.kWorld) ; //ScaleTransform3D scale =new ScaleTransform3D (scales [0], scales [1], scales [2]) ; //transformGroup.Children.Add (scale) ; MMatrix mat =matrix.asMatrixProperty ; Matrix3D matrix3d =new Matrix3D (mat [0, 0], mat [0, 1], mat [0, 2], mat [0, 3], mat [1, 0], mat [1, 1], mat [1, 2], mat [1, 3], mat [2, 0], mat [2, 1], mat [2, 2], mat [2, 3], mat [3, 0], mat [3, 1], mat [3, 2], mat [3, 3]) ; MatrixTransform3D matrixTransform = new MatrixTransform3D (matrix3d) ; transformGroup.Children.Add (matrixTransform) ; return (r) ; }
private BabylonNode ExportMesh(MObject mObject, BabylonScene babylonScene) { MFnMesh mFnMesh = new MFnMesh(mObject); MFnDagNode mFnDagNode = new MFnDagNode(mObject); var mObjectParent = mFnMesh.parent(0); MFnDagNode mFnDagNodeParent = new MFnDagNode(mObjectParent); // --- prints --- #region prints RaiseVerbose("BabylonExporter.Mesh | mFnMesh data", 2); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.name=" + mFnMesh.name, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.absoluteName=" + mFnMesh.absoluteName, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.fullPathName=" + mFnMesh.fullPathName, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.partialPathName=" + mFnMesh.partialPathName, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numVertices=" + mFnMesh.numVertices, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numEdges=" + mFnMesh.numEdges, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numPolygons=" + mFnMesh.numPolygons, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numFaceVertices=" + mFnMesh.numFaceVertices, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numNormals=" + mFnMesh.numNormals, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numUVSets=" + mFnMesh.numUVSets, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numUVsProperty=" + mFnMesh.numUVsProperty, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.activeColor=" + mFnMesh.activeColor.toString(), 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.attributeCount=" + mFnMesh.attributeCount, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.childCount=" + mFnMesh.childCount, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.displayColors=" + mFnMesh.displayColors, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.dormantColor=" + mFnMesh.dormantColor, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.hasUniqueName=" + mFnMesh.hasUniqueName, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.inUnderWorld=" + mFnMesh.inUnderWorld, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isDefaultNode=" + mFnMesh.isDefaultNode, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isInstanceable=" + mFnMesh.isInstanceable, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isInstanced(true)=" + mFnMesh.isInstanced(true), 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isInstanced(false)=" + mFnMesh.isInstanced(false), 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isInstanced()=" + mFnMesh.isInstanced(), 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isIntermediateObject=" + mFnMesh.isIntermediateObject, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.isShared=" + mFnMesh.isShared, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numColorSets=" + mFnMesh.numColorSets, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.numColorsProperty=" + mFnMesh.numColorsProperty, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.objectColor=" + mFnMesh.objectColor, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.parentCount=" + mFnMesh.parentCount, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.parentNamespace=" + mFnMesh.parentNamespace, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.uuid().asString()=" + mFnMesh.uuid().asString(), 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.dagRoot().apiType=" + mFnMesh.dagRoot().apiType, 3); RaiseVerbose("BabylonExporter.Mesh | mFnMesh.model.equalEqual(mFnMesh.objectProperty)=" + mFnMesh.model.equalEqual(mFnMesh.objectProperty), 3); RaiseVerbose("BabylonExporter.Mesh | ToString(mFnMesh.transformationMatrix)=" + mFnMesh.transformationMatrix.toString(), 3); var transformationMatrix = new MTransformationMatrix(mFnMesh.transformationMatrix); RaiseVerbose("BabylonExporter.Mesh | transformationMatrix.getTranslation().toString()=" + transformationMatrix.getTranslation().toString(), 3); var transformationMatrixParent = new MTransformationMatrix(mFnDagNodeParent.transformationMatrix); RaiseVerbose("BabylonExporter.Mesh | transformationMatrixParent.getTranslation().toString()=" + transformationMatrixParent.getTranslation().toString(), 3); // Geometry MIntArray triangleCounts = new MIntArray(); MIntArray trianglesVertices = new MIntArray(); mFnMesh.getTriangles(triangleCounts, trianglesVertices); RaiseVerbose("BabylonExporter.Mesh | triangleCounts.ToArray()=" + triangleCounts.ToArray().toString(), 3); RaiseVerbose("BabylonExporter.Mesh | trianglesVertices.ToArray()=" + trianglesVertices.ToArray().toString(), 3); int[] polygonsVertexCount = new int[mFnMesh.numPolygons]; for (int polygonId = 0; polygonId < mFnMesh.numPolygons; polygonId++) { polygonsVertexCount[polygonId] = mFnMesh.polygonVertexCount(polygonId); } RaiseVerbose("BabylonExporter.Mesh | polygonsVertexCount=" + polygonsVertexCount.toString(), 3); //MFloatPointArray points = new MFloatPointArray(); //mFnMesh.getPoints(points); //RaiseVerbose("BabylonExporter.Mesh | points.ToArray()=" + points.ToArray().Select(mFloatPoint => mFloatPoint.toString()), 3); //MFloatVectorArray normals = new MFloatVectorArray(); //mFnMesh.getNormals(normals); //RaiseVerbose("BabylonExporter.Mesh | normals.ToArray()=" + normals.ToArray().Select(mFloatPoint => mFloatPoint.toString()), 3); for (int polygonId = 0; polygonId < mFnMesh.numPolygons; polygonId++) { MIntArray verticesId = new MIntArray(); RaiseVerbose("BabylonExporter.Mesh | polygonId=" + polygonId, 3); int nbTriangles = triangleCounts[polygonId]; RaiseVerbose("BabylonExporter.Mesh | nbTriangles=" + nbTriangles, 3); for (int triangleIndex = 0; triangleIndex < triangleCounts[polygonId]; triangleIndex++) { RaiseVerbose("BabylonExporter.Mesh | triangleIndex=" + triangleIndex, 3); int[] triangleVertices = new int[3]; mFnMesh.getPolygonTriangleVertices(polygonId, triangleIndex, triangleVertices); RaiseVerbose("BabylonExporter.Mesh | triangleVertices=" + triangleVertices.toString(), 3); foreach (int vertexId in triangleVertices) { RaiseVerbose("BabylonExporter.Mesh | vertexId=" + vertexId, 3); MPoint point = new MPoint(); mFnMesh.getPoint(vertexId, point); RaiseVerbose("BabylonExporter.Mesh | point=" + point.toString(), 3); MVector normal = new MVector(); mFnMesh.getFaceVertexNormal(polygonId, vertexId, normal); RaiseVerbose("BabylonExporter.Mesh | normal=" + normal.toString(), 3); } } } #endregion if (IsMeshExportable(mFnMesh) == false) { return(null); } RaiseMessage(mFnMesh.name, 1); var babylonMesh = new BabylonMesh { name = mFnMesh.name, id = mFnMesh.uuid().asString() }; // Position / rotation / scaling / hierarchy ExportNode(babylonMesh, mFnDagNode, babylonScene); // Misc. // TODO - Retreive from Maya // TODO - What is the difference between isVisible and visibility? // TODO - Fix fatal error: Attempting to save in C:/Users/Fabrice/AppData/Local/Temp/Fabrice.20171205.1613.ma //babylonMesh.isVisible = mDagPath.isVisible; //babylonMesh.visibility = meshNode.MaxNode.GetVisibility(0, Tools.Forever); //babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows == 1; //babylonMesh.applyFog = meshNode.MaxNode.ApplyAtmospherics == 1; if (mFnMesh.numPolygons < 1) { RaiseError($"Mesh {babylonMesh.name} has no face", 2); } if (mFnMesh.numVertices < 3) { RaiseError($"Mesh {babylonMesh.name} has not enough vertices", 2); } if (mFnMesh.numVertices >= 65536) { RaiseWarning($"Mesh {babylonMesh.name} has more than 65536 vertices which means that it will require specific WebGL extension to be rendered. This may impact portability of your scene on low end devices.", 2); } // TODO - Material var vertices = new List <GlobalVertex>(); var indices = new List <int>(); // TODO - UV, color, alpha //var mappingChannels = unskinnedMesh.ActiveMapChannelNum; //bool hasUV = false; //bool hasUV2 = false; //for (int i = 0; i < mappingChannels.Count; ++i) //{ // var indexer = i; // var channelNum = mappingChannels[indexer]; // if (channelNum == 1) // { // hasUV = true; // } // else if (channelNum == 2) // { // hasUV2 = true; // } //} //var hasColor = unskinnedMesh.NumberOfColorVerts > 0; //var hasAlpha = unskinnedMesh.GetNumberOfMapVerts(-2) > 0; // TODO - Add custom properties var optimizeVertices = false; // meshNode.MaxNode.GetBoolProperty("babylonjs_optimizevertices"); // Compute normals var subMeshes = new List <BabylonSubMesh>(); ExtractGeometry(mFnMesh, vertices, indices, subMeshes, optimizeVertices); if (vertices.Count >= 65536) { RaiseWarning($"Mesh {babylonMesh.name} has {vertices.Count} vertices. This may prevent your scene to work on low end devices where 32 bits indice are not supported", 2); if (!optimizeVertices) { RaiseError("You can try to optimize your object using [Try to optimize vertices] option", 2); } } RaiseMessage($"{vertices.Count} vertices, {indices.Count / 3} faces", 2); // Buffers babylonMesh.positions = vertices.SelectMany(v => v.Position).ToArray(); babylonMesh.normals = vertices.SelectMany(v => v.Normal).ToArray(); babylonMesh.subMeshes = subMeshes.ToArray(); // Buffers - Indices babylonMesh.indices = indices.ToArray(); babylonScene.MeshesList.Add(babylonMesh); RaiseMessage("BabylonExporter.Mesh | done", 3); return(babylonMesh); }
private List <BabylonAnimation> GetAnimationsFrameByFrame(MFnTransform mFnTransform) { int start = Loader.GetMinTime(); int end = Loader.GetMaxTime(); // Animations List <BabylonAnimation> animations = new List <BabylonAnimation>(); string[] babylonAnimationProperties = new string[] { "scaling", "rotationQuaternion", "position", "visibility" }; Dictionary <string, List <BabylonAnimationKey> > keysPerProperty = new Dictionary <string, List <BabylonAnimationKey> >(); keysPerProperty.Add("scaling", new List <BabylonAnimationKey>()); keysPerProperty.Add("rotationQuaternion", new List <BabylonAnimationKey>()); keysPerProperty.Add("position", new List <BabylonAnimationKey>()); keysPerProperty.Add("visibility", new List <BabylonAnimationKey>()); // get keys for (int currentFrame = start; currentFrame <= end; currentFrame++) { // get transformation matrix at this frame MDoubleArray mDoubleMatrix = new MDoubleArray(); MGlobal.executeCommand($"getAttr -t {currentFrame} {mFnTransform.fullPathName}.matrix", mDoubleMatrix); mDoubleMatrix.get(out float[] localMatrix); MMatrix matrix = new MMatrix(localMatrix); var transformationMatrix = new MTransformationMatrix(matrix); // Retreive TRS vectors from matrix var position = transformationMatrix.getTranslation(); var rotationQuaternion = transformationMatrix.getRotationQuaternion(); var scaling = transformationMatrix.getScale(); // Switch coordinate system at object level position[2] *= -1; rotationQuaternion[0] *= -1; rotationQuaternion[1] *= -1; // create animation key for each property for (int indexAnimation = 0; indexAnimation < babylonAnimationProperties.Length; indexAnimation++) { string babylonAnimationProperty = babylonAnimationProperties[indexAnimation]; BabylonAnimationKey key = new BabylonAnimationKey(); key.frame = currentFrame; switch (indexAnimation) { case 0: // scaling key.values = scaling.ToArray(); break; case 1: // rotationQuaternion key.values = rotationQuaternion.ToArray(); break; case 2: // position key.values = position.ToArray(); break; case 3: // visibility key.values = new float[] { Loader.GetVisibility(mFnTransform.fullPathName, currentFrame) }; break; } keysPerProperty[babylonAnimationProperty].Add(key); } } // create animation for each property for (int indexAnimation = 0; indexAnimation < babylonAnimationProperties.Length; indexAnimation++) { string babylonAnimationProperty = babylonAnimationProperties[indexAnimation]; List <BabylonAnimationKey> keys = keysPerProperty[babylonAnimationProperty]; var keysFull = new List <BabylonAnimationKey>(keys); // Optimization OptimizeAnimations(keys, true); // Ensure animation has at least 2 frames if (IsAnimationKeysRelevant(keys)) { int dataType = 0; // "scaling", "rotationQuaternion", "position", "visibility" if (indexAnimation == 0 || indexAnimation == 2) // scaling and position { dataType = (int)BabylonAnimation.DataType.Vector3; } else if (indexAnimation == 1) // rotationQuaternion { dataType = (int)BabylonAnimation.DataType.Quaternion; } else // visibility { dataType = (int)BabylonAnimation.DataType.Float; } // Create BabylonAnimation animations.Add(new BabylonAnimation() { dataType = dataType, name = babylonAnimationProperty + " animation", framePerSecond = Loader.GetFPS(), loopBehavior = (int)BabylonAnimation.LoopBehavior.Cycle, property = babylonAnimationProperty, keys = keys.ToArray(), keysFull = keysFull }); } } return(animations); }
void printTransformData(MDagPath dagPath, bool quiet) { MObject transformNode = null; try { transformNode = dagPath.transform; } catch (System.Exception) { // This node has no transform - i.e., it's the world node // return; } MFnDagNode transform = null; try { transform = new MFnDagNode(transformNode); } catch (System.Exception ) { return; } MTransformationMatrix matrix = new MTransformationMatrix(transform.transformationMatrix); if (!quiet) { MGlobal.displayInfo(" translation: " + MVectorToString(matrix.translation(MSpace.Space.kWorld)) + Environment.NewLine); } double[] threeDoubles = new double[3]; int rOrder = 0; matrix.getRotation (threeDoubles, out rOrder, MSpace.Space.kWorld); if (!quiet) { MGlobal.displayInfo(string.Format(" rotation: [%f, %f, %f]\n", threeDoubles[0], threeDoubles[1], threeDoubles[2])); } matrix.getScale (threeDoubles, MSpace.Space.kWorld); if (!quiet) { MGlobal.displayInfo(string.Format(" scale: [%f, %f, %f]\n", threeDoubles[0], threeDoubles[1], threeDoubles[2])); } }
public void WriteSiegeSource(string FilePath) { // Validate anim this.ValidateXAnim(); // Prepare to write the source file var Result = new SiegeAnim(); // Set basic flags var FrameCount = this.FrameCount(); if (FrameCount <= 0) { return; } // Set it Result.animation.frames = FrameCount; Result.animation.loop = 1; Result.animation.nodes = this.Parts.Count; Result.animation.playbackSpeed = 1; Result.animation.speed = 0; // Default shot Result.shots.Add(new Shot() { start = 0, end = FrameCount, name = "default" }); // Default info Result.info.argJson = "{}"; Result.info.computer = "D3V-137"; Result.info.domain = "ATVI"; Result.info.ta_game_path = "c:\\"; Result.info.time = ""; Result.info.user = "******"; // Prepare to generate siege data foreach (var Part in this.Parts) { Result.nodes.Add(new Node() { name = Part.TagName }); } using (var Zip = ZipStorer.Create(FilePath, string.Empty)) { using (var WritePosition = new BinaryWriter(new MemoryStream())) using (var WriteRotation = new BinaryWriter(new MemoryStream())) { // Loop over frames, then parts, and write data for (int i = 0; i < FrameCount; i++) { foreach (var Part in this.Parts) { // Get rotation as quaternion var RotationQuat = new MTransformationMatrix(Part.Frames[i].RotationMatrix).rotation; // Write rotation and position raw WritePosition.Write((float)Part.Frames[i].Offset.x); WritePosition.Write((float)Part.Frames[i].Offset.y); WritePosition.Write((float)Part.Frames[i].Offset.z); WriteRotation.Write((float)RotationQuat.x); WriteRotation.Write((float)RotationQuat.y); WriteRotation.Write((float)RotationQuat.z); WriteRotation.Write((float)RotationQuat.w); } } // Flush WritePosition.Flush(); WriteRotation.Flush(); // Reset WritePosition.BaseStream.Position = 0; WriteRotation.BaseStream.Position = 0; // Add to archive Zip.AddStream(ZipStorer.Compression.Deflate, "data/positions", WritePosition.BaseStream, DateTime.Now, string.Empty); Zip.AddStream(ZipStorer.Compression.Deflate, "data/quaternions", WriteRotation.BaseStream, DateTime.Now, string.Empty); // Set strides Result.data.dataPositionsBase.byteStride = 12 * this.Parts.Count; Result.data.dataPositionsBase.byteSize = 12 * this.Parts.Count * FrameCount; Result.data.dataRotationsBase.byteStride = 16 * this.Parts.Count; Result.data.dataRotationsBase.byteSize = 16 * this.Parts.Count * FrameCount; // Serialize to file var SourceMod = new JavaScriptSerializer().Serialize(Result); // Remove the broken names SourceMod = SourceMod.Replace("dataRotationsBase", "data/quaternions").Replace("dataPositionsBase", "data/positions"); // Add to archive using (var Index = new MemoryStream(Encoding.UTF8.GetBytes(SourceMod))) Zip.AddStream(ZipStorer.Compression.Deflate, "index.json", Index, DateTime.Now, string.Empty); } } }
/// <summary> /// Default space is transform /// </summary> /// <param name="mTransformationMatrix"></param> /// <returns></returns> public static float[] getTranslation(this MTransformationMatrix mTransformationMatrix) { MVector mVector = mTransformationMatrix.getTranslation(MSpace.Space.kTransform); return(mVector.toArray()); }
public void ResetLights() { //<AmbientLight Color="White" /> //<DirectionalLight Color="White" Direction="-1,-1,-1" /> //<PointLight Color="White" ConstantAttenuation="1" LinearAttenuation="1" Position="0,0,0" QuadraticAttenuation="1" Range="0" /> //<SpotLight Color="White" ConstantAttenuation="1" Direction="-1,-1,-1" InnerConeAngle="10" LinearAttenuation="1" OuterConeAngle="10" Position="0,0,0" QuadraticAttenuation="1" Range="0" /> lights.Children.Clear(); MItDag dagIterator = new MItDag(MItDag.TraversalType.kDepthFirst, MFn.Type.kLight); for ( ; !dagIterator.isDone; dagIterator.next()) { MDagPath lightPath = new MDagPath(); dagIterator.getPath(lightPath); MFnLight light = new MFnLight(lightPath); bool isAmbient = light.lightAmbient; MColor mcolor = light.color; Color color = Color.FromScRgb(1.0f, mcolor.r, mcolor.g, mcolor.b); if (isAmbient) { AmbientLight ambient = new AmbientLight(color); lights.Children.Add(ambient); continue; } MFloatVector lightDirection = light.lightDirection(0, MSpace.Space.kWorld); Vector3D direction = new Vector3D(lightDirection.x, lightDirection.y, lightDirection.z); bool isDiffuse = light.lightDiffuse; try { MFnDirectionalLight dirLight = new MFnDirectionalLight(lightPath); DirectionalLight directional = new DirectionalLight(color, direction); lights.Children.Add(directional); continue; } catch { } MObject transformNode = lightPath.transform; MFnDagNode transform = new MFnDagNode(transformNode); MTransformationMatrix matrix = new MTransformationMatrix(transform.transformationMatrix); double [] threeDoubles = new double [3]; int rOrder = 0; //MTransformationMatrix.RotationOrder rOrder ; matrix.getRotation(threeDoubles, out rOrder, MSpace.Space.kWorld); matrix.getScale(threeDoubles, MSpace.Space.kWorld); MVector pos = matrix.getTranslation(MSpace.Space.kWorld); Point3D position = new Point3D(pos.x, pos.y, pos.z); try { MFnPointLight pointLight = new MFnPointLight(lightPath); PointLight point = new PointLight(color, position); //point.ConstantAttenuation =pointLight. ; // LinearAttenuation / QuadraticAttenuation //point.Range =pointLight.rayDepthLimit ; lights.Children.Add(point); continue; } catch { } try { MFnSpotLight spotLight = new MFnSpotLight(lightPath); MAngle InnerConeAngle = new MAngle(spotLight.coneAngle); MAngle OuterConeAngle = new MAngle(spotLight.penumbraAngle); SpotLight spot = new SpotLight(color, position, direction, OuterConeAngle.asDegrees, InnerConeAngle.asDegrees); spot.ConstantAttenuation = spotLight.dropOff; // LinearAttenuation / QuadraticAttenuation //spot.Range =spotLight.rayDepthLimit ; lights.Children.Add(spot); continue; } catch { } } }
/// <summary> /// Default space is transform /// </summary> /// <param name="mTransformationMatrix"></param> /// <returns></returns> public static float[] getScale(this MTransformationMatrix mTransformationMatrix) { double[] scale = new double[3]; mTransformationMatrix.getScale(scale, MSpace.Space.kTransform); return(Array.ConvertAll(scale, item => (float)item)); }
private List <BabylonAnimation> GetAnimationsFrameByFrame(MFnTransform mFnTransform) { int start = GetMinTime()[0]; int end = GetMaxTime()[0]; // Animations List <BabylonAnimation> animations = new List <BabylonAnimation>(); string[] babylonAnimationProperties = new string[] { "scaling", "rotationQuaternion", "position" }; Dictionary <string, List <BabylonAnimationKey> > keysPerProperty = new Dictionary <string, List <BabylonAnimationKey> >(); keysPerProperty.Add("scaling", new List <BabylonAnimationKey>()); keysPerProperty.Add("rotationQuaternion", new List <BabylonAnimationKey>()); keysPerProperty.Add("position", new List <BabylonAnimationKey>()); // get keys for (int currentFrame = start; currentFrame <= end; currentFrame++) { // get transformation matrix at this frame MDoubleArray mDoubleMatrix = new MDoubleArray(); MGlobal.executeCommand($"getAttr -t {currentFrame} {mFnTransform.fullPathName}.matrix", mDoubleMatrix); mDoubleMatrix.get(out float[] localMatrix); MMatrix matrix = new MMatrix(localMatrix); var transformationMatrix = new MTransformationMatrix(matrix); // Retreive TRS vectors from matrix var position = transformationMatrix.getTranslation(); var rotationQuaternion = transformationMatrix.getRotationQuaternion(); var scaling = transformationMatrix.getScale(); // Switch coordinate system at object level position[2] *= -1; rotationQuaternion[0] *= -1; rotationQuaternion[1] *= -1; // create animation key for each property for (int indexAnimation = 0; indexAnimation < babylonAnimationProperties.Length; indexAnimation++) { string babylonAnimationProperty = babylonAnimationProperties[indexAnimation]; BabylonAnimationKey key = new BabylonAnimationKey(); key.frame = currentFrame; switch (indexAnimation) { case 0: // scaling key.values = scaling.ToArray(); break; case 1: // rotationQuaternion key.values = rotationQuaternion.ToArray(); break; case 2: // position key.values = position.ToArray(); break; } keysPerProperty[babylonAnimationProperty].Add(key); } } // create animation for each property for (int indexAnimation = 0; indexAnimation < babylonAnimationProperties.Length; indexAnimation++) { string babylonAnimationProperty = babylonAnimationProperties[indexAnimation]; List <BabylonAnimationKey> keys = keysPerProperty[babylonAnimationProperty]; // Optimization OptimizeAnimations(keys, true); // Ensure animation has at least 2 frames if (keys.Count > 1) { var animationPresent = true; // Ensure animation has at least 2 non equal frames if (keys.Count == 2) { if (keys[0].values.IsEqualTo(keys[1].values)) { animationPresent = false; } } if (animationPresent) { // Create BabylonAnimation animations.Add(new BabylonAnimation() { dataType = indexAnimation == 1 ? (int)BabylonAnimation.DataType.Quaternion : (int)BabylonAnimation.DataType.Vector3, name = babylonAnimationProperty + " animation", framePerSecond = GetFPS(), loopBehavior = (int)BabylonAnimation.LoopBehavior.Cycle, property = babylonAnimationProperty, keys = keys.ToArray() }); } } } return(animations); }
/// <summary> /// /// </summary> /// <param name="mDagPath">DAG path to the transform above light</param> /// <param name="babylonScene"></param> /// <returns></returns> private BabylonNode ExportLight(MDagPath mDagPath, BabylonScene babylonScene) { RaiseMessage(mDagPath.partialPathName, 1); // Transform above light MFnTransform mFnTransform = new MFnTransform(mDagPath); // Light direct child of the transform MFnLight mFnLight = null; for (uint i = 0; i < mFnTransform.childCount; i++) { MObject childObject = mFnTransform.child(i); if (childObject.hasFn(MFn.Type.kLight)) { mFnLight = new MFnLight(childObject); } } if (mFnLight == null) { RaiseError("No light found has child of " + mDagPath.fullPathName); return(null); } RaiseMessage("mFnLight.fullPathName=" + mFnLight.fullPathName, 2); // --- prints --- #region prints // MFnLight RaiseVerbose("BabylonExporter.Light | mFnLight data", 2); RaiseVerbose("BabylonExporter.Light | mFnLight.color.toString()=" + mFnLight.color.toString(), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.intensity=" + mFnLight.intensity, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.useRayTraceShadows=" + mFnLight.useRayTraceShadows, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.shadowColor.toString()=" + mFnLight.shadowColor.toString(), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.centerOfIllumination=" + mFnLight.centerOfIllumination, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.numShadowSamples=" + mFnLight.numShadowSamples, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.rayDepthLimit=" + mFnLight.rayDepthLimit, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.opticalFXvisibility.toString()=" + mFnLight.opticalFXvisibility.toString(), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.lightIntensity.toString()=" + mFnLight.lightIntensity.toString(), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.instanceCount(true)=" + mFnLight.instanceCount(true), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.lightDirection(0).toString()=" + mFnLight.lightDirection(0).toString(), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.lightAmbient=" + mFnLight.lightAmbient, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.lightDiffuse=" + mFnLight.lightDiffuse, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.lightSpecular=" + mFnLight.lightSpecular, 3); switch (mFnLight.objectProperty.apiType) { case MFn.Type.kSpotLight: MFnSpotLight mFnSpotLight = new MFnSpotLight(mFnLight.objectProperty); // MFnNonAmbientLight RaiseVerbose("BabylonExporter.Light | mFnSpotLight.decayRate=" + mFnSpotLight.decayRate, 3); // dropdown enum value // MFnNonExtendedLight RaiseVerbose("BabylonExporter.Light | mFnSpotLight.shadowRadius=" + mFnSpotLight.shadowRadius, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.castSoftShadows=" + mFnSpotLight.castSoftShadows, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.useDepthMapShadows=" + mFnSpotLight.useDepthMapShadows, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.depthMapFilterSize()=" + mFnSpotLight.depthMapFilterSize(), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.depthMapResolution()=" + mFnSpotLight.depthMapResolution(), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.depthMapBias()=" + mFnSpotLight.depthMapBias(), 3); // MFnSpotLight RaiseVerbose("BabylonExporter.Light | mFnSpotLight.coneAngle=" + mFnSpotLight.coneAngle, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.penumbraAngle=" + mFnSpotLight.penumbraAngle, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.dropOff=" + mFnSpotLight.dropOff, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.barnDoors=" + mFnSpotLight.barnDoors, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.useDecayRegions=" + mFnSpotLight.useDecayRegions, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kFirst)=" + mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kFirst), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kFirst)=" + mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kFirst), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kSecond)=" + mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kSecond), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kSecond)=" + mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kSecond), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kThird)=" + mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kThird), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kThird)=" + mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kThird), 3); break; } #endregion if (IsLightExportable(mFnLight, mDagPath) == false) { return(null); } var babylonLight = new BabylonLight { name = mFnTransform.name, id = mFnTransform.uuid().asString() }; // Hierarchy ExportHierarchy(babylonLight, mFnTransform); // Position RaiseVerbose("BabylonExporter.Light | ExportTransform", 2); float[] position = null; GetTransform(mFnTransform, ref position); babylonLight.position = position; // Direction var vDir = new MVector(0, 0, -1); var transformationMatrix = new MTransformationMatrix(mFnTransform.transformationMatrix); vDir = vDir.multiply(transformationMatrix.asMatrixProperty); vDir.normalize(); babylonLight.direction = new[] { (float)vDir.x, (float)vDir.y, -(float)vDir.z }; // Common fields babylonLight.intensity = mFnLight.intensity; babylonLight.diffuse = mFnLight.lightDiffuse ? mFnLight.color.toArrayRGB() : new float[] { 0, 0, 0 }; babylonLight.specular = mFnLight.lightSpecular ? mFnLight.color.toArrayRGB() : new float[] { 0, 0, 0 }; // Type switch (mFnLight.objectProperty.apiType) { case MFn.Type.kPointLight: babylonLight.type = 0; break; case MFn.Type.kSpotLight: MFnSpotLight mFnSpotLight = new MFnSpotLight(mFnLight.objectProperty); babylonLight.type = 2; babylonLight.angle = (float)mFnSpotLight.coneAngle; babylonLight.exponent = 1; if (mFnSpotLight.useDecayRegions) { babylonLight.range = mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kThird); // Max distance } break; case MFn.Type.kDirectionalLight: babylonLight.type = 1; break; case MFn.Type.kAmbientLight: babylonLight.type = 3; babylonLight.groundColor = new float[] { 0, 0, 0 }; break; case MFn.Type.kAreaLight: case MFn.Type.kVolumeLight: RaiseError("Unsupported light type '" + mFnLight.objectProperty.apiType + "' for DAG path '" + mFnLight.fullPathName + "'. Light is ignored. Supported light types are: ambient, directional, point and spot."); return(null); default: RaiseWarning("Unknown light type '" + mFnLight.objectProperty.apiType + "' for DAG path '" + mFnLight.fullPathName + "'. Light is ignored."); return(null); } // TODO - Shadows // TODO - Exclusion // TODO - Animations babylonScene.LightsList.Add(babylonLight); return(babylonLight); }
/// <summary> /// /// </summary> /// <param name="mDagPath">DAG path to the transform above light</param> /// <param name="babylonScene"></param> /// <returns></returns> private BabylonNode ExportLight(MDagPath mDagPath, BabylonScene babylonScene) { RaiseMessage(mDagPath.partialPathName, 1); // Transform above light MFnTransform mFnTransform = new MFnTransform(mDagPath); // Light direct child of the transform MFnLight mFnLight = null; for (uint i = 0; i < mFnTransform.childCount; i++) { MObject childObject = mFnTransform.child(i); if (childObject.hasFn(MFn.Type.kLight)) { var _mFnLight = new MFnLight(childObject); if (!_mFnLight.isIntermediateObject) { mFnLight = _mFnLight; } } } if (mFnLight == null) { RaiseError("No light found has child of " + mDagPath.fullPathName); return(null); } RaiseMessage("mFnLight.fullPathName=" + mFnLight.fullPathName, 2); // --- prints --- #region prints // MFnLight RaiseVerbose("BabylonExporter.Light | mFnLight data", 2); RaiseVerbose("BabylonExporter.Light | mFnLight.color.toString()=" + mFnLight.color.toString(), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.intensity=" + mFnLight.intensity, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.useRayTraceShadows=" + mFnLight.useRayTraceShadows, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.shadowColor.toString()=" + mFnLight.shadowColor.toString(), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.centerOfIllumination=" + mFnLight.centerOfIllumination, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.numShadowSamples=" + mFnLight.numShadowSamples, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.rayDepthLimit=" + mFnLight.rayDepthLimit, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.opticalFXvisibility.toString()=" + mFnLight.opticalFXvisibility.toString(), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.lightIntensity.toString()=" + mFnLight.lightIntensity.toString(), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.instanceCount(true)=" + mFnLight.instanceCount(true), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.lightDirection(0).toString()=" + mFnLight.lightDirection(0).toString(), 3); RaiseVerbose("BabylonExporter.Light | mFnLight.lightAmbient=" + mFnLight.lightAmbient, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.lightDiffuse=" + mFnLight.lightDiffuse, 3); RaiseVerbose("BabylonExporter.Light | mFnLight.lightSpecular=" + mFnLight.lightSpecular, 3); switch (mFnLight.objectProperty.apiType) { case MFn.Type.kSpotLight: MFnSpotLight mFnSpotLight = new MFnSpotLight(mFnLight.objectProperty); // MFnNonAmbientLight RaiseVerbose("BabylonExporter.Light | mFnSpotLight.decayRate=" + mFnSpotLight.decayRate, 3); // dropdown enum value // MFnNonExtendedLight RaiseVerbose("BabylonExporter.Light | mFnSpotLight.shadowRadius=" + mFnSpotLight.shadowRadius, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.castSoftShadows=" + mFnSpotLight.castSoftShadows, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.useDepthMapShadows=" + mFnSpotLight.useDepthMapShadows, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.depthMapFilterSize()=" + mFnSpotLight.depthMapFilterSize(), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.depthMapResolution()=" + mFnSpotLight.depthMapResolution(), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.depthMapBias()=" + mFnSpotLight.depthMapBias(), 3); // MFnSpotLight RaiseVerbose("BabylonExporter.Light | mFnSpotLight.coneAngle=" + mFnSpotLight.coneAngle, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.penumbraAngle=" + mFnSpotLight.penumbraAngle, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.dropOff=" + mFnSpotLight.dropOff, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.barnDoors=" + mFnSpotLight.barnDoors, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.useDecayRegions=" + mFnSpotLight.useDecayRegions, 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kFirst)=" + mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kFirst), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kFirst)=" + mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kFirst), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kSecond)=" + mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kSecond), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kSecond)=" + mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kSecond), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kThird)=" + mFnSpotLight.startDistance(MFnSpotLight.MDecayRegion.kThird), 3); RaiseVerbose("BabylonExporter.Light | mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kThird)=" + mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kThird), 3); break; } Print(mFnTransform, 2, "Print ExportLight mFnTransform"); Print(mFnLight, 2, "Print ExportLight mFnLight"); #endregion if (IsLightExportable(mFnLight, mDagPath) == false) { return(null); } var babylonLight = new BabylonLight { name = mFnTransform.name, id = mFnTransform.uuid().asString() }; // Hierarchy ExportHierarchy(babylonLight, mFnTransform); // User custom attributes babylonLight.metadata = ExportCustomAttributeFromTransform(mFnTransform); // Position //RaiseVerbose("BabylonExporter.Light | ExportTransform", 2); float[] position = null; GetTransform(mFnTransform, ref position); babylonLight.position = position; // Direction var vDir = new MVector(0, 0, -1); var transformationMatrix = new MTransformationMatrix(mFnTransform.transformationMatrix); vDir = vDir.multiply(transformationMatrix.asMatrixProperty); vDir.normalize(); babylonLight.direction = new[] { (float)vDir.x, (float)vDir.y, -(float)vDir.z }; // Common fields babylonLight.intensity = mFnLight.intensity; babylonLight.diffuse = mFnLight.lightDiffuse ? mFnLight.color.toArrayRGB() : new float[] { 0, 0, 0 }; babylonLight.specular = mFnLight.lightSpecular ? mFnLight.color.toArrayRGB() : new float[] { 0, 0, 0 }; // Type switch (mFnLight.objectProperty.apiType) { case MFn.Type.kPointLight: babylonLight.type = 0; break; case MFn.Type.kSpotLight: MFnSpotLight mFnSpotLight = new MFnSpotLight(mFnLight.objectProperty); babylonLight.type = 2; babylonLight.angle = (float)mFnSpotLight.coneAngle; babylonLight.exponent = 1; if (mFnSpotLight.useDecayRegions) { babylonLight.range = mFnSpotLight.endDistance(MFnSpotLight.MDecayRegion.kThird); // Max distance } break; case MFn.Type.kDirectionalLight: babylonLight.type = 1; break; case MFn.Type.kAmbientLight: babylonLight.type = 3; babylonLight.groundColor = new float[] { 0, 0, 0 }; // No emit diffuse /specular checkbox for ambient light babylonLight.diffuse = mFnLight.color.toArrayRGB(); babylonLight.specular = babylonLight.diffuse; // Direction vDir = new MVector(0, 1, 0); transformationMatrix = new MTransformationMatrix(mFnTransform.transformationMatrix); vDir = vDir.multiply(transformationMatrix.asMatrixProperty); vDir.normalize(); babylonLight.direction = new[] { (float)vDir.x, (float)vDir.y, -(float)vDir.z }; break; case MFn.Type.kAreaLight: case MFn.Type.kVolumeLight: RaiseError("Unsupported light type '" + mFnLight.objectProperty.apiType + "' for DAG path '" + mFnLight.fullPathName + "'. Light is ignored. Supported light types are: ambient, directional, point and spot.", 1); return(null); default: RaiseWarning("Unknown light type '" + mFnLight.objectProperty.apiType + "' for DAG path '" + mFnLight.fullPathName + "'. Light is ignored.", 1); return(null); } // TODO - Shadows //Variable declaration MStringArray enlightedMeshesFullPathNames = new MStringArray(); List <string> includeMeshesIds = new List <string>(); MStringArray kTransMesh = new MStringArray(); String typeMesh = null; MStringArray UUIDMesh = new MStringArray(); //MEL Command that get the enlighted mesh for a given light MGlobal.executeCommand($@"lightlink -query -light {mFnTransform.fullPathName};", enlightedMeshesFullPathNames); //For each enlighted mesh foreach (String Mesh in enlightedMeshesFullPathNames) { //MEL Command use to get the type of each mesh typeMesh = MGlobal.executeCommandStringResult($@"nodeType -api {Mesh};"); //We are targeting the type kMesh and not kTransform (for parenting) if (typeMesh == "kMesh") { MGlobal.executeCommand($@"listRelatives -parent -fullPath {Mesh};", kTransMesh); //And finally the MEL Command for the uuid of each mesh MGlobal.executeCommand($@"ls -uuid {kTransMesh[0]};", UUIDMesh); includeMeshesIds.Add(UUIDMesh[0]); } } babylonLight.includedOnlyMeshesIds = includeMeshesIds.ToArray(); // Animations if (exportParameters.bakeAnimationFrames) { ExportNodeAnimationFrameByFrame(babylonLight, mFnTransform); } else { ExportNodeAnimation(babylonLight, mFnTransform); } babylonScene.LightsList.Add(babylonLight); return(babylonLight); }
public void ResetLights() { //<AmbientLight Color="White" /> //<DirectionalLight Color="White" Direction="-1,-1,-1" /> //<PointLight Color="White" ConstantAttenuation="1" LinearAttenuation="1" Position="0,0,0" QuadraticAttenuation="1" Range="0" /> //<SpotLight Color="White" ConstantAttenuation="1" Direction="-1,-1,-1" InnerConeAngle="10" LinearAttenuation="1" OuterConeAngle="10" Position="0,0,0" QuadraticAttenuation="1" Range="0" /> lights.Children.Clear () ; MItDag dagIterator =new MItDag (MItDag.TraversalType.kDepthFirst, MFn.Type.kLight) ; for ( ; !dagIterator.isDone ; dagIterator.next () ) { MDagPath lightPath =new MDagPath () ; dagIterator.getPath (lightPath) ; MFnLight light =new MFnLight (lightPath) ; bool isAmbient =light.lightAmbient ; MColor mcolor =light.color ; Color color =Color.FromScRgb (1.0f, mcolor.r, mcolor.g, mcolor.b) ; if ( isAmbient ) { AmbientLight ambient =new AmbientLight (color) ; lights.Children.Add (ambient) ; continue ; } MFloatVector lightDirection =light.lightDirection (0, MSpace.Space.kWorld) ; Vector3D direction =new Vector3D (lightDirection.x, lightDirection.y, lightDirection.z) ; bool isDiffuse =light.lightDiffuse ; try { MFnDirectionalLight dirLight =new MFnDirectionalLight (lightPath) ; DirectionalLight directional =new DirectionalLight (color, direction) ; lights.Children.Add (directional) ; continue ; } catch { } MObject transformNode =lightPath.transform ; MFnDagNode transform =new MFnDagNode (transformNode) ; MTransformationMatrix matrix =new MTransformationMatrix (transform.transformationMatrix) ; double [] threeDoubles =new double [3] ; int rOrder =0 ; //MTransformationMatrix.RotationOrder rOrder ; matrix.getRotation (threeDoubles, out rOrder, MSpace.Space.kWorld) ; matrix.getScale (threeDoubles, MSpace.Space.kWorld) ; MVector pos =matrix.getTranslation (MSpace.Space.kWorld) ; Point3D position =new Point3D (pos.x, pos.y, pos.z) ; try { MFnPointLight pointLight =new MFnPointLight (lightPath) ; PointLight point =new PointLight (color, position) ; //point.ConstantAttenuation =pointLight. ; // LinearAttenuation / QuadraticAttenuation //point.Range =pointLight.rayDepthLimit ; lights.Children.Add (point) ; continue ; } catch { } try { MFnSpotLight spotLight =new MFnSpotLight (lightPath) ; MAngle InnerConeAngle =new MAngle (spotLight.coneAngle) ; MAngle OuterConeAngle =new MAngle (spotLight.penumbraAngle) ; SpotLight spot =new SpotLight (color, position, direction, OuterConeAngle.asDegrees, InnerConeAngle.asDegrees) ; spot.ConstantAttenuation =spotLight.dropOff ; // LinearAttenuation / QuadraticAttenuation //spot.Range =spotLight.rayDepthLimit ; lights.Children.Add (spot) ; continue ; } catch { } } }