CinemachineSmoothPathEditor.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. using UnityEditor;
  2. using UnityEngine;
  3. using System.Linq;
  4. using System.Collections.Generic;
  5. using UnityEditorInternal;
  6. using Cinemachine.Utility;
  7. namespace Cinemachine.Editor
  8. {
  9. [CustomEditor(typeof(CinemachineSmoothPath))]
  10. sealed class CinemachineSmoothPathEditor : BaseEditor<CinemachineSmoothPath>
  11. {
  12. private ReorderableList mWaypointList;
  13. /// <summary>Get the property names to exclude in the inspector.</summary>
  14. /// <param name="excluded">Add the names to this list</param>
  15. protected override void GetExcludedPropertiesInInspector(List<string> excluded)
  16. {
  17. base.GetExcludedPropertiesInInspector(excluded);
  18. excluded.Add(FieldPath(x => x.m_Waypoints));
  19. }
  20. void OnEnable()
  21. {
  22. mWaypointList = null;
  23. }
  24. // ReSharper disable once UnusedMember.Global - magic method called when doing Frame Selected
  25. public bool HasFrameBounds()
  26. {
  27. return Target.m_Waypoints != null && Target.m_Waypoints.Length > 0;
  28. }
  29. // ReSharper disable once UnusedMember.Global - magic method called when doing Frame Selected
  30. public Bounds OnGetFrameBounds()
  31. {
  32. Vector3[] wp;
  33. int selected = mWaypointList == null ? -1 : mWaypointList.index;
  34. if (selected >= 0 && selected < Target.m_Waypoints.Length)
  35. wp = new Vector3[1] { Target.m_Waypoints[selected].position };
  36. else
  37. wp = Target.m_Waypoints.Select(p => p.position).ToArray();
  38. return GeometryUtility.CalculateBounds(wp, Target.transform.localToWorldMatrix);
  39. }
  40. public override void OnInspectorGUI()
  41. {
  42. BeginInspector();
  43. if (mWaypointList == null)
  44. SetupWaypointList();
  45. if (mWaypointList.index >= mWaypointList.count)
  46. mWaypointList.index = mWaypointList.count - 1;
  47. // Ordinary properties
  48. DrawRemainingPropertiesInInspector();
  49. // Path length
  50. EditorGUILayout.LabelField("Path Length", Target.PathLength.ToString());
  51. // Waypoints
  52. EditorGUI.BeginChangeCheck();
  53. mWaypointList.DoLayoutList();
  54. if (EditorGUI.EndChangeCheck())
  55. serializedObject.ApplyModifiedProperties();
  56. }
  57. void SetupWaypointList()
  58. {
  59. mWaypointList = new ReorderableList(
  60. serializedObject, FindProperty(x => x.m_Waypoints),
  61. true, true, true, true);
  62. mWaypointList.drawHeaderCallback = (Rect rect) =>
  63. { EditorGUI.LabelField(rect, "Waypoints"); };
  64. mWaypointList.drawElementCallback
  65. = (Rect rect, int index, bool isActive, bool isFocused) =>
  66. { DrawWaypointEditor(rect, index); };
  67. mWaypointList.onAddCallback = (ReorderableList l) =>
  68. { InsertWaypointAtIndex(l.index); };
  69. }
  70. void DrawWaypointEditor(Rect rect, int index)
  71. {
  72. // Needed for accessing string names of fields
  73. CinemachineSmoothPath.Waypoint def = new CinemachineSmoothPath.Waypoint();
  74. SerializedProperty element = mWaypointList.serializedProperty.GetArrayElementAtIndex(index);
  75. float hSpace = 3;
  76. rect.width -= hSpace; rect.y += 1;
  77. Vector2 numberDimension = GUI.skin.label.CalcSize(new GUIContent("999"));
  78. Rect r = new Rect(rect.position, numberDimension);
  79. if (GUI.Button(r, new GUIContent(index.ToString(), "Go to the waypoint in the scene view")))
  80. {
  81. if (SceneView.lastActiveSceneView != null)
  82. {
  83. mWaypointList.index = index;
  84. SceneView.lastActiveSceneView.pivot = Target.EvaluatePosition(index);
  85. SceneView.lastActiveSceneView.size = 4;
  86. SceneView.lastActiveSceneView.Repaint();
  87. }
  88. }
  89. float floatFieldWidth = EditorGUIUtility.singleLineHeight * 2f;
  90. GUIContent rollLabel = new GUIContent("Roll");
  91. Vector2 labelDimension = GUI.skin.label.CalcSize(rollLabel);
  92. float rollWidth = labelDimension.x + floatFieldWidth;
  93. r.x += r.width + hSpace; r.width = rect.width - (r.width + hSpace + rollWidth) - (r.height + hSpace);
  94. EditorGUI.PropertyField(r, element.FindPropertyRelative(() => def.position), GUIContent.none);
  95. r.x += r.width + hSpace; r.width = rollWidth;
  96. float oldWidth = EditorGUIUtility.labelWidth;
  97. EditorGUIUtility.labelWidth = labelDimension.x;
  98. var indent = EditorGUI.indentLevel;
  99. EditorGUI.indentLevel = 0;
  100. EditorGUI.PropertyField(r, element.FindPropertyRelative(() => def.roll), rollLabel);
  101. EditorGUIUtility.labelWidth = oldWidth;
  102. EditorGUI.indentLevel = indent;
  103. r.x += r.width + hSpace; r.height += 1; r.width = r.height;
  104. GUIContent setButtonContent = EditorGUIUtility.IconContent("d_RectTransform Icon");
  105. setButtonContent.tooltip = "Set to scene-view camera position";
  106. if (GUI.Button(r, setButtonContent, GUI.skin.label) && SceneView.lastActiveSceneView != null)
  107. {
  108. Undo.RecordObject(Target, "Set waypoint");
  109. CinemachineSmoothPath.Waypoint wp = Target.m_Waypoints[index];
  110. Vector3 pos = SceneView.lastActiveSceneView.camera.transform.position;
  111. wp.position = Target.transform.InverseTransformPoint(pos);
  112. Target.m_Waypoints[index] = wp;
  113. }
  114. }
  115. void InsertWaypointAtIndex(int indexA)
  116. {
  117. Vector3 pos = Vector3.right;
  118. float roll = 0;
  119. // Get new values from the current indexA (if any)
  120. int numWaypoints = Target.m_Waypoints.Length;
  121. if (indexA < 0)
  122. indexA = numWaypoints - 1;
  123. if (indexA >= 0)
  124. {
  125. int indexB = indexA + 1;
  126. if (Target.m_Looped && indexB >= numWaypoints)
  127. indexB = 0;
  128. if (indexB >= numWaypoints)
  129. {
  130. Vector3 delta = Vector3.right;
  131. if (indexA > 0)
  132. delta = Target.m_Waypoints[indexA].position - Target.m_Waypoints[indexA-1].position;
  133. pos = Target.m_Waypoints[indexA].position + delta;
  134. roll = Target.m_Waypoints[indexA].roll;
  135. }
  136. else
  137. {
  138. // Interpolate
  139. pos = Target.transform.InverseTransformPoint(Target.EvaluatePosition(0.5f + indexA));
  140. roll = Mathf.Lerp(Target.m_Waypoints[indexA].roll, Target.m_Waypoints[indexB].roll, 0.5f);
  141. }
  142. }
  143. Undo.RecordObject(Target, "Add waypoint");
  144. var wp = new CinemachineSmoothPath.Waypoint();
  145. wp.position = pos;
  146. wp.roll = roll;
  147. var list = new List<CinemachineSmoothPath.Waypoint>(Target.m_Waypoints);
  148. list.Insert(indexA + 1, wp);
  149. Target.m_Waypoints = list.ToArray();
  150. Target.InvalidateDistanceCache();
  151. InspectorUtility.RepaintGameView();
  152. mWaypointList.index = indexA + 1; // select it
  153. }
  154. void OnSceneGUI()
  155. {
  156. if (mWaypointList == null)
  157. SetupWaypointList();
  158. if (Tools.current == Tool.Move)
  159. {
  160. Color colorOld = Handles.color;
  161. var localToWorld = Target.transform.localToWorldMatrix;
  162. for (int i = 0; i < Target.m_Waypoints.Length; ++i)
  163. {
  164. DrawSelectionHandle(i, localToWorld);
  165. if (mWaypointList.index == i)
  166. DrawPositionControl(i, localToWorld, Target.transform.rotation); // Waypoint is selected
  167. }
  168. Handles.color = colorOld;
  169. }
  170. }
  171. void DrawSelectionHandle(int i, Matrix4x4 localToWorld)
  172. {
  173. if (Event.current.button != 1)
  174. {
  175. Vector3 pos = localToWorld.MultiplyPoint(Target.m_Waypoints[i].position);
  176. float size = HandleUtility.GetHandleSize(pos) * 0.2f;
  177. Handles.color = Color.white;
  178. if (Handles.Button(pos, Quaternion.identity, size, size, Handles.SphereHandleCap)
  179. && mWaypointList.index != i)
  180. {
  181. mWaypointList.index = i;
  182. InspectorUtility.RepaintGameView();
  183. }
  184. // Label it
  185. Handles.BeginGUI();
  186. Vector2 labelSize = new Vector2(
  187. EditorGUIUtility.singleLineHeight * 2, EditorGUIUtility.singleLineHeight);
  188. Vector2 labelPos = HandleUtility.WorldToGUIPoint(pos);
  189. labelPos.y -= labelSize.y / 2;
  190. labelPos.x -= labelSize.x / 2;
  191. GUILayout.BeginArea(new Rect(labelPos, labelSize));
  192. GUIStyle style = new GUIStyle();
  193. style.normal.textColor = Color.black;
  194. style.alignment = TextAnchor.MiddleCenter;
  195. GUILayout.Label(new GUIContent(i.ToString(), "Waypoint " + i), style);
  196. GUILayout.EndArea();
  197. Handles.EndGUI();
  198. }
  199. }
  200. void DrawPositionControl(int i, Matrix4x4 localToWorld, Quaternion localRotation)
  201. {
  202. CinemachineSmoothPath.Waypoint wp = Target.m_Waypoints[i];
  203. Vector3 pos = localToWorld.MultiplyPoint(wp.position);
  204. EditorGUI.BeginChangeCheck();
  205. Handles.color = Target.m_Appearance.pathColor;
  206. Quaternion rotation = (Tools.pivotRotation == PivotRotation.Local)
  207. ? localRotation : Quaternion.identity;
  208. float size = HandleUtility.GetHandleSize(pos) * 0.1f;
  209. Handles.SphereHandleCap(0, pos, rotation, size, EventType.Repaint);
  210. pos = Handles.PositionHandle(pos, rotation);
  211. if (EditorGUI.EndChangeCheck())
  212. {
  213. Undo.RecordObject(target, "Move Waypoint");
  214. wp.position = Matrix4x4.Inverse(localToWorld).MultiplyPoint(pos);
  215. Target.m_Waypoints[i] = wp;
  216. Target.InvalidateDistanceCache();
  217. InspectorUtility.RepaintGameView();
  218. }
  219. }
  220. [DrawGizmo(GizmoType.Active | GizmoType.NotInSelectionHierarchy
  221. | GizmoType.InSelectionHierarchy | GizmoType.Pickable, typeof(CinemachineSmoothPath))]
  222. static void DrawGizmos(CinemachineSmoothPath path, GizmoType selectionType)
  223. {
  224. var isActive = Selection.activeGameObject == path.gameObject;
  225. CinemachinePathEditor.DrawPathGizmo(
  226. path, isActive ? path.m_Appearance.pathColor : path.m_Appearance.inactivePathColor,
  227. isActive, LocalSpaceSamplePath);
  228. }
  229. static Vector4[] s_BezierWeightsCache;
  230. // Optimizer for gizmo drawing
  231. static int LocalSpaceSamplePath(CinemachinePathBase pathBase, int samplesPerSegment, Vector3[] positions, Quaternion[] rotations)
  232. {
  233. CinemachineSmoothPath path = pathBase as CinemachineSmoothPath;
  234. path.UpdateControlPoints();
  235. int numSegments = path.m_Waypoints.Length - (path.Looped ? 0 : 1);
  236. if (numSegments == 0)
  237. return 0;
  238. // Compute the bezier weights only once - this is shared by all segments
  239. if (s_BezierWeightsCache == null || s_BezierWeightsCache.Length < samplesPerSegment)
  240. s_BezierWeightsCache = new Vector4[samplesPerSegment];
  241. for (int i = 0; i < samplesPerSegment; ++i)
  242. {
  243. float t = ((float)i) / samplesPerSegment;
  244. float d = 1.0f - t;
  245. s_BezierWeightsCache[i] = new Vector4(d * d * d, 3f * d * d * t, 3f * d * t * t, t * t * t);
  246. }
  247. // Process the positions
  248. int numSamples = 0;
  249. for (int wp = 0; wp < numSegments && numSamples < positions.Length; ++wp)
  250. {
  251. int nextWp = (wp + 1) % path.m_Waypoints.Length;
  252. for (int i = 0; i < samplesPerSegment; ++i)
  253. {
  254. if (numSamples >= positions.Length)
  255. break;
  256. positions[numSamples++]
  257. = (s_BezierWeightsCache[i].x * path.m_Waypoints[wp].position)
  258. + (s_BezierWeightsCache[i].y * path.m_ControlPoints1[wp].position)
  259. + (s_BezierWeightsCache[i].z * path.m_ControlPoints2[wp].position)
  260. + (s_BezierWeightsCache[i].w * path.m_Waypoints[nextWp].position);
  261. }
  262. }
  263. if (numSamples < positions.Length)
  264. positions[numSamples++] = path.Looped ? positions[0] : path.m_Waypoints[path.m_Waypoints.Length - 1].position;
  265. // Process rotations
  266. if (rotations != null && rotations.Length >= numSamples)
  267. {
  268. int numRotSamples = 0;
  269. for (int wp = 0; wp < numSegments && numRotSamples < numSamples; ++wp)
  270. {
  271. int nextWp = (wp + 1) % path.m_Waypoints.Length;
  272. SplineHelpers.BezierTangentWeights3(
  273. path.m_Waypoints[wp].position, path.m_ControlPoints1[wp].position,
  274. path.m_ControlPoints2[wp].position, path.m_Waypoints[nextWp].position,
  275. out var w0, out var w1, out var w2);
  276. for (int i = 0; i < samplesPerSegment; ++i)
  277. {
  278. if (numRotSamples >= numSamples)
  279. break;
  280. float roll
  281. = (s_BezierWeightsCache[i].x * path.m_Waypoints[wp].roll)
  282. + (s_BezierWeightsCache[i].y * path.m_ControlPoints1[wp].roll)
  283. + (s_BezierWeightsCache[i].z * path.m_ControlPoints2[wp].roll)
  284. + (s_BezierWeightsCache[i].w * path.m_Waypoints[nextWp].roll);
  285. float t = ((float)i) / samplesPerSegment;
  286. // From SplineHelpers.BezierTangent3()
  287. var fwd = (w0 * (t * t)) + (w1 * t) + w2;
  288. rotations[numRotSamples++] = Quaternion.LookRotation(fwd) * RollAroundForward(roll);
  289. }
  290. }
  291. if (numRotSamples < numSamples)
  292. rotations[numRotSamples++] = path.Looped ? rotations[0] : path.EvaluateLocalOrientation(path.MaxPos);
  293. }
  294. return numSamples;
  295. }
  296. // same as Quaternion.AngleAxis(roll, Vector3.forward), just simplified
  297. static Quaternion RollAroundForward(float angle)
  298. {
  299. var halfAngle = angle * 0.5F * Mathf.Deg2Rad;
  300. return new Quaternion(0, 0, Mathf.Sin(halfAngle), Mathf.Cos(halfAngle));
  301. }
  302. }
  303. }