TimelineAnimationUtilities.cs 17.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
using UnityEngineInternal;
using UnityEngine.Timeline;
using UnityEngine.Playables;
using Object = UnityEngine.Object;

namespace UnityEditor.Timeline
{
    class TimelineAnimationUtilities
    {
        public enum OffsetEditMode
        {
            None = -1,
            Translation = 0,
            Rotation = 1
        }

        public static bool ValidateOffsetAvailabitity(PlayableDirector director, Animator animator)
        {
            if (director == null || animator == null)
                return false;

            return true;
        }

        public static TimelineClip GetPreviousClip(TimelineClip clip)
        {
            TimelineClip previousClip = null;
            foreach (var c in clip.parentTrack.clips)
            {
                if (c.start < clip.start && (previousClip == null || c.start >= previousClip.start))
                    previousClip = c;
            }
            return previousClip;
        }

        public static TimelineClip GetNextClip(TimelineClip clip)
        {
            return clip.parentTrack.clips.Where(c => c.start > clip.start).OrderBy(c => c.start).FirstOrDefault();
        }

        public struct RigidTransform
        {
            public Vector3 position;
            public Quaternion rotation;

            public static RigidTransform Compose(Vector3 pos, Quaternion rot)
            {
                RigidTransform ret;
                ret.position = pos;
                ret.rotation = rot;
                return ret;
            }

            public static RigidTransform Mul(RigidTransform a, RigidTransform b)
            {
                RigidTransform ret;
                ret.rotation = a.rotation * b.rotation;
                ret.position = a.position + a.rotation * b.position;
                return ret;
            }

            public static RigidTransform Inverse(RigidTransform a)
            {
                RigidTransform ret;
                ret.rotation = Quaternion.Inverse(a.rotation);
                ret.position = ret.rotation * (-a.position);
                return ret;
            }

            public static RigidTransform identity
            {
                get { return Compose(Vector3.zero, Quaternion.identity); }
            }
        }


        private static Matrix4x4 GetTrackMatrix(Transform transform, AnimationTrack track)
        {
            Matrix4x4 trackMatrix = Matrix4x4.TRS(track.position, track.rotation, Vector3.one);

            // in scene off mode, the track offsets are set to the preview position which is stored in the track
            if (track.trackOffset == TrackOffset.ApplySceneOffsets)
            {
                trackMatrix = Matrix4x4.TRS(track.sceneOffsetPosition, Quaternion.Euler(track.sceneOffsetRotation), Vector3.one);
            }

            // put the parent transform on to the track matrix
            if (transform.parent != null)
            {
                trackMatrix = transform.parent.localToWorldMatrix * trackMatrix;
            }

            return trackMatrix;
        }

        // Given a world space position and rotation, updates the clip offsets to match that
        public static RigidTransform UpdateClipOffsets(AnimationPlayableAsset asset, AnimationTrack track, Transform transform, Vector3 globalPosition, Quaternion globalRotation)
        {
            Matrix4x4 worldToLocal = transform.worldToLocalMatrix;
            Matrix4x4 clipMatrix = Matrix4x4.TRS(asset.position, asset.rotation, Vector3.one);
            Matrix4x4 trackMatrix = GetTrackMatrix(transform, track);


            // Use the transform to find the proper goal matrix with scale taken into account
            var oldPos = transform.position;
            var oldRot = transform.rotation;
            transform.position = globalPosition;
            transform.rotation = globalRotation;
            Matrix4x4 goal = transform.localToWorldMatrix;
            transform.position = oldPos;
            transform.rotation = oldRot;

            // compute the new clip matrix.
            Matrix4x4 newClip = trackMatrix.inverse * goal * worldToLocal * trackMatrix * clipMatrix;
            return RigidTransform.Compose(newClip.GetColumn(3), MathUtils.QuaternionFromMatrix(newClip));
        }

        public static RigidTransform GetTrackOffsets(AnimationTrack track, Transform transform)
        {
            Vector3 position = track.position;
            Quaternion rotation = track.rotation;
            if (transform != null && transform.parent != null)
            {
                position = transform.parent.TransformPoint(position);
                rotation = transform.parent.rotation * rotation;
                MathUtils.QuaternionNormalize(ref rotation);
            }

            return RigidTransform.Compose(position, rotation);
        }

        public static void UpdateTrackOffset(AnimationTrack track, Transform transform, RigidTransform offsets)
        {
            if (transform != null && transform.parent != null)
            {
                offsets.position = transform.parent.InverseTransformPoint(offsets.position);
                offsets.rotation = Quaternion.Inverse(transform.parent.rotation) * offsets.rotation;
                MathUtils.QuaternionNormalize(ref offsets.rotation);
            }

            track.position = offsets.position;
            track.eulerAngles = AnimationUtility.GetClosestEuler(offsets.rotation, track.eulerAngles, RotationOrder.OrderZXY);
            track.UpdateClipOffsets();
        }

        static MatchTargetFields GetMatchFields(TimelineClip clip)
        {
            var track = clip.parentTrack as AnimationTrack;
            if (track == null)
                return MatchTargetFieldConstants.None;

            var asset = clip.asset as AnimationPlayableAsset;
            var fields = track.matchTargetFields;
            if (asset != null && !asset.useTrackMatchFields)
                fields = asset.matchTargetFields;
            return fields;
        }

        static void WriteMatchFields(AnimationPlayableAsset asset, RigidTransform result, MatchTargetFields fields)
        {
            Vector3 position = asset.position;

            position.x = fields.HasAny(MatchTargetFields.PositionX) ? result.position.x : position.x;
            position.y = fields.HasAny(MatchTargetFields.PositionY) ? result.position.y : position.y;
            position.z = fields.HasAny(MatchTargetFields.PositionZ) ? result.position.z : position.z;

            asset.position = position;

            // check first to avoid unnecessary conversion errors
            if (fields.HasAny(MatchTargetFieldConstants.Rotation))
            {
                Vector3 eulers = asset.eulerAngles;
                Vector3 resultEulers = result.rotation.eulerAngles;

                eulers.x = fields.HasAny(MatchTargetFields.RotationX) ? resultEulers.x : eulers.x;
                eulers.y = fields.HasAny(MatchTargetFields.RotationY) ? resultEulers.y : eulers.y;
                eulers.z = fields.HasAny(MatchTargetFields.RotationZ) ? resultEulers.z : eulers.z;

                asset.eulerAngles = AnimationUtility.GetClosestEuler(Quaternion.Euler(eulers), asset.eulerAngles, RotationOrder.OrderZXY);
            }
        }

        public static void MatchPrevious(TimelineClip currentClip, Transform matchPoint, PlayableDirector director)
        {
            const double timeEpsilon = 0.00001;
            MatchTargetFields matchFields = GetMatchFields(currentClip);
            if (matchFields == MatchTargetFieldConstants.None || matchPoint == null)
                return;

            double cachedTime = director.time;

            // finds previous clip
            TimelineClip previousClip = GetPreviousClip(currentClip);
            if (previousClip == null || currentClip == previousClip)
                return;

            // make sure the transform is properly updated before modifying the graph
            director.Evaluate();

            var parentTrack = currentClip.parentTrack as AnimationTrack;

            var blendIn = currentClip.blendInDuration;
            currentClip.blendInDuration = 0;
            var blendOut = previousClip.blendOutDuration;
            previousClip.blendOutDuration = 0;

            //evaluate previous without current
            parentTrack.RemoveClip(currentClip);
            director.RebuildGraph();
            double previousEndTime = currentClip.start > previousClip.end ? previousClip.end : currentClip.start;
            director.time = previousEndTime - timeEpsilon;
            director.Evaluate(); // add port to evaluate only track

            var targetPosition = matchPoint.position;
            var targetRotation = matchPoint.rotation;

            // evaluate current without previous
            parentTrack.AddClip(currentClip);
            parentTrack.RemoveClip(previousClip);
            director.RebuildGraph();
            director.time = currentClip.start + timeEpsilon;
            director.Evaluate();

            //////////////////////////////////////////////////////////////////////
            //compute offsets

            var animationPlayable = currentClip.asset as AnimationPlayableAsset;
            var match = UpdateClipOffsets(animationPlayable, parentTrack, matchPoint, targetPosition, targetRotation);
            WriteMatchFields(animationPlayable, match, matchFields);

            //////////////////////////////////////////////////////////////////////

            currentClip.blendInDuration = blendIn;
            previousClip.blendOutDuration = blendOut;

            parentTrack.AddClip(previousClip);
            director.RebuildGraph();
            director.time = cachedTime;
            director.Evaluate();
        }

        public static void MatchNext(TimelineClip currentClip, Transform matchPoint, PlayableDirector director)
        {
            const double timeEpsilon = 0.00001;
            MatchTargetFields matchFields = GetMatchFields(currentClip);
            if (matchFields == MatchTargetFieldConstants.None || matchPoint == null)
                return;

            double cachedTime = director.time;

            // finds next clip
            TimelineClip nextClip = GetNextClip(currentClip);
            if (nextClip == null || currentClip == nextClip)
                return;

            // make sure the transform is properly updated before modifying the graph
            director.Evaluate();

            var parentTrack = currentClip.parentTrack as AnimationTrack;

            var blendOut = currentClip.blendOutDuration;
            var blendIn = nextClip.blendInDuration;
            currentClip.blendOutDuration = 0;
            nextClip.blendInDuration = 0;

            //evaluate previous without current
            parentTrack.RemoveClip(currentClip);
            director.RebuildGraph();
            director.time = nextClip.start + timeEpsilon;
            director.Evaluate(); // add port to evaluate only track

            var targetPosition = matchPoint.position;
            var targetRotation = matchPoint.rotation;

            // evaluate current without next
            parentTrack.AddClip(currentClip);
            parentTrack.RemoveClip(nextClip);
            director.RebuildGraph();
            director.time = Math.Min(nextClip.start, currentClip.end - timeEpsilon);
            director.Evaluate();

            //////////////////////////////////////////////////////////////////////
            //compute offsets

            var animationPlayable = currentClip.asset as AnimationPlayableAsset;
            var match = UpdateClipOffsets(animationPlayable, parentTrack, matchPoint, targetPosition, targetRotation);
            WriteMatchFields(animationPlayable, match, matchFields);

            //////////////////////////////////////////////////////////////////////

            currentClip.blendOutDuration = blendOut;
            nextClip.blendInDuration = blendIn;

            parentTrack.AddClip(nextClip);
            director.RebuildGraph();
            director.time = cachedTime;
            director.Evaluate();
        }

        public static TimelineWindowTimeControl CreateTimeController(WindowState state, TimelineClip clip)
        {
            var animationWindow = EditorWindow.GetWindow<AnimationWindow>();
            var timeController = ScriptableObject.CreateInstance<TimelineWindowTimeControl>();
            timeController.Init(animationWindow.state, clip);
            return timeController;
        }

        public static TimelineWindowTimeControl CreateTimeController(WindowState state, TimelineWindowTimeControl.ClipData clipData)
        {
            var animationWindow = EditorWindow.GetWindow<AnimationWindow>();
            var timeController = ScriptableObject.CreateInstance<TimelineWindowTimeControl>();
            timeController.Init(animationWindow.state, clipData);
            return timeController;
        }

        public static void EditAnimationClipWithTimeController(AnimationClip animationClip, TimelineWindowTimeControl timeController, Object sourceObject)
        {
            var animationWindow = EditorWindow.GetWindow<AnimationWindow>();
            animationWindow.EditSequencerClip(animationClip, sourceObject, timeController);
        }

        public static void UnlinkAnimationWindowFromTracks(IEnumerable<TrackAsset> tracks)
        {
            var clips = new List<AnimationClip>();
            foreach (var track in tracks)
            {
                var animationTrack = track as AnimationTrack;
                if (animationTrack != null && animationTrack.infiniteClip != null)
                    clips.Add(animationTrack.infiniteClip);

                GetAnimationClips(track.GetClips(), clips);
            }
            UnlinkAnimationWindowFromAnimationClips(clips);
        }

        public static void UnlinkAnimationWindowFromClips(IEnumerable<TimelineClip> timelineClips)
        {
            var clips = new List<AnimationClip>();
            GetAnimationClips(timelineClips, clips);
            UnlinkAnimationWindowFromAnimationClips(clips);
        }

        public static void UnlinkAnimationWindowFromAnimationClips(ICollection<AnimationClip> clips)
        {
            if (clips.Count == 0)
                return;

            UnityEngine.Object[] windows = Resources.FindObjectsOfTypeAll(typeof(AnimationWindow));
            foreach (var animWindow in windows.OfType<AnimationWindow>())
            {
                if (animWindow != null && animWindow.state != null && animWindow.state.linkedWithSequencer && clips.Contains(animWindow.state.activeAnimationClip))
                    animWindow.UnlinkSequencer();
            }
        }

        public static void UnlinkAnimationWindow()
        {
            UnityEngine.Object[] windows = Resources.FindObjectsOfTypeAll(typeof(AnimationWindow));
            foreach (var animWindow in windows.OfType<AnimationWindow>())
            {
                if (animWindow != null && animWindow.state != null && animWindow.state.linkedWithSequencer)
                    animWindow.UnlinkSequencer();
            }
        }

        private static void GetAnimationClips(IEnumerable<TimelineClip> timelineClips, List<AnimationClip> clips)
        {
            foreach (var timelineClip in timelineClips)
            {
                if (timelineClip.curves != null)
                    clips.Add(timelineClip.curves);
                AnimationPlayableAsset apa = timelineClip.asset as AnimationPlayableAsset;
                if (apa != null && apa.clip != null)
                    clips.Add(apa.clip);
            }
        }

        public static int GetAnimationWindowCurrentFrame()
        {
            var animationWindow = EditorWindow.GetWindow<AnimationWindow>();
            if (animationWindow)
                return animationWindow.state.currentFrame;
            return -1;
        }

        public static void SetAnimationWindowCurrentFrame(int frame)
        {
            var animationWindow = EditorWindow.GetWindow<AnimationWindow>();
            if (animationWindow)
                animationWindow.state.currentFrame = frame;
        }

        public static void ConstrainCurveToBooleanValues(AnimationCurve curve)
        {
            // Clamp the values first
            var keys = curve.keys;
            for (var i = 0; i < keys.Length; i++)
            {
                var key = keys[i];
                key.value = key.value < 0.5f ? 0.0f : 1.0f;
                keys[i] = key;
            }
            curve.keys = keys;

            // Update the tangents once all the values are clamped
            for (var i = 0; i < curve.length; i++)
            {
                AnimationUtility.SetKeyLeftTangentMode(curve, i, AnimationUtility.TangentMode.Constant);
                AnimationUtility.SetKeyRightTangentMode(curve, i, AnimationUtility.TangentMode.Constant);
            }
        }

        public static void ConstrainCurveToRange(AnimationCurve curve, float minValue, float maxValue)
        {
            var keys = curve.keys;
            for (var i = 0; i < keys.Length; i++)
            {
                var key = keys[i];
                key.value = Mathf.Clamp(key.value, minValue, maxValue);
                keys[i] = key;
            }
            curve.keys = keys;
        }

        public static bool IsAnimationClip(TimelineClip clip)
        {
            return clip != null && (clip.asset as AnimationPlayableAsset) != null;
        }
    }
}