CinemachinePathEditor.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. using UnityEditor;
  2. using UnityEngine;
  3. using System.Collections.Generic;
  4. using UnityEditorInternal;
  5. using Cinemachine.Utility;
  6. using System.Linq;
  7. namespace Cinemachine.Editor
  8. {
  9. [CustomEditor(typeof(CinemachinePath))]
  10. internal sealed class CinemachinePathEditor : BaseEditor<CinemachinePath>
  11. {
  12. public static string kPreferTangentSelectionKey = "CinemachinePathEditor.PreferTangentSelection";
  13. public static bool PreferTangentSelection
  14. {
  15. get { return EditorPrefs.GetBool(kPreferTangentSelectionKey, false); }
  16. set
  17. {
  18. if (value != PreferTangentSelection)
  19. EditorPrefs.SetBool(kPreferTangentSelectionKey, value);
  20. }
  21. }
  22. private ReorderableList mWaypointList;
  23. static bool mWaypointsExpanded;
  24. bool mPreferTangentSelection;
  25. /// <summary>Get the property names to exclude in the inspector.</summary>
  26. /// <param name="excluded">Add the names to this list</param>
  27. protected override void GetExcludedPropertiesInInspector(List<string> excluded)
  28. {
  29. base.GetExcludedPropertiesInInspector(excluded);
  30. excluded.Add(FieldPath(x => x.m_Waypoints));
  31. }
  32. void OnEnable()
  33. {
  34. mWaypointList = null;
  35. mPreferTangentSelection = PreferTangentSelection;
  36. }
  37. // ReSharper disable once UnusedMember.Global - magic method called when doing Frame Selected
  38. public bool HasFrameBounds()
  39. {
  40. return Target.m_Waypoints != null && Target.m_Waypoints.Length > 0;
  41. }
  42. // ReSharper disable once UnusedMember.Global - magic method called when doing Frame Selected
  43. public Bounds OnGetFrameBounds()
  44. {
  45. Vector3[] wp;
  46. int selected = mWaypointList == null ? -1 : mWaypointList.index;
  47. if (selected >= 0 && selected < Target.m_Waypoints.Length)
  48. wp = new Vector3[1] { Target.m_Waypoints[selected].position };
  49. else
  50. wp = Target.m_Waypoints.Select(p => p.position).ToArray();
  51. return GeometryUtility.CalculateBounds(wp, Target.transform.localToWorldMatrix);
  52. }
  53. public override void OnInspectorGUI()
  54. {
  55. BeginInspector();
  56. if (mWaypointList == null)
  57. SetupWaypointList();
  58. if (mWaypointList.index >= mWaypointList.count)
  59. mWaypointList.index = mWaypointList.count - 1;
  60. // Ordinary properties
  61. DrawRemainingPropertiesInInspector();
  62. // Path length
  63. EditorGUILayout.LabelField("Path Length", Target.PathLength.ToString());
  64. GUILayout.Label(new GUIContent("Selected Waypoint:"));
  65. EditorGUILayout.BeginVertical(GUI.skin.box);
  66. Rect rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 3 + 10);
  67. if (mWaypointList.index >= 0)
  68. {
  69. DrawWaypointEditor(rect, mWaypointList.index);
  70. serializedObject.ApplyModifiedProperties();
  71. }
  72. else
  73. {
  74. if (Target.m_Waypoints.Length > 0)
  75. {
  76. EditorGUI.HelpBox(rect,
  77. "Click on a waypoint in the scene view\nor in the Path Details list",
  78. MessageType.Info);
  79. }
  80. else if (GUI.Button(rect, new GUIContent("Add a waypoint to the path")))
  81. {
  82. InsertWaypointAtIndex(mWaypointList.index);
  83. mWaypointList.index = 0;
  84. }
  85. }
  86. EditorGUILayout.EndVertical();
  87. if (mPreferTangentSelection != EditorGUILayout.Toggle(
  88. new GUIContent("Prefer Tangent Drag",
  89. "When editing the path, if waypoint position and tangent coincide, dragging will apply preferentially to the tangent"),
  90. mPreferTangentSelection))
  91. {
  92. PreferTangentSelection = mPreferTangentSelection = !mPreferTangentSelection;
  93. }
  94. mWaypointsExpanded = EditorGUILayout.Foldout(mWaypointsExpanded, "Path Details", true);
  95. if (mWaypointsExpanded)
  96. {
  97. EditorGUI.BeginChangeCheck();
  98. mWaypointList.DoLayoutList();
  99. if (EditorGUI.EndChangeCheck())
  100. serializedObject.ApplyModifiedProperties();
  101. }
  102. }
  103. void SetupWaypointList()
  104. {
  105. mWaypointList = new ReorderableList(
  106. serializedObject, FindProperty(x => x.m_Waypoints),
  107. true, true, true, true);
  108. mWaypointList.elementHeight *= 3;
  109. mWaypointList.drawHeaderCallback = (Rect rect) =>
  110. {
  111. EditorGUI.LabelField(rect, "Waypoints");
  112. };
  113. mWaypointList.drawElementCallback
  114. = (Rect rect, int index, bool isActive, bool isFocused) =>
  115. {
  116. DrawWaypointEditor(rect, index);
  117. };
  118. mWaypointList.onAddCallback = (ReorderableList l) =>
  119. {
  120. InsertWaypointAtIndex(l.index);
  121. };
  122. }
  123. void DrawWaypointEditor(Rect rect, int index)
  124. {
  125. // Needed for accessing string names of fields
  126. CinemachinePath.Waypoint def = new CinemachinePath.Waypoint();
  127. Vector2 numberDimension = GUI.skin.button.CalcSize(new GUIContent("999"));
  128. Vector2 labelDimension = GUI.skin.label.CalcSize(new GUIContent("Position"));
  129. Vector2 addButtonDimension = new Vector2(labelDimension.y + 5, labelDimension.y + 1);
  130. float vSpace = 2;
  131. float hSpace = 3;
  132. SerializedProperty element = mWaypointList.serializedProperty.GetArrayElementAtIndex(index);
  133. rect.y += vSpace / 2;
  134. Rect r = new Rect(rect.position, numberDimension);
  135. Color color = GUI.color;
  136. // GUI.color = Target.m_Appearance.pathColor;
  137. if (GUI.Button(r, new GUIContent(index.ToString(), "Go to the waypoint in the scene view")))
  138. {
  139. if (SceneView.lastActiveSceneView != null)
  140. {
  141. mWaypointList.index = index;
  142. SceneView.lastActiveSceneView.pivot = Target.EvaluatePosition(index);
  143. SceneView.lastActiveSceneView.size = 3;
  144. SceneView.lastActiveSceneView.Repaint();
  145. }
  146. }
  147. GUI.color = color;
  148. r = new Rect(rect.position, labelDimension);
  149. r.x += hSpace + numberDimension.x;
  150. EditorGUI.LabelField(r, "Position");
  151. r.x += hSpace + r.width;
  152. r.width = rect.width - (numberDimension.x + hSpace + r.width + hSpace + addButtonDimension.x + hSpace);
  153. EditorGUI.PropertyField(r, element.FindPropertyRelative(() => def.position), GUIContent.none);
  154. r.x += r.width + hSpace;
  155. r.size = addButtonDimension;
  156. GUIContent buttonContent = EditorGUIUtility.IconContent("d_RectTransform Icon");
  157. buttonContent.tooltip = "Set to scene-view camera position";
  158. GUIStyle style = new GUIStyle(GUI.skin.label);
  159. style.alignment = TextAnchor.MiddleCenter;
  160. if (GUI.Button(r, buttonContent, style) && SceneView.lastActiveSceneView != null)
  161. {
  162. Undo.RecordObject(Target, "Set waypoint");
  163. CinemachinePath.Waypoint wp = Target.m_Waypoints[index];
  164. Vector3 pos = SceneView.lastActiveSceneView.camera.transform.position;
  165. wp.position = Target.transform.InverseTransformPoint(pos);
  166. Target.m_Waypoints[index] = wp;
  167. }
  168. r = new Rect(rect.position, labelDimension);
  169. r.y += numberDimension.y + vSpace;
  170. r.x += hSpace + numberDimension.x; r.width = labelDimension.x;
  171. EditorGUI.LabelField(r, "Tangent");
  172. r.x += hSpace + r.width;
  173. r.width = rect.width - (numberDimension.x + hSpace + r.width + hSpace + addButtonDimension.x + hSpace);
  174. EditorGUI.PropertyField(r, element.FindPropertyRelative(() => def.tangent), GUIContent.none);
  175. r.x += r.width + hSpace;
  176. r.size = addButtonDimension;
  177. buttonContent = EditorGUIUtility.IconContent("ol minus@2x");
  178. buttonContent.tooltip = "Remove this waypoint";
  179. if (GUI.Button(r, buttonContent, style))
  180. {
  181. Undo.RecordObject(Target, "Delete waypoint");
  182. var list = new List<CinemachinePath.Waypoint>(Target.m_Waypoints);
  183. list.RemoveAt(index);
  184. Target.m_Waypoints = list.ToArray();
  185. if (index == Target.m_Waypoints.Length)
  186. mWaypointList.index = index - 1;
  187. }
  188. r = new Rect(rect.position, labelDimension);
  189. r.y += 2 * (numberDimension.y + vSpace);
  190. r.x += hSpace + numberDimension.x; r.width = labelDimension.x;
  191. EditorGUI.LabelField(r, "Roll");
  192. r.x += hSpace + labelDimension.x;
  193. r.width = rect.width
  194. - (numberDimension.x + hSpace)
  195. - (labelDimension.x + hSpace)
  196. - (addButtonDimension.x + hSpace);
  197. r.width /= 3;
  198. EditorGUI.MultiPropertyField(r, new GUIContent[] { new GUIContent(" ") },
  199. element.FindPropertyRelative(() => def.roll));
  200. r.x = rect.x + rect.width - addButtonDimension.x;
  201. r.size = addButtonDimension;
  202. buttonContent = EditorGUIUtility.IconContent("ol plus@2x");
  203. buttonContent.tooltip = "Add a new waypoint after this one";
  204. if (GUI.Button(r, buttonContent, style))
  205. {
  206. mWaypointList.index = index;
  207. InsertWaypointAtIndex(index);
  208. }
  209. }
  210. void InsertWaypointAtIndex(int indexA)
  211. {
  212. Vector3 pos = Vector3.forward;
  213. Vector3 tangent = Vector3.right;
  214. float roll = 0;
  215. // Get new values from the current indexA (if any)
  216. int numWaypoints = Target.m_Waypoints.Length;
  217. if (indexA < 0)
  218. indexA = numWaypoints - 1;
  219. if (indexA >= 0)
  220. {
  221. int indexB = indexA + 1;
  222. if (Target.m_Looped && indexB >= numWaypoints)
  223. indexB = 0;
  224. if (indexB >= numWaypoints)
  225. {
  226. // Extrapolate the end
  227. if (!Target.m_Waypoints[indexA].tangent.AlmostZero())
  228. tangent = Target.m_Waypoints[indexA].tangent;
  229. pos = Target.m_Waypoints[indexA].position + tangent;
  230. roll = Target.m_Waypoints[indexA].roll;
  231. }
  232. else
  233. {
  234. // Interpolate
  235. pos = Target.transform.InverseTransformPoint(
  236. Target.EvaluatePosition(0.5f + indexA));
  237. tangent = Target.transform.InverseTransformDirection(
  238. Target.EvaluateTangent(0.5f + indexA).normalized);
  239. roll = Mathf.Lerp(
  240. Target.m_Waypoints[indexA].roll, Target.m_Waypoints[indexB].roll, 0.5f);
  241. }
  242. }
  243. Undo.RecordObject(Target, "Add waypoint");
  244. var wp = new CinemachinePath.Waypoint();
  245. wp.position = pos;
  246. wp.tangent = tangent;
  247. wp.roll = roll;
  248. var list = new List<CinemachinePath.Waypoint>(Target.m_Waypoints);
  249. list.Insert(indexA + 1, wp);
  250. Target.m_Waypoints = list.ToArray();
  251. Target.InvalidateDistanceCache();
  252. mWaypointList.index = indexA + 1; // select it
  253. }
  254. void OnSceneGUI()
  255. {
  256. if (mWaypointList == null)
  257. SetupWaypointList();
  258. if (Tools.current == Tool.Move)
  259. {
  260. Color colorOld = Handles.color;
  261. var localToWorld = Target.transform.localToWorldMatrix;
  262. var localRotation = Target.transform.rotation;
  263. for (int i = 0; i < Target.m_Waypoints.Length; ++i)
  264. {
  265. DrawSelectionHandle(i, localToWorld);
  266. if (mWaypointList.index == i)
  267. {
  268. // Waypoint is selected
  269. if (PreferTangentSelection)
  270. {
  271. DrawPositionControl(i, localToWorld, localRotation);
  272. DrawTangentControl(i, localToWorld, localRotation);
  273. }
  274. else
  275. {
  276. DrawTangentControl(i, localToWorld, localRotation);
  277. DrawPositionControl(i, localToWorld, localRotation);
  278. }
  279. }
  280. }
  281. Handles.color = colorOld;
  282. }
  283. }
  284. void DrawSelectionHandle(int i, Matrix4x4 localToWorld)
  285. {
  286. if (Event.current.button != 1)
  287. {
  288. Vector3 pos = localToWorld.MultiplyPoint(Target.m_Waypoints[i].position);
  289. float size = HandleUtility.GetHandleSize(pos) * 0.2f;
  290. Handles.color = Color.white;
  291. if (Handles.Button(pos, Quaternion.identity, size, size, Handles.SphereHandleCap)
  292. && mWaypointList.index != i)
  293. {
  294. mWaypointList.index = i;
  295. InspectorUtility.RepaintGameView();
  296. }
  297. // Label it
  298. Handles.BeginGUI();
  299. Vector2 labelSize = new Vector2(
  300. EditorGUIUtility.singleLineHeight * 2, EditorGUIUtility.singleLineHeight);
  301. Vector2 labelPos = HandleUtility.WorldToGUIPoint(pos);
  302. labelPos.y -= labelSize.y / 2;
  303. labelPos.x -= labelSize.x / 2;
  304. GUILayout.BeginArea(new Rect(labelPos, labelSize));
  305. GUIStyle style = new GUIStyle();
  306. style.normal.textColor = Color.black;
  307. style.alignment = TextAnchor.MiddleCenter;
  308. GUILayout.Label(new GUIContent(i.ToString(), "Waypoint " + i), style);
  309. GUILayout.EndArea();
  310. Handles.EndGUI();
  311. }
  312. }
  313. void DrawTangentControl(int i, Matrix4x4 localToWorld, Quaternion localRotation)
  314. {
  315. CinemachinePath.Waypoint wp = Target.m_Waypoints[i];
  316. Vector3 hPos = localToWorld.MultiplyPoint(wp.position + wp.tangent);
  317. Handles.color = Color.yellow;
  318. Handles.DrawLine(localToWorld.MultiplyPoint(wp.position), hPos);
  319. EditorGUI.BeginChangeCheck();
  320. Quaternion rotation = (Tools.pivotRotation == PivotRotation.Local)
  321. ? localRotation : Quaternion.identity;
  322. float size = HandleUtility.GetHandleSize(hPos) * 0.1f;
  323. Handles.SphereHandleCap(0, hPos, rotation, size, EventType.Repaint);
  324. Vector3 newPos = Handles.PositionHandle(hPos, rotation);
  325. if (EditorGUI.EndChangeCheck())
  326. {
  327. Undo.RecordObject(target, "Change Waypoint Tangent");
  328. newPos = Matrix4x4.Inverse(localToWorld).MultiplyPoint(newPos);
  329. wp.tangent = newPos - wp.position;
  330. Target.m_Waypoints[i] = wp;
  331. Target.InvalidateDistanceCache();
  332. InspectorUtility.RepaintGameView();
  333. }
  334. }
  335. void DrawPositionControl(int i, Matrix4x4 localToWorld, Quaternion localRotation)
  336. {
  337. CinemachinePath.Waypoint wp = Target.m_Waypoints[i];
  338. Vector3 pos = localToWorld.MultiplyPoint(wp.position);
  339. EditorGUI.BeginChangeCheck();
  340. Handles.color = Target.m_Appearance.pathColor;
  341. Quaternion rotation = (Tools.pivotRotation == PivotRotation.Local)
  342. ? localRotation : Quaternion.identity;
  343. float size = HandleUtility.GetHandleSize(pos) * 0.1f;
  344. Handles.SphereHandleCap(0, pos, rotation, size, EventType.Repaint);
  345. pos = Handles.PositionHandle(pos, rotation);
  346. if (EditorGUI.EndChangeCheck())
  347. {
  348. Undo.RecordObject(target, "Move Waypoint");
  349. wp.position = Matrix4x4.Inverse(localToWorld).MultiplyPoint(pos);;
  350. Target.m_Waypoints[i] = wp;
  351. Target.InvalidateDistanceCache();
  352. InspectorUtility.RepaintGameView();
  353. }
  354. }
  355. public static void DrawPathGizmo(CinemachinePathBase path, Color pathColor, bool isActive)
  356. {
  357. // Draw the path
  358. Color colorOld = Gizmos.color;
  359. Gizmos.color = pathColor;
  360. float step = 1f / path.m_Resolution;
  361. float halfWidth = path.m_Appearance.width * 0.5f;
  362. Vector3 lastPos = path.EvaluatePosition(path.MinPos);
  363. Vector3 lastW = (path.EvaluateOrientation(path.MinPos)
  364. * Vector3.right) * halfWidth;
  365. float tEnd = path.MaxPos + step / 2;
  366. for (float t = path.MinPos + step; t <= tEnd; t += step)
  367. {
  368. Vector3 p = path.EvaluatePosition(t);
  369. if (!isActive || halfWidth == 0)
  370. {
  371. Gizmos.DrawLine(p, lastPos);
  372. }
  373. else
  374. {
  375. Quaternion q = path.EvaluateOrientation(t);
  376. Vector3 w = (q * Vector3.right) * halfWidth;
  377. Vector3 w2 = w * 1.2f;
  378. Vector3 p0 = p - w2;
  379. Vector3 p1 = p + w2;
  380. Gizmos.DrawLine(p0, p1);
  381. Gizmos.DrawLine(lastPos - lastW, p - w);
  382. Gizmos.DrawLine(lastPos + lastW, p + w);
  383. #if false
  384. // Show the normals, for debugging
  385. Gizmos.color = Color.red;
  386. Vector3 y = (q * Vector3.up) * halfWidth;
  387. Gizmos.DrawLine(p, p + y);
  388. Gizmos.color = pathColor;
  389. #endif
  390. lastW = w;
  391. }
  392. lastPos = p;
  393. }
  394. Gizmos.color = colorOld;
  395. }
  396. [DrawGizmo(GizmoType.Active | GizmoType.NotInSelectionHierarchy
  397. | GizmoType.InSelectionHierarchy | GizmoType.Pickable, typeof(CinemachinePath))]
  398. static void DrawGizmos(CinemachinePath path, GizmoType selectionType)
  399. {
  400. var isActive = Selection.activeGameObject == path.gameObject;
  401. DrawPathGizmo(path, isActive ? path.m_Appearance.pathColor : path.m_Appearance.inactivePathColor, isActive);
  402. }
  403. }
  404. }