private Vector3 InterpolatedPosition(KeyFrame keyFrame1, KeyFrame keyFrame2, float t) { float frameLen = keyFrames[keyFrameNr2].fromF - keyFrames[keyFrameNr1].fromF; float localT = (t - keyFrame1.fromF) / frameLen; return Vector3.Lerp(keyFrame1.position, keyFrame2.position, localT); }
public void CyclicLoopBehavior() { var keyFrame0 = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(0.0), _random.NextQuaternionF()); var keyFrame1 = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(1.0), _random.NextQuaternionF()); var keyFrame2 = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(2.0), _random.NextQuaternionF()); var animation = new QuaternionFKeyFrameAnimation(); animation.KeyFrames.Add(keyFrame0); animation.KeyFrames.Add(keyFrame1); animation.KeyFrames.Add(keyFrame2); var animationClip = new AnimationClip<QuaternionF> { Animation = animation }; animationClip.LoopBehavior = LoopBehavior.Cycle; animationClip.Duration = TimeSpan.MaxValue; animationClip.ClipOffset = TimeSpan.FromSeconds(-1); var defaultSource = _random.NextQuaternionF(); var defaultTarget = _random.NextQuaternionF(); // Pre loop var expected = InterpolationHelper.Lerp(keyFrame1.Value, keyFrame2.Value, 0.25f); Assert.AreEqual(expected, animationClip.GetValue(TimeSpan.FromSeconds(0.25), defaultSource, defaultTarget)); // Post loop expected = InterpolationHelper.Lerp(keyFrame1.Value, keyFrame2.Value, 0.75f); Assert.AreEqual(expected, animationClip.GetValue(TimeSpan.FromSeconds(4.75), defaultSource, defaultTarget)); }
void CalculateKeyFrameNr(KeyFrame[] keyFrames, float f, out int keyFrameNr1, out int keyFrameNr2) { keyFrameNr1 = 0; keyFrameNr2 = 1; for (int i = 0; i < keyFrames.Length - 1; i++) { if (f >= keyFrames[i].fromF && f < keyFrames[i+1].fromF) { keyFrameNr1 = i; keyFrameNr2 = i + 1; } } }
public Bone(string name, Bone parent, Matrix4 localRotationMatrix, Matrix4 localTranslationMatrix, KeyFrame[] keyFrames) { this.name = name; this.parent = parent; this.localRotationMatrix = localRotationMatrix; this.localTranslationMatrix = localTranslationMatrix; this.localTransformationMatrix = localRotationMatrix * localTranslationMatrix; this.globalTransformationMatrix = this.GetGlobalTransformationMatrix(); this.keyFrames = keyFrames; }
public void AnimationWithOneKeyFrame() { var keyFrame = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(1.0), _random.NextQuaternionF()); var keyFrameAnimation = new QuaternionFKeyFrameAnimation(); keyFrameAnimation.KeyFrames.Add(keyFrame); var animation = new AnimationClip<QuaternionF>(); animation.Animation = keyFrameAnimation; animation.Duration = TimeSpan.MaxValue; var defaultSource = _random.NextQuaternionF(); var defaultTarget = _random.NextQuaternionF(); Assert.AreEqual(keyFrame.Value, animation.GetValue(TimeSpan.FromSeconds(0.0), defaultSource, defaultTarget)); // Pre loop Assert.AreEqual(keyFrame.Value, animation.GetValue(TimeSpan.FromSeconds(1.0), defaultSource, defaultTarget)); // Key frame Assert.AreEqual(keyFrame.Value, animation.GetValue(TimeSpan.FromSeconds(2.0), defaultSource, defaultTarget)); // Post loop }
public void GetEnumeratorTest() { var collection = new KeyFrameCollection<QuaternionF>(); var keyFrame = new KeyFrame<QuaternionF>(); var keyFrame2 = new KeyFrame<QuaternionF>(); collection.Add(keyFrame); collection.Add(keyFrame2); foreach (var k in collection) { } Assert.AreEqual(2, collection.Count()); Assert.Contains(keyFrame, collection); Assert.Contains(keyFrame2, collection); }
public void CyclicAnimationWithZeroLength() { var keyFrame0 = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(1.0), _random.NextQuaternionF()); var keyFrame1 = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(1.0), _random.NextQuaternionF()); var animation = new QuaternionFKeyFrameAnimation(); animation.KeyFrames.Add(keyFrame0); animation.KeyFrames.Add(keyFrame1); var animationClip = new AnimationClip<QuaternionF> { Animation = animation }; animationClip.LoopBehavior = LoopBehavior.Cycle; animationClip.Duration = TimeSpan.MaxValue; var defaultSource = _random.NextQuaternionF(); var defaultTarget = _random.NextQuaternionF(); // Just ensure that calls don't crash. (Ignore actual result because ambiguous.) Assert.That(() => { animationClip.GetValue(TimeSpan.FromSeconds(0.25), defaultSource, defaultTarget); }, Throws.Nothing); Assert.That(() => { animationClip.GetValue(TimeSpan.FromSeconds(4.75), defaultSource, defaultTarget); }, Throws.Nothing); }
public Sequence(FileReader reader) { Name = reader.ReadString(28); uint keyFrameCount = reader.ReadUInt32(); BeginIndex = reader.ReadUInt16(); ushort elementCount = reader.ReadUInt16(); //Data starts 8 bytes, stride of 4 (size of float) using (reader.TemporarySeek(8 + (BeginIndex * 4), SeekOrigin.Begin)) { KeyFrames = new KeyFrame[keyFrameCount]; for (int i = 0; i < keyFrameCount; i++) { KeyFrames[i] = new KeyFrame() { Frame = reader.ReadSingle(), Values = reader.ReadSingles(elementCount - 1), }; } } }
/// <summary> /// Adds a new keyframe to the animation curve. /// </summary> /// <param name="time">Time at which to add the keyframe.</param> /// <param name="value">Value of the keyframe.</param> /// <param name="tangentMode">Tangent mode of the keyframe.</param> internal void AddKeyframe(float time, float value, TangentMode tangentMode) { KeyFrame[] newKeyFrames = new KeyFrame[keyFrames.Length + 1]; newKeyFrames[newKeyFrames.Length - 1].time = float.PositiveInfinity; TangentMode[] newTangentModes = new TangentMode[tangentModes.Length + 1]; int insertIdx = keyFrames.Length; for (int i = 0; i < keyFrames.Length; i++) { if (time < keyFrames[i].time) { insertIdx = i; break; } } Array.Copy(keyFrames, newKeyFrames, insertIdx); Array.Copy(tangentModes, newTangentModes, insertIdx); KeyFrame keyFrame = new KeyFrame(); keyFrame.time = time; keyFrame.value = value; newKeyFrames[insertIdx] = keyFrame; newTangentModes[insertIdx] = tangentMode; if (insertIdx < keyFrames.Length) { int remaining = keyFrames.Length - insertIdx; Array.Copy(keyFrames, insertIdx, newKeyFrames, insertIdx + 1, remaining); Array.Copy(tangentModes, insertIdx, newTangentModes, insertIdx + 1, remaining); } tangentModes = newTangentModes; keyFrames = newKeyFrames; }
private void button1_Click_1(object sender, EventArgs e) { int RailIndex = listBox1.SelectedIndex; //Index of rail we are translating int OldFrameIndex = listBox2.SelectedIndex; //Store this so we can set the selected index back at the end if (RailIndex == -1 || listBox1.Items.Count == 0) //Make sure indicies make sense { return; } VectorInput VectorInput = new VectorInput(); if (VectorInput.ShowDialog() != DialogResult.OK)//Cancel if no vector is put in. { return; } Vector Centre = Vector.Zero; int NumOfFrames = file.GetAllRails()[RailIndex].frames.Length; for (int i = 0; i < NumOfFrames; i++) { Vector KFPos = new Vector(file.GetAllRails()[RailIndex].frames[i].x, file.GetAllRails()[RailIndex].frames[i].y, file.GetAllRails()[RailIndex].frames[i].z); Centre = new Vector(KFPos.X + Centre.X, KFPos.Y + Centre.Y, KFPos.Z + Centre.Z); } Centre = new Vector(Centre.X / NumOfFrames, Centre.Y / NumOfFrames, Centre.Z / NumOfFrames);//Average position of Key frames for (int i = 0; i < NumOfFrames; i++) { KeyFrame FrameToEdit = file.GetAllRails()[RailIndex].frames[i]; Vector KFPosToCentre = new Vector(file.GetAllRails()[RailIndex].frames[i].x - Centre.X, file.GetAllRails()[RailIndex].frames[i].y - Centre.Y, file.GetAllRails()[RailIndex].frames[i].z - Centre.Z); FrameToEdit.x = (short)(Centre.X + VectorInput.X * KFPosToCentre.X); FrameToEdit.y = (short)(Centre.Y + VectorInput.Y * KFPosToCentre.Y); FrameToEdit.z = (short)(Centre.Z + VectorInput.Z * KFPosToCentre.Z);//Scale file.GetAllRails()[RailIndex].frames[i] = FrameToEdit; } UpdateRails(RailIndex, 0); listBox2.SelectedIndex = OldFrameIndex; }
/// <summary> /// Update the Tween with a deltaTime. /// </summary> /// <param name="deltaTime">deltaTime.</param> public Tween DeltaUpdate(float deltaTime) { // redundancy, required for avoiding increasing timesteps if (!isStarted) { return(this); } if (isPaused) { return(this); } // special condition for first round KeyFrame keyFrame = this.keyFrames[currentKeyFrame]; if (keyFrame.startedAt < 0) { keyFrame.startedAt = 0; keyFrame.SetupIterations(); } this.deltaNowAccumulator += deltaTime; return(this.Update(this.deltaNowAccumulator)); }
float CalculateSegmentPos(float now) { KeyFrame frame = _currentFrame; float speed = GetGoInfo().MoTransport.moveSpeed; float accel = GetGoInfo().MoTransport.accelRate; float timeSinceStop = frame.TimeFrom + (now - (1.0f / Time.InMilliseconds) * frame.DepartureTime); float timeUntilStop = frame.TimeTo - (now - (1.0f / Time.InMilliseconds) * frame.DepartureTime); float segmentPos, dist; float accelTime = _transportInfo.accelTime; float accelDist = _transportInfo.accelDist; // calculate from nearest stop, less confusing calculation... if (timeSinceStop < timeUntilStop) { if (timeSinceStop < accelTime) { dist = 0.5f * accel * timeSinceStop * timeSinceStop; } else { dist = accelDist + (timeSinceStop - accelTime) * speed; } segmentPos = dist - frame.DistSinceStop; } else { if (timeUntilStop < _transportInfo.accelTime) { dist = (0.5f * accel) * (timeUntilStop * timeUntilStop); } else { dist = accelDist + (timeUntilStop - accelTime) * speed; } segmentPos = frame.DistUntilStop - dist; } return(segmentPos / frame.NextDistFromPrev); }
public void Reset() { skeleton = GetComponentsInChildren <Transform>(); history = new Queue <KeyFrame>(); if (initialState == null || initialState.records.Length != skeleton.Length) { initialState = new KeyFrame(skeleton.Length); for (int i = 0; i < skeleton.Length; i++) { initialState.records[i].localPos = skeleton[i].localPosition; initialState.records[i].localRot = skeleton[i].localRotation; } } else { for (int i = 0; i < skeleton.Length; i++) { skeleton[i].localPosition = initialState.records[i].localPos; skeleton[i].localRotation = initialState.records[i].localRot; } } }
private void Awake() { seq = DOTween.Sequence(); seq.SetAutoKill(false); trImage = GetComponent <Image>(); float time = 0f; for (int i = 0; i < size; i++) { KeyFrame frame = KeyFrames[i]; time += frame.delay; seq.Insert(time, transform.DOLocalMove(frame.Position, frame.duration) .SetEase(frame.Ease)); seq.Insert(time, transform.DOLocalRotate(frame.Rotation, frame.duration) .SetEase(frame.Ease)); seq.Insert(time, transform.DOScale(frame.Scale, frame.duration) .SetEase(frame.Ease)); if (trImage != null) { seq.Insert(time, trImage.DOColor(frame.Color, frame.duration) .SetEase(frame.Ease)); } time += frame.duration; } }
/// <summary> /// creates the show animation /// </summary> /// <returns></returns> private Animation.Animation CreateShowAnimation() { Animation.Animation animation = new Animation.Animation(); animation.Duration = TimeSpan.FromMilliseconds(200); animation.FillMode = Animation.FillMode.Forward; KeyFrame keyFrame = new KeyFrame(); //keyFrame.KeyTime = TimeSpan.FromMilliseconds(0); keyFrame.Cue = new Cue(0d); keyFrame.Setters.Add(new Setter { Property = IsVisibleProperty, Value = true }); animation.Children.Add(keyFrame); keyFrame = new KeyFrame(); //keyFrame.KeyTime = TimeSpan.FromMilliseconds(0); keyFrame.Cue = new Cue(0d); keyFrame.Setters.Add(new Setter { Property = OpacityProperty, Value = 0d }); animation.Children.Add(keyFrame); keyFrame = new KeyFrame(); //keyFrame.KeyTime = TimeSpan.FromMilliseconds(200); keyFrame.Cue = new Cue(1d); keyFrame.Setters.Add(new Setter { Property = OpacityProperty, Value = 1d }); animation.Children.Add(keyFrame); return(animation); }
/// <summary> /// Removes a keyframe at the specified index. /// </summary> /// <param name="index">Index of the keyframe, referencing the <see cref="KeyFrames"/> array.</param> internal void RemoveKeyframe(int index) { if (index < 0 || index >= KeyFrames.Length) { return; } KeyFrame[] newKeyFrames = new KeyFrame[KeyFrames.Length - 1]; TangentMode[] newTangentModes = new TangentMode[tangentModes.Length - 1]; Array.Copy(KeyFrames, newKeyFrames, index); Array.Copy(tangentModes, newTangentModes, index); if (index < newKeyFrames.Length) { int remaining = newKeyFrames.Length - index; Array.Copy(KeyFrames, index + 1, newKeyFrames, index, remaining); Array.Copy(tangentModes, index + 1, newTangentModes, index, remaining); } tangentModes = newTangentModes; keyFrames = newKeyFrames; }
private float EvalCurved(KeyFrame keyframe0, KeyFrame keyframe1, float time) { float dt = keyframe1.Time - keyframe0.Time; float t = (time - keyframe0.Time) / dt; float m0 = keyframe0.OutTangent * dt; float m1 = keyframe1.InTangent * dt; if (float.IsInfinity(m0) || float.IsInfinity(m1)) { return(keyframe0.Value); } float t2 = t * t; float t3 = t2 * t; float a = 2 * t3 - 3 * t2 + 1; float b = t3 - 2 * t2 + t; float c = t3 - t2; float d = -2 * t3 + 3 * t2; return(a * keyframe0.Value + b * m0 + c * m1 + d * keyframe1.Value); }
//Function to remove key frames public void RemoveKeyFrame(int aIndex) { int lastIndex = amountOfKFInArray - 1; if (aIndex < amountOfKFInArray && aIndex >= 0) { for (int index = aIndex; index < lastIndex; ++index) { keyFrames[index] = keyFrames[index + 1]; } keyFrames[lastIndex] = new KeyFrame(); amountOfKFInArray--; } else if (aIndex == lastIndex) { keyFrames[lastIndex] = new KeyFrame(); amountOfKFInArray--; } else { Debug.Log("Remove Keyframe: Invalid index(" + aIndex + ")"); } }
public void Remove(KeyFrame value, bool bSuspendRedraw) { // Use base class to process actual collection operation base.List.Remove(value as object); if (value.KeyFrameType == KeyFrame.enumKeyFrameType.Snapshot) { _arySingleFrames.Remove(value); } else if (value.KeyFrameType == KeyFrame.enumKeyFrameType.CurrentFrame) { _CurrentFrame = null; } else { _aryMulitFrames.Remove(value); } if (!bSuspendRedraw) { _Ruler.RedrawBitmap(); } }
public void Add(KeyFrame keyFrame) { if (keyFrame == null) { return; } int finalIndex = -1; for (int i = 0; i < m_keyFrames.Count; ++i) { if (m_keyFrames[i].Time >= keyFrame.Time) { finalIndex = i; break; } } if (finalIndex == -1) { finalIndex = m_keyFrames.Count; } m_keyFrames.Insert(finalIndex, keyFrame); }
public KeyFrame GetKeyFrame(float frame, bool InsertNewKey = true) { if (Keys.Count == 0) { return(null); } KeyFrame k1 = (KeyFrame)Keys[0], k2 = (KeyFrame)Keys[0]; foreach (KeyFrame k in Keys) { if (k.Frame < frame) { k1 = k; } else { k2 = k; break; } } return(k1); }
public KeyFrame[] GetFrame(float frame) { if (Keys.Count == 0) { return(null); } KeyFrame k1 = (KeyFrame)Keys[0], k2 = (KeyFrame)Keys[0]; foreach (KeyFrame k in Keys) { if (k.Frame < frame) { k1 = k; } else { k2 = k; break; } } return(new KeyFrame[] { k1, k2 }); }
/// <summary> /// 加载关键帧 /// </summary> /// <param name="videoName"></param> private void LoadKeyFrames(string videoName) { List <int> videoTimeList = new List <int>(); string path = @"resource\" + videoName + @"\time.txt"; if (File.Exists(path)) { using (StreamReader sr = new StreamReader(path, System.Text.Encoding.Default)) { string s = ""; while ((s = sr.ReadLine()) != null) { string[] line = s.Split(' '); videoTimeList.Add(Int32.Parse(line[1])); } } } for (int j = 1; j <= videoTimeList.Count; j++) { KeyFrame keyFrame = new KeyFrame(GlobalValues.FilesPath + "/WPFInkResource/" + videoName + ".avi", @"resource\" + videoName + @"\" + j + ".png", videoTimeList[j - 1]); keyFrames.Add(keyFrame); } }
public void CyclicAnimationWithZeroLength() { var keyFrame0 = new KeyFrame <QuaternionF>(TimeSpan.FromSeconds(1.0), _random.NextQuaternionF()); var keyFrame1 = new KeyFrame <QuaternionF>(TimeSpan.FromSeconds(1.0), _random.NextQuaternionF()); var animation = new QuaternionFKeyFrameAnimation(); animation.KeyFrames.Add(keyFrame0); animation.KeyFrames.Add(keyFrame1); var animationClip = new AnimationClip <QuaternionF> { Animation = animation }; animationClip.LoopBehavior = LoopBehavior.Cycle; animationClip.Duration = TimeSpan.MaxValue; var defaultSource = _random.NextQuaternionF(); var defaultTarget = _random.NextQuaternionF(); // Just ensure that calls don't crash. (Ignore actual result because ambiguous.) Assert.That(() => { animationClip.GetValue(TimeSpan.FromSeconds(0.25), defaultSource, defaultTarget); }, Throws.Nothing); Assert.That(() => { animationClip.GetValue(TimeSpan.FromSeconds(4.75), defaultSource, defaultTarget); }, Throws.Nothing); }
void blendAnimation() { bool usingQuaternion = true; for (int i = 0; i < currentAnim.poseBase.Length; i++) { animationTransformData poseresult = new animationTransformData(); animationTransformData dataPose0 = new animationTransformData(); animationTransformData dataPose1 = new animationTransformData(); KeyFrame key0 = prevAnim.poseBase[i].keyFrames[currentFrame]; KeyFrame key1 = currentAnim.poseBase[i].keyFrames[currentFrame]; dataPose0.setTransformIndividual(key0.keyPosition, Quaternion.Euler(key0.keyRotation), new Vector3(1, 1, 1)); dataPose1.setTransformIndividual(key1.keyPosition, Quaternion.Euler(key1.keyRotation), new Vector3(1, 1, 1)); poseresult = blendStatic.lerp(dataPose0, dataPose1, transitionParameter, usingQuaternion); int parentIndex = currentAnim.poseBase[i].parentNodeIndex; Vector3 localPosition = currentAnim.poseBase[i].getLocalPosition(); Vector3 localRotation = currentAnim.poseBase[i].getLocalRotationEuler(); //find delta change from localpose Matrix4x4 deltaMatrix = Matrix4x4.TRS(localPosition + poseresult.localPosition, Quaternion.Euler(localRotation + poseresult.localRotation.eulerAngles), new Vector4(1, 1, 1, 1)); if (parentIndex == -1) { //is root currentAnim.poseBase[i].currentTransform = deltaMatrix; } else { //current transform = take the parent index current transform and multiply with delta matrix currentAnim.poseBase[i].currentTransform = currentAnim.poseBase[parentIndex].currentTransform * deltaMatrix; } currentAnim.poseBase[i].updateNewPosition(objectHierarchy.getObject(i)); } }
/// <summary> /// Applies the provided keyframe to the control, /// overriding all needed properties /// </summary> /// <param name="frame"></param> public override void ApplyKeyFrame(KeyFrame startFrame, KeyFrame endFrame, float factor) { base.ApplyKeyFrame(startFrame, endFrame, factor); SpriteLayout startLayout = startFrame != null ? startFrame.Layout as SpriteLayout : null; SpriteLayout endLayout = endFrame != null ? endFrame.Layout as SpriteLayout : null; if (startLayout == null && endLayout == null) { return; } int r, g, b, a; float skew; if (endLayout == null) { r = startLayout.Color.R; g = startLayout.Color.G; b = startLayout.Color.B; a = startLayout.Color.A; skew = startLayout.Skew; } else { r = (int)((float)startLayout.Color.R * (1.0f - factor) + (float)endLayout.Color.R * factor); g = (int)((float)startLayout.Color.G * (1.0f - factor) + (float)endLayout.Color.G * factor); b = (int)((float)startLayout.Color.B * (1.0f - factor) + (float)endLayout.Color.B * factor); a = (int)((float)startLayout.Color.A * (1.0f - factor) + (float)endLayout.Color.A * factor); skew = startLayout.Skew * (1.0f - factor) + endLayout.Skew * factor; } this.Color = Color.FromArgb(a, r, g, b); this.Skew = skew; }
protected KeyFrame GetKeyFrame(ushort sequenceNumber) { KeyFrame key = new KeyFrame(); key.ConfigurationVersion = m_MetaFrame.ConfigurationVersion; key.NetworkMessageHeader = new NetworkMessageHeader { PublisherID = new String(PublisherId), VersionAndFlags = 0xD1, ExtendedFlags1 = new ExtendedFlags1 { RawValue = 0x04 } }; key.Flags1.RawValue = 0xEB; key.Flags2.RawValue = 0x10; key.MetaFrame = m_MetaFrame; key.Items = new List <DataPointValue>(); for (int i = 0; i < m_ProcessValues.Values.Count; i++) { DataPointValue dataPoint = m_ProcessValues.Values.ElementAt(i) .DataPoint; dataPoint.Index = i; key.Items.Add(dataPoint); m_ProcessValues.Values.ElementAt(i) .IsModified = false; } key.PayloadHeader = new DataSetPayloadHeader { Count = 1, DataSetWriterID = new[] { m_MetaFrame.DataSetWriterID } }; key.DataSetMessageSequenceNumber = sequenceNumber; key.Timestamp = DateTime.Now; return(key); }
//------------------------------------------------------ // Get Animation Data //------------------------------------------------------ // Get the skelton's bone matrices at the specified time public Dictionary <string, Matrix4> getKeyFrame(float time, int num_repeats) { Dictionary <string, Matrix4> temp_bone_matrices = new Dictionary <string, Matrix4>(); foreach (KeyValuePair <string, Dictionary <float, KeyFrame> > keypair in _key_frames_skeleton) { string temp_bone_name = keypair.Key; List <float> key_frame_times = keypair.Value.Keys.ToList(); float last_frame_time = _global_last_frame_time; float repeat_multiplier = (num_repeats == -1) ? (float)Math.Floor(time / last_frame_time) : Math.Min((float)Math.Floor(time / last_frame_time), num_repeats - 1); float repeat_frame = repeat_multiplier * last_frame_time; float loop_time = time - repeat_frame; // Get prevous and next frame with interpolation between them Vector3 PrevNextInterp = AnimationHelper.getNearestFrame(key_frame_times.ToArray(), loop_time); // Default to the most recent frame's data Matrix4 output = keypair.Value[PrevNextInterp.X].data; if (PrevNextInterp.Z != -1) { KeyFrame previous_frame = keypair.Value[PrevNextInterp.X]; KeyFrame next_frame = keypair.Value[PrevNextInterp.Y]; float interpolation = PrevNextInterp.Z; output = EngineHelper.lerp(previous_frame.data, next_frame.data, interpolation); } temp_bone_matrices.Add(temp_bone_name, output); } return(temp_bone_matrices); }
YamlMap FromKeyFrame <T>(KeyFrame <T> keyFrame, Func <T, YamlObject> valueSelector) where T : IEquatable <T> { var result = new YamlMap { { nameof(keyFrame.Frame), keyFrame.Frame }, { nameof(keyFrame.Value), valueSelector(keyFrame.Value) }, { nameof(keyFrame.Easing), FromEasing(keyFrame.Easing) }, }; if (keyFrame is KeyFrame <Vector3> v3kf) { var cp1 = v3kf.SpatialControlPoint1; var cp2 = v3kf.SpatialControlPoint2; if (cp1 != Vector3.Zero || cp2 != Vector3.Zero) { // Spatial Bezier result.Add(nameof(v3kf.SpatialControlPoint1), FromVector3(cp1)); result.Add(nameof(v3kf.SpatialControlPoint2), FromVector3(cp2)); } } return(result); }
/// <summary> /// Create a KeyFrame with multiple transformations. /// </summary> /// <param name="items">Items (target, properties, target, properties, ... , duration).</param> public Tween To(params object[] items) { if (items.Length < 3) { throw new ArgumentException("invalid number of arguments"); } float duration = System.Convert.ToSingle(items[items.Length - 1]); KeyFrame keyFrame = new KeyFrame(duration, this.easing); for (int i = 0; i < items.Length - 1; i += 2) { object target = items[i]; object values = items[i + 1]; foreach (PropertyInfo pInfo in values.GetType().GetProperties()) { object endValue = pInfo.GetValue(values, null); keyFrame.AddIteration(target, pInfo.Name, endValue); } } this.keyFrames.Add(keyFrame); return(this); }
private void Start() { animationExecutor = GetComponent <AnimationExecutor>(); if (Presenter != null) { presenterCarouselKeyFrame = AnimationExecutor.SaveKeyFrame(Presenter.gameObject); presenterSleepingKeyFrame = AnimationExecutor.SaveKeyFrame(Presenter.gameObject); presenterAnimationExecutor = Presenter.GetComponent <AnimationExecutor>(); Presenter.Clicked += () => { Clicked.RaiseEvent(); }; } carouselKeyFrame = AnimationExecutor.SaveKeyFrame(gameObject); sleepingKeyFrame = AnimationExecutor.SaveKeyFrame(gameObject); sleepingKeyFrame.LocalScale = Vector3.zero; sleepingKeyFrame.LocalRotation = Constants.PlaneRotationCorrection + new Vector3(0, 0, 180); gridWorldScale = transform.lossyScale * Constants.GridStatePhotoScaleFactor; transform.localScale = Vector3.zero; }
/// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { if (mouseClick) { editingText = EDITING_NONE; } bool drawRow = false; #if SCREENSHOTMODE Keys[] keys = Keyboard.GetState().GetPressedKeys(); foreach (Keys key in keys) { if (key == Keys.End) { drawRow = true; } } #endif if (drawRow) { graphics.GraphicsDevice.Clear(Color.White); KeyFrame[] keyFrame = charDef.GetAnimation(selAnim).getKeyFrameArray(); for (int i = 0; i < keyFrame.Length; i++) { int fref = charDef.GetAnimation(selAnim).GetKeyFrame(i).frameRef; if (fref >= 0) { DrawCharacter(new Vector2( 100f + (float)(i % 12) * 100f, 130f + (float)(i / 12) * 130f ), 0.5f, FACE_LEFT, fref, true, 1.0f); } } } else { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); #region Black BG spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); spriteBatch.Draw(nullTex, new Rectangle(300, 450, 200, 5), new Color(new Vector4(1.0f, 0.0f, 0.0f, 0.5f))); spriteBatch.Draw(nullTex, new Rectangle(0, 0, 200, 450), new Color(new Vector4(0.0f, 0.0f, 0.0f, 0.5f))); spriteBatch.Draw(nullTex, new Rectangle(590, 0, 300, 600), new Color(new Vector4(0.0f, 0.0f, 0.0f, 0.5f))); spriteBatch.Draw(nullTex, new Rectangle(200, 0, 150, 130), new Color(new Vector4(0.0f, 0.0f, 0.0f, 0.5f))); spriteBatch.End(); #endregion if (selFrame > 0) { DrawCharacter(new Vector2(400f, 450f), 2f, FACE_RIGHT, selFrame - 1, false, 0.2f); } if (selFrame < charDef.GetFrameArray().Length - 1) { DrawCharacter(new Vector2(400f, 450f), 2f, FACE_RIGHT, selFrame + 1, false, 0.2f); } DrawCharacter(new Vector2(400f, 450f), 2f, FACE_RIGHT, selFrame, false, 1.0f); int fref = charDef.GetAnimation(selAnim).GetKeyFrame(curKey).frameRef; if (fref < 0) { fref = 0; } DrawCharacter(new Vector2(500f, 100f), 0.5f, FACE_LEFT, fref, true, 1.0f); text.Size = 0.45f; #region Play Stop if (playing) { if (text.DrawClickText(480, 100, "stop", mouseState.X, mouseState.Y, mouseClick)) { playing = false; } } else { if (text.DrawClickText(480, 100, "play", mouseState.X, mouseState.Y, mouseClick)) { playing = true; } } #endregion #region Load/Save if (drawButton(200, 5, 3, mouseClick)) { charDef.WriteBackup(); } if (drawButton(230, 5, 4, mouseClick)) { charDef.Read(); } if (editingText == EDITING_PATH) { text.Color = Color.Lime; text.DrawText(270, 15, charDef.path + "*"); } else { if (text.DrawClickText(270, 15, charDef.path, mouseState.X, mouseState.Y, mouseClick)) { editingText = EDITING_PATH; } } #endregion #region Texture Switching if (auxMode == AUX_TEXTURES) { for (int i = 0; i < 4; i++) { if (drawButton(210 + i * 21, 40, 1, mouseClick, 0.45f)) { switch (i) { case 0: if (charDef.headIdx > 0) { charDef.headIdx--; } break; case 1: if (charDef.torsoIdx > 0) { charDef.torsoIdx--; } break; case 2: if (charDef.legsIdx > 0) { charDef.legsIdx--; } break; case 3: if (charDef.weaponIdx > 0) { charDef.weaponIdx--; } break; } } string t = charDef.headIdx.ToString(); switch (i) { case 1: t = charDef.torsoIdx.ToString(); break; case 2: t = charDef.legsIdx.ToString(); break; case 3: t = charDef.weaponIdx.ToString(); break; } text.Color = (Color.White); text.DrawText(212 + i * 21, 60, t); if (drawButton(210 + i * 21, 85, 2, mouseClick, 0.45f)) { switch (i) { case 0: if (charDef.headIdx < headTex.Length - 1) { charDef.headIdx++; } break; case 1: if (charDef.torsoIdx < torsoTex.Length - 1) { charDef.torsoIdx++; } break; case 2: if (charDef.legsIdx < legsTex.Length - 1) { charDef.legsIdx++; } break; case 3: if (charDef.weaponIdx < weaponTex.Length - 1) { charDef.weaponIdx++; } break; } } } } #endregion #region Script/Trigs Selector if (auxMode == AUX_SCRIPT) { text.Color = Color.Lime; text.DrawText(210, 110, "script"); } else { if (text.DrawClickText(210, 110, "script", mouseState.X, mouseState.Y, mouseClick)) { auxMode = AUX_SCRIPT; } } if (auxMode == AUX_TRIGS) { text.Color = Color.Lime; text.DrawText(260, 110, "trigs"); } else { if (text.DrawClickText(260, 110, "trigs", mouseState.X, mouseState.Y, mouseClick)) { auxMode = AUX_TRIGS; } } if (auxMode == AUX_TEXTURES) { text.Color = Color.Lime; text.DrawText(300, 110, "tex"); } else { if (text.DrawClickText(300, 110, "tex", mouseState.X, mouseState.Y, mouseClick)) { auxMode = AUX_TEXTURES; } } #endregion #region Trigs if (auxMode == AUX_TRIGS) { if (drawButton(330, 42, 1, (mouseState.LeftButton == ButtonState.Pressed), 0.5f)) { if (trigScroll > 0) { trigScroll--; } } if (drawButton(330, 92, 2, (mouseState.LeftButton == ButtonState.Pressed), 0.5f)) { if (trigScroll < 100) { trigScroll++; } } for (int i = 0; i < 4; i++) { int t = i + trigScroll; if (text.DrawClickText(210, 42 + i * 16, GetTrigName(t), mouseState.X, mouseState.Y, mouseClick)) { charDef.GetFrame(selFrame).GetPart(selPart).idx = t + 1000; } } } #endregion #region Script if (auxMode == AUX_SCRIPT) { for (int i = 0; i < 4; i++) { if (editingText == EDITING_SCRIPT && selScriptLine == i) { text.Color = Color.Lime; text.DrawText(210, 42 + i * 16, i.ToString() + ": " + charDef.GetAnimation(selAnim).GetKeyFrame(selKeyFrame).GetScript(i) + "*"); } else { if (text.DrawClickText(210, 42 + i * 16, i.ToString() + ": " + charDef.GetAnimation(selAnim).GetKeyFrame(selKeyFrame).GetScript(i), mouseState.X, mouseState.Y, mouseClick)) { selScriptLine = i; editingText = EDITING_SCRIPT; } } } } #endregion #region Parts List for (int i = 0; i < charDef.GetFrame(selFrame).GetPartArray().Length; i++) { String line = ""; int idx = charDef.GetFrame(selFrame).GetPart(i).idx; if (idx < 0) { line = ""; } else if (idx < 64) { line = "head" + idx.ToString(); } else if (idx < 74) { line = "torso" + idx.ToString(); } else if (idx < 128) { line = "arms" + idx.ToString(); } else if (idx < 192) { line = "legs" + idx.ToString(); } else if (idx < 1000) { line = "weapon" + idx.ToString(); } else { line = GetTrigName(idx - 1000); } if (selPart == i) { text.Color = Color.Lime; text.DrawText(600, 5 + i * 15, i.ToString() + ": " + line); if (drawButton(700, 5 + i * 15, 1, mouseClick, 0.5f)) { SwapParts(selPart, selPart - 1); if (selPart > 0) { selPart--; } } if (drawButton(720, 5 + i * 15, 2, mouseClick, 0.5f)) { SwapParts(selPart, selPart + 1); if (selPart < charDef.GetFrame(selFrame).GetPartArray().Length - 1) { selPart++; } } Part part = charDef.GetFrame(selFrame).GetPart(selPart); if (text.DrawClickText(740, 5 + i * 15, (part.flip == 0 ? "(n)" : "(m)"), mouseState.X, mouseState.Y, mouseClick)) { part.flip = 1 - part.flip; } if (text.DrawClickText(762, 5 + i * 15, "(r)", mouseState.X, mouseState.Y, mouseClick)) { part.scaling = new Vector2(1.0f, 1.0f); } if (text.DrawClickText(780, 5 + i * 15, "(x)", mouseState.X, mouseState.Y, mouseClick)) { part.idx = -1; } } else { if (text.DrawClickText(600, 5 + i * 15, i.ToString() + ": " + line, mouseState.X, mouseState.Y, mouseClick)) { selPart = i; } } } #endregion #region Frame List for (int i = frameScroll; i < frameScroll + 20; i++) { if (i < charDef.GetFrameArray().Length) { int y = (i - frameScroll) * 15 + 280; if (i == selFrame) { text.Color = Color.Lime; text.DrawText(600, y, i.ToString() + ": " + charDef.GetFrame(i).name + (editingText == EDITING_FRAME_NAME ? "*" : "")); if (text.DrawClickText(720, y, "(a)", mouseState.X, mouseState.Y, mouseClick)) { Animation animation = charDef.GetAnimation(selAnim); for (int j = 0; j < animation.getKeyFrameArray().Length ; j++) { KeyFrame keyframe = animation.GetKeyFrame(j); if (keyframe.frameRef == -1) { keyframe.frameRef = i; keyframe.duration = 1; break; } } } } else { if (text.DrawClickText(600, y, i.ToString() + ": " + charDef.GetFrame(i).name, mouseState.X, mouseState.Y, mouseClick)) { if (selFrame != i) { if (charDef.GetFrame(i).name == "") { CopyFrame(selFrame, i); } selFrame = i; editingText = EDITING_FRAME_NAME; } } } } } if (drawButton(770, 280, 1, (mouseState.LeftButton == ButtonState.Pressed)) && frameScroll > 0) { frameScroll--; } if (drawButton(770, 570, 2, (mouseState.LeftButton == ButtonState.Pressed)) && frameScroll < charDef.GetFrameArray().Length - 20) { frameScroll++; } #endregion #region Animation List for (int i = animScroll; i < animScroll + 15; i++) { if (i < charDef.GetAnimationArray().Length) { int y = (i - animScroll) * 15 + 5; if (i == selAnim) { text.Color = Color.Lime; text.DrawText(5, y, i.ToString() + ": " + charDef.GetAnimation(i).name + (editingText == EDITING_ANIMATION_NAME ? "*" : "")); } else { if (text.DrawClickText(5, y, i.ToString() + ": " + charDef.GetAnimation(i).name, mouseState.X, mouseState.Y, mouseClick)) { selAnim = i; editingText = EDITING_ANIMATION_NAME; } } } } if (drawButton(170, 5, 1, (mouseState.LeftButton == ButtonState.Pressed)) && animScroll > 0) { animScroll--; } if (drawButton(170, 200, 2, (mouseState.LeftButton == ButtonState.Pressed)) && animScroll < charDef.GetAnimationArray().Length - 15) { animScroll++; } #endregion #region Keyframe List for (int i = keyFrameScroll; i < keyFrameScroll + 13; i++) { Animation animation = charDef.GetAnimation(selAnim); if (i < animation.getKeyFrameArray().Length) { int y = (i - keyFrameScroll) * 15 + 250; int frameRef = animation.GetKeyFrame(i).frameRef; String name = ""; if (frameRef > -1) { name = charDef.GetFrame(frameRef).name; } if (i == selKeyFrame) { text.Color = Color.Lime; text.DrawText(5, y, i.ToString() + ": " + name); } else { if (text.DrawClickText(5, y, i.ToString() + ": " + name, mouseState.X, mouseState.Y, mouseClick)) { selKeyFrame = i; } } if (animation.GetKeyFrame(i).frameRef > -1) { if (text.DrawClickText(110, y, "-", mouseState.X, mouseState.Y, mouseClick)) { animation.GetKeyFrame(i).duration--; if (animation.GetKeyFrame(i).duration <= 0) { for (int j = i; j < animation.getKeyFrameArray().Length - 1; j++) { KeyFrame keyframe = animation.GetKeyFrame(j); keyframe.frameRef = animation.GetKeyFrame(j + 1).frameRef; keyframe.duration = animation.GetKeyFrame(j + 1).duration; } animation.GetKeyFrame( animation.getKeyFrameArray().Length - 1).frameRef = -1; } } text.DrawText(125, y, animation.GetKeyFrame(i).duration.ToString()); if (text.DrawClickText(140, y, "+", mouseState.X, mouseState.Y, mouseClick)) { animation.GetKeyFrame(i).duration++; } } } } if (drawButton(170, 250, 1, (mouseState.LeftButton == ButtonState.Pressed)) && keyFrameScroll > 0) { keyFrameScroll--; } if (drawButton(170, 410, 2, (mouseState.LeftButton == ButtonState.Pressed)) && keyFrameScroll < charDef.GetAnimation(selAnim).getKeyFrameArray().Length - 13) { keyFrameScroll++; } #endregion #region Icon Palette spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); for (int l = 0; l < 4; l++) { Texture2D texture = null; switch (l) { case 0: texture = headTex[charDef.headIdx]; break; case 1: texture = torsoTex[charDef.torsoIdx]; break; case 2: texture = legsTex[charDef.legsIdx]; break; case 3: texture = weaponTex[charDef.weaponIdx]; break; } if (texture != null) { for (int i = 0; i < 25; i++) { Rectangle sRect = new Rectangle((i % 5) * 64, (i / 5) * 64, 64, 64); Rectangle dRect = new Rectangle(i * 23, 467 + l * 32, 23, 32); spriteBatch.Draw(nullTex, dRect, new Color(new Vector4(0f, 0f, 0f, 0.1f))); if (l == 3) { sRect.X = (i % 4) * 80; sRect.Y = (i / 4) * 64; sRect.Width = 80; if (i < 15) { dRect.X = i * 30; dRect.Width = 30; } } spriteBatch.Draw(texture, dRect, sRect, Color.White); if (dRect.Contains(mouseState.X, mouseState.Y)) { if (mouseClick) { if (l < 3 || i < 15) { charDef.GetFrame(selFrame).GetPart(selPart).idx = i + 64 * l; } } } } } } spriteBatch.End(); #endregion DrawCursor(); } mouseClick = false; base.Draw(gameTime); }
/// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); } UpdateKeys(); Animation animation = charDef.GetAnimation(selAnim); KeyFrame keyframe = animation.GetKeyFrame(curKey); if (playing) { curFrame += (float)gameTime.ElapsedGameTime.TotalSeconds * 30.0f; if (curFrame > (float)keyframe.duration) { curFrame -= (float)keyframe.duration; curKey++; keyframe = animation.GetKeyFrame(curKey); if (curKey >= animation.getKeyFrameArray().Length) { curKey = 0; } } } else { curKey = selKeyFrame; } if (keyframe.frameRef < 0) { curKey = 0; } mouseState = Mouse.GetState(); if (mouseState.LeftButton == ButtonState.Pressed) { if (preState.LeftButton == ButtonState.Released) { } else { if (CanEdit()) { int xM = mouseState.X - preState.X; int yM = mouseState.Y - preState.Y; charDef.GetFrame(selFrame).GetPart(selPart).location += new Vector2((float)xM / 2.0f, (float)yM / 2.0f); } } } else { if (preState.LeftButton == ButtonState.Pressed) { mouseClick = true; } } if (mouseState.RightButton == ButtonState.Pressed) { if (preState.RightButton == ButtonState.Pressed) { if (CanEdit()) { int yM = mouseState.Y - preState.Y; charDef.GetFrame(selFrame).GetPart(selPart).rotation += (float)yM / 100.0f; } } } if (mouseState.MiddleButton == ButtonState.Pressed) { if (preState.MiddleButton == ButtonState.Pressed) { if (CanEdit()) { int xM = mouseState.X - preState.X; int yM = mouseState.Y - preState.Y; charDef.GetFrame(selFrame).GetPart(selPart).scaling += new Vector2((float)xM * 0.01f, (float)yM * 0.01f); } } } preState = mouseState; base.Update(gameTime); }
public List <byte[]> GetChunkedKeyFrame(uint chunkSize, ushort sequenceNumber) { KeyFrame key = GetKeyFrame(sequenceNumber); return(GetChunkedFrame(chunkSize, key)); }
/// <summary> /// Recalculates tangents for all keyframes using the keyframe values and set tangent modes. /// </summary> private void UpdateTangents() { if (keyFrames.Length == 0) { return; } if (keyFrames.Length == 1) { keyFrames[0].inTangent = 0.0f; keyFrames[0].outTangent = 0.0f; return; } // First keyframe { KeyFrame keyThis = keyFrames[0]; KeyFrame keyNext = keyFrames[1]; keyThis.inTangent = 0.0f; TangentMode tangentMode = tangentModes[0]; if (tangentMode == TangentMode.Auto || tangentMode.HasFlag(TangentMode.OutAuto) || tangentMode.HasFlag(TangentMode.OutLinear)) { float diff = keyNext.time - keyThis.time; if (!MathEx.ApproxEquals(diff, 0.0f)) { keyThis.outTangent = (keyNext.value - keyThis.value) / diff; } else { keyThis.outTangent = float.PositiveInfinity; } } else if (tangentMode.HasFlag(TangentMode.OutStep)) { keyThis.outTangent = float.PositiveInfinity; } keyFrames[0] = keyThis; } // Inner keyframes for (int i = 1; i < keyFrames.Length - 1; i++) { KeyFrame keyPrev = keyFrames[i - 1]; KeyFrame keyThis = keyFrames[i]; KeyFrame keyNext = keyFrames[i + 1]; keyThis.inTangent = 0.0f; TangentMode tangentMode = tangentModes[i]; if (tangentMode == TangentMode.Auto) // Both automatic { float diff = keyNext.time - keyPrev.time; if (!MathEx.ApproxEquals(diff, 0.0f)) { keyThis.outTangent = (keyNext.value - keyPrev.value) / diff; } else { keyThis.outTangent = float.PositiveInfinity; } keyThis.inTangent = keyThis.outTangent; } else if (tangentMode == TangentMode.Free) // Both free { keyThis.inTangent = keyThis.outTangent; } else // Different per-tangent modes { // In tangent if (tangentMode.HasFlag(TangentMode.InAuto)) { float diff = keyNext.time - keyPrev.time; if (!MathEx.ApproxEquals(diff, 0.0f)) { keyThis.inTangent = (keyNext.value - keyPrev.value) / diff; } else { keyThis.inTangent = float.PositiveInfinity; } } else if (tangentMode.HasFlag(TangentMode.InLinear)) { float diff = keyThis.time - keyPrev.time; if (!MathEx.ApproxEquals(diff, 0.0f)) { keyThis.inTangent = (keyThis.value - keyPrev.value) / diff; } else { keyThis.inTangent = float.PositiveInfinity; } } else if (tangentMode.HasFlag(TangentMode.InStep)) { keyThis.inTangent = float.PositiveInfinity; } // Out tangent if (tangentMode.HasFlag(TangentMode.OutAuto)) { float diff = keyNext.time - keyPrev.time; if (!MathEx.ApproxEquals(diff, 0.0f)) { keyThis.outTangent = (keyNext.value - keyPrev.value) / diff; } else { keyThis.outTangent = float.PositiveInfinity; } } else if (tangentMode.HasFlag(TangentMode.OutLinear)) { float diff = keyNext.time - keyThis.time; if (!MathEx.ApproxEquals(diff, 0.0f)) { keyThis.outTangent = (keyNext.value - keyThis.value) / diff; } else { keyThis.outTangent = float.PositiveInfinity; } } else if (tangentMode.HasFlag(TangentMode.OutStep)) { keyThis.outTangent = float.PositiveInfinity; } } keyFrames[i] = keyThis; } // Last keyframe { KeyFrame keyThis = keyFrames[keyFrames.Length - 1]; KeyFrame keyPrev = keyFrames[keyFrames.Length - 2]; keyThis.outTangent = 0.0f; TangentMode tangentMode = tangentModes[tangentModes.Length - 1]; if (tangentMode == TangentMode.Auto || tangentMode.HasFlag(TangentMode.InAuto) || tangentMode.HasFlag(TangentMode.InLinear)) { float diff = keyThis.time - keyPrev.time; if (!MathEx.ApproxEquals(diff, 0.0f)) { keyThis.inTangent = (keyThis.value - keyPrev.value) / diff; } else { keyThis.inTangent = float.PositiveInfinity; } } else if (tangentMode.HasFlag(TangentMode.InStep)) { keyThis.inTangent = float.PositiveInfinity; } keyFrames[keyFrames.Length - 1] = keyThis; } }
private void UpdateKeyFrames(Vector3 origin, Vector3 target) { keyFrames = new KeyFrame[3]; keyFrames[0] = new KeyFrame( 0,12,origin, Vector3.zero, 24); keyFrames[1] = new KeyFrame(12,24,new Vector3(origin.x/2 + target.x/2, target.y/2 + 0.3f, origin.z/2 + target.z/2), Vector3.zero, 24); keyFrames[2] = new KeyFrame(24,60,new Vector3(target.x, target.y, target.z), Vector3.zero, 24); }
/// <summary> /// calculates the key frame of the animation of the specified time. /// If there are two bound animations, it will calculate by blending. /// </summary> /// <param name="time">animation time</param> /// <returns>Matrix of the animation key frame</returns> public Matrix GetKeyFrameMatrix(float time) { Matrix keyFrameMatrix = Matrix.Identity; if (firstBinder == null) return keyFrameMatrix; this.elapsedTime += time; // We have to blend animations, if it has multiple binders if (bindCount > 1) { float t = this.elapsedTime / this.blendTime; // Blending finished if (t > 1.0f) { keyFrameMatrix = secondBinder.GetKeyFrameMatrix(time); ShiftBinder(); } // Calculate blending matrix else { KeyFrame[] sourceKeyFrame = new KeyFrame[2]; KeyFrame targetKeyFrame = new KeyFrame(); // Calculate two keyFrame sourceKeyFrame[0] = firstBinder.GetKeyFrame(time); sourceKeyFrame[1] = secondBinder.GetKeyFrame(time); // Calculate blending key frame { // Interpolate translation using two key frame if (sourceKeyFrame[0].HasTranslation && sourceKeyFrame[1].HasTranslation) { targetKeyFrame.Translation = Vector3.Lerp( sourceKeyFrame[0].Translation, sourceKeyFrame[1].Translation, t); targetKeyFrame.HasTranslation = true; } else if (sourceKeyFrame[0].HasTranslation) { targetKeyFrame.Translation = sourceKeyFrame[0].Translation; targetKeyFrame.HasTranslation = true; } else if (sourceKeyFrame[1].HasTranslation) { targetKeyFrame.Translation = sourceKeyFrame[1].Translation; targetKeyFrame.HasTranslation = true; } // Interpolate scale using two key frame if (sourceKeyFrame[0].HasScale && sourceKeyFrame[1].HasScale) { targetKeyFrame.Scale = Vector3.Lerp( sourceKeyFrame[0].Scale, sourceKeyFrame[1].Scale, t); targetKeyFrame.HasScale = true; } else if (sourceKeyFrame[0].HasScale) { targetKeyFrame.Scale = sourceKeyFrame[0].Scale; targetKeyFrame.HasScale = true; } else if (sourceKeyFrame[1].HasScale) { targetKeyFrame.Scale = sourceKeyFrame[1].Scale; targetKeyFrame.HasScale = true; } // Interpolate rotation using two key frame if (sourceKeyFrame[0].HasRotation && sourceKeyFrame[1].HasRotation) { targetKeyFrame.Rotation = Quaternion.Slerp( sourceKeyFrame[0].Rotation, sourceKeyFrame[1].Rotation, t); targetKeyFrame.HasRotation = true; } else if (sourceKeyFrame[0].HasRotation) { targetKeyFrame.Rotation = sourceKeyFrame[0].Rotation; targetKeyFrame.HasRotation = true; } else if (sourceKeyFrame[1].HasRotation) { targetKeyFrame.Rotation = sourceKeyFrame[1].Rotation; targetKeyFrame.HasRotation = true; } } // Final, creates a frame matrix using blending key frame { // Has Rotation ? if (targetKeyFrame.HasRotation) { // Calculates rotation matrix using the quaternion keyFrameMatrix = Matrix.CreateFromQuaternion( targetKeyFrame.Rotation); } // Has translation ? if (targetKeyFrame.HasTranslation) { // Calculates position using keyframe keyFrameMatrix.Translation = targetKeyFrame.Translation; } // Has scale ? if (targetKeyFrame.HasScale) { // Calculates scale value using keyframe keyFrameMatrix = keyFrameMatrix * Matrix.CreateScale(targetKeyFrame.Scale); } } return keyFrameMatrix; } } else { // No blending, or finished blending keyFrameMatrix = firstBinder.GetKeyFrameMatrix(time); } return keyFrameMatrix; }
public void SamplingKeyFrames() { var keyFrame0 = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(1.0), _random.NextQuaternionF()); var keyFrame1 = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(2.0), _random.NextQuaternionF()); var keyFrame2 = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(3.0), _random.NextQuaternionF()); var animation = new QuaternionFKeyFrameAnimation(); animation.KeyFrames.Add(keyFrame0); animation.KeyFrames.Add(keyFrame1); animation.KeyFrames.Add(keyFrame2); var defaultSource = _random.NextQuaternionF(); var defaultTarget = _random.NextQuaternionF(); // Without interpolation animation.EnableInterpolation = false; Assert.AreEqual(keyFrame0.Value, animation.GetValue(TimeSpan.FromSeconds(1.0), defaultSource, defaultTarget)); Assert.AreEqual(keyFrame0.Value, animation.GetValue(TimeSpan.FromSeconds(1.75), defaultSource, defaultTarget)); Assert.AreEqual(keyFrame1.Value, animation.GetValue(TimeSpan.FromSeconds(2.0), defaultSource, defaultTarget)); Assert.AreEqual(keyFrame1.Value, animation.GetValue(TimeSpan.FromSeconds(2.75), defaultSource, defaultTarget)); Assert.AreEqual(keyFrame2.Value, animation.GetValue(TimeSpan.FromSeconds(3.0), defaultSource, defaultTarget)); // With interpolation animation.EnableInterpolation = true; Assert.IsTrue(QuaternionF.AreNumericallyEqual(keyFrame0.Value, animation.GetValue(TimeSpan.FromSeconds(1.0), defaultSource, defaultTarget))); var expected = InterpolationHelper.Lerp(keyFrame0.Value, keyFrame1.Value, 0.75f); Assert.AreEqual(expected, animation.GetValue(TimeSpan.FromSeconds(1.75), defaultSource, defaultTarget)); Assert.AreEqual(keyFrame1.Value, animation.GetValue(TimeSpan.FromSeconds(2.0), defaultSource, defaultTarget)); expected = InterpolationHelper.Lerp(keyFrame1.Value, keyFrame2.Value, 0.75f); Assert.AreEqual(expected, animation.GetValue(TimeSpan.FromSeconds(2.75), defaultSource, defaultTarget)); Assert.AreEqual(keyFrame2.Value, animation.GetValue(TimeSpan.FromSeconds(3.0), defaultSource, defaultTarget)); }
public void ShouldReturnTheFirstOrLastKeyFrame() { var keyFrame0 = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(1.0), _random.NextQuaternionF()); var keyFrame1 = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(2.0), _random.NextQuaternionF()); var keyFrame2 = new KeyFrame<QuaternionF>(TimeSpan.FromSeconds(3.0), _random.NextQuaternionF()); var animation = new QuaternionFKeyFrameAnimation(); animation.KeyFrames.Add(keyFrame0); animation.KeyFrames.Add(keyFrame1); animation.KeyFrames.Add(keyFrame2); var defaultSource = _random.NextQuaternionF(); var defaultTarget = _random.NextQuaternionF(); // Pre loop Assert.IsTrue(QuaternionF.AreNumericallyEqual(keyFrame0.Value, animation.GetValue(TimeSpan.FromSeconds(0.0), defaultSource, defaultTarget))); // Post loop Assert.IsTrue(QuaternionF.AreNumericallyEqual(keyFrame2.Value, animation.GetValue(TimeSpan.FromSeconds(3.75), defaultSource, defaultTarget))); }
void MakeKeyFramesAndJointData() { var keyBlobs = animation.keyFrames; keyframes = new List <List <KeyFrame> >(10); for (int i = 0; i < 10; i++) { keyframes.Add(new List <KeyFrame>()); } jointData = new JointData[numJoints]; List <QJoint> indexedJoints = new List <QJoint>(numJoints); for (int i = 0; i < numJoints; i++) { indexedJoints.Add(null); } foreach (KeyValuePair <string, KeyBlob> kv in keyBlobs) { QJoint curJoint = FindJointByName(kv.Key); int curIdx = curJoint.index; indexedJoints[curIdx] = curJoint; } for (int i = 0; i < numJoints; i++) { QJoint joint = indexedJoints[i]; KeyBlob blob = keyBlobs[joint.name]; int[] jointDataArgs = new int[20]; for (int j = 0; j < 10; j++) { string attribName = "m_LocalPosition.x"; switch (j) { case (1): attribName = "m_LocalPosition.y"; break; case (2): attribName = "m_LocalPosition.z"; break; case (3): attribName = "m_LocalRotation.x"; break; case (4): attribName = "m_LocalRotation.y"; break; case (5): attribName = "m_LocalRotation.z"; break; case (6): attribName = "m_LocalRotation.w"; break; case (7): attribName = "m_LocalScale.x"; break; case (8): attribName = "m_LocalScale.y"; break; case (9): attribName = "m_LocalScale.z"; break; } SortedList <float, ScalarFrame> frames = blob.keyedAttributes[attribName].values; jointDataArgs[j * 2] = keyframes[j].Count; jointDataArgs[j * 2 + 1] = frames.Count; for (int k = 0; k < frames.Count; k++) { float time = frames.Keys[k]; ScalarFrame frame = frames.Values[k]; KeyFrame newFrame = new KeyFrame(time, frame.value, frame.inTangent, frame.outTangent); keyframes[j].Add(newFrame); } } int numChildren = NumChildren(i); Matrix4x4 bindPose = bindTransforms[i];//.inverse; jointData[i] = new JointData(jointDataArgs, numChildren, bindPose); } }
public override void _presenter_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { Stroke lastStroke = _inkCanvas.Strokes.Last(); if (!(_startPoint.X == 0 && _startPoint.Y == 0)) { //先清空原来选中的关键帧序列 //clearPreMessage(); _currPoint = e.GetPosition(_inkCanvas); if (_currPoint.Y < TableGrid.ActualHeight / 2) { if (_currPoint.X < TableGrid.ActualWidth / 2) { _currPoint.X -= ((InkCanvas)_inkCanvas.Children[0]).Margin.Left; _currPoint.Y -= ((InkCanvas)_inkCanvas.Children[0]).Margin.Top; endIndex = _inkCollector._mainPage.VideoSummarizationControl.SpiralSummarizationLeft.getSelectedKeyFrameIndex(_currPoint); if (startIndex != int.MinValue && endIndex != int.MinValue) { endKeyFrame = _inkCollector._mainPage.VideoSummarizationControl.SpiralSummarizationLeft.KeyFrames[endIndex]; endSpiralSummarization = _inkCollector._mainPage.VideoSummarizationControl.SpiralSummarizationLeft; } _currPoint.X += ((InkCanvas)_inkCanvas.Children[0]).Margin.Left; _currPoint.Y += ((InkCanvas)_inkCanvas.Children[0]).Margin.Top; } //右边的螺旋摘要 else { Point endPointRight = e.GetPosition((InkCanvas)_inkCanvas.Children[1]); endIndex = _inkCollector._mainPage.VideoSummarizationControl.SpiralSummarizationRight.getSelectedKeyFrameIndex(endPointRight); if (startIndex != int.MinValue && endIndex != int.MinValue) { endKeyFrame = _inkCollector._mainPage.VideoSummarizationControl.SpiralSummarizationRight.KeyFrames[endIndex]; endSpiralSummarization = _inkCollector._mainPage.VideoSummarizationControl.SpiralSummarizationRight; } } } else { Point endPointBottom = e.GetPosition((InkCanvas)_inkCanvas.Children[2]); endIndex = _inkCollector._mainPage.VideoSummarizationControl.SpiralSummarizationBottom.getSelectedKeyFrameIndex(endPointBottom); if (startIndex != int.MinValue && endIndex != int.MinValue) { endKeyFrame = _inkCollector._mainPage.VideoSummarizationControl.SpiralSummarizationBottom.KeyFrames[endIndex]; endSpiralSummarization = _inkCollector._mainPage.VideoSummarizationControl.SpiralSummarizationBottom; } } if (startKeyFrame != null && endKeyFrame != null && startKeyFrame != endKeyFrame) { startKeyFrame.HyperLink = endKeyFrame; _inkCollector.HyperLinkKeyFrames.Add(startKeyFrame); startKeyFrame.HyperLinkSpiralSummarization = endSpiralSummarization; _inkCanvas.Strokes.Remove(_inkCanvas.Strokes.Last()); InkTool.getInstance().DrawLine(_startPoint.X, _startPoint.Y, _currPoint.X, _currPoint.Y, _inkCanvas, Colors.Red); InkTool.getInstance().drawPoint(_startPoint.X, _startPoint.Y, 8, Colors.Blue, _inkCanvas); } else { mouseGesture.StopCapture(); _inkCanvas.Strokes.Remove(lastStroke); } _startPoint.X = 0; _startPoint.Y = 0; } }
public Skeleton Import(Stream stream) { using (var reader = XmlReader.Create(stream)) { var skeleton = new Skeleton(); Dictionary<string, int> nameToId = new Dictionary<string, int>(); while (reader.Read()) { if (reader.NodeType != XmlNodeType.Element) continue; // Read bones if (reader.Name == "bones") { var bonesReader = reader.ReadSubtree(); while (bonesReader.Read()) { if (bonesReader.NodeType != XmlNodeType.Element || bonesReader.Name != "bone") continue; var index = StringConverter.Parse<int>(bonesReader.GetAttribute("id")); var name = bonesReader.GetAttribute("name"); nameToId.Add(name, index); Vector3 position = Vector3.Zero; Quaternion orientation = Quaternion.Identity; var boneReader = bonesReader.ReadSubtree(); while (boneReader.Read()) { if (boneReader.NodeType != XmlNodeType.Element) continue; if (boneReader.Name == "position") { position = ReadVector3(boneReader); } else if (boneReader.Name == "rotation") { var angle = StringConverter.Parse<float>(boneReader.GetAttribute("angle")); boneReader.ReadToFollowing("axis"); var axis = ReadVector3(boneReader); orientation = Quaternion.FromAxisAngle(axis, angle); } } skeleton.Bones.Insert(index, new Transform { Position = position, Orientation = orientation }); } } // Read hierarchy else if (reader.Name == "bonehierarchy") { var boneReader = reader.ReadSubtree(); while (boneReader.Read()) { if (boneReader.NodeType != XmlNodeType.Element || boneReader.Name != "boneparent") continue; var index = nameToId[boneReader.GetAttribute("bone")]; var parentId = nameToId[boneReader.GetAttribute("parent")]; while (index >= skeleton.BoneParents.Count) skeleton.BoneParents.Add(-1); skeleton.BoneParents.Insert(index, parentId); } } // Read animations else if (reader.Name == "animations") { var animationsReader = reader.ReadSubtree(); while (animationsReader.Read()) { if (animationsReader.NodeType != XmlNodeType.Element || animationsReader.Name != "animation") continue; var animation = new Animation(); skeleton.Animations.Add(animation); animation.Name = animationsReader.GetAttribute("name"); animation.Length = StringConverter.Parse<float>(animationsReader.GetAttribute("length")); var animationReader = animationsReader.ReadSubtree(); while (animationReader.Read()) { if (animationReader.NodeType != XmlNodeType.Element || animationReader.Name != "track") continue; var track = new Track(); animation.Tracks.Add(track); track.BoneIndex = nameToId[animationReader.GetAttribute("bone")]; var trackReader = animationReader.ReadSubtree(); while (trackReader.Read()) { if (trackReader.NodeType != XmlNodeType.Element || trackReader.Name != "keyframe") continue; var keyFrame = new KeyFrame(); track.KeyFrames.Add(keyFrame); keyFrame.Time = StringConverter.Parse<float>(trackReader.GetAttribute("time")); var position = Vector3.Zero; var orientation = Quaternion.Identity; var keyframeReader = trackReader.ReadSubtree(); while (keyframeReader.Read()) { if (keyframeReader.NodeType != XmlNodeType.Element) continue; if (keyframeReader.Name == "translate") { position = ReadVector3(keyframeReader); } else if (keyframeReader.Name == "rotate") { var angle = StringConverter.Parse<float>(keyframeReader.GetAttribute("angle")); keyframeReader.ReadToFollowing("axis"); var axis = ReadVector3(keyframeReader); orientation = Quaternion.FromAxisAngle(axis, angle); } } keyFrame.Transform.Position = position; keyFrame.Transform.Orientation = orientation; } } } } } return skeleton; } }