HierarchicalBox.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. using System;
  2. using UnityEngine;
  3. using System.Reflection;
  4. namespace UnityEditor.Rendering
  5. {
  6. /// <summary>
  7. /// Provide a gizmo/handle representing a box where all face can be moved independently.
  8. /// Also add a contained sub gizmo/handle box if contained is used at creation.
  9. /// </summary>
  10. /// <example>
  11. /// <code>
  12. /// class MyComponentEditor : Editor
  13. /// {
  14. /// static HierarchicalBox box;
  15. /// static HierarchicalBox containedBox;
  16. ///
  17. /// static MyComponentEditor()
  18. /// {
  19. /// Color[] handleColors = new Color[]
  20. /// {
  21. /// Color.red,
  22. /// Color.green,
  23. /// Color.Blue,
  24. /// new Color(0.5f, 0f, 0f, 1f),
  25. /// new Color(0f, 0.5f, 0f, 1f),
  26. /// new Color(0f, 0f, 0.5f, 1f)
  27. /// };
  28. /// box = new HierarchicalBox(new Color(1f, 1f, 1f, 0.25), handleColors);
  29. /// containedBox = new HierarchicalBox(new Color(1f, 0f, 1f, 0.25), handleColors, container: box);
  30. /// }
  31. ///
  32. /// [DrawGizmo(GizmoType.Selected|GizmoType.Active)]
  33. /// void DrawGizmo(MyComponent comp, GizmoType gizmoType)
  34. /// {
  35. /// box.center = comp.transform.position;
  36. /// box.size = comp.transform.scale;
  37. /// box.DrawHull(gizmoType == GizmoType.Selected);
  38. ///
  39. /// containedBox.center = comp.innerposition;
  40. /// containedBox.size = comp.innerScale;
  41. /// containedBox.DrawHull(gizmoType == GizmoType.Selected);
  42. /// }
  43. ///
  44. /// void OnSceneGUI()
  45. /// {
  46. /// EditorGUI.BeginChangeCheck();
  47. ///
  48. /// //container box must be also set for contained box for clamping
  49. /// box.center = comp.transform.position;
  50. /// box.size = comp.transform.scale;
  51. /// box.DrawHandle();
  52. ///
  53. /// containedBox.DrawHandle();
  54. /// containedBox.center = comp.innerposition;
  55. /// containedBox.size = comp.innerScale;
  56. ///
  57. /// if(EditorGUI.EndChangeCheck())
  58. /// {
  59. /// comp.innerposition = containedBox.center;
  60. /// comp.innersize = containedBox.size;
  61. /// }
  62. /// }
  63. /// }
  64. /// </code>
  65. /// </example>
  66. public class HierarchicalBox
  67. {
  68. const float k_HandleSizeCoef = 0.05f;
  69. static Material k_Material_Cache;
  70. static Material k_Material => (k_Material_Cache == null || k_Material_Cache.Equals(null) ? (k_Material_Cache = new Material(Shader.Find("Hidden/UnlitTransparentColored"))) : k_Material_Cache);
  71. static Mesh k_MeshQuad_Cache;
  72. static Mesh k_MeshQuad => k_MeshQuad_Cache == null || k_MeshQuad_Cache.Equals(null) ? (k_MeshQuad_Cache = Resources.GetBuiltinResource<Mesh>("Quad.fbx")) : k_MeshQuad_Cache;
  73. enum NamedFace { Right, Top, Front, Left, Bottom, Back, None }
  74. Material m_Material;
  75. readonly Color[] m_PolychromeHandleColor;
  76. readonly HierarchicalBox m_Parent;
  77. Color m_MonochromeFillColor;
  78. Color m_MonochromeHandleColor;
  79. Color m_WireframeColor;
  80. Color m_WireframeColorBehind;
  81. int[] m_ControlIDs = new int[6] { 0, 0, 0, 0, 0, 0 };
  82. bool m_MonoHandle = true;
  83. Material material
  84. {
  85. get
  86. {
  87. if (m_Material == null || m_Material.Equals(null))
  88. m_Material = new Material(k_Material);
  89. //material can be lost when exiting play mode so gather the color again when reconstructing it
  90. m_Material.color = m_MonochromeFillColor;
  91. return m_Material;
  92. }
  93. }
  94. /// <summary>
  95. /// Allow to switch between the mode where all axis are controlled together or not
  96. /// Note that if there is several handles, they will use the polychrome colors.
  97. /// </summary>
  98. public bool monoHandle { get => m_MonoHandle; set => m_MonoHandle = value; }
  99. /// <summary>The position of the center of the box in Handle.matrix space.</summary>
  100. public Vector3 center { get; set; }
  101. /// <summary>The size of the box in Handle.matrix space.</summary>
  102. public Vector3 size { get; set; }
  103. /// <summary>The baseColor used to fill hull. All other colors are deduced from it except specific handle colors.</summary>
  104. public Color baseColor
  105. {
  106. get { return material.color; }
  107. set
  108. {
  109. value.a = 8f / 255;
  110. m_MonochromeFillColor = value;
  111. material.color = m_MonochromeFillColor;
  112. value.a = 1f;
  113. m_MonochromeHandleColor = value;
  114. value.a = 0.7f;
  115. m_WireframeColor = value;
  116. value.a = 0.2f;
  117. m_WireframeColorBehind = value;
  118. }
  119. }
  120. //Note: Handles.Slider not allow to use a specific ControlID.
  121. //Thus Slider1D is used (with reflection)
  122. static Type k_Slider1D = Type.GetType("UnityEditorInternal.Slider1D, UnityEditor");
  123. static MethodInfo k_Slider1D_Do = k_Slider1D
  124. .GetMethod(
  125. "Do",
  126. BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public,
  127. null,
  128. CallingConventions.Any,
  129. new[] { typeof(int), typeof(Vector3), typeof(Vector3), typeof(float), typeof(Handles.CapFunction), typeof(float) },
  130. null);
  131. static void Slider1D(int controlID, ref Vector3 handlePosition, Vector3 handleOrientation, float snapScale, Color color)
  132. {
  133. using (new Handles.DrawingScope(color))
  134. {
  135. handlePosition = (Vector3)k_Slider1D_Do.Invoke(null, new object[]
  136. {
  137. controlID,
  138. handlePosition,
  139. handleOrientation,
  140. HandleUtility.GetHandleSize(handlePosition) * k_HandleSizeCoef,
  141. new Handles.CapFunction(Handles.DotHandleCap),
  142. snapScale
  143. });
  144. }
  145. }
  146. /// <summary>Constructor. Used to setup colors and also the container if any.</summary>
  147. /// <param name="baseColor">The color of each face of the box. Other colors are deduced from it.</param>
  148. /// <param name="polychromeHandleColors">The color of handle when they are separated. When they are grouped, they use a variation of the faceColor instead.</param>
  149. /// <param name="parent">The HierarchicalBox containing this box. If null, the box will not be limited in size.</param>
  150. public HierarchicalBox(Color baseColor, Color[] polychromeHandleColors = null, HierarchicalBox parent = null)
  151. {
  152. if (polychromeHandleColors != null && polychromeHandleColors.Length != 6)
  153. throw new ArgumentException("polychromeHandleColors must be null or have a size of 6.");
  154. m_Parent = parent;
  155. m_Material = new Material(k_Material);
  156. this.baseColor = baseColor;
  157. m_PolychromeHandleColor = polychromeHandleColors ?? new Color[]
  158. {
  159. Handles.xAxisColor, Handles.yAxisColor, Handles.zAxisColor,
  160. Handles.xAxisColor, Handles.yAxisColor, Handles.zAxisColor
  161. };
  162. }
  163. /// <summary>Draw the hull which means the boxes without the handles</summary>
  164. /// <param name="filled">If true, also fill the faces of the hull</param>
  165. public void DrawHull(bool filled)
  166. {
  167. Color previousColor = Handles.color;
  168. if (filled)
  169. {
  170. // Draw the hull
  171. var xSize = new Vector3(size.z, size.y, 1f);
  172. material.SetPass(0);
  173. Graphics.DrawMeshNow(k_MeshQuad, Handles.matrix * Matrix4x4.TRS(center + size.x * .5f * Vector3.left, Quaternion.FromToRotation(Vector3.forward, Vector3.left), xSize));
  174. Graphics.DrawMeshNow(k_MeshQuad, Handles.matrix * Matrix4x4.TRS(center + size.x * .5f * Vector3.right, Quaternion.FromToRotation(Vector3.forward, Vector3.right), xSize));
  175. var ySize = new Vector3(size.x, size.z, 1f);
  176. Graphics.DrawMeshNow(k_MeshQuad, Handles.matrix * Matrix4x4.TRS(center + size.y * .5f * Vector3.up, Quaternion.FromToRotation(Vector3.forward, Vector3.up), ySize));
  177. Graphics.DrawMeshNow(k_MeshQuad, Handles.matrix * Matrix4x4.TRS(center + size.y * .5f * Vector3.down, Quaternion.FromToRotation(Vector3.forward, Vector3.down), ySize));
  178. var zSize = new Vector3(size.x, size.y, 1f);
  179. Graphics.DrawMeshNow(k_MeshQuad, Handles.matrix * Matrix4x4.TRS(center + size.z * .5f * Vector3.forward, Quaternion.identity, zSize));
  180. Graphics.DrawMeshNow(k_MeshQuad, Handles.matrix * Matrix4x4.TRS(center + size.z * .5f * Vector3.back, Quaternion.FromToRotation(Vector3.forward, Vector3.back), zSize));
  181. //if as a parent, also draw handle distance to the parent
  182. if (m_Parent != null)
  183. {
  184. var centerDiff = center - m_Parent.center;
  185. var xRecal = centerDiff;
  186. var yRecal = centerDiff;
  187. var zRecal = centerDiff;
  188. xRecal.x = 0;
  189. yRecal.y = 0;
  190. zRecal.z = 0;
  191. Handles.color = GetHandleColor(NamedFace.Left);
  192. Handles.DrawLine(m_Parent.center + xRecal + m_Parent.size.x * .5f * Vector3.left, center + size.x * .5f * Vector3.left);
  193. Handles.color = GetHandleColor(NamedFace.Right);
  194. Handles.DrawLine(m_Parent.center + xRecal + m_Parent.size.x * .5f * Vector3.right, center + size.x * .5f * Vector3.right);
  195. Handles.color = GetHandleColor(NamedFace.Top);
  196. Handles.DrawLine(m_Parent.center + yRecal + m_Parent.size.y * .5f * Vector3.up, center + size.y * .5f * Vector3.up);
  197. Handles.color = GetHandleColor(NamedFace.Bottom);
  198. Handles.DrawLine(m_Parent.center + yRecal + m_Parent.size.y * .5f * Vector3.down, center + size.y * .5f * Vector3.down);
  199. Handles.color = GetHandleColor(NamedFace.Front);
  200. Handles.DrawLine(m_Parent.center + zRecal + m_Parent.size.z * .5f * Vector3.forward, center + size.z * .5f * Vector3.forward);
  201. Handles.color = GetHandleColor(NamedFace.Back);
  202. Handles.DrawLine(m_Parent.center + zRecal + m_Parent.size.z * .5f * Vector3.back, center + size.z * .5f * Vector3.back);
  203. }
  204. }
  205. Handles.color = m_WireframeColor;
  206. Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual;
  207. Handles.DrawWireCube(center, size);
  208. Handles.color = m_WireframeColorBehind;
  209. Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater;
  210. Handles.DrawWireCube(center, size);
  211. Handles.zTest = UnityEngine.Rendering.CompareFunction.Always;
  212. Handles.color = previousColor;
  213. }
  214. /// <summary>Draw the manipulable handles</summary>
  215. public void DrawHandle()
  216. {
  217. Event evt = Event.current;
  218. bool useHomothety = evt.shift;
  219. bool useSymetry = evt.alt || evt.command;
  220. // Note: snapping is handled natively on ctrl for each Slider1D
  221. for (int i = 0, count = m_ControlIDs.Length; i < count; ++i)
  222. m_ControlIDs[i] = GUIUtility.GetControlID("HierarchicalBox".GetHashCode() + i, FocusType.Passive);
  223. EditorGUI.BeginChangeCheck();
  224. var leftPosition = center + size.x * .5f * Vector3.left;
  225. var rightPosition = center + size.x * .5f * Vector3.right;
  226. var topPosition = center + size.y * .5f * Vector3.up;
  227. var bottomPosition = center + size.y * .5f * Vector3.down;
  228. var frontPosition = center + size.z * .5f * Vector3.forward;
  229. var backPosition = center + size.z * .5f * Vector3.back;
  230. var theChangedFace = NamedFace.None;
  231. EditorGUI.BeginChangeCheck();
  232. Slider1D(m_ControlIDs[(int)NamedFace.Left], ref leftPosition, Vector3.left, EditorSnapSettings.scale, GetHandleColor(NamedFace.Left));
  233. if (EditorGUI.EndChangeCheck())
  234. theChangedFace = NamedFace.Left;
  235. EditorGUI.BeginChangeCheck();
  236. Slider1D(m_ControlIDs[(int)NamedFace.Right], ref rightPosition, Vector3.right, EditorSnapSettings.scale, GetHandleColor(NamedFace.Right));
  237. if (EditorGUI.EndChangeCheck())
  238. theChangedFace = NamedFace.Right;
  239. EditorGUI.BeginChangeCheck();
  240. Slider1D(m_ControlIDs[(int)NamedFace.Top], ref topPosition, Vector3.up, EditorSnapSettings.scale, GetHandleColor(NamedFace.Top));
  241. if (EditorGUI.EndChangeCheck())
  242. theChangedFace = NamedFace.Top;
  243. EditorGUI.BeginChangeCheck();
  244. Slider1D(m_ControlIDs[(int)NamedFace.Bottom], ref bottomPosition, Vector3.down, EditorSnapSettings.scale, GetHandleColor(NamedFace.Bottom));
  245. if (EditorGUI.EndChangeCheck())
  246. theChangedFace = NamedFace.Bottom;
  247. EditorGUI.BeginChangeCheck();
  248. Slider1D(m_ControlIDs[(int)NamedFace.Front], ref frontPosition, Vector3.forward, EditorSnapSettings.scale, GetHandleColor(NamedFace.Front));
  249. if (EditorGUI.EndChangeCheck())
  250. theChangedFace = NamedFace.Front;
  251. EditorGUI.BeginChangeCheck();
  252. Slider1D(m_ControlIDs[(int)NamedFace.Back], ref backPosition, Vector3.back, EditorSnapSettings.scale, GetHandleColor(NamedFace.Back));
  253. if (EditorGUI.EndChangeCheck())
  254. theChangedFace = NamedFace.Back;
  255. if (EditorGUI.EndChangeCheck())
  256. {
  257. float delta = 0f;
  258. switch (theChangedFace)
  259. {
  260. case NamedFace.Left: delta = (leftPosition - center - size.x * .5f * Vector3.left).x; break;
  261. case NamedFace.Right: delta = -(rightPosition - center - size.x * .5f * Vector3.right).x; break;
  262. case NamedFace.Top: delta = -(topPosition - center - size.y * .5f * Vector3.up).y; break;
  263. case NamedFace.Bottom: delta = (bottomPosition - center - size.y * .5f * Vector3.down).y; break;
  264. case NamedFace.Front: delta = -(frontPosition - center - size.z * .5f * Vector3.forward).z; break;
  265. case NamedFace.Back: delta = (backPosition - center - size.z * .5f * Vector3.back).z; break;
  266. }
  267. if (monoHandle || useHomothety && useSymetry)
  268. {
  269. var tempSize = size - Vector3.one * delta;
  270. //ensure that the box face are still facing outside
  271. for (int axis = 0; axis < 3; ++axis)
  272. {
  273. if (tempSize[axis] < 0)
  274. {
  275. delta += tempSize[axis];
  276. tempSize = size - Vector3.one * delta;
  277. }
  278. }
  279. //ensure containedBox do not exit container
  280. if (m_Parent != null)
  281. {
  282. for (int axis = 0; axis < 3; ++axis)
  283. {
  284. if (tempSize[axis] > m_Parent.size[axis])
  285. tempSize[axis] = m_Parent.size[axis];
  286. }
  287. }
  288. size = tempSize;
  289. }
  290. else
  291. {
  292. if (useSymetry)
  293. {
  294. switch (theChangedFace)
  295. {
  296. case NamedFace.Left: rightPosition.x -= delta; break;
  297. case NamedFace.Right: leftPosition.x += delta; break;
  298. case NamedFace.Top: bottomPosition.y += delta; break;
  299. case NamedFace.Bottom: topPosition.y -= delta; break;
  300. case NamedFace.Front: backPosition.z += delta; break;
  301. case NamedFace.Back: frontPosition.z -= delta; break;
  302. }
  303. }
  304. if (useHomothety)
  305. {
  306. float halfDelta = delta * 0.5f;
  307. switch (theChangedFace)
  308. {
  309. case NamedFace.Left:
  310. case NamedFace.Right:
  311. bottomPosition.y += halfDelta;
  312. topPosition.y -= halfDelta;
  313. backPosition.z += halfDelta;
  314. frontPosition.z -= halfDelta;
  315. break;
  316. case NamedFace.Top:
  317. case NamedFace.Bottom:
  318. rightPosition.x -= halfDelta;
  319. leftPosition.x += halfDelta;
  320. backPosition.z += halfDelta;
  321. frontPosition.z -= halfDelta;
  322. break;
  323. case NamedFace.Front:
  324. case NamedFace.Back:
  325. rightPosition.x -= halfDelta;
  326. leftPosition.x += halfDelta;
  327. bottomPosition.y += halfDelta;
  328. topPosition.y -= halfDelta;
  329. break;
  330. }
  331. }
  332. var max = new Vector3(rightPosition.x, topPosition.y, frontPosition.z);
  333. var min = new Vector3(leftPosition.x, bottomPosition.y, backPosition.z);
  334. //ensure that the box face are still facing outside
  335. for (int axis = 0; axis < 3; ++axis)
  336. {
  337. if (min[axis] > max[axis])
  338. {
  339. // Control IDs in m_ControlIDs[0-3[ are for positive axes
  340. if (GUIUtility.hotControl == m_ControlIDs[axis])
  341. max[axis] = min[axis];
  342. else
  343. min[axis] = max[axis];
  344. }
  345. }
  346. //ensure containedBox do not exit container
  347. if (m_Parent != null)
  348. {
  349. for (int axis = 0; axis < 3; ++axis)
  350. {
  351. if (min[axis] < m_Parent.center[axis] - m_Parent.size[axis] * 0.5f)
  352. min[axis] = m_Parent.center[axis] - m_Parent.size[axis] * 0.5f;
  353. if (max[axis] > m_Parent.center[axis] + m_Parent.size[axis] * 0.5f)
  354. max[axis] = m_Parent.center[axis] + m_Parent.size[axis] * 0.5f;
  355. }
  356. }
  357. center = (max + min) * .5f;
  358. size = max - min;
  359. }
  360. }
  361. }
  362. Color GetHandleColor(NamedFace name) => monoHandle ? m_MonochromeHandleColor : m_PolychromeHandleColor[(int)name];
  363. }
  364. }