Example #1
0
 static bool BoneWeight_op_Inequality__BoneWeight__BoneWeight(JSVCall vc, int argc)
 {
     UnityEngine.BoneWeight arg0 = (UnityEngine.BoneWeight)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
     UnityEngine.BoneWeight arg1 = (UnityEngine.BoneWeight)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
     JSApi.setBooleanS((int)JSApi.SetType.Rval, (System.Boolean)(arg0 != arg1));
     return(true);
 }
Example #2
0
 static void Mesh_boneWeights(JSVCall vc)
 {
     if (vc.bGet)
     {
         UnityEngine.Mesh _this = (UnityEngine.Mesh)vc.csObj;
         var result             = _this.boneWeights;
         var arrRet             = result;
         for (int i = 0; arrRet != null && i < arrRet.Length; i++)
         {
             JSMgr.datax.setObject((int)JSApi.SetType.SaveAndTempTrace, arrRet[i]);
             JSApi.moveSaveID2Arr(i);
         }
         JSApi.setArrayS((int)JSApi.SetType.Rval, (arrRet != null ? arrRet.Length : 0), true);
     }
     else
     {
         UnityEngine.BoneWeight[] arg0 = JSDataExchangeMgr.GetJSArg <UnityEngine.BoneWeight[]>(() =>
         {
             int jsObjID = JSApi.getObject((int)JSApi.GetType.Arg);
             int length  = JSApi.getArrayLength(jsObjID);
             var ret     = new UnityEngine.BoneWeight[length];
             for (var i = 0; i < length; i++)
             {
                 JSApi.getElement(jsObjID, i);
                 ret[i] = (UnityEngine.BoneWeight)JSMgr.datax.getObject((int)JSApi.GetType.SaveAndRemove);
             }
             return(ret);
         });
         UnityEngine.Mesh _this = (UnityEngine.Mesh)vc.csObj;
         _this.boneWeights = arg0;
     }
 }
        public RopeData(UltimateRope rope)
        {
            m_rope                  = rope;
            m_hashFieldName2Value   = new Dictionary<string, object>();
            m_aLinkTransformInfo    = new TransformInfo[rope.TotalLinks];
            m_transformInfoSegments = new TransformInfo[rope.RopeNodes.Count];

            m_bSkin = rope.GetComponent<SkinnedMeshRenderer>() != null;

            if(m_bSkin)
            {
                SkinnedMeshRenderer skin = rope.GetComponent<SkinnedMeshRenderer>();

                Mesh skinMesh = skin.sharedMesh;

                int nVertices          = skin.sharedMesh.vertexCount;
                int nTrianglesRope     = skin.sharedMesh.GetTriangles(0).Length;
                int nTrianglesSections = skin.sharedMesh.GetTriangles(1).Length;

                m_av3SkinVertices         = new Vector3   [nVertices];
                m_av2SkinMapping          = new Vector2   [nVertices];
                m_av4SkinTangents         = skinMesh.tangents != null ? new Vector4[skinMesh.tangents.Length] : null;
		        m_aSkinBoneWeights        = new BoneWeight[nVertices];
		        m_anSkinTrianglesRope     = new int       [nTrianglesRope];
                m_anSkinTrianglesSections = new int       [nTrianglesSections];
                m_amtxSkinBindPoses       = new Matrix4x4 [skin.sharedMesh.bindposes.Length];

                MakeSkinDeepCopy(skinMesh.vertices, skinMesh.uv,      skinMesh.tangents, skinMesh.boneWeights, skinMesh.GetTriangles(0), skinMesh.GetTriangles(1),  skinMesh.bindposes,
                                 m_av3SkinVertices, m_av2SkinMapping, m_av4SkinTangents, m_aSkinBoneWeights,   m_anSkinTrianglesRope,    m_anSkinTrianglesSections, m_amtxSkinBindPoses);
            }
        }
 static public int constructor(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         UnityEngine.BoneWeight o;
         o = new UnityEngine.BoneWeight();
         pushValue(l, true);
         pushValue(l, o);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
        public static void MakeSkinDeepCopy(Vector3[] av3VerticesSource,  Vector2[] av2MappingSource,  BoneWeight[] aBoneWeightsSource,  int[] anTrianglesRopeSource,  int[] anTrianglesSectionsSource,  Matrix4x4[] aBindPosesSource, 
                                            Vector3[] av3VerticesDestiny, Vector2[] av2MappingDestiny, BoneWeight[] aBoneWeightsDestiny, int[] anTrianglesRopeDestiny, int[] anTrianglesSectionsDestiny, Matrix4x4[] aBindPosesDestiny)
        {
            int nVertices = av3VerticesSource.Length;

            for(int nVertex = 0; nVertex < nVertices; nVertex++)
            {
                av3VerticesDestiny [nVertex] = av3VerticesSource [nVertex];
                av2MappingDestiny  [nVertex] = av2MappingSource  [nVertex];
                aBoneWeightsDestiny[nVertex] = aBoneWeightsSource[nVertex];
            }

            for(int nIndex = 0; nIndex < anTrianglesRopeDestiny.Length; nIndex++)
            {
                anTrianglesRopeDestiny[nIndex] = anTrianglesRopeSource[nIndex];
            }

            for(int nIndex = 0; nIndex < anTrianglesSectionsDestiny.Length; nIndex++)
            {
                anTrianglesSectionsDestiny[nIndex] = anTrianglesSectionsSource[nIndex];
            }

            for(int nIndex = 0; nIndex < aBindPosesSource.Length; nIndex++)
            {
                aBindPosesDestiny[nIndex] = aBindPosesSource[nIndex];
            }
        }
 /*
 @Description: Setting the Indexes for the new bones
 */
 static BoneWeight recalculateIndexes(BoneWeight bw,Hashtable boneHash,Transform[] meshBones )
 {
     BoneWeight retBw = bw;
     retBw.boneIndex0 = (int)boneHash[meshBones[bw.boneIndex0].name];
     retBw.boneIndex1 = (int)boneHash[meshBones[bw.boneIndex1].name];
     retBw.boneIndex2 = (int)boneHash[meshBones[bw.boneIndex2].name];
     retBw.boneIndex3 = (int)boneHash[meshBones[bw.boneIndex3].name];
     return retBw;
 }
Example #7
0
        public void Build()
        {
            var halfwidth = 0.5f * width;
            var nSegments = bones.Length - 1;

            var vertices = new Vector3[bones.Length * 2];
            var weights = new BoneWeight[vertices.Length];
            var poses = new Matrix4x4[bones.Length];
            var counter = 0;
            for (var i = 0; i < bones.Length; i++) {
                var bone = bones[i];
                poses[i] = bone.worldToLocalMatrix * transform.localToWorldMatrix;
                var center = transform.InverseTransformPoint(bone.position);
                var right = halfwidth * bone.InverseTransformDirection(axis);
                vertices[counter] = center - right;
                vertices[counter + 1] = center + right;
                for (var j = 0; j < 2; j++) {
                    weights[counter + j].boneIndex0 = i;
                    weights[counter + j].weight0 = 1f;
                }
                counter += 2;
            }

            counter = 0;
            var triangles = new int[6 * nSegments];
            for (var i = 0; i < nSegments; i++) {
                var baseVertex = 2 * i;
                triangles[counter++] = baseVertex;
                triangles[counter++] = baseVertex + 1;
                triangles[counter++] = baseVertex + 3;
                triangles[counter++] = baseVertex;
                triangles[counter++] = baseVertex + 3;
                triangles[counter++] = baseVertex + 2;
            }

            var skin = GetComponent<SkinnedMeshRenderer>();
            if (skin == null)
                skin = gameObject.AddComponent<SkinnedMeshRenderer>();

            var bounds = new Bounds();
            foreach (var bone in bones)
                bounds.Encapsulate(bone.transform.localPosition);

            var mesh = skin.sharedMesh;
            if (mesh == null)
                mesh = skin.sharedMesh = new Mesh();
            mesh.vertices = vertices;
            mesh.triangles = triangles;
            mesh.boneWeights = weights;
            mesh.bindposes = poses;
            mesh.bounds = bounds;

            skin.bones = bones;
            skin.localBounds = bounds;
            skin.sharedMaterial = mat;
        }
    static public int set_weight2(IntPtr l)
    {
        UnityEngine.BoneWeight o = (UnityEngine.BoneWeight)checkSelf(l);
        float v;

        checkType(l, 2, out v);
        o.weight2 = v;
        setBack(l, o);
        return(0);
    }
    static public int set_boneIndex3(IntPtr l)
    {
        UnityEngine.BoneWeight o = (UnityEngine.BoneWeight)checkSelf(l);
        int v;

        checkType(l, 2, out v);
        o.boneIndex3 = v;
        setBack(l, o);
        return(0);
    }
 public SBoneWeight(BoneWeight source)
 {
     this.boneIndex0 = source.boneIndex0;
     this.boneIndex1 = source.boneIndex1;
     this.boneIndex2 = source.boneIndex2;
     this.boneIndex3 = source.boneIndex3;
     this.weight0 = source.weight0;
     this.weight1 = source.weight1;
     this.weight2 = source.weight2;
     this.weight3 = source.weight3;
 }
Example #11
0
 public void Serialize(ref UnityEngine.BoneWeight bw)
 {
     if (m_writing)
     {
         SerializeOut_boneweight(bw);
     }
     else
     {
         bw = SerializeIn_boneweight();
     }
 }
Example #12
0
 public void SerializeOut_boneweight(UnityEngine.BoneWeight bw)
 {
     SerializeOut_int32(bw.boneIndex0);
     SerializeOut_int32(bw.boneIndex1);
     SerializeOut_int32(bw.boneIndex2);
     SerializeOut_int32(bw.boneIndex3);
     SerializeOut_float(bw.weight0);
     SerializeOut_float(bw.weight1);
     SerializeOut_float(bw.weight2);
     SerializeOut_float(bw.weight3);
 }
 public static int GetBone(BoneWeight bw, int i)
 {
     if (i == 0)
         return bw.boneIndex0;
     else if (i == 1)
         return bw.boneIndex1;
     else if (i == 2)
         return bw.boneIndex2;
     else if (i == 3)
         return bw.boneIndex3;
     throw new Exception("44444");
 }
Example #14
0
 static public int constructor(IntPtr l)
 {
     try {
         UnityEngine.BoneWeight o;
         o = new UnityEngine.BoneWeight();
         pushValue(l, o);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Example #15
0
 /// <summary>
 /// Write the specified value using the writer.
 /// </summary>
 /// <param name="value">Value.</param>
 /// <param name="writer">Writer.</param>
 public override void Write(object value, ISaveGameWriter writer)
 {
     UnityEngine.BoneWeight boneWeight = (UnityEngine.BoneWeight)value;
     writer.WriteProperty("weight0", boneWeight.weight0);
     writer.WriteProperty("weight1", boneWeight.weight1);
     writer.WriteProperty("weight2", boneWeight.weight2);
     writer.WriteProperty("weight3", boneWeight.weight3);
     writer.WriteProperty("boneIndex0", boneWeight.boneIndex0);
     writer.WriteProperty("boneIndex1", boneWeight.boneIndex1);
     writer.WriteProperty("boneIndex2", boneWeight.boneIndex2);
     writer.WriteProperty("boneIndex3", boneWeight.boneIndex3);
 }
Example #16
0
    static bool BoneWeight_GetHashCode(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 0)
        {
            UnityEngine.BoneWeight argThis = (UnityEngine.BoneWeight)vc.csObj;                JSApi.setInt32((int)JSApi.SetType.Rval, (System.Int32)(argThis.GetHashCode()));
            JSMgr.changeJSObj(vc.jsObjID, argThis);
        }

        return(true);
    }
	static public int constructor(IntPtr l) {
		try {
			UnityEngine.BoneWeight o;
			o=new UnityEngine.BoneWeight();
			pushValue(l,true);
			pushValue(l,o);
			return 2;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
Example #18
0
	public Uni2DBoneWeight(BoneWeight a_oBoneWeight)
	{
		boneIndex0 = a_oBoneWeight.boneIndex0;
		boneIndex1 = a_oBoneWeight.boneIndex1;
		boneIndex2 = a_oBoneWeight.boneIndex2;
		boneIndex3 = a_oBoneWeight.boneIndex3;
		
		weight0 = a_oBoneWeight.weight0;
		weight1 = a_oBoneWeight.weight1;
		weight2 = a_oBoneWeight.weight2;
		weight3 = a_oBoneWeight.weight3;
	}
Example #19
0
// methods

    static bool BoneWeight_Equals__Object(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 1)
        {
            System.Object          arg0    = (System.Object)JSMgr.datax.getWhatever((int)JSApi.GetType.Arg);
            UnityEngine.BoneWeight argThis = (UnityEngine.BoneWeight)vc.csObj;                JSApi.setBooleanS((int)JSApi.SetType.Rval, (System.Boolean)(argThis.Equals(arg0)));
            JSMgr.changeJSObj(vc.jsObjID, argThis);
        }

        return(true);
    }
Example #20
0
    public static BoneWeight Clone(this BoneWeight bw) {
        BoneWeight ret = new BoneWeight();
        ret.boneIndex0 = bw.boneIndex0;
        ret.boneIndex1 = bw.boneIndex1;
        ret.boneIndex2 = bw.boneIndex2;
        ret.boneIndex3 = bw.boneIndex3;
        ret.weight0 = bw.weight0;
        ret.weight1 = bw.weight1;
        ret.weight2 = bw.weight2;
        ret.weight3 = bw.weight3;

        return ret;
    }
			BoneWeight[] EntryBoneWeights(PMD.PMDFormat format)
			{
				int vcount = (int)format.vertex_list.vert_count;
				BoneWeight[] weights = new BoneWeight[vcount];
				for (int i = 0; i < vcount; i++)
				{
					weights[i].boneIndex0 = (int)format.vertex_list.vertex[i].bone_num[0];
					weights[i].boneIndex1 = (int)format.vertex_list.vertex[i].bone_num[1];
					weights[i].weight0 = format.vertex_list.vertex[i].bone_weight;
					weights[i].weight1 = 100 - format.vertex_list.vertex[i].bone_weight;
				}
				return weights;
			}
 public static void SetBone(ref BoneWeight bw, int i, int id)
 {
     if (i == 0)
         bw.boneIndex0 = id;
     else if (i == 1)
         bw.boneIndex1 = id;
     else if (i == 2)
         bw.boneIndex2 = id;
     else if (i == 3)
         bw.boneIndex3 = id;
     else
         throw new Exception("4444");
 }
 public static int constructor(IntPtr l)
 {
     try {
         UnityEngine.BoneWeight o;
         o=new UnityEngine.BoneWeight();
         pushValue(l,o);
         return 1;
     }
     catch(Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return 0;
     }
 }
 static public int constructor(IntPtr l)
 {
     try {
         UnityEngine.BoneWeight o;
         o = new UnityEngine.BoneWeight();
         pushValue(l, o);
         return(1);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Example #25
0
    public UnityEngine.BoneWeight SerializeIn_boneweight()
    {
        var bw = new UnityEngine.BoneWeight();

        bw.boneIndex0 = SerializeIn_int32();
        bw.boneIndex1 = SerializeIn_int32();
        bw.boneIndex2 = SerializeIn_int32();
        bw.boneIndex3 = SerializeIn_int32();
        bw.weight0    = SerializeIn_float();
        bw.weight1    = SerializeIn_float();
        bw.weight2    = SerializeIn_float();
        bw.weight3    = SerializeIn_float();
        return(bw);
    }
Example #26
0
 void Start()
 {
     gameObject.AddComponent<Animation>();
     gameObject.AddComponent<SkinnedMeshRenderer>();
     SkinnedMeshRenderer renderer = GetComponent<SkinnedMeshRenderer>();
     Mesh mesh = new Mesh();
     mesh.vertices = new Vector3[] { new Vector3(-1, 0, 0), new Vector3(1, 0, 0), new Vector3(-1, 5, 0), new Vector3(1, 5, 0) };
     mesh.uv = new Vector2[] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1), new Vector2(1, 1) };
     mesh.triangles = new int[] { 0, 1, 2, 1, 3, 2 };
     mesh.RecalculateNormals();
     renderer.material = new Material(Shader.Find(" Diffuse"));
     BoneWeight[] weights = new BoneWeight[4];
     weights[0].boneIndex0 = 0;
     weights[0].weight0 = 1;
     weights[1].boneIndex0 = 0;
     weights[1].weight0 = 1;
     weights[2].boneIndex0 = 1;
     weights[2].weight0 = 1;
     weights[3].boneIndex0 = 1;
     weights[3].weight0 = 1;
     mesh.boneWeights = weights;
     Transform[] bones = new Transform[2];
     Matrix4x4[] bindPoses = new Matrix4x4[2];
     bones[0] = new GameObject("Lower").transform;
     bones[0].parent = transform;
     bones[0].localRotation = Quaternion.identity;
     bone0_ratation = bones[0].localRotation;
     bones[0].localPosition = Vector3.zero;
     bindPoses[0] = bones[0].worldToLocalMatrix * transform.localToWorldMatrix;
     bones[1] = new GameObject("Upper").transform;
     bones[1].parent = transform;
     bones[1].localRotation = new Quaternion(0, 0, 0.717f, 0.717f);
     bone1_ratation = bones[1].localRotation;
     bones[1].localPosition = new Vector3(0, 5, 0);
     bindPoses[1] = bones[1].worldToLocalMatrix * transform.localToWorldMatrix;
     mesh.bindposes = bindPoses;
     renderer.bones = bones;
     renderer.sharedMesh = mesh;
     AnimationCurve curve = new AnimationCurve();
     curve.keys = new Keyframe[] { new Keyframe(0, 0), new Keyframe(1, 3), new Keyframe(2, 0.0F) };
     AnimationClip clip = new AnimationClip();
     clip.SetCurve("Lower", typeof(Transform), "m_LocalPosition.y", curve);
     AnimationCurve curve1 = new AnimationCurve();
     curve1.keys = new Keyframe[] { new Keyframe(0, 5), new Keyframe(1, 3), new Keyframe(2, 5F) };
     clip.SetCurve("Upper", typeof(Transform), "m_LocalPosition.y", curve1);
     clip.wrapMode = WrapMode.Loop;
     animation.AddClip(clip, "test");
     animation.Play("test");
 }
Example #27
0
    public static void ImportCharMesh(string meshPath, string zmsPath)
    {
        if (!File.Exists(zmsPath)) {
            Debug.LogWarning("Failed to find referenced ZMS.");
            return;
        }

        var mesh = new Mesh();

        var zms = new Revise.Files.ZMS.ModelFile();
        zms.Load(zmsPath);

        var verts = new Vector3[zms.Vertices.Count];
        var uvs = new Vector2[zms.Vertices.Count];
        var bones = new BoneWeight[zms.Vertices.Count];

        for (int k = 0; k < zms.Vertices.Count; ++k) {
            var v = zms.Vertices[k];
            v.TextureCoordinates[0].y = 1 - v.TextureCoordinates[0].y;

            verts[k] = rtuPosition(v.Position);
            uvs[k] = v.TextureCoordinates[0];

            bones[k] = new BoneWeight();
            bones[k].boneIndex0 = zms.BoneTable[v.BoneIndices.X];
            bones[k].boneIndex1 = zms.BoneTable[v.BoneIndices.Y];
            bones[k].boneIndex2 = zms.BoneTable[v.BoneIndices.Z];
            bones[k].boneIndex3 = zms.BoneTable[v.BoneIndices.W];
            bones[k].weight0 = v.BoneWeights.x;
            bones[k].weight1 = v.BoneWeights.y;
            bones[k].weight2 = v.BoneWeights.z;
            bones[k].weight3 = v.BoneWeights.w;
        }
        mesh.vertices = verts;
        mesh.uv = uvs;
        mesh.boneWeights = bones;

        int[] indices = new int[zms.Indices.Count * 3];
        for (int k = 0; k < zms.Indices.Count; ++k) {
            indices[k * 3 + 0] = zms.Indices[k].X;
            indices[k * 3 + 2] = zms.Indices[k].Y;
            indices[k * 3 + 1] = zms.Indices[k].Z;
        }
        mesh.triangles = indices;

        mesh.RecalculateNormals();

        AssetDatabase.CreateAsset(mesh, meshPath);
    }
Example #28
0
        BoneWeight CreateBoneWeightFromUnityBoneWeight(UnityEngine.BoneWeight unityBoneWeight)
        {
            BoneWeight boneWeight = new BoneWeight();

            boneWeight.boneIndex0 = unityBoneWeight.boneIndex0;
            boneWeight.boneIndex1 = unityBoneWeight.boneIndex1;
            boneWeight.boneIndex2 = unityBoneWeight.boneIndex2;
            boneWeight.boneIndex3 = unityBoneWeight.boneIndex3;
            boneWeight.weight0    = unityBoneWeight.weight0;
            boneWeight.weight1    = unityBoneWeight.weight1;
            boneWeight.weight2    = unityBoneWeight.weight2;
            boneWeight.weight3    = unityBoneWeight.weight3;

            return(boneWeight);
        }
Example #29
0
 static void BoneWeight_weight3(JSVCall vc)
 {
     if (vc.bGet)
     {
         UnityEngine.BoneWeight _this = (UnityEngine.BoneWeight)vc.csObj;
         var result = _this.weight3;
         JSApi.setSingle((int)JSApi.SetType.Rval, (System.Single)(result));
     }
     else
     {
         System.Single          arg0  = (System.Single)JSApi.getSingle((int)JSApi.GetType.Arg);
         UnityEngine.BoneWeight _this = (UnityEngine.BoneWeight)vc.csObj;
         _this.weight3 = arg0;
         JSMgr.changeJSObj(vc.jsObjID, _this);
     }
 }
Example #30
0
 static void BoneWeight_boneIndex3(JSVCall vc)
 {
     if (vc.bGet)
     {
         UnityEngine.BoneWeight _this = (UnityEngine.BoneWeight)vc.csObj;
         var result = _this.boneIndex3;
         JSApi.setInt32((int)JSApi.SetType.Rval, (System.Int32)(result));
     }
     else
     {
         System.Int32           arg0  = (System.Int32)JSApi.getInt32((int)JSApi.GetType.Arg);
         UnityEngine.BoneWeight _this = (UnityEngine.BoneWeight)vc.csObj;
         _this.boneIndex3 = arg0;
         JSMgr.changeJSObj(vc.jsObjID, _this);
     }
 }
Example #31
0
        public static UnityEngine.BoneWeight[] CalculateBbw(Vector2[] vertices, IndexedEdge[] edges,
                                                            Vector2[] controlPoints, IndexedEdge[] controlPointEdges, int[] pins)
        {
            Vector2[] sampledEdges = SampleEdges(controlPoints, controlPointEdges, 10);

            List <Vector2> verticesAndSamplesList = new List <Vector2>(vertices.Length + sampledEdges.Length);

            verticesAndSamplesList.AddRange(vertices);
            verticesAndSamplesList.AddRange(controlPoints);
            verticesAndSamplesList.AddRange(sampledEdges);

            List <IndexedEdge> edgesList   = new List <IndexedEdge>(edges);
            List <Hole>        holes       = new List <Hole>();
            List <int>         indicesList = new List <int>();

            SpriteMeshUtils.Tessellate(verticesAndSamplesList, edgesList, holes, indicesList, 4f);

            Vector2[] verticesAndSamples = verticesAndSamplesList.ToArray();
            int[]     indices            = indicesList.ToArray();

            UnityEngine.BoneWeight[] weights = new UnityEngine.BoneWeight[vertices.Length];

            GCHandle verticesHandle      = GCHandle.Alloc(verticesAndSamples, GCHandleType.Pinned);
            GCHandle indicesHandle       = GCHandle.Alloc(indices, GCHandleType.Pinned);
            GCHandle controlPointsHandle = GCHandle.Alloc(controlPoints, GCHandleType.Pinned);
            GCHandle boneEdgesHandle     = GCHandle.Alloc(controlPointEdges, GCHandleType.Pinned);
            GCHandle pinsHandle          = GCHandle.Alloc(pins, GCHandleType.Pinned);
            GCHandle weightsHandle       = GCHandle.Alloc(weights, GCHandleType.Pinned);

            Bbw(-1,
                verticesHandle.AddrOfPinnedObject(), verticesAndSamples.Length, vertices.Length,
                indicesHandle.AddrOfPinnedObject(), indices.Length,
                controlPointsHandle.AddrOfPinnedObject(), controlPoints.Length,
                boneEdgesHandle.AddrOfPinnedObject(), controlPointEdges.Length,
                pinsHandle.AddrOfPinnedObject(), pins.Length,
                weightsHandle.AddrOfPinnedObject());

            verticesHandle.Free();
            indicesHandle.Free();
            controlPointsHandle.Free();
            boneEdgesHandle.Free();
            pinsHandle.Free();
            weightsHandle.Free();

            return(weights);
        }
Example #32
0
	public BoneWeight[] GetBoneWeightStructs()
	{
		if(boneWeights == null)
		{
			return null;
		}
		
		int iBoneWeightCount = boneWeights.Length;
		
		BoneWeight[] oBoneWeights = new BoneWeight[iBoneWeightCount];
		for(int i = 0; i < iBoneWeightCount; ++i)
		{
			oBoneWeights[i] = boneWeights[i];
		}
		
		return oBoneWeights;
	}
    public BoneWeight[] GetUnityBoneWeights() {
        List<BoneWeight> bweights = new List<BoneWeight>();

        var groups = weights.GroupBy(bw => bw.vertex);

        foreach (var g in groups) {
            var wv = g.Where(w => w.weight > 0).ToList();

            float max = wv.Sum(bw => bw.weight);

            if (max > 1.0f) {
                wv.ForEach(bw => bw.weight = bw.weight / max);
            }

            int i = 0;

            BoneWeight bweight = new BoneWeight(); 

            foreach (Bone2DWeight w in wv) {
                switch (i) {
                    case 0:
                        bweight.boneIndex0 = w.index;
                        bweight.weight0 = w.weight;
                        break;
                    case 1:
                        bweight.boneIndex1 = w.index;
                        bweight.weight1 = w.weight;
                        break;
                    case 2:
                        bweight.boneIndex2 = w.index;
                        bweight.weight2 = w.weight;
                        break;
                    case 3:
                        bweight.boneIndex3 = w.index;
                        bweight.weight3 = w.weight;
                        break;
                }
                i++;
            }

            bweights.Add(bweight);
        }

        return bweights.ToArray();
    }
Example #34
0
        /// <summary>
        /// Read the data using the reader.
        /// </summary>
        /// <param name="reader">Reader.</param>
        public override object Read(ISaveGameReader reader)
        {
            UnityEngine.BoneWeight boneWeight = new UnityEngine.BoneWeight();
            foreach (string property in reader.Properties)
            {
                switch (property)
                {
                case "weight0":
                    boneWeight.weight0 = reader.ReadProperty <System.Single> ();
                    break;

                case "weight1":
                    boneWeight.weight1 = reader.ReadProperty <System.Single> ();
                    break;

                case "weight2":
                    boneWeight.weight2 = reader.ReadProperty <System.Single> ();
                    break;

                case "weight3":
                    boneWeight.weight3 = reader.ReadProperty <System.Single> ();
                    break;

                case "boneIndex0":
                    boneWeight.boneIndex0 = reader.ReadProperty <System.Int32> ();
                    break;

                case "boneIndex1":
                    boneWeight.boneIndex1 = reader.ReadProperty <System.Int32> ();
                    break;

                case "boneIndex2":
                    boneWeight.boneIndex2 = reader.ReadProperty <System.Int32> ();
                    break;

                case "boneIndex3":
                    boneWeight.boneIndex3 = reader.ReadProperty <System.Int32> ();
                    break;
                }
            }
            return(boneWeight);
        }
Example #35
0
 public static void FillMesh(Mesh mesh, Vector3[] vs, Vector3[] ns, Vector2[] uv1s, Vector2[] uv2s, Vector2[] uv3s, Vector2[] uv4s, Color32[] colors32, int[] ts, BoneWeight[] bws, Matrix4x4[] bindposes, int[] subMeshOffsets, bool recalcNormals)
 {
     mesh.vertices = vs;
     if(ns != null && ns.Length > 0) mesh.normals = ns;
     if(uv1s != null && uv1s.Length > 0) mesh.uv = uv1s;
     if(uv2s != null && uv2s.Length > 0) mesh.uv2 = uv2s;
     #if UNITY_4_3
     #elif UNITY_4_4
     #elif UNITY_4_5
     #elif UNITY_4_6
     #else
         if(uv3s != null && uv2s.Length > 0) mesh.uv3 = uv3s;
         if(uv4s != null && uv2s.Length > 0) mesh.uv4 = uv4s;
     #endif
     if(colors32 != null && colors32.Length > 0) mesh.colors32 = colors32;
     if(bws != null && bws.Length > 0) mesh.boneWeights = bws;
     if(bindposes != null && bindposes.Length > 0) mesh.bindposes = bindposes;
     if(subMeshOffsets.Length == 1) {
         mesh.triangles = ts;
     } else {
         mesh.subMeshCount = subMeshOffsets.Length;
         for(int s=0;s<subMeshOffsets.Length;s++) {
             subMeshOffsets[s] = Mathf.Max(0,subMeshOffsets[s]);
             int end = s+1 < subMeshOffsets.Length ? subMeshOffsets[s+1] : ts.Length;
             if(end - subMeshOffsets[s] > 0) {
                 int[] subTs = new int[end - subMeshOffsets[s]];
                 Array.Copy(ts, subMeshOffsets[s], subTs, 0, end - subMeshOffsets[s]);
                 mesh.SetTriangles(subTs, s);
             } else {
                 mesh.SetTriangles((int[])null, s);
             }
         }
     }
     if(recalcNormals || mesh.normals == null || mesh.normals.Length <= 0) mesh.RecalculateNormals();
     mesh.RecalculateTangents();
 }
        public static Vector3 Unskin(Vector3 skinedPosition,
                                     Matrix4x4 localToWorld,
                                     UnityEngine.BoneWeight boneWeight,
                                     Matrix4x4[] bindposes,
                                     Transform[] bones)
        {
            Matrix4x4 m0 = bones[boneWeight.boneIndex0].localToWorldMatrix * bindposes[boneWeight.boneIndex0];
            Matrix4x4 m1 = bones[boneWeight.boneIndex1].localToWorldMatrix * bindposes[boneWeight.boneIndex1];
            Matrix4x4 m2 = bones[boneWeight.boneIndex2].localToWorldMatrix * bindposes[boneWeight.boneIndex2];
            Matrix4x4 m3 = bones[boneWeight.boneIndex3].localToWorldMatrix * bindposes[boneWeight.boneIndex3];

            Matrix4x4 m = Matrix4x4.identity;

            for (int n = 0; n < 16; n++)
            {
                m0[n] *= boneWeight.weight0;
                m1[n] *= boneWeight.weight1;
                m2[n] *= boneWeight.weight2;
                m3[n] *= boneWeight.weight3;
                m[n]   = m0[n] + m1[n] + m2[n] + m3[n];
            }

            return(localToWorld.MultiplyPoint3x4(m.inverse.MultiplyPoint3x4(skinedPosition)));
        }
Example #37
0
        public void CalculateAutomaticWeights(List <Node> targetNodes)
        {
            float pixelsPerUnit = SpriteMeshUtils.GetSpritePixelsPerUnit(spriteMesh.sprite);

            if (nodes.Count <= 0)
            {
                Debug.Log("Cannot calculate automatic weights from a SpriteMesh with no vertices.");
                return;
            }

            if (bindPoses.Count <= 0)
            {
                Debug.Log("Cannot calculate automatic weights. Specify bones to the SpriteMeshInstance.");
                return;
            }

            if (!spriteMesh)
            {
                return;
            }

            List <Vector2>     controlPoints     = new List <Vector2>();
            List <IndexedEdge> controlPointEdges = new List <IndexedEdge>();
            List <int>         pins = new List <int>();

            foreach (BindInfo bindInfo in bindPoses)
            {
                Vector2 tip  = SpriteMeshUtils.VertexToTexCoord(spriteMesh, pivotPoint, bindInfo.position, pixelsPerUnit);
                Vector2 tail = SpriteMeshUtils.VertexToTexCoord(spriteMesh, pivotPoint, bindInfo.endPoint, pixelsPerUnit);

                if (bindInfo.boneLength <= 0f)
                {
                    int index = controlPoints.Count;
                    controlPoints.Add(tip);
                    pins.Add(index);

                    continue;
                }

                int index1 = -1;

                if (!ContainsVector(tip, controlPoints, 0.01f, out index1))
                {
                    index1 = controlPoints.Count;
                    controlPoints.Add(tip);
                }

                int index2 = -1;

                if (!ContainsVector(tail, controlPoints, 0.01f, out index2))
                {
                    index2 = controlPoints.Count;
                    controlPoints.Add(tail);
                }

                IndexedEdge edge = new IndexedEdge(index1, index2);
                controlPointEdges.Add(edge);
            }

            UnityEngine.BoneWeight[] boneWeights = BbwPlugin.CalculateBbw(m_TexVertices.ToArray(), indexedEdges.ToArray(), controlPoints.ToArray(), controlPointEdges.ToArray(), pins.ToArray());

            foreach (Node node in targetNodes)
            {
                UnityEngine.BoneWeight unityBoneWeight = boneWeights[node.index];

                SetBoneWeight(node, CreateBoneWeightFromUnityBoneWeight(unityBoneWeight));
            }

            isDirty = true;
        }
Example #38
0
	static Mesh ExtractSkinnedMeshAttachment (string name, SkinnedMeshAttachment attachment, int slotIndex, SkeletonData skeletonData, List<Transform> boneList, Mesh mesh = null) {

		Skeleton skeleton = new Skeleton(skeletonData);
		skeleton.UpdateWorldTransform();

		float[] floatVerts = new float[attachment.UVs.Length];
		attachment.ComputeWorldVertices(skeleton.Slots[slotIndex], floatVerts);

		Vector2[] uvs = ExtractUV(attachment.UVs);
		Vector3[] verts = ExtractVerts(floatVerts);

		int[] triangles = attachment.Triangles;
		Color color = new Color(attachment.R, attachment.G, attachment.B, attachment.A);

		if (mesh == null)
			mesh = new Mesh();

		mesh.triangles = new int[0];

		mesh.vertices = verts;
		mesh.uv = uvs;
		mesh.triangles = triangles;
		Color[] colors = new Color[verts.Length];
		for (int i = 0; i < verts.Length; i++)
			colors[i] = color;

		mesh.colors = colors;
		mesh.name = name;
		mesh.RecalculateNormals();
		mesh.RecalculateBounds();

		//Handle weights and binding
		Dictionary<int, BoneWeightContainer> weightTable = new Dictionary<int, BoneWeightContainer>();
		System.Text.StringBuilder warningBuilder = new System.Text.StringBuilder();

		int[] bones = attachment.Bones;
		float[] weights = attachment.Weights;
		for (int w = 0, v = 0, b = 0, n = bones.Length; v < n; w += 2) {

			int nn = bones[v++] + v;
			for (; v < nn; v++, b += 3) {
				Transform boneTransform = boneList[bones[v]];
				int vIndex = w / 2;

				float weight = weights[b + 2];

				BoneWeightContainer container;
				if (weightTable.ContainsKey(vIndex))
					container = weightTable[vIndex];
				else {
					container = new BoneWeightContainer();
					weightTable.Add(vIndex, container);
				}


				container.Add(boneTransform, weight);
			}
		}

		BoneWeight[] boneWeights = new BoneWeight[weightTable.Count];

		for (int i = 0; i < weightTable.Count; i++) {
			BoneWeight bw = new BoneWeight();
			var container = weightTable[i];

			var pairs = container.pairs.OrderByDescending(pair => pair.weight).ToList();

			for (int b = 0; b < pairs.Count; b++) {
				if (b > 3) {
					if (warningBuilder.Length == 0)
						warningBuilder.Insert(0, "[SkinnedMeshAttachment " + name + "]\r\nUnity only supports 4 weight influences per vertex!  The 4 strongest influences will be used.\r\n");

					warningBuilder.AppendFormat("{0} ignored on vertex {1}!\r\n", pairs[b].bone.name, i);
					continue;
				}

				int boneIndex = boneList.IndexOf(pairs[b].bone);
				float weight = pairs[b].weight;

				switch (b) {
					case 0:
						bw.boneIndex0 = boneIndex;
						bw.weight0 = weight;
						break;
					case 1:
						bw.boneIndex1 = boneIndex;
						bw.weight1 = weight;
						break;
					case 2:
						bw.boneIndex2 = boneIndex;
						bw.weight2 = weight;
						break;
					case 3:
						bw.boneIndex3 = boneIndex;
						bw.weight3 = weight;
						break;
				}
			}

			boneWeights[i] = bw;
		}

		Matrix4x4[] bindPoses = new Matrix4x4[boneList.Count];
		for (int i = 0; i < boneList.Count; i++) {
			bindPoses[i] = boneList[i].worldToLocalMatrix;
		}

		mesh.boneWeights = boneWeights;
		mesh.bindposes = bindPoses;

		string warningString = warningBuilder.ToString();
		if (warningString.Length > 0)
			Debug.LogWarning(warningString);


		return mesh;
	}
 static public int get_weight2(IntPtr l)
 {
     UnityEngine.BoneWeight o = (UnityEngine.BoneWeight)checkSelf(l);
     pushValue(l, o.weight2);
     return(1);
 }
Example #40
0
    public static float GetNeighbourWeight(Vector3[] vertices ,BoneWeight[] boneWeights, List<int> indexes, int index, int boneIndex)
    {
        float distance = 1000000f;
        int closestIndex = indexes[0];
        for (int i = 0; i < indexes.Count; i++)
        {
            float checkDistance = (vertices[indexes[i]] - vertices[index]).magnitude;
            if(checkDistance < distance)
            {
                closestIndex = indexes[i];
                distance =checkDistance;
            }

        }
        if(boneWeights[closestIndex].boneIndex0 == boneIndex)
            return boneWeights[closestIndex].weight0;
        if(boneWeights[closestIndex].boneIndex1 == boneIndex)
            return boneWeights[closestIndex].weight1;
        if(boneWeights[closestIndex].boneIndex2 == boneIndex)
            return boneWeights[closestIndex].weight2;
        if(boneWeights[closestIndex].boneIndex3 == boneIndex)
            return boneWeights[closestIndex].weight3;
        return 0;
    }
Example #41
0
	void OnWizardCreate() 
	{
		if(sknFile == null) {
			Debug.LogError("null skn file");
			return;
		}

		//https://code.google.com/p/lolblender/wiki/fileFormats
		try {

			Mesh mesh = null;

			string sknPath = AssetDatabase.GetAssetPath(sknFile);
			using(FileStream fs = File.OpenRead (sknPath)) {
				byte[] headerBlock = new byte[8];
				fs.Read(headerBlock,0,8);
				int magicNumber = BitConverter.ToInt32(headerBlock,0);
				short numObjects = BitConverter.ToInt16(headerBlock,4);
				short matHeader = BitConverter.ToInt16(headerBlock,6);
				//Debug.Log("magicNumber : " + magicNumber + "\nnumObjects : " + numObjects + "\nmatHeader : " + matHeader);

				if(matHeader == 1) {
					byte[] numMaterialBlock = new byte[4];
					fs.Read(numMaterialBlock,0,4);
					int numMaterials = BitConverter.ToInt32 (numMaterialBlock,0);
					//Debug.Log ("numMaterial : " + numMaterials);

					byte[] materialBlock = new byte[80];
					for(int i=0;i<numMaterials;i++) {
						fs.Read(materialBlock,0,80);
						//Debug.Log (materialBlock);
						string materialName = System.Text.Encoding.ASCII.GetString (materialBlock,0,64).TrimEnd('\0');
						//Debug.Log (name.Length);
						int startVertex = BitConverter.ToInt32 (materialBlock,64);
						int numMaterialVertices = BitConverter.ToInt32 (materialBlock,68);
						int startIndex = BitConverter.ToInt32 (materialBlock,72);
						int numMaterialIndices = BitConverter.ToInt32(materialBlock,76);

						//Debug.Log ("material : " +materialName + "\nstartVertex : " + startVertex + 
						//           "\nnumVertices : " + numMaterialVertices + "\nstartIndex : " + startIndex + 
						//           "\nnumIndices : " + numMaterialIndices);
					}
				}

				byte[] countBlock = new byte[8];
				fs.Read (countBlock,0,8);
				int numIndices = BitConverter.ToInt32 (countBlock,0);
				int numVertices = BitConverter.ToInt32 (countBlock,4);

				//Debug.Log("numIndices : " + numIndices + "\nnumVertices : " + numVertices);

				int[] indices = new int[numIndices];
				byte[] indexBlock = new byte[2];
				for(int i=0;i<numIndices;i++) {
					fs.Read (indexBlock,0,2);
					indices[i] = (int)BitConverter.ToInt16 (indexBlock,0);
				}

				Vector3[] vertices = new Vector3[numVertices];
				BoneWeight[] boneWeights = new BoneWeight[numVertices];
				Vector2[] uv = new Vector2[numVertices];
				Vector3[] normals = new Vector3[numVertices];

				byte[] vertexBlock = new byte[52];

				//for debugging
				//System.Collections.Generic.Dictionary<int,int> boneIdxNums = new System.Collections.Generic.Dictionary<int, int>();
				////

				for(int i=0;i<numVertices;i++) {
					fs.Read (vertexBlock,0,52);
					float x = BitConverter.ToSingle(vertexBlock,0);
					float y = BitConverter.ToSingle(vertexBlock,4);
					float z = BitConverter.ToSingle(vertexBlock,8);
					int boneIdx0 = (int)vertexBlock[12];
					int boneIdx1 = (int)vertexBlock[13];
					int boneIdx2 = (int)vertexBlock[14];
					int boneIdx3 = (int)vertexBlock[15];
					float boneWeight0 = BitConverter.ToSingle(vertexBlock,16);
					float boneWeight1 = BitConverter.ToSingle(vertexBlock,20);
					float boneWeight2 = BitConverter.ToSingle(vertexBlock,24);
					float boneWeight3 = BitConverter.ToSingle(vertexBlock,28);

					float normalX = BitConverter.ToSingle(vertexBlock,32);
					float normalY = BitConverter.ToSingle(vertexBlock,36);
					float normalZ = BitConverter.ToSingle(vertexBlock,40);

					float u = BitConverter.ToSingle(vertexBlock,44);
					float v = 1-BitConverter.ToSingle(vertexBlock,48);


					//////basic skin blitzcrank bone idx matching error temporary fix >22, +=2
					//////custom skin blitzcrank bone idx matching error temporary fix >20 +=2
                    /*
					if(boneIdx0 >= 20) {
						boneIdx0 +=2;
					}
					if(boneIdx1 >= 20) {
						boneIdx1 +=2;
					}
					if(boneIdx2 >= 20) {
						boneIdx2 += 2;
					}
					if(boneIdx3 >= 20) {
						boneIdx3 += 2;
					}*/
					//////////

					vertices[i] = new Vector3(x,y,z);
					boneWeights[i].boneIndex0 = (int)boneIdx0;
					boneWeights[i].boneIndex1 = (int)boneIdx1;
					boneWeights[i].boneIndex2 = (int)boneIdx2;
					boneWeights[i].boneIndex3 = (int)boneIdx3;
					boneWeights[i].weight0 = boneWeight0;
					boneWeights[i].weight1 = boneWeight1;
					boneWeights[i].weight2 = boneWeight2;
					boneWeights[i].weight3 = boneWeight3;
					normals[i] = new Vector3(normalX,normalY,normalZ);
					uv[i] = new Vector2(u,v);

					//for debugging
					/*
					if(boneWeight0 > 0) {
						if(boneIdxNums.ContainsKey(boneIdx0)) {
							boneIdxNums[boneIdx0] = boneIdxNums[boneIdx0]+1;
						} else {
							boneIdxNums.Add (boneIdx0,1);
						}
					} 
					if(boneWeight1 > 0) {
						if(boneIdxNums.ContainsKey(boneIdx1)) {
							boneIdxNums[boneIdx1] = boneIdxNums[boneIdx1]+1;
						} else {
							boneIdxNums.Add (boneIdx1,1);
						}
					}
					if(boneWeight2 > 0) {
						if(boneIdxNums.ContainsKey(boneIdx2)) {
							boneIdxNums[boneIdx2] = boneIdxNums[boneIdx2]+1;
						} else {
							boneIdxNums.Add (boneIdx2,1);
						}
					}
					if(boneWeight3 > 0) {
						if(boneIdxNums.ContainsKey(boneIdx3)) {
							boneIdxNums[boneIdx3] = boneIdxNums[boneIdx3]+1;
						} else {
							boneIdxNums.Add (boneIdx3,1);
						}
					}*/
					///////


				}
				///////for debugging
				/*System.Text.StringBuilder sb = new System.Text.StringBuilder();

				System.Collections.Generic.List<int> keys = new System.Collections.Generic.List<int>(boneIdxNums.Keys);
				keys.Sort ();
				foreach(int idx in keys) {
					sb.Append (string.Format ("idx {0} : {1}\n",idx,boneIdxNums[idx]));
				}
				Debug.Log(sb.ToString());*/
				///////
				mesh = new Mesh();
				mesh.vertices = vertices;
				mesh.uv = uv;
				mesh.triangles = indices;
				mesh.boneWeights = boneWeights;
				mesh.normals = normals;	

				AssetDatabase.CreateAsset(mesh,"Assets/CreatedAsset/" + name + ".asset");

			}/*
			if(mesh == null) {
				Debug.LogError("null mesh");
				return;
			}

			GameObject go = new GameObject(name);

			string sklPath = AssetDatabase.GetAssetPath(sklFile);
			using(FileStream fs = File.OpenRead (sklPath)) {
				byte[] headerBlock = new byte[20];
				fs.Read(headerBlock,0,20);
				string version = System.Text.Encoding.ASCII.GetString (headerBlock,0,8).TrimEnd('\0');
				int numObjects = BitConverter.ToInt32(headerBlock,8);
				int skeletonHash = BitConverter.ToInt32 (headerBlock,12);
				int numElements = BitConverter.ToInt32 (headerBlock,16);

				Transform[] bones = new Transform[numElements];
				for(int i=0;i<numElements;i++) {
					bones[i] = new GameObject().transform;
				}

				byte[] boneBlock = new byte[88];
				for(int i=0;i<numElements;i++) {
					fs.Read (boneBlock,0,88);
					string boneName = System.Text.Encoding.ASCII.GetString (boneBlock,0,32).TrimEnd('\0');
					int parent = BitConverter.ToInt32 (boneBlock,32);
					float scale = BitConverter.ToSingle (boneBlock,36);
					float[,] matrix = new float[3,4];
					for(int n=0;n<3;n++) { 
						for(int m=0;m<4;m++) {
							matrix[n,m] = BitConverter.ToSingle(boneBlock,40 + n*16 + m*4);
						}
					}

					bones[i].gameObject.name = boneName;
					bones[i].parent = parent>=0?bones[parent]:go.transform;

					bones[i].localPosition = new Vector3(matrix[0,3],matrix[1,3],matrix[2,3]);

					float qw = Mathf.Sqrt (1f + matrix[0,0] + matrix[1,1] + matrix[2,2])/2f;
					float w  = 4f * qw;
					float qx = (matrix[2,1] - matrix[1,2])/w;
					float qy = (matrix[0,2] - matrix[2,0])/w;
					float qz = (matrix[1,0] - matrix[0,1])/w;

					bones[i].localRotation = new Quaternion(qx,qy,qz,qw);

					float sx = Mathf.Sqrt (matrix[0,0]*matrix[0,0] + matrix[0,1]*matrix[0,1] + matrix[0,2]*matrix[0,2]);
					float sy = Mathf.Sqrt (matrix[1,0]*matrix[1,0] + matrix[1,1]*matrix[1,1] + matrix[1,2]*matrix[1,2]);
					float sz = Mathf.Sqrt (matrix[2,0]*matrix[2,0] + matrix[2,1]*matrix[2,1] + matrix[2,2]*matrix[2,2]);

					bones[i].localScale = new Vector3(sx,sy,sz);
				}

				Matrix4x4[] bindPoses = new Matrix4x4[numElements];
				for(int i=0;i<numElements;i++) {
					bindPoses[i] = bones[i].worldToLocalMatrix * go.transform.localToWorldMatrix;
				}

				mesh.bindposes = bindPoses;

				SkinnedMeshRenderer renderer = go.AddComponent<SkinnedMeshRenderer>();
				renderer.bones = bones;
				renderer.sharedMesh = mesh;
			
				
			}

			AssetDatabase.CreateAsset(go,"Assets/CreatedAsset/" + name + ".prefab");

*/






		}
		catch(Exception e) {
			Debug.LogError(e.ToString());
			return;
		}





	}
    private static void readMesh(string path, string filename, string texturepath)
    {
        

        if (File.Exists(path + "/" + filename))
        {
                string nm = Path.GetFileNameWithoutExtension(filename);
                importingAssetsDir = "Assets/Prefabs/" + nm + "/";

                if (saveAssets)
                {
                if (!Directory.Exists(importingAssetsDir))
                {
                    Directory.CreateDirectory(importingAssetsDir);
                }
               
                }


            trace("load file :"+path + "/" + filename);

            using (FileStream fs = File.OpenRead(path + "/" + filename))
            {

              
                file = new BinaryReader(fs);
                file.BaseStream.Position = 0;



                GameObject ObjectRoot = new GameObject(nm);
                GameObject meshContainer = new GameObject("Surfaces");
                meshContainer.transform.parent = ObjectRoot.transform;
                //   GameObject Skeleton = new GameObject("Skeleton");
                //   Skeleton.transform.parent= ObjectRoot.transform;
               



                string tag = ReadChunk();
                int version = file.ReadInt32();

                trace(tag + ",  Version :" + version);

                while (getChunkSize() != 0)
                {
                    string ChunkName = ReadChunk();
   
                    if (ChunkName == "TEXS")
                    {
                        readTEX(); 
                    }
                    else if (ChunkName == "BRUS")
                    {
              
                        readBRUS();
                    }
                    else if (ChunkName == "NODE")
                    {
              
                        readNODE(ObjectRoot, meshContainer, null, importingAssetsDir);
                    }
                    breakChunk();
                }
                breakChunk();
               

                if (!isStatic)
                {
                    AnimationClip clip = new AnimationClip();
                    clip.name = nm + "_anim";
                    clip.wrapMode = WrapMode.Loop;
                    clip.frameRate = framesPerSecond;
        
                    for (int b = 0; b < listJoints.Count; b++)
                    {
                        CoreJoint joint = listJoints[b];
                        joint.addCurves(clip);
                        // trace("PATH:Skeleton" + joint.Path);
                    }

                    clip.legacy = true;
                    Animation anim = (UnityEngine.Animation)ObjectRoot.AddComponent(typeof(Animation));
                    anim.AddClip(clip, clip.name);
                    anim.clip = clip;
                    anim.playAutomatically = true;


                    if (saveAssets)
                    {
                  
                        string clipAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + clip.name + ".asset");
                        AssetDatabase.CreateAsset(clip, clipAssetPath);
          
                    }
                }

                for (int i = 0; i < surfaces.Count; i++)
                {
                    CoreMesh mesh = surfaces[i];

                    if (!isStatic)
                    {
                        B3DBone bone = Bones[i];

                
                   

                   
                        for (int j = 0; j < bone.vertex.Count; j++)
                        {
                        
                            VertexBone vertex = bone.vertex[j];
                            BoneWeight b = new BoneWeight();
                            b.boneIndex0 = vertex.bones[0].boneId;
                            b.weight0 = vertex.bones[0].Weight;
                     
                            b.boneIndex1 = vertex.bones[1].boneId;
                            b.weight1 = vertex.bones[1].Weight;

                            b.boneIndex2 = vertex.bones[2].boneId;
                            b.weight2 = vertex.bones[2].Weight;

                            b.boneIndex3 = vertex.bones[3].boneId;
                            b.weight3 = vertex.bones[3].Weight;
                     
                            mesh.addBone(b);

                    
                        }
                    }
                  
                    mesh.build();

                    if (saveAssets)
                    {
                        string meshAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + mesh.name + "_" + i + ".asset");
                        AssetDatabase.CreateAsset(mesh.geometry, meshAssetPath);
                    }
                }


                if (saveAssets)
                {

                    string prefabPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + Path.GetFileNameWithoutExtension(filename) + ".prefab");
                    var prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
                    PrefabUtility.ReplacePrefab(ObjectRoot, prefab, ReplacePrefabOptions.ConnectToPrefab);
                    AssetDatabase.Refresh();
                }

                if(saveKeysFrames)
                {
                    /*
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;

                XmlWriter textWriter = XmlWriter.Create(importingAssetsDir + "keyframes.xml", settings);
                textWriter.WriteStartDocument();
                textWriter.WriteComment("by luis santos aka djoker");
                textWriter.WriteStartElement("KeyFrames");

                    textWriter.WriteStartAttribute("Fps");
                    textWriter.WriteValue(framesPerSecond);
                    textWriter.WriteEndAttribute();
                    textWriter.WriteStartAttribute("NumFrames");
                    textWriter.WriteValue(NumFrames);
                    textWriter.WriteEndAttribute();


                // BinaryWriter writer = new BinaryWriter(new FileStream("out.lvl", FileMode.Create));
                //  writer.Close();


                for (int b = 0; b < listJoints.Count; b++)
                {
                    CoreJoint joint = listJoints[b];
                     

                    textWriter.WriteStartElement("Joint");

                    textWriter.WriteStartAttribute("ContainsPosition");
                    textWriter.WriteValue(joint.containsPosition);
                    textWriter.WriteEndAttribute();
                      
                    textWriter.WriteStartAttribute("ContainsScale");
                    textWriter.WriteValue(joint.containsScale);
                    textWriter.WriteEndAttribute();

                    textWriter.WriteStartAttribute("ContainsRotation");
                    textWriter.WriteValue(joint.containsRotation);
                    textWriter.WriteEndAttribute();


                    textWriter.WriteElementString("Name", joint.Name);
                    textWriter.WriteElementString("Path", joint.Path);
            
                    if (joint.containsPosition)
                    {
                        textWriter.WriteStartElement("Positions");

                        for (int i = 0; i < joint.rotXcurve.length; i++)
                        {
                            Keyframe xkey = joint.posXcurve.keys[i];
                            Keyframe ykey = joint.posYcurve.keys[i];
                            Keyframe zkey = joint.posZcurve.keys[i];

                            float time = xkey.time;
                            float x = xkey.value;
                            float y = ykey.value;
                            float z = zkey.value;


                            textWriter.WriteStartElement("Poition");
                            textWriter.WriteAttributeString("Time", time.ToString());
                            textWriter.WriteAttributeString("X", x.ToString());
                            textWriter.WriteAttributeString("Y", y.ToString());
                            textWriter.WriteAttributeString("Z", z.ToString());

                            textWriter.WriteEndElement();


                        }
                        textWriter.WriteEndElement();
                    }

                    if (joint.containsScale)
                    {
                        textWriter.WriteStartElement("Scales");
                        for (int i = 0; i < joint.rotXcurve.length; i++)
                        {
                            Keyframe xkey = joint.scaleXcurve.keys[i];
                            Keyframe ykey = joint.scaleYcurve.keys[i];
                            Keyframe zkey = joint.scaleZcurve.keys[i];

                            float time = xkey.time;
                            float x = xkey.value;
                            float y = ykey.value;
                            float z = zkey.value;


                            textWriter.WriteStartElement("Scale");
                            textWriter.WriteAttributeString("Time", time.ToString());
                            textWriter.WriteAttributeString("X", x.ToString());
                            textWriter.WriteAttributeString("Y", y.ToString());
                            textWriter.WriteAttributeString("Z", z.ToString());

                            textWriter.WriteEndElement();


                        }
                        textWriter.WriteEndElement();
                    }

                    if (joint.containsRotation)
                    {
                      
                        textWriter.WriteStartElement("Rotations");
                        for (int i = 0; i < joint.rotXcurve.length; i++)
                        {
                            Keyframe xkey = joint.rotXcurve.keys[i];
                            Keyframe ykey = joint.rotYcurve.keys[i];
                            Keyframe zkey = joint.rotZcurve.keys[i];
                            Keyframe wkey = joint.rotWcurve.keys[i];

                                var fps = 1f *  framesPerSecond;

                            float time = xkey.time ;

                            float x = xkey.value;
                            float y = ykey.value;
                            float z = zkey.value;
                            float w = wkey.value;

                            textWriter.WriteStartElement("Rotation");
                            textWriter.WriteAttributeString("Time", time.ToString());
                            textWriter.WriteAttributeString("X", x.ToString());
                            textWriter.WriteAttributeString("Y", y.ToString());
                            textWriter.WriteAttributeString("Z", z.ToString());
                            textWriter.WriteAttributeString("W", w.ToString());
                            textWriter.WriteEndElement();


                        }
                        textWriter.WriteEndElement();
                    }


                    textWriter.WriteEndElement();
                 
                }
      
                textWriter.WriteEndElement();
                textWriter.WriteEndDocument();
                textWriter.Flush();
                textWriter.Close();



                    AnimationClip clip = new AnimationClip();

                    for (int b = 0; b < listJoints.Count; b++)
                    {
                        CoreJoint joint = listJoints[b];

                        if (joint.containsRotation)
                        {
                         
                            AnimationCurve rotXcurve = new AnimationCurve();
                            AnimationCurve rotYcurve = new AnimationCurve();
                            AnimationCurve rotZcurve = new AnimationCurve();
                            AnimationCurve rotWcurve = new AnimationCurve();

                            int to = 3;// (int)( 14 /  framesPerSecond) % NumFrames;

                            Debug.LogWarning(" to frame:" + to);
                            for (int i = 0; i < to; i++)
                            {
                                
                                Keyframe xkey = joint.rotXcurve.keys[i];
                                Keyframe ykey = joint.rotYcurve.keys[i];
                                Keyframe zkey = joint.rotZcurve.keys[i];
                                Keyframe wkey = joint.rotWcurve.keys[i];
                                float time = xkey.time ;

                                rotXcurve.AddKey(time, xkey.value);
                                rotYcurve.AddKey(time, ykey.value);
                                rotZcurve.AddKey(time, zkey.value);
                                rotWcurve.AddKey(time, wkey.value);
                             
                            }
                            clip.SetCurve( joint.Path, typeof(Transform), "localRotation.x",rotXcurve);
                            clip.SetCurve( joint.Path, typeof(Transform), "localRotation.y", rotYcurve);
                            clip.SetCurve( joint.Path, typeof(Transform), "localRotation.z", rotZcurve);
                            clip.SetCurve( joint.Path, typeof(Transform), "localRotation.w", rotWcurve);
                        }

                    }
                    clip.name = nm + "_walk";
                    clip.wrapMode = WrapMode.Loop;
                    clip.legacy = true;
                    string clipAssetPath = AssetDatabase.GenerateUniqueAssetPath(importingAssetsDir + clip.name + ".asset");
                    AssetDatabase.CreateAsset(clip, clipAssetPath);
*/

            }

            }//file open

            Debug.LogWarning(path + "/" + filename + " Imported ;) ");
        }

    }
        public void addBone(BoneWeight b)
        {
            boneWeightsList.Add(b);

        }
Example #44
0
 public static bool LoadBinary(this Mesh lMesh, byte[] lData)
 {
     int num = Marshal.SizeOf(typeof(Vector2));
     int num2 = Marshal.SizeOf(typeof(Vector3));
     int num3 = Marshal.SizeOf(typeof(Vector4));
     int num4 = Marshal.SizeOf(typeof(Matrix4x4));
     int num5 = Marshal.SizeOf(typeof(BoneWeight));
     int num6 = Marshal.SizeOf(typeof(Color));
     int num7 = 20;
     if (lData == null || lData.Length < 20)
     {
         return false;
     }
     short num8 = BitConverter.ToInt16(lData, 0);
     short num9 = BitConverter.ToInt16(lData, 2);
     if (num8 != 245 || num9 != 1)
     {
         return false;
     }
     lMesh.Clear();
     int num10 = BitConverter.ToInt32(lData, 4);
     int num11 = BitConverter.ToInt32(lData, 8);
     int num12 = BitConverter.ToInt32(lData, 12);
     byte b = lData[16];
     bool flag = (b & 1) > 0;
     bool flag2 = (b & 2) > 0;
     bool flag3 = (b & 4) > 0;
     bool flag4 = (b & 8) > 0;
     bool flag5 = (b & 16) > 0;
     bool flag6 = (b & 32) > 0;
     bool flag7 = (b & 64) > 0;
     bool flag8 = (b & 128) > 0;
     Vector3[] array = new Vector3[num10];
     int num13 = array.Length * num2;
     GCHandle gCHandle = GCHandle.Alloc(array, GCHandleType.Pinned);
     Marshal.Copy(lData, num7, gCHandle.AddrOfPinnedObject(), num13);
     gCHandle.Free();
     num7 += num13;
     lMesh.vertices = array;
     if (flag)
     {
         Vector2[] array2 = new Vector2[num10];
         num13 = array2.Length * num;
         gCHandle = GCHandle.Alloc(array2, GCHandleType.Pinned);
         Marshal.Copy(lData, num7, gCHandle.AddrOfPinnedObject(), num13);
         gCHandle.Free();
         num7 += num13;
         lMesh.uv = array2;
         Debug.Log("UV Count : " + array2.Length);
     }
     if (flag2)
     {
         Vector2[] array2 = new Vector2[num10];
         num13 = array2.Length * num;
         gCHandle = GCHandle.Alloc(array2, GCHandleType.Pinned);
         Marshal.Copy(lData, num7, gCHandle.AddrOfPinnedObject(), num13);
         gCHandle.Free();
         num7 += num13;
         lMesh.uv2 = array2;
         Debug.Log("UV1 Count : " + array2.Length);
     }
     if (flag3)
     {
         Vector2[] array2 = new Vector2[num10];
         num13 = array2.Length * num;
         gCHandle = GCHandle.Alloc(array2, GCHandleType.Pinned);
         Marshal.Copy(lData, num7, gCHandle.AddrOfPinnedObject(), num13);
         gCHandle.Free();
         num7 += num13;
         lMesh.uv2 = array2;
         Debug.Log("UV2 Count : " + array2.Length);
     }
     if (flag4)
     {
         Vector3[] array3 = new Vector3[num10];
         num13 = array3.Length * num2;
         gCHandle = GCHandle.Alloc(array3, GCHandleType.Pinned);
         Marshal.Copy(lData, num7, gCHandle.AddrOfPinnedObject(), num13);
         gCHandle.Free();
         num7 += num13;
         lMesh.normals = array3;
         Debug.Log("Normal Count : " + array3.Length);
     }
     if (flag5)
     {
         Vector4[] array4 = new Vector4[num10];
         num13 = array4.Length * num3;
         gCHandle = GCHandle.Alloc(array4, GCHandleType.Pinned);
         Marshal.Copy(lData, num7, gCHandle.AddrOfPinnedObject(), num13);
         gCHandle.Free();
         num7 += num13;
         lMesh.tangents = array4;
         Debug.Log("Tangents Count : " + array4.Length);
     }
     if (flag6)
     {
         Color[] array5 = new Color[num10];
         num13 = array5.Length * num6;
         gCHandle = GCHandle.Alloc(array5, GCHandleType.Pinned);
         Marshal.Copy(lData, num7, gCHandle.AddrOfPinnedObject(), num13);
         gCHandle.Free();
         num7 += num13;
         lMesh.colors = array5;
     }
     if (flag7)
     {
         Matrix4x4[] array6 = new Matrix4x4[num10];
         num13 = array6.Length * num4;
         gCHandle = GCHandle.Alloc(array6, GCHandleType.Pinned);
         Marshal.Copy(lData, num7, gCHandle.AddrOfPinnedObject(), num13);
         gCHandle.Free();
         num7 += num13;
         lMesh.bindposes = array6;
     }
     if (flag8)
     {
         BoneWeight[] array7 = new BoneWeight[num10];
         num13 = array7.Length * num5;
         gCHandle = GCHandle.Alloc(array7, GCHandleType.Pinned);
         Marshal.Copy(lData, num7, gCHandle.AddrOfPinnedObject(), num13);
         gCHandle.Free();
         num7 += num13;
         lMesh.boneWeights = array7;
     }
     int[] array8 = new int[num11];
     num13 = array8.Length * 4;
     Buffer.BlockCopy(lData, num7, array8, 0, num13);
     num7 += num13;
     lMesh.triangles = array8;
     for (int i = 0; i < num12; i++)
     {
         int num14 = BitConverter.ToInt32(lData, num7);
         num7 += 4;
         array8 = new int[num14];
         num13 = array8.Length * 4;
         Buffer.BlockCopy(lData, num7, array8, 0, num13);
         num7 += num13;
         if (array8.Length > 0 && array8.Length % 3 == 0)
         {
             lMesh.SetTriangles(array8, i);
         }
     }
     return true;
 }
        public ResourceObject Parse(ByteBuffer bb)
        {
            Schema.Mesh fbMesh = Schema.Mesh.GetRootAsMesh(bb);

            UnityEngine.Mesh mesh = new UnityEngine.Mesh();

            Vec3 v3 = new Vec3();
            Vec2 v2 = new Vec2();
            Vec4 v4 = new Vec4();

            Vector3[] inVertices = new Vector3[fbMesh.VerticesLength];
            for (int i = 0; i < fbMesh.VerticesLength; i++)
            {
                Vec3 v = fbMesh.GetVertices(v3, i);
                inVertices[i] = new Vector3(v.X, v.Y, v.Z);
            }
            mesh.vertices = inVertices;

            if (fbMesh.UvLength > 0)
            {
                Vector2[] uvs = new Vector2[fbMesh.UvLength];
                for (int i = 0; i < fbMesh.UvLength; i++)
                {
                    Vec2 v = fbMesh.GetUv(v2, i);
                    uvs[i] = new Vector2(v.X, v.Y);
                }
                mesh.uv = uvs;
            }
            if (fbMesh.Uv2Length > 0)
            {
                Vector2[] uvs = new Vector2[fbMesh.Uv2Length];
                for (int i = 0; i < fbMesh.Uv2Length; i++)
                {
                    Vec2 v = fbMesh.GetUv2(v2, i);
                    uvs[i] = new Vector2(v.X, v.Y);
                }
                mesh.uv2 = uvs;
            }
            if (fbMesh.Uv3Length > 0)
            {
                Vector2[] uvs = new Vector2[fbMesh.Uv3Length];
                for (int i = 0; i < fbMesh.Uv3Length; i++)
                {
                    Vec2 v = fbMesh.GetUv3(v2, i);
                    uvs[i] = new Vector2(v.X, v.Y);
                }
                mesh.uv3 = uvs;
            }
            if (fbMesh.Uv4Length > 0)
            {
                Vector2[] uvs = new Vector2[fbMesh.Uv4Length];
                for (int i = 0; i < fbMesh.Uv4Length; i++)
                {
                    Vec2 v = fbMesh.GetUv4(v2, i);
                    uvs[i] = new Vector2(v.X, v.Y);
                }
                mesh.uv4 = uvs;
            }
            if (fbMesh.NormalsLength > 0)
            {
                Vector3[] normals = new Vector3[fbMesh.NormalsLength];
                for (int i = 0; i < fbMesh.NormalsLength; i++)
                {
                    Vec3 v = fbMesh.GetNormals(v3, i);
                    normals[i] = new Vector3(v.X, v.Y, v.Z);
                }
                mesh.normals = normals;
            }
            if (fbMesh.TangentsLength > 0)
            {
                Vector4[] tangents = new Vector4[fbMesh.TangentsLength];
                for (int i = 0; i < fbMesh.TangentsLength; i++)
                {
                    Vec4 v = fbMesh.GetTangents(v4, i);
                    tangents[i] = new Vector4(v.X, v.Y, v.Z, v.W);
                }
                mesh.tangents = tangents;
            }
            if (fbMesh.ColorsLength > 0)
            {
                Schema.Color        cobj   = new Schema.Color();
                UnityEngine.Color[] colors = new UnityEngine.Color[fbMesh.ColorsLength];
                for (int i = 0; i < fbMesh.ColorsLength; i++)
                {
                    Schema.Color c = fbMesh.GetColors(cobj, i);
                    colors[i] = new UnityEngine.Color(c.R, c.G, c.B, c.A);
                }
                mesh.colors = colors;
            }
            if (fbMesh.Colors32Length > 0)
            {
                Schema.Color32        cobj   = new Schema.Color32();
                UnityEngine.Color32[] colors = new UnityEngine.Color32[fbMesh.Colors32Length];
                for (int i = 0; i < fbMesh.Colors32Length; i++)
                {
                    Schema.Color32 c = fbMesh.GetColors32(cobj, i);
                    colors[i] = new UnityEngine.Color32(c.R, c.G, c.B, c.A);
                }
                mesh.colors32 = colors;
            }
            if (fbMesh.BoneWeightsLength > 0)
            {
                Schema.BoneWeight        bwobj       = new Schema.BoneWeight();
                UnityEngine.BoneWeight[] boneWeights = new UnityEngine.BoneWeight[fbMesh.BoneWeightsLength];
                for (int i = 0; i < fbMesh.BoneWeightsLength; i++)
                {
                    Schema.BoneWeight      _bw = fbMesh.GetBoneWeights(bwobj, i);
                    UnityEngine.BoneWeight bw  = new UnityEngine.BoneWeight();
                    bw.boneIndex0  = _bw.BoneIndex0;
                    bw.boneIndex1  = _bw.BoneIndex1;
                    bw.boneIndex2  = _bw.BoneIndex2;
                    bw.boneIndex3  = _bw.BoneIndex3;
                    bw.weight0     = _bw.Weight0;
                    bw.weight1     = _bw.Weight1;
                    bw.weight2     = _bw.Weight2;
                    bw.weight3     = _bw.Weight3;
                    boneWeights[i] = bw;
                }
                mesh.boneWeights = boneWeights;
            }

            int[] triangles = new int[fbMesh.TrianglesLength];
            for (int i = 0; i < fbMesh.TrianglesLength; i++)
            {
                triangles[i] = fbMesh.GetTriangles(i);
            }
            mesh.triangles = triangles;

            if (fbMesh.SubmeshesLength > 1)
            {
                for (int i = 0; i < fbMesh.SubmeshesLength; i++)
                {
                    Schema.SubMesh sb      = fbMesh.GetSubmeshes(i);
                    int[]          indices = new int[sb.NumOfTriangles];
                    for (int j = 0; j < sb.NumOfTriangles; j++)
                    {
                        indices[j] = fbMesh.GetTriangles((int)sb.StartTriangle + j);
                    }
                    mesh.SetIndices(indices, (UnityEngine.MeshTopology)sb.MeshTopology, i);
                }
            }

            if (fbMesh.BindposesLength > 0)
            {
                Matrix16    matrixObj = new Matrix16();
                Matrix4x4[] matrices  = new Matrix4x4[fbMesh.BindposesLength];
                for (int i = 0; i < fbMesh.BindposesLength; i++)
                {
                    Matrix16  _matrix = fbMesh.GetBindposes(matrixObj, i);
                    Matrix4x4 matrix  = new Matrix4x4();
                    matrix.m00  = _matrix.M00;
                    matrix.m01  = _matrix.M01;
                    matrix.m02  = _matrix.M02;
                    matrix.m03  = _matrix.M03;
                    matrix.m10  = _matrix.M10;
                    matrix.m11  = _matrix.M11;
                    matrix.m12  = _matrix.M12;
                    matrix.m13  = _matrix.M13;
                    matrix.m20  = _matrix.M20;
                    matrix.m21  = _matrix.M21;
                    matrix.m22  = _matrix.M22;
                    matrix.m23  = _matrix.M23;
                    matrix.m30  = _matrix.M30;
                    matrix.m31  = _matrix.M31;
                    matrix.m32  = _matrix.M32;
                    matrix.m33  = _matrix.M33;
                    matrices[i] = matrix;
                }
                mesh.bindposes = matrices;
            }

            Bound   _b   = fbMesh.GetBound(new Bound());
            Vec3    _min = _b.GetMin(v3);
            Vector3 min  = new Vector3(_min.X, _min.Y, _min.Z);
            Vec3    _max = _b.GetMax(v3);
            Vector3 max  = new Vector3(_max.X, _max.Y, _max.Z);
            Bounds  b    = new Bounds(min, max);

            mesh.bounds = b;

            string[] joints = new string[fbMesh.JointsLength];
            for (int i = 0; i < fbMesh.JointsLength; i++)
            {
                joints[i] = fbMesh.GetJoints(i);
            }

            return(new ResourceObjectMesh(mesh, joints));
        }
Example #46
0
    //----------------------------------------------------------------------------
    public void Merge()
    {
        // if not specified, go find meshes
        if (meshFilters.Length == 0)
        {
            // find all the mesh filters
            Component[] comps = GetComponentsInChildren(typeof(MeshFilter));
            meshFilters = new MeshFilter[comps.Length];

            int mfi = 0;
            foreach (Component comp in comps)
                meshFilters[mfi++] = (MeshFilter)comp;
        }

        // figure out array sizes
        int vertCount = 0;
        int normCount = 0;
        int triCount = 0;
        int uvCount = 0;

        foreach (MeshFilter mf in meshFilters)
        {
            vertCount += mf.mesh.vertices.Length;
            normCount += mf.mesh.normals.Length;
            triCount += mf.mesh.triangles.Length;
            uvCount += mf.mesh.uv.Length;
            if (material == null)
                material = mf.gameObject.GetComponent<Renderer>().material;
        }

        // allocate arrays
        Vector3[] verts = new Vector3[vertCount];
        Vector3[] norms = new Vector3[normCount];
        Transform[] aBones = new Transform[meshFilters.Length];
        Matrix4x4[] bindPoses = new Matrix4x4[meshFilters.Length];
        BoneWeight[] weights = new BoneWeight[vertCount];
        int[] tris = new int[triCount];
        Vector2[] uvs = new Vector2[uvCount];

        int vertOffset = 0;
        int normOffset = 0;
        int triOffset = 0;
        int uvOffset = 0;
        int meshOffset = 0;

        // merge the meshes and set up bones
        foreach (MeshFilter mf in meshFilters)
        {
            foreach (int i in mf.mesh.triangles)
                tris[triOffset++] = i + vertOffset;

            aBones[meshOffset] = mf.transform;
            bindPoses[meshOffset] = Matrix4x4.identity;

            foreach (Vector3 v in mf.mesh.vertices)
            {
                weights[vertOffset].weight0 = 1.0f;
                weights[vertOffset].boneIndex0 = meshOffset;
                verts[vertOffset++] = v;
            }

            foreach (Vector3 n in mf.mesh.normals)
                norms[normOffset++] = n;

            foreach (Vector2 uv in mf.mesh.uv)
                uvs[uvOffset++] = uv;

            meshOffset++;

            MeshRenderer mr =
              mf.gameObject.GetComponent(typeof(MeshRenderer))
              as MeshRenderer;

            if (mr)
                mr.enabled = false;
        }

        // hook up the mesh
        Mesh me = new Mesh();
        me.name = gameObject.name;
        me.vertices = verts;
        me.normals = norms;
        me.boneWeights = weights;
        me.uv = uvs;
        me.triangles = tris;
        me.bindposes = bindPoses;

        // hook up the mesh renderer
        SkinnedMeshRenderer smr =
          gameObject.AddComponent(typeof(SkinnedMeshRenderer))
          as SkinnedMeshRenderer;

        smr.sharedMesh = me;
        smr.bones = aBones;
        GetComponent<Renderer>().material = material;

        foreach (MeshFilter mf in meshFilters)
        {
            mf.gameObject.SetActive(false);
        }
    }
Example #47
0
        public void VertexComponents()
        {
            UnityEngine.Mesh resultMesh = _resultMesh.Unity3dObject as UnityEngine.Mesh;

            Assert.IsTrue(mesh.VerticesLength == resultMesh.vertexCount);

            // vertices
            for (int i = 0; i < mesh.VerticesLength; i++)
            {
                Vec3    v1 = mesh.GetVertices(i);
                Vector3 v2 = resultMesh.vertices[i];
                Assert.AreEqual(v1.X, v2.x);
                Assert.AreEqual(v1.Y, v2.y);
                Assert.AreEqual(v1.Z, v2.z);
            }

            // uv
            Assert.IsTrue(mesh.UvLength == resultMesh.uv.Length);
            for (int i = 0; i < mesh.UvLength; i++)
            {
                Vec2    v1 = mesh.GetUv(i);
                Vector2 v2 = resultMesh.uv[i];
                Assert.AreEqual(v1.X, v2.x);
                Assert.AreEqual(v1.Y, v2.y);
            }

            // uv2
            Assert.IsTrue(mesh.Uv2Length == resultMesh.uv2.Length);
            for (int i = 0; i < mesh.Uv2Length; i++)
            {
                Vec2    v1 = mesh.GetUv2(i);
                Vector2 v2 = resultMesh.uv2[i];
                Assert.AreEqual(v1.X, v2.x);
                Assert.AreEqual(v1.Y, v2.y);
            }

            // uv3
            Assert.IsTrue(mesh.Uv3Length == resultMesh.uv3.Length);
            for (int i = 0; i < mesh.Uv3Length; i++)
            {
                Vec2    v1 = mesh.GetUv3(i);
                Vector2 v2 = resultMesh.uv3[i];
                Assert.AreEqual(v1.X, v2.x);
                Assert.AreEqual(v1.Y, v2.y);
            }

            // uv4
            Assert.IsTrue(mesh.Uv4Length == resultMesh.uv4.Length);
            for (int i = 0; i < mesh.Uv4Length; i++)
            {
                Vec2    v1 = mesh.GetUv4(i);
                Vector2 v2 = resultMesh.uv4[i];
                Assert.AreEqual(v1.X, v2.x);
                Assert.AreEqual(v1.Y, v2.y);
            }

            // normals
            Assert.IsTrue(mesh.NormalsLength == resultMesh.normals.Length);
            for (int i = 0; i < mesh.NormalsLength; i++)
            {
                Vec3    v1 = mesh.GetNormals(i);
                Vector3 v2 = resultMesh.normals[i];
                Assert.AreEqual(v1.X, v2.x);
                Assert.AreEqual(v1.Y, v2.y);
                Assert.AreEqual(v1.Z, v2.z);
            }

            // tangents
            Assert.IsTrue(mesh.TangentsLength == resultMesh.tangents.Length);
            for (int i = 0; i < mesh.TangentsLength; i++)
            {
                Vec4    v1 = mesh.GetTangents(i);
                Vector4 v2 = resultMesh.tangents[i];
                Assert.AreEqual(v1.X, v2.x);
                Assert.AreEqual(v1.Y, v2.y);
                Assert.AreEqual(v1.Z, v2.z);
                Assert.AreEqual(v1.W, v2.w);
            }

            // colors
            Assert.IsTrue(mesh.ColorsLength == resultMesh.colors.Length);
            for (int i = 0; i < mesh.ColorsLength; i++)
            {
                Schema.Color      c1 = mesh.GetColors(i);
                UnityEngine.Color c2 = resultMesh.colors[i];
                Assert.AreEqual(c1.A, c2.a);
                Assert.AreEqual(c1.B, c2.b);
                Assert.AreEqual(c1.G, c2.g);
                Assert.AreEqual(c1.R, c2.r);
            }

            // colors32
            Assert.IsTrue(mesh.Colors32Length == resultMesh.colors32.Length);
            for (int i = 0; i < mesh.Colors32Length; i++)
            {
                Schema.Color32      c1 = mesh.GetColors32(i);
                UnityEngine.Color32 c2 = resultMesh.colors32[i];
                Assert.AreEqual(c1.A, c2.a);
                Assert.AreEqual(c1.B, c2.b);
                Assert.AreEqual(c1.G, c2.g);
                Assert.AreEqual(c1.R, c2.r);
            }

            // BoneWeigths
            Assert.IsTrue(mesh.BoneWeightsLength == resultMesh.boneWeights.Length);
            for (int i = 0; i < mesh.BoneWeightsLength; i++)
            {
                Schema.BoneWeight      bw1 = mesh.GetBoneWeights(i);
                UnityEngine.BoneWeight bw2 = resultMesh.boneWeights[i];
                Assert.AreEqual(bw1.BoneIndex0, bw2.boneIndex0);
                Assert.AreEqual(bw1.BoneIndex1, bw2.boneIndex1);
                Assert.AreEqual(bw1.BoneIndex2, bw2.boneIndex2);
                Assert.AreEqual(bw1.BoneIndex3, bw2.boneIndex3);
                Assert.AreEqual(bw1.Weight0, bw2.weight0);
                Assert.AreEqual(bw1.Weight1, bw2.weight1);
                Assert.AreEqual(bw1.Weight2, bw2.weight2);
                Assert.AreEqual(bw1.Weight3, bw2.weight3);
            }

            // 三角面列表
            Assert.IsTrue(mesh.TrianglesLength == resultMesh.triangles.Length);
            for (int i = 0; i < mesh.TrianglesLength; i++)
            {
                int t1 = mesh.GetTriangles(i);
                int t2 = resultMesh.triangles[i];
                Assert.AreEqual(t1, t2);
            }
        }
Example #48
0
        public override void UpdateUMAMesh(bool updatedAtlas, UMAData umaData, string[] textureNameList, int atlasResolution)
        {
            this.umaData = umaData;
            this.textureNameList = textureNameList;
            this.atlasResolution = atlasResolution;

            combinedGroupedList = new List<CombineInstance>();
            combinedMeshList = new List<CombineInstance>();
            combinedMaterialList = new List<Material>();
            combinedSlotList = new List<SlotData>();

            if (updatedAtlas)
            {
                CombineByShader();
            }
            else
            {
                CombineByMaterial();
            }

            Matrix4x4[] bindposesArray = umaData.myRenderer.sharedMesh.bindposes;

            tempMatrix = Matrix4x4.identity;

            int boneArraySize = 0;
            int boneArrayIndex = 0;

            for(int i = 0; i < combinedSlotList.Count; i++){
                boneArraySize = boneArraySize + combinedSlotList[i].boneWeights.Length;
            }

            BoneWeight[] boneWeightsArray = new BoneWeight[boneArraySize];

            for(int i = 0; i < combinedSlotList.Count; i++){

                BoneWeight[] tempBoneWeights = combinedSlotList[i].boneWeights;

                for(int boneWeightCount = 0; boneWeightCount < tempBoneWeights.Length; boneWeightCount++){
                    boneWeightsArray[boneArrayIndex] = tempBoneWeights[boneWeightCount];
                    boneArrayIndex++;
                }
            }

            Mesh newMesh = umaData.firstBake ? new Mesh() : umaData.myRenderer.sharedMesh;
            newMesh.CombineMeshes(combinedGroupedList.ToArray(),false,false);

            for(int i = 0; i < combinedGroupedList.Count; i++){
                GameObject.DestroyImmediate(combinedGroupedList[i].mesh);
            }

            newMesh.boneWeights = boneWeightsArray;
            newMesh.bindposes = bindposesArray;
            umaData.myRenderer.sharedMesh = newMesh;

            if(updatedAtlas){
                RecalculateUV();
            }

            umaData.umaRecipe.ClearDNAConverters();
            for (int i = 0; i < umaData.umaRecipe.slotDataList.Length; i++)
            {
                SlotData slotData = umaData.umaRecipe.slotDataList[i];
                if(slotData != null){
                    umaData.umaRecipe.AddDNAUpdater(slotData.slotDNA);
                }
            }

            umaData.myRenderer.quality = SkinQuality.Bone4;
            umaData.myRenderer.useLightProbes = true;
            umaData.myRenderer.sharedMaterials = combinedMaterialList.ToArray();
            //umaData.myRenderer.sharedMesh.RecalculateBounds();
            umaData.myRenderer.sharedMesh.name = "UMAMesh";

            umaData.firstBake = false;
        }
Example #49
0
	///// Skeletal animation /////

	public void UpdatePosing( bool a_bCleanSkinning = false )
	{
		Uni2DSmoothBindingBone[ ] rBones = this.Bones;
		int iBoneCount = rBones.Length;

		MeshFilter rMeshFilterComponent                   = this.GetComponent<MeshFilter>( );
		MeshRenderer rMeshRendererComponent               = this.GetComponent<MeshRenderer>( );
		SkinnedMeshRenderer rSkinnedMeshRendererComponent = this.GetComponent<SkinnedMeshRenderer>( );

		// The skinned mesh
		Mesh rSkinnedMesh = SpriteData.renderMesh;

		if( rMeshFilterComponent == null )
		{
			rMeshFilterComponent = this.gameObject.AddComponent<MeshFilter>( );
		}

		// Bones are attached to the sprite: need to update its posing / bindpose / bone weights
		// and ensure the sprite has the required components to be rendered as a skinned mesh
		if( iBoneCount > 0 )
		{
			// Create skinned mesh renderer component if none exists
			if( rSkinnedMeshRendererComponent == null )
			{
				rSkinnedMeshRendererComponent = this.gameObject.AddComponent<SkinnedMeshRenderer>( );
			}

			// If a mesh renderer component exists, copy its shared materials to the skinned mesh renderer component
			// then destroy it to have only one (skinned) mesh renderer
			if( rMeshRendererComponent != null )
			{
				rSkinnedMeshRendererComponent.sharedMaterials = rMeshRendererComponent.sharedMaterials;
				DestroyImmediate( rMeshRendererComponent );
			}

			// Force skinned mesh renderer component to be enabled
			rSkinnedMeshRendererComponent.enabled = true;
			
			// Skinned vertices
			int iSkinnedVertexCount = rSkinnedMesh.vertexCount;
			Vector3[ ] rSkinnedMeshVertices = rSkinnedMesh.vertices;

			Transform[ ] oBoneTransforms = new Transform[ iBoneCount ];
			Matrix4x4[ ] oBindPoses      = new Matrix4x4[ iBoneCount ];
			BoneWeight[ ] oBoneWeights   = new BoneWeight[ iSkinnedVertexCount ];
	
			// Create poses
			Matrix4x4 rLocalToWorldMatrix = this.transform.localToWorldMatrix;
			Dictionary<Uni2DSmoothBindingBone,int> oBoneIndexDict = new Dictionary<Uni2DSmoothBindingBone, int>( iBoneCount );

			int iBoneIndex = 0;
			foreach( Uni2DSmoothBindingBone rBone in rBones )
			{
				Transform rBoneTransform      = rBone.transform;
				oBoneTransforms[ iBoneIndex ] = rBoneTransform;
				oBindPoses[ iBoneIndex ]      = rBoneTransform.worldToLocalMatrix * rLocalToWorldMatrix;
				
				oBoneIndexDict.Add( rBone, iBoneIndex );
				++iBoneIndex;
			}
	
			// Compute bone weights for each vertex
			for( int iSkinnedVertexIndex = 0; iSkinnedVertexIndex < iSkinnedVertexCount; ++iSkinnedVertexIndex )
			{
				oBoneWeights[ iSkinnedVertexIndex ] = this.ComputeBoneWeight( rSkinnedMeshVertices[ iSkinnedVertexIndex ], oBoneIndexDict );
			}
	
			// Set bindposes and weights
			rSkinnedMesh.boneWeights = oBoneWeights;
			rSkinnedMesh.bindposes   = oBindPoses;
	
			// Set bones and skinned mesh
			rSkinnedMeshRendererComponent.bones       = oBoneTransforms;
			rSkinnedMeshRendererComponent.sharedMesh  = rSkinnedMesh;
			rSkinnedMeshRendererComponent.localBounds = rSkinnedMesh.bounds;
			rSkinnedMeshRendererComponent.quality     = this.SpriteSettings.skinQuality;

			rMeshFilterComponent.sharedMesh = rSkinnedMesh;

			EditorUtility.SetDirty( rSkinnedMesh );
			EditorUtility.SetDirty( rSkinnedMeshRendererComponent );
			EditorUtility.SetDirty( rMeshFilterComponent );
			EditorUtility.SetDirty( this.gameObject );
		}
		else if( a_bCleanSkinning && rSkinnedMeshRendererComponent != null )	// In this case, revert sprite to a "classic" (unskinned) rendering
		{

			if( rMeshRendererComponent == null )
			{
				rMeshRendererComponent = this.gameObject.AddComponent<MeshRenderer>( );
			}

			rSkinnedMesh.boneWeights = null;
			rSkinnedMesh.bindposes   = null;

			rMeshFilterComponent.sharedMesh        = rSkinnedMesh;
			rMeshRendererComponent.sharedMaterials = rSkinnedMeshRendererComponent.sharedMaterials;

			// Remove useless skinned mesh component
			DestroyImmediate( rSkinnedMeshRendererComponent );
			
			EditorUtility.SetDirty( rSkinnedMesh );
			EditorUtility.SetDirty( rMeshFilterComponent );
			EditorUtility.SetDirty( rMeshRendererComponent );
			EditorUtility.SetDirty( this.gameObject );
		}
	}
    public void BuildMesh() {
        float startTime = Time.realtimeSinceStartup;
        
        // NOISE VOLUME!
        RenderTexture DensityVolume = new RenderTexture(16, 16, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.sRGB);
        DensityVolume.volumeDepth = 16;
        DensityVolume.isVolume = true;
        DensityVolume.enableRandomWrite = true;
        DensityVolume.filterMode = FilterMode.Bilinear;
        DensityVolume.wrapMode = TextureWrapMode.Repeat;
        DensityVolume.Create();
        int mgen_id = CShaderSimplex.FindKernel("FillEmpty");
        // uses renderTexture rather than StructuredBuffer?
        CShaderSimplex.SetTexture(mgen_id, "Result", DensityVolume);  // Links RenderTexture to the "Result" RWTexture in the compute shader?	
        CShaderSimplex.Dispatch(mgen_id, 1, 1, 16);  // run computeShader "FillEmpty" with 1 x 1 x 31 threadGroups?      
        mgen_id = CShaderSimplex.FindKernel("Simplex3d");
        CShaderSimplex.SetTexture(mgen_id, "Result", DensityVolume);
        CShaderSimplex.Dispatch(mgen_id, 1, 1, 16);  // Fill shared RenderTexture with GPU simplex Noise
        

        ComputeBuffer cBufferSegmentTransform = new ComputeBuffer(critterSegmentTransforms.Length, sizeof(float) * (3 + 3 + 4));
        cBufferSegmentTransform.SetData(critterSegmentTransforms);
        int kernelID = CShaderBuildMC.FindKernel("CSMain");
        CShaderBuildMC.SetBuffer(kernelID, "segmentTransformBuffer", cBufferSegmentTransform);
        CShaderBuildMC.SetTexture(kernelID, "noise_volume", DensityVolume);  // Noise 3D texture
        //Debug.Log(DensityVolume.colorBuffer.ToString());

        // Figure out how many chunks are needed:
        int numChunksX = Mathf.CeilToInt(GlobalBoundingBoxDimensions.x / (cellResolution * 8f));
        int numChunksY = Mathf.CeilToInt(GlobalBoundingBoxDimensions.y / (cellResolution * 8f));
        int numChunksZ = Mathf.CeilToInt(GlobalBoundingBoxDimensions.z / (cellResolution * 8f));
        //Debug.Log("numChunks: (" + numChunksX.ToString() + ", " + numChunksY.ToString() + ", " + numChunksZ.ToString() + ")");

        int totalNumChunks = numChunksX * numChunksY * numChunksZ;
        Poly[][] PolyArrayArray = new Poly[totalNumChunks][];  // This will hold the mesh data from the chunks calculated on the GPU
        int[] numPolysArray = new int[totalNumChunks];
        int totalNumPolys = 0;

        // Get each chunk!
        int chunkIndex = 0;
        for(int x = 0; x < numChunksX; x++) {
            for(int y = 0; y < numChunksY; y++) {
                for(int z = 0; z < numChunksZ; z++) {
                    // Figure out chunk offset amount:
                    Vector3 chunkOffset = new Vector3(cellResolution * 8f * x, cellResolution * 8f * y, cellResolution * 8f * z) + GlobalBoundingBoxOffset - (GlobalBoundingBoxDimensions / 2f);

                    int[] numPolys = new int[1];
                    ComputeBuffer cBufferNumPoly = new ComputeBuffer(1, sizeof(int));
                    cBufferNumPoly.SetData(numPolys);

                    int id = CShaderBuildMC.FindKernel("CSMain");
                    CShaderBuildMC.SetInt("_CalcNumPolys", 1); // only calculate how many tris so I can correctly size the poly buffer
                    CShaderBuildMC.SetFloat("_GlobalOffsetX", chunkOffset.x);
                    CShaderBuildMC.SetFloat("_GlobalOffsetY", chunkOffset.y);
                    CShaderBuildMC.SetFloat("_GlobalOffsetZ", chunkOffset.z);
                    CShaderBuildMC.SetFloat("_CellSize", cellResolution);
                    CShaderBuildMC.SetVector("_ColorPrimary", colorPrimary);
                    CShaderBuildMC.SetVector("_ColorSecondary", colorSecondary);
                    CShaderBuildMC.SetFloat("_ColorNoiseScale", colorNoiseScale);
                    CShaderBuildMC.SetFloat("_ColorSmlAmplitude", colorSmlAmplitude);
                    CShaderBuildMC.SetFloat("_ColorMedAmplitude", colorMedAmplitude);
                    CShaderBuildMC.SetFloat("_ColorLrgAmplitude", colorLrgAmplitude);
                    CShaderBuildMC.SetFloat("_ColorContrast", colorContrast);
                    CShaderBuildMC.SetFloat("_ColorThreshold", colorThreshold);
                    CShaderBuildMC.SetVector("_SkinNoiseScale", skinNoiseScale);
                    CShaderBuildMC.SetFloat("_SkinNoiseAmplitude", skinNoiseAmplitude);
                    CShaderBuildMC.SetVector("_SkinLocalTaper", skinLocalTaper);
                    CShaderBuildMC.SetVector("_SkinLocalSinFreq", skinLocalSinFreq);
                    CShaderBuildMC.SetVector("_SkinLocalSinAmp", skinLocalSinAmp);
                    // Local Segment-space modifications, sin, taper, etc.

                    CShaderBuildMC.SetBuffer(id, "numPolyBuffer", cBufferNumPoly);
                    CShaderBuildMC.Dispatch(id, 1, 1, 1);  // calc num polys      
                    cBufferNumPoly.GetData(numPolys);  // get numPolys
                    //Debug.Log("Chunk: " + (z + (numChunksZ * y) + (numChunksZ * numChunksY * x)).ToString() + ", cBufferNumPoly.GetData(numPolys): " + numPolys[0].ToString() + ", chunkOffset: " + chunkOffset.ToString());
                    totalNumPolys += numPolys[0];
                    numPolysArray[chunkIndex] = numPolys[0];
                                        
                    if(numPolys[0] > 0) {   // only do this if there was at least 1 triangle in the test pass
                        Poly[] polyArray = new Poly[numPolys[0]];
                        int cBufferStride = sizeof(float) * (18 + 9 + 6) + sizeof(int) * (6);
                        ComputeBuffer cBuffer = new ComputeBuffer(numPolys[0], cBufferStride);  // 18 floats x 4 bytes/float = 72   + COLORS! 9 x 4 = 36  = 108   + BONES! 6x4 = 24 + 6 xint...
                        cBuffer.SetData(polyArray);
                        
                        CShaderBuildMC.SetBuffer(id, "buffer", cBuffer);
                        CShaderBuildMC.SetInt("_CalcNumPolys", 0);  // Actually calc tris        
                        CShaderBuildMC.Dispatch(id, 1, 1, 1);
                        cBuffer.GetData(polyArray);  // return data from GPU

                        PolyArrayArray[chunkIndex] = polyArray;
                        cBuffer.Dispose();
                    }

                    cBufferNumPoly.Dispose();

                    chunkIndex++;
                }
            }
        }

        
        CritterDecorationsTest.decorationStruct[] points = new CritterDecorationsTest.decorationStruct[totalNumPolys];
        
        //Construct mesh using received data 
        int vindex = 0;
        int decindex = 0;
                
        // Why same number of tris as vertices?  == // because all triangles have duplicate verts - no shared vertices?
        Vector3[] vertices = new Vector3[totalNumPolys * 3];
        Color[] colors = new Color[totalNumPolys * 3];
        int[] tris = new int[totalNumPolys * 3];
        Vector2[] uvs = new Vector2[totalNumPolys * 3];
        Vector3[] normals = new Vector3[totalNumPolys * 3];
        BoneWeight[] weights = new BoneWeight[totalNumPolys * 3];

        //Parse triangles
        for(int i = 0; i < PolyArrayArray.Length; i++) {
            if(numPolysArray[i] > 0) {  // only do this if there was at least 1 triangle in the test pass
                for (int ix = 0; ix < numPolysArray[i]; ix++) {

                    Vector3 vPos;
                    Vector3 vOffset = new Vector3(0, 0, 0);   //???  offsets all vertices by this amount, but why 30?? 
                                                              //A1,A2,A3
                    vPos = new Vector3(PolyArrayArray[i][ix].A1, PolyArrayArray[i][ix].A2, PolyArrayArray[i][ix].A3) + vOffset;
                    vertices[vindex] = vPos * _Scale;
                    normals[vindex] = new Vector3(PolyArrayArray[i][ix].NA1, PolyArrayArray[i][ix].NA2, PolyArrayArray[i][ix].NA3);
                    tris[vindex] = vindex;
                    uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);
                    colors[vindex] = new Color(PolyArrayArray[i][ix].CAR, PolyArrayArray[i][ix].CAG, PolyArrayArray[i][ix].CAB, 1.0f);
                    weights[vindex].boneIndex0 = PolyArrayArray[i][ix].BoneIndexA0;
                    weights[vindex].boneIndex1 = PolyArrayArray[i][ix].BoneIndexA1;
                    weights[vindex].weight0 = PolyArrayArray[i][ix].BoneWeightA0;
                    weights[vindex].weight1 = PolyArrayArray[i][ix].BoneWeightA1;

                    points[decindex].pos = vPos;
                    points[decindex].normal = normals[vindex];
                    points[decindex].color = new Vector3(colors[vindex].r, colors[vindex].g, colors[vindex].b);
                    
                    decindex++;
                    vindex++;

                    //B1,B2,B3
                    vPos = new Vector3(PolyArrayArray[i][ix].B1, PolyArrayArray[i][ix].B2, PolyArrayArray[i][ix].B3) + vOffset;
                    vertices[vindex] = vPos * _Scale;
                    normals[vindex] = new Vector3(PolyArrayArray[i][ix].NB1, PolyArrayArray[i][ix].NB2, PolyArrayArray[i][ix].NB3);
                    tris[vindex] = vindex;
                    uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);
                    colors[vindex] = new Color(PolyArrayArray[i][ix].CBR, PolyArrayArray[i][ix].CBG, PolyArrayArray[i][ix].CBB, 1.0f);
                    weights[vindex].boneIndex0 = PolyArrayArray[i][ix].BoneIndexB0;
                    weights[vindex].boneIndex1 = PolyArrayArray[i][ix].BoneIndexB1;
                    weights[vindex].weight0 = PolyArrayArray[i][ix].BoneWeightB0;
                    weights[vindex].weight1 = PolyArrayArray[i][ix].BoneWeightB1;

                    vindex++;

                    //C1,C2,C3
                    vPos = new Vector3(PolyArrayArray[i][ix].C1, PolyArrayArray[i][ix].C2, PolyArrayArray[i][ix].C3) + vOffset;
                    vertices[vindex] = vPos * _Scale;
                    normals[vindex] = new Vector3(PolyArrayArray[i][ix].NC1, PolyArrayArray[i][ix].NC2, PolyArrayArray[i][ix].NC3);
                    tris[vindex] = vindex;
                    uvs[vindex] = new Vector2(vertices[vindex].z, vertices[vindex].x);
                    colors[vindex] = new Color(PolyArrayArray[i][ix].CCR, PolyArrayArray[i][ix].CCG, PolyArrayArray[i][ix].CCB, 1.0f);
                    weights[vindex].boneIndex0 = PolyArrayArray[i][ix].BoneIndexC0;
                    weights[vindex].boneIndex1 = PolyArrayArray[i][ix].BoneIndexC1;
                    weights[vindex].weight0 = PolyArrayArray[i][ix].BoneWeightC0;
                    weights[vindex].weight1 = PolyArrayArray[i][ix].BoneWeightC1;
                    
                    vindex++;
                }
            }            
        }
        
        //We have got all data and are ready to setup a new mesh!
        Mesh newMesh = new Mesh();
        newMesh.vertices = vertices;
        newMesh.uv = uvs; //Unwrapping.GeneratePerTriangleUV(NewMesh);
        newMesh.triangles = tris;
        newMesh.normals = normals; //NewMesh.RecalculateNormals();
        newMesh.colors = colors;
        newMesh.Optimize();        

        // Set up SKINNING!!!:
        Transform[] bones = new Transform[critter.critterSegmentList.Count];
        Matrix4x4[] bindPoses = new Matrix4x4[critter.critterSegmentList.Count];
        // Try just using existing critter's GameObjects/Transforms:
        for(int seg = 0; seg < critter.critterSegmentList.Count; seg++) {
            bones[seg] = critter.critterSegmentList[seg].transform;
            bindPoses[seg] = bones[seg].worldToLocalMatrix * transform.localToWorldMatrix;  // ?????????????????  
            // the bind pose is the inverse of inverse transformation matrix of the bone, when the bone is in the bind pose .... unhelpful ....
        }
        newMesh.boneWeights = weights;
        newMesh.bindposes = bindPoses;
        SkinnedMeshRenderer skinnedMeshRenderer = this.GetComponent<SkinnedMeshRenderer>();
        skinnedMeshRenderer.bones = bones;
        skinnedMeshRenderer.sharedMesh = newMesh;
        skinnedMeshRenderer.enabled = true;
                
        cBufferSegmentTransform.Release();

        critterDecorationsTest.TurnOn(points);

        float calcTime = Time.realtimeSinceStartup - startTime;
        Debug.Log("MeshCreated! " + calcTime.ToString());
    }
Example #51
0
	private BoneWeight ComputeBoneWeight( Vector3 a_f3VertexLocalCoords, Dictionary<Uni2DSmoothBindingBone,int> a_rBonesIndexes )
	{
		Dictionary<Uni2DSmoothBindingBone, float> rBonesInfluences = this.GetBonesInfluences( a_f3VertexLocalCoords, a_rBonesIndexes.Keys );
		float[ ] rWeights = rBonesInfluences.Values.ToArray( );
		Uni2DSmoothBindingBone[ ] rBones = rBonesInfluences.Keys.ToArray( );

		float fInvInfluenceSum = 1.0f / rBonesInfluences.Sum( x => x.Value );

		int iBoneCount = rBones.Length;
		BoneWeight oBoneWeight = new BoneWeight( );

		// Bone 1
		if( iBoneCount > 0 )
		{
			oBoneWeight.weight0 = rWeights[ 0 ] * fInvInfluenceSum;
			oBoneWeight.boneIndex0 = a_rBonesIndexes[ rBones[ 0 ] ];

			// Bone 2
			if( iBoneCount > 1 )
			{
				oBoneWeight.weight1 = rWeights[ 1 ] * fInvInfluenceSum;
				oBoneWeight.boneIndex1 = a_rBonesIndexes[ rBones[ 1 ] ];
		
				// Bone 3
				if( iBoneCount > 2 )
				{
					oBoneWeight.weight2 = rWeights[ 2 ] * fInvInfluenceSum;
					oBoneWeight.boneIndex2 = a_rBonesIndexes[ rBones[ 2 ] ];
		
					// Bone 4
					if( iBoneCount > 3 )
					{
						oBoneWeight.weight3 = rWeights[ 3 ] * fInvInfluenceSum;
						oBoneWeight.boneIndex3 = a_rBonesIndexes[ rBones[ 3 ] ];
					}
				}
			}
		}

		return oBoneWeight;
	}
    void ImportSetMesh(string strNodeName, GameObject goNode, GameObject goTopAttachNode, bool bDirectControlPointsMode)
    {
        // Get Mesh
        IntPtr pFBXGetMesh = FBXImporterGetMesh(strNodeName, bInDirectControlPointsMode, bInNormalSmoothing);
        if (pFBXGetMesh != IntPtr.Zero)
        {
            FBXMesh sFBXMesh = new FBXMesh();
            IntPtr pFBXMesh = Marshal.AllocHGlobal(Marshal.SizeOf(sFBXMesh));
            try
            {
                sFBXMesh = (FBXMesh)Marshal.PtrToStructure(pFBXGetMesh, typeof(FBXMesh));
            }
            finally
            {
                Marshal.FreeHGlobal(pFBXMesh);
            }
            if (bDirectControlPointsMode)
            {
                sFBXMesh.numVertexs = sFBXMesh.numVertexs / 3;
                sFBXMesh.numNormals = sFBXMesh.numNormals / 3;
                sFBXMesh.numUVs = sFBXMesh.numUVs / 3;
            }

            // Vertex
            float[] fVertexs = new float[sFBXMesh.numVertexs * 3];
            Marshal.Copy(sFBXMesh.fVertexs, fVertexs, 0, sFBXMesh.numVertexs * 3);
            Vector3[] vecVertexs = new Vector3[sFBXMesh.numVertexs];
            int j = 0;
            for (int i = 0; i < sFBXMesh.numVertexs; i++)
            {
                vecVertexs[i].x = -fVertexs[j] * fGlobalScale;
                j++;
                vecVertexs[i].y = fVertexs[j] * fGlobalScale;
                j++;
                vecVertexs[i].z = fVertexs[j] * fGlobalScale;
                j++;
            }

            // Normal
            float[] fNormals = new float[sFBXMesh.numNormals * 3];
            Marshal.Copy(sFBXMesh.fNormals, fNormals, 0, sFBXMesh.numNormals * 3);
            Vector3[] vecNormals = new Vector3[sFBXMesh.numNormals];
            j = 0;
            for (int i = 0; i < sFBXMesh.numNormals; i++)
            {
                vecNormals[i].x = -fNormals[j];
                j++;
                vecNormals[i].y = fNormals[j];
                j++;
                vecNormals[i].z = fNormals[j];
                j++;
            }

            // UV
            float[] fUVs = new float[sFBXMesh.numUVs * 2];
            Marshal.Copy(sFBXMesh.fUVs, fUVs, 0, sFBXMesh.numUVs * 2);
            Vector2[] vecUVs = new Vector2[sFBXMesh.numUVs];
            j = 0;
            for (int i = 0; i < sFBXMesh.numUVs; i++)
            {
                vecUVs[i].x = fUVs[j];
                j++;
                vecUVs[i].y = fUVs[j];
                j++;
            }

            // Polygon (MaterialID)
            int[] iPolygonMatIDs = new int[sFBXMesh.numPolygonMatID];
            Marshal.Copy(sFBXMesh.iPolygonMatIDs, iPolygonMatIDs, 0, sFBXMesh.numPolygonMatID);
            int numPolygonIndex = sFBXMesh.numPolygonIndex;
            int[] iPolygonIndexs = new int[numPolygonIndex];
            Marshal.Copy(sFBXMesh.iPolygonIndexs, iPolygonIndexs, 0, numPolygonIndex);
            if (bDirectControlPointsMode)
            {
                sFBXMesh.numPolygonMatID = sFBXMesh.numPolygonMatID / 3;
            }

            // Set Mesh
            goNode.AddComponent<MeshRenderer>();
            goNode.AddComponent<MeshFilter>();
            Mesh sMesh = new Mesh();
            sMesh.name = goNode.name;
            goNode.GetComponent<MeshFilter>().mesh = sMesh;
            sMesh.Clear();
            sMesh.vertices = vecVertexs;
            sMesh.normals = vecNormals;
            sMesh.uv = vecUVs;
            sMesh.subMeshCount = sFBXMesh.numMatID;
            List<List<int>> listListMatIDIndeices = new List<List<int>>();
            for (int i = 0; i < sFBXMesh.numMatID; i++)
            {
                List<int> iListMatIDIndeices = new List<int>();
                listListMatIDIndeices.Add(iListMatIDIndeices);
            }

            // Polygon (Material Index)
            if (bDirectControlPointsMode)
            {
                j = 0;
                for (int i = 0; i < sFBXMesh.numPolygonMatID; i++)
                {
                    int iMatID = iPolygonMatIDs[i];
                    if (iMatID < listListMatIDIndeices.Count)
                    {
                        listListMatIDIndeices[iMatID].Add(iPolygonIndexs[j + 0]);
                        listListMatIDIndeices[iMatID].Add(iPolygonIndexs[j + 2]);
                        listListMatIDIndeices[iMatID].Add(iPolygonIndexs[j + 1]);
                        j = j + 3;
                    }
                }
            }
            else
            {
                j = 0;
                for (int i = 0; i < sFBXMesh.numPolygonMatID; i++)
                {
                    int iMatID = iPolygonMatIDs[i];
                    if (iMatID < listListMatIDIndeices.Count)
                    {
                        listListMatIDIndeices[iMatID].Add(j + 0);
                        listListMatIDIndeices[iMatID].Add(j + 2);
                        listListMatIDIndeices[iMatID].Add(j + 1);
                        j = j + 3;
                    }
                }
            }

            // Triangles (Material Index)
            j = 0;
            for (int i = 0; i < sFBXMesh.numMatID; i++)
            {
                int[] iMatIDIndeices = listListMatIDIndeices[i].ToArray();
                //if (iMatIDIndeices.Length > 0)
                {
                    sMesh.SetTriangles(iMatIDIndeices, j);
                    j++;
                }
            }

            // Get Weight
            IntPtr pFBXGetWeight = FBXImporterGetWeight(strNodeName, iPolygonIndexs, numPolygonIndex, bInDirectControlPointsMode);
            if (pFBXGetWeight != IntPtr.Zero)
            {
                FBXWeight sFBXWeight = new FBXWeight();
                IntPtr pFBXWeight = Marshal.AllocHGlobal(Marshal.SizeOf(sFBXWeight));
                try
                {
                    sFBXWeight = (FBXWeight)Marshal.PtrToStructure(pFBXGetWeight, typeof(FBXWeight));
                }
                finally
                {
                    Marshal.FreeHGlobal(pFBXWeight);
                }
                if (bDirectControlPointsMode)
                {
                    sFBXWeight.iBoneWeightCount = sFBXWeight.iBoneWeightCount / 3;
                }

                // Weight (Bone)
                int[] iBoneID = new int[sFBXWeight.iBoneWeightCount * 4];
                Marshal.Copy(sFBXWeight.iBoneID, iBoneID, 0, sFBXWeight.iBoneWeightCount * 4);
                float[] fBoneWeight = new float[sFBXWeight.iBoneWeightCount * 4];
                Marshal.Copy(sFBXWeight.fBoneWeight, fBoneWeight, 0, sFBXWeight.iBoneWeightCount * 4);
                BoneWeight[] boneWeights = new BoneWeight[sFBXWeight.iBoneWeightCount];
                for (int i = 0; i < sFBXWeight.iBoneWeightCount; i++)
                {
                    BoneWeight boneWeight = new BoneWeight();
                    boneWeight.boneIndex0 = iBoneID[(i * 4) + 0];
                    boneWeight.boneIndex1 = iBoneID[(i * 4) + 1];
                    boneWeight.boneIndex2 = iBoneID[(i * 4) + 2];
                    boneWeight.boneIndex3 = iBoneID[(i * 4) + 3];
                    boneWeight.weight0 = fBoneWeight[(i * 4) + 0];
                    boneWeight.weight1 = fBoneWeight[(i * 4) + 1];
                    boneWeight.weight2 = fBoneWeight[(i * 4) + 2];
                    boneWeight.weight3 = fBoneWeight[(i * 4) + 3];
                    boneWeights[i] = boneWeight;
                }
                sMesh.boneWeights = boneWeights;

                // Bind Pose (Bone)
                SkinnedMeshRenderer sSkinnedMeshRenderer = goNode.AddComponent<SkinnedMeshRenderer>();
                string strBoneName = Marshal.PtrToStringAnsi(sFBXWeight.strBoneNodeNames).ToString();
                if (strBoneName != "")
                {
                    string[] strBoneNodeNames = strBoneName.Split(',');
                    //float[] matBonePose = new float[strBoneNodeNames.Length * 16];
                    //Marshal.Copy(sFBXWeight.matBonePose, matBonePose, 0, strBoneNodeNames.Length * 16);
                    Matrix4x4[] bindposes = new Matrix4x4[strBoneNodeNames.Length];
                    Transform[] bones = new Transform[strBoneNodeNames.Length];
                    sSkinnedMeshRenderer.bones = new Transform[strBoneNodeNames.Length];
                    float[] fGlbTranslation = new float[3 * strBoneNodeNames.Length];
                    Marshal.Copy(sFBXWeight.fGlbTranslation, fGlbTranslation, 0, 3 * strBoneNodeNames.Length);
                    float[] fGlbRotation = new float[4 * strBoneNodeNames.Length];
                    Marshal.Copy(sFBXWeight.fGlbRotation, fGlbRotation, 0, 4 * strBoneNodeNames.Length);
                    float[] fGlbScale = new float[3 * strBoneNodeNames.Length];
                    Marshal.Copy(sFBXWeight.fGlbScale, fGlbScale, 0, 3 * strBoneNodeNames.Length);
                    for (int i = 0; i < strBoneNodeNames.Length; i++)
                    {
                        /*
                        Matrix4x4 matBindPose = new Matrix4x4();
                        matBindPose.m00 = matBonePose[(i * 16) + 0];
                        matBindPose.m01 = matBonePose[(i * 16) + 1];
                        matBindPose.m02 = matBonePose[(i * 16) + 2];
                        matBindPose.m03 = matBonePose[(i * 16) + 3];
                        matBindPose.m10 = matBonePose[(i * 16) + 4];
                        matBindPose.m11 = matBonePose[(i * 16) + 5];
                        matBindPose.m12 = matBonePose[(i * 16) + 6];
                        matBindPose.m13 = matBonePose[(i * 16) + 7];
                        matBindPose.m20 = matBonePose[(i * 16) + 8];
                        matBindPose.m21 = matBonePose[(i * 16) + 9];
                        matBindPose.m22 = matBonePose[(i * 16) + 10];
                        matBindPose.m23 = matBonePose[(i * 16) + 11];
                        matBindPose.m30 = matBonePose[(i * 16) + 12] * fGlobalScale;
                        matBindPose.m31 = matBonePose[(i * 16) + 13] * fGlobalScale;
                        matBindPose.m32 = matBonePose[(i * 16) + 14] * fGlobalScale;
                        matBindPose.m33 = matBonePose[(i * 16) + 15];
                        */
                        Transform bone = goTopAttachNode.transform.FindDeep(strBoneNodeNames[i]).transform;
                        bone.position = new Vector3(-fGlbTranslation[(i * 3) + 0] * fGlobalScale, fGlbTranslation[(i * 3) + 1] * fGlobalScale, fGlbTranslation[(i * 3) + 2] * fGlobalScale);
                        bone.rotation = new Quaternion(-fGlbRotation[(i * 4) + 0], fGlbRotation[(i * 4) + 1], fGlbRotation[(i * 4) + 2], -fGlbRotation[(i * 4) + 3]);
                        bone.localScale = new Vector3(fGlbScale[(i * 3) + 0], fGlbScale[(i * 3) + 1], fGlbScale[(i * 3) + 2]);
                        bones[i] = bone;
                        bindposes[i] = bones[i].worldToLocalMatrix;
                    }
                    //sSkinnedMeshRenderer.rootBone = goNode.transform;
                    sSkinnedMeshRenderer.bones = bones;
                    sSkinnedMeshRenderer.sharedMesh = sMesh;
                    sSkinnedMeshRenderer.sharedMesh.bindposes = bindposes;
                    //sSkinnedMeshRenderer.sharedMesh.RecalculateNormals();
                    //sSkinnedMeshRenderer.sharedMesh.RecalculateBounds();
                }
            }

            // Set Material
            SetMaterial(goNode);
        }
    }
Example #53
0
        public static void ToUnityMesh(this SharedMesh sharedMesh, Mesh mesh)
        {
            mesh.Clear();

            mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;

            UVector3[] vertices = new UVector3[sharedMesh.positions.Length];
            for (int i = 0; i < vertices.Length; i++)
            {
                vertices[i] = new UVector3((float)sharedMesh.positions[i].x, (float)sharedMesh.positions[i].y, (float)sharedMesh.positions[i].z);
            }

            mesh.vertices = vertices;

            if (sharedMesh.attributes != null)
            {
                for (int i = 0; i < sharedMesh.attributeDefinitions.Length; i++)
                {
                    if (sharedMesh.attributeDefinitions[i].type == AttributeType.Normals)
                    {
                        UVector3[] normals = new UVector3[sharedMesh.positions.Length];
                        for (int j = 0; j < sharedMesh.attributes.Count; j++)
                        {
                            NVector3F normal = sharedMesh.attributes[j].Get <NVector3F>(i);
                            normals[j] = new UVector3(normal.x, normal.y, normal.z);
                        }
                        mesh.normals = normals;
                    }
                    else if (sharedMesh.attributeDefinitions[i].type == AttributeType.UVs)
                    {
                        UVector2[] uvs = new UVector2[sharedMesh.positions.Length];
                        for (int j = 0; j < sharedMesh.attributes.Count; j++)
                        {
                            NVector2F uv = sharedMesh.attributes[j].Get <NVector2F>(i);
                            uvs[j] = new UVector2(uv.x, uv.y);
                        }
                        mesh.SetUVs(sharedMesh.attributeDefinitions[i].id, uvs);
                    }
                    else if (sharedMesh.attributeDefinitions[i].type == AttributeType.BoneWeights)
                    {
                        UBoneWeight[] boneWeights = new UBoneWeight[sharedMesh.positions.Length];
                        for (int j = 0; j < sharedMesh.attributes.Count; j++)
                        {
                            NBoneWeight boneWeight = sharedMesh.attributes[j].Get <NBoneWeight>(i);
                            boneWeights[j] = new UBoneWeight
                            {
                                boneIndex0 = boneWeight.index0,
                                boneIndex1 = boneWeight.index1,
                                boneIndex2 = boneWeight.index2,
                                boneIndex3 = boneWeight.index3,
                                weight0    = boneWeight.weight0,
                                weight1    = boneWeight.weight1,
                                weight2    = boneWeight.weight2,
                                weight3    = boneWeight.weight3,
                            };
                        }
                        mesh.boneWeights = boneWeights;
                    }
                }
            }

            mesh.triangles    = sharedMesh.triangles;
            mesh.subMeshCount = sharedMesh.groups.Length;

            for (int i = 0; i < sharedMesh.groups.Length; i++)
            {
                mesh.SetSubMesh(i, new UnityEngine.Rendering.SubMeshDescriptor(sharedMesh.groups[i].firstIndex, sharedMesh.groups[i].indexCount));
            }

            mesh.RecalculateTangents();
        }
Example #54
0
    public static GameObject BindSmoothSkin()
    {
        GameObject[] selection = Selection.gameObjects;
        List<Transform> selectedBones = new List<Transform>();
        List<GameObject> selectedMeshes= new List<GameObject>();
        List<GameObject> ffdControls= new List<GameObject>();

        foreach (GameObject Obj in selection)
        {
            if (Obj.GetComponent<SpriteRenderer>()== null)
            {
                if ((Obj.GetComponent<MeshRenderer>())||(Obj.GetComponent<SkinnedMeshRenderer>()))
                {
                    selectedMeshes.Add(Obj);
                }
                else
                {
                    Debug.LogWarning("Please select a mesh with a MeshRenderer, and some bones");
                    //return null;
                }

            }
            else if (Obj.GetComponent<SpriteRenderer>().sprite.name.Contains("Bone"))
            {
                if (Obj.GetComponent<SpriteRenderer>().sprite.name.Contains("ffdBone"))
                    ffdControls.Add(Obj);

                selectedBones.Add(Obj.transform);
                if (Obj.GetComponent<SpriteRenderer>().sprite.name.Contains("BoneScaled"))
                    Obj.GetComponent<SpriteRenderer>().sprite = Puppet2D_Editor.boneOriginal;

            }
            else
            {
                Debug.LogWarning("Please select a mesh with a MeshRenderer, not a sprite");
                //return null;
            }
        }
        if (selectedBones.Count == 0)
        {
            if (selectedMeshes.Count > 0)
            {
                if(EditorUtility.DisplayDialog("Detatch Skin?","Do you want to detatch the Skin From the bones?", "Detach", "Do Not Detach"))
                {
                    foreach (GameObject mesh in selectedMeshes)
                    {
                        SkinnedMeshRenderer smr = mesh.GetComponent<SkinnedMeshRenderer>();
                        if (smr)
                        {
                            Material mat = smr.sharedMaterial;
                            Undo.DestroyObjectImmediate(smr);
                            MeshRenderer mr = mesh.AddComponent<MeshRenderer>();
                            mr.sharedMaterial = mat;
                        }
                    }
                    return null;
                }

            }
            return null;
        }
        for (int i = selectedMeshes.Count - 1; i >= 0; i--)
        {
            // check to make sure its not a FFD mesh
            GameObject mesh = selectedMeshes[i];
            Puppet2D_FFDLineDisplay[] allFFDPointsInScene = Transform.FindObjectsOfType<Puppet2D_FFDLineDisplay>();
            bool isFFDMesh = false;
            foreach (Puppet2D_FFDLineDisplay ffdPoint in allFFDPointsInScene)
            {
                if (ffdPoint.outputSkinnedMesh && ffdPoint.outputSkinnedMesh.gameObject == mesh)
                {
                    ffdControls.Add(ffdPoint.gameObject);
                    selectedBones.Add(ffdPoint.transform);
                    isFFDMesh = true;
                }
            }
            if (isFFDMesh)
                selectedMeshes.Remove(mesh);
        }
        if ((ffdControls.Count > 0)&&selectedMeshes.Count==0 && ffdControls[0].GetComponent<Puppet2D_FFDLineDisplay>().outputSkinnedMesh)
        {
            GameObject preSkinnedMesh = new GameObject();
            MeshFilter mf = preSkinnedMesh.AddComponent<MeshFilter>();
            preSkinnedMesh.AddComponent<MeshRenderer>();
            Mesh mesh = new Mesh();
            ffdControls[0].GetComponent<Puppet2D_FFDLineDisplay>().outputSkinnedMesh.BakeMesh(mesh);
            mf.sharedMesh = mesh ;

            List<Object> newObjs = new List<Object>();
            foreach (Transform tr in selectedBones)
            {
                if(tr.GetComponent<SpriteRenderer>() && tr.GetComponent<SpriteRenderer>().sprite && !tr.GetComponent<SpriteRenderer>().sprite.name.Contains("ffd")&&!tr.GetComponent<Puppet2D_HiddenBone>())
                    newObjs.Add(tr.gameObject);
            }
            newObjs.Add(preSkinnedMesh);
            Selection.objects = newObjs.ToArray();
            GameObject newGO = BindSmoothSkin();
            foreach (GameObject go in ffdControls)
            {
                go.GetComponent<Puppet2D_FFDLineDisplay>().skinnedMesh = newGO.GetComponent<SkinnedMeshRenderer>();
                go.GetComponent<Puppet2D_FFDLineDisplay>().Init();
            }
            Undo.DestroyObjectImmediate(newGO);

            return preSkinnedMesh;
        }
        foreach (GameObject mesh in selectedMeshes)
        {

            Material mat = null;
            string sortingLayer = "";
            int sortingOrder = 0;
            if(mesh.GetComponent<MeshRenderer>()!=null )
            {
                mat = mesh.GetComponent<MeshRenderer>().sharedMaterial;

                sortingLayer = mesh.GetComponent<Renderer>().sortingLayerName;
                sortingOrder = mesh.GetComponent<Renderer>().sortingOrder;

                Undo.DestroyObjectImmediate(mesh.GetComponent<MeshRenderer>());
            }

            SkinnedMeshRenderer renderer = mesh.GetComponent<SkinnedMeshRenderer>();
            if(renderer == null)
                renderer = Undo.AddComponent<SkinnedMeshRenderer>(mesh);

            Puppet2D_SortingLayer puppet2D_SortingLayer = mesh.GetComponent<Puppet2D_SortingLayer>();
            if(puppet2D_SortingLayer != null)
                Undo.DestroyObjectImmediate(puppet2D_SortingLayer);

            Mesh sharedMesh = mesh.transform.GetComponent<MeshFilter>().sharedMesh;
            Vector3[] verts = sharedMesh.vertices;

            Matrix4x4[] bindPoses = new Matrix4x4[selectedBones.Count];

            List<Transform> closestBones =  new List<Transform>();
            closestBones.Clear();
            BoneWeight[] weights = new BoneWeight[verts.Length];
            int index = 0;
            int index2 = 0;
            int index3 = 0;

            for (int j = 0; j < weights.Length; j++)
            {
                float testdist = 1000000;
                float testdist2 = 1000000;
                for (int i = 0; i < selectedBones.Count; i++)
                {

                    Vector3 worldPt = mesh.transform.TransformPoint(verts[j]);

                    float dist = Vector2.Distance(new Vector2(selectedBones[i].GetComponent<Renderer>().bounds.center.x,selectedBones[i].GetComponent<Renderer>().bounds.center.y), new Vector2(worldPt.x,worldPt.y));

                    if (dist < testdist)
                    {
                        testdist = dist;
                        index = selectedBones.IndexOf(selectedBones[i]);

                    }

                    Transform bone = selectedBones[i];
                    bindPoses[i] = bone.worldToLocalMatrix * mesh.transform.localToWorldMatrix;
                }
                for (int i = 0; i < selectedBones.Count; i++)
                {
                    if(!(index==(selectedBones.IndexOf(selectedBones[i]))))
                    {
                        Vector3 worldPt = mesh.transform.TransformPoint(verts[j]);
                        float dist = Vector2.Distance(new Vector2(selectedBones[i].GetComponent<Renderer>().bounds.center.x,selectedBones[i].GetComponent<Renderer>().bounds.center.y), new Vector2(worldPt.x,worldPt.y));

                        if (dist < testdist2)
                        {
                            testdist2 = dist;
                            index2 = selectedBones.IndexOf(selectedBones[i]);

                        }
                    }

                }

                float combinedDistance = testdist+testdist2;
                float weight1 = (testdist/combinedDistance);
                float weight2 =  (testdist2/combinedDistance);
                weight1 = Mathf.Lerp(1, 0, weight1);
                weight2 = Mathf.Lerp(1, 0, weight2);

                weight1= Mathf.Clamp01((weight1+0.5f)*(weight1+0.5f)*(weight1+0.5f) - 0.5f);
                weight2= Mathf.Clamp01((weight2+0.5f)*(weight2+0.5f)*(weight2+0.5f) - 0.5f);

                if (Puppet2D_Editor._numberBonesToSkinToIndex == 1)
                {
                    renderer.quality = SkinQuality.Bone2;

                    weights [j].boneIndex0 = index;
                    weights [j].weight0 = weight1;
                    weights [j].boneIndex1 = index2;
                    weights [j].weight1 = weight2;
                }
                else if(Puppet2D_Editor._numberBonesToSkinToIndex == 2)
                {

                    Vector3 worldPt = mesh.transform.TransformPoint(verts[j]);
                    //Vector3 worldPt = verts[j];

                    renderer.quality = SkinQuality.Bone4;

                    if (ffdControls.Count == 0)
                    {
                        Debug.LogWarning("You must select some FFD controls to bind to");
                        return null;
                    }
                    if (ffdControls[0].GetComponent<Puppet2D_FFDLineDisplay>().outputSkinnedMesh == null || ffdControls[0].GetComponent<Puppet2D_FFDLineDisplay>().outputSkinnedMesh.sharedMesh == null)
                    {
                        Debug.LogWarning("You need the original FFD output mesh to copy skin weights. Make sure the outputSkinnedMesh is assigned to the ffdControl");
                        return null;
                    }
                    if (!ffdControls[0].transform.parent || !ffdControls[0].transform.parent.parent)
                    {
                        Debug.LogWarning("Your FFD Controls need a parent Group for offset");
                        return null;
                    }

                    int[] tris = ffdControls[0].GetComponent<Puppet2D_FFDLineDisplay>().outputSkinnedMesh.sharedMesh.triangles;
                    Vector3[] ffdMeshVerts = ffdControls[0].GetComponent<Puppet2D_FFDLineDisplay>().outputSkinnedMesh.sharedMesh.vertices;

                    bool insideTriangle = false;
                    for (int t =0; t<tris.Length-2; t+=3)
                    {
                        Vector3[] polygon = new Vector3[3];
                        polygon[0] = ffdControls[0].transform.parent.parent.TransformPoint(ffdMeshVerts[tris[t]]);
                        polygon[1] = ffdControls[0].transform.parent.parent.TransformPoint(ffdMeshVerts[tris[t+1]]);
                        polygon[2] = ffdControls[0].transform.parent.parent.TransformPoint(ffdMeshVerts[tris[t+2]]);

                        //Debug.Log(worldPt+" "+polygon[0]+" "+polygon[1]+" "+polygon[2]);
                        if (ContainsPoint(polygon, worldPt))
                        {
                            index = Puppet2D_FFD.GetIndexOfVector3(ffdControls,polygon[0] );
                            index2 = Puppet2D_FFD.GetIndexOfVector3(ffdControls,polygon[1] );
                            index3 = Puppet2D_FFD.GetIndexOfVector3(ffdControls,polygon[2] );
                            insideTriangle = true;
                        }

                    }
                    if(insideTriangle)
                    {
                        Vector3 weightBary = Barycentric(ffdControls[index].transform.position, ffdControls[index2].transform.position, ffdControls[index3].transform.position, worldPt);
                        //Debug.Log(ffdControls[index] + " " + ffdControls[index2] + " " + ffdControls[index3]);
                        //if (index != -1 && weights[j].weight0 > 0)
                        {
                            weights[j].boneIndex0 = index;
                            weights[j].weight0 = weightBary.z;
                        }
                        //if (index2 != -1 && weights[j].weight1 > 0)
                        {
                            weights[j].boneIndex1 = index2;
                            weights[j].weight1 = weightBary.x;
                        }
                        //if (index3 != -1 && weights[j].weight2 > 0)
                        {
                            weights[j].boneIndex2 = index3;
                            weights[j].weight2 = weightBary.y;
                        }

                    }
                    else
                    {
                        weights [j].boneIndex0 = 0;
                        weights [j].weight0 = 1;

                    }

                }
                else
                {
                    renderer.quality = SkinQuality.Bone1;

                    weights [j].boneIndex0 = index;
                    weights [j].weight0 = 1;

                }

            }

            sharedMesh.boneWeights = weights;

            sharedMesh.bindposes = bindPoses;

            renderer.bones = selectedBones.ToArray();

            renderer.sharedMesh = sharedMesh;
            if(mat)
                renderer.sharedMaterial = mat;

            renderer.sortingLayerName = sortingLayer;
            renderer.sortingOrder = sortingOrder;
            mesh.AddComponent<Puppet2D_SortingLayer>();

            sharedMesh.colors = new Color[sharedMesh.vertices.Length];
            EditorUtility.SetDirty(mesh);
            EditorUtility.SetDirty(sharedMesh);
            AssetDatabase.SaveAssets();
            EditorApplication.SaveAssets();

        }
        foreach (Transform bone in selectedBones)
        {
            if (bone.GetComponent<SpriteRenderer> ().sprite.name=="Bone")
                bone.GetComponent<SpriteRenderer> ().sprite = Puppet2D_Editor.boneSprite;
        }
        if (selectedMeshes.Count > 0)
        {
            return selectedMeshes[0];
        }
        else
            return null;

        //FinishEditingWeights();
    }
 static public int get_boneIndex3(IntPtr l)
 {
     UnityEngine.BoneWeight o = (UnityEngine.BoneWeight)checkSelf(l);
     pushValue(l, o.boneIndex3);
     return(1);
 }
Example #56
0
        public static void UpdateAssets(SpriteMesh spriteMesh, SpriteMeshData spriteMeshData)
        {
            if (spriteMesh && spriteMeshData)
            {
                string spriteMeshPath = AssetDatabase.GetAssetPath(spriteMesh);

                SerializedObject   spriteMeshSO   = new SerializedObject(spriteMesh);
                SerializedProperty sharedMeshProp = spriteMeshSO.FindProperty("m_SharedMesh");

                if (!spriteMesh.sharedMesh)
                {
                    Mesh mesh = new Mesh();
                    mesh.hideFlags = HideFlags.HideInHierarchy;
                    AssetDatabase.AddObjectToAsset(mesh, spriteMeshPath);

                    spriteMeshSO.Update();
                    sharedMeshProp.objectReferenceValue = mesh;
                    spriteMeshSO.ApplyModifiedProperties();
                    EditorUtility.SetDirty(mesh);
                }

                spriteMesh.sharedMesh.name = spriteMesh.name;

                spriteMeshData.hideFlags = HideFlags.HideInHierarchy;
                EditorUtility.SetDirty(spriteMeshData);

                int width  = 0;
                int height = 0;

                GetSpriteTextureSize(spriteMesh.sprite, ref width, ref height);

                Vector3[] vertices = GetMeshVertices(spriteMesh.sprite, spriteMeshData);

                Vector2 textureWidthHeightInv = new Vector2(1f / width, 1f / height);

                Vector2[] uvs = (new List <Vector2>(spriteMeshData.vertices)).ConvertAll(v => Vector2.Scale(v, textureWidthHeightInv)).ToArray();

                Vector3[] normals = (new List <Vector3>(vertices)).ConvertAll(v => Vector3.back).ToArray();

                BoneWeight[] boneWeightsData = spriteMeshData.boneWeights;

                if (boneWeightsData.Length != spriteMeshData.vertices.Length)
                {
                    boneWeightsData = new BoneWeight[spriteMeshData.vertices.Length];
                }

                List <UnityEngine.BoneWeight> boneWeights = new List <UnityEngine.BoneWeight>(boneWeightsData.Length);

                List <float> verticesOrder = new List <float>(spriteMeshData.vertices.Length);

                for (int i = 0; i < boneWeightsData.Length; i++)
                {
                    BoneWeight boneWeight = boneWeightsData[i];

                    List <KeyValuePair <int, float> > pairs = new List <KeyValuePair <int, float> >();
                    pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex0, boneWeight.weight0));
                    pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex1, boneWeight.weight1));
                    pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex2, boneWeight.weight2));
                    pairs.Add(new KeyValuePair <int, float>(boneWeight.boneIndex3, boneWeight.weight3));

                    pairs = pairs.OrderByDescending(s => s.Value).ToList();

                    UnityEngine.BoneWeight boneWeight2 = new UnityEngine.BoneWeight();
                    boneWeight2.boneIndex0 = Mathf.Max(0, pairs[0].Key);
                    boneWeight2.boneIndex1 = Mathf.Max(0, pairs[1].Key);
                    boneWeight2.boneIndex2 = Mathf.Max(0, pairs[2].Key);
                    boneWeight2.boneIndex3 = Mathf.Max(0, pairs[3].Key);
                    boneWeight2.weight0    = pairs[0].Value;
                    boneWeight2.weight1    = pairs[1].Value;
                    boneWeight2.weight2    = pairs[2].Value;
                    boneWeight2.weight3    = pairs[3].Value;

                    boneWeights.Add(boneWeight2);

                    float vertexOrder = i;

                    if (spriteMeshData.bindPoses.Length > 0)
                    {
                        vertexOrder = spriteMeshData.bindPoses[boneWeight2.boneIndex0].zOrder * boneWeight2.weight0 +
                                      spriteMeshData.bindPoses[boneWeight2.boneIndex1].zOrder * boneWeight2.weight1 +
                                      spriteMeshData.bindPoses[boneWeight2.boneIndex2].zOrder * boneWeight2.weight2 +
                                      spriteMeshData.bindPoses[boneWeight2.boneIndex3].zOrder * boneWeight2.weight3;
                    }

                    verticesOrder.Add(vertexOrder);
                }

                List <WeightedTriangle> weightedTriangles = new List <WeightedTriangle>(spriteMeshData.indices.Length / 3);

                for (int i = 0; i < spriteMeshData.indices.Length; i += 3)
                {
                    int p1 = spriteMeshData.indices[i];
                    int p2 = spriteMeshData.indices[i + 1];
                    int p3 = spriteMeshData.indices[i + 2];

                    weightedTriangles.Add(new WeightedTriangle(p1, p2, p3,
                                                               verticesOrder[p1],
                                                               verticesOrder[p2],
                                                               verticesOrder[p3]));
                }

                weightedTriangles = weightedTriangles.OrderBy(t => t.weight).ToList();

                List <int> indices = new List <int>(spriteMeshData.indices.Length);

                for (int i = 0; i < weightedTriangles.Count; ++i)
                {
                    WeightedTriangle t = weightedTriangles[i];
                    indices.Add(t.p1);
                    indices.Add(t.p2);
                    indices.Add(t.p3);
                }

                List <Matrix4x4> bindposes = (new List <BindInfo>(spriteMeshData.bindPoses)).ConvertAll(p => p.bindPose);

                for (int i = 0; i < bindposes.Count; i++)
                {
                    Matrix4x4 bindpose = bindposes [i];

                    bindpose.m23 = 0f;

                    bindposes[i] = bindpose;
                }

                spriteMesh.sharedMesh.Clear();
                spriteMesh.sharedMesh.vertices    = vertices;
                spriteMesh.sharedMesh.uv          = uvs;
                spriteMesh.sharedMesh.triangles   = indices.ToArray();
                spriteMesh.sharedMesh.normals     = normals;
                spriteMesh.sharedMesh.boneWeights = boneWeights.ToArray();
                spriteMesh.sharedMesh.bindposes   = bindposes.ToArray();
                spriteMesh.sharedMesh.RecalculateBounds();
#if UNITY_5_6_OR_NEWER
                spriteMesh.sharedMesh.RecalculateTangents();
#endif
                RebuildBlendShapes(spriteMesh);
            }
        }
Example #57
0
 public Boolean UnityEngine.BoneWeight::op_Inequality(UnityEngine.BoneWeight,UnityEngine.BoneWeight)