static public int EnsureQuaternionContinuity(IntPtr l)
 {
     try{
         UnityEngine.AnimationClip self = (UnityEngine.AnimationClip)checkSelf(l);
         self.EnsureQuaternionContinuity();
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
 static public int EnsureQuaternionContinuity(IntPtr l)
 {
     try {
         UnityEngine.AnimationClip self = (UnityEngine.AnimationClip)checkSelf(l);
         self.EnsureQuaternionContinuity();
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
		private void SetCurves (Transform child, SpatialInfo defaultInfo, List<TimeLineKey> parentTimeline, TimeLine timeLine, AnimationClip clip, Animation animation, ref float defaultZ) {
			var childPath = GetPathToChild (child);
			foreach (var kvPair in GetCurves (timeLine, defaultInfo, parentTimeline)) { //Makes sure that curves are only added for properties 
				switch (kvPair.Key) {									//that actually mutate in the animation
				case ChangedValues.PositionX :
					SetKeys (kvPair.Value, timeLine, x => x.x, animation);
					clip.SetCurve (childPath, typeof(Transform), "localPosition.x", kvPair.Value);
					break;
				case ChangedValues.PositionY :
					SetKeys (kvPair.Value, timeLine, x => x.y, animation);
					clip.SetCurve (childPath, typeof(Transform), "localPosition.y", kvPair.Value);
					break;
				case ChangedValues.PositionZ :
					kvPair.Value.AddKey (0f, defaultZ);
					clip.SetCurve (childPath, typeof(Transform), "localPosition.z", kvPair.Value);
					defaultZ = inf; //Lets the next method know this value has been set
					break;
				case ChangedValues.RotationZ :
					SetKeys (kvPair.Value, timeLine, x => x.rotation.z, animation);
					clip.SetCurve (childPath, typeof(Transform), "localRotation.z", kvPair.Value);
					break;
				case ChangedValues.RotationW :
					SetKeys (kvPair.Value, timeLine, x => x.rotation.w, animation);
					clip.SetCurve (childPath, typeof(Transform), "localRotation.w", kvPair.Value);
					break;
				case ChangedValues.ScaleX :
					SetKeys (kvPair.Value, timeLine, x => x.scale_x, animation);
					clip.SetCurve (childPath, typeof(Transform), "localScale.x", kvPair.Value);
					break;
				case ChangedValues.ScaleY :
					SetKeys (kvPair.Value, timeLine, x => x.scale_y, animation);
					clip.SetCurve (childPath, typeof(Transform), "localScale.y", kvPair.Value);
					break;
				case ChangedValues.ScaleZ :
					kvPair.Value.AddKey (0f, 1f);
					clip.SetCurve (childPath, typeof(Transform), "localScale.z", kvPair.Value);
					break;
				case ChangedValues.Alpha :
					SetKeys (kvPair.Value, timeLine, x => x.a, animation);
					clip.SetCurve (childPath, typeof(SpriteRenderer), "m_Color.a", kvPair.Value);
					break;
				case ChangedValues.Sprite :
					var swapper = child.GetComponent<TextureController> ();
					if (swapper == null) { //Add a Texture Controller if one doesn't already exist
						swapper = child.gameObject.AddComponent<TextureController> ();
						var info = (SpriteInfo)defaultInfo;
						swapper.Sprites = new[] {Folders [info.folder] [info.file]};
					}
					SetKeys (kvPair.Value, timeLine, ref swapper.Sprites, animation);
					clip.SetCurve (childPath, typeof(TextureController), "DisplayedSprite", kvPair.Value);
					break;
				}
			}
			clip.EnsureQuaternionContinuity ();
		}
Example #4
0
        private static UnityEngine.AnimationClip Convert(Clip animation, FrameContainer frames,
                                                         out UVector3 rootStart, out UVector3 rootEnd)
        {
            var clip = new UnityEngine.AnimationClip();

            clip.legacy = true;

            var rotateAxes = new[] {
                new { Name = "x", Mask = new UVector4(1f, 0f, 0f, 0f) },
                new { Name = "y", Mask = new UVector4(0f, 1f, 0f, 0f) },
                new { Name = "z", Mask = new UVector4(0f, 0f, 1f, 0f) },
                new { Name = "w", Mask = new UVector4(0f, 0f, 0f, 1f) }
            };

            var translateAxes = new[] {
                new { Name = "x", Mask = new UVector3(1f, 0f, 0f) },
                new { Name = "y", Mask = new UVector3(0f, 1f, 0f) },
                new { Name = "z", Mask = new UVector3(0f, 0f, 1f) },
            };

            var root = animation.Bones.FirstOrDefault(x => x.BoneId == 0);

            if (root != null && root.FrameCount > 0)
            {
                rootStart = Types.Convert(root.Frames.First().Translation);
                rootEnd   = Types.Convert(root.Frames.Last().Translation);
            }
            else
            {
                rootStart = rootEnd = UVector3.zero;
            }

            foreach (var bone in animation.Bones)
            {
                var bFrames = bone.Frames;
                var frame   = frames.GetByBoneId(bone.BoneId);

                string bonePath = frame.Path;

                var axisAngle = bFrames.ToDictionary(x => x, x =>
                {
                    var q = Types.Convert(x.Rotation);
                    float ang; UnityEngine.Vector3 axis;
                    q.ToAngleAxis(out ang, out axis);
                    return(new UVector4(q.x, q.y, q.z, q.w));
                });

                foreach (var axis in rotateAxes)
                {
                    var keys = bFrames
                               .Select(x => new Keyframe(x.Time * TimeScale,
                                                         UVector4.Dot(axisAngle[x], axis.Mask)))
                               .ToArray();

                    clip.SetCurve(bonePath, typeof(Transform), "localRotation." + axis.Name,
                                  new UnityEngine.AnimationCurve(keys));
                }

                var converted = bFrames.Select(x => Types.Convert(x.Translation)).ToArray();

                if (!converted.Any(x => !x.Equals(UVector3.zero)))
                {
                    continue;
                }

                var anyVelocities = false;
                var deltaVals     = converted.Select((x, i) =>
                {
                    var prev = Math.Max(0, i - 1);
                    var next = Math.Min(i + 1, converted.Length - 1);

                    var prevTime = bFrames[prev].Time * TimeScale;
                    var nextTime = bFrames[next].Time * TimeScale;

                    return(prevTime == nextTime || !(anyVelocities = true) ? UVector3.zero
                        : (converted[next] - converted[prev]) / (nextTime - prevTime));
                }).ToArray();

                foreach (var translateAxis in translateAxes)
                {
                    var positions = bFrames
                                    .Select((x, i) => new Keyframe(x.Time * TimeScale,
                                                                   UVector3.Dot(frame.transform.localPosition + converted[i], translateAxis.Mask)))
                                    .ToArray();

                    var deltas = bFrames.Select((x, i) => new Keyframe(x.Time * TimeScale,
                                                                       UVector3.Dot(deltaVals[i], translateAxis.Mask))).ToArray();

                    clip.SetCurve(bonePath, typeof(Transform), "localPosition." + translateAxis.Name,
                                  new UnityEngine.AnimationCurve(positions));

                    if (!anyVelocities)
                    {
                        continue;
                    }

                    clip.SetCurve(bonePath, typeof(BFrame), "LocalVelocity." + translateAxis.Name,
                                  new UnityEngine.AnimationCurve(deltas));
                }
            }

            clip.wrapMode = WrapMode.Loop;
            clip.EnsureQuaternionContinuity();

            return(clip);
        }
    private void Run()
    {
        string fileData = File.ReadAllText (json_location);
        JSONObject data = new JSONObject (fileData);

        Uri assetsPath = new Uri (Application.dataPath);
        Uri jsonPath = new Uri (System.IO.Path.GetDirectoryName (json_location));
        Uri diff = assetsPath.MakeRelativeUri (jsonPath);
        string wd = diff.OriginalString+System.IO.Path.DirectorySeparatorChar;

        //test data
        if(!data.HasFields(new string[]{"framerate","images","frames","animations"}))
        {
            Debug.LogError("Error: json file must contain framerate, images, frames, and animations.");
            return;
        }

        //generate sprite frames
        List<JSONObject> frames_data = data.GetField ("frames").list;
        List<JSONObject> images_data = data.GetField ("images").list;

        // load textures
        List<Texture2D> images = new List<Texture2D>();
        List<List<SpriteMetaData>> sprite_metadata = new List<List<SpriteMetaData>> ();
        for(int i=0; i<images_data.Count; i++)
        {
            string path = wd+images_data[i].str;
            Texture2D tex = AssetDatabase.LoadMainAssetAtPath(path) as Texture2D;
            images.Add(tex);
            sprite_metadata.Add (new List<SpriteMetaData> ());
        }

        //set meta data based on frames
        for(int i=0; i<frames_data.Count; i++)
        {
            List<JSONObject> frame = frames_data[i].list;
            float x = frame[0].f;
            float y = frame[1].f;
            float w = frame[2].f;
            float h = frame[3].f;
            int img = (int)frame[4].f;
            float rx = frame[5].f;
            float ry = frame[6].f;

            float imgHeight = (float)images[img].height;

            SpriteMetaData meta = new SpriteMetaData{
                alignment = (int)SpriteAlignment.Custom,
                border = new Vector4(),
                name = prefix+"_"+(i).ToString(),
                pivot = new Vector2(rx/w,1-(ry/h)),
                rect = new Rect(x, imgHeight - y - h, w, h)
            };
            sprite_metadata[img].Add(meta);
        }

        //save data back
        for(int i=0; i<images.Count; i++)
        {
            TextureImporter importer = TextureImporter.GetAtPath(wd+images_data[i].str) as TextureImporter;
            //importer.assetPath = images_data[i].str;
            importer.mipmapEnabled = false;
            importer.textureType = TextureImporterType.Sprite;
            importer.spriteImportMode = SpriteImportMode.Multiple;
            importer.spritesheet = sprite_metadata[i].ToArray();

            try
            {
                AssetDatabase.StartAssetEditing();
                AssetDatabase.ImportAsset(importer.assetPath);
            }
            finally
            {
                AssetDatabase.StopAssetEditing();
            }
        }

        //load sprite dictionary
        Dictionary<String,Sprite> sprites = new Dictionary<string, Sprite> ();
        for(int i=0; i<images_data.Count; i++)
        {
            Sprite[] sp = AssetDatabase.LoadAllAssetsAtPath( wd+images_data[i].str ).OfType<Sprite>().ToArray();
            for(int j=0; j<sp.Length; j++)
            {
                sprites[sp[j].name] = sp[j];
            }
        }

        //create animations
        int fps = (int)data.GetField ("framerate").f;
        List<string> animation_names = data.GetField ("animations").keys;

        foreach(string animationName in animation_names)
        {
            JSONObject animationJson = data.GetField("animations").GetField(animationName);
            List<JSONObject> frame_Data = animationJson.GetField("frames").list;
            float fpsinc = 1/(float)fps;

            EditorCurveBinding curveBinding = new EditorCurveBinding();
            curveBinding.type = typeof(SpriteRenderer);
            curveBinding.path = "";
            curveBinding.propertyName = "m_Sprite";

            List<ObjectReferenceKeyframe> keyframes = new List<ObjectReferenceKeyframe>();
            string lastFrame = "";
            for(int i=0; i<frame_Data.Count; i++)
            {
                string fname = frame_Data[i].f.ToString();
                if(i == frame_Data.Count-1 || fname!=lastFrame)
                {
                    ObjectReferenceKeyframe k = new ObjectReferenceKeyframe();
                    k.time = i*fpsinc;
                    k.value = sprites[prefix+"_"+fname];
                    keyframes.Add(k);
                    lastFrame = fname;
                }
            }

            AnimationClip clip = new AnimationClip();
            clip.frameRate = (float)fps;
            clip.legacy = false;
            clip.EnsureQuaternionContinuity();

            AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyframes.ToArray());

            //load asset if it exists, else create new
            AnimationClip a = AssetDatabase.LoadAssetAtPath<AnimationClip>(wd + animationName + ".anim");
            if(a!= null)
            {
                Debug.Log("update clip");
                clip.wrapMode = a.wrapMode;
                a = clip;
            } else
            {
                AssetDatabase.CreateAsset(clip, wd + animationName + ".anim");
            }
        }
        AssetDatabase.SaveAssets();
    }
    protected AnimationClip BuildAnimationClip()
    {
        clip = new AnimationClip ();
        clip.wrapMode = WrapMode.Loop;

        //populate dictionaries with curves
        RotationWCurves.Clear ();
        RotationXCurves.Clear ();
        RotationYCurves.Clear ();
        RotationZCurves.Clear ();
        PositionXCurves.Clear ();
        PositionYCurves.Clear ();
        PositionZCurves.Clear ();
        foreach (string animationName in AnimationNames.Values)
        {
            RotationWCurves.Add (animationName, new AnimationCurve ());
            RotationXCurves.Add (animationName, new AnimationCurve ());
            RotationYCurves.Add (animationName, new AnimationCurve ());
            RotationZCurves.Add (animationName, new AnimationCurve ());

            PositionXCurves.Add (animationName, new AnimationCurve ());
            PositionYCurves.Add (animationName, new AnimationCurve ());
            PositionZCurves.Add (animationName, new AnimationCurve ());
        }

        //populate curves with keyframe values
        foreach (var keyframe in Keyframes)
        {
            foreach (string animationName in AnimationNames.Values)
            {
                RotationWCurves [animationName].AddKey (keyframe.Time, keyframe.GetValue (animationName, KAS_ValueType.RotW));
                RotationXCurves [animationName].AddKey (keyframe.Time, keyframe.GetValue (animationName, KAS_ValueType.RotX));
                RotationYCurves [animationName].AddKey (keyframe.Time, keyframe.GetValue (animationName, KAS_ValueType.RotY));
                RotationZCurves [animationName].AddKey (keyframe.Time, keyframe.GetValue (animationName, KAS_ValueType.RotZ));
                PositionXCurves [animationName].AddKey (keyframe.Time, keyframe.GetValue (animationName, KAS_ValueType.PosX));
                PositionYCurves [animationName].AddKey (keyframe.Time, keyframe.GetValue (animationName, KAS_ValueType.PosY));
                PositionZCurves [animationName].AddKey (keyframe.Time, keyframe.GetValue (animationName, KAS_ValueType.PosZ));
            }
        }

        //set curves to clip
        foreach (string animationName in AnimationNames.Values)
        {
            clip.SetCurve (animationName, typeof(Transform), "localRotation.w", RotationWCurves [animationName]);
            clip.SetCurve (animationName, typeof(Transform), "localRotation.x", RotationXCurves [animationName]);
            clip.SetCurve (animationName, typeof(Transform), "localRotation.y", RotationYCurves [animationName]);
            clip.SetCurve (animationName, typeof(Transform), "localRotation.z", RotationZCurves [animationName]);

            clip.SetCurve (animationName, typeof(Transform), "localPosition.x", PositionXCurves [animationName]);
            clip.SetCurve (animationName, typeof(Transform), "localPosition.y", PositionYCurves [animationName]);
            clip.SetCurve (animationName, typeof(Transform), "localPosition.z", PositionZCurves [animationName]);
        }

        clip.EnsureQuaternionContinuity ();
        return clip;
    }
		/**
	     * @brief Stores the current clip into a Unity .anim file
	     * Important: If you use your own character with blend shapes, you have to make sure it is
	     * set to 'legacy' animation type. You can do this by the following steps in Unity3D:
	     * 1. In the 'project' window in the Assets hierarchy, click on your fbx model
	     * 2. In the Inspector, you should see now the Import Settings of your model.
	     * 3. Select in these Import Settings in the 'Rig' tab for the 'Animation Type' the value 'Legacy'
	     */ 
		public AnimationClip GetClipAsAnim(string path) {

			bool have_t_pose = false; 
			if (m_TPose != null && m_TPose.m_joints != null) {
				if (m_TPose.m_joints.Count != m_GameObjectTransformations.Count) {
					Debug.LogError ("tpose and model do not have the same number of transformations (" + m_TPose.m_joints.Count + "!=" 
					                + m_GameObjectTransformations.Count + ")");
					return null;
				}
				have_t_pose = true;
			} else {
				Debug.LogWarning ("tpose missing");
			}
			
			AnimationClip animation_clip = new AnimationClip();
			
			// Not all of them might actually be used, since not all of them might be a target
			AnimationCurve [] translation_x_curves = new AnimationCurve[m_GameObjectTransformations.Count];
			AnimationCurve [] translation_y_curves = new AnimationCurve[m_GameObjectTransformations.Count];
			AnimationCurve [] translation_z_curves = new AnimationCurve[m_GameObjectTransformations.Count];
			AnimationCurve [] rotation_x_curves = new AnimationCurve[m_GameObjectTransformations.Count];
			AnimationCurve [] rotation_y_curves = new AnimationCurve[m_GameObjectTransformations.Count];
			AnimationCurve [] rotation_z_curves = new AnimationCurve[m_GameObjectTransformations.Count];
			AnimationCurve [] rotation_w_curves = new AnimationCurve[m_GameObjectTransformations.Count];
			AnimationCurve [] bs_curves = new AnimationCurve[m_GameObjectBlendshapes.Count];
			
			Clip clip = m_clip.Duplicate();
			if (m_normalize_headpose) clip.NormalizeHeadPoseAllClip();
			
			Debug.Log("nr of clip states: " + clip.NumStates());
			for (int frame_nr = 0; frame_nr < clip.NumStates(); frame_nr++) {
				if (!clip[frame_nr].TrackingSuccessful()) {
					Debug.Log("skipping clip state");
					continue;
				}
				
				// get frame time
				float time = (float)(clip[frame_nr].Timestamp() - clip[0].Timestamp()) * 0.001f; // time is in ms
				
				// evaluate transformation
				TransformationValue [] transformation_values = null;
				if (have_t_pose) {
					transformation_values = Utils.EvaluateTargetTransformations(m_Retargeting, clip.Rig(), clip[frame_nr], m_TPose.m_joints);
				} else {
					transformation_values = Utils.EvaluateTargetTransformations(m_Retargeting, clip.Rig(), clip[frame_nr], m_GameObjectTransformations);
				}
				
				int key_index = -1;
				if (transformation_values.Length == m_GameObjectTransformations.Count) {
					for (int index = 0; index < transformation_values.Length; index++) {
						// Apply the value for this target
						if (transformation_values[index] != null) {
							// Apply the translation value for this target
							if (translation_x_curves[index] == null) {
								translation_x_curves[index] = new AnimationCurve();
								translation_y_curves[index] = new AnimationCurve();
								translation_z_curves[index] = new AnimationCurve();
							}
							key_index = translation_x_curves[index].AddKey(time, transformation_values[index].m_translation.x);
							if (key_index < 0) Debug.LogError("Could not add key at time " + time);
							key_index = translation_y_curves[index].AddKey(time, transformation_values[index].m_translation.y);
							if (key_index < 0) Debug.LogError("Could not add key at time " + time);
							key_index = translation_z_curves[index].AddKey(time, transformation_values[index].m_translation.z);
							if (key_index < 0) Debug.LogError("Could not add key at time " + time);
							
							if (rotation_x_curves[index] == null) {
								rotation_x_curves[index] = new AnimationCurve();
								rotation_y_curves[index] = new AnimationCurve();
								rotation_z_curves[index] = new AnimationCurve();
								rotation_w_curves[index] = new AnimationCurve();
							}
							// Add to curve for the animation
							key_index = rotation_x_curves[index].AddKey(time, transformation_values[index].m_rotation.x);
							if (key_index < 0) Debug.LogError("Could not add key at time " + time);
							key_index = rotation_y_curves[index].AddKey(time, transformation_values[index].m_rotation.y);
							if (key_index < 0) Debug.LogError("Could not add key at time " + time);
							key_index = rotation_z_curves[index].AddKey(time, transformation_values[index].m_rotation.z);
							if (key_index < 0) Debug.LogError("Could not add key at time " + time);
							key_index = rotation_w_curves[index].AddKey(time, transformation_values[index].m_rotation.w);
							if (key_index < 0) Debug.LogError("Could not add key at time " + time);
						}
					}
				} else {
					Debug.LogError("Cannot create transformation as evaluated shape size is incorrect");
				}
				
				// evaluate blendshapes
				BlendshapeValue [] blendshape_values = Utils.EvaluateTargetBlendshapes(m_Retargeting, clip.Rig(), clip[frame_nr], m_GameObjectBlendshapes);
				
				if (blendshape_values.Length == m_GameObjectBlendshapes.Count) {
					for (int index = 0; index < m_GameObjectBlendshapes.Count; index++) {
						// Apply the value for this target
						if (blendshape_values[index] != null) {
							if (bs_curves[index] == null) {
								bs_curves[index] = new AnimationCurve();
							}
							bs_curves[index].AddKey(time, (float)blendshape_values[index].m_value);
						}
					}
				} else {
					Debug.LogError("Cannot create blendshapes as evaluated shape size is incorrect");
				}
			}
			
			// Set all transformation curves for all transformations that are animated
			for (int target_nr = 0; target_nr < m_GameObjectTransformations.Count; target_nr++) {
				// Extract path:
				string path_to_transformation = ((TransformationInformation)m_GameObjectTransformations[target_nr]).transformPath;
				// Apply translation curve, if there is one
				if (translation_x_curves[target_nr] != null) {
					animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localPosition.x", translation_x_curves[target_nr]);
					animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localPosition.y", translation_y_curves[target_nr]);
					animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localPosition.z", translation_z_curves[target_nr]);
				}
				// Apply rotation curve, if there is one
				if (rotation_x_curves[target_nr] != null) {
					animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localRotation.x", rotation_x_curves[target_nr]);
					animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localRotation.y", rotation_y_curves[target_nr]);
					animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localRotation.z", rotation_z_curves[target_nr]);
					animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localRotation.w", rotation_w_curves[target_nr]);
				}
			}
			
			// Without this, there are some weird jumps (rotation) in the animation:
			animation_clip.EnsureQuaternionContinuity();
			
			// Set all blendshape curves for all blendshapes that are animated
			for (int i = 0; i < m_GameObjectBlendshapes.Count; i++) {
				if (bs_curves[i] != null) {
					BlendshapeInfo bs_info = (BlendshapeInfo)(m_GameObjectBlendshapes[i]);
					// Debug.Log("bs_curves[" + i + "].length=" + bs_curves[i].length);
					string bs_path = bs_info.m_path;
					string bs_name = bs_info.m_name;
					animation_clip.SetCurve(bs_path, typeof(SkinnedMeshRenderer), "blendShape." + bs_name, bs_curves[i]);
				}
			}
			
			Debug.Log ("Animation clip = " + animation_clip.length);
			
			// animation clip asset 
			string animation_name = Path.GetFileNameWithoutExtension(path);
			animation_clip.name = animation_name;
			AnimationEvent animation_event = new AnimationEvent();
			animation_event.functionName = "AnimationClipEventCallback";
			animation_event.time = animation_clip.length;
			#if UNITY_EDITOR
			AnimationEvent[] animation_events = { animation_event };
			AnimationUtility.SetAnimationEvents(animation_clip, animation_events);
			AssetDatabase.CreateAsset(animation_clip, path);
			#endif
			
			Debug.Log("Wrote animation with length " + (1000.0 * animation_clip.length) + " milliseconds");
			return animation_clip;
		}
Example #8
0
 public static AnimationClip metcreatetransitionanimation(Transform varpsource, string varptargetanimname, float varptransitiontime, string varpnewanimationname, ref Vector3 varprootnormalizer, clsurganimationstatesmanager varpanimationstatemanager = null, bool varppositioncurves = false)
 {
     if (varpanimationstatemanager == null)
     {
         varpanimationstatemanager = varpsource.root.GetComponentInChildren<clsurganimationstatesmanager>();
         if (varpanimationstatemanager == null)
         {
             Debug.Log("No animation states manager in the source");
             return null;
         }
     }
     int num = varpanimationstatemanager.vargamstatenames.IndexOf(varptargetanimname);
     if (num < 0)
     {
         Debug.LogError("Animation state not memorized in manager");
         return null;
     }
     if (varpanimationstatemanager.vargamrootname != varpsource.name)
     {
         Debug.LogWarning(string.Concat(new string[]
         {
             "The animation states root is different than the source passed in. Unexpected behavior may occur [passed ",
             varpsource.name,
             " expected ",
             varpanimationstatemanager.vargamrootname,
             "]"
         }));
     }
     AnimationClip animationClip = new AnimationClip();
     AnimationCurve curve = new AnimationCurve();
     AnimationCurve curve2 = new AnimationCurve();
     AnimationCurve curve3 = new AnimationCurve();
     AnimationCurve curve4 = new AnimationCurve();
     AnimationCurve curve5 = new AnimationCurve();
     AnimationCurve curve6 = new AnimationCurve();
     AnimationCurve curve7 = new AnimationCurve();
     animationClip.name = varpnewanimationname;
     varprootnormalizer = varpanimationstatemanager.vargamrootoriginallocalposition;
     Transform[] componentsInChildren = varpsource.GetComponentsInChildren<Transform>();
     if (componentsInChildren.Length != varpanimationstatemanager.vargamanimationstates[num].propanimationstate.Length)
     {
         Debug.LogError(string.Concat(new object[]
         {
             "Source and state body parts length missmatch. Can't continue [",
             componentsInChildren.Length,
             " - ",
             varpanimationstatemanager.vargamanimationstates[num].propanimationstate.Length,
             "]"
         }));
         return null;
     }
     varptransitiontime -= varptransitiontime / 24f;
     for (int i = 0; i < varpanimationstatemanager.vargamanimationstates[num].propanimationstate.Length; i++)
     {
         Vector3 localPosition = componentsInChildren[i].localPosition;
         Vector3 propposition = varpanimationstatemanager.vargamanimationstates[num].propanimationstate[i].propposition;
         if (localPosition != propposition)
         {
             curve = AnimationCurve.EaseInOut(0f, localPosition.x, varptransitiontime, propposition.x);
             curve2 = AnimationCurve.EaseInOut(0f, localPosition.y, varptransitiontime, propposition.y);
             curve3 = AnimationCurve.EaseInOut(0f, localPosition.z, varptransitiontime, propposition.z);
             animationClip.SetCurve(varpanimationstatemanager.vargamanimationstates[num].propanimationstate[i].proppath, typeof(Transform), "localPosition.x", curve);
             animationClip.SetCurve(varpanimationstatemanager.vargamanimationstates[num].propanimationstate[i].proppath, typeof(Transform), "localPosition.y", curve2);
             animationClip.SetCurve(varpanimationstatemanager.vargamanimationstates[num].propanimationstate[i].proppath, typeof(Transform), "localPosition.z", curve3);
         }
         Quaternion localRotation = componentsInChildren[i].localRotation;
         Quaternion proprotation = varpanimationstatemanager.vargamanimationstates[num].propanimationstate[i].proprotation;
         if (localRotation != proprotation)
         {
             curve4 = AnimationCurve.Linear(0f, localRotation.x, varptransitiontime, proprotation.x);
             curve5 = AnimationCurve.Linear(0f, localRotation.y, varptransitiontime, proprotation.y);
             curve6 = AnimationCurve.Linear(0f, localRotation.z, varptransitiontime, proprotation.z);
             curve7 = AnimationCurve.Linear(0f, localRotation.w, varptransitiontime, proprotation.w);
             animationClip.SetCurve(varpanimationstatemanager.vargamanimationstates[num].propanimationstate[i].proppath, typeof(Transform), "localRotation.x", curve4);
             animationClip.SetCurve(varpanimationstatemanager.vargamanimationstates[num].propanimationstate[i].proppath, typeof(Transform), "localRotation.y", curve5);
             animationClip.SetCurve(varpanimationstatemanager.vargamanimationstates[num].propanimationstate[i].proppath, typeof(Transform), "localRotation.z", curve6);
             animationClip.SetCurve(varpanimationstatemanager.vargamanimationstates[num].propanimationstate[i].proppath, typeof(Transform), "localRotation.w", curve7);
         }
     }
     animationClip.EnsureQuaternionContinuity();
     animationClip.wrapMode = WrapMode.ClampForever;
     return animationClip;
 }
Example #9
0
	public AnimationClip assignCurvesToClip()
	{
		HoudiniCurvesCollection curves = this;
						
		AnimationClip clip = new AnimationClip();
		
		bool found_nonconst_curve = false;
		
		if( !curves.isConstantAnimCurve( curves.tx ) )
		{
			clip.SetCurve( "", typeof(Transform), "localPosition.x", curves.tx );
			found_nonconst_curve = true;
		}
		
		if( !curves.isConstantAnimCurve( curves.ty ) )
		{
			clip.SetCurve( "", typeof(Transform), "localPosition.y", curves.ty );
			found_nonconst_curve = true;
		}
		
		if( !curves.isConstantAnimCurve( curves.tz ) )
		{				
			clip.SetCurve( "", typeof(Transform), "localPosition.z", curves.tz );
			found_nonconst_curve = true;
		}
		
		if( !curves.isConstantAnimCurve( curves.qx ) || 
			!curves.isConstantAnimCurve( curves.qy ) ||
			!curves.isConstantAnimCurve( curves.qz ) ||
			!curves.isConstantAnimCurve( curves.qw ) )
		{
			clip.SetCurve( "", typeof(Transform), "localRotation.x", curves.qx );
			clip.SetCurve( "", typeof(Transform), "localRotation.y", curves.qy );
			clip.SetCurve( "", typeof(Transform), "localRotation.z", curves.qz );
			clip.SetCurve( "", typeof(Transform), "localRotation.w", curves.qw );
			found_nonconst_curve = true;
		}		
		
		if( !curves.isConstantAnimCurve( curves.sx ) )
		{
			clip.SetCurve( "", typeof(Transform), "localScale.x", curves.sx );
			found_nonconst_curve = true;
		}	
		
		if( !curves.isConstantAnimCurve( curves.sy ) )
		{
			clip.SetCurve( "", typeof(Transform), "localScale.y", curves.sy );
			found_nonconst_curve = true;
		}
		
		if( !curves.isConstantAnimCurve( curves.sz ) )
		{
			clip.SetCurve( "", typeof(Transform), "localScale.z", curves.sz );
			found_nonconst_curve = true;
		}	
		
		if( found_nonconst_curve )
		{
			clip.EnsureQuaternionContinuity();
			return clip;
		}
		return null;
	}
        private void CreateCharacterPrefab()
        {
            // All character creation is done in the hierarchy, then saved to a prefab

            // Create root object
            Transform characterRoot = new GameObject(entity.name).transform;
            characterRoot.gameObject.AddComponent<Animation>();

            if (Selection.activeTransform)
            {
                characterRoot.parent = Selection.activeTransform;
                characterRoot.localScale = Vector3.one;
            }

            //Do an inital pass to ensure all sprites are created
            foreach (SpriterAnimation anim in entity.animations)
            {
                // Create an animation clip
                var tempClip = new AnimationClip();
                var curves = new Dictionary<string, AnimationCurve>[14];
                for (int i = 0; i < 14; i++)
                {
                    curves[i] = new Dictionary<string, AnimationCurve>();
                }

                // Process each keyframe
                foreach (SpriterMainlineKey t in anim.mainline.keys)
                {
                    RecordFrame(anim, characterRoot, t, null, t.time/1000f, tempClip.frameRate, curves);
                }
            }

            // Go through each animation
            foreach(SpriterAnimation anim in entity.animations)
            {
                // Create an animation clip
                var clip = new AnimationClip();
                clip.EnsureQuaternionContinuity();
                clip.name = anim.name;
                clip.wrapMode = WrapMode.Loop;

                bool last = anim == entity.animations.LastOrDefault();

                // Create animation curves
                var curves = new Dictionary<string, AnimationCurve>[14];

                for(int i = 0; i < 14; i++)
                {
                    curves[i] = new Dictionary<string, AnimationCurve>();
                }

                // Go through each keyframe
                foreach (SpriterMainlineKey t in anim.mainline.keys)
                {
                    // Record the frame
                    RecordFrame(anim, characterRoot, t, null, t.time/1000f, clip.frameRate, curves);
                }
                //if there's no keyframe at the end, give an end target to set the animations length
                if (anim.mainline.keys.Last().time < anim.length)
                {
                    if (anim.playbackType == PlaybackType.Loop || anim.playbackType == PlaybackType.Unknown)
                        RecordFrame(anim, characterRoot, anim.mainline.keys[0], last ? anim.mainline.keys[0] : null, anim.length / 1000f, clip.frameRate,
                                    curves);
                    else
                        RecordFrame(anim, characterRoot, anim.mainline.keys.Last(), last ? anim.mainline.keys.Last() : null, anim.length / 1000f, clip.frameRate,
                                    curves);
                }

                switch (anim.playbackType)
                {
                    case PlaybackType.Unknown:
                        clip.wrapMode = WrapMode.Loop;
                        break;
                    case PlaybackType.PlayOnce:
                        clip.wrapMode = WrapMode.Once;
                        break;
                    case PlaybackType.Loop:
                        clip.wrapMode = WrapMode.Loop;
                        break;
                    case PlaybackType.PingPong:
                        clip.wrapMode = WrapMode.PingPong;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                RemoveTangents(curves);

                // Bind the animation
                BindAnimation(clip, curves);

                // Save the animation
                string p = GetSaveFolder() + characterRoot.name + "@" + clip.name + ".anim";
                if (AssetDatabase.LoadAssetAtPath(p, typeof(AnimationClip)))
                {
                    AssetDatabase.DeleteAsset(p);
                    AssetDatabase.CreateAsset(clip, p);
                }
                else
                {
                    AssetDatabase.CreateAsset(clip, p);
                }

                // Update the reference
                clip = (AnimationClip)AssetDatabase.LoadAssetAtPath(p, typeof(AnimationClip));

                // Add the clip to the root object
                characterRoot.animation.AddClip(clip, clip.name);

                if (!characterRoot.animation.clip)
                {
                    characterRoot.animation.clip = characterRoot.animation.GetClip(clip.name);
                }
            }

            SaveAssets(characterRoot.gameObject);
        }
    private static AnimationClip GetAnimationClip(Animator animator, GameObject rootObject, MoCapData data,
        bool processBodyTransforms, bool processFaceTransforms, bool processFaceBlendShapes)
    {
        var animationClip = new AnimationClip();

        animationClip.name = Path.GetFileNameWithoutExtension(DataFile);
        animationClip.legacy = true;
        animationClip.wrapMode = WrapMode.Once;
        animationClip.frameRate = 25;

        animationClip.ClearCurves();

        if (data.BodyFrames != null && data.BodyFrames.Length > 0)
        {
            if (processBodyTransforms)
            {
                var transforms = new TransformTime[(int) MoCapKinectBone.Count][];

                for (var i = 0; i < (int) MoCapKinectBone.Count; i++)
                {
                    transforms[i] = new TransformTime[data.BodyFrames.Length];

                    for (var j = 0; j < data.BodyFrames.Length; j++)
                    {
                        transforms[i][j].Time = data.BodyFrames[j].SkeletonTransforms[i].Time;
                        transforms[i][j].Position = Vector3.Zero;
                        transforms[i][j].Rotation = MoCapBoneMapper.LocalRotation(ref data.BodyFrames[j],
                            (MoCapKinectBone) i);
                        transforms[i][j].Scale = Vector3.One;
                    }
                }

                foreach (MoCapKinectBone kinectBone in Enum.GetValues(typeof (MoCapKinectBone)))
                    if (MoCapBoneMapper.IsValidKinectBone(kinectBone))
                    {
                        var mecanimBone = MoCapBoneMapper.Kinect2Mecanim(kinectBone);
                        if (MoCapBoneMapper.IsValidMecanimBone(mecanimBone))
                            SetAnimationCurvesForBody(animator, rootObject, transforms[(int) kinectBone], animationClip,
                                mecanimBone, false, true, false);
                    }
            }
        }

        if (data.FaceFrames != null && data.FaceFrames.Length > 0)
        {
            if (processFaceTransforms)
            {
                var transforms = new TransformTime[data.FaceFrames.Length];

                for (var i = 0; i < data.FaceFrames.Length; i++)
                {
                    transforms[i].Time = data.FaceFrames[i].FaceTransform.Time;
                    transforms[i].Position = Vector3.Zero;
                    transforms[i].Rotation = new Quaternion(-data.FaceFrames[i].FaceTransform.Rotation.X,
                        data.FaceFrames[i].FaceTransform.Rotation.Y, data.FaceFrames[i].FaceTransform.Rotation.Z,
                        data.FaceFrames[i].FaceTransform.Rotation.W);
                    transforms[i].Scale = Vector3.One;
                }

                SetAnimationCurvesForBody(animator, rootObject, transforms, animationClip, MoCapMecanimBone.Head, false,
                    true, false);
            }

            if (processFaceBlendShapes)
            {
                var weights =
                    new List<KeyValuePair<float, float>>[(int) MoCapMixamoFacialExpression.LastBlendShape];

                foreach (
                    MoCapKinectFacialExpression kinectFacialExpression in
                        Enum.GetValues(typeof (MoCapKinectFacialExpression)))
                    if (MoCapFacialExpressionMapper.IsValidKinectFacialExpression(kinectFacialExpression))
                    {
                        for (var j = 0; j < data.FaceFrames.Length; j++)
                        {
                            MoCapMixamoFacialExpression mixamoFacialExpression;
                            float mixamoWeight;
                            MoCapFacialExpressionMapper.Kinect2Mixamo(kinectFacialExpression,
                                data.FaceFrames[j].ExpressionWeights[(int) kinectFacialExpression],
                                out mixamoFacialExpression, out mixamoWeight);

                            if (MoCapFacialExpressionMapper.IsValidMixamoFacialExpression(mixamoFacialExpression))
                            {
                                if (weights[(int) mixamoFacialExpression] == null)
                                    weights[(int) mixamoFacialExpression] =
                                        new List<KeyValuePair<float, float>>(data.FaceFrames.Length);

                                weights[(int) mixamoFacialExpression].Add(
                                    new KeyValuePair<float, float>(data.FaceFrames[j].FaceTransform.Time, mixamoWeight));
                            }
                        }
                    }

                foreach (
                    MoCapMixamoFacialExpression mixamoFacialExpression in
                        Enum.GetValues(typeof (MoCapMixamoFacialExpression)))
                    if (MoCapFacialExpressionMapper.IsValidMixamoFacialExpression(mixamoFacialExpression))
                        if (weights[(int) mixamoFacialExpression] != null &&
                            weights[(int) mixamoFacialExpression].Count > 0)
                            SetAnimationCurvesForFace(animator, rootObject,
                                weights[(int) mixamoFacialExpression].ToArray(), animationClip, mixamoFacialExpression);
            }
        }

        animationClip.EnsureQuaternionContinuity();

        return animationClip;
    }
Example #12
0
        private static UnityEngine.AnimationClip Convert(Clip animation, FrameContainer frames,
            out UVector3 rootStart, out UVector3 rootEnd)
        {
            var clip = new UnityEngine.AnimationClip();
            clip.legacy = true;

            var rotateAxes = new[] {
                new { Name = "x", Mask = new UVector4(1f, 0f, 0f, 0f) },
                new { Name = "y", Mask = new UVector4(0f, 1f, 0f, 0f) },
                new { Name = "z", Mask = new UVector4(0f, 0f, 1f, 0f) },
                new { Name = "w", Mask = new UVector4(0f, 0f, 0f, 1f) }
            };

            var translateAxes = new[] {
                new { Name = "x", Mask = new UVector3(1f, 0f, 0f) },
                new { Name = "y", Mask = new UVector3(0f, 1f, 0f) },
                new { Name = "z", Mask = new UVector3(0f, 0f, 1f) },
            };

            var root = animation.Bones.FirstOrDefault(x => x.BoneId == 0);
            if (root != null && root.FrameCount > 0) {
                rootStart = Types.Convert(root.Frames.First().Translation);
                rootEnd = Types.Convert(root.Frames.Last().Translation);
            } else {
                rootStart = rootEnd = UVector3.zero;
            }

            foreach (var bone in animation.Bones) {
                var bFrames = bone.Frames;
                var frame = frames.GetByBoneId(bone.BoneId);

                string bonePath = frame.Path;

                var axisAngle = bFrames.ToDictionary(x => x, x => {
                    var q = Types.Convert(x.Rotation);
                    float ang; UnityEngine.Vector3 axis;
                    q.ToAngleAxis(out ang, out axis);
                    return new UVector4(q.x, q.y, q.z, q.w);
                });

                foreach (var axis in rotateAxes) {
                    var keys = bFrames
                        .Select(x => new Keyframe(x.Time * TimeScale,
                            UVector4.Dot(axisAngle[x], axis.Mask)))
                        .ToArray();

                    clip.SetCurve(bonePath, typeof(Transform), "localRotation." + axis.Name,
                        new UnityEngine.AnimationCurve(keys));
                }

                var converted = bFrames.Select(x => Types.Convert(x.Translation)).ToArray();

                if (!converted.Any(x => !x.Equals(UVector3.zero))) continue;

                var anyVelocities = false;
                var deltaVals = converted.Select((x, i) => {
                    var prev = Math.Max(0, i - 1);
                    var next = Math.Min(i + 1, converted.Length - 1);

                    var prevTime = bFrames[prev].Time * TimeScale;
                    var nextTime = bFrames[next].Time * TimeScale;

                    return prevTime == nextTime || !(anyVelocities = true) ? UVector3.zero
                        : (converted[next] - converted[prev]) / (nextTime - prevTime);
                }).ToArray();

                foreach (var translateAxis in translateAxes) {
                    var positions = bFrames
                        .Select((x, i) => new Keyframe(x.Time * TimeScale,
                            UVector3.Dot(frame.transform.localPosition + converted[i], translateAxis.Mask)))
                        .ToArray();

                    var deltas = bFrames.Select((x, i) => new Keyframe(x.Time * TimeScale,
                        UVector3.Dot(deltaVals[i], translateAxis.Mask))).ToArray();

                    clip.SetCurve(bonePath, typeof(Transform), "localPosition." + translateAxis.Name,
                        new UnityEngine.AnimationCurve(positions));

                    if (!anyVelocities) continue;

                    clip.SetCurve(bonePath, typeof(BFrame), "LocalVelocity." + translateAxis.Name,
                        new UnityEngine.AnimationCurve(deltas));
                }
            }

            clip.wrapMode = WrapMode.Loop;
            clip.EnsureQuaternionContinuity();

            return clip;
        }
Example #13
0
        public AnimationClip BuildSkeletonAnimationClip(string []boneNames)
        {
            var clip = new AnimationClip();
            clip.legacy = true;

            for (var i = 0; i < channelCount; ++i)
            {
                var boneId = Channels[i].ID;
                var cbn = boneNames[boneId];

                if (Channels[i].Type == ChannelType.Rotation)
                {
                    var curvex = new AnimationCurve();
                    var curvey = new AnimationCurve();
                    var curvez = new AnimationCurve();
                    var curvew = new AnimationCurve();
                    for (var j = 0; j < frameCount; ++j)
                    {
                        Frame.Channel chan = Frames[j].Channels[i];
                        curvex.AddKey((float)j / (float)FPS, chan.Rotation.x);
                        curvey.AddKey((float)j / (float)FPS, chan.Rotation.y);
                        curvez.AddKey((float)j / (float)FPS, chan.Rotation.z);
                        curvew.AddKey((float)j / (float)FPS, chan.Rotation.w);
                    }
                    clip.SetCurve(cbn, typeof(Transform), "localRotation.x", curvex);
                    clip.SetCurve(cbn, typeof(Transform), "localRotation.y", curvey);
                    clip.SetCurve(cbn, typeof(Transform), "localRotation.z", curvez);
                    clip.SetCurve(cbn, typeof(Transform), "localRotation.w", curvew);
                }
                else if (Channels[i].Type == ChannelType.Position)
                {
                    var curvex = new AnimationCurve();
                    var curvey = new AnimationCurve();
                    var curvez = new AnimationCurve();
                    for (var j = 0; j < frameCount; ++j)
                    {
                        Frame.Channel chan = Frames[j].Channels[i];
                        curvex.AddKey((float)j / (float)FPS, chan.Position.x);
                        curvey.AddKey((float)j / (float)FPS, chan.Position.y);
                        curvez.AddKey((float)j / (float)FPS, chan.Position.z);
                    }
                    clip.SetCurve(cbn, typeof(Transform), "localPosition.x", curvex);
                    clip.SetCurve(cbn, typeof(Transform), "localPosition.y", curvey);
                    clip.SetCurve(cbn, typeof(Transform), "localPosition.z", curvez);
                }
            }

            clip.EnsureQuaternionContinuity();
            return clip;
        }
Example #14
0
        public AnimationClip buildAnimationClip(ZMD skeleton)
        {
            var clip = new AnimationClip();

            for (var i = 0; i < channelCount ; ++i) {
                if (Channels[i].ID < 0 || Channels[i].ID >= skeleton.nBones) {
                    Debug.LogWarning("Found invalid channel index.");
                    continue;
                }

                string cbn = skeleton.bones[Channels[i].ID].Path;
                if (Channels[i].Type == ChannelType.Rotation) {
                    var curvex = new AnimationCurve();
                    var curvey = new AnimationCurve();
                    var curvez = new AnimationCurve();
                    var curvew = new AnimationCurve();
                    for (var j = 0; j < frameCount; ++j) {
                        Frame.Channel chan = Frames[j].Channels[i];
                        curvex.AddKey((float)j / (float)FPS, chan.Rotation.x);
                        curvey.AddKey((float)j / (float)FPS, chan.Rotation.y);
                        curvez.AddKey((float)j / (float)FPS, chan.Rotation.z);
                        curvew.AddKey((float)j / (float)FPS, chan.Rotation.w);
                    }
                    clip.SetCurve(cbn, typeof(Transform), "localRotation.x", curvex);
                    clip.SetCurve(cbn, typeof(Transform), "localRotation.y", curvey);
                    clip.SetCurve(cbn, typeof(Transform), "localRotation.z", curvez);
                    clip.SetCurve(cbn, typeof(Transform), "localRotation.w", curvew);
                }
                else if (Channels[i].Type == ChannelType.Position) {
                    var curvex = new AnimationCurve();
                    var curvey = new AnimationCurve();
                    var curvez = new AnimationCurve();
                    for (var j = 0; j < frameCount; ++j) {
                        Frame.Channel chan = Frames[j].Channels[i];
                        curvex.AddKey((float)j / (float)FPS, chan.Position.x);
                        curvey.AddKey((float)j / (float)FPS, chan.Position.y);
                        curvez.AddKey((float)j / (float)FPS, chan.Position.z);
                    }
                    clip.SetCurve(cbn, typeof(Transform), "localPosition.x", curvex);
                    clip.SetCurve(cbn, typeof(Transform), "localPosition.y", curvey);
                    clip.SetCurve(cbn, typeof(Transform), "localPosition.z", curvez);
                }
            }

            clip.EnsureQuaternionContinuity ();
            return clip;
        }