public Vector3Sampler(object t, string memberName, AnimationCurve x, AnimationCurve y, AnimationCurve z) : base(t, memberName) { this.x = x; this.y = y; this.z = z; }
public ColorGradingCurve(AnimationCurve curve, float zeroValue, bool loop, Vector2 bounds) { this.curve = curve; m_ZeroValue = zeroValue; m_Loop = loop; m_Range = bounds.magnitude; }
public FloatSampler(object t, string memberName, AnimationCurve curve) : base(t, memberName) { this.curve = curve; if (curve == null) { throw new ArgumentNullException("curve", "The animation curve cannot be null"); } }
internal override void AddCurveData(AnimationClipCurveData curveData) { base.AddCurveData(curveData); if (curveData.propertyName.EndsWith(".x")) { x = curveData.curve; } if (curveData.propertyName.EndsWith(".y")) { y = curveData.curve; } if (curveData.propertyName.EndsWith(".z")) { z = curveData.curve; } }
public void Cache() { if (!m_Loop) return; var length = curve.length; if (length < 2) return; if (m_InternalLoopingCurve == null) m_InternalLoopingCurve = new AnimationCurve(); var prev = curve[length - 1]; prev.time -= m_Range; var next = curve[0]; next.time += m_Range; m_InternalLoopingCurve.keys = curve.keys; m_InternalLoopingCurve.AddKey(prev); m_InternalLoopingCurve.AddKey(next); }
//public delegate float[] ReverseZ(float[] current, float[] last); public void SetAnimationCurve( AnimationClip targetClip, string relativePath, string[] propertyNames, float[] input, float[] output, string interpolation, Type curveType, Func <float[], float[], float[]> reverse) { var tangentMode = GetTangentMode(interpolation); // Debug.Log(relativePath+" == "+interpolation); // Debug.Log("input = "+string.Join(",",input)); // Debug.Log("output = "+string.Join(",",output)); var curveCount = propertyNames.Length; AnimationCurve[] curves = new AnimationCurve[curveCount]; List <Keyframe>[] keyframes = new List <Keyframe> [curveCount]; int elementNum = curveCount; int inputIndex = 0; //Quaternion用 float[] last = new float[curveCount]; if (last.Length == 4) { last[3] = 1.0f; } for (inputIndex = 0; inputIndex < input.Length; ++inputIndex) { var time = input[inputIndex]; var outputIndex = 0; if (tangentMode == TangentMode.Cubicspline) { outputIndex = inputIndex * elementNum * 3; var value = new float[curveCount]; for (int i = 0; i < value.Length; i++) { value[i] = output[outputIndex + elementNum + i]; } var reversed = reverse(value, last); last = reversed; for (int i = 0; i < keyframes.Length; i++) { if (keyframes[i] == null) { keyframes[i] = new List <Keyframe>(); } keyframes[i].Add(new Keyframe( time, reversed[i], output[outputIndex + i], output[outputIndex + i + elementNum * 2])); } } else { outputIndex = inputIndex * elementNum; var value = new float[curveCount]; for (int i = 0; i < value.Length; i++) { value[i] = output[outputIndex + i]; } var reversed = reverse(value, last); last = reversed; for (int i = 0; i < keyframes.Length; i++) { if (keyframes[i] == null) { keyframes[i] = new List <Keyframe>(); } if (tangentMode == TangentMode.Linear) { keyframes[i].Add(new Keyframe(time, reversed[i], 0, 0)); if (keyframes[i].Count > 0) { CalculateTanget(keyframes[i], keyframes[i].Count - 1); } } else if (tangentMode == TangentMode.Constant) { keyframes[i].Add(new Keyframe(time, reversed[i], 0, float.PositiveInfinity)); } } } } for (int i = 0; i < curves.Length; i++) { curves[i] = new AnimationCurve(); for (int j = 0; j < keyframes[i].Count; j++) { curves[i].AddKey(keyframes[i][j]); } targetClip.SetCurve(relativePath, curveType, propertyNames[i], curves[i]); } }
public static Vector3[] SmoothLine(Vector3[] inputPoints, float segmentSize) { //create curves AnimationCurve curveX = new AnimationCurve(); AnimationCurve curveY = new AnimationCurve(); AnimationCurve curveZ = new AnimationCurve(); //create keyframe sets Keyframe[] keysX = new Keyframe[inputPoints.Length]; Keyframe[] keysY = new Keyframe[inputPoints.Length]; Keyframe[] keysZ = new Keyframe[inputPoints.Length]; //set keyframes for (int i = 0; i < inputPoints.Length; i++) { keysX[i] = new Keyframe(i, inputPoints[i].x); keysY[i] = new Keyframe(i, inputPoints[i].y); keysZ[i] = new Keyframe(i, inputPoints[i].z); } //apply keyframes to curves curveX.keys = keysX; curveY.keys = keysY; curveZ.keys = keysZ; //smooth curve tangents for (int i = 0; i < inputPoints.Length; i++) { curveX.SmoothTangents(i, 0); curveY.SmoothTangents(i, 0); curveZ.SmoothTangents(i, 0); } //list to write smoothed values to List <Vector3> lineSegments = new List <Vector3>(); //find segments in each section for (int i = 0; i < inputPoints.Length; i++) { //add first point lineSegments.Add(inputPoints[i]); //make sure within range of array if (i + 1 < inputPoints.Length) { //find distance to next point float distanceToNext = Vector3.Distance(inputPoints[i], inputPoints[i + 1]); //number of segments int segments = (int)(distanceToNext / segmentSize); //add segments for (int s = 1; s < segments; s++) { //interpolated time on curve float time = ((float)s / (float)segments) + (float)i; //sample curves to find smoothed position Vector3 newSegment = new Vector3(curveX.Evaluate(time), curveY.Evaluate(time), curveZ.Evaluate(time)); //add to list lineSegments.Add(newSegment); } } } return(lineSegments.ToArray()); }
// 移動のみの抽出 void CreateKeysForLocation(MMD.VMD.VMDFormat format, AnimationClip clip, string current_bone, string bone_path) { try { List<MMD.VMD.VMDFormat.Motion> mlist = format.motion_list.motion[current_bone]; List<Keyframe> lx_keys = new List<Keyframe>(); List<Keyframe> ly_keys = new List<Keyframe>(); List<Keyframe> lz_keys = new List<Keyframe>(); for (int i = 0; i < mlist.Count; i++) { const float tick_time = 1.0f / 30.0f; // 0だけのいらんデータを捨てる if (Vector3.zero != mlist[i].location) { float tick = mlist[i].flame_no * tick_time; float a_x, a_y, a_z, b_x, b_y, b_z; // 各軸別々に補間が付いてる a_x = GetTangent(mlist[i].interpolation, 0, 0); a_y = GetTangent(mlist[i].interpolation, 1, 0); a_z = GetTangent(mlist[i].interpolation, 2, 0); b_x = GetTangent(mlist[i].interpolation, 0, 1); b_y = GetTangent(mlist[i].interpolation, 1, 1); b_z = GetTangent(mlist[i].interpolation, 2, 1); lx_keys.Add(new Keyframe(tick, mlist[i].location.x, a_x, b_x)); ly_keys.Add(new Keyframe(tick, mlist[i].location.y, a_y, b_y)); lz_keys.Add(new Keyframe(tick, mlist[i].location.z, a_z, b_z)); } } // 回転ボーンの場合はデータが入ってないはず int count = lx_keys.Count; if (count != 0) { AnimationCurve curve_x = new AnimationCurve(lx_keys.ToArray()); AnimationCurve curve_y = new AnimationCurve(ly_keys.ToArray()); AnimationCurve curve_z = new AnimationCurve(lz_keys.ToArray()); clip.SetCurve(bone_path, typeof(Transform), "localPosition.x", curve_x); clip.SetCurve(bone_path, typeof(Transform), "localPosition.y", curve_y); clip.SetCurve(bone_path, typeof(Transform), "localPosition.z", curve_z); } } catch (KeyNotFoundException) { //Debug.LogError("互換性のないボーンが読み込まれました:" + current_bone); } }
void CreateKeysForSkin(MMD.VMD.VMDFormat format, AnimationClip clip) { const float tick_time = 1f / 30f; // 全ての表情に打たれているキーフレームを探索 List<VMD.VMDFormat.SkinData> s; foreach (var skin in format.skin_list.skin) { s = skin.Value; Keyframe[] keyframe = new Keyframe[skin.Value.Count]; // キーフレームの登録を行う for (int i = 0; i < skin.Value.Count; i++) keyframe[i] = new Keyframe(s[i].flame_no * tick_time, s[i].weight); // Z軸移動にキーフレームを打つ AnimationCurve curve = new AnimationCurve(keyframe); clip.SetCurve(format.pmd + "/Expression/" + skin.Key, typeof(Transform), "localPosition.z", curve); } }
public Cone AddCone(Vector2 size, int numSegment, float angle, Vector3 dir, int uvStretch, float maxFps, bool usedelta, AnimationCurve deltaAngle) { VertexSegment segment = GetVertices((numSegment + 1) * 2, numSegment * 6); Cone f = new Cone(segment, size, numSegment, angle, dir, uvStretch, maxFps); f.UseDeltaAngle = usedelta; f.CurveAngle = deltaAngle; return(f); }
/************************************************* * * Animation Curve Enhancement * *************************************************/ /// <summary> /// AnimationCurve 的x轴不能设置负值,这里的作用是,如果 time < 0 ,则取原点对称的值 /// </summary> public static float EvaluateEx(this AnimationCurve curve, float time) { return(Math.Sign(time) * curve.Evaluate(Math.Abs(time))); }
public void Setup() { animation = new Components.Animation(); h = new TestHierarchy(); leftRight = new AnimationClip() { length = 1 }; simple = new AnimationCurve() { PreLoop = CurveLoopType.Constant, PostLoop = CurveLoopType.Constant }; empty = new AnimationCurve() { PreLoop = CurveLoopType.Constant, PostLoop = CurveLoopType.Constant }; simple.Keys.Add(new CurveKey(0, 0, 10, 10, CurveContinuity.Smooth)); simple.Keys.Add(new CurveKey(0.5f, 5, 0, 0, CurveContinuity.Smooth)); simple.Keys.Add(new CurveKey(1, 0, 0, 0, CurveContinuity.Smooth)); }
public void SetAnimationPosition(Vector2 StartAnchoredPos, Vector2 EndAnchoredPos, AnimationCurve EntryTween, AnimationCurve ExitTween) { currentAnimationGoing.SetAnimationPos(StartAnchoredPos, EndAnchoredPos, EntryTween, ExitTween, rectTransform); }
/// <summary>Sets the ease of the tween using an AnimationCurve. /// <para>Has no effect on Sequences</para></summary> public TweenParms SetEase(AnimationCurve animCurve) { this.easeType = Ease.INTERNAL_Custom; this.customEase = new EaseCurve(animCurve).Evaluate; return(this); }
public static MeshData GenerateTerrainMesh(float[,] HeightMap, float HeightMultiplier, AnimationCurve _HeightCurve, int LevelOfDetail) { int simpleIncrent = (LevelOfDetail == 0)? 1:LevelOfDetail * 2; AnimationCurve HeightCurve = new AnimationCurve(_HeightCurve.keys); int brordedWidth = HeightMap.GetLength(0); int meshSize = brordedWidth - 2 * simpleIncrent; int meshSizeunSimple = brordedWidth - 2; float TopLeftX = (meshSizeunSimple - 1) / -2f; float TopLeftZ = (meshSizeunSimple - 1) / 2f; int verticesPerLine = (meshSize - 1) / simpleIncrent + 1; MeshData meshData = new MeshData(verticesPerLine); int[,] vertexInices = new int[brordedWidth, brordedWidth]; int meshvertexIndex = 0; int BordervertexIndex = -1; int vertexIndex = 0; for (int y = 0; y < brordedWidth; y += simpleIncrent) { for (int x = 0; x < brordedWidth; x += simpleIncrent) { bool isBordervertex = y == 0 || y == brordedWidth - 1 || x == 0 || x == brordedWidth - 1; if (isBordervertex) { vertexInices[x, y] = BordervertexIndex; BordervertexIndex--; } else { vertexInices[x, y] = meshvertexIndex; meshvertexIndex++; } } } for (int y = 0; y < brordedWidth; y += simpleIncrent) { for (int x = 0; x < brordedWidth; x += simpleIncrent) { int VertexIndex = vertexInices[x, y]; Vector2 precent = new Vector2((x - simpleIncrent) / (float)meshSize, (y - simpleIncrent) / (float)meshSize); float height = HeightCurve.Evaluate(HeightMap[x, y]) * HeightMultiplier; Vector3 vertexPos = new Vector3(TopLeftX + precent.x * meshSizeunSimple, height, TopLeftZ - precent.y * meshSizeunSimple); meshData.addvertex(vertexPos, precent, VertexIndex); if (x < brordedWidth - 1 && y < brordedWidth - 1) { int a = vertexInices[x, y]; int b = vertexInices[x + simpleIncrent, y]; int c = vertexInices[x, y + simpleIncrent]; int d = vertexInices[x + simpleIncrent, y + simpleIncrent]; meshData.AddTriangle(a, d, c); meshData.AddTriangle(d, a, b); } vertexIndex++; } } meshData.Bake(); return(meshData); }
void Update() { //reset array transform if (TestNullReferenceTransform()) { pointsTransform = ReCalculateArrayTransform(); } if (pointsTransform.Length < 2 && previewCountPointsTransform != pointsTransform.Length) { points = new Vector3[0]; lineRenderer.SetVertexCount(0); } previewCountPointsTransform = pointsTransform.Length; //inherit points for array transform if (pointsTransform.Length > 1) { points = new Vector3[pointsTransform.Length]; for (int i = 0; i < pointsTransform.Length; i++) { points[i] = pointsTransform[i].position; } } //exit if not met the basic conditions if (points.Length < 2) { return; } //create lights if (points.Length != previewCountPoints && onLight || onLight && lights == null) { DestroyLights(); lights = new Light[points.Length - 1]; for (int i = 0; i < points.Length - 1; i++) { Vector3 midPoint = Vector3.Lerp(points[i], points[i + 1], 0.5f); GameObject go = new GameObject("light " + i.ToString()); go.transform.position = midPoint; go.transform.parent = gameObject.transform; lights[i] = go.AddComponent <Light>(); } } previewCountPoints = points.Length; //Destroy lights if (!onLight && lights != null) { DestroyLights(); } if (Time.time > lastTimeChangePosition + delayChangedPosition) { lastTimeChangePosition = Time.time; //save prewiev state line if (listSmoothingPointsPatch.Count > 0) { previewListSmoothingPointsPatch.Clear(); previewListSmoothingPointsPatch.AddRange(listSmoothingPointsPatch); } listSmoothingPointsPatch.Clear(); listBasePointsPatch.Clear(); AnimationCurve curveTurbulent = new AnimationCurve(new Keyframe(0, peripheryAmplititude * scale), new Keyframe(1, centralAmplitude * scale), new Keyframe(2, peripheryAmplititude * scale)); for (int i = 0; i < points.Length - 1; i++) { //create point for line electricity List <Vector3> listBasePoints = new List <Vector3>(); Vector3 directionToPoint2 = points[i + 1] - points[i]; float fullDistance = Vector3.Distance(points[i], points[i + 1]); int countPoints = (int)(fullDistance / minDistanceBeetwenPoints) + 1; float currentDistance = (fullDistance / countPoints); for (int g = 0; g < countPoints + 1; g++) { Vector3 newPointPosition = points[i] + (directionToPoint2.normalized * (currentDistance * g)); float coeffEvolute = ((float)g / (float)(countPoints)) * 2; Vector3 axisRandom = Quaternion.AngleAxis(Random.Range(-180, 180), directionToPoint2) * new Vector3(directionToPoint2.y, directionToPoint2.x * -1, 0); newPointPosition = newPointPosition + (axisRandom.normalized * (Random.Range(-curveTurbulent.Evaluate(coeffEvolute), curveTurbulent.Evaluate(coeffEvolute)))); listBasePoints.Add(newPointPosition); } listBasePointsPatch.AddRange(listBasePoints); //Move lights to midle points line electricity if (onLight) { lights[i].transform.position = Vector3.Lerp(points[i], points[i + 1], 0.5f); } //create points smoothing Bezier bezier = new Bezier(listBasePoints.ToArray()); int countSmoothingPoints = (int)(fullDistance / minDistanceBeetwenSmoothingPoints); listSmoothingPointsPatch.AddRange(bezier.GetSmoothingPoints(countSmoothingPoints)); } } //apply light setting if (onLight) { foreach (Light l in lights) { l.color = color; l.intensity = (Random.Range(centralAmplitude, centralAmplitude * 0.8f) * lightIntesity) * scale; } } // lerp prewiev state to next state List <Vector3> mixedListSmoothingPointsPatch = new List <Vector3>(); if (previewListSmoothingPointsPatch.Count > 0) { float mixCoefficient = (Time.time - lastTimeChangePosition) / delayChangedPosition; for (int i = 0; i < Mathf.Min(previewListSmoothingPointsPatch.Count, listSmoothingPointsPatch.Count); i++) { mixedListSmoothingPointsPatch.Add(Vector3.Lerp(previewListSmoothingPointsPatch[i], listSmoothingPointsPatch[i], mixCoefficient)); } } else { mixedListSmoothingPointsPatch.AddRange(listSmoothingPointsPatch); } //set parametrs to lineRenderer lineRenderer.SetVertexCount(mixedListSmoothingPointsPatch.Count); for (int p = 0; p < mixedListSmoothingPointsPatch.Count; p++) { lineRenderer.SetPosition(p, mixedListSmoothingPointsPatch[p]); } lineRenderer.SetWidth(Width, Width); lineRenderer.SetColors(color, color); }
public static void PlayHapticClipOver(this RagdollHand hand, AnimationCurve curve, float duration) { hand.StartCoroutine(HapticPlayer(hand, curve, duration)); }
/// <summary> /// Creates a new instance of this plugin. /// </summary> /// <param name="p_endVal"> /// The <see cref="float"/> value to tween to. /// </param> /// <param name="p_easeAnimCurve"> /// The <see cref="AnimationCurve"/> to use for easing. /// </param> /// <param name="p_isRelative"> /// If <c>true</c>, the given end value is considered relative instead than absolute. /// </param> public PlugVector3X(float p_endVal, AnimationCurve p_easeAnimCurve, bool p_isRelative) : base(p_endVal, p_easeAnimCurve, p_isRelative) { }
public void SetCurve(string relativePath, Type type, string propertyName, AnimationCurve curve){}
private static int INTERNAL_CALL_MoveKey(AnimationCurve self, int index, ref Keyframe key){}
public void SetAnimationScale(Vector3 StartAnchoredScale, Vector3 EndAnchoredScale, AnimationCurve EntryTween, AnimationCurve ExitTween) { currentAnimationGoing.SetAnimationScale(StartAnchoredScale, EndAnchoredScale, EntryTween, ExitTween); }
public void SetAnimationRotation(Vector3 StartAnchoredEulerAng, Vector3 EndAnchoredEulerAng, AnimationCurve EntryTween, AnimationCurve ExitTween) { currentAnimationGoing.SetAnimationRotation(StartAnchoredEulerAng, EndAnchoredEulerAng, EntryTween, ExitTween); }
/// <summary> /// Shows the curve editor window that allows the user to edit a single curve. /// </summary> /// <param name="curve">Curve to initialize the window with.</param> /// <param name="closedCallback">Optional callback to trigger when the user finishes editing the curve or /// cancels out of the dialog.</param> /// <returns>An instance of the curve editor window.</returns> public static CurveEditorWindow Show(AnimationCurve curve, Action <bool, AnimationCurve> closedCallback = null) { CurveEditorWindow picker = new CurveEditorWindow(curve, closedCallback); return(picker); }
public Pattern01(int _waveCount, float _animationTime, float _bulletAnimationTime, float _animationAngle, AnimationCurve _curve_Angle) { this._waveCount = _waveCount; this._animationTime = _animationTime; this._bulletAnimationTime = _bulletAnimationTime; this._animationAngle = _animationAngle; this._curve_Angle = _curve_Angle; }
private unsafe object ExportAnimation(ICommandContext commandContext, ContentManager contentManager, bool failOnEmptyAnimation) { // Read from model file var modelSkeleton = LoadSkeleton(commandContext, contentManager); // we get model skeleton to compare it to real skeleton we need to map to AdjustSkeleton(modelSkeleton); TimeSpan duration; var animationClips = LoadAnimation(commandContext, contentManager, out duration); // Fix the animation frames double startFrameSeconds = StartFrame.TotalSeconds; double endFrameSeconds = EndFrame.TotalSeconds; var startTime = CompressedTimeSpan.FromSeconds(-startFrameSeconds); foreach (var clip in animationClips) { foreach (var animationCurve in clip.Value.Curves) { animationCurve.ShiftKeys(startTime); } } var durationTimeSpan = TimeSpan.FromSeconds((endFrameSeconds - startFrameSeconds)); if (duration > durationTimeSpan) { duration = durationTimeSpan; } var animationClip = new AnimationClip { Duration = duration }; if (animationClips.Count > 0) { AnimationClip rootMotionAnimationClip = null; // If root motion is explicitely enabled, or if there is no skeleton, try to find root node and apply animation directly on TransformComponent if ((AnimationRootMotion || SkeletonUrl == null) && modelSkeleton.Nodes.Length >= 1) { // No skeleton, map root node only // TODO: For now, it seems to be located on node 1 in FBX files. Need to check if always the case, and what happens with Assimp var rootNode0 = modelSkeleton.Nodes.Length >= 1 ? modelSkeleton.Nodes[0].Name : null; var rootNode1 = modelSkeleton.Nodes.Length >= 2 ? modelSkeleton.Nodes[1].Name : null; if ((rootNode0 != null && animationClips.TryGetValue(rootNode0, out rootMotionAnimationClip)) || (rootNode1 != null && animationClips.TryGetValue(rootNode1, out rootMotionAnimationClip))) { foreach (var channel in rootMotionAnimationClip.Channels) { var curve = rootMotionAnimationClip.Curves[channel.Value.CurveIndex]; // Root motion var channelName = channel.Key; if (channelName.StartsWith("Transform.")) { animationClip.AddCurve($"[TransformComponent.Key]." + channelName.Replace("Transform.", string.Empty), curve); } // Also apply Camera curves // TODO: Add some other curves? if (channelName.StartsWith("Camera.")) { animationClip.AddCurve($"[CameraComponent.Key]." + channelName.Replace("Camera.", string.Empty), curve); } } } } // Load asset reference skeleton if (SkeletonUrl != null) { var skeleton = contentManager.Load <Skeleton>(SkeletonUrl); var skeletonMapping = new SkeletonMapping(skeleton, modelSkeleton); // Process missing nodes foreach (var nodeAnimationClipEntry in animationClips) { var nodeName = nodeAnimationClipEntry.Key; var nodeAnimationClip = nodeAnimationClipEntry.Value; var nodeIndex = modelSkeleton.Nodes.IndexOf(x => x.Name == nodeName); // Node doesn't exist in skeleton? skip it if (nodeIndex == -1 || skeletonMapping.SourceToSource[nodeIndex] != nodeIndex) { continue; } // Skip root motion node (if any) if (nodeAnimationClip == rootMotionAnimationClip) { continue; } // Find parent node var parentNodeIndex = modelSkeleton.Nodes[nodeIndex].ParentIndex; if (parentNodeIndex != -1 && skeletonMapping.SourceToSource[parentNodeIndex] != parentNodeIndex) { // Some nodes were removed, we need to concat the anim curves var currentNodeIndex = nodeIndex; var nodesToMerge = new List <Tuple <ModelNodeDefinition, AnimationBlender, AnimationClipEvaluator> >(); while (currentNodeIndex != -1 && currentNodeIndex != skeletonMapping.SourceToSource[parentNodeIndex]) { AnimationClip animationClipToMerge; AnimationClipEvaluator animationClipEvaluator = null; AnimationBlender animationBlender = null; if (animationClips.TryGetValue(modelSkeleton.Nodes[currentNodeIndex].Name, out animationClipToMerge)) { animationBlender = new AnimationBlender(); animationClipEvaluator = animationBlender.CreateEvaluator(animationClipToMerge); } nodesToMerge.Add(Tuple.Create(modelSkeleton.Nodes[currentNodeIndex], animationBlender, animationClipEvaluator)); currentNodeIndex = modelSkeleton.Nodes[currentNodeIndex].ParentIndex; } // Put them in proper parent to children order nodesToMerge.Reverse(); // Find all key times // TODO: We should detect discontinuities and keep them var animationKeysSet = new HashSet <CompressedTimeSpan>(); foreach (var node in nodesToMerge) { if (node.Item3 != null) { foreach (var curve in node.Item3.Clip.Curves) { foreach (CompressedTimeSpan time in curve.Keys) { animationKeysSet.Add(time); } } } } // Sort key times var animationKeys = animationKeysSet.ToList(); animationKeys.Sort(); var animationOperations = new FastList <AnimationOperation>(); var combinedAnimationClip = new AnimationClip(); var translationCurve = new AnimationCurve <Vector3>(); var rotationCurve = new AnimationCurve <Quaternion>(); var scaleCurve = new AnimationCurve <Vector3>(); // Evaluate at every key frame foreach (var animationKey in animationKeys) { var matrix = Matrix.Identity; // Evaluate node foreach (var node in nodesToMerge) { // Needs to be an array in order for it to be modified by the UpdateEngine, otherwise it would get passed by value var modelNodeDefinitions = new ModelNodeDefinition[1] { node.Item1 }; if (node.Item2 != null && node.Item3 != null) { // Compute AnimationClipResult animationClipResult = null; animationOperations.Clear(); animationOperations.Add(AnimationOperation.NewPush(node.Item3, animationKey)); node.Item2.Compute(animationOperations, ref animationClipResult); var updateMemberInfos = new List <UpdateMemberInfo>(); foreach (var channel in animationClipResult.Channels) { if (channel.IsUserCustomProperty) { continue; } updateMemberInfos.Add(new UpdateMemberInfo { Name = "[0]." + channel.PropertyName, DataOffset = channel.Offset }); } // TODO: Cache this var compiledUpdate = UpdateEngine.Compile(typeof(ModelNodeDefinition[]), updateMemberInfos); fixed(byte *data = animationClipResult.Data) { UpdateEngine.Run(modelNodeDefinitions, compiledUpdate, (IntPtr)data, null); } } Matrix localMatrix; var transformTRS = modelNodeDefinitions[0].Transform; Matrix.Transformation(ref transformTRS.Scale, ref transformTRS.Rotation, ref transformTRS.Position, out localMatrix); matrix = Matrix.Multiply(localMatrix, matrix); } // Done evaluating, let's decompose matrix TransformTRS transform; matrix.Decompose(out transform.Scale, out transform.Rotation, out transform.Position); // Create a key translationCurve.KeyFrames.Add(new KeyFrameData <Vector3>(animationKey, transform.Position)); rotationCurve.KeyFrames.Add(new KeyFrameData <Quaternion>(animationKey, transform.Rotation)); scaleCurve.KeyFrames.Add(new KeyFrameData <Vector3>(animationKey, transform.Scale)); } combinedAnimationClip.AddCurve($"{nameof(ModelNodeTransformation.Transform)}.{nameof(TransformTRS.Position)}", translationCurve); combinedAnimationClip.AddCurve($"{nameof(ModelNodeTransformation.Transform)}.{nameof(TransformTRS.Rotation)}", rotationCurve); combinedAnimationClip.AddCurve($"{nameof(ModelNodeTransformation.Transform)}.{nameof(TransformTRS.Scale)}", scaleCurve); nodeAnimationClip = combinedAnimationClip; } var transformStart = $"{nameof(ModelNodeTransformation.Transform)}."; var transformPosition = $"{nameof(ModelNodeTransformation.Transform)}.{nameof(TransformTRS.Position)}"; foreach (var channel in nodeAnimationClip.Channels) { var curve = nodeAnimationClip.Curves[channel.Value.CurveIndex]; // TODO: Root motion var channelName = channel.Key; if (channelName.StartsWith(transformStart)) { if (channelName == transformPosition) { // Translate node with parent 0 using PivotPosition var keyFrames = ((AnimationCurve <Vector3>)curve).KeyFrames; for (int i = 0; i < keyFrames.Count; ++i) { if (parentNodeIndex == 0) { keyFrames.Items[i].Value -= PivotPosition; } keyFrames.Items[i].Value *= ScaleImport; } } animationClip.AddCurve($"[ModelComponent.Key].Skeleton.NodeTransformations[{skeletonMapping.SourceToTarget[nodeIndex]}]." + channelName, curve); } } } } if (ImportCustomAttributes) { // Add clips clips animating other properties than node transformations foreach (var nodeAnimationClipPair in animationClips) { var nodeName = nodeAnimationClipPair.Key; var nodeAnimationClip = nodeAnimationClipPair.Value; foreach (var channel in nodeAnimationClip.Channels) { var channelName = channel.Key; var channelValue = channel.Value; if (channelValue.IsUserCustomProperty) { animationClip.AddCurve(nodeName + "_" + channelName, nodeAnimationClip.Curves[channel.Value.CurveIndex], true); } } } } } if (animationClip.Channels.Count == 0) { var logString = $"File {SourcePath} doesn't have any animation information."; if (failOnEmptyAnimation) { commandContext.Logger.Error(logString); return(null); } commandContext.Logger.Info(logString); } else { if (animationClip.Duration.Ticks == 0) { commandContext.Logger.Verbose($"File {SourcePath} has a 0 tick long animation."); } // Optimize and set common parameters animationClip.RepeatMode = AnimationRepeatMode; animationClip.Optimize(); } return(animationClip); }
///<summary> /// Create a new curve generator ///</summary> ///<param name="source">Source generator</param> ///<param name="curve">Curve to use</param> public Curve(Generator source, AnimationCurve curve) { m_source = source; m_curve = curve; }
/// <summary> /// This API is specifically for Timeline. Do not use it. /// Override the current camera and current blend. This setting will trump /// any in-game logic that sets virtual camera priorities and Enabled states. /// This is the main API for the timeline. /// </summary> /// <param name="overrideId">Id to represent a specific client. An internal /// stack is maintained, with the most recent non-empty override taking precenence. /// This id must be > 0. If you pass -1, a new id will be created, and returned. /// Use that id for subsequent calls. Don't forget to /// call ReleaseCameraOverride after all overriding is finished, to /// free the OverideStack resources.</param> /// <param name="camA"> The camera to set, corresponding to weight=0</param> /// <param name="camB"> The camera to set, corresponding to weight=1</param> /// <param name="weightB">The blend weight. 0=camA, 1=camB</param> /// <param name="deltaTime">override for deltaTime. Should be Time.FixedDelta for /// time-based calculations to be included, -1 otherwise</param> /// <returns>The oiverride ID. Don't forget to call ReleaseCameraOverride /// after all overriding is finished, to free the OverideStack resources.</returns> internal int SetCameraOverride( int overrideId, ICinemachineCamera camA, ICinemachineCamera camB, float weightB, float deltaTime) { //UnityEngine.Profiling.Profiler.BeginSample("CinemachineBrain.SetCameraOverride"); if (overrideId < 0) { overrideId = mNextOverrideId++; } OverrideStackFrame ovr = GetOverrideFrame(overrideId); ovr.camera = null; ovr.deltaTime = deltaTime; ovr.timeOfOverride = Time.realtimeSinceStartup; if (camA != null || camB != null) { if (weightB <= Utility.UnityVectorExtensions.Epsilon) { ovr.blend = null; if (camA != null) { ovr.camera = camA; // no blend } } else if (weightB >= (1f - Utility.UnityVectorExtensions.Epsilon)) { ovr.blend = null; if (camB != null) { ovr.camera = camB; // no blend } } else { // We have a blend. If one of the supplied cameras is null, // we use the current active virtual camera (blending in/out of game logic), // If we do have a null camera, make sure it's the 'from' camera. // Timeline does not distinguish between from and to cams, but we do. if (camB == null) { // Swap them ICinemachineCamera c = camB; camB = camA; camA = c; weightB = 1f - weightB; } // Are we blending with something in progress? if (camA == null) { OverrideStackFrame frame = GetNextActiveFrame(overrideId); if (frame.blend != null) { camA = new BlendSourceVirtualCamera(frame.blend, deltaTime); } else { camA = frame.camera != null ? frame.camera : camB; } } // Create the override blend if (ovr.blend == null) { ovr.blend = new CinemachineBlend( camA, camB, AnimationCurve.Linear(0, 0, 1, 1), 1, weightB); } ovr.blend.CamA = camA; ovr.blend.CamB = camB; ovr.blend.TimeInBlend = weightB; ovr.camera = camB; } } //UnityEngine.Profiling.Profiler.EndSample(); return(overrideId); }
// あるボーンに含まれるキーフレを抽出 // これは回転のみ void CreateKeysForRotation(MMD.VMD.VMDFormat format, AnimationClip clip, string current_bone, string bone_path) { try { List<MMD.VMD.VMDFormat.Motion> mlist = format.motion_list.motion[current_bone]; Keyframe[] rx_keys = new Keyframe[mlist.Count]; Keyframe[] ry_keys = new Keyframe[mlist.Count]; Keyframe[] rz_keys = new Keyframe[mlist.Count]; Keyframe[] rw_keys = new Keyframe[mlist.Count]; for (int i = 0; i < mlist.Count; i++) { const float tick_time = 1.0f / 30.0f; float tick = mlist[i].flame_no * tick_time; float a = GetTangent(mlist[i].interpolation, 3, 0); // inTangent float b; // outTangent // -1フレにはoutTangentは存在しないのでcatch try { b = GetTangent(mlist[i-1].interpolation, 3, 1); } catch { b = 0; } rx_keys[i] = new Keyframe(tick, mlist[i].rotation.x, a, b); ry_keys[i] = new Keyframe(tick, mlist[i].rotation.y, a, b); rz_keys[i] = new Keyframe(tick, mlist[i].rotation.z, a, b); rw_keys[i] = new Keyframe(tick, mlist[i].rotation.w, a, b); } AnimationCurve curve_x = new AnimationCurve(rx_keys); AnimationCurve curve_y = new AnimationCurve(ry_keys); AnimationCurve curve_z = new AnimationCurve(rz_keys); AnimationCurve curve_w = new AnimationCurve(rw_keys); // ここで回転クォータニオンをセット clip.SetCurve(bone_path, typeof(Transform), "localRotation.x", curve_x); clip.SetCurve(bone_path, typeof(Transform), "localRotation.y", curve_y); clip.SetCurve(bone_path, typeof(Transform), "localRotation.z", curve_z); clip.SetCurve(bone_path, typeof(Transform), "localRotation.w", curve_w); } catch (KeyNotFoundException) { //Debug.LogError("互換性のないボーンが読み込まれました:" + bone_path); } }
public CurveEditor(Rect rect, AnimationCurve curve) { animationCurve = curve; FrameSelected(rect); }
// MOVE FUNCTION public IEnumerator Move() { RotationPending = true; AnimationCurve rotationcurve = AnimationCurve.EaseInOut(0, 0, 1f, 1f); float TimeProgression = 0f; Transform t = transform; if (RotationSide == SideOfRotation.Left) { InitialRot = Quaternion.Euler(0, -InitialAngle, 0); FinalRot = Quaternion.Euler(0, -InitialAngle - RotationAngle, 0); } if (RotationSide == SideOfRotation.Right) { InitialRot = Quaternion.Euler(0, -InitialAngle, 0); FinalRot = Quaternion.Euler(0, -InitialAngle + RotationAngle, 0); } if (HingeType == TypeOfHinge.Centered) { t = hinge.transform; RotationOffset = Quaternion.identity; } if (TimesRotated < TimesMoveable || TimesMoveable == 0) { // Change state from 1 to 0 and back (= alternate between FinalRot and InitialRot) if (t.rotation == (State == 0 ? FinalRot * RotationOffset : InitialRot *RotationOffset)) { State ^= 1; } // Set 'FinalRotation' to 'FinalRot' when moving and to 'InitialRot' when moving back Quaternion FinalRotation = ((State == 0) ? FinalRot * RotationOffset : InitialRot * RotationOffset); // Make the door/window rotate until it is fully opened/closed while (TimeProgression <= (1 / Speed)) { TimeProgression += Time.deltaTime; float RotationProgression = Mathf.Clamp01(TimeProgression / (1 / Speed)); float RotationCurveValue = rotationcurve.Evaluate(RotationProgression); t.rotation = Quaternion.Lerp(t.rotation, FinalRotation, RotationCurveValue); yield return(null); } if (TimesMoveable == 0) { TimesRotated = 0; } else { TimesRotated++; } } RotationPending = false; // Broadcast that door has moved. Messenger.Broadcast(GameEvent.DOOR_MOVED); }
// Same as previous, but with torqueFactor multiplier for torque public void SetDrive(DriveForce from, float torqueFactor) { rpm = from.rpm; torque = from.torque * torqueFactor; curve = from.curve; }
public override void OnInspectorGUI() { EditorGUILayout.Space(); Rect weightCurveRect = GUILayoutUtility.GetAspectRect(2.0f); Color previousGUIColor = GUI.color; GUI.color = Color.black; GUI.DrawTexture( new Rect( weightCurveRect.x - 1.0f, weightCurveRect.y - 1.0f, weightCurveRect.width + 2.0f, weightCurveRect.height + 2.0f), this.lineTexture); GUI.color = Color.grey; GUI.Box(weightCurveRect, ""); GUI.color = previousGUIColor; string error = null; if (this.targets.Length <= 1) { Effect targetEffect = (Effect)this.target; if (targetEffect.Duration != 0.0f) { Keyframe[] weightCurveKeyframes = new Keyframe[(int)(weightCurveRect.width * 0.4f)]; for (int i = 0; i < weightCurveKeyframes.Length; ++i) { float time = targetEffect.SimulatedTime - targetEffect.Duration + (i / (float)weightCurveKeyframes.Length) * targetEffect.Duration * 2.0f; weightCurveKeyframes[i] = new Keyframe(time, targetEffect.CalculateWeight(time)); } for (int i = 0; i < weightCurveKeyframes.Length - 1; ++i) { weightCurveKeyframes[i].outTangent = (weightCurveKeyframes[i + 1].value - weightCurveKeyframes[i].value) / (weightCurveKeyframes[i + 1].time - weightCurveKeyframes[i].time); weightCurveKeyframes[i + 1].inTangent = (weightCurveKeyframes[i].value - weightCurveKeyframes[i + 1].value) / (weightCurveKeyframes[i].time - weightCurveKeyframes[i + 1].time); } AnimationCurve weightCurve = new AnimationCurve(weightCurveKeyframes); EditorGUIUtility.DrawRegionSwatch( weightCurveRect, weightCurve, AnimationCurve.Linear( targetEffect.SimulatedTime - targetEffect.Duration, 0.0f, targetEffect.SimulatedTime + targetEffect.Duration, 0.0f), Color.cyan, Color.grey, new Rect( targetEffect.SimulatedTime - targetEffect.Duration, -MAX_WEIGHT, targetEffect.Duration * 2.0f, MAX_WEIGHT * 2.0f)); GUI.color = new Color(0.0f, 0.0f, 0.0f, 0.3f); float topLineY = weightCurveRect.y + weightCurveRect.height * ((MAX_WEIGHT - 1.0f) / (MAX_WEIGHT * 2.0f)); // Top Line GUI.DrawTexture( new Rect( weightCurveRect.x, topLineY, weightCurveRect.width, 1.0f), this.lineTexture); float bottomLineY = weightCurveRect.y + weightCurveRect.height * ((2.0f + MAX_WEIGHT - 1.0f) / (MAX_WEIGHT * 2.0f)); // Bottom Line GUI.DrawTexture( new Rect( weightCurveRect.x, bottomLineY, weightCurveRect.width, 1.0f), this.lineTexture); GUI.color = new Color(0.0f, 0.0f, 0.0f, 1.0f); // Middle Horizontal Line float middleLineThickness = 1.0f + (weightCurveRect.height % 2.0f == 1.0f ? 0.0f : 1.0f); GUI.DrawTexture( new Rect( weightCurveRect.x, weightCurveRect.y + weightCurveRect.height * 0.5f - (int)(middleLineThickness / 2.0f), weightCurveRect.width, middleLineThickness), this.lineTexture); //Middle Vertical Line middleLineThickness = 1.0f + (weightCurveRect.width % 2.0f == 1.0f ? 0.0f : 1.0f); GUI.DrawTexture( new Rect( weightCurveRect.x + weightCurveRect.width * 0.5f - (int)(middleLineThickness / 2.0f), weightCurveRect.y, middleLineThickness, weightCurveRect.height), this.lineTexture); if (targetEffect.IsSleeping) { GUI.color = new Color(1.0f, 0.3f, 0.3f, 0.6f); // Time Text GUI.Box( new Rect( weightCurveRect.x + weightCurveRect.width - 5.0f - 40.0f, bottomLineY - 5.0f - 20.0f, 40.0f, 20.0f), "Zzz"); } GUI.color = new Color(0.0f, 0.0f, 0.0f, 0.5f); // Time Text EditorGUI.LabelField( new Rect( weightCurveRect.x + 5.0f, topLineY + 5.0f, 95.0f, 16.0f), "Time: " + targetEffect.SimulatedTime.ToString("0.00")); // Weight Text EditorGUI.LabelField( new Rect( weightCurveRect.x + 5.0f, topLineY + 21.0f, 95.0f, 16.0f), "Weight: " + targetEffect.CalculateWeight().ToString("0.00")); } else { error = "zero duration"; } } else { error = "multiple objects selected"; } if (error != null) { if (this.errorStyle == null) { this.errorStyle = new GUIStyle(GUI.skin.label); this.errorStyle.alignment = TextAnchor.MiddleCenter; } GUI.color = Color.black; this.errorStyle.fontSize = 72; EditorGUI.LabelField(weightCurveRect, "X", this.errorStyle); GUI.color = new Color(1.0f, 1.0f, 1.0f, 0.5f); this.errorStyle.fontSize = 16; EditorGUI.LabelField( new Rect( weightCurveRect.x, weightCurveRect.y + weightCurveRect.height * 0.5f, weightCurveRect.width, weightCurveRect.height * 0.5f), error, this.errorStyle); } EditorGUILayout.Space(); GUI.color = previousGUIColor; base.OnInspectorGUI(); }
private static void ApplyAudioSourceParameters(AudioSourceParameters audioSourceParameters, SoundSpawn soundSpawn) { AudioSource audioSource = soundSpawn.AudioSource; if (audioSourceParameters != null) { if (audioSourceParameters.MixerType != MixerType.Unspecified) { audioSource.outputAudioMixerGroup = audioSourceParameters.MixerType == MixerType.Master ? Instance.DefaultMixer : Instance.MuffledMixer; } if (audioSourceParameters.Pitch != null) { audioSource.pitch = audioSourceParameters.Pitch.Value; } else { audioSource.pitch = 1; } if (audioSourceParameters.Time != null) { audioSource.time = audioSourceParameters.Time.Value; } if (audioSourceParameters.Volume != null) { audioSource.volume = audioSourceParameters.Volume.Value; } if (audioSourceParameters.Pan != null) { audioSource.panStereo = audioSourceParameters.Pan.Value; } if (audioSourceParameters.SpatialBlend != null) { audioSource.spatialBlend = audioSourceParameters.SpatialBlend.Value; } if (audioSourceParameters.MinDistance != null) { audioSource.minDistance = audioSourceParameters.MinDistance.Value; } if (audioSourceParameters.MaxDistance != null) { audioSource.maxDistance = audioSourceParameters.MaxDistance.Value; } if (audioSourceParameters.Spread != null) { audioSource.spread = audioSourceParameters.Spread.Value; } switch (audioSourceParameters.VolumeRolloffType) { case VolumeRolloffType.EaseInAndOut: audioSource.rolloffMode = AudioRolloffMode.Custom; audioSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, AnimationCurve.EaseInOut(0, 1, 1, 0)); break; case VolumeRolloffType.Linear: audioSource.rolloffMode = AudioRolloffMode.Linear; break; case VolumeRolloffType.Logarithmic: audioSource.rolloffMode = AudioRolloffMode.Logarithmic; break; } } }
private void ProcessActiveCamera(float deltaTime) { // This condition should never occur, but let's be defensive if (!isActiveAndEnabled) { mActiveCameraPreviousFrame = null; mOutgoingCameraPreviousFrame = null; mPreviousFrameWasOverride = false; return; } //UnityEngine.Profiling.Profiler.BeginSample("CinemachineBrain.ProcessActiveCamera"); OverrideStackFrame activeOverride = GetActiveOverride(); ICinemachineCamera activeCamera = ActiveVirtualCamera; if (activeCamera == null) { mOutgoingCameraPreviousFrame = null; } else { // If there is an override, we kill the in-game blend if (activeOverride != null) { mActiveBlend = null; } CinemachineBlend activeBlend = ActiveBlend; // Check for unexpected deletion of the cached mActiveCameraPreviousFrame if (mActiveCameraPreviousFrame != null && mActiveCameraPreviousFrame.VirtualCameraGameObject == null) { mActiveCameraPreviousFrame = null; } // Are we transitioning cameras? if (mActiveCameraPreviousFrame != activeCamera) { // Do we need to create a game-play blend? if (mActiveCameraPreviousFrame != null && !mPreviousFrameWasOverride && activeOverride == null && deltaTime >= 0) { // Create a blend (will be null if a cut) float duration = 0; AnimationCurve curve = LookupBlendCurve( mActiveCameraPreviousFrame, activeCamera, out duration); activeBlend = CreateBlend( mActiveCameraPreviousFrame, activeCamera, curve, duration, mActiveBlend); } // Need this check because Timeline override sometimes inverts outgoing and incoming if (activeCamera != mOutgoingCameraPreviousFrame) { // Notify incoming camera of transition activeCamera.OnTransitionFromCamera(mActiveCameraPreviousFrame); // If the incoming camera is disabled, then we must assume // that it has not been updated properly if (!activeCamera.VirtualCameraGameObject.activeInHierarchy && (activeBlend == null || !activeBlend.Uses(activeCamera))) { activeCamera.UpdateCameraState(DefaultWorldUp, -1); } if (m_CameraActivatedEvent != null) { m_CameraActivatedEvent.Invoke(activeCamera); } } // If we're cutting without a blend, or no active cameras // were active last frame, send an event if (activeBlend == null || (activeBlend.CamA != mActiveCameraPreviousFrame && activeBlend.CamB != mActiveCameraPreviousFrame && activeBlend.CamA != mOutgoingCameraPreviousFrame && activeBlend.CamB != mOutgoingCameraPreviousFrame)) { if (m_CameraCutEvent != null) { m_CameraCutEvent.Invoke(this); } } } // Advance the current blend (if any) if (activeBlend != null) { if (activeOverride == null) { activeBlend.TimeInBlend += (deltaTime >= 0) ? deltaTime : activeBlend.Duration; } if (activeBlend.IsComplete) { activeBlend = null; } } if (activeOverride == null) { mActiveBlend = activeBlend; } // Apply the result to the Unity camera CameraState state = activeCamera.State; if (activeBlend != null) { state = activeBlend.State; } PushStateToUnityCamera(state, activeCamera); mOutgoingCameraPreviousFrame = null; if (activeBlend != null) { mOutgoingCameraPreviousFrame = activeBlend.CamB; } } mActiveCameraPreviousFrame = activeCamera; mPreviousFrameWasOverride = activeOverride != null; if (mPreviousFrameWasOverride) { // Hack: Because we don't know whether blending in or out... grrr... if (activeOverride.blend != null) { if (activeOverride.blend.BlendWeight < 0.5f) { mActiveCameraPreviousFrame = activeOverride.blend.CamA; mOutgoingCameraPreviousFrame = activeOverride.blend.CamB; } else { mActiveCameraPreviousFrame = activeOverride.blend.CamB; mOutgoingCameraPreviousFrame = activeOverride.blend.CamA; } } } //UnityEngine.Profiling.Profiler.EndSample(); }
public ValueVector3(Vector3 startValue, Vector3 endValue, Action <Vector3> valueUpdatedCallback, float duration, float delay, bool obeyTimescale, AnimationCurve curve, Tween.LoopType loop, Action startCallback, Action completeCallback) { //set essential properties: SetEssentials(Tween.TweenType.Value, -1, duration, delay, obeyTimescale, curve, loop, startCallback, completeCallback); //catalog custom properties: _valueUpdatedCallback = valueUpdatedCallback; _start = startValue; EndValue = endValue; }
void DrawCurve(AnimationCurve curve) { float normalStepSize = 0.05F; float initialstepSize = 0.00001F; if (curve.length == 0) { return; } // Draw curve Vector3 lhs, rhs; Handles.color = m_CurveColor; float lastPosition = curve[0].value; float lastTime = curve[0].time; for (int i = 0; i < curve.length - 1; i++) { float stepSize = initialstepSize; lastTime = curve[i].time; lastPosition = curve.Evaluate(curve[i].time); for (float f = 0.0F; f < 1.0F - stepSize * 0.5F; f += stepSize) { float newTime = Mathf.Lerp(curve[i].time, curve[i + 1].time, f); newTime = Mathf.Min(curve[i + 1].time, newTime); newTime = Mathf.Max(curve[i].time, newTime); float newPosition = curve.Evaluate(newTime); lhs = new Vector3(lastTime, lastPosition, 0); rhs = new Vector3(newTime, newPosition, 0); Handles.DrawLine(transform.MultiplyPoint(lhs), transform.MultiplyPoint(rhs)); lastTime = newTime; lastPosition = newPosition; if (f != 0.0F) { stepSize = normalStepSize; } } float newTime2 = curve[i + 1].time - 0.00001F; lhs = new Vector3(lastTime, lastPosition, 0); rhs = new Vector3(newTime2, curve.Evaluate(newTime2), 0); Handles.DrawLine(transform.MultiplyPoint(lhs), transform.MultiplyPoint(rhs)); } // Draw all keys (except selected) CurveSelection activeKey = m_DragKey != null ? m_DragKey : m_SelectedKey; GUI.color = m_KeyColor; for (int i = 0; i < curve.length; i++) { if (activeKey != null && i == activeKey.index) { continue; } DrawPoint(curve[i].time, curve[i].value); } // Draw Selected if (activeKey != null) { Vector2 keyPoint = GetPosition(curve, new CurveSelection(activeKey.index, SelectionType.Key)); Vector2 leftTangent = GetPosition(curve, new CurveSelection(activeKey.index, SelectionType.InTangent)); Vector2 rightTangent = GetPosition(curve, new CurveSelection(activeKey.index, SelectionType.OutTangent)); GUI.color = activeKey.type == SelectionType.Key ? m_SelectedKeyColor : m_KeyColor; DrawPoint(keyPoint.x, keyPoint.y); GUI.color = activeKey.type == SelectionType.InTangent ? m_SelectedKeyColor : m_KeyColor; DrawPoint(leftTangent.x, leftTangent.y); GUI.color = activeKey.type == SelectionType.OutTangent ? m_SelectedKeyColor : m_KeyColor; DrawPoint(rightTangent.x, rightTangent.y); // Draw Handles Handles.color = m_TangentColor; DrawLine(leftTangent, keyPoint); DrawLine(keyPoint, rightTangent); } }
/// <summary> /// Reset the value of a property. /// </summary> /// <param name="property">Serialized property for a serialized property.</param> public static void ResetValue(SerializedProperty property) { if (property == null) { throw new ArgumentNullException(nameof(property)); } switch (property.propertyType) { case SerializedPropertyType.Integer: property.intValue = 0; break; case SerializedPropertyType.Boolean: property.boolValue = false; break; case SerializedPropertyType.Float: property.floatValue = 0f; break; case SerializedPropertyType.String: property.stringValue = ""; break; case SerializedPropertyType.Color: property.colorValue = Color.black; break; case SerializedPropertyType.ObjectReference: property.objectReferenceValue = null; break; case SerializedPropertyType.LayerMask: property.intValue = 0; break; case SerializedPropertyType.Enum: property.enumValueIndex = 0; break; case SerializedPropertyType.Vector2: property.vector2Value = default(Vector2); break; case SerializedPropertyType.Vector3: property.vector3Value = default(Vector3); break; case SerializedPropertyType.Vector4: property.vector4Value = default(Vector4); break; case SerializedPropertyType.Rect: property.rectValue = default(Rect); break; case SerializedPropertyType.ArraySize: property.intValue = 0; break; case SerializedPropertyType.Character: property.intValue = 0; break; case SerializedPropertyType.AnimationCurve: property.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f); break; case SerializedPropertyType.Bounds: property.boundsValue = default(Bounds); break; case SerializedPropertyType.Gradient: //!TODO: Amend when Unity add a public API for setting the gradient. break; } if (property.isArray) { property.arraySize = 0; } ResetChildPropertyValues(property); }
public override void OnInspectorGUI() { AudioSourceInspector.InitStyles(); base.serializedObject.Update(); if (this.m_LowpassObject != null) { this.m_LowpassObject.Update(); } this.HandleLowPassFilter(); AudioSourceInspector.AudioCurveWrapper[] audioCurves = this.m_AudioCurves; for (int i = 0; i < audioCurves.Length; i++) { AudioSourceInspector.AudioCurveWrapper audioCurveWrapper = audioCurves[i]; CurveWrapper curveWrapperById = this.m_CurveEditor.getCurveWrapperById(audioCurveWrapper.id); if (audioCurveWrapper.curveProp != null) { AnimationCurve animationCurveValue = audioCurveWrapper.curveProp.animationCurveValue; if (curveWrapperById == null != audioCurveWrapper.curveProp.hasMultipleDifferentValues) { this.m_RefreshCurveEditor = true; } else if (curveWrapperById != null) { if (curveWrapperById.curve.length == 0) { this.m_RefreshCurveEditor = true; } else if (animationCurveValue.length >= 1 && animationCurveValue.keys[0].value != curveWrapperById.curve.keys[0].value) { this.m_RefreshCurveEditor = true; } } } else if (curveWrapperById != null) { this.m_RefreshCurveEditor = true; } } this.UpdateWrappersAndLegend(); EditorGUILayout.PropertyField(this.m_AudioClip, AudioSourceInspector.ms_Styles.audioClipLabel, new GUILayoutOption[0]); EditorGUILayout.Space(); EditorGUILayout.PropertyField(this.m_OutputAudioMixerGroup, AudioSourceInspector.ms_Styles.outputMixerGroupLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Mute, new GUILayoutOption[0]); if (AudioUtil.canUseSpatializerEffect) { EditorGUILayout.PropertyField(this.m_Spatialize, new GUILayoutOption[0]); } EditorGUILayout.PropertyField(this.m_BypassEffects, new GUILayoutOption[0]); bool flag = base.targets.Any((UnityEngine.Object t) => (t as AudioSource).outputAudioMixerGroup != null); if (flag) { EditorGUI.BeginDisabledGroup(true); } EditorGUILayout.PropertyField(this.m_BypassListenerEffects, new GUILayoutOption[0]); if (flag) { EditorGUI.EndDisabledGroup(); } EditorGUILayout.PropertyField(this.m_BypassReverbZones, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_PlayOnAwake, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Loop, new GUILayoutOption[0]); EditorGUILayout.Space(); EditorGUIUtility.sliderLabels.SetLabels(AudioSourceInspector.ms_Styles.priorityLeftLabel, AudioSourceInspector.ms_Styles.priorityRightLabel); EditorGUILayout.IntSlider(this.m_Priority, 0, 256, AudioSourceInspector.ms_Styles.priorityLabel, new GUILayoutOption[0]); EditorGUIUtility.sliderLabels.SetLabels(null, null); EditorGUILayout.Space(); EditorGUILayout.Slider(this.m_Volume, 0f, 1f, AudioSourceInspector.ms_Styles.volumeLabel, new GUILayoutOption[0]); EditorGUILayout.Space(); EditorGUILayout.Slider(this.m_Pitch, -3f, 3f, AudioSourceInspector.ms_Styles.pitchLabel, new GUILayoutOption[0]); EditorGUILayout.Space(); EditorGUIUtility.sliderLabels.SetLabels(AudioSourceInspector.ms_Styles.panLeftLabel, AudioSourceInspector.ms_Styles.panRightLabel); EditorGUILayout.Slider(this.m_Pan2D, -1f, 1f, AudioSourceInspector.ms_Styles.panStereoLabel, new GUILayoutOption[0]); EditorGUIUtility.sliderLabels.SetLabels(null, null); EditorGUILayout.Space(); EditorGUIUtility.sliderLabels.SetLabels(AudioSourceInspector.ms_Styles.spatialLeftLabel, AudioSourceInspector.ms_Styles.spatialRightLabel); AudioSourceInspector.AnimProp(AudioSourceInspector.ms_Styles.spatialBlendLabel, this.m_AudioCurves[1].curveProp, 0f, 1f, false); EditorGUIUtility.sliderLabels.SetLabels(null, null); EditorGUILayout.Space(); AudioSourceInspector.AnimProp(AudioSourceInspector.ms_Styles.reverbZoneMixLabel, this.m_AudioCurves[4].curveProp, 0f, 1.1f, false); EditorGUILayout.Space(); this.m_Expanded3D = EditorGUILayout.Foldout(this.m_Expanded3D, "3D Sound Settings"); if (this.m_Expanded3D) { EditorGUI.indentLevel++; this.Audio3DGUI(); EditorGUI.indentLevel--; } base.serializedObject.ApplyModifiedProperties(); if (this.m_LowpassObject != null) { this.m_LowpassObject.ApplyModifiedProperties(); } }
private void Audio3DGUI() { EditorGUILayout.Slider(this.m_DopplerLevel, 0f, 5f, AudioSourceInspector.ms_Styles.dopplerLevelLabel, new GUILayoutOption[0]); EditorGUI.BeginChangeCheck(); AudioSourceInspector.AnimProp(AudioSourceInspector.ms_Styles.spreadLabel, this.m_AudioCurves[2].curveProp, 0f, 360f, true); if (this.m_RolloffMode.hasMultipleDifferentValues || (this.m_RolloffMode.enumValueIndex == 2 && this.m_AudioCurves[0].curveProp.hasMultipleDifferentValues)) { EditorGUILayout.TargetChoiceField(this.m_AudioCurves[0].curveProp, AudioSourceInspector.ms_Styles.rolloffLabel, new TargetChoiceHandler.TargetChoiceMenuFunction(AudioSourceInspector.SetRolloffToTarget), new GUILayoutOption[0]); } else { EditorGUILayout.PropertyField(this.m_RolloffMode, AudioSourceInspector.ms_Styles.rolloffLabel, new GUILayoutOption[0]); if (this.m_RolloffMode.enumValueIndex != 2) { EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.m_MinDistance, new GUILayoutOption[0]); if (EditorGUI.EndChangeCheck()) { this.m_MinDistance.floatValue = Mathf.Clamp(this.m_MinDistance.floatValue, 0f, this.m_MaxDistance.floatValue / 1.01f); } } else { EditorGUI.BeginDisabledGroup(true); EditorGUILayout.LabelField(this.m_MinDistance.displayName, AudioSourceInspector.ms_Styles.controlledByCurveLabel, new GUILayoutOption[0]); EditorGUI.EndDisabledGroup(); } } EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.m_MaxDistance, new GUILayoutOption[0]); if (EditorGUI.EndChangeCheck()) { this.m_MaxDistance.floatValue = Mathf.Min(Mathf.Max(Mathf.Max(this.m_MaxDistance.floatValue, 0.01f), this.m_MinDistance.floatValue * 1.01f), 1000000f); } if (EditorGUI.EndChangeCheck()) { this.m_RefreshCurveEditor = true; } Rect aspectRect = GUILayoutUtility.GetAspectRect(1.333f, GUI.skin.textField); aspectRect.xMin += EditorGUI.indent; if (Event.current.type != EventType.Layout && Event.current.type != EventType.Used) { this.m_CurveEditor.rect = new Rect(aspectRect.x, aspectRect.y, aspectRect.width, aspectRect.height); } this.UpdateWrappersAndLegend(); GUI.Label(this.m_CurveEditor.drawRect, GUIContent.none, "TextField"); this.m_CurveEditor.hRangeLocked = Event.current.shift; this.m_CurveEditor.vRangeLocked = EditorGUI.actionKey; this.m_CurveEditor.OnGUI(); if (base.targets.Length == 1) { AudioSource audioSource = (AudioSource)this.target; AudioListener x = (AudioListener)UnityEngine.Object.FindObjectOfType(typeof(AudioListener)); if (x != null) { float magnitude = (AudioUtil.GetListenerPos() - audioSource.transform.position).magnitude; this.DrawLabel("Listener", magnitude, aspectRect); } } this.DrawLegend(); AudioSourceInspector.AudioCurveWrapper[] audioCurves = this.m_AudioCurves; for (int i = 0; i < audioCurves.Length; i++) { AudioSourceInspector.AudioCurveWrapper audioCurveWrapper = audioCurves[i]; if (this.m_CurveEditor.getCurveWrapperById(audioCurveWrapper.id) != null && this.m_CurveEditor.getCurveWrapperById(audioCurveWrapper.id).changed) { AnimationCurve curve = this.m_CurveEditor.getCurveWrapperById(audioCurveWrapper.id).curve; if (curve.length > 0) { audioCurveWrapper.curveProp.animationCurveValue = curve; this.m_CurveEditor.getCurveWrapperById(audioCurveWrapper.id).changed = false; if (audioCurveWrapper.type == AudioSourceInspector.AudioCurveType.Volume) { this.m_RolloffMode.enumValueIndex = 2; } } } } }
private static int INTERNAL_CALL_AddKey_Internal(AnimationCurve self, ref Keyframe key){}
public RotateAffector(AnimationCurve curve, EffectNode node) : base(node) { this.Type = RSTYPE.CURVE; this.RotateCurve = curve; }
public void LoadFrom(Stream stream) { BinaryReader reader = new BinaryReader(stream); scalar = reader.ReadSingle(); maxCurve = new AnimationCurve<float>(reader, reader.ReadSingle); minCurve = new AnimationCurve<float>(reader, reader.ReadSingle); minMaxState = reader.ReadInt16(); reader.ReadBytes(2); }
/// <summary> /// 自动眨眼 /// </summary> /// <param name="minInterval">最小间隔</param> /// <param name="maxInterval">最大间隔</param> /// <param name="duration">眨眼过程时间</param> /// <returns>Blink Value</returns> protected float AutoBlinkCtrl(float minInterval, float maxInterval, float duration, AnimationCurve blinkCurve) { var r = Random.Range(minInterval, maxInterval); if (Time.time - _timer > r) { _timer = Time.time; DOTween.To(() => _eyeAutoBlinkTimer, v => _eyeAutoBlinkTimer = v, 1, duration).onComplete += () => _eyeAutoBlinkTimer = 0; } return(blinkCurve.Evaluate(_eyeAutoBlinkTimer)); }
protected List<Affector> InitAffectors(EffectNode node) { List<Affector> AffectorList = new List<Affector>(); if (UVAffectorEnable) { UVAnimation uvAnim = new UVAnimation(); if (UVType == 1) { float perWidth = OriUVDimensions.x / Cols; float perHeight = Mathf.Abs(OriUVDimensions.y / Rows); Vector2 cellSize = new Vector2(perWidth, perHeight); uvAnim.BuildUVAnim(OriTopLeftUV, cellSize, Cols, Rows, Cols * Rows); } UVDimension = uvAnim.UVDimensions[0]; UVTopLeft = uvAnim.frames[0]; if (uvAnim.frames.Length != 1) { uvAnim.loopCycles = LoopCircles; Affector aft = new UVAffector(uvAnim, UVTime, node, RandomStartFrame); AffectorList.Add(aft); } } else { UVDimension = OriUVDimensions; UVTopLeft = OriTopLeftUV; } if (RotAffectorEnable && RotateType != RSTYPE.NONE) { Affector aft; if (RotateType == RSTYPE.CURVE) aft = new RotateAffector(RotateCurve, node); else aft = new RotateAffector(DeltaRot, node); AffectorList.Add(aft); } if (ScaleAffectorEnable && ScaleType != RSTYPE.NONE) { Affector aft; if (UseSameScaleCurve) ScaleYCurve = ScaleXCurve; if (ScaleType == RSTYPE.CURVE) aft = new ScaleAffector(ScaleXCurve, ScaleYCurve, node); else aft = new ScaleAffector(DeltaScaleX, DeltaScaleY, node); AffectorList.Add(aft); } if (ColorAffectorEnable /*&& ColorAffectType != 0*/) { ColorAffector aft = new ColorAffector(this, node); AffectorList.Add(aft); } if (JetAffectorEnable) { Affector aft = new JetAffector(JetMag,JetMagType,JetCurve,node); AffectorList.Add(aft); } if (VortexAffectorEnable) { Affector aft; aft = new VortexAffector(VortexObj, VortexMagType, VortexMag, VortexCurve, VortexDirection, VortexInheritRotation, node); AffectorList.Add(aft); } if (UVRotAffectorEnable) { Affector aft; float xscroll = UVRotXSpeed; float yscroll = UVRotYSpeed; if (RandomUVRotateSpeed) { xscroll = Random.Range(UVRotXSpeed,UVRotXSpeedMax); yscroll = Random.Range(UVRotYSpeed,UVRotYSpeedMax); } aft = new UVRotAffector(xscroll, yscroll, node); AffectorList.Add(aft); } if (GravityAffectorEnable) { Affector aft; aft = new GravityAffector(GravityObject, GravityAftType, GravityMagType, IsGravityAccelerate,GravityDirection, GravityMag, GravityCurve, node); AffectorList.Add(aft); if (GravityAftType == GAFTTYPE.Spherical && GravityObject == null) { Debug.LogWarning("Gravity Object is missing, automatically set to effect layer self:" + gameObject.name); GravityObject = transform; } } if (AirAffectorEnable) { Affector aft = new AirFieldAffector(AirObject, AirDirection, AirMagType, AirMagnitude, AirMagCurve, AirAttenuation, AirUseMaxDistance, AirMaxDistance, AirEnableSpread, AirSpread, AirInheritVelocity, AirInheritRotation, node); AffectorList.Add(aft); } if (BombAffectorEnable) { Affector aft = new BombAffector(BombObject, BombType, BombMagType, BombDecayType, BombMagnitude, BombMagCurve, BombDecay, BombAxis, node); AffectorList.Add(aft); } if (TurbulenceAffectorEnable) { Affector aft = new TurbulenceFieldAffector(TurbulenceObject, TurbulenceMagType, TurbulenceMagnitude, TurbulenceMagCurve, TurbulenceAttenuation, TurbulenceUseMaxDistance, TurbulenceMaxDistance, node); AffectorList.Add(aft); } if (DragAffectorEnable) { Affector aft = new DragAffector(DragObj,DragUseDir,DragDir,DragMag,DragUseMaxDist,DragMaxDist,DragAtten,node); AffectorList.Add(aft); } return AffectorList; }
public void LoadFrom(Stream stream) { BinaryReader reader = new BinaryReader(stream); m_GameObject = new PPtr<GameObject>(stream, file); m_Enabled = reader.ReadByte(); stream.Position += 3; m_audioClip = new PPtr<AudioClip>(stream, file); m_PlayOnAwake = reader.ReadBoolean(); stream.Position += 3; m_Volume = reader.ReadSingle(); m_Pitch = reader.ReadSingle(); Loop = reader.ReadBoolean(); Mute = reader.ReadBoolean(); stream.Position += 2; Priority = reader.ReadInt32(); DopplerLevel = reader.ReadSingle(); MinDistance = reader.ReadSingle(); MaxDistance = reader.ReadSingle(); Pan2D = reader.ReadSingle(); rolloffMode = reader.ReadInt32(); BypassEffects = reader.ReadBoolean(); BypassListenerEffects = reader.ReadBoolean(); BypassReverbZones = reader.ReadBoolean(); stream.Position += 1; rolloffCustomCurve = new AnimationCurve<float>(reader, reader.ReadSingle); panLevelCustomCurve = new AnimationCurve<float>(reader, reader.ReadSingle); spreadCustomCurve = new AnimationCurve<float>(reader, reader.ReadSingle); }